source: User Procedures/Irena/IR2_Reflectivity.ipf @ 10

Last change on this file since 10 was 10, checked in by ilavsky, 9 years ago

Plotting tool 2 modifications, minor changes other packages

File size: 159.6 KB
Line 
1#pragma rtGlobals=1             // Use modern global access method.
2#pragma version=1.12
3Constant IR2RversionNumber=1.12
4
5//*************************************************************************\
6//* Copyright (c) 2005 - 2013, Argonne National Laboratory
7//* This file is distributed subject to a Software License Agreement found
8//* in the file LICENSE that is included with this distribution.
9//*************************************************************************/
10
11//1.01 added license for ANL
12//1.02 removed old method of Genetic optimization
13//1.03 fixed minor bug when SLD step change disalowed negative SLDs
14//1.04 added ability to export Model result to new folder if there are no input data. 
15//1.05 added double precision ParametersIn wave as seems to be needed by new version of Abeles.xop, added to check version for panesl and widened range of thicknesses displayed.
16//1.06 removed all font and font size from panel definitions to enable user control
17//1.07 added information about Motofit and using new Andrew Melsons function speeded up by ~ 40x
18//1.08 added sliders to control the parameters. Seems to work very well, need testing.  Added ability to use dq as resolution wave, not only % resolution.
19//1.09 added ability to link parameters. Major change in GUI. Added saving fitting uncertainities into already existing "Error" variables. Made many functions static. 
20//1.10 added Remove/Insert layer capability, made minor change which increases speed by about 20% when all imaginary SLDs are set to 0 (neutrons typically). 
21//1.11 added Motofit data types for convenience.
22//1.12 modified panel to be scrollable
23
24Function IR2R_ReflectivitySimpleToolMain()
25
26        IN2G_CheckScreenSize("height",670)
27        IR2R_InitializeSimpleTool()
28       
29        DoWindow IR2R_ReflSimpleToolMainPanel
30        if(V_Flag)
31                DOWIndow/K IR2R_ReflSimpleToolMainPanel
32        endif
33        Execute("IR2R_ReflSimpleToolMainPanel()")
34        ING2_AddScrollControl()
35        UpdatePanelVersionNumber("IR2R_ReflSimpleToolMainPanel", IR2RversionNumber)
36        print "***** Important information *****"
37        print "The reflectometry analysis in IRENA is based on functionality from the Motofit package (written by Andrew Nelson, www.sourceforge.net/projects/motofit)."
38        print "If you use this functionality please cite the Motofit paper [J. Appl. Cryst. 39, 273-276]"
39        print "*****"
40end
41
42
43//************************************************************************************************************
44//************************************************************************************************************
45//************************************************************************************************************
46//************************************************************************************************************
47
48Function IR2R_MainCheckVersion()       
49        DoWindow IR2R_ReflSimpleToolMainPanel
50        if(V_Flag)
51                if(!CheckPanelVersionNumber("IR2R_ReflSimpleToolMainPanel", IR2RversionNumber))
52                        DoAlert /T="The Reflectivity panel was created by old version of Irena " 1, "Reflectivity may need to be restarted to work properly. Restart now?"
53                        if(V_flag==1)
54                                Execute/P("IR2R_ReflectivitySimpleToolMain()")
55                        else            //at least reinitialize the variables so we avoid major crashes...
56                                IR2R_InitializeSimpleTool()     
57                        endif
58                endif
59        endif
60end
61
62
63///******************************************************************************************
64///******************************************************************************************
65///******************************************************************************************
66///******************************************************************************************
67///******************************************************************************************
68///******************************************************************************************
69Window IR2R_ReflSimpleToolMainPanel()
70        PauseUpdate; Silent 1           // building window...
71        NewPanel /K=1 /W=(2.25,43.25,390,720) as "Reflectivity Simple Tool"
72        string UserDataTypes="*_R;"
73        string UserNameString="Motofit"
74        string XUserLookup="*_R:*_q;"
75        string EUserLookup="*_R:*_E;"
76        IR2C_AddDataControls("Refl_SimpleTool","IR2R_ReflSimpleToolMainPanel","DSM_Int;M_DSM_Int;","",UserDataTypes,UserNameString,XUserLookup,EUserLookup, 0,1)
77        PopupMenu SelectDataFolder proc=IR2R_ReplMainPanelPopMenuProc
78
79
80        SetDrawLayer UserBack
81//      SetDrawEnv linefgc= (65535,65535,65535),fillfgc= (60928,60928,60928)
82//      DrawRect 1,156,387,193
83//      SetDrawLayer UserBack
84//      SetDrawEnv fillfgc= (65280,65280,32768)
85//      DrawRect 1,570,387,615
86//      SetDrawEnv fillfgc= (32768,65280,32768)
87//      DrawRect 1,501,387,569
88//      SetDrawEnv fillfgc= (48896,59904,65280)
89//      DrawRect 1,235,387,264
90
91//      SetDrawEnv fname= "Times New Roman", save
92//      SetDrawEnv fsize= 22,fstyle= 3,textrgb= (0,0,52224)
93//      DrawText 58,28,"Simple reflectivity tool"
94        TitleBox MainTitle title="Simple reflectivity tool",pos={20,0},frame=0,fstyle=3, fixedSize=1,font= "Times New Roman", size={360,24},fSize=22,fColor=(0,0,52224)
95//      SetDrawEnv linethick= 3,linefgc= (0,0,52224)
96//      DrawLine 16,194,339,194
97        TitleBox FakeLine1 title=" ",fixedSize=1,size={330,3},pos={16,191},frame=0,fColor=(0,0,52224), labelBack=(0,0,52224)
98//      SetDrawEnv fsize= 16,fstyle= 1
99//      DrawText 2,49,"Data input"
100        TitleBox Info1 title="Data input",pos={10,28},frame=0,fstyle=1, fixedSize=1,size={80,20},fSize=14,fColor=(0,0,52224)
101//      SetDrawEnv fsize= 20,fstyle= 1, textrgb= (52224,0,0)
102//      DrawText 5,217,"Model input:"
103        TitleBox Info2 title="Model input:",pos={10,196},frame=0,fstyle=3, fixedSize=1,size={150,20},fSize=14
104//      SetDrawEnv fsize= 12, fstyle= 1
105//      DrawText 187,303,"Fit? Link?"
106        TitleBox Info3 title="Fit? Link?  Low L/LinkTo  High L/Ratio",pos={190,286},frame=0,fstyle=2, fixedSize=0,size={20,15},fSize=10
107//      SetDrawEnv fsize= 10, fstyle= 1
108//      DrawText 245,303,"Low L/LinkTo   High L/Ratio"
109//      TitleBox Info4 title="Low L/LinkTo   High L/Ratio",pos={245,300},frame=0,fstyle=2, fixedSize=0,size={120,15},fSize=12
110//      SetDrawEnv fsize= 16,fstyle= 1, textrgb= (0,0,52224)
111//      DrawText 10,258,"Top environment "
112        TitleBox Info5 title="Top environment",pos={2,237},frame=0,fstyle=3,fSize=14,fColor=(0,0,52224)
113        TitleBox Info5 fixedSize=1,size={384,27},anchor=LC,labelBack=(16385,65535,65535)
114//      SetDrawEnv fsize= 16,fstyle= 1, textrgb= (0,0,52224)
115//      DrawText 10,520,"Substrate "
116        TitleBox Info6 title="Substrate",frame=0,fstyle=3, fixedSize=1,fSize=14,fColor=(0,0,52224), pos={2,500},size={385,70}, labelBack=(32768,65280,32768)
117        TitleBox Info8 title=" ",frame=0,fstyle=3, fixedSize=1,fSize=14,fColor=(0,0,52224), pos={2,570},size={385,43}, labelBack=(65280,65280,32768)
118
119//      SetDrawEnv linebgc= (56576,56576,56576)
120//      SetDrawEnv linepat= 4
121//      SetDrawEnv fillpat= 2
122//      SetDrawEnv fillfgc= (56576,56576,56576)
123//      DrawRect 10,380,375,403
124//      SetDrawEnv fsize= 12
125//      DrawText 20,398,"SLD units - either * 10^-6 [1/A^2] or * 10^10  [1/cm^2]"
126        TitleBox Info7 title="SLD units - either * 10^-6 [1/A^2] or * 10^10  [1/cm^2]",pos={10,386},frame=0,fstyle=2, fixedSize=0,size={40,15},fSize=10
127
128
129        //************************
130        Button DrawGraphs,pos={270,39},size={100,18}, proc=IR2R_InputPanelButtonProc,title="Graph", help={"Create a graph (log-log) of your experiment data"}, fColor=(65280,65280,48896)
131
132        CheckBox ZeroAtTheSubstrate,pos={10,160},size={63,14},proc=IR2R_InputPanelCheckboxProc,title="0 at the substrate?"
133        CheckBox ZeroAtTheSubstrate,variable= root:Packages:Refl_SimpleTool:ZeroAtTheSubstrate, help={"Check if you want to Define SLD profile with 0 at the substrate"}
134        CheckBox L1AtTheBottom,pos={10,175},size={63,14},proc=IR2R_InputPanelCheckboxProc,title="L1 at the substrate?"
135        CheckBox L1AtTheBottom,variable= root:Packages:Refl_SimpleTool:L1AtTheBottom, help={"Check if you want to Define SLD profile with Layer 1 at the substrate, else Layer 1 is at the top"}
136
137
138        CheckBox AutoUpdate,pos={130,175},size={63,14},proc=IR2R_InputPanelCheckboxProc,title="Auto update?"
139        CheckBox AutoUpdate,variable= root:Packages:Refl_SimpleTool:AutoUpdate, help={"Check if you want to update with every change inthe panel."}
140
141        CheckBox UseErrors,pos={130,160},size={63,14},proc=IR2R_InputPanelCheckboxProc,title="Use errors?"
142        CheckBox UseErrors,variable= root:Packages:Refl_SimpleTool:UseErrors, help={"Check if you want to use Intensity errors in fitting (if errors are available)"}
143
144        PopupMenu ErrorDataName, disable=!root:Packages:Refl_SimpleTool:UseErrors
145
146//      CheckBox UseResolutionWave,pos={260,158},size={80,16},proc=IR2R_InputPanelCheckboxProc,title="Resolution wave?"
147//      CheckBox UseResolutionWave,variable= root:Packages:Refl_SimpleTool:UseResolutionWave, help={"Use wave for instrument resolution? Must be in the same folder as data... "}
148        PopupMenu ResolutionType,pos={215,155},size={80,14},proc=IR2R_PanelPopupControl,title="Resolution?", help={"Select what resolution you want to use. "}
149        PopupMenu ResolutionType,mode=1,popvalue=StringFromList(root:Packages:Refl_SimpleTool:UseResolutionWave, "Fixed [%];Wave [%];Wave [dq];Wave [dq^2];"),value= "Fixed [%];Wave [%];Wave [dq];Wave [dq^2];"//, disable=!(root:Packages:Refl_SimpleTool:UseResolutionWave)
150        SetVariable Resolution,pos={240,177},size={110,16},proc=IR2R_PanelSetVarProc,title="Instr res.", help={"Instrument resolution in %"}
151        SetVariable Resolution,limits={0,Inf,0},variable= root:Packages:Refl_SimpleTool:Resoln, disable = (root:Packages:Refl_SimpleTool:UseResolutionWave)
152        //ResolutionWaveName
153        PopupMenu ResolutionWaveName,pos={215,176},size={100,14},proc=IR2R_PanelPopupControl,title="Res Wave:", help={"Select wave with resolution data. Must be in % and have same number of points as other data. "}
154        PopupMenu ResolutionWaveName,mode=1,popvalue="---",value= #"\"---;Create From Parameters;\"+IR2R_ResWavesList()", disable=!(root:Packages:Refl_SimpleTool:UseResolutionWave)
155
156
157        PopupMenu NumberOfLevels,pos={120,198},size={140,21},proc=IR2R_PanelPopupControl,title="Number of layers :", help={"Select number of layers to use, NOTE that the layer 1 has to have the top one, layer 8 last one"}
158        PopupMenu NumberOfLevels,mode=2,popvalue=num2str(WhichListItem(num2str(root:Packages:Refl_SimpleTool:NumberOfLayers), "0;1;2;3;4;5;6;7;8;")),value= #"\"0;1;2;3;4;5;6;7;8;\""
159
160        PopupMenu FitIQN,pos={270,198},size={100,21},proc=IR2R_PanelPopupControl,title="Fit I*Q^n :", help={"For display & fitting purposes, display & fit I * Q^n (scaling to help least sqaure fitting). n=0 fits Intensity"}
161        PopupMenu FitIQN,mode=2,popvalue=num2str(WhichListItem(num2str(root:Packages:Refl_SimpleTool:FitIQN), "0;1;2;3;4;")),value= #"\"0;1;2;3;4;\""
162
163
164        SetVariable SLD_Real_Top,pos={140,245},size={110,16},proc=IR2R_PanelSetVarProc,title="SLD (real) "
165        SetVariable SLD_Real_Top,limits={-inf,inf,0},variable= root:Packages:Refl_SimpleTool:SLD_Real_Top, help={"SLD (real part) of top material"}
166        SetVariable SLD_Imag_Top,pos={270,245},size={110,16},proc=IR2R_PanelSetVarProc,title="SLD (imag) "
167        SetVariable SLD_Imag_Top,limits={-inf,inf,0},variable= root:Packages:Refl_SimpleTool:SLD_Imag_Top, help={"SLD (imag part) of top material"}
168
169        SetVariable ScalingFactor,pos={8,220},size={160,16},proc=IR2R_PanelSetVarProc,title="ScalingFactor", fstyle=1
170        SetVariable ScalingFactor,limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:ScalingFactor, help={"ScalingFactor - 1 if data corrected correctly"}
171        CheckBox FitScalingFactor,pos={200,220},size={80,16},proc=IR2R_InputPanelCheckboxProc,title=""
172        CheckBox FitScalingFactor,variable= root:Packages:Refl_SimpleTool:FitScalingFactor, help={"Fit FitScalingFactor?, "}
173        SetVariable ScalingFactorLL,pos={230,220},size={60,16},proc=IR2R_PanelSetVarProc, title=" "
174        SetVariable ScalingFactorLL,limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:ScalingFactorLL, help={"Low limit for ScalingFactor"}
175        SetVariable ScalingFactorUL,pos={300,220},size={60,16},proc=IR2R_PanelSetVarProc, title=" "
176        SetVariable ScalingFactorUL,limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:ScalingFactorUL, help={"High limit for ScalingFactor"}
177
178        SetVariable Roughness_Bot,pos={14,525},size={160,16},proc=IR2R_PanelSetVarProc,title="Roughness "
179        SetVariable Roughness_Bot,limits={0,inf,1},variable= root:Packages:Refl_SimpleTool:Roughness_Bot, help={"Roughness of the substrate material"}
180        CheckBox FitRoughness_Bot,pos={190,525},size={80,16},proc=IR2R_InputPanelCheckboxProc,title=" "
181        CheckBox FitRoughness_Bot,variable= root:Packages:Refl_SimpleTool:FitRoughness_Bot, help={"Fit roughness of substrate?, find god starting conditions and select fitting limits..."}
182        SetVariable Roughness_BotLL,pos={230,525},size={60,16},proc=IR2R_PanelSetVarProc, title=" "
183        SetVariable Roughness_BotLL,limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:Roughness_BotLL, help={"Low limit for substrate Roughness"}
184        SetVariable Roughness_BotUL,pos={300,525},size={60,16},proc=IR2R_PanelSetVarProc, title=" "
185        SetVariable Roughness_BotUL,limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:Roughness_BotUL, help={"High limit for substrate Roughness"}
186
187        SetVariable SLD_real_Bot,pos={14,550},size={150,16},proc=IR2R_PanelSetVarProc,title="SLD (real) "
188        SetVariable SLD_Real_Bot,limits={-inf,inf,0},variable= root:Packages:Refl_SimpleTool:SLD_Real_Bot, help={"SLD (real part) of substrate material"}
189        SetVariable SLD_Imag_Bot,pos={190,550},size={150,16},proc=IR2R_PanelSetVarProc,title="SLD (imag) "
190        SetVariable SLD_Imag_Bot,limits={-inf,inf,0},variable= root:Packages:Refl_SimpleTool:SLD_Imag_Bot, help={"SLD (real part) of substrate material"}
191
192
193        SetVariable Background,pos={10,575},size={160,16},proc=IR2R_PanelSetVarProc,title="Background", help={"Background"}
194        SetVariable Background,limits={0,Inf,root:Packages:Refl_SimpleTool:BackgroundStep},variable= root:Packages:Refl_SimpleTool:Background
195        SetVariable BackgroundStep,pos={25,595},size={160,16},title="Background step",proc=IR2R_PanelSetVarProc, help={"Step for increments in background"}
196        SetVariable BackgroundStep,limits={0,Inf,0},variable= root:Packages:Refl_SimpleTool:BackgroundStep
197        CheckBox FitBackground,pos={190,575},size={63,14},proc=IR2R_InputPanelCheckboxProc,title=" "
198        CheckBox FitBackground,variable= root:Packages:Refl_SimpleTool:FitBackground, help={"Check if you want the background to be fitting parameter"}
199        SetVariable BackgroundLL,pos={230,575},size={60,16},proc=IR2R_PanelSetVarProc, title=" "
200        SetVariable BackgroundLL,limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:BackgroundLL, help={"Low limit for Background"}
201        SetVariable BackgroundUL,pos={300,575},size={60,16},proc=IR2R_PanelSetVarProc, title=" "
202        SetVariable BackgroundUL,limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:BackgroundUL, help={"High limit for Background"}
203
204        Button AddRemoveLayers,pos={230,482},size={155,15}, proc=IR2R_InputPanelButtonProc,title="Insert/Remove Layer", help={"Insert or remove layer from the system"}
205        Button SaveDataBtn,pos={195,617},size={90,20}, proc=IR2R_InputPanelButtonProc,title="Save data", help={"Save data"}
206        Button ExportData,pos={290,617},size={90,20}, proc=IR2R_InputPanelButtonProc,title="Export data", help={"Export data"}
207        Button FixLimits,pos={5,617},size={90,20}, proc=IR2R_InputPanelButtonProc,title="Fix Limits", help={"Fix limits for all parameters"}
208        Button CalculateModel,pos={5,655},size={90,20}, proc=IR2R_InputPanelButtonProc,title="Graph model", help={"Graph model data and calculate reflectivity"}
209        Button Fitmodel,pos={100,655},size={90,20}, proc=IR2R_InputPanelButtonProc,title="Fit model", help={"Fit modto data"}
210        Button ReversFit,pos={195,655},size={90,20}, proc=IR2R_InputPanelButtonProc,title="Reverse fit", help={"Fit modto data"}
211
212        CheckBox UseGenOpt,pos={100,618},size={90,10},proc=IR2R_InputPanelCheckboxProc,title="Genetic Opt.?", mode=1
213        CheckBox UseGenOpt,variable= root:Packages:Refl_SimpleTool:UseGenOpt, help={"Use genetic Optimization? SLOW..."}
214        CheckBox UseLSQF,pos={100,634},size={90,10},proc=IR2R_InputPanelCheckboxProc,title="LSQF?", mode=1
215        CheckBox UseLSQF,variable= root:Packages:Refl_SimpleTool:UseLSQF, help={"Use LSQF?"}
216        CheckBox UpdateDuringFitting,pos={190,638},size={80,16},noproc,title="Update while fitting?"
217        CheckBox UpdateDuringFitting,variable= root:Packages:Refl_SimpleTool:UpdateDuringFitting, help={"Update graph during fitting? Will slow things down!!! "}
218
219        //Dist Tabs definition
220        TabControl DistTabs,pos={3,265},size={380,230},proc=IR2R_TabPanelControl
221        TabControl DistTabs,fSize=10,tabLabel(0)="L 1",tabLabel(1)="L 2"
222        TabControl DistTabs,tabLabel(2)="L 3",tabLabel(3)="L 4",value= 0
223        TabControl DistTabs,tabLabel(4)="L 5",tabLabel(5)="L 6"
224        TabControl DistTabs,tabLabel(6)="L 7",tabLabel(7)="L 8"
225        string Selection="1;2;3;4;5;6;7;"
226        string TempSel
227        variable i=1
228        Do     
229                TempSel = RemoveFromList(num2str(i), Selection)
230                Execute("TitleBox LayerTitleBox"+num2str(i)+", title=\"   Layer "+num2str(i)+"  \", frame=1, labelBack=("+num2str(4000*i)+","+num2str(6000*(i))+","+num2str(4000*(8-i))+"), pos={14,285}, fstyle=1,size={200,8},fColor=(65535,65535,65535)")
231                Execute("SetVariable ThicknessLayer"+num2str(i)+",pos={8,308},size={160,16},proc=IR2R_PanelSetVarProc,title=\"Thickness [A]   \", fstyle=1")
232                Execute("SetVariable ThicknessLayer"+num2str(i)+",limits={0,inf,root:Packages:Refl_SimpleTool:ThicknessLayerStep"+num2str(i)+"},variable= root:Packages:Refl_SimpleTool:ThicknessLayer"+num2str(i)+", help={\"Layer Thickness in A\"}")
233                Execute("SetVariable ThicknessLayerStep"+num2str(i)+",pos={200,325},size={160,16},proc=IR2R_PanelSetVarProc,title=\"Thickness step   \",bodyWidth=50")
234                Execute("SetVariable ThicknessLayerStep"+num2str(i)+",limits={0,inf,1},variable= root:Packages:Refl_SimpleTool:ThicknessLayerStep"+num2str(i)+", help={\"Layer Thickness step to take above\"}")
235                Execute("CheckBox FitThicknessLayer"+num2str(i)+",pos={190,308},size={80,16},proc=IR2R_InputPanelCheckboxProc,title=\" \"")
236                Execute("CheckBox FitThicknessLayer"+num2str(i)+",variable= root:Packages:Refl_SimpleTool:FitThicknessLayer"+num2str(i)+", help={\"Fit thickness surface?, find god starting conditions and select fitting limits...\"}")
237                Execute("SetVariable ThicknessLayerLL"+num2str(i)+",pos={238,308},size={60,16},proc=IR2R_PanelSetVarProc, title=\" \"")
238                Execute("SetVariable ThicknessLayerLL"+num2str(i)+",limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:ThicknessLayerLL"+num2str(i)+", help={\"Low limit for thickness\"}")
239                Execute("SetVariable ThicknessLayerUL"+num2str(i)+",pos={310,308},size={60,16},proc=IR2R_PanelSetVarProc, title=\" \"")
240                Execute("SetVariable ThicknessLayerUL"+num2str(i)+",limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:ThicknessLayerUL"+num2str(i)+", help={\"High limit for thickness\"}")
241                Execute("Slider ThicknessLayerSl"+num2str(i)+",pos={8,325},size={180,20},vert=0,proc=IR2R_ReflSliderProc,variable=root:Packages:Refl_SimpleTool:ThicknessLayer"+num2str(i)+",ticks=0")
242                Execute("Slider ThicknessLayerSl"+num2str(i)+",help={\"Controls Thickness as slider, uses Fit Low, High limits and step\"}")
243                Execute("Slider ThicknessLayerSl"+num2str(i)+",limits={"+num2str($"root:Packages:Refl_SimpleTool:ThicknessLayerLL"+num2str(i))+","+num2str($"root:Packages:Refl_SimpleTool:ThicknessLayerUL"+num2str(i))+",0}")
244                Execute("CheckBox LinkThicknessLayer"+num2str(i)+",pos={215,308},size={80,16},proc=IR2R_InputPanelCheckboxProc,title=\" \"")
245                Execute("CheckBox LinkThicknessLayer"+num2str(i)+",variable= root:Packages:Refl_SimpleTool:LinkThicknessLayer"+num2str(i)+", help={\"Link thickness surface?, find god starting conditions and select fitting limits...\"}")
246                Execute("PopupMenu LinkToThicknessLayer"+num2str(i)+",pos={243,308},size={60,12},proc=IR2R_PanelPopupControl,title=\"\", help={\"Select to which layer you want to link this value. \"}")
247                Execute("PopupMenu LinkToThicknessLayer"+num2str(i)+",mode=1,fsize=8,bodyWidth=50,popvalue=num2str(root:Packages:Refl_SimpleTool:LinkToThicknessLayer"+num2str(i)+"),value=\""+TempSel+"\"")    //  value= #\"\\"0;1;2;3;4;\""
248                Execute("SetVariable LinkFThicknessLayer"+num2str(i)+",pos={310,308},size={60,16},proc=IR2R_PanelSetVarProc, title=\" \"")
249                Execute("SetVariable LinkFThicknessLayer"+num2str(i)+",limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:LinkFThicknessLayer"+num2str(i)+", help={\"Ratio to use for linking the thickness\"}")
250
251               
252
253                Execute("SetVariable SLD_Real_Layer"+num2str(i)+",pos={8,345},size={160,16},proc=IR2R_PanelSetVarProc,title=\"SLD (real)  \", fstyle=1")
254                Execute("SetVariable SLD_Real_Layer"+num2str(i)+",limits={-inf,inf,root:Packages:Refl_SimpleTool:SLD_Real_LayerStep"+num2str(i)+"},variable= root:Packages:Refl_SimpleTool:SLD_Real_Layer"+num2str(i)+", help={\"Layer SLD (real part)\"}")
255                Execute("SetVariable SLD_Real_LayerStep"+num2str(i)+",pos={200,362},size={160,16},proc=IR2R_PanelSetVarProc,title=\"SLD (real) step   \",bodyWidth=50")
256                Execute("SetVariable SLD_Real_LayerStep"+num2str(i)+",limits={-inf,inf,1},variable= root:Packages:Refl_SimpleTool:SLD_Real_LayerStep"+num2str(i)+", help={\"Layer SLD (real) step to take above\"}")
257                Execute("CheckBox FitSLD_Real_Layer"+num2str(i)+",pos={190,345},size={80,16},proc=IR2R_InputPanelCheckboxProc,title=\" \"")
258                Execute("CheckBox FitSLD_Real_Layer"+num2str(i)+",variable= root:Packages:Refl_SimpleTool:FitSLD_Real_Layer"+num2str(i)+", help={\"Fit SLD?, find good starting conditions and select fitting limits...\"}")
259                Execute("SetVariable SLD_Real_LayerLL"+num2str(i)+",pos={238,345},size={60,16},proc=IR2R_PanelSetVarProc, title=\" \"")
260                Execute("SetVariable SLD_Real_LayerLL"+num2str(i)+",limits={-inf,inf,0},variable= root:Packages:Refl_SimpleTool:SLD_Real_LayerLL"+num2str(i)+", help={\"Low limit for SLD\"}")
261                Execute("SetVariable SLD_Real_LayerUL"+num2str(i)+",pos={310,345},size={60,16},proc=IR2R_PanelSetVarProc, title=\" \"")
262                Execute("SetVariable SLD_Real_LayerUL"+num2str(i)+",limits={-inf,inf,0},variable= root:Packages:Refl_SimpleTool:SLD_Real_LayerUL"+num2str(i)+", help={\"High limit for SLD\"}")
263                Execute("Slider SLD_Real_LayerSl"+num2str(i)+",pos={8,362},size={180,20},vert=0,proc=IR2R_ReflSliderProc,variable=root:Packages:Refl_SimpleTool:SLD_Real_Layer"+num2str(i)+",ticks=0")
264                Execute("Slider SLD_Real_LayerSl"+num2str(i)+",help={\"Controls SLD Real as slider, uses Fit Low, High limits and step\"}")
265                Execute("Slider SLD_Real_LayerSl"+num2str(i)+",limits={"+num2str($"root:Packages:Refl_SimpleTool:SLD_Real_LayerLL"+num2str(i))+","+num2str($"root:Packages:Refl_SimpleTool:SLD_Real_LayerUL"+num2str(i))+",0}")
266                Execute("CheckBox LinkSLD_Real_Layer"+num2str(i)+",pos={215,345},size={80,16},proc=IR2R_InputPanelCheckboxProc,title=\" \"")
267                Execute("CheckBox LinkSLD_Real_Layer"+num2str(i)+",variable= root:Packages:Refl_SimpleTool:LinkSLD_Real_Layer"+num2str(i)+", help={\"Link SLD?, find good starting conditions and select fitting limits...\"}")
268
269                Execute("PopupMenu LinkToSLD_Real_Layer"+num2str(i)+",pos={243,345},size={60,12},proc=IR2R_PanelPopupControl,title=\"\", help={\"Select to which layer you want to link this value. \"}")
270                Execute("PopupMenu LinkToSLD_Real_Layer"+num2str(i)+",mode=1,fsize=8,bodyWidth=50,popvalue=num2str(root:Packages:Refl_SimpleTool:LinkToSLD_Real_Layer"+num2str(i)+"),value=\""+TempSel+"\"")    //  value= #\"\\"0;1;2;3;4;\""
271                Execute("SetVariable LinkFSLD_Real_Layer"+num2str(i)+",pos={310,345},size={60,16},proc=IR2R_PanelSetVarProc, title=\" \"")
272                Execute("SetVariable LinkFSLD_Real_Layer"+num2str(i)+",limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:LinkFSLD_Real_Layer"+num2str(i)+", help={\"Ratio to use for linking the SLD real value\"}")
273
274
275                Execute("SetVariable SLD_Imag_Layer"+num2str(i)+",pos={8,410},size={160,16},proc=IR2R_PanelSetVarProc,title=\"SLD (imag)  \", fstyle=1")
276                Execute("SetVariable SLD_Imag_Layer"+num2str(i)+",limits={-inf,inf,root:Packages:Refl_SimpleTool:SLD_Imag_LayerStep"+num2str(i)+"},variable= root:Packages:Refl_SimpleTool:SLD_Imag_Layer"+num2str(i)+", help={\"Layer SLD (imag part) in A\"}")
277                Execute("SetVariable SLD_Imag_LayerStep"+num2str(i)+",pos={200,427},size={160,16},proc=IR2R_PanelSetVarProc,title=\"SLD (imag) step   \",bodyWidth=50")
278                Execute("SetVariable SLD_Imag_LayerStep"+num2str(i)+",limits={-inf,inf,1},variable= root:Packages:Refl_SimpleTool:SLD_Imag_LayerStep"+num2str(i)+", help={\"Layer SLD (imag) step to take above\"}")
279                Execute("CheckBox FitSLD_Imag_Layer"+num2str(i)+",pos={190,410},size={80,16},proc=IR2R_InputPanelCheckboxProc,title=\" \"")
280                Execute("CheckBox FitSLD_Imag_Layer"+num2str(i)+",variable= root:Packages:Refl_SimpleTool:FitSLD_Imag_Layer"+num2str(i)+", help={\"Fit SLD?, find good starting conditions and select fitting limits...\"}")
281                Execute("SetVariable SLD_Imag_LayerLL"+num2str(i)+",pos={238,410},size={60,16},proc=IR2R_PanelSetVarProc, title=\" \"")
282                Execute("SetVariable SLD_Imag_LayerLL"+num2str(i)+",limits={-inf,inf,0},variable= root:Packages:Refl_SimpleTool:SLD_Imag_LayerLL"+num2str(i)+", help={\"Low limit for SLD\"}")
283                Execute("SetVariable SLD_Imag_LayerUL"+num2str(i)+",pos={310,410},size={60,16},proc=IR2R_PanelSetVarProc, title=\" \"")
284                Execute("SetVariable SLD_Imag_LayerUL"+num2str(i)+",limits={-inf,inf,0},variable= root:Packages:Refl_SimpleTool:SLD_Imag_LayerUL"+num2str(i)+", help={\"High limit for SLD\"}")
285                Execute("Slider SLD_Imag_LayerSl"+num2str(i)+",pos={8,427},size={180,20},vert=0,proc=IR2R_ReflSliderProc,variable=root:Packages:Refl_SimpleTool:SLD_Imag_Layer"+num2str(i)+",ticks=0")
286                Execute("Slider SLD_Imag_LayerSl"+num2str(i)+",help={\"Controls SLD Imag  as slider, uses Fit Low, High limits and step\"}")
287                Execute("Slider SLD_Imag_LayerSl"+num2str(i)+",limits={"+num2str($"root:Packages:Refl_SimpleTool:SLD_Imag_LayerLL"+num2str(i))+","+num2str($"root:Packages:Refl_SimpleTool:SLD_Imag_LayerUL"+num2str(i))+",0}")
288                Execute("CheckBox LinkSLD_Imag_Layer"+num2str(i)+",pos={215,410},size={80,16},proc=IR2R_InputPanelCheckboxProc,title=\" \"")
289                Execute("CheckBox LinkSLD_Imag_Layer"+num2str(i)+",variable= root:Packages:Refl_SimpleTool:LinkSLD_Imag_Layer"+num2str(i)+", help={\"Fit SLD?, find good starting conditions and select fitting limits...\"}")
290
291                Execute("PopupMenu LinkToSLD_Imag_Layer"+num2str(i)+",pos={243,410},size={60,12},proc=IR2R_PanelPopupControl,title=\"\", help={\"Select to which layer you want to link this value. \"}")
292                Execute("PopupMenu LinkToSLD_Imag_Layer"+num2str(i)+",mode=1,fsize=8,bodyWidth=50,popvalue=num2str(root:Packages:Refl_SimpleTool:LinkToSLD_Imag_Layer"+num2str(i)+"),value=\""+TempSel+"\"")    //  value= #\"\\"0;1;2;3;4;\""
293                Execute("SetVariable LinkFSLD_Imag_Layer"+num2str(i)+",pos={310,410},size={60,16},proc=IR2R_PanelSetVarProc, title=\" \"")
294                Execute("SetVariable LinkFSLD_Imag_Layer"+num2str(i)+",limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:LinkFSLD_Imag_Layer"+num2str(i)+", help={\"Ratio to use for linking the SLD imag value\"}")
295
296                Execute("SetVariable RoughnessLayer"+num2str(i)+",pos={8,450},size={160,16},proc=IR2R_PanelSetVarProc,title=\"Roughness  \", fstyle=1")
297                Execute("SetVariable RoughnessLayer"+num2str(i)+",limits={0,inf,root:Packages:Refl_SimpleTool:RoughnessLayerStep"+num2str(i)+"},variable= root:Packages:Refl_SimpleTool:RoughnessLayer"+num2str(i)+", help={\"Layer roughness \"}")
298                Execute("SetVariable RoughnessLayerStep"+num2str(i)+",pos={200,467},size={160,16},proc=IR2R_PanelSetVarProc,title=\"Roughness step   \",bodyWidth=50")
299                Execute("SetVariable RoughnessLayerStep"+num2str(i)+",limits={0,inf,1},variable= root:Packages:Refl_SimpleTool:RoughnessLayerStep"+num2str(i)+", help={\"Layer roughness step to take above\"}")
300                Execute("CheckBox FitRoughnessLayer"+num2str(i)+",pos={190,450},size={80,16},proc=IR2R_InputPanelCheckboxProc,title=\" \"")
301                Execute("CheckBox FitRoughnessLayer"+num2str(i)+",variable= root:Packages:Refl_SimpleTool:FitRoughnessLayer"+num2str(i)+", help={\"Fit roughness?, find good starting conditions and select fitting limits...\"}")
302                Execute("SetVariable RoughnessLayerLL"+num2str(i)+",pos={238,450},size={60,16},proc=IR2R_PanelSetVarProc, title=\" \"")
303                Execute("SetVariable RoughnessLayerLL"+num2str(i)+",limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:RoughnessLayerLL"+num2str(i)+", help={\"Low limit for roughness\"}")
304                Execute("SetVariable RoughnessLayerUL"+num2str(i)+",pos={310,450},size={60,16},proc=IR2R_PanelSetVarProc, title=\" \"")
305                Execute("SetVariable RoughnessLayerUL"+num2str(i)+",limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:RoughnessLayerUL"+num2str(i)+", help={\"High limit for roughness\"}")
306                Execute("Slider RoughnessLayerSl"+num2str(i)+",pos={8,467},size={180,20},vert=0,proc=IR2R_ReflSliderProc,variable=root:Packages:Refl_SimpleTool:RoughnessLayer"+num2str(i)+",ticks=0")
307                Execute("Slider RoughnessLayerSl"+num2str(i)+",help={\"Controls Roughness  as slider, uses Fit Low, High limits and step\"}")
308                Execute("Slider RoughnessLayerSl"+num2str(i)+",limits={"+num2str($"root:Packages:Refl_SimpleTool:RoughnessLayerLL"+num2str(i))+","+num2str($"root:Packages:Refl_SimpleTool:RoughnessLayerUL"+num2str(i))+",1}")
309                Execute("CheckBox LinkRoughnessLayer"+num2str(i)+",pos={215,450},size={80,16},proc=IR2R_InputPanelCheckboxProc,title=\" \"")
310                Execute("CheckBox LinkRoughnessLayer"+num2str(i)+",variable= root:Packages:Refl_SimpleTool:LinkRoughnessLayer"+num2str(i)+", help={\"Fit roughness?, find good starting conditions and select fitting limits...\"}")
311
312                Execute("PopupMenu LinkToRoughnessLayer"+num2str(i)+",pos={243,450},size={60,12},proc=IR2R_PanelPopupControl,title=\"\", help={\"Select to which layer you want to link this value. \"}")
313                Execute("PopupMenu LinkToRoughnessLayer"+num2str(i)+",mode=1,fsize=8,bodyWidth=50,popvalue=num2str(root:Packages:Refl_SimpleTool:LinkToRoughnessLayer"+num2str(i)+"),value=\""+TempSel+"\"")    //  value= #\"\\"0;1;2;3;4;\""
314                Execute("SetVariable LinkFRoughnessLayer"+num2str(i)+",pos={310,450},size={60,16},proc=IR2R_PanelSetVarProc, title=\" \"")
315                Execute("SetVariable LinkFRoughnessLayer"+num2str(i)+",limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:LinkFRoughnessLayer"+num2str(i)+", help={\"Ratio to use for linking the roughness value\"}")
316        i+=1
317        while(i<=8)     
318        //endfor
319
320        IR2R_TabPanelControl("",0)
321end
322///******************************************************************************************
323///******************************************************************************************
324///******************************************************************************************
325///******************************************************************************************
326///******************************************************************************************
327
328Function IR2R_ReplMainPanelPopMenuProc(pa) : PopupMenuControl
329        STRUCT WMPopupAction &pa
330
331        if(Pa.eventCode!=2)
332                return 0
333        endif   
334        IR2C_PanelPopupControl(Pa)
335        SVAR ResolutionWaveName=root:Packages:Refl_SimpleTool:ResolutionWaveName
336        ResolutionWaveName="---"
337        PopupMenu ResolutionWaveName,mode=1,popvalue="---",value= #"\"---;Create From Parameters;\"+IR2R_ResWavesList()"
338       
339        return 0
340End
341///******************************************************************************************
342///******************************************************************************************
343///******************************************************************************************
344///******************************************************************************************
345///******************************************************************************************
346///******************************************************************************************
347Function IR2R_ReflSliderProc(sa) : SliderControl
348        STRUCT WMSliderAction &sa
349
350        //print sa.eventCode
351
352        switch( sa.eventCode )
353                //Variable curval = sa.curval
354                case -1: // control being killed
355                        break
356                case 4 : // mouse up
357                                string CtrlName=sa.ctrlName
358                                string LLName=CtrlName[0,13]+"LL"+CtrlName[16,inf]
359                                string ULName=CtrlName[0,13]+"UL"+CtrlName[16,inf]
360                                NVAR LLVal=$("root:Packages:Refl_SimpleTool:"+LLName)
361                                NVAR ULVal=$("root:Packages:Refl_SimpleTool:"+ULName)
362                                LLVal = sa.curval * 0.5
363                                ULVal = sa.curVal * 1.5
364                                Execute("Slider "+CtrlName+",limits={"+num2str(LLVal)+","+num2str(ULVal)+",0}")
365                                NVAR AutoUpdate=root:Packages:Refl_SimpleTool:AutoUpdate
366                                if (AutoUpdate)
367                                        IR2R_UpdateLinkedVariables()
368                                        IR2R_CalculateModelResults()
369                                        IR2R_CalculateSLDProfile()
370                                        IR2R_GraphModelResults()       
371                                        DoWindow IR2R_ReflSimpleToolMainPanel
372                                        if(V_Flag)
373                                                DoWIndow/F IR2R_ReflSimpleToolMainPanel
374                                        endif   
375                                endif
376                default:
377                        if( sa.eventCode & 1 ) // value set
378                                NVAR AutoUpdate=root:Packages:Refl_SimpleTool:AutoUpdate
379                                //print "recalculate"
380                                if (AutoUpdate)
381                                        IR2R_UpdateLinkedVariables()
382                                        IR2R_CalculateModelResults()
383                                        IR2R_CalculateSLDProfile()
384                                        //IR2R_GraphModelResults()             
385                                        DoWindow IR2R_ReflSimpleToolMainPanel
386                                        if(V_Flag)
387                                                DoWIndow/F IR2R_ReflSimpleToolMainPanel
388                                        endif   
389                                endif
390                               
391                        endif
392                        break
393        endswitch
394
395        return 0
396End
397///******************************************************************************************
398///******************************************************************************************
399///******************************************************************************************
400Function/T IR2R_ResWavesList()
401
402        string TopPanel=WinName(0,64)
403        SVAR ControlProcsLocations=root:Packages:IrenaControlProcs:ControlProcsLocations
404        string CntrlLocation="root:Packages:"+StringByKey(TopPanel, ControlProcsLocations)
405        SVAR Dtf=$(CntrlLocation+":DataFolderName")
406        string tempresult=IN2G_CreateListOfItemsInFolder(Dtf,2)
407        return tempresult
408end
409///******************************************************************************************
410///******************************************************************************************
411///******************************************************************************************
412
413
414static Function IR2R_GraphMeasuredData()
415       
416        string oldDf=GetDataFolder(1)
417        setDataFolder root:Packages:Refl_SimpleTool
418        SVAR DataFolderName
419        SVAR IntensityWaveName
420        SVAR QWavename
421        SVAR ErrorWaveName
422        SVAR ResolutionWaveName
423        NVAR UseResolutionWave = root:Packages:Refl_SimpleTool:UseResolutionWave
424       
425        //fix for liberal names
426        IntensityWaveName = PossiblyQuoteName(IntensityWaveName)
427        QWavename = PossiblyQuoteName(QWavename)
428        ErrorWaveName = PossiblyQuoteName(ErrorWaveName)
429       
430        WAVE/Z test=$(DataFolderName+IntensityWaveName)
431        if (!WaveExists(test))
432                abort "Error in IntensityWaveName wave selection"
433        endif
434        Duplicate/O $(DataFolderName+IntensityWaveName), OriginalIntensity
435        Wave OriginalIntensity
436
437        WAVE/Z test=$(DataFolderName+QWavename)
438        if (!WaveExists(test))
439                abort "Error in QWavename wave selection"
440        endif
441        Duplicate/O $(DataFolderName+QWavename), OriginalQvector
442        WAVE/Z test=$(DataFolderName+ErrorWaveName)
443        if (!WaveExists(test))
444                //no error wave provided - fudge one with 1 in it...
445                Duplicate/O $(DataFolderName+IntensityWaveName), OriginalError
446                Wave OriginalError
447                //OriginalError*=0.03
448                IN2G_GenerateSASErrors(OriginalIntensity,OriginalError,4,.06, .01,.001,1)
449                print "***********          IMPORTANT NOTE       **********************"
450                print "User did not provide data uncertainity (\"error\") so fudged error wave with guessed values was created"
451                print "*********************************"
452        else
453                Duplicate/O $(DataFolderName+ErrorWaveName), OriginalError
454        endif
455        //read resolution wave if not set by recovery and should be set - and w_ wave exists...
456        //ResolutionWaveName
457        string tempStr
458        if(UseResolutionWave>0 && stringmatch(ResolutionWaveName,"*---*"))
459                tempStr= IN2G_ReturnExistingWaveName(DataFolderName,"w"+IntensityWaveName[1,inf])
460                if(strlen(tempStr)>0)
461                        ResolutionWaveName = StringFromList(0,tempStr,";")
462                        PopupMenu ResolutionWaveName,mode=1,popvalue=ResolutionWaveName,value= #"\"---;Create From Parameters;\"+IR2R_ResWavesList()"
463                endif
464        endif
465        Redimension/D OriginalIntensity, OriginalQvector, OriginalError
466
467        DoWindow IR2R_LogLogPlotRefl
468        if (V_flag)
469                Dowindow/K IR2R_LogLogPlotRefl
470        endif
471        Execute ("IR2R_LogLogPlotRefl()")
472       
473        //create different view on data (may be fitting view?)
474        Duplicate/O OriginalIntensity, IntensityQN
475        Duplicate/O OriginalQvector, QvectorToN
476        Duplicate/O OriginalError, ErrorQN
477        NVAR FitIQN=root:Packages:Refl_SimpleTool:FitIQN       
478       
479        IntensityQN = OriginalIntensity * OriginalQvector^FitIQN
480        QvectorToN = OriginalQvector^FitIQN
481        ErrorQN = OriginalError  * OriginalQvector^FitIQN
482       
483
484                DoWindow IR2R_IQN_Q_PlotV
485                if (V_flag)
486                        Dowindow/K IR2R_IQN_Q_PlotV
487                endif
488                Execute ("IR2R_IQN_Q_PlotV()")
489
490                IR2R_CalculateSLDProfile()
491                DoWindow IR2R_SLDProfile
492                if (V_flag)
493                        Dowindow/K IR2R_SLDProfile
494                endif
495                Execute ("IR2R_SLDProfile()")
496        AutopositionWindow/E/M=0 /R=IR2R_ReflSimpleToolMainPanel  IR2R_LogLogPlotRefl
497        AutopositionWindow/E/M=1 /R=IR2R_LogLogPlotRefl IR2R_IQN_Q_PlotV
498        AutopositionWindow/E/M=1 /R=IR2R_IQN_Q_PlotV IR2R_SLDProfile
499       
500       
501        setDataFolder oldDf
502end
503
504Proc  IR2R_LogLogPlotRefl()
505        PauseUpdate; Silent 1           // building window...
506        String fldrSav= GetDataFolder(1)
507        SetDataFolder root:Packages:Refl_SimpleTool
508        Display /W=(300,37.25,850,300)/K=1  OriginalIntensity vs OriginalQvector as "LogLogPlot"
509        DoWIndow/C IR2R_LogLogPlotRefl
510        ModifyGraph mode(OriginalIntensity)=3
511        ModifyGraph msize(OriginalIntensity)=1
512        ModifyGraph log(left)=1
513        ModifyGraph mirror=1
514        ShowInfo
515        Label left "Reflectivity"
516        Label bottom "Q [A\\S-1\\M]"
517        TextBox/W=IR2R_LogLogPlotRefl/C/N=DateTimeTag/F=0/A=RB/E=2/X=2.00/Y=1.00 "\\Z07"+date()+", "+time()     
518        TextBox/W=IR2R_LogLogPlotRefl/C/N=SampleNameTag/F=0/A=LB/E=2/X=2.00/Y=1.00 "\\Z07"+DataFolderName+IntensityWaveName     
519        Legend/W=IR2R_LogLogPlotRefl/N=text0/J/F=0/A=MC/X=32.03/Y=38.79 "\\s(OriginalIntensity) Experimental intensity"
520        SetDataFolder fldrSav
521        ErrorBars/Y=1 OriginalIntensity Y,wave=(root:Packages:Refl_SimpleTool:OriginalError,root:Packages:Refl_SimpleTool:OriginalError)
522EndMacro
523
524Proc  IR2R_IQN_Q_PlotV()
525        PauseUpdate; Silent 1           // building window...
526        String fldrSav= GetDataFolder(1)
527        SetDataFolder root:Packages:Refl_SimpleTool:
528        Display /W=(300,250,850,430)/K=1  IntensityQN vs OriginalQvector as "IQ^N_Q_Plot"
529        DoWIndow/C IR2R_IQN_Q_PlotV
530        ModifyGraph mode(IntensityQN)=3
531        ModifyGraph msize(IntensityQN)=1
532        ModifyGraph log=1
533        ModifyGraph mirror=1
534        Label left "Reflectivity * Q^n"
535        Label bottom "Q [A\\S-1\\M]"
536        TextBox/W=IR2R_IQN_Q_PlotV/C/N=DateTimeTag/F=0/A=RB/E=2/X=2.00/Y=1.00 "\\Z07"+date()+", "+time()       
537        TextBox/W=IR2R_IQN_Q_PlotV/C/N=SampleNameTag/F=0/A=LB/E=2/X=2.00/Y=1.00 "\\Z07"+DataFolderName+IntensityWaveName       
538        SetDataFolder fldrSav
539        ErrorBars/Y=1 IntensityQN Y,wave=(root:Packages:Refl_SimpleTool:ErrorQN,root:Packages:Refl_SimpleTool:ErrorQN)
540EndMacro
541
542Proc  IR2R_SLDProfile()
543        PauseUpdate; Silent 1           // building window...
544        String fldrSav0= GetDataFolder(1)
545        SetDataFolder root:Packages:Refl_SimpleTool:
546        Display /W=(298.5,390.5,847.5,567.5)/K=1 SLDProfile as "SLD profile (top=left, substrate=right)"
547        DoWindow/C IR2R_SLDProfile
548        Label left "SLD profile [A\\S-2\\M]"
549        if(ZeroAtTheSubstrate)
550                Label bottom "<<--Substrate                                               Layer thickness [A]                                         Top -->>"
551                DoWindow/T IR2R_SLDProfile,"SLD profile (substrate=left, top=right)"
552        else
553                Label bottom "<<--TOP                                               Layer thickness [A]                                         Substrate -->>"
554                DoWindow/T IR2R_SLDProfile,"SLD profile (top=left, substrate=right) "
555        endif
556        SetDataFolder fldrSav0
557EndMacro
558
559
560///******************************************************************************************
561///******************************************************************************************
562///******************************************************************************************
563///******************************************************************************************
564///******************************************************************************************
565///******************************************************************************************
566
567static Function IR2R_InitializeSimpleTool()
568
569        string oldDf=GetDataFolder(1)
570       
571        NewDataFolder/O/S root:Packages
572        NewdataFolder/O/S root:Packages:Refl_SimpleTool
573       
574        string ListOfVariables
575        string ListOfStrings
576       
577        //here define the lists of variables and strings needed, separate names by ;...
578       
579        ListOfVariables="NumberOfLayers;ActiveTab;AutoUpdate;FitIQN;Resoln;UpdateAutomatically;ActiveTab;UseErrors;UseResolutionWave;UseLSQF;UseGenOpt;"
580        ListOfVariables+="SLD_Real_Top;SLD_Imag_Top;SLD_Real_Bot;SLD_Imag_Bot;ZeroAtTheSubstrate;UpdateDuringFitting;"
581        ListOfVariables+="Roughness_Bot;FitRoughness_Bot;Roughness_BotLL;Roughness_BotUL;Roughness_BotError;"
582        ListOfVariables+="Background;BackgroundStep;FitBackground;BackgroundLL;BackgroundUL;BackgroundError;"
583        ListOfVariables+="L1AtTheBottom;"
584
585        ListOfVariables+="Res_DeltaLambdaOverLambda;Res_DeltaLambda;Res_Lambda;Res_SourceDivergence;Res_DetectorSize;Res_DetectorDistance;"
586        ListOfVariables+="Res_DetectorAngularResolution;Res_sampleSize;Res_beamHeight;"
587        ListOfVariables+="ScalingFactor;ScalingFactorLL;ScalingFactorUL;FitScalingFactor;ScalingFactorError;"
588       
589        ListOfStrings="DataFolderName;IntensityWaveName;QWavename;ErrorWaveName;ResolutionWaveName;"
590       
591        variable i, j
592        //and here we create them
593        for(i=0;i<itemsInList(ListOfVariables);i+=1)   
594                IN2G_CreateItem("variable",StringFromList(i,ListOfVariables))
595        endfor         
596// create 8 x this following list:
597        ListOfVariables="SLD_Real_Layer;SLD_Imag_Layer;ThicknessLayer;RoughnessLayer;"
598        ListOfVariables+="SLD_Real_LayerError;SLD_Imag_LayerError;ThicknessLayerError;RoughnessLayerError;"
599        ListOfVariables+="SLD_Real_LayerStep;SLD_Imag_LayerStep;ThicknessLayerStep;RoughnessLayerStep;"
600        ListOfVariables+="SLD_Real_LayerLL;SLD_Imag_LayerLL;ThicknessLayerLL;RoughnessLayerLL;"
601        ListOfVariables+="SLD_Real_LayerUL;SLD_Imag_LayerUL;ThicknessLayerUL;RoughnessLayerUL;"
602        ListOfVariables+="FitSLD_Real_Layer;FitSLD_Imag_Layer;FitThicknessLayer;FitRoughnessLayer;"
603        ListOfVariables+="LinkSLD_Real_Layer;LinkSLD_Imag_Layer;LinkThicknessLayer;LinkRoughnessLayer;"
604        ListOfVariables+="LinkFSLD_Real_Layer;LinkFSLD_Imag_Layer;LinkFThicknessLayer;LinkFRoughnessLayer;"
605        ListOfVariables+="LinkToSLD_Real_Layer;LinkToSLD_Imag_Layer;LinkToThicknessLayer;LinkToRoughnessLayer;"
606        for(j=1;j<=8;j+=1)     
607                for(i=0;i<itemsInList(ListOfVariables);i+=1)   
608                        IN2G_CreateItem("variable",StringFromList(i,ListOfVariables)+num2str(j))
609                endfor         
610        endfor
611                                                                               
612        for(i=0;i<itemsInList(ListOfStrings);i+=1)     
613                IN2G_CreateItem("string",StringFromList(i,ListOfStrings))
614        endfor 
615        //cleanup after possible previous fitting stages...
616        Wave/Z CoefNames=root:Packages:FractalsModel:CoefNames
617        Wave/Z CoefficientInput=root:Packages:FractalsModel:CoefficientInput
618        KillWaves/Z CoefNames, CoefficientInput
619       
620        IR2R_SetInitialValues()         
621        setDataFolder oldDF
622
623end
624
625
626///******************************************************************************************
627///******************************************************************************************
628///******************************************************************************************
629///******************************************************************************************
630///******************************************************************************************
631/////******************************************************************************************
632//
633static Function IR2R_SetInitialValues()
634//      //and here set default values...
635//
636        string OldDf=getDataFolder(1)
637        setDataFolder root:Packages:Refl_SimpleTool
638//     
639        string ListOfVariables
640        variable i, j
641       
642        //      here we set what needs to be 0
643        ListOfVariables="SLD_Real_Top;SLD_Imag_Top;Background;Roughness_Bot;FitIQN;FitBackground;BackgroundLL;BackgroundUL;UpdateAutomatically;FitRoughness_Bot;Roughness_BotLL;Roughness_BotUL;"
644        For(i=0;i<itemsInList(ListOfVariables);i+=1)
645                NVAR/Z testVar=$(StringFromList(i,ListOfVariables))
646                testVar=0
647        endfor
648               
649        //and here to 1
650        ListOfVariables="NumberOfLayers;Resoln;UseErrors;ScalingFactor;"
651        For(i=0;i<itemsInList(ListOfVariables);i+=1)
652                NVAR/Z testVar=$(StringFromList(i,ListOfVariables))
653                if (testVar==0)
654                        testVar=1
655                endif
656        endfor
657        ListOfVariables="FitIQN;"
658        For(i=0;i<itemsInList(ListOfVariables);i+=1)
659                NVAR/Z testVar=$(StringFromList(i,ListOfVariables))
660                if (testVar==0)
661                        testVar=4
662                endif
663        endfor
664
665        ListOfVariables="ScalingFactorLL;"
666        For(i=0;i<itemsInList(ListOfVariables);i+=1)
667                NVAR/Z testVar=$(StringFromList(i,ListOfVariables))
668                if (testVar==0)
669                        testVar=0.1
670                endif
671        endfor
672
673        ListOfVariables="ScalingFactorUL;"
674        For(i=0;i<itemsInList(ListOfVariables);i+=1)
675                NVAR/Z testVar=$(StringFromList(i,ListOfVariables))
676                if (testVar==0)
677                        testVar=2
678                endif
679        endfor
680       
681       
682        NVAR SLD_Real_Bot
683        if(SLD_Real_Bot==0)
684                SLD_Real_Bot = 2.073
685        endif
686
687        NVAR SLD_Imag_Bot
688        if(SLD_Imag_Bot==0)
689                SLD_Imag_Bot = 2.37e-5
690        endif
691       
692        NVAR UseLSQF
693        NVAR UseGenOpt
694        if((UseLSQF+UseGenOpt)!=1)
695                UseLSQF=1
696                UseGenOpt=0
697        endif
698
699        For(j=1;j<=8;j+=1)
700                //set to 0
701                ListOfVariables="RoughnessLayer;SolventPenetrationLayer;"
702                For(i=0;i<itemsInList(ListOfVariables);i+=1)
703                        NVAR/Z testVar=$(StringFromList(i,ListOfVariables)+num2str(j))
704                        if (testVar==0)
705                                testVar=0
706                        endif
707                endfor
708                ListOfVariables="RoughnessLayerStep;SolventPenetrationLayerStep;"
709                For(i=0;i<itemsInList(ListOfVariables);i+=1)
710                        NVAR/Z testVar=$(StringFromList(i,ListOfVariables)+num2str(j))
711                        if (testVar==0)
712                                testVar=0.3
713                        endif
714                endfor
715                ListOfVariables="LinkFSLD_Real_Layer;LinkFSLD_Imag_Layer;LinkFThicknessLayer;LinkFRoughnessLayer;"
716                For(i=0;i<itemsInList(ListOfVariables);i+=1)
717                        NVAR/Z testVar=$(StringFromList(i,ListOfVariables)+num2str(j))
718                        if (testVar<=0)
719                                testVar=1
720                        endif
721                endfor
722                ListOfVariables="FitSLD_Real_Layer;FitSLD_Imag_Layer;FitThicknessLayer;FitRoughnessLayer;FitSolventPenetrationLayer;"
723                For(i=0;i<itemsInList(ListOfVariables);i+=1)
724                        NVAR/Z testVar=$(StringFromList(i,ListOfVariables)+num2str(j))
725                        if (testVar==0)
726                                testVar=0
727                        endif
728                endfor
729                //set to 25
730                ListOfVariables="ThicknessLayer;"
731                For(i=0;i<itemsInList(ListOfVariables);i+=1)
732                        NVAR/Z testVar=$(StringFromList(i,ListOfVariables)+num2str(j))
733                        if (testVar==0)
734                                testVar=25
735                        endif
736                endfor
737                //set to 25
738                ListOfVariables="ThicknessLayerStep;"
739                For(i=0;i<itemsInList(ListOfVariables);i+=1)
740                        NVAR/Z testVar=$(StringFromList(i,ListOfVariables)+num2str(j))
741                        if (testVar==0)
742                                testVar=5
743                        endif
744                endfor
745                //set to 3.47e-6
746                ListOfVariables="SLD_Real_Layer;"
747                For(i=0;i<itemsInList(ListOfVariables);i+=1)
748                        NVAR/Z testVar=$(StringFromList(i,ListOfVariables)+num2str(j))
749                        if (testVar==0)
750                                testVar=3.47
751                        endif
752                endfor
753                //set to 3.47e-6
754                ListOfVariables="SLD_Real_LayerStep;"
755                For(i=0;i<itemsInList(ListOfVariables);i+=1)
756                        NVAR/Z testVar=$(StringFromList(i,ListOfVariables)+num2str(j))
757                        if (testVar==0)
758                                testVar=0.1
759                        endif
760                endfor
761                //set to 3.47e-6
762                ListOfVariables="SLD_Imag_Layer;"
763                For(i=0;i<itemsInList(ListOfVariables);i+=1)
764                        NVAR/Z testVar=$(StringFromList(i,ListOfVariables)+num2str(j))
765                        if (testVar==0)
766                                testVar=1.05e-5
767                        endif
768                endfor
769                //set to 3.47e-6
770                ListOfVariables="SLD_Imag_LayerStep;"
771                For(i=0;i<itemsInList(ListOfVariables);i+=1)
772                        NVAR/Z testVar=$(StringFromList(i,ListOfVariables)+num2str(j))
773                        if (testVar==0)
774                                testVar=1e-6
775                        endif
776                endfor
777       
778               
779        endfor
780        IR2R_SetErrorsToZero()
781        setDataFolder oldDF
782end
783//
784//
785/////******************************************************************************************
786/////******************************************************************************************
787/////******************************************************************************************
788/////******************************************************************************************
789/////******************************************************************************************
790/////******************************************************************************************
791static Function IR2R_SetErrorsToZero()
792
793        string oldDf=GetDataFolder(1)
794        setDataFolder root:Packages:Refl_SimpleTool
795
796        string ListOfVariables="Roughness_BotError;BackgroundError;"
797        variable i,j
798       
799        For(i=0;i<itemsInList(ListOfVariables);i+=1)
800                NVAR/Z testVar=$(StringFromList(i,ListOfVariables))
801                testVar=0
802        endfor
803
804        ListOfVariables="SLD_Real_Layer;SLD_Imag_Layer;ThicknessLayer;RoughnessLayer;SolventPenetrationLayer;"
805
806        For(j=1;j<9;j+=1)
807                For(i=0;i<itemsInList(ListOfVariables);i+=1)
808                        NVAR/Z testVar=$(StringFromList(i,ListOfVariables)+"Error"+num2str(j))
809                        testVar=0
810                endfor
811        endfor
812
813        setDataFolder oldDF
814
815end
816
817///******************************************************************************************
818///******************************************************************************************
819///******************************************************************************************
820///******************************************************************************************
821///******************************************************************************************
822///******************************************************************************************
823static Function IR2R_CalculateSLDProfile()
824        //this function calculates model data
825//      make/o/t parameters_Cref = {"Numlayers","scale","re_SLDtop","imag_SLDtop","re_SLDbase","imag_SLD base","bkg","sigma_base","thick1","re_SLD1","imag_SLD1","rough1","thick2","re_SLD2","imag_SLD2","rough2"}
826//      Edit parameters_Cref,coef_Cref,par_res,resolution
827//      ywave_Cref:= Motofit_Imag(coef_Cref,xwave_Cref)
828
829        variable i, j
830        string OldDf=getDataFolder(1)
831        setDataFolder root:Packages:Refl_SimpleTool
832
833                //Need to create wave with parameters for Motofit_Imag here
834        NVAR NumberOfLayers= root:Packages:Refl_SimpleTool:NumberOfLayers
835        variable NumPntsInSLDPlot=NumberOfLayers * 200+50
836        make/O/N=(NumPntsInSLDPlot) SLDThicknessWv, SLDProfile
837        //need 8 parameters to start with - numLayers, scale, TopSLD_real, TopSLD_Imag, Bot_SLD_real, BotSLD_imag, Background, SubstareRoughness, and then 4 parameters for each layer
838        // thickness, re_SLD, imag_SLD and roughness
839        variable NumPointsNeeded= NumberOfLayers * 4 + 8
840       
841        make/O/N=(NumPointsNeeded) SLDParametersIn
842        //now let's fill this in
843        SLDParametersIn[0] = NumberOfLayers
844        NVAR ScalingFactor=root:Packages:Refl_SimpleTool:ScalingFactor
845        NVAR SLD_Real_Top=root:Packages:Refl_SimpleTool:SLD_Real_Top
846        NVAR SLD_Imag_Top=root:Packages:Refl_SimpleTool:SLD_Imag_Top
847        NVAR SLD_Real_Bot=root:Packages:Refl_SimpleTool:SLD_Real_Bot
848        NVAR SLD_Imag_Bot=root:Packages:Refl_SimpleTool:SLD_Imag_Bot
849        NVAR Background=root:Packages:Refl_SimpleTool:Background
850        NVAR Roughness_Bot=root:Packages:Refl_SimpleTool:Roughness_Bot 
851        NVAR L1AtTheBottom=root:Packages:Refl_SimpleTool:L1AtTheBottom
852       
853        SLDParametersIn[1] = ScalingFactor             
854        SLDParametersIn[2] = SLD_Real_Top
855        SLDParametersIn[3] = SLD_Imag_Top
856        SLDParametersIn[4] = SLD_Real_Bot
857        SLDParametersIn[5] = SLD_Imag_Bot
858        SLDParametersIn[6] = Background
859        SLDParametersIn[7] = Roughness_Bot
860
861        //fix to allow L1 at the bottom
862        if(L1AtTheBottom)
863                j=0
864                for(i=NumberOfLayers;i>=1;i-=1)
865                        j+=1
866                        NVAR ThicknessLayer= $("root:Packages:Refl_SimpleTool:ThicknessLayer"+Num2str(i))
867                        NVAR SLD_real_Layer = $("root:Packages:Refl_SimpleTool:SLD_Real_Layer"+Num2str(i))
868                        NVAR SLD_imag_Layer = $("root:Packages:Refl_SimpleTool:SLD_Imag_Layer"+Num2str(i))
869                        NVAR RoughnessLayer = $("root:Packages:Refl_SimpleTool:RoughnessLayer"+Num2str(i))
870                        SLDParametersIn[7+(j-1)*4+1] =  ThicknessLayer
871                        SLDParametersIn[7+(j-1)*4+2] =  SLD_real_Layer
872                        SLDParametersIn[7+(j-1)*4+3] =  SLD_imag_Layer
873                        SLDParametersIn[7+(j-1)*4+4] =  RoughnessLayer
874                endfor
875        else
876                for(i=1;i<=NumberOfLayers;i+=1)
877                        NVAR ThicknessLayer= $("root:Packages:Refl_SimpleTool:ThicknessLayer"+Num2str(i))
878                        NVAR SLD_real_Layer = $("root:Packages:Refl_SimpleTool:SLD_Real_Layer"+Num2str(i))
879                        NVAR SLD_imag_Layer = $("root:Packages:Refl_SimpleTool:SLD_Imag_Layer"+Num2str(i))
880                        NVAR RoughnessLayer = $("root:Packages:Refl_SimpleTool:RoughnessLayer"+Num2str(i))
881                        SLDParametersIn[7+(i-1)*4+1] =  ThicknessLayer
882                        SLDParametersIn[7+(i-1)*4+2] =  SLD_real_Layer
883                        SLDParametersIn[7+(i-1)*4+3] =  SLD_imag_Layer
884                        SLDParametersIn[7+(i-1)*4+4] =  RoughnessLayer
885                endfor
886        endif
887
888
889        //setup the thickness scaling...
890        variable zstart
891        if (NumberOfLayers==0)
892                zstart=-4*abs(Roughness_Bot)    //roughness substrate
893        else
894                  NVAR RoughnessLayer = root:Packages:Refl_SimpleTool:RoughnessLayer1
895               zstart=-4*abs(RoughnessLayer)    //roughness first layer
896        endif
897         
898        variable zend, temp
899       
900        temp=0
901        if (NumberOfLayers==0)
902                zend=4*abs(Roughness_Bot)       //roughness substrate
903        else   
904                for(i=1;i<=NumberOfLayers;i+=1)
905                        NVAR ThicknessLayer= $("root:Packages:Refl_SimpleTool:ThicknessLayer"+Num2str(i))
906                        temp+=ThicknessLayer
907                endfor           
908                  NVAR RoughnessLayer = root:Packages:Refl_SimpleTool:RoughnessLayer1
909           zend=temp+4*abs(RoughnessLayer)
910        endif
911        variable totalLength = zend - zstart
912//        zstart = zstart- floor( 0.04 * totalLength)
913//        zend = zend + floor( 0.04 * totalLength)
914        zstart = zstart- floor( 0.08 * totalLength)             //seemed too small for Dale
915        zend = zend + floor( 0.08 * totalLength)
916        SetScale/I x zstart,zend,"", SLDProfile
917
918//      Duplicate/O OriginalQvector, ModelQvector, ModelIntensity
919//      ModelIntensity=Calcreflectivity_Imag(ParametersIn,ModelQvector)
920//      variable/g plotyp=2
921//      ModelIntensity=Motofit_Imag(ParametersIn,ModelQvector)
922        SLDProfile = IR2R_SLDplot(SLDParametersIn,x)
923        //this has 0 at the top...
924        //Now we may have to flip the top and bottom..
925         NVAR ZeroAtTheSubstrate=root:Packages:Refl_SimpleTool:ZeroAtTheSubstrate
926        if(ZeroAtTheSubstrate)
927                SetScale/I x zend,zstart,"", SLDProfile
928        endif
929        setDataFolder OldDf
930       
931end
932
933///******************************************************************************************
934///******************************************************************************************
935///******************************************************************************************
936///******************************************************************************************
937///******************************************************************************************
938
939
940static Function IR2R_SLDplot(w,z)
941        Wave w
942        Variable z
943       
944        string OldDf=getDataFolder(1)
945        setDataFolder root:Packages:Refl_SimpleTool
946//      Wave SLDThicknessWv=root:Packages:Refl_SimpleTool:SLDThicknessWv
947//      variable  SLDpts=numpnts(SLDThicknessWv)
948       
949        variable nlayers,SLD1,SLD2,zstart,zend,ii,temp,zinc,summ,deltarho,zi,dindex,sigma,thick,dist,rhotop
950
951
952////This function calculates the SLD profile. 
953        nlayers=w[0]
954        rhotop=w[3]
955                dist=0
956                summ=w[2]               //SLDTop
957                ii=0
958                do
959                        if(ii==0)
960                                //SLD1=(w[7]/100)*(100-w[8])+(w[8]*rhosolv/100)         original...
961                                SLD1=w[9]
962                                deltarho=-w[2]+SLD1
963                                thick=0
964                                if(nlayers==0)
965                                        sigma=abs(w[7])         //substrate roughness
966                                        //deltarho=-w[2]+w[3]   //SLD substrate and top
967                                        deltarho=-w[2]+w[4]     //SLD substrate and top
968                                else
969                                        //sigma=abs(w[9])
970                                        sigma=abs(w[11])                //roughness first layer
971//                                      deltarho=-w[2]+w[4]     //SLD substrate and first layer
972                                endif
973                        elseif(ii==nlayers)
974                                //SLD1=(w[4*ii+3]/100)*(100-w[4*ii+4])+(w[4*ii+4]*rhosolv/100)
975                                SLD1=(w[7+(ii-1)*4+2])
976                                SLD2=w[4]                       //substrate
977                                //deltarho=-SLD1+rhosolv
978                                deltarho=-SLD1+SLD2
979                                //thick=abs(w[4*ii+2])
980                                //sigma=abs(w[5])
981                                thick=abs(w[7+(ii-1)*4+1])
982                                sigma=abs(w[7])
983                        else
984                                //SLD1=(w[4*ii+3]/100)*(100-w[4*ii+4])+(w[4*ii+4]*rhosolv/100)
985                                //SLD2=(w[4*(ii+1)+3]/100)*(100-w[4*(ii+1)+4])+(w[4*(ii+1)+4]*rhosolv/100)
986                                //deltarho=-SLD1+SLD2
987                                //thick=abs(w[4*(ii)+2])
988                                //sigma=abs(w[4*(ii+1)+5])
989                                SLD1=(w[7+(ii-1)*4+2])
990                                SLD2=(w[7+(ii)*4+2])
991                                deltarho=-SLD1+SLD2
992                                thick=abs(w[7+(ii-1)*4+1])
993                                sigma=abs(w[7+(ii)*4+4])
994                        endif
995                       
996                       
997                        dist+=thick
998                       
999                       
1000                        //if sigma=0 then the computer goes haywire (division by zero), so say it's vanishingly small
1001                        if(sigma==0)
1002                                sigma+=1e-3
1003                        endif
1004                        summ+=(deltarho/2)*(1+erf((z-dist)/(sigma*sqrt(2))))
1005                       
1006                       
1007                        ii+=1
1008                while(ii<nlayers+1)
1009                       
1010                return summ
1011End
1012
1013
1014///******************************************************************************************
1015///******************************************************************************************
1016///******************************************************************************************
1017///******************************************************************************************
1018
1019static Function IR2R_CalculateReflectivityNewRW(w, RR, qq, dq)
1020        Wave w, RR, qq, dq
1021        variable bkg
1022       
1023        NVAR UseResolutionWave = root:Packages:Refl_SimpleTool:UseResolutionWave       
1024        make/free/d/n=(numpnts(qq), 2) xtemp
1025        xtemp[][0] = qq[p]
1026        //Abeles expects the resolution wave to be in %
1027        if(UseResolutionWave==1)                //old % input
1028                xtemp[][1] = dq[p]*qq[p]/100
1029        elseif(UseResolutionWave==2)            //dq input
1030                xtemp[][1] = dq[p]
1031        elseif(UseResolutionWave==3)            //dq^2 input
1032                xtemp[][1] = sqrt(dq[p])                       
1033        else
1034                Abort "Error in IR2R_CalculateReflectivityNewRW, unknown resolution type"
1035        endif
1036       
1037        //let's try to check if we need _imag or not...
1038        //imag  -> no imag
1039        //w[0]  -> w[0]   num layers
1040        //w[1]  -> w[1]         scale
1041        //w[2]  -> w[2]         sldtop
1042        //w[3]  .....                   imag sld top
1043        //w[4]  -> w[3]         sld base
1044        //w[5]  .....                   imag sld base
1045        //w[6]  -> w[4]         backg.
1046        //w[7]  -> w[5]         rough base
1047        //w[8]  -> w[6]         thick 1
1048        //w[9]  -> w[7]         sld1
1049        //w[10]         ...             imag sld 1
1050        //w[11] -> w[8]         rough 1
1051        //and repeat 8-11
1052        variable oldWlength=numpnts(w)
1053        variable newWlength=6 + (oldWlength-8)/4
1054        //check if something imag is there...
1055        variable ImagVals=0
1056        variable i
1057        if(w[3]>0 || w[5]>0)
1058                ImagVals=1
1059        endif
1060        For(i=10;i<oldWlength;i+=4)
1061                if(w[i]>0)
1062                        ImagVals=1
1063                        break
1064                endif
1065        endfor 
1066        if(ImagVals)
1067//      print "used imag"
1068                bkg = abs(w[6])
1069                w[6] = 0
1070                Abeles_imagALl(w, RR, xtemp)
1071                w[6] = bkg
1072                fastop RR = (bkg) + RR
1073        else //no imag values...
1074                bkg = abs(w[6])
1075                w[6] = 0
1076                Abeles_imagALl(w, RR, xtemp)
1077                w[6] = bkg
1078                fastop RR = (bkg) + RR
1079        endif
1080       
1081       
1082End
1083
1084///******************************************************************************************
1085///******************************************************************************************
1086///******************************************************************************************
1087///******************************************************************************************
1088
1089static Function IR2R_CalculateReflectivityNew(w,RR,qq, resolution)
1090        Wave w, RR,qq
1091        variable resolution
1092
1093        variable mode, bkg
1094        variable plotyp
1095        plotyp = 1
1096                       
1097        if(numtype(resolution) || resolution < 0.5)
1098                resolution = 0
1099        endif
1100               
1101        bkg = abs(w[6])
1102        w[6] = 0
1103//      markperftesttime 1                     
1104        if(resolution > 0.5)
1105                //make it an odd number
1106                resolution/=100
1107                Variable gaussnum=13
1108
1109                Make/free/d/n=(gaussnum) gausswave
1110                Setscale/I x, -resolution, resolution, gausswave
1111                Gausswave=gauss(x, 0, resolution/(2 * sqrt(2 * ln(2))))
1112                Variable middle = gausswave[x2pnt(gausswave, 0)]
1113                 Gausswave /= middle
1114                Variable gaussgpoint = (gaussnum-1)/2
1115                               
1116                //find out what the lowest and highest qvalue are
1117                variable lowQ = wavemin(qq)
1118                variable highQ = wavemax(qq)
1119               
1120                if(lowQ == 0)
1121                        lowQ =1e-6
1122                endif
1123               
1124                Variable start=log(lowQ) - 6 * resolution / 2.35482
1125                Variable finish=log(highQ * (1 + 6 * resolution / 2.35482))
1126                Variable interpnum=round(abs(1 * (abs(start - finish)) / (resolution / 2.35482 / gaussgpoint)))
1127                variable val = (abs(start - finish)) / (interpnum)
1128                make/free/d/n=(interpnum) ytemp, xtemp
1129                multithread xtemp=(start) + p * val
1130
1131                matrixop/o xtemp = powR(10, xtemp)
1132
1133//              markperftesttime 2
1134
1135                Abeles_imagALl(w, ytemp, xtemp)
1136//              markperftesttime 3
1137                //do the resolution convolution
1138                setscale/I x, start, log(xtemp[numpnts(xtemp) - 1]), ytemp
1139                convolve/A gausswave, ytemp
1140
1141                //delete start and finish nodes.
1142                variable number2d = round(6 * (resolution / 2.35482) / ((abs(start - finish)) / (interpnum))) - 1
1143                variable left = leftx(ytemp), space = deltax(ytemp)
1144                deletepoints 0, number2d, ytemp
1145                setscale/P x, left + (number2d * space), space, ytemp
1146               
1147                variable gaussum = 1/(sum(gausswave))
1148                fastop ytemp = (gaussum) * ytemp
1149
1150//              markperftesttime 4
1151                matrixop/free xrtemp = log(qq)
1152                duplicate/free rr, ytemp2
1153                //interpolate to get the theoretical points at the same spacing of the real dataset
1154//              markperftesttime 5
1155                Interpolate2/T=2/E=2/I=3/Y=ytemp2/X=xrtemp ytemp
1156                multithread RR = ytemp2
1157//              markperftesttime 6
1158
1159        else
1160                Abeles_imagALl(w, RR, qq)
1161        endif
1162
1163        //add in the linear background again
1164        w[6] = bkg
1165        fastop RR = (bkg) + RR
1166               
1167
1168End
1169
1170
1171///******************************************************************************************
1172///******************************************************************************************
1173///******************************************************************************************
1174
1175static Function IR2R_CalculateReflectivity(w,x, res)
1176        Wave w
1177        variable x, res
1178        Variable dq,reflectivity
1179       
1180        duplicate/o w call
1181        Wave call
1182        call[6]=0
1183        dq=x*(res/100)
1184
1185#if Exists("Abeles_imag")       
1186        reflectivity=Abeles_imag(call,x)
1187        if(dq>0)
1188                reflectivity+=0.135*Abeles_imag(call,x-dq)
1189                reflectivity+=0.135*Abeles_imag(call,x+dq)
1190                reflectivity+=0.325*Abeles_imag(call,x-(dq*0.75))
1191                reflectivity+=0.325*Abeles_imag(call,x+(dq*0.75))
1192                reflectivity+=0.605*Abeles_imag(call,x-(dq/2))
1193                reflectivity+=0.605*Abeles_imag(call,x+(dq/2))
1194                reflectivity+=0.88*Abeles_imag(call,x-(dq/4))
1195                reflectivity+=0.88*Abeles_imag(call,x+(dq/4))
1196                reflectivity/=4.89
1197        endif
1198#else
1199        reflectivity=IR2R_CalculateReflectivityInt(call,x)
1200        if(dq>0)
1201                reflectivity+=0.135*IR2R_CalculateReflectivityInt(call,x-dq)
1202                reflectivity+=0.135*IR2R_CalculateReflectivityInt(call,x+dq)
1203                reflectivity+=0.325*IR2R_CalculateReflectivityInt(call,x-(dq*0.75))
1204                reflectivity+=0.325*IR2R_CalculateReflectivityInt(call,x+(dq*0.75))
1205                reflectivity+=0.605*IR2R_CalculateReflectivityInt(call,x-(dq/2))
1206                reflectivity+=0.605*IR2R_CalculateReflectivityInt(call,x+(dq/2))
1207                reflectivity+=0.88*IR2R_CalculateReflectivityInt(call,x-(dq/4))
1208                reflectivity+=0.88*IR2R_CalculateReflectivityInt(call,x+(dq/4))
1209                reflectivity/=4.89
1210        endif
1211#endif
1212
1213
1214        reflectivity+=abs(w[6])
1215       
1216        Killwaves/Z kzn,rn,rrn
1217       
1218        return reflectivity
1219End
1220
1221///******************************************************************************************
1222///******************************************************************************************
1223///******************************************************************************************
1224///******************************************************************************************
1225///******************************************************************************************
1226//static Function IR2R_CalcReflectivitySwitch(w,x)
1227//      Wave w
1228//      Variable x
1229//
1230////    //if we can use the xop here and skip the rest. This should be basically transparent to user, if we can get the xop function...
1231////    //
1232//
1233//      if(exists("Abeles_imag")==3)
1234//         Funcref IR2R_CalculateReflectivityInt f=$"Abeles_imag"
1235//      else
1236//         Funcref IR2R_CalculateReflectivityInt f=IR2R_CalculateReflectivityInt
1237//      endif
1238//
1239//      variable y
1240//      y=f(w,x)
1241//
1242//      return y
1243//end
1244///******************************************************************************************
1245///******************************************************************************************
1246///******************************************************************************************
1247///******************************************************************************************
1248///******************************************************************************************
1249
1250static Function IR2R_CalculateReflectivityInt(w,x) //:fitfunc
1251        Wave w
1252        Variable x
1253       
1254        Variable reflectivity,ii,nlayers,inter,qq,scale,bkg,subrough
1255        Variable/C super,sub,arg,cinter,SLD
1256       
1257        //number of layers,re_SUPERphaseSLD,imag_SUPER,re_SUBphaseSLD,imag_SUB
1258       
1259        //subsequent layers have 4 parameters each: thickness, re_SLD, imag_SLD and roughness
1260        //if you increase the number of layers you have to put extra parameters in.
1261        //you should be able to remember the order in which they go.
1262       
1263       
1264        //Layer 1 is always closest to the SUPERPHASE (e.g. air).  increasing layers go down
1265        //towards the subphase.  This may be confusing if you switch between air-solid and solid-liquid
1266        //I will write some functions to create exotic SLD profiles if required.
1267       
1268       
1269        nlayers=w[0]
1270        scale=w[1]
1271        super=cmplx(w[2]*1e-6,-abs(w[3]))                       // JI 3/306 this fixes some problems - f" is negative and hence the SLD imaginary part should be also...
1272        sub=cmplx(w[4]*1e-6,-abs(w[5]))                 // JI 3/306 this fixes some problems - f" is negative and hence the SLD imaginary part should be also...
1273        bkg=abs(w[6])
1274        subrough=w[7]
1275        qq=x
1276       
1277        //for definitions of these see Parratt handbook
1278        Make/o/d/C/n=(nlayers+2) kzn
1279        Make/o/d/C/n=(nlayers+2) rn
1280        Make/o/d/C/n=(nlayers+2) RRN
1281       
1282        //workout the wavevector in the incident medium/superphase
1283        inter=cabs(sqrt((qq/2)^2))
1284        kzn[0]=cmplx(inter,0)
1285       
1286        //workout the wavevector in the subphase
1287        kzn[nlayers+1]=sqrt(kzn[0]^2-4*Pi*(sub-super))
1288       
1289        //workout the wavevector in each of the layers
1290        ii=1
1291        if(ii<nlayers+1)
1292                do
1293        //       SLD=cmplx(w[4*ii+5],w[4*ii+6])                 //original
1294                 SLD=cmplx(w[4*ii+5]*1e-6,-abs(w[4*ii+6]))                      // JI 3/306 this fixes some problems - f" is negative and hence the SLD imaginary part should be also...
1295                 
1296                 cinter=sqrt(kzn[0]^2-4*Pi*(SLD-super))         //this bit is important otherwise the SQRT doesn't work on the complex number
1297                 kzn[ii]=(cinter)
1298                 ii+=1
1299                while(ii<nlayers+1)
1300        endif
1301       
1302        //RRN[subphase]=0,RRN[subphase-1]=fresnel reflectance of n, subphase
1303        RRN[nlayers+1]=cmplx(0,0)
1304        RRN[nlayers]=(kzn[nlayers]-kzn[nlayers+1])/(kzn[nlayers]+kzn[nlayers+1])
1305        arg=-2*kzn[nlayers]*kzn[nlayers+1]*subrough^2
1306        RRN[nlayers]*=exp(arg)
1307       
1308        //work out the fresnel reflectance for the layer then calculate the total reflectivity from each layer
1309        ii=nlayers-1
1310        do
1311                //work out the fresnel reflectance for each layer
1312                rn[ii]=(kzn[ii]-kzn[ii+1])/(kzn[ii]+kzn[ii+1])
1313                arg=-2*kzn[ii]*kzn[ii+1]*w[4*(ii+1)+7]^2
1314                rn[ii]*=exp(arg)
1315                //now work out the total reflectivity from the layer
1316                arg=cmplx(0,2*abs(w[4*(ii+1)+4]))
1317                arg*=(kzn[ii+1])
1318                RRN[ii]=rn[ii]+RRN[ii+1]*exp(arg)
1319                RRN[ii]/=1+rn[ii]*RRN[ii+1]*exp(arg)
1320               
1321                ii-=1
1322        while(ii>-1)
1323       
1324        //reflectivity=abs(Ro)^2
1325        reflectivity=magsqr(RRN[0])
1326        reflectivity*=scale
1327        reflectivity+=bkg
1328       
1329       
1330//      reflectivity=(reflectivity)
1331       
1332        return reflectivity
1333       
1334End
1335
1336
1337//Control procedures for simple tool Mottfit
1338
1339///******************************************************************************************
1340///******************************************************************************************
1341///******************************************************************************************
1342
1343static Function IR2R_UpdateLinkedVariables()
1344
1345        string ListOfVariables="SLD_Real_Layer;SLD_Imag_Layer;ThicknessLayer;RoughnessLayer;"
1346        variable i, j
1347        string tempVarName
1348        For(i=1;i<=8;i+=1)
1349                For(j=0;j<ItemsInList(ListOfVariables);j+=1)
1350                        tempVarName = stringFromList(j, ListOfVariables)
1351                        NVAR ValueVar=$("root:Packages:Refl_SimpleTool:"+tempVarName+num2str(i))
1352                        NVAR LinkVar=$("root:Packages:Refl_SimpleTool:Link"+tempVarName+num2str(i))
1353                        NVAR LinkFractionVar=$("root:Packages:Refl_SimpleTool:LinkF"+tempVarName+num2str(i))
1354                        NVAR LinkToVar=$("root:Packages:Refl_SimpleTool:LinkTo"+tempVarName+num2str(i))
1355                        if(LinkVar && LinkToVar>0 && LinkToVar!=i)
1356                                NVAR LinkedVarVal = $("root:Packages:Refl_SimpleTool:"+tempVarName+num2str(LinkToVar))
1357                                ValueVar = LinkedVarVal * LinkFractionVar
1358                        endif
1359                endfor
1360        endfor
1361end
1362
1363///******************************************************************************************
1364///******************************************************************************************
1365///******************************************************************************************
1366
1367Function IR2R_PanelSetVarProc(ctrlName,varNum,varStr,varName) : SetVariableControl
1368        String ctrlName
1369        Variable varNum
1370        String varStr
1371        String varName
1372
1373        string oldDf=GetDataFolder(1)
1374        setDataFolder root:Packages:Refl_SimpleTool
1375        variable currentVar
1376
1377        if (stringmatch(ctrlName,"LinkF*"))
1378                IR2R_UpdateLinkedVariables()
1379        endif
1380        if (stringmatch(ctrlName,"ThicknessLayer*") && !stringmatch(ctrlName,"*Step*") && !stringmatch(ctrlName,"*LL*") && !stringmatch(ctrlName,"*UL*"))
1381                currentVar=str2num(ctrlName[14,inf])
1382                NVAR ThicknessLayer=$("root:Packages:Refl_SimpleTool:ThicknessLayer"+num2str(currentVar))
1383                NVAR ThicknessLayerLL=$("root:Packages:Refl_SimpleTool:ThicknessLayerLL"+num2str(currentVar))
1384                NVAR ThicknessLayerUL=$("root:Packages:Refl_SimpleTool:ThicknessLayerUL"+num2str(currentVar))
1385                ThicknessLayerLL = ThicknessLayer/2
1386                ThicknessLayerUL = ThicknessLayer*2
1387                Execute("Slider ThicknessLayerSl"+num2str(currentVar)+" limits={"+num2str(ThicknessLayerLL)+","+num2str(ThicknessLayerUL)+",0}")
1388                //and impose limit on roughness...
1389                NVAR RoughnessLayerUL=$("root:Packages:Refl_SimpleTool:RoughnessLayerUL"+num2str(currentVar))
1390                if(RoughnessLayerUL>ThicknessLayer/2.38)
1391                        RoughnessLayerUL = ThicknessLayer/2.38
1392                endif
1393        endif
1394        if (stringmatch(ctrlName,"ThicknessLayerLL*") || stringmatch(ctrlName,"ThicknessLayerUL*"))
1395                currentVar=str2num(ctrlName[16,inf])
1396                NVAR ThicknessLayerLL=$("root:Packages:Refl_SimpleTool:ThicknessLayerLL"+num2str(currentVar))
1397                NVAR ThicknessLayerUL=$("root:Packages:Refl_SimpleTool:ThicknessLayerUL"+num2str(currentVar))
1398                Execute("Slider ThicknessLayerSl"+num2str(currentVar)+" limits={"+num2str(ThicknessLayerLL)+","+num2str(ThicknessLayerUL)+",0}")
1399        endif
1400               
1401        if (stringmatch(ctrlName,"SLD_Real_Layer*") && !stringmatch(ctrlName,"*Step*") && !stringmatch(ctrlName,"*LL*") && !stringmatch(ctrlName,"*UL*"))
1402                currentVar=str2num(ctrlName[14,inf])
1403                NVAR SLD_Real_Layer=$("root:Packages:Refl_SimpleTool:SLD_Real_Layer"+num2str(currentVar))
1404                NVAR SLD_Real_LayerLL=$("root:Packages:Refl_SimpleTool:SLD_Real_LayerLL"+num2str(currentVar))
1405                NVAR SLD_Real_LayerUL=$("root:Packages:Refl_SimpleTool:SLD_Real_LayerUL"+num2str(currentVar))
1406                SLD_Real_LayerLL = SLD_Real_Layer/2
1407                SLD_Real_LayerUL = SLD_Real_Layer*2
1408                Execute("Slider SLD_Real_LayerSl"+num2str(currentVar)+" limits={"+num2str(SLD_Real_LayerLL)+","+num2str(SLD_Real_LayerUL)+",0}")
1409        endif
1410        if (stringmatch(ctrlName,"SLD_Real_LayerLL*") || stringmatch(ctrlName,"SLD_Real_LayerUL*"))
1411                currentVar=str2num(ctrlName[16,inf])
1412                NVAR SLD_Real_LayerLL=$("root:Packages:Refl_SimpleTool:SLD_Real_LayerLL"+num2str(currentVar))
1413                NVAR SLD_Real_LayerUL=$("root:Packages:Refl_SimpleTool:SLD_Real_LayerUL"+num2str(currentVar))
1414                Execute("Slider SLD_Real_LayerSl"+num2str(currentVar)+" limits={"+num2str(SLD_Real_LayerLL)+","+num2str(SLD_Real_LayerUL)+",0}")
1415        endif
1416
1417
1418        if (stringmatch(ctrlName,"SLD_Imag_Layer*")&& !stringmatch(ctrlName,"*Step*") && !stringmatch(ctrlName,"*LL*") && !stringmatch(ctrlName,"*UL*"))
1419                currentVar=str2num(ctrlName[14,inf])
1420                NVAR SLD_Imag_Layer=$("root:Packages:Refl_SimpleTool:SLD_Imag_Layer"+num2str(currentVar))
1421                NVAR SLD_Imag_LayerLL=$("root:Packages:Refl_SimpleTool:SLD_Imag_LayerLL"+num2str(currentVar))
1422                NVAR SLD_Imag_LayerUL=$("root:Packages:Refl_SimpleTool:SLD_Imag_LayerUL"+num2str(currentVar))
1423                SLD_Imag_LayerLL = SLD_Imag_Layer/2
1424                SLD_Imag_LayerUL = SLD_Imag_Layer*2
1425                Execute("Slider SLD_Imag_LayerSl"+num2str(currentVar)+" limits={"+num2str(SLD_Imag_LayerLL)+","+num2str(SLD_Imag_LayerUL)+",0}")
1426        endif
1427        if (stringmatch(ctrlName,"SLD_Imag_LayerLL*")||stringmatch(ctrlName,"SLD_Imag_LayerUL*"))
1428                currentVar=str2num(ctrlName[16,inf])
1429                NVAR SLD_Imag_LayerLL=$("root:Packages:Refl_SimpleTool:SLD_Imag_LayerLL"+num2str(currentVar))
1430                NVAR SLD_Imag_LayerUL=$("root:Packages:Refl_SimpleTool:SLD_Imag_LayerUL"+num2str(currentVar))
1431                Execute("Slider SLD_Imag_LayerSl"+num2str(currentVar)+" limits={"+num2str(SLD_Imag_LayerLL)+","+num2str(SLD_Imag_LayerUL)+",0}")
1432        endif
1433
1434        if (stringmatch(ctrlName,"RoughnessLayer*")&& !stringmatch(ctrlName,"*Step*") && !stringmatch(ctrlName,"*LL*") && !stringmatch(ctrlName,"*UL*"))
1435                currentVar=str2num(ctrlName[14,inf])
1436                NVAR RoughnessLayer=$("root:Packages:Refl_SimpleTool:RoughnessLayer"+num2str(currentVar))
1437                NVAR RoughnessLayerLL=$("root:Packages:Refl_SimpleTool:RoughnessLayerLL"+num2str(currentVar))
1438                NVAR RoughnessLayerUL=$("root:Packages:Refl_SimpleTool:RoughnessLayerUL"+num2str(currentVar))
1439                NVAR ThicknessLayer=$("root:Packages:Refl_SimpleTool:ThicknessLayer"+num2str(currentVar))
1440                RoughnessLayerLL = RoughnessLayer/2
1441                RoughnessLayerUL = RoughnessLayer*2
1442                Execute("Slider RoughnessLayerSl"+num2str(currentVar)+" limits={"+num2str(RoughnessLayerLL)+","+num2str(RoughnessLayerUL)+",0}")
1443        endif
1444        if (stringmatch(ctrlName,"RoughnessLayerLL*")||stringmatch(ctrlName,"RoughnessLayerUL*") )
1445                currentVar=str2num(ctrlName[16,inf])
1446                NVAR RoughnessLayerLL=$("root:Packages:Refl_SimpleTool:RoughnessLayerLL"+num2str(currentVar))
1447                NVAR RoughnessLayerUL=$("root:Packages:Refl_SimpleTool:RoughnessLayerUL"+num2str(currentVar))
1448                Execute("Slider RoughnessLayerSl"+num2str(currentVar)+" limits={"+num2str(RoughnessLayerLL)+","+num2str(RoughnessLayerUL)+",0}")
1449        endif
1450        if (stringmatch(ctrlName,"Roughness_Bot")&& !stringmatch(ctrlName,"*Step*") && !stringmatch(ctrlName,"*LL*") && !stringmatch(ctrlName,"*UL*"))
1451                NVAR Roughness_Bot=root:Packages:Refl_SimpleTool:Roughness_Bot
1452                NVAR Roughness_BotLL=root:Packages:Refl_SimpleTool:Roughness_BotLL
1453                NVAR Roughness_BotUL=root:Packages:Refl_SimpleTool:Roughness_BotUL
1454                Roughness_BotLL = Roughness_Bot/2
1455                Roughness_BotUL = Roughness_Bot*2
1456        endif
1457        if (stringmatch(ctrlName,"Background")&& !stringmatch(ctrlName,"*Step*") && !stringmatch(ctrlName,"*LL*") && !stringmatch(ctrlName,"*UL*"))
1458                NVAR Background=root:Packages:Refl_SimpleTool:Background
1459                NVAR BackgroundLL=root:Packages:Refl_SimpleTool:BackgroundLL
1460                NVAR BackgroundUL=root:Packages:Refl_SimpleTool:BackgroundUL
1461                BackgroundLL = Background/2
1462                BackgroundUL = Background*2
1463        endif
1464        if (stringmatch(ctrlName,"ScalingFactor")&& !stringmatch(ctrlName,"*Step*") && !stringmatch(ctrlName,"*LL*") && !stringmatch(ctrlName,"*UL*"))
1465                NVAR ScalingFactor=root:Packages:Refl_SimpleTool:ScalingFactor
1466                NVAR ScalingFactorLL=root:Packages:Refl_SimpleTool:ScalingFactorLL
1467                NVAR ScalingFactorUL=root:Packages:Refl_SimpleTool:ScalingFactorUL
1468                ScalingFactorLL = ScalingFactor/2
1469                ScalingFactorUL = ScalingFactor*2
1470        endif
1471
1472//      ListOfVariables="Background;Roughness_Bot;ScalingFactor;"
1473
1474        if (stringmatch(ctrlName,"ThicknessLayerStep*"))
1475                currentVar=str2num(ctrlName[18,inf])
1476                NVAR ThicknessLayerStep=$("root:Packages:Refl_SimpleTool:ThicknessLayerStep"+num2str(currentVar))
1477                Execute("SetVariable ThicknessLayer"+num2str(currentVar)+",limits={0,inf,root:Packages:Refl_SimpleTool:ThicknessLayerStep"+num2str(currentVar)+"},win=IR2R_ReflSimpleToolMainPanel")
1478        endif
1479        if (stringmatch(ctrlName,"SLD_Real_LayerStep*"))
1480                currentVar=str2num(ctrlName[18,inf])
1481                NVAR ThicknessLayerStep=$("root:Packages:Refl_SimpleTool:SLD_Real_LayerStep"+num2str(currentVar))
1482                Execute("SetVariable SLD_Real_Layer"+num2str(currentVar)+",limits={-inf,inf,root:Packages:Refl_SimpleTool:SLD_Real_LayerStep"+num2str(currentVar)+"},win=IR2R_ReflSimpleToolMainPanel")
1483        endif
1484        if (stringmatch(ctrlName,"SLD_Imag_LayerStep*"))
1485                currentVar=str2num(ctrlName[18,inf])
1486                NVAR ThicknessLayerStep=$("root:Packages:Refl_SimpleTool:SLD_Imag_LayerStep"+num2str(currentVar))
1487                Execute("SetVariable SLD_Imag_Layer"+num2str(currentVar)+",limits={-inf,inf,root:Packages:Refl_SimpleTool:SLD_Imag_LayerStep"+num2str(currentVar)+"},win=IR2R_ReflSimpleToolMainPanel")
1488        endif
1489       
1490        if (stringmatch(ctrlName,"RoughnessLayerStep*"))
1491                currentVar=str2num(ctrlName[18,inf])
1492                NVAR RoughnessLayerStep=$("root:Packages:Refl_SimpleTool:RoughnessLayerStep"+num2str(currentVar))
1493                Execute("SetVariable RoughnessLayer"+num2str(currentVar)+",limits={0,inf,root:Packages:Refl_SimpleTool:RoughnessLayerStep"+num2str(currentVar)+"},win=IR2R_ReflSimpleToolMainPanel")
1494        endif
1495
1496        if (cmpstr(ctrlName,"BackgroundStep")==0)
1497        //      currentVar=str2num(ctrlName[18,inf])
1498                NVAR BackgroundStep=$("root:Packages:Refl_SimpleTool:BackgroundStep")
1499                Execute("SetVariable Background,limits={0,inf,root:Packages:Refl_SimpleTool:BackgroundStep},win=IR2R_ReflSimpleToolMainPanel")
1500        endif
1501
1502        if (!stringmatch(ctrlName,"*Step*") && !stringmatch(ctrlName,"*LL*") && !stringmatch(ctrlName,"*UL*"))
1503                NVAR AutoUpdate=root:Packages:Refl_SimpleTool:AutoUpdate
1504                if (AutoUpdate)
1505                        IR2R_CalculateModelResults()
1506                        IR2R_CalculateSLDProfile()
1507                        IR2R_GraphModelResults()               
1508                endif
1509        endif   
1510        DoWindow /F IR2R_ReflSimpleToolMainPanel
1511        setDataFolder OldDf
1512end
1513
1514//*****************************************************************************************************************
1515//*****************************************************************************************************************
1516//*****************************************************************************************************************
1517//*****************************************************************************************************************
1518//*****************************************************************************************************************
1519
1520Function IR2R_InputPanelCheckboxProc(ctrlName,checked) : CheckBoxControl
1521        String ctrlName
1522        Variable checked
1523
1524        string oldDf=GetDataFolder(1)
1525        setDataFolder root:Packages:Refl_SimpleTool
1526        variable tempVal
1527        string tempStr
1528       
1529        if (stringmatch(ctrlName,"Link*"))
1530                tempVal=str2num(ctrlName[18,inf])
1531                if(checked)
1532                        NVAR FitVar = $("root:Packages:Refl_SimpleTool:"+ReplaceString("Link", ctrlName, "Fit"))
1533                        NVAR VarValue = $("root:Packages:Refl_SimpleTool:"+ ReplaceString("Link", ctrlName, ""))
1534                        NVAR LinkToVar = $("root:Packages:Refl_SimpleTool:"+ReplaceString("Link", ctrlName, "LinkTo"))
1535                        NVAR LinkFracVar = $("root:Packages:Refl_SimpleTool:"+ReplaceString("Link", ctrlName, "LinkF"))
1536                        FitVar=0
1537                        if(LinkToVar>0 && LinkToVar!=tempVal)
1538                                //tempStr=ReplaceString("Link", ctrlName, "")
1539                                //print tempStr[0,13]
1540                                NVAR LinkedToVarValue = $("root:Packages:Refl_SimpleTool:"+ ReplaceString("Link", ctrlName, "")[0,13]+num2str(LinkToVar))
1541                                LinkFracVar = VarValue/LinkedToVarValue
1542                        endif
1543                endif
1544                IR2R_TabPanelControl("",tempVal-1)
1545                IR2R_UpdateLinkedVariables()
1546        endif
1547
1548        NVAR AutoUpdate=root:Packages:Refl_SimpleTool:AutoUpdate
1549        if ( (stringmatch(ctrlName,"Link*") || cmpstr(ctrlName,"AutoUpdate")==0 ||  cmpstr(ctrlName,"L1AtTheBottom")==0 ||  cmpstr(ctrlName,"ZeroAtTheSubstrate")==0 ) && AutoUpdate)
1550                IR2R_CalculateModelResults()
1551                IR2R_CalculateSLDProfile()
1552                IR2R_GraphModelResults()               
1553        endif
1554        if (cmpstr(ctrlName,"UseErrors")==0)
1555                Execute ("PopupMenu ErrorDataName, disable=!root:Packages:Refl_SimpleTool:UseErrors, win=IR2R_ReflSimpleToolMainPanel")
1556        endif
1557        if (cmpstr(ctrlName,"UseResolutionWave")==0)
1558                Execute ("PopupMenu ResolutionWaveName, disable=!root:Packages:Refl_SimpleTool:UseResolutionWave, win=IR2R_ReflSimpleToolMainPanel")
1559                Execute ("SetVariable Resolution, disable=root:Packages:Refl_SimpleTool:UseResolutionWave, win=IR2R_ReflSimpleToolMainPanel")
1560        endif
1561
1562        if (cmpstr(ctrlName,"ZeroAtTheSubstrate")==0)
1563                DoWindow IR2R_SLDProfile
1564                if(V_Flag)
1565                        NVAR ZeroAtTheSubstrate=root:Packages:Refl_SimpleTool:ZeroAtTheSubstrate
1566                        DoWindow/F IR2R_SLDProfile
1567                        if(ZeroAtTheSubstrate)
1568                                Label bottom "<<--Substrate                                               Layer thickness [A]                                         Top -->>"
1569                                DoWindow/T IR2R_SLDProfile,"SLD profile (substrate=left,  top=right) "
1570                        else
1571                                Label bottom "<<--TOP                                               Layer thickness [A]                                         Substrate -->>"
1572                                DoWindow/T IR2R_SLDProfile,"SLD profile (top=left, substrate=right) "
1573                        endif
1574                        IR2R_CalculateSLDProfile()
1575                endif
1576        endif
1577        if ((stringmatch(ctrlName,"Fit*"))&& !StringMatch(ctrlName, "*Background*" ) && !StringMatch(ctrlName,"*Roughness_Bot*") && !StringMatch(ctrlName,"*ScalingFactor*"))
1578                if(checked )
1579                        NVAR LinkVar = $("root:Packages:Refl_SimpleTool:"+ReplaceString("Fit", ctrlName, "Link"))
1580                        LinkVar=0
1581                endif
1582                tempVal=str2num(ctrlName[17,inf])
1583                IR2R_TabPanelControl("",tempVal-1)
1584        endif
1585
1586
1587        NVAR UseGeneticOptimization=root:Packages:Refl_SimpleTool:UseGenOpt
1588        NVAR UseLSQF=root:Packages:Refl_SimpleTool:UseLSQF
1589        if (stringMatch(ctrlName,"UseGenOpt"))
1590                UseGeneticOptimization=1
1591                UseLSQF=0
1592        endif
1593        if (stringMatch(ctrlName,"UseLSQF"))
1594                UseLSQF=1
1595                UseGeneticOptimization=0
1596        endif
1597        DoWindow /F IR2R_ReflSimpleToolMainPanel       
1598        setDataFolder OldDf
1599end
1600///******************************************************************************************
1601///******************************************************************************************
1602///******************************************************************************************
1603
1604Function IR2R_PanelPopupControl(ctrlName,popNum,popStr) : PopupMenuControl
1605        String ctrlName
1606        Variable popNum
1607        String popStr
1608
1609        string oldDf=GetDataFolder(1)
1610        setDataFolder root:Packages:Refl_SimpleTool
1611       
1612        NVAR ActiveTab=root:Packages:Refl_SimpleTool:ActiveTab
1613        NVAR NumberOfLayers=root:Packages:Refl_SimpleTool:NumberOfLayers
1614        ControlInfo /W=IR2R_ReflSimpleToolMainPanel DistTabs
1615        ActiveTab = V_value
1616
1617        if (cmpstr(ctrlName,"NumberOfLevels")==0)
1618                NumberOfLayers=str2num(popStr)
1619                if (NumberOfLayers<ActiveTab)
1620                        ActiveTab=0
1621                        //IR2R_TabPanelControl("",ActiveTab)
1622                        Execute("TabControl DistTabs,value= 0, win=IR2R_ReflSimpleToolMainPanel")
1623                endif
1624                IR2R_CalculateModelResults()
1625                IR2R_CalculateSLDProfile()
1626                IR2R_GraphModelResults()               
1627                IR2R_TabPanelControl("",ActiveTab)
1628        endif
1629       
1630        if (cmpstr(ctrlName,"FitIQN")==0)
1631                NVAR FitIQN=root:Packages:Refl_SimpleTool:FitIQN
1632                FitIQN = str2num(popStr)       
1633                Wave/Z OInt=root:Packages:Refl_SimpleTool:OriginalIntensity
1634                Wave/Z OQvec=root:Packages:Refl_SimpleTool:OriginalQvector
1635                Wave/Z OErr=root:Packages:Refl_SimpleTool:OriginalError
1636                Wave/Z NInt=root:Packages:Refl_SimpleTool:IntensityQN
1637                Wave/Z NQvec=root:Packages:Refl_SimpleTool:QvectorToN
1638                Wave/Z NErr=root:Packages:Refl_SimpleTool:ErrorQN
1639                if(WaveExists(OInt) &&WaveExists(OQvec) &&WaveExists(NInt) &&WaveExists(NQvec) )
1640                        NInt= OInt * OQvec^FitIQN
1641                endif
1642                if(WaveExists(OErr) &&WaveExists(OQvec) &&WaveExists(NErr) &&WaveExists(NQvec) )
1643                        NErr = OErr * OQvec^FitIQN
1644                endif
1645                IR2R_CalculateModelResults()
1646                IR2R_CalculateSLDProfile()
1647                IR2R_GraphModelResults()               
1648        endif
1649
1650        if (cmpstr(ctrlName,"ResolutionType")==0)
1651                NVAR UseResolutionWave=root:Packages:Refl_SimpleTool:UseResolutionWave
1652                UseResolutionWave = popNum-1
1653                Execute ("PopupMenu ResolutionWaveName, disable=!root:Packages:Refl_SimpleTool:UseResolutionWave, win=IR2R_ReflSimpleToolMainPanel")
1654                Execute ("SetVariable Resolution, disable=root:Packages:Refl_SimpleTool:UseResolutionWave, win=IR2R_ReflSimpleToolMainPanel")
1655        endif
1656
1657        if (cmpstr(ctrlName,"ResolutionWaveName")==0)
1658                SVAR ResolutionWaveName=root:Packages:Refl_SimpleTool:ResolutionWaveName
1659                if(stringmatch("Create From Parameters",popStr))
1660                        ResolutionWaveName="CreatedFromParamaters"
1661                        IR2R_CreateResolutionWave()
1662                else
1663                        ResolutionWaveName=possiblyQUoteName(popstr)
1664                endif
1665        endif
1666        if (stringmatch(ctrlName,"LinkToThicknessLayer*"))
1667                NVAR LinkToThicknessLayer=$("root:Packages:Refl_SimpleTool:"+ctrlName)
1668                LinkToThicknessLayer = str2num(popStr)
1669                NVAR VarValue = $("root:Packages:Refl_SimpleTool:"+ ReplaceString("LinkTo", ctrlName, ""))
1670                NVAR LinkToVar = $("root:Packages:Refl_SimpleTool:"+ctrlName)
1671                NVAR LinkFracVar = $("root:Packages:Refl_SimpleTool:"+ReplaceString("LinkTo", ctrlName, "LinkF"))
1672                if(LinkToVar>0)
1673                        NVAR LinkedToVarValue = $("root:Packages:Refl_SimpleTool:"+ ReplaceString("LinkTo", ctrlName, "")[0,13]+num2str(LinkToVar))
1674                        LinkFracVar = VarValue/LinkedToVarValue
1675                endif
1676                IR2R_UpdateLinkedVariables()
1677        endif
1678        if (stringmatch(ctrlName,"LinkToSLD_Real_Layer*"))
1679                NVAR LinkToThicknessLayer=$("root:Packages:Refl_SimpleTool:"+ctrlName)
1680                LinkToThicknessLayer = str2num(popStr)
1681                NVAR VarValue = $("root:Packages:Refl_SimpleTool:"+ ReplaceString("LinkTo", ctrlName, ""))
1682                NVAR LinkToVar = $("root:Packages:Refl_SimpleTool:"+ctrlName)
1683                NVAR LinkFracVar = $("root:Packages:Refl_SimpleTool:"+ReplaceString("LinkTo", ctrlName, "LinkF"))
1684                if(LinkToVar>0)
1685                        NVAR LinkedToVarValue = $("root:Packages:Refl_SimpleTool:"+ ReplaceString("LinkTo", ctrlName, "")[0,13]+num2str(LinkToVar))
1686                        LinkFracVar = VarValue/LinkedToVarValue
1687                endif
1688                IR2R_UpdateLinkedVariables()
1689        endif
1690        if (stringmatch(ctrlName,"LinkToSLD_Imag_Layer*"))
1691                NVAR LinkToThicknessLayer=$("root:Packages:Refl_SimpleTool:"+ctrlName)
1692                LinkToThicknessLayer = str2num(popStr)
1693                NVAR VarValue = $("root:Packages:Refl_SimpleTool:"+ ReplaceString("LinkTo", ctrlName, ""))
1694                NVAR LinkToVar = $("root:Packages:Refl_SimpleTool:"+ctrlName)
1695                NVAR LinkFracVar = $("root:Packages:Refl_SimpleTool:"+ReplaceString("LinkTo", ctrlName, "LinkF"))
1696                if(LinkToVar>0)
1697                        NVAR LinkedToVarValue = $("root:Packages:Refl_SimpleTool:"+ ReplaceString("LinkTo", ctrlName, "")[0,13]+num2str(LinkToVar))
1698                        LinkFracVar = VarValue/LinkedToVarValue
1699                endif
1700                IR2R_UpdateLinkedVariables()
1701        endif
1702        if (stringmatch(ctrlName,"LinkToRoughnessLayer*"))
1703                NVAR LinkToThicknessLayer=$("root:Packages:Refl_SimpleTool:"+ctrlName)
1704                LinkToThicknessLayer = str2num(popStr)
1705                NVAR VarValue = $("root:Packages:Refl_SimpleTool:"+ ReplaceString("LinkTo", ctrlName, ""))
1706                NVAR LinkToVar = $("root:Packages:Refl_SimpleTool:"+ctrlName)
1707                NVAR LinkFracVar = $("root:Packages:Refl_SimpleTool:"+ReplaceString("LinkTo", ctrlName, "LinkF"))
1708                if(LinkToVar>0)
1709                        NVAR LinkedToVarValue = $("root:Packages:Refl_SimpleTool:"+ ReplaceString("LinkTo", ctrlName, "")[0,13]+num2str(LinkToVar))
1710                        LinkFracVar = VarValue/LinkedToVarValue
1711                endif
1712                IR2R_UpdateLinkedVariables()
1713        endif
1714
1715        DoWindow/F IR2R_ReflSimpleToolMainPanel
1716        setDataFolder OldDf
1717
1718end
1719///******************************************************************************************
1720///******************************************************************************************
1721///******************************************************************************************
1722Function IR2R_TabPanelControl(name,tab)
1723        String name
1724        Variable tab
1725
1726        string oldDf=GetDataFolder(1)
1727        setDataFolder root:Packages:Refl_SimpleTool
1728       
1729        NVAR ActiveTab=root:Packages:Refl_SimpleTool:ActiveTab
1730        ActiveTab=tab+1
1731
1732        NVAR NumberOfLayers=root:Packages:Refl_SimpleTool:NumberOfLayers
1733        if (NumberOfLayers==0)
1734                ActiveTab=0
1735        endif
1736        //need to kill any outstanding windows for shapes... Any... All should have the same name...
1737        DoWindow/F IR2R_ReflSimpleToolMainPanel
1738        NVAR UseResolutionWave=root:Packages:Refl_SimpleTool:UseResolutionWave
1739        SetVariable Resolution, disable = UseResolutionWave
1740        PopupMenu ResolutionWaveName,disable=!UseResolutionWave
1741
1742        variable i, test1, test2, test3, test4
1743        For(i=1;i<=8;i+=1)
1744                //test1=(tab!=(i-1))
1745                //test2=((tab+1)>NumberOfLayers)
1746                NVAR FitTh=$("root:Packages:Refl_SimpleTool:FitThicknessLayer"+num2str(i))
1747                NVAR LinkTh=$("root:Packages:Refl_SimpleTool:LinkThicknessLayer"+num2str(i))
1748                NVAR FitRSLD=$("root:Packages:Refl_SimpleTool:FitSLD_Real_Layer"+num2str(i))
1749                NVAR LinkRSLD=$("root:Packages:Refl_SimpleTool:LinkSLD_Real_Layer"+num2str(i))
1750                NVAR FitISLD=$("root:Packages:Refl_SimpleTool:FitSLD_Imag_Layer"+num2str(i))
1751                NVAR LinkISLD=$("root:Packages:Refl_SimpleTool:LinkSLD_Imag_Layer"+num2str(i))
1752                NVAR FitROUGH=$("root:Packages:Refl_SimpleTool:FitRoughnessLayer"+num2str(i))
1753                NVAR LinkROUGH=$("root:Packages:Refl_SimpleTool:LinkRoughnessLayer"+num2str(i))
1754                //fix the parameters here...
1755                if(FitTh)
1756                        LinkTh=0
1757                endif
1758                if(linkTh)
1759                        FitTh=0
1760                endif
1761                if(FitRSLD)
1762                        LinkRSLD=0
1763                endif
1764                if(linkRSLD)
1765                        FitRSLD=0
1766                endif
1767                if(FitISLD)
1768                        LinkISLD=0
1769                endif
1770                if(linkISLD)
1771                        FitISLD=0
1772                endif
1773                if(FitROUGH)
1774                        LinkROUGH=0
1775                endif
1776                if(linkROUGH)
1777                        FitROUGH=0
1778                endif
1779                if((tab!=(i-1) || (tab+1)>NumberOfLayers))
1780                        test4 =1
1781                else
1782                        test4=0
1783                endif
1784                if(!test4 && LinkTh)
1785                        test3 =2
1786                else
1787                        test3 =test4
1788                endif
1789
1790                //Execute("TitleBox LayerTitleBox"+num2str(i)+",disable = "+num2str(tab!=(i-1) || (tab+1)>NumberOfLayers))
1791                Execute("TitleBox LayerTitleBox"+num2str(i)+",disable = "+num2str(test4))
1792
1793                Execute("SetVariable ThicknessLayer"+num2str(i)+",disable = "+num2str(test3))
1794                Execute("Slider ThicknessLayerSL"+num2str(i)+",disable = "+num2str(test3))
1795                Execute("SetVariable ThicknessLayerStep"+num2str(i)+",disable = "+num2str(test3))
1796                Execute("CheckBox FitThicknessLayer"+num2str(i)+",disable = "+num2str(test4))
1797                Execute("SetVariable ThicknessLayerLL"+num2str(i)+",disable = "+num2str(test4 || !FitTh))
1798                Execute("SetVariable ThicknessLayerUL"+num2str(i)+",disable = "+num2str(test4 || !FitTh))
1799                Execute("CheckBox LinkThicknessLayer"+num2str(i)+",disable = "+num2str(test4))
1800                NVAR LinkMeTo= $("root:Packages:Refl_SimpleTool:LinkToThicknessLayer"+num2str(i))
1801                Execute("PopupMenu LinkToThicknessLayer"+num2str(i)+",disable = "+num2str(test4 || !LinkTh)+", popmatch = \""+num2str(LinkMeTo)+"\"")
1802                Execute("SetVariable LinkFThicknessLayer"+num2str(i)+",disable = "+num2str(test4 || !LinkTh))
1803
1804                if(!test4 && LinkRSLD)
1805                        test3 =2
1806                else
1807                        test3 =test4
1808                endif
1809                Execute("SetVariable SLD_Real_Layer"+num2str(i)+",disable = "+num2str(test3))
1810                Execute("Slider SLD_Real_LayerSL"+num2str(i)+",disable = "+num2str(test3))
1811                Execute("SetVariable SLD_Real_LayerStep"+num2str(i)+",disable = "+num2str(test3))
1812                Execute("CheckBox FitSLD_Real_Layer"+num2str(i)+",disable = "+num2str(test4))
1813                Execute("SetVariable SLD_Real_LayerLL"+num2str(i)+",disable = "+num2str(test4 || !FitRSLD))
1814                Execute("SetVariable SLD_Real_LayerUL"+num2str(i)+",disable = "+num2str(test4 || !FitRSLD))
1815                Execute("CheckBox LinkSLD_Real_Layer"+num2str(i)+",disable = "+num2str(test4))
1816                NVAR LinkMeTo= $("root:Packages:Refl_SimpleTool:LinkToSLD_Real_Layer"+num2str(i))
1817                Execute("PopupMenu LinkToSLD_Real_Layer"+num2str(i)+",disable = "+num2str(test4 || !LinkRSLD)+", popmatch = \""+num2str(LinkMeTo)+"\"")
1818                Execute("SetVariable LinkFSLD_Real_Layer"+num2str(i)+",disable = "+num2str(test4 || !LinkRSLD))
1819
1820                if(!test4 && LinkISLD)
1821                        test3 =2
1822                else
1823                        test3 =test4
1824                endif
1825                Execute("SetVariable SLD_Imag_Layer"+num2str(i)+",disable = "+num2str(test3))
1826                Execute("Slider SLD_Imag_LayerSL"+num2str(i)+",disable = "+num2str(test3))
1827                Execute("SetVariable SLD_Imag_LayerStep"+num2str(i)+",disable = "+num2str(test3))
1828                Execute("CheckBox FitSLD_Imag_Layer"+num2str(i)+",disable = "+num2str(test4))
1829                Execute("SetVariable SLD_Imag_LayerLL"+num2str(i)+",disable = "+num2str(test4 || !FitISLD))
1830                Execute("SetVariable SLD_Imag_LayerUL"+num2str(i)+",disable = "+num2str(test4 || !FitISLD))
1831                Execute("CheckBox LinkSLD_Imag_Layer"+num2str(i)+",disable = "+num2str(test4))
1832                NVAR LinkMeTo= $("root:Packages:Refl_SimpleTool:LinkToSLD_Imag_Layer"+num2str(i))
1833                Execute("PopupMenu LinkToSLD_Imag_Layer"+num2str(i)+",disable = "+num2str(test4 || !LinkISLD)+", popmatch = \""+num2str(LinkMeTo)+"\"")
1834                Execute("SetVariable LinkFSLD_Imag_Layer"+num2str(i)+",disable = "+num2str(test4 || !LinkISLD))
1835
1836                if(!test4 && LinkROUGH)
1837                        test3 =2
1838                else
1839                        test3 =test4
1840                endif
1841                Execute("SetVariable RoughnessLayer"+num2str(i)+",disable = "+num2str(test3))
1842                Execute("Slider RoughnessLayerSL"+num2str(i)+",disable = "+num2str(test3))
1843                Execute("SetVariable RoughnessLayerStep"+num2str(i)+",disable = "+num2str(test3))
1844                Execute("CheckBox FitRoughnessLayer"+num2str(i)+",disable = "+num2str(test4))
1845                Execute("SetVariable RoughnessLayerLL"+num2str(i)+",disable = "+num2str(test4 || !FitROUGH))
1846                Execute("SetVariable RoughnessLayerUL"+num2str(i)+",disable = "+num2str(test4 || !FitROUGH))
1847                Execute("CheckBox LinkRoughnessLayer"+num2str(i)+",disable = "+num2str(test4))
1848                NVAR LinkMeTo= $("root:Packages:Refl_SimpleTool:LinkToRoughnessLayer"+num2str(i))
1849                Execute("PopupMenu LinkToRoughnessLayer"+num2str(i)+",disable = "+num2str(test4 || !linkROUGH)+", popmatch = \""+num2str(LinkMeTo)+"\"")
1850                Execute("SetVariable LinkFRoughnessLayer"+num2str(i)+",disable = "+num2str(test4 || !linkROUGH))
1851
1852
1853        endfor
1854
1855end
1856///******************************************************************************************
1857///******************************************************************************************
1858///******************************************************************************************
1859
1860Function IR2R_InputPanelButtonProc(ctrlName) : ButtonControl
1861        String ctrlName
1862
1863        string oldDf=GetDataFolder(1)
1864        setDataFolder root:Packages:Refl_SimpleTool
1865       
1866
1867        if (cmpstr(ctrlName,"DrawGraphs")==0)
1868                //here goes what is done, when user pushes Graph button
1869                SVAR DFloc=root:Packages:Refl_SimpleTool:DataFolderName
1870                SVAR DFInt=root:Packages:Refl_SimpleTool:IntensityWaveName
1871                SVAR DFQ=root:Packages:Refl_SimpleTool:QWaveName
1872                SVAR DFE=root:Packages:Refl_SimpleTool:ErrorWaveName
1873                variable IsAllAllRight=1
1874                if (cmpstr(DFloc,"---")==0 || strlen(DFloc)==0)
1875                        IsAllAllRight=0
1876                endif
1877                if (cmpstr(DFInt,"---")==0 || strlen(DFInt)==0)
1878                        IsAllAllRight=0
1879                endif
1880                if (cmpstr(DFQ,"---")==0 || strlen(DFQ)==0)
1881                        IsAllAllRight=0
1882                endif
1883//              if (cmpstr(DFE,"---")==0 || strlen(DFE)==0)
1884//                      IsAllAllRight=0
1885//              endif
1886               
1887                if (IsAllAllRight)
1888                        variable recovered = IR2R_RecoverOldParameters()        //recovers old parameters and returns 1 if done so...
1889                        IR2R_GraphMeasuredData()
1890                        if (recovered)
1891                                IR2R_TabPanelControl("",0)
1892                                IR2R_CalculateModelResults()
1893                                IR2R_CalculateSLDProfile()
1894                                IR2R_GraphModelResults()
1895                        endif
1896                else
1897                        Abort "Data not selected properly"
1898                endif
1899        endif
1900
1901        if(cmpstr(ctrlName,"ReversFit")==0)
1902                //here we call the fitting routine
1903                IR2R_ResetParamsAfterBadFit()
1904                IR2R_CalculateModelResults()
1905                IR2R_CalculateSLDProfile()
1906                IR2R_GraphModelResults()
1907        endif
1908        if(cmpstr(ctrlName,"CalculateModel")==0)
1909                //here we graph the distribution
1910                IR2R_CalculateModelResults()
1911                IR2R_CalculateSLDProfile()
1912                IR2R_GraphModelResults()
1913        endif
1914        if(cmpstr(ctrlName,"Fitmodel")==0)
1915                //here we copy final data back to original data folder 
1916                IR2R_SimpleToolFit()            //fitting       
1917                IR2R_CalculateModelResults()
1918                IR2R_CalculateSLDProfile()
1919                IR2R_GraphModelResults()
1920        endif   
1921        if(cmpstr(ctrlName,"SaveDataBtn")==0)
1922                //here we copy final data back to original data folder          I       
1923                IR2R_SaveDataToFolder()
1924        endif
1925        if(cmpstr(ctrlName,"FixLimits")==0)
1926                //here we copy final data back to original data folder          I       
1927                IR2R_FixLimits()
1928        endif
1929        if(cmpstr(ctrlName,"ExportData")==0)
1930                //here we export ASCII form of the data
1931                IR2R_SaveASCII()
1932        endif
1933
1934        Dowindow /F IR2R_ReflSimpleToolMainPanel
1935
1936        if(cmpstr(ctrlName,"AddRemoveLayers")==0)
1937                IR2R_AddRemoveLayersFnct()
1938                DoWindow/F IR2R_InsertRemoveLayers
1939        endif
1940
1941//      DoWindow IR2R_InsertRemoveLayers
1942//      if(V_Flag)
1943//              DoWindow/F IR2R_InsertRemoveLayers
1944//      endif
1945        setDataFolder oldDF
1946end
1947///******************************************************************************************
1948///******************************************************************************************
1949static Function IR2R_FixLimits()
1950        string ListOfVariables="SLD_Real_Layer;SLD_Imag_Layer;ThicknessLayer;RoughnessLayer;"
1951        variable i, j
1952        string tempVarName
1953        For(i=1;i<=8;i+=1)
1954                For(j=0;j<ItemsInList(ListOfVariables);j+=1)
1955                        tempVarName = stringFromList(j, ListOfVariables)
1956                        NVAR ValueVar=$("root:Packages:Refl_SimpleTool:"+tempVarName+num2str(i))
1957                        NVAR ValueVarLL=$("root:Packages:Refl_SimpleTool:"+tempVarName+"LL"+num2str(i))
1958                        NVAR ValueVarUL=$("root:Packages:Refl_SimpleTool:"+tempVarName+"UL"+num2str(i))
1959                        ValueVarLL = ValueVar/2
1960                        ValueVarUL = ValueVar*2
1961                        Execute("Slider "+tempVarName+"SL"+num2str(i)+" limits={"+num2str(ValueVarLL)+","+num2str(ValueVarUL)+",0}")
1962                endfor
1963        endfor
1964        ListOfVariables="Background;Roughness_Bot;ScalingFactor;"
1965        For(j=0;j<ItemsInList(ListOfVariables);j+=1)
1966                        tempVarName = stringFromList(j, ListOfVariables)
1967                        NVAR ValueVar=$("root:Packages:Refl_SimpleTool:"+tempVarName)
1968                        NVAR ValueVarLL=$("root:Packages:Refl_SimpleTool:"+tempVarName+"LL")
1969                        NVAR ValueVarUL=$("root:Packages:Refl_SimpleTool:"+tempVarName+"UL")
1970                        ValueVarLL = ValueVar/2
1971                        ValueVarUL = ValueVar*2
1972        endfor
1973
1974end
1975///******************************************************************************************
1976///******************************************************************************************
1977///******************************************************************************************
1978///******************************************************************************************
1979///******************************************************************************************
1980///******************************************************************************************
1981///******************************************************************************************
1982
1983static Function IR2R_RecoverOldParameters()
1984       
1985        string OldDf=getDataFolder(1)
1986        setDataFolder root:Packages:Refl_SimpleTool
1987
1988//      NVAR SASBackground=root:Packages:FractalsModel:SASBackground
1989//      NVAR SASBackgroundError=root:Packages:FractalsModel:SASBackgroundError
1990        SVAR DataFolderName=root:Packages:Refl_SimpleTool:DataFolderName
1991       
1992
1993        variable DataExists=0,i
1994        string ListOfWaves=IN2G_CreateListOfItemsInFolder(DataFolderName, 2)
1995        string tempString, tmpNote
1996        if (stringmatch(ListOfWaves, "*ReflModel_*" ))
1997                string ListOfSolutions=""
1998                For(i=0;i<itemsInList(ListOfWaves);i+=1)
1999                        if (stringmatch(stringFromList(i,ListOfWaves),"*ReflModel_*"))
2000                                tempString=stringFromList(i,ListOfWaves)
2001                                Wave tempwv=$(DataFolderName+tempString)
2002                                tempString=stringByKey("UsersComment",note(tempwv),"=",";")
2003                                ListOfSolutions+=stringFromList(i,ListOfWaves)+"*  "+tempString+";"
2004                        endif
2005                endfor
2006                DataExists=1
2007                string ReturnSolution=""
2008                Prompt ReturnSolution, "Select solution to recover", popup,  ListOfSolutions+";Start fresh"
2009                DoPrompt "Previous solutions found, select one to recover", ReturnSolution
2010                if (V_Flag)
2011                        abort
2012                endif
2013        endif
2014
2015        if (DataExists==1 && cmpstr("Start fresh", ReturnSolution)!=0)
2016                ReturnSolution=ReturnSolution[0,strsearch(ReturnSolution, "*", 0 )-1]
2017                Wave/Z OldDistribution=$(DataFolderName+ReturnSolution)
2018
2019                string OldNote=note(OldDistribution)
2020                string tempStr
2021                for(i=0;i<ItemsInList(OldNote);i+=1)
2022                        tempStr=StringFromList(0,StringFromList(i,OldNote),"=")
2023                        if(stringMatch(tempStr,"ResolutionWaveName"))
2024                                SVAR/Z testStr=$(tempStr)
2025                                if(SVAR_Exists(testStr))
2026                                        testStr=(StringFromList(1,StringFromList(i,OldNote),"="))
2027                                endif
2028                        else
2029                                NVAR/Z testVal=$(tempStr)
2030                                if(NVAR_Exists(testVal))
2031                                        testVal=str2num(StringFromList(1,StringFromList(i,OldNote),"="))
2032                                endif
2033                        endif
2034                endfor
2035                //Now, fix displayed panel...
2036                DoWindow/F IR2R_ReflSimpleToolMainPanel
2037                NVAR UseResolutionWave=root:Packages:Refl_SimpleTool:UseResolutionWave
2038                SVAR ResolutionWaveName = root:Packages:Refl_SimpleTool:ResolutionWaveName
2039                SetVariable Resolution, disable = UseResolutionWave
2040                popupMenu ResolutionType, disable=0, mode=UseResolutionWave+1
2041                PopupMenu ResolutionWaveName,value= #"\"---;Create From Parameters;\"+IR2R_ResWavesList()"
2042                PopupMenu ResolutionWaveName,disable=!UseResolutionWave, popmatch=IN2G_RemoveExtraQuote(ResolutionWaveName,1,1)
2043                NVAR NumberOfLayers=root:Packages:Refl_SimpleTool:NumberOfLayers
2044                PopupMenu NumberOfLevels mode=NumberOfLayers+1
2045                TabControl DistTabs value=0
2046                IR2R_TabPanelControl("",0)
2047                return 1
2048        else
2049                return 0
2050        endif
2051        setDataFolder oldDF
2052end
2053
2054
2055///******************************************************************************************
2056///******************************************************************************************
2057///******************************************************************************************
2058///******************************************************************************************
2059///******************************************************************************************
2060///******************************************************************************************
2061
2062static Function IR2R_SaveASCII()
2063       
2064        string OldDf=getDataFolder(1)
2065        setDataFolder root:Packages:Refl_SimpleTool
2066
2067        string UsersComment="Reflectivity results from : "+date()+" "+time()
2068        Prompt  UsersComment, "Input comments to be included with exported data"
2069        string DataRecordStr="UsersComment="+UsersComment+";"
2070       
2071        string ListOfVariables
2072        string ListOfStrings
2073        variable i, j
2074
2075        ListOfStrings="DataFolderName;IntensityWaveName;QWavename;ErrorWaveName;ResolutionWaveName;"
2076
2077        for(i=0;i<itemsInList(ListOfStrings);i+=1)     
2078                SVAR testStr= $(stringFromList(i,ListOfStrings))
2079                DataRecordStr+=stringFromList(i,ListOfStrings)+"="+testStr+";"
2080        endfor         
2081       
2082        //here define the lists of variables and strings needed, separate names by ;...
2083       
2084        ListOfVariables="NumberOfLayers;ActiveTab;AutoUpdate;FitIQN;Resoln;UpdateAutomatically;ActiveTab;UseErrors;UseResolutionWave;"
2085        ListOfVariables+="SLD_Real_Top;SLD_Imag_Top;SLD_Real_Bot;SLD_Imag_Bot;"
2086        ListOfVariables+="Roughness_Bot;FitRoughness_Bot;Roughness_BotLL;Roughness_BotUL;Roughness_BotError;"
2087        ListOfVariables+="Background;BackgroundStep;FitBackground;BackgroundLL;BackgroundUL;BackgroundError;"
2088        ListOfVariables+="ScalingFactor;FitScalingFactor;ScalingFactorLL;ScalingFactorUL;ScalingFactorError;"
2089
2090       
2091        //and here we read them to the list
2092       
2093        for(i=0;i<itemsInList(ListOfVariables);i+=1)   
2094                NVAR test= $(stringFromList(i,ListOfVariables))
2095                DataRecordStr+=stringFromList(i,ListOfVariables)+"="+num2str(test)+";"
2096        endfor         
2097// create 8 x this following list:
2098        ListOfVariables="SLD_Real_Layer;SLD_Imag_Layer;ThicknessLayer;RoughnessLayer;"
2099        ListOfVariables+="SLD_Real_LayerError;SLD_Imag_LayerError;ThicknessLayerError;RoughnessLayerError;"
2100        ListOfVariables+="SLD_Real_LayerStep;SLD_Imag_LayerStep;ThicknessLayerStep;RoughnessLayerStep;"
2101        ListOfVariables+="SLD_Real_LayerLL;SLD_Imag_LayerLL;ThicknessLayerLL;RoughnessLayerLL;"
2102        ListOfVariables+="SLD_Real_LayerUL;SLD_Imag_LayerUL;ThicknessLayerUL;RoughnessLayerUL;"
2103        ListOfVariables+="FitSLD_Real_Layer;FitSLD_Imag_Layer;FitThicknessLayer;FitRoughnessLayer;"
2104        ListOfVariables+="LinkSLD_Real_Layer;LinkSLD_Imag_Layer;LinkThicknessLayer;LinkRoughnessLayer;"
2105        ListOfVariables+="LinkFSLD_Real_Layer;LinkFSLD_Imag_Layer;LinkFThicknessLayer;LinkFRoughnessLayer;"
2106        ListOfVariables+="LinkToSLD_Real_Layer;LinkToSLD_Imag_Layer;LinkToThicknessLayer;LinkToRoughnessLayer;"
2107        NVAR  NumberOfLayers
2108        if(NumberOfLayers<1)
2109        //      abort "Save data errors, Number of Layers <1, nothing to save.."
2110                DoALert 0, "Note: No layers used, stored only substrate and top layer values"
2111        endif
2112        for(j=1;j<=NumberOfLayers;j+=1)
2113                for(i=0;i<itemsInList(ListOfVariables);i+=1)   
2114                        NVAR test= $(stringFromList(i,ListOfVariables)+num2str(j))
2115                        DataRecordStr+=stringFromList(i,ListOfVariables)+num2str(j)+"="+num2str(test)+";"
2116                endfor         
2117        endfor
2118       
2119        wave/Z Reflectivity=root:Packages:Refl_SimpleTool:ModelIntensity
2120        wave/Z Qvec=root:Packages:Refl_SimpleTool:ModelQvector
2121        if(!WaveExists(Reflectivity) || !WaveExists(Qvec))
2122                abort "Save error, Reflectivity and Q wave do not exist"
2123        endif
2124       
2125        SVAR DataFolderName
2126        if(strlen(DataFolderName)<1)
2127                abort "Save data error, DataFolderName is not correct"
2128        endif
2129        variable TextWvLength=ItemsInList(DataRecordStr,";")
2130        make/O/T/N=(TextWvLength) Record_Of_All_Model_Parameters
2131        for(i=0;i<TextWvLength;i+=1)
2132                Record_Of_All_Model_Parameters[i]=stringFromList(i,DataRecordStr,";")
2133        endfor
2134       
2135        Duplicate /O Reflectivity, Reflectivity_Model
2136        Wave Reflectivity_Model
2137        Duplicate/O Qvec, Q_Reflectivity_Model
2138        Wave Q_Reflectivity_Model
2139        Save/G/M="\r\n"/W/I Record_Of_All_Model_Parameters, Q_Reflectivity_Model, Reflectivity_Model
2140       
2141        KilLWaves/Z Record_Of_All_Model_Parameters, Q_Reflectivity_Model, Reflectivity_Model
2142
2143        setDataFOlder OldDf
2144end
2145
2146///******************************************************************************************
2147///******************************************************************************************
2148///******************************************************************************************
2149
2150///******************************************************************************************
2151///******************************************************************************************
2152///******************************************************************************************
2153
2154static Function IR2R_SaveDataToFolder()
2155       
2156        string OldDf=getDataFolder(1)
2157        setDataFolder root:Packages:Refl_SimpleTool
2158
2159        string UsersComment="Reflectivity results from : "+date()+" "+time()
2160        Prompt  UsersComment, "Input comments to be included with stored data"
2161        DoPrompt "Correct comment for saved data", UsersComment
2162        if(V_Flag)
2163                abort
2164        endif
2165        string DataRecord="UsersComment="+UsersComment+";"
2166       
2167        string ListOfVariables
2168        string ListOfStrings
2169        variable i, j
2170
2171        ListOfStrings="DataFolderName;IntensityWaveName;QWavename;ErrorWaveName;ResolutionWaveName;"
2172
2173        for(i=0;i<itemsInList(ListOfStrings);i+=1)     
2174                SVAR testStr= $(stringFromList(i,ListOfStrings))
2175                DataRecord+=stringFromList(i,ListOfStrings)+"="+testStr+";"
2176        endfor         
2177       
2178        //here define the lists of variables and strings needed, separate names by ;...
2179       
2180        ListOfVariables="NumberOfLayers;ActiveTab;AutoUpdate;FitIQN;Resoln;UpdateAutomatically;ActiveTab;UseErrors;UseResolutionWave;"
2181        ListOfVariables+="SLD_Real_Top;SLD_Imag_Top;SLD_Real_Bot;SLD_Imag_Bot;"
2182        ListOfVariables+="Roughness_Bot;FitRoughness_Bot;Roughness_BotLL;Roughness_BotUL;Roughness_BotError;"
2183        ListOfVariables+="Background;BackgroundStep;FitBackground;BackgroundLL;BackgroundUL;BackgroundError;"
2184        ListOfVariables+="ScalingFactor;FitScalingFactor;ScalingFactorLL;ScalingFactorUL;ScalingFactorError;"
2185
2186       
2187        //and here we read them to the list
2188       
2189        for(i=0;i<itemsInList(ListOfVariables);i+=1)   
2190                NVAR test= $(stringFromList(i,ListOfVariables))
2191                DataRecord+=stringFromList(i,ListOfVariables)+"="+num2str(test)+";"
2192        endfor         
2193// create 8 x this following list:
2194        ListOfVariables="SLD_Real_Layer;SLD_Imag_Layer;ThicknessLayer;RoughnessLayer;"
2195        ListOfVariables+="SLD_Real_LayerError;SLD_Imag_LayerError;ThicknessLayerError;RoughnessLayerError;"
2196        ListOfVariables+="SLD_Real_LayerStep;SLD_Imag_LayerStep;ThicknessLayerStep;RoughnessLayerStep;"
2197        ListOfVariables+="SLD_Real_LayerLL;SLD_Imag_LayerLL;ThicknessLayerLL;RoughnessLayerLL;"
2198        ListOfVariables+="SLD_Real_LayerUL;SLD_Imag_LayerUL;ThicknessLayerUL;RoughnessLayerUL;"
2199        ListOfVariables+="FitSLD_Real_Layer;FitSLD_Imag_Layer;FitThicknessLayer;FitRoughnessLayer;"
2200        ListOfVariables+="LinkSLD_Real_Layer;LinkSLD_Imag_Layer;LinkThicknessLayer;LinkRoughnessLayer;"
2201        ListOfVariables+="LinkFSLD_Real_Layer;LinkFSLD_Imag_Layer;LinkFThicknessLayer;LinkFRoughnessLayer;"
2202        ListOfVariables+="LinkToSLD_Real_Layer;LinkToSLD_Imag_Layer;LinkToThicknessLayer;LinkToRoughnessLayer;"
2203        NVAR/Z  NumberOfLayers
2204        if(NumberOfLayers<1)
2205        //      abort "Save data error, Number of Layers <1 nothing to save..."
2206                DoAlert 0, "Note: No layers used, stored only top and substrate values"
2207        endif
2208        for(j=1;j<=NumberOfLayers;j+=1)
2209                for(i=0;i<itemsInList(ListOfVariables);i+=1)   
2210                        NVAR test= $(stringFromList(i,ListOfVariables)+num2str(j))
2211                        DataRecord+=stringFromList(i,ListOfVariables)+num2str(j)+"="+num2str(test)+";"
2212                endfor         
2213        endfor
2214       
2215        wave/Z Reflectivity=root:Packages:Refl_SimpleTool:ModelIntensity
2216        wave/Z Qvec=root:Packages:Refl_SimpleTool:ModelQvector
2217        if(!WaveExists(Reflectivity) || !WaveExists(Qvec))
2218                abort "Save error, Reflectivity and Q wave do not exist"
2219        endif
2220       
2221        wave/Z SLDProfile=root:Packages:Refl_SimpleTool:SLDProfile
2222        if(!WaveExists(SLDProfile))
2223                abort "Save error, SLDProfile wave does not exist"
2224        endif
2225
2226        SVAR DataFolderName
2227        if(strlen(DataFolderName)<1)
2228                abort "Save data error, DataFolderName is not correct"
2229        endif
2230        if(stringmatch(DataFolderName, "*root:Packages:*"))             //using Modeling tool
2231                string NewFldrName
2232                NewFldrName="ReflectivityModeling"
2233                Prompt NewFldrName, "Using model, need to create new folder for the results"
2234                DoPrompt "Type new Folder name for the results, will be in root: folder", NewFldrName
2235                if(V_Flag)
2236                        abort
2237                endif
2238                setDataFolder root:
2239                NewDataFOlder/O/S $(UniqueName((PossiblyQuoteName(NewFldrName)), 11, 0  ))
2240                DataFolderName = GetDataFolder(1)
2241        endif
2242       
2243        setDataFolder root:
2244        setDataFolder DataFolderName
2245        string NewIntName=UniqueName("ReflModel_", 1, 0)
2246        variable FoundIndex=str2num(stringFromList(1,NewIntName,"_"))
2247        string NewQwave="ReflQ_"+num2str(FoundIndex)
2248        string NewSLDProfileWave="SLDProfile_"+num2str(FoundIndex)
2249        string NewSLDProfileXWave="SLDProfileX_"+num2str(FoundIndex)
2250       
2251        Duplicate/O Reflectivity, $NewIntName
2252        Wave NewReflectivity=$(NewIntName)
2253        Duplicate/O Qvec, $NewQwave
2254        Wave NewQ=$(NewQwave)
2255        Duplicate/O SLDProfile, $NewSLDProfileWave
2256        Duplicate/O SLDProfile, $NewSLDProfileXWave
2257        Wave NewSLDProfile=$(NewSLDProfileWave)
2258        Wave NewSLDProfileX=$(NewSLDProfileXWave)
2259        NewSLDProfileX = leftx(NewSLDProfile )+deltax(NewSLDProfile )*p
2260        note/NOCR NewReflectivity, DataRecord
2261        note/NOCR NewQ, DataRecord
2262        note/NOCR NewSLDProfile, DataRecord
2263
2264        setDataFOlder OldDf
2265end
2266
2267///******************************************************************************************
2268///******************************************************************************************
2269///******************************************************************************************
2270static Function IR2R_CalculateModelResults()
2271        //this function calculates model data
2272//variable startTime=ticks
2273        variable i, j
2274        string OldDf=getDataFolder(1)
2275        setDataFolder root:Packages:Refl_SimpleTool
2276        IR2R_UpdateLinkedVariables()
2277       
2278        wave/Z OriginalQvector=root:Packages:Refl_SimpleTool:OriginalQvector
2279        if(!WaveExists(OriginalQvector))
2280                abort
2281        endif
2282
2283        //Need to create wave with parameters for Motofit_Imag here
2284        NVAR NumberOfLayers= root:Packages:Refl_SimpleTool:NumberOfLayers
2285        //need 8 parameters to start with - numLayers, scale, TopSLD_real, TopSLD_Imag, Bot_SLD_real, BotSLD_imag, Background, SubstareRoughness, and then 4 parameters for each layer
2286        // thickness, re_SLD, imag_SLD and roughness
2287        variable NumPointsNeeded= NumberOfLayers * 4 + 8
2288       
2289        make/O/D/N=(NumPointsNeeded) ParametersIn
2290        //now let's fill this in
2291        ParametersIn[0] = NumberOfLayers
2292        NVAR ScalingFactor=root:Packages:Refl_SimpleTool:ScalingFactor
2293        NVAR SLD_Real_Top=root:Packages:Refl_SimpleTool:SLD_Real_Top
2294        NVAR SLD_Imag_Top=root:Packages:Refl_SimpleTool:SLD_Imag_Top
2295        NVAR SLD_Real_Bot=root:Packages:Refl_SimpleTool:SLD_Real_Bot
2296        NVAR SLD_Imag_Bot=root:Packages:Refl_SimpleTool:SLD_Imag_Bot
2297        NVAR Background=root:Packages:Refl_SimpleTool:Background
2298        NVAR Roughness_Bot=root:Packages:Refl_SimpleTool:Roughness_Bot 
2299        NVAR L1AtTheBottom=root:Packages:Refl_SimpleTool:L1AtTheBottom
2300       
2301        ParametersIn[1] = ScalingFactor
2302        ParametersIn[2] = SLD_Real_Top//*1e-6
2303        ParametersIn[3] = SLD_Imag_Top*1e-6
2304        ParametersIn[4] = SLD_Real_Bot//*1e-6
2305        ParametersIn[5] = SLD_Imag_Bot*1e-6
2306        ParametersIn[6] = Background
2307        ParametersIn[7] = Roughness_Bot
2308
2309        //fix to allow L1 at the bottom...
2310        if(L1AtTheBottom)
2311                j=0
2312                for(i=NumberOfLayers;i>=1;i-=1)
2313                        j+=1
2314                        NVAR ThicknessLayer= $("root:Packages:Refl_SimpleTool:ThicknessLayer"+Num2str(i))
2315                        NVAR SLD_real_Layer = $("root:Packages:Refl_SimpleTool:SLD_Real_Layer"+Num2str(i))
2316                        NVAR SLD_imag_Layer = $("root:Packages:Refl_SimpleTool:SLD_Imag_Layer"+Num2str(i))
2317                        NVAR RoughnessLayer = $("root:Packages:Refl_SimpleTool:RoughnessLayer"+Num2str(i))
2318                        ParametersIn[7+(j-1)*4+1] =  ThicknessLayer
2319                        ParametersIn[7+(j-1)*4+2] =  SLD_real_Layer//*1e-6
2320                        ParametersIn[7+(j-1)*4+3] =  SLD_imag_Layer*1e-6
2321                        ParametersIn[7+(j-1)*4+4] =  RoughnessLayer
2322                endfor
2323        else
2324                for(i=1;i<=NumberOfLayers;i+=1)
2325                        NVAR ThicknessLayer= $("root:Packages:Refl_SimpleTool:ThicknessLayer"+Num2str(i))
2326                        NVAR SLD_real_Layer = $("root:Packages:Refl_SimpleTool:SLD_Real_Layer"+Num2str(i))
2327                        NVAR SLD_imag_Layer = $("root:Packages:Refl_SimpleTool:SLD_Imag_Layer"+Num2str(i))
2328                        NVAR RoughnessLayer = $("root:Packages:Refl_SimpleTool:RoughnessLayer"+Num2str(i))
2329                        ParametersIn[7+(i-1)*4+1] =  ThicknessLayer
2330                        ParametersIn[7+(i-1)*4+2] =  SLD_real_Layer//*1e-6
2331                        ParametersIn[7+(i-1)*4+3] =  SLD_imag_Layer*1e-6
2332                        ParametersIn[7+(i-1)*4+4] =  RoughnessLayer
2333                endfor
2334        endif
2335
2336        Duplicate/O OriginalQvector, ModelQvector, ModelIntensity
2337        NVAR Resoln=root:Packages:Refl_SimpleTool:Resoln
2338        NVAR UseResolutionWave=root:Packages:Refl_SimpleTool:UseResolutionWave
2339        SVAR ResolutionWaveName=root:Packages:Refl_SimpleTool:ResolutionWaveName
2340        SVAR DataFolderName=root:Packages:Refl_SimpleTool:DataFolderName
2341        Wave/Z ResolutionWave=$(DataFolderName+ResolutionWaveName)
2342        if(UseResolutionWave)   
2343                if(!WaveExists(ResolutionWave))
2344                        abort "Resolution wave does not exist"
2345                endif
2346                //ModelIntensity=IR2R_CalculateReflectivity(ParametersIn,ModelQvector,ResolutionWave)
2347                //ModelIntensity=Abeles_imagALl(ParametersIn,ModelQvector,ResolutionWave)
2348                //              Abeles_imagALl(w, RR, xtemp)
2349                IR2R_CalculateReflectivityNewRW(ParametersIn,ModelIntensity,ModelQvector,ResolutionWave)
2350        else//use resoln
2351                //ModelIntensity=IR2R_CalculateReflectivity(ParametersIn,ModelQvector,Resoln)
2352                IR2R_CalculateReflectivityNew(ParametersIn,ModelIntensity,ModelQvector,Resoln)
2353        endif
2354        Wave ModelIntensity=root:Packages:Refl_SimpleTool:ModelIntensity
2355        Wave ModelQvector=root:Packages:Refl_SimpleTool:ModelQvector
2356        NVAR FitIQN=root:Packages:Refl_SimpleTool:FitIQN
2357        Duplicate/O ModelIntensity, ModelIntensityQN
2358        Duplicate/O ModelQvector, ModelQvectorToN
2359        ModelIntensityQN = ModelIntensity * ModelQvectorToN^FitIQN
2360
2361        setDataFolder OldDf
2362//print (ticks-startTime)/60   
2363end
2364
2365///******************************************************************************************
2366///******************************************************************************************
2367///******************************************************************************************
2368///******************************************************************************************
2369///******************************************************************************************
2370static Function IR2R_GraphModelResults()
2371        //this function graphs model data
2372       
2373        string OldDf=getDataFolder(1)
2374        setDataFolder root:Packages:Refl_SimpleTool
2375        Wave/Z ModelIntensity=root:Packages:Refl_SimpleTool:ModelIntensity
2376        if(!WaveExists(ModelIntensity))
2377                abort   //no data to do anything
2378        endif
2379        Wave ModelQvector=root:Packages:Refl_SimpleTool:ModelQvector
2380        NVAR FitIQN=root:Packages:Refl_SimpleTool:FitIQN
2381        Duplicate/O ModelIntensity, ModelIntensityQN
2382        Duplicate/O ModelQvector, ModelQvectorToN
2383        ModelIntensityQN = ModelIntensity * ModelQvectorToN^FitIQN
2384
2385        DoWindow IR2R_LogLogPlotRefl
2386        if(V_Flag)
2387                DoWindow/F IR2R_LogLogPlotRefl
2388                CheckDisplayed /W=IR2R_LogLogPlotRefl ModelIntensity
2389                if(V_Flag!=1)
2390                        AppendToGraph/W=IR2R_LogLogPlotRefl ModelIntensity vs ModelQvector
2391                endif
2392                ModifyGraph rgb(ModelIntensity)=(0,0,0)
2393        endif
2394        DoWindow IR2R_IQN_Q_PlotV
2395        if(V_Flag)
2396                DoWindow/F IR2R_IQN_Q_PlotV
2397                CheckDisplayed /W=IR2R_IQN_Q_PlotV ModelIntensityQN
2398                if(V_Flag!=1)
2399                        AppendToGraph/W=IR2R_IQN_Q_PlotV ModelIntensityQN vs ModelQvectorToN
2400                endif
2401                ModifyGraph rgb(ModelIntensityQN)=(0,0,0)
2402        endif
2403        DoWindow IR2R_SLDProfile
2404        if(V_Flag)
2405                DoWindow/F IR2R_SLDProfile
2406        else
2407                Execute ("IR2R_SLDProfile()")
2408        endif
2409
2410        setDataFolder OldDf
2411end
2412
2413
2414///******************************************************************************************
2415///******************************************************************************************
2416///******************************************************************************************
2417///******************************************************************************************
2418///******************************************************************************************
2419
2420
2421static Function IR2R_SimpleToolFit()
2422
2423        string oldDf=GetDataFolder(1)
2424        setDataFolder root:Packages:Refl_SimpleTool
2425        //setup waves for fitting
2426        string ListOfVariables
2427        variable i, j, curLen, curLenConst
2428        //Each variable has Name, FitName, NameLL, NameUL, and for layers the name has index 1 to NumberOfLayers (up to 8)
2429        NVAR NumberOfLayers=root:Packages:Refl_SimpleTool:NumberOfLayers
2430        NVAR FitIQN=root:Packages:Refl_SimpleTool:FitIQN
2431        make/O/N=0/T CoefNames, T_Constraints
2432        Make/O/N=(0,2) Gen_Constraints
2433        make/O/D/N=0 W_coef
2434
2435        ListOfVariables="SLD_Real_LayerError;SLD_Imag_LayerError;ThicknessLayerError;RoughnessLayerError;"
2436        For(i=0;i<ItemsInList(ListOfVariables);i+=1)
2437                For(j=1;j<=8;j+=1)
2438                        NVAR Value = $("root:Packages:Refl_SimpleTool:"+StringFromList(i,ListOfVariables)+num2str(j))
2439                        Value=0
2440                endfor
2441        endfor
2442
2443
2444        ListOfVariables="Roughness_Bot;"//FitRoughness_Bot;Roughness_BotLL;Roughness_BotUL;"
2445        ListOfVariables+="Background;ScalingFactor;"//FitBackground;BackgroundLL;BackgroundUL;"
2446        T_Constraints=""
2447        CoefNames=""
2448
2449        For(i=0;i<ItemsInList(ListOfVariables);i+=1)
2450                NVAR CurValErr=$("root:Packages:Refl_SimpleTool:"+StringFromList(i,ListOfVariables)+"Error")
2451                NVAR FitMe=$("root:Packages:Refl_SimpleTool:Fit"+StringFromList(i,ListOfVariables))
2452                NVAR CurVal=$("root:Packages:Refl_SimpleTool:"+StringFromList(i,ListOfVariables))
2453                NVAR LLVal=$("root:Packages:Refl_SimpleTool:"+StringFromList(i,ListOfVariables)+"LL")
2454                NVAR ULVal=$("root:Packages:Refl_SimpleTool:"+StringFromList(i,ListOfVariables)+"UL")
2455                CurValErr=0
2456                curLen=numpnts(W_coef)
2457                curLenConst=numpnts(T_Constraints)
2458                if(FitMe)
2459                        if(LLVal>CurVal || ULVal<CurVal)
2460                                abort "Limits for "+ StringFromList(i,ListOfVariables)+"  set incorrectly"
2461                        endif
2462                        redimension/N=(curlen+1) CoefNames, W_coef
2463                        Redimension /N=((curlen+1),2) Gen_Constraints
2464                        redimension/N=(curLenConst+2) T_Constraints
2465                        W_coef[curLen] = CurVal
2466                        CoefNames[curLen] = StringFromList(i,ListOfVariables)
2467                        T_Constraints[curLenConst] = {"K"+num2str(curlen)+" > "+num2str(LLVal)}
2468                        T_Constraints[curLenConst+1] = {"K"+num2str(curlen)+" < "+num2str(ULVal)}
2469                        Gen_Constraints[curLen][0] = LLVal
2470                        Gen_Constraints[curLen][1] = ULVal
2471                endif
2472        endfor
2473       
2474// create 8 x this following list:
2475//      NVAR SLDinCm=root:Packages:Refl_SimpleTool:SLDinCm
2476//      NVAR SLDinA=root:Packages:Refl_SimpleTool:SLDinA
2477        variable tempThickKVal, tempRoughKVal
2478        string tempStr
2479        ListOfVariables="SLD_Real_Layer;SLD_Imag_Layer;ThicknessLayer;RoughnessLayer;"
2480        For(j=1;j<=NumberOfLayers;j+=1)
2481                tempThickKVal=0
2482                tempRoughKVal=0
2483                For(i=0;i<ItemsInList(ListOfVariables);i+=1)
2484                        tempStr = StringFromList(i,ListOfVariables)+num2str(j)
2485                        NVAR FitMe=$("root:Packages:Refl_SimpleTool:Fit"+StringFromList(i,ListOfVariables)+num2str(j))
2486                        NVAR CurVal=$("root:Packages:Refl_SimpleTool:"+StringFromList(i,ListOfVariables)+num2str(j))
2487                        NVAR LLVal=$("root:Packages:Refl_SimpleTool:"+StringFromList(i,ListOfVariables)+"LL"+num2str(j))
2488                        NVAR ULVal=$("root:Packages:Refl_SimpleTool:"+StringFromList(i,ListOfVariables)+"UL"+num2str(j))
2489                        curLen=numpnts(W_coef)
2490                        curLenConst=numpnts(T_Constraints)
2491                        if(FitMe)
2492                                if(LLVal>CurVal || ULVal<CurVal)
2493                                        abort "Limits for "+ StringFromList(i,ListOfVariables)+num2str(j)+"  set incorrectly"
2494                                endif
2495                                redimension/N=(curlen+1) CoefNames, W_coef
2496                                Redimension /N=((curlen+1),2) Gen_Constraints
2497                                redimension/N=(curLenConst+2) T_Constraints
2498                                        W_coef[curLen] = CurVal
2499                                        CoefNames[curLen] = StringFromList(i,ListOfVariables)+num2str(j)
2500                                        T_Constraints[curLenConst] = {"K"+num2str(curlen)+" > "+num2str(LLVal)}
2501                                        T_Constraints[curLenConst+1] = {"K"+num2str(curlen)+" < "+num2str(ULVal)}
2502                                        Gen_Constraints[curLen][0] = LLVal
2503                                        Gen_Constraints[curLen][1] = ULVal
2504                                if(StringMatch(tempStr, "ThicknessLayer*" ))
2505                                        tempThickKVal = curlen
2506                                endif
2507                                if(StringMatch(tempStr, "RoughnessLayer*" ))
2508                                        tempRoughKVal = curlen
2509                                endif
2510                        endif
2511                endfor
2512                if(tempThickKVal>0 && tempRoughKVal>0)
2513                        curLenConst=numpnts(T_Constraints)
2514                        redimension/N=(curLenConst+1) T_Constraints
2515                        curLenConst=numpnts(T_Constraints)
2516                        //roughness <thickness/2.38
2517                        T_Constraints[curLenConst-1] = {"K"+num2str(tempRoughKVal)+"<K"+num2str(tempThickKVal)+"/2.38"}
2518                endif
2519        endfor
2520        //Now let's check if we have what to fit at all...
2521        if (numpnts(CoefNames)==0)
2522                beep
2523                Abort "Select parameters to fit and set their fitting limits"
2524        endif
2525        IR2R_SetErrorsToZero()
2526       
2527        DoWindow /F IR2R_LogLogPlotRefl
2528        Wave OriginalQvector
2529        Wave OriginalIntensity
2530        Wave OriginalError     
2531        NVAR FitIQN=root:Packages:Refl_SimpleTool:FitIQN       
2532        NVAR UseErrors=root:Packages:Refl_SimpleTool:UseErrors
2533       
2534        Variable V_chisq
2535        Duplicate/O W_Coef, E_wave, CoefficientInput
2536        E_wave=W_coef/20
2537
2538        NVAR/Z UseLSQF = root:Packages:Refl_SimpleTool:UseLSQF
2539        NVAR/Z UseGenOpt = root:Packages:Refl_SimpleTool:UseGenOpt
2540        if(!NVAR_Exists(UseGenOpt)||!NVAR_Exists(UseLSQF))
2541                variable/g UseGenOpt
2542                variable/g UseLSQF
2543                UseLSQF=1
2544                UseGenOpt=0
2545        endif
2546        string HoldStr=""
2547        For(i=0;i<numpnts(W_Coef);i+=1)
2548                HoldStr+="0"
2549        endfor
2550        if(UseGenOpt)   //check the limits, for GenOpt the ratio between min and max should not be too high
2551                IR2R_CheckFittingParamsFnct()
2552                PauseForUser IR2R_CheckFittingParams
2553                NVAR UserCanceled=root:Packages:Refl_SimpleTool:UserCanceled
2554                if (UserCanceled)
2555                        setDataFolder OldDf
2556                        abort
2557                endif
2558               
2559        endif
2560
2561
2562                ////    IR1A_RecordResults("before")
2563
2564        Variable V_FitError=0                   //This should prevent errors from being generated
2565        variable temp
2566       
2567        NVAR Resoln=root:Packages:Refl_SimpleTool:Resoln
2568        NVAR UseResolutionWave=root:Packages:Refl_SimpleTool:UseResolutionWave
2569        SVAR ResolutionWaveName=root:Packages:Refl_SimpleTool:ResolutionWaveName
2570        SVAR DataFolderName=root:Packages:Refl_SimpleTool:DataFolderName
2571        Wave/Z ResolutionWave=$(DataFolderName+ResolutionWaveName)
2572                if(!WaveExists(ResolutionWave) && UseResolutionWave)
2573                        abort "Resolution wave does not exist"
2574                endif
2575        //remember, to allow user not to have errors, if they are not provided we create them and set them to 0...
2576        //and now the fit...
2577
2578        Print "Reflectivity Optimization fit started at: "+ time()
2579        DoWIndow UserOptimizationWidnow
2580        if(V_Flag)
2581                DoWIndow/F UserOptimizationWidnow
2582        else
2583                UserOptimizationWidnowP()
2584                DoUpdate/W=UserOptimizationWidnow
2585        endif
2586        //Print "NOTE: The optimization is running even though there may be no indication in the screen. Be patient... "
2587        variable startTicks=ticks
2588        if (strlen(csrWave(A))!=0 && strlen(csrWave(B))!=0)             //cursors in the graph
2589                //check that the cursors are on the right wave or get them set to the right wave
2590                if(cmpstr(CsrWave(A),"OriginalIntensity")!=0)
2591                        temp = CsrXWaveRef(A)[xcsr(A)]
2592                        cursor A OriginalIntensity binarysearch(OriginalQvector,temp)
2593                endif
2594                if(cmpstr(CsrWave(B),"OriginalIntensity")!=0)
2595                        temp = CsrXWaveRef(B)[xcsr(B)]
2596                        cursor B OriginalIntensity binarysearch(OriginalQvector,temp)
2597                endif
2598               
2599                Duplicate/O/R=[pcsr(A),pcsr(B)] OriginalIntensity, FitIntensityWave, ErrorFractionWave, tempFitWv               
2600                Duplicate/O/R=[pcsr(A),pcsr(B)] OriginalQvector, FitQvectorWave
2601                Duplicate/O/R=[pcsr(A),pcsr(B)] OriginalError, FitErrorWave
2602                tempFitWv=NaN
2603                if(UseResolutionWave)
2604                        Duplicate/O/R=[pcsr(A),pcsr(B)] ResolutionWave, FitResolutionWave       
2605                endif
2606                ErrorFractionWave = FitErrorWave / FitIntensityWave
2607                FitIntensityWave = FitIntensityWave * FitQvectorWave^FitIQN
2608                FitErrorWave = FitIntensityWave * ErrorFractionWave
2609                if(sum(FitErrorWave)==0 || !UseErrors)  //no errors to use...
2610                        if(UseLSQF)
2611                                FuncFit /N/Q IR2R_ST_FitFunction W_coef FitIntensityWave /X=FitQvectorWave /E=E_wave  /C=T_Constraints
2612                        else
2613                                Duplicate/O FitIntensityWave, GenMaskWv
2614                                GenMaskWv=1
2615#if Exists("gencurvefit")
2616                gencurvefit  /M=GenMaskWv/MAT=0/N/D=tempFitWv /TOL=0.05 /K={50,20,0.7,0.5} /X=FitQvectorWave IR2R_ST_FitFunction, FitIntensityWave  , W_Coef, HoldStr, Gen_Constraints         
2617#else
2618                Abort  "Genetic Optimization xop NOT installed. Install xop support and then try again"
2619#endif
2620                        endif
2621                else            //have errorrs
2622                        if(UseLSQF)
2623                                FuncFit /N/Q IR2R_ST_FitFunction W_coef FitIntensityWave /X=FitQvectorWave /W=FitErrorWave /I=1/E=E_wave /C=T_Constraints
2624                        else
2625                                Duplicate/O FitIntensityWave, GenMaskWv
2626                                GenMaskWv=1
2627#if Exists("gencurvefit")
2628                //gencurvefit  /I=1 /W=FitErrorWave /M=GenMaskWv /N /TOL=0.001 /K={50,20,0.7,0.5} /X=FitQvectorWave IR2R_ST_FitFunction, FitIntensityWave  , W_Coef, HoldStr, Gen_Constraints   
2629                gencurvefit  /I=1/MAT=0/N /W=FitErrorWave/D=tempFitWv /M=GenMaskWv /TOL=0.05 /K={50,20,0.7,0.5} /X=FitQvectorWave IR2R_ST_FitFunction, FitIntensityWave  , W_Coef, HoldStr, Gen_Constraints     
2630#else
2631                Abort "Genetic Optimization xop NOT installed. Install xop support and then try again"
2632#endif
2633                        endif
2634                endif
2635        else            //no cursors used....
2636                Duplicate/O OriginalIntensity, FitIntensityWave, ErrorFractionWave, tempFitWv   
2637                Duplicate/O OriginalQvector, FitQvectorWave
2638                Duplicate/O OriginalError, FitErrorWave
2639                tempFitWv=NaN
2640                if(UseResolutionWave)
2641                        Duplicate/O ResolutionWave, FitResolutionWave   
2642                endif
2643                ErrorFractionWave = FitErrorWave / FitIntensityWave
2644                FitIntensityWave = FitIntensityWave * FitQvectorWave^FitIQN
2645                FitErrorWave = FitIntensityWave * ErrorFractionWave
2646                if(sum(FitErrorWave)==0 || !UseErrors)  //no errors to use...
2647                        if(UseLSQF)
2648                                FuncFit /N/Q IR2R_ST_FitFunction W_coef FitIntensityWave /X=FitQvectorWave /E=E_wave /C=T_Constraints   
2649                        else
2650                                Duplicate/O FitIntensityWave, GenMaskWv
2651                                GenMaskWv=1
2652#if Exists("gencurvefit")
2653                gencurvefit  /M=GenMaskWv/MAT=0/N/D=tempFitWv /TOL=0.05 /K={50,20,0.7,0.5} /X=FitQvectorWave IR2R_ST_FitFunction, FitIntensityWave  , W_Coef, HoldStr, Gen_Constraints         
2654#else
2655                Abort  "Genetic Optimization xop NOT installed. Install xop support and then try again"
2656#endif
2657                        endif
2658                else            //have errors
2659                        if(UseLSQF)
2660                                FuncFit /N/Q IR2R_ST_FitFunction W_coef FitIntensityWave /X=FitQvectorWave /W=FitErrorWave /I=1 /E=E_wave /C=T_Constraints     
2661                        else
2662                                Duplicate/O FitIntensityWave, GenMaskWv
2663                                GenMaskWv=1
2664#if Exists("gencurvefit")
2665                gencurvefit  /I=1 /W=FitErrorWave/MAT=0/Q/N/D=tempFitWv /M=GenMaskWv /TOL=0.05 /K={50,20,0.7,0.5} /X=FitQvectorWave IR2R_ST_FitFunction, FitIntensityWave  , W_Coef, HoldStr, Gen_Constraints   
2666#else
2667                Abort  "Genetic Optimization xop NOT installed. Install xop support and then try again"
2668#endif
2669                        endif
2670                endif
2671        endif
2672        Print "Optimization fit ended at: \t"+ time()+"\tafter\t"+num2str((ticks-startTicks)/60)+" [s]"
2673        DoWIndow UserOptimizationWidnow
2674        if(V_Flag)
2675                DoWIndow/K UserOptimizationWidnow
2676        endif
2677        if (V_FitError!=0)      //there was error in fitting
2678                IR2R_ResetParamsAfterBadFit()
2679                beep
2680                Abort "Fitting error, check starting parameters and fitting limits"
2681        else
2682                Wave W_sigma = root:Packages:Refl_SimpleTool:W_sigma
2683                SVAR Dataname=root:Packages:Refl_SimpleTool:DataFolderName
2684                Print "________________________________"
2685                Print "Achieved results of optimization"
2686                Print "   "
2687                Print "Data fitted : "+Dataname
2688                Print "   "
2689                For(i=0;i<numpnts(W_coef);i+=1)
2690                        NVAR testVal=$(CoefNames[i])
2691                        testVal=W_coef[i]
2692                        if(stringMatch("Roughness_Bot;Background;ScalingFactor;", "*"+CoefNames[i]+"*"))
2693                                //print "root:Packages:Refl_SimpleTool:"+CoefNames[i]+"Error"
2694                                NVAR testValError=$("root:Packages:Refl_SimpleTool:"+CoefNames[i]+"Error")
2695                        else
2696                                //print "root:Packages:Refl_SimpleTool:"+(CoefNames[i])[0,strlen(CoefNames[i])-2]+"Error"+(CoefNames[i])[strlen(CoefNames[i])-1,inf]
2697                                NVAR testValError=$("root:Packages:Refl_SimpleTool:"+(CoefNames[i])[0,strlen(CoefNames[i])-2]+"Error"+(CoefNames[i])[strlen(CoefNames[i])-1,inf])
2698                        endif
2699                        testValError = W_sigma[i]
2700                        print CoefNames[i]+"\t=\t"+num2str(W_coef[i])+"\t+/-\t"+ num2str(W_sigma[i])
2701                endfor 
2702                Print "________________________________"
2703                Print "   "
2704        endif
2705        variable/g AchievedChisq=V_chisq
2706        //here we graph the distribution
2707        IR2R_CalculateModelResults()
2708        IR2R_CalculateSLDProfile()
2709        IR2R_GraphModelResults()
2710        KillWaves/Z ErrorFractionWave   
2711        setDataFolder OldDf
2712end
2713///******************************************************************************************
2714///******************************************************************************************
2715Function UserOptimizationWidnowP() : Panel
2716        PauseUpdate; Silent 1           // building window...
2717        NewPanel /W=(352,245,806,366) as "Optimization in Progress"
2718        DoWindow/C UserOptimizationWidnow
2719        SetDrawLayer UserBack
2720        SetDrawEnv fillfgc= (65535,0,0)
2721        DrawRect 17,12,426,107
2722        SetDrawEnv fsize= 18
2723        DrawText 83,40,"Reflectivity optimization in progress"
2724        SetDrawEnv fsize= 18
2725        DrawText 79,68,"This window will close when finished"
2726        DrawText 76,93,"If you abort the optimization, close the window manually"
2727EndMacro
2728///******************************************************************************************
2729///******************************************************************************************
2730///******************************************************************************************
2731///******************************************************************************************
2732//*****************************************************************************************************************
2733//*****************************************************************************************************************
2734//*****************************************************************************************************************
2735//*****************************************************************************************************************
2736//*****************************************************************************************************************
2737
2738static Function IR2R_CheckFittingParamsFnct()
2739        //PauseUpdate; Silent 1         // building window...
2740        NewPanel /K=1/W=(400,140,870,600) as "Check fitting parameters"
2741        Dowindow/C IR2R_CheckFittingParams
2742        SetDrawLayer UserBack
2743        SetDrawEnv fsize= 20,fstyle= 3,textrgb= (0,0,65280)
2744        DrawText 39,28,"Reflectivity Fit Params & Limits"
2745                SetDrawEnv fstyle= 1,fsize= 14
2746                DrawText 10,50,"For Gen Opt. verify fitted parameters. Make sure"
2747                SetDrawEnv fstyle= 1,fsize= 14
2748                DrawText 10,70,"the parameter range is appropriate."
2749                SetDrawEnv fstyle= 1,fsize= 14
2750                DrawText 10,90,"The whole range must be valid! It will be tested!"
2751                SetDrawEnv fstyle= 1,fsize= 14
2752                DrawText 10,110,"       Then continue....."
2753        Button CancelBtn,pos={27,420},size={150,20},proc=IR2R_CheckFitPrmsButtonProc,title="Cancel fitting"
2754        Button ContinueBtn,pos={187,420},size={150,20},proc=IR2R_CheckFitPrmsButtonProc,title="Continue fitting"
2755        String fldrSav0= GetDataFolder(1)
2756        SetDataFolder root:Packages:Refl_SimpleTool:
2757        Wave Gen_Constraints,W_coef
2758        Wave/T CoefNames
2759        SetDimLabel 1,0,Min,Gen_Constraints
2760        SetDimLabel 1,1,Max,Gen_Constraints
2761        variable i
2762        For(i=0;i<numpnts(CoefNames);i+=1)
2763                SetDimLabel 0,i,$(CoefNames[i]),Gen_Constraints
2764        endfor
2765                Edit/W=(0.05,0.25,0.95,0.865)/HOST=#  Gen_Constraints.ld,W_coef
2766//              ModifyTable format(Point)=1,width(Point)=0, width(Gen_Constraints)=110
2767//              ModifyTable alignment(W_coef)=1,sigDigits(W_coef)=4,title(W_coef)="Curent value"
2768//              ModifyTable alignment(Gen_Constraints)=1,sigDigits(Gen_Constraints)=4,title(Gen_Constraints)="Limits"
2769//              ModifyTable statsArea=85
2770                ModifyTable format(Point)=1,width(Point)=0,alignment(W_coef.y)=1,sigDigits(W_coef.y)=4
2771                ModifyTable width(W_coef.y)=90,title(W_coef.y)="Start value",width(Gen_Constraints.l)=172
2772//              ModifyTable title[1]="Min"
2773//              ModifyTable title[2]="Max"
2774                ModifyTable alignment(Gen_Constraints.d)=1,sigDigits(Gen_Constraints.d)=4,width(Gen_Constraints.d)=72
2775                ModifyTable title(Gen_Constraints.d)="Limits"
2776//              ModifyTable statsArea=85
2777//              ModifyTable statsArea=20
2778        SetDataFolder fldrSav0
2779        RenameWindow #,T0
2780        SetActiveSubwindow ##
2781End
2782
2783// Function Test()
2784//> Make /o /n=(5,2) myWave
2785//> SetDimLabel 1,0,min,myWave
2786//> SetDimLabel 1,1,max,myWave
2787//> Edit myWave.ld
2788//> End
2789
2790//*****************************************************************************************************************
2791//*****************************************************************************************************************
2792//*****************************************************************************************************************
2793//*****************************************************************************************************************
2794//*****************************************************************************************************************
2795Function IR2R_CheckFitPrmsButtonProc(ctrlName) : ButtonControl
2796        String ctrlName
2797       
2798        if(stringmatch(ctrlName,"*CancelBtn*"))
2799                variable/g root:Packages:Refl_SimpleTool:UserCanceled=1
2800                DoWindow/K IR2R_CheckFittingParams
2801        endif
2802
2803        if(stringmatch(ctrlName,"*ContinueBtn*"))
2804                variable/g root:Packages:Refl_SimpleTool:UserCanceled=0
2805                DoWindow/K IR2R_CheckFittingParams
2806        endif
2807
2808End
2809
2810//*****************************************************************************************************************
2811//*****************************************************************************************************************
2812//*****************************************************************************************************************
2813//*****************************************************************************************************************
2814//*****************************************************************************************************************
2815//*****************************************************************************************************************
2816
2817static Function IR2R_ResetParamsAfterBadFit()
2818       
2819        string oldDf=GetDataFolder(1)
2820        setDataFolder root:Packages:Refl_SimpleTool
2821
2822        Wave w=root:Packages:Refl_SimpleTool:CoefficientInput
2823        Wave/T CoefNames=root:Packages:Refl_SimpleTool:CoefNames                //text wave with names of parameters
2824
2825        if ((!WaveExists(w)) || (!WaveExists(CoefNames)))
2826                Beep
2827                abort "Record of old parameters does not exist, this is BUG, please report it..."
2828        endif
2829
2830        variable i
2831        For(i=0;i<numpnts(w);i+=1)
2832                NVAR testVal=$(CoefNames[i])
2833                testVal=w[i]
2834        endfor
2835        setDataFolder oldDF
2836end
2837
2838///******************************************************************************************
2839///******************************************************************************************
2840///******************************************************************************************
2841///******************************************************************************************
2842///******************************************************************************************
2843///******************************************************************************************
2844
2845///******************************************************************************************
2846///******************************************************************************************
2847///******************************************************************************************
2848///******************************************************************************************
2849///******************************************************************************************
2850///******************************************************************************************
2851Function IR2R_ST_FitFunction(w,yw,xw) : FitFunc
2852        Wave w,yw,xw
2853       
2854        //here the w contains the parameters, yw will be the result and xw is the input
2855        //CurveFitDialog/ These comments were created by the Curve Fitting dialog. Altering them will
2856        //CurveFitDialog/ make the function less convenient to work with in the Curve Fitting dialog.
2857        //CurveFitDialog/ Equation:
2858        //CurveFitDialog/ f(q) = very complex calculations, forget about formula
2859        //CurveFitDialog/ End of Equation
2860        //CurveFitDialog/ Independent Variables 1 - the q vector...
2861        //CurveFitDialog/ q
2862
2863        string oldDf=GetDataFolder(1)
2864        setDataFolder root:Packages:Refl_SimpleTool
2865
2866        Wave/T CoefNames=root:Packages:Refl_SimpleTool:CoefNames                //text wave with names of parameters
2867        NVAR FitIQN=root:Packages:Refl_SimpleTool:FitIQN       
2868
2869        variable i, NumOfParam
2870        NumOfParam=numpnts(CoefNames)
2871        string ParamName=""
2872       
2873        for (i=0;i<NumOfParam;i+=1)
2874                ParamName=CoefNames[i]
2875                NVAR tempVar=$(ParamName)
2876                //let's allow enforcement of positivity of given parameter here...
2877                if(stringmatch(ParamName, "*roughness*"))
2878                        tempVar = abs( w[i])
2879                else
2880                        tempVar = w[i]
2881                endif
2882        endfor
2883        //add here fix for linking, if parameter is linked to something, that something needs to be fixed herer also to match it during fitting...
2884        IR2R_UpdateLinkedVariables()   
2885        Wave QvectorWave=root:Packages:Refl_SimpleTool:FitQvectorWave
2886        //and now we need to calculate the model Intensity
2887        IR2R_FitCalculateModelResults(QvectorWave)                     
2888        Wave resultWv=root:Packages:Refl_SimpleTool:SimpleToolFitIntensity
2889        resultWv = resultWv * QvectorWave^FitIQN       
2890        yw=resultWv
2891
2892        NVAR UpdateDuringFitting=root:Packages:Refl_SimpleTool:UpdateDuringFitting
2893        if(UpdateDuringFitting)
2894                IR2R_CalculateModelResults()
2895                IR2R_CalculateSLDProfile()
2896                IR2R_GraphModelResults()
2897                DoUpdate/W=IR2R_LogLogPlotRefl
2898                DoUpdate/W=IR2R_IQN_Q_PlotV
2899        endif
2900        setDataFolder oldDF
2901End
2902
2903
2904///******************************************************************************************
2905///******************************************************************************************
2906///******************************************************************************************
2907///******************************************************************************************
2908///******************************************************************************************
2909///******************************************************************************************
2910static Function IR2R_FitCalculateModelResults(FitQvector)
2911        wave FitQvector
2912        //this function calculates model data
2913//      make/o/t parameters_Cref = {"Numlayers","scale","re_SLDtop","imag_SLDtop","re_SLDbase","imag_SLD base","bkg","sigma_base","thick1","re_SLD1","imag_SLD1","rough1","thick2","re_SLD2","imag_SLD2","rough2"}
2914//      Edit parameters_Cref,coef_Cref,par_res,resolution
2915//      ywave_Cref:= Motofit_Imag(coef_Cref,xwave_Cref)
2916
2917        variable i,j
2918        string OldDf=getDataFolder(1)
2919        setDataFolder root:Packages:Refl_SimpleTool
2920        //Need to create wave with parameters for Motofit_Imag here
2921        NVAR NumberOfLayers= root:Packages:Refl_SimpleTool:NumberOfLayers
2922        //need 8 parameters to start with - numLayers, scale, TopSLD_real, TopSLD_Imag, Bot_SLD_real, BotSLD_imag, Background, SubstareRoughness, and then 4 parameters for each layer
2923        // thickness, re_SLD, imag_SLD and roughness
2924        variable NumPointsNeeded= NumberOfLayers * 4 + 8
2925       
2926        make/O/D/N=(NumPointsNeeded) ParametersIn
2927        //now let's fill this in
2928        ParametersIn[0] = NumberOfLayers
2929        NVAR ScalingFactor=root:Packages:Refl_SimpleTool:ScalingFactor
2930        NVAR SLD_Real_Top=root:Packages:Refl_SimpleTool:SLD_Real_Top
2931        NVAR SLD_Imag_Top=root:Packages:Refl_SimpleTool:SLD_Imag_Top
2932        NVAR SLD_Real_Bot=root:Packages:Refl_SimpleTool:SLD_Real_Bot
2933        NVAR SLD_Imag_Bot=root:Packages:Refl_SimpleTool:SLD_Imag_Bot
2934        NVAR Background=root:Packages:Refl_SimpleTool:Background
2935        NVAR Roughness_Bot=root:Packages:Refl_SimpleTool:Roughness_Bot 
2936        NVAR L1AtTheBottom=root:Packages:Refl_SimpleTool:L1AtTheBottom
2937       
2938       
2939        ParametersIn[1] = ScalingFactor         
2940        ParametersIn[2] = SLD_Real_Top// * 1e-6
2941        ParametersIn[3] = SLD_Imag_Top * 1e-6
2942        ParametersIn[4] = SLD_Real_Bot// * 1e-6
2943        ParametersIn[5] = SLD_Imag_Bot * 1e-6
2944        ParametersIn[6] = Background
2945        ParametersIn[7] = Roughness_Bot
2946
2947        //fix to allow L1 at the bottom...
2948       
2949        if(L1AtTheBottom)
2950                j=0
2951                for(i=NumberOfLayers;i>=1;i-=1)
2952                        j+=1
2953                        NVAR ThicknessLayer= $("root:Packages:Refl_SimpleTool:ThicknessLayer"+Num2str(i))
2954                        NVAR SLD_real_Layer = $("root:Packages:Refl_SimpleTool:SLD_Real_Layer"+Num2str(i))
2955                        NVAR SLD_imag_Layer = $("root:Packages:Refl_SimpleTool:SLD_Imag_Layer"+Num2str(i))
2956                        NVAR RoughnessLayer = $("root:Packages:Refl_SimpleTool:RoughnessLayer"+Num2str(i))
2957                        ParametersIn[7+(j-1)*4+1] =  ThicknessLayer
2958                        ParametersIn[7+(j-1)*4+2] =  SLD_real_Layer// * 1e-6
2959                        ParametersIn[7+(j-1)*4+3] =  SLD_imag_Layer * 1e-6
2960                        ParametersIn[7+(j-1)*4+4] =  RoughnessLayer
2961                endfor
2962
2963        else
2964                for(i=1;i<=NumberOfLayers;i+=1)
2965                        NVAR ThicknessLayer= $("root:Packages:Refl_SimpleTool:ThicknessLayer"+Num2str(i))
2966                        NVAR SLD_real_Layer = $("root:Packages:Refl_SimpleTool:SLD_Real_Layer"+Num2str(i))
2967                        NVAR SLD_imag_Layer = $("root:Packages:Refl_SimpleTool:SLD_Imag_Layer"+Num2str(i))
2968                        NVAR RoughnessLayer = $("root:Packages:Refl_SimpleTool:RoughnessLayer"+Num2str(i))
2969                        ParametersIn[7+(i-1)*4+1] =  ThicknessLayer
2970                        ParametersIn[7+(i-1)*4+2] =  SLD_real_Layer// * 1e-6
2971                        ParametersIn[7+(i-1)*4+3] =  SLD_imag_Layer * 1e-6
2972                        ParametersIn[7+(i-1)*4+4] =  RoughnessLayer
2973                endfor
2974        endif
2975
2976        Duplicate/O FitQvector, SimpleToolFitIntensity
2977        NVAR Resoln=root:Packages:Refl_SimpleTool:Resoln
2978        NVAR UseResolutionWave=root:Packages:Refl_SimpleTool:UseResolutionWave
2979        Wave/Z FitResolutionWave=root:Packages:Refl_SimpleTool:FitResolutionWave
2980        if(UseResolutionWave)   
2981                //SimpleToolFitIntensity=IR2R_CalculateReflectivity(ParametersIn,FitQvector,FitResolutionWave)
2982                //IR2R_CalculateReflectivityNewRW(ParametersIn,SimpleToolFitIntensity,ModelQvector,FitResolutionWave)
2983                IR2R_CalculateReflectivityNewRW(ParametersIn,SimpleToolFitIntensity,FitQvector,FitResolutionWave)
2984        else//use resoln
2985                //SimpleToolFitIntensity=IR2R_CalculateReflectivity(ParametersIn,FitQvector,Resoln)
2986                //ModelIntensity=IR2R_CalculateReflectivity(ParametersIn,ModelQvector,Resoln)
2987                //R2R_CalculateReflectivityNew(ParametersIn,SimpleToolFitIntensity,ModelQvector,Resoln)
2988                IR2R_CalculateReflectivityNew(ParametersIn,SimpleToolFitIntensity,FitQvector,Resoln)
2989        endif
2990
2991        setDataFolder OldDf
2992       
2993end
2994
2995///******************************************************************************************
2996///******************************************************************************************
2997///******************************************************************************************
2998///******************************************************************************************
2999///******************************************************************************************
3000
3001static Function IR2R_CreateResolutionWave()
3002        //add on to create resolution wave...
3003        string oldDf=GetDataFolder(1)
3004        setDataFolder root:Packages:Refl_SimpleTool
3005       
3006        NVAR/Z Res_DeltaLambdaOverLambda
3007        if(!NVAR_EXISTS(Res_DeltaLambdaOverLambda))
3008                IR2R_InitializeSimpleTool()
3009        endif   
3010        NVAR Res_DeltaLambdaOverLambda
3011        NVAR Res_DeltaLambda
3012        NVAR Res_Lambda
3013        NVAR Res_SourceDivergence
3014        NVAR Res_DetectorSize
3015        NVAR Res_DetectorDistance
3016        NVAR Res_DetectorAngularResolution
3017        NVAR Res_sampleSize
3018        NVAR Res_beamHeight
3019        if(Res_Lambda==0)
3020                Res_Lambda=1
3021        endif
3022        if(Res_DetectorDistance==0)
3023                Res_DetectorDistance=1
3024        endif
3025        SVAR DataFolderName
3026        SVAR QWavename
3027        SetDataFolder $(DataFolderName)
3028        Wave Qwave=$(QWavename)
3029        Duplicate/O Qwave, CreatedFromParamaters
3030        Wave CreatedFromParamaters=CreatedFromParamaters
3031       
3032        setDataFolder root:Packages:Refl_SimpleTool
3033        DoWIndow ResolutionCalculator
3034        if(V_Flag)
3035                DoWindow/F ResolutionCalculator
3036        else
3037                //create new panel...
3038                //PauseUpdate; Silent 1         // building window...
3039                NewPanel/K=1 /W=(195,94,658,561) as "Resolution calculator"
3040                DoWindow/C ResolutionCalculator
3041                SetDrawLayer UserBack
3042                SetDrawEnv fsize= 22,fstyle= 1,textrgb= (0,0,52224)
3043                DrawText 95,35,"Create resolution data"
3044                SetDrawEnv fsize= 16,fstyle= 1,textrgb= (0,0,52224)
3045                DrawText 9,63,"Wavelength resolution"
3046                SetDrawEnv fsize= 16,fstyle= 1,textrgb= (0,0,52224)
3047                DrawText 9,148,"Source divergence resolution"
3048                SetDrawEnv fsize= 16,fstyle= 1,textrgb= (0,0,52224)
3049                DrawText 9,233,"Sample footprint resolution"
3050                SetDrawEnv fsize= 16,fstyle= 1,textrgb= (0,0,52224)
3051                DrawText 9,318,"Detector resolution"
3052                SetDrawEnv fsize= 14,fstyle= 1
3053                DrawText 9,454,"Close when finished. Resolution data are always recalculated"
3054                SetDrawEnv fsize= 14,fstyle= 1
3055                DrawText 9,434,"Set to 0 unneeded or negligible calculations"
3056
3057                SetVariable Res_DeltaLambda,pos={14,70},size={180,16},proc=IR2R_ResPanelSetVarProc,title="delta Wavelength [A]"
3058                SetVariable Res_DeltaLambda,limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:Res_DeltaLambda, help={"Uncertaininty of wavelength in wavelength units"}
3059                SetVariable Res_Lambda,pos={230,70},size={180,16},proc=IR2R_ResPanelSetVarProc,title="Wavelength [A]"
3060                SetVariable Res_Lambda,limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:Res_Lambda, help={"wavelength in wavelength units"}
3061                SetVariable Res_DeltaLambdaOverLambda,pos={100,100},size={200,16},proc=IR2R_ResPanelSetVarProc,title="Wavelength resolution "
3062                SetVariable Res_DeltaLambdaOverLambda,limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:Res_DeltaLambdaOverLambda, help={"dLambda/Lambda"}
3063
3064                SetVariable Res_SourceDivergence,pos={14,160},size={300,16},proc=IR2R_ResPanelSetVarProc,title="Source angular divergence [rad]"
3065                SetVariable Res_SourceDivergence,limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:Res_SourceDivergence, help={"Angular divergence of source. 0 for parallel beam."}
3066
3067                SetVariable Res_sampleSize,pos={14,250},size={180,16},proc=IR2R_ResPanelSetVarProc,title="Sample size [mm] "
3068                SetVariable Res_sampleSize,limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:Res_sampleSize, help={"length of sample in the beam direction in mm"}
3069                SetVariable Res_beamHeight,pos={230,250},size={180,16},proc=IR2R_ResPanelSetVarProc,title="Beam height in [mm] "
3070                SetVariable Res_beamHeight,limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:Res_beamHeight, help={"Height of beam in mm in the sample position"}
3071
3072                SetVariable Res_DetectorSize,pos={14,340},size={180,16},proc=IR2R_ResPanelSetVarProc,title="Detector size [mm] "
3073                SetVariable Res_DetectorSize,limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:Res_DetectorSize, help={"Detector slits opening (size) in scanning direction in mm"}
3074                SetVariable Res_DetectorDistance,pos={230,340},size={180,16},proc=IR2R_ResPanelSetVarProc,title="Detector distance [mm] "
3075                SetVariable Res_DetectorDistance,limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:Res_DetectorDistance, help={"Distance between detector slits and sample in mm"}
3076                SetVariable Res_DetectorAngularResolution,pos={100,370},size={200,16},proc=IR2R_ResPanelSetVarProc,title="Detector resolution [rad] "
3077                SetVariable Res_DetectorAngularResolution,limits={0,inf,0},variable= root:Packages:Refl_SimpleTool:Res_DetectorAngularResolution, help={"Detector resolution in radians"}
3078        endif
3079       
3080        IR2R_ResRecalculateResolution()
3081        setDataFolder OldDf
3082       
3083end
3084///******************************************************************************************
3085///******************************************************************************************
3086static Function IR2R_ResRecalculateResolution()
3087
3088        string oldDf=GetDataFolder(1)
3089        setDataFolder root:Packages:Refl_SimpleTool
3090        SVAR DataFolderName
3091        SVAR QWavename
3092        SetDataFolder $(DataFolderName)
3093        Wave Qwave=$(QWavename)
3094        Wave ResWv=CreatedFromParamaters
3095        setDataFolder root:Packages:Refl_SimpleTool
3096
3097        NVAR Res_DeltaLambdaOverLambda
3098        NVAR Res_SourceDivergence
3099        NVAR Res_DetectorAngularResolution
3100        NVAR Res_sampleSize
3101        NVAR Res_beamHeight
3102        NVAR Res_Lambda
3103        NVAR Res_DetectorDistance
3104        variable i
3105        variable curAngRes
3106        variable curAngle
3107        variable curFootprint, curDetRes
3108       
3109        for(i=0;i<numpnts(Qwave);i+=1)
3110                curAngle = asin(Qwave[i] * Res_Lambda /(4*pi))
3111                if(Res_sampleSize>0 && Res_beamHeight>0)
3112                        curFootprint = min(Res_sampleSize,(Res_beamHeight/sin(curAngle)))
3113                        curDetRes = curFootprint * sin(curAngle)/Res_DetectorDistance
3114                else
3115                        curDetRes=0
3116                endif
3117                if(Res_DetectorAngularResolution>0)
3118                        curAngRes = Res_DetectorAngularResolution / curAngle
3119                else
3120                        curAngRes=0
3121                endif
3122               
3123                ResWv[i] = 100 * sqrt(curDetRes^2 + curAngRes^2 + Res_SourceDivergence^2 +Res_DeltaLambdaOverLambda^2)
3124        endfor
3125
3126        setDataFolder OldDf
3127end
3128
3129///******************************************************************************************
3130///******************************************************************************************
3131///******************************************************************************************
3132///******************************************************************************************
3133
3134Function IR2R_ResPanelSetVarProc(ctrlName,varNum,varStr,varName) : SetVariableControl
3135        String ctrlName
3136        Variable varNum
3137        String varStr
3138        String varName
3139
3140        string oldDf=GetDataFolder(1)
3141        setDataFolder root:Packages:Refl_SimpleTool
3142        NVAR Res_DeltaLambdaOverLambda
3143        NVAR Res_DeltaLambda
3144        NVAR Res_Lambda
3145        NVAR Res_SourceDivergence
3146        NVAR Res_DetectorSize
3147        NVAR Res_DetectorDistance
3148        NVAR Res_DetectorAngularResolution
3149        NVAR Res_sampleSize
3150        NVAR Res_beamHeight
3151
3152        if (stringmatch(ctrlName,"Res_DeltaLambda") || stringmatch(ctrlName,"Res_Lambda"))
3153                Res_DeltaLambdaOverLambda = Res_DeltaLambda/Res_Lambda
3154        endif
3155        if (stringmatch(ctrlName,"Res_DeltaLambdaOverLambda"))
3156                Res_DeltaLambda = Res_DeltaLambdaOverLambda * Res_Lambda
3157        endif
3158        if (stringmatch(ctrlName,"Res_DetectorSize") || stringmatch(ctrlName,"Res_DetectorDistance"))
3159                Res_DetectorAngularResolution = Res_DetectorSize/Res_DetectorDistance
3160        endif
3161        if (stringmatch(ctrlName,"Res_DetectorAngularResolution"))
3162                Res_DetectorSize = Res_DetectorAngularResolution * Res_DetectorDistance
3163        endif
3164       
3165        IR2R_ResRecalculateResolution()
3166        setDataFolder OldDf
3167end
3168
3169
3170///******************************************************************************************
3171///******************************************************************************************
3172///******************************************************************************************
3173///******************************************************************************************
3174
3175static Function IR2R_AddRemoveLayersFnct()
3176
3177        string OldDf=GetDataFolder(1)
3178        setDataFolder   root:Packages:Refl_SimpleTool
3179        NVAR NumberOfLayers=root:Packages:Refl_SimpleTool:NumberOfLayers
3180       
3181        DoWindow IR2R_InsertRemoveLayers
3182        if(V_Flag)
3183                DoWindow/F IR2R_InsertRemoveLayers
3184        else
3185                Execute("IR2R_InsRemoveLayers()")
3186        endif
3187
3188        setDataFolder OldDf
3189end
3190
3191
3192///******************************************************************************************
3193///******************************************************************************************
3194///******************************************************************************************
3195///******************************************************************************************
3196
3197Function IR2R_RemAddLayersButtonProc(ba) : ButtonControl
3198        STRUCT WMButtonAction &ba
3199
3200        switch( ba.eventCode )
3201                case 2: // mouse up
3202                        // click code here
3203                        if(stringmatch(ba.ctrlName,"RemoveLayer"))
3204                                ControlInfo /W=IR2R_InsertRemoveLayers SelectLayerToChange
3205                                IR2R_RemoveLayer(V_Value)
3206                        endif
3207                        if(stringmatch(ba.ctrlName,"AddLayer"))
3208                                ControlInfo /W=IR2R_InsertRemoveLayers SelectLayerToChange
3209                                IR2R_InsertLayer(V_Value)
3210                        endif
3211                        break
3212                case -1: // control being killed
3213                        break
3214        endswitch
3215
3216        return 0
3217End
3218
3219///******************************************************************************************
3220///******************************************************************************************
3221///******************************************************************************************
3222///******************************************************************************************
3223
3224static Function IR2R_RemoveLayer(WhichLayer)
3225        variable WhichLayer
3226        string OldDf=GetDataFolder(1)
3227        setDataFolder  root:Packages:Refl_SimpleTool
3228        NVAR NumberOfLayers=root:Packages:Refl_SimpleTool:NumberOfLayers
3229        if(NumberOfLayers<=1)
3230                Abort "Cannot remove last layer, makes no sense..."
3231        endif
3232        String ListOfVariables
3233        ListOfVariables="SLD_Real_Layer;SLD_Imag_Layer;ThicknessLayer;RoughnessLayer;"
3234        ListOfVariables+="SLD_Real_LayerError;SLD_Imag_LayerError;ThicknessLayerError;RoughnessLayerError;"
3235        ListOfVariables+="SLD_Real_LayerStep;SLD_Imag_LayerStep;ThicknessLayerStep;RoughnessLayerStep;"
3236        ListOfVariables+="SLD_Real_LayerLL;SLD_Imag_LayerLL;ThicknessLayerLL;RoughnessLayerLL;"
3237        ListOfVariables+="SLD_Real_LayerUL;SLD_Imag_LayerUL;ThicknessLayerUL;RoughnessLayerUL;"
3238        ListOfVariables+="FitSLD_Real_Layer;FitSLD_Imag_Layer;FitThicknessLayer;FitRoughnessLayer;"
3239        ListOfVariables+="LinkSLD_Real_Layer;LinkSLD_Imag_Layer;LinkThicknessLayer;LinkRoughnessLayer;"
3240        ListOfVariables+="LinkFSLD_Real_Layer;LinkFSLD_Imag_Layer;LinkFThicknessLayer;LinkFRoughnessLayer;"
3241        ListOfVariables+="LinkToSLD_Real_Layer;LinkToSLD_Imag_Layer;LinkToThicknessLayer;LinkToRoughnessLayer;"
3242        String ListOfLinkVariables     
3243        ListOfLinkVariables="LinkSLD_Real_Layer;LinkSLD_Imag_Layer;LinkThicknessLayer;LinkRoughnessLayer;"
3244        //OK, we are removing one layer, number WhichLayer
3245        //nothing happens with layers below, layers above move by 1 lower and we need to fix linking...
3246        variable i, j
3247        string tempName
3248        //first need to move around the Fit variables...
3249        For(i=1;i<=8;i+=1)
3250                For(j=0;j<ItemsInList(ListOfLinkVariables);j+=1)
3251                        tempName = stringFromList(j,ListOfLinkVariables)+num2str(i)
3252                        NVAR LinkMe = $("root:Packages:Refl_SimpleTool:"+tempName)
3253                        if(LinkMe)
3254                                NVAR LinkMeTo = $("root:Packages:Refl_SimpleTool:"+ReplaceString("Link", tempName, "LinkTo"))
3255                                if(LinkMeTo<WhichLayer)
3256                                        //do nothing, this does not change
3257                                else
3258                                        LinkMeTo = LinkMeTo-1
3259                                        Execute("PopupMenu "+ReplaceString("Link", tempName, "LinkTo") +", win=IR2R_ReflSimpleToolMainPanel, popmatch = \""+num2str(LinkMeTo)+"\"")
3260                                endif
3261                        endif
3262                endfor
3263        endfor
3264        //OK, here should be fixed linking. The new links should always exist...
3265        For(i=WhichLayer+1;i<8;i+=1)
3266                For(j=0;j<ItemsInList(ListOfVariables);j+=1)
3267                        tempName = stringFromList(j,ListOfVariables)+num2str(i)
3268                        NVAR HigherValue = $("root:Packages:Refl_SimpleTool:"+tempName)
3269                        tempName = stringFromList(j,ListOfVariables)+num2str(i-1)
3270                        NVAR LowerValue = $("root:Packages:Refl_SimpleTool:"+tempName)
3271                        LowerValue = HigherValue
3272                endfor
3273        endfor
3274//      For(j=0;j<ItemsInList(ListOfVariables);j+=1)
3275//              tempName = stringFromList(j,ListOfVariables)+num2str(8)
3276//              NVAR Value = $("root:Packages:Refl_SimpleTool:"+tempName)
3277//              Value = 0
3278//      endfor
3279        NumberOfLayers=NumberOfLayers-1
3280        IR2R_TabPanelControl("",WhichLayer-1)
3281        Execute("TabControl DistTabs, win= IR2R_ReflSimpleToolMainPanel, value= "+num2str(WhichLayer-1))
3282        Execute("PopupMenu NumberOfLevels, win=IR2R_ReflSimpleToolMainPanel, popmatch = \""+num2str(NumberOfLayers)+"\"")       
3283        setDataFolder OldDf     
3284        DoAlert 0, "Layer "+num2str(WhichLayer)+" was removed, layers were shifted lower as needed. "
3285end
3286
3287///******************************************************************************************
3288///******************************************************************************************
3289///******************************************************************************************
3290///******************************************************************************************
3291
3292static Function IR2R_InsertLayer(WhichLayer)
3293        variable WhichLayer
3294        string OldDf=GetDataFolder(1)
3295        setDataFolder  root:Packages:Refl_SimpleTool
3296        NVAR NumberOfLayers=root:Packages:Refl_SimpleTool:NumberOfLayers
3297        if(NumberOfLayers>=8)
3298                Abort "Cannot insert new layer, all layers are already used"
3299        endif
3300        String ListOfVariables
3301        ListOfVariables="SLD_Real_Layer;SLD_Imag_Layer;ThicknessLayer;RoughnessLayer;"
3302        ListOfVariables+="SLD_Real_LayerError;SLD_Imag_LayerError;ThicknessLayerError;RoughnessLayerError;"
3303        ListOfVariables+="SLD_Real_LayerStep;SLD_Imag_LayerStep;ThicknessLayerStep;RoughnessLayerStep;"
3304        ListOfVariables+="SLD_Real_LayerLL;SLD_Imag_LayerLL;ThicknessLayerLL;RoughnessLayerLL;"
3305        ListOfVariables+="SLD_Real_LayerUL;SLD_Imag_LayerUL;ThicknessLayerUL;RoughnessLayerUL;"
3306        ListOfVariables+="FitSLD_Real_Layer;FitSLD_Imag_Layer;FitThicknessLayer;FitRoughnessLayer;"
3307        ListOfVariables+="LinkSLD_Real_Layer;LinkSLD_Imag_Layer;LinkThicknessLayer;LinkRoughnessLayer;"
3308        ListOfVariables+="LinkFSLD_Real_Layer;LinkFSLD_Imag_Layer;LinkFThicknessLayer;LinkFRoughnessLayer;"
3309        ListOfVariables+="LinkToSLD_Real_Layer;LinkToSLD_Imag_Layer;LinkToThicknessLayer;LinkToRoughnessLayer;"
3310        String ListOfLinkVariables     
3311        ListOfLinkVariables="LinkSLD_Real_Layer;LinkSLD_Imag_Layer;LinkThicknessLayer;LinkRoughnessLayer;"
3312        //ListOfLinkVariables+="LinkFSLD_Real_Layer;LinkFSLD_Imag_Layer;LinkFThicknessLayer;LinkFRoughnessLayer;"
3313        //ListOfLinkVariables+="LinkToSLD_Real_Layer;LinkToSLD_Imag_Layer;LinkToThicknessLayer;LinkToRoughnessLayer;"
3314        //OK, we are inserting new layer, number WhichLayer
3315        //nothing happens with layers below, layers above move by 1 higher and we need to fix linking...
3316        variable i, j
3317        string tempName
3318        //first need to move around the Fit variables...
3319        For(i=1;i<=8;i+=1)
3320                For(j=0;j<ItemsInList(ListOfLinkVariables);j+=1)
3321                        tempName = stringFromList(j,ListOfLinkVariables)+num2str(i)
3322                        NVAR LinkMe = $("root:Packages:Refl_SimpleTool:"+tempName)
3323                        if(LinkMe)
3324                                NVAR LinkMeTo = $("root:Packages:Refl_SimpleTool:"+ReplaceString("Link", tempName, "LinkTo"))
3325                                if(LinkMeTo<WhichLayer)
3326                                        //do nothing, this does not change
3327                                else
3328                                        LinkMeTo = LinkMeTo+1
3329                                        Execute("PopupMenu "+ReplaceString("Link", tempName, "LinkTo") +", win=IR2R_ReflSimpleToolMainPanel, popmatch = \""+num2str(LinkMeTo)+"\"")
3330                                endif
3331                        endif
3332                endfor
3333        endfor
3334        //OK, here should be fixed linking. The new links should always exist...
3335        For(i=8;i>WhichLayer;i-=1)
3336                For(j=0;j<ItemsInList(ListOfVariables);j+=1)
3337                        tempName = stringFromList(j,ListOfVariables)+num2str(i)
3338                        NVAR HigherValue = $("root:Packages:Refl_SimpleTool:"+tempName)
3339                        tempName = stringFromList(j,ListOfVariables)+num2str(i-1)
3340                        NVAR LowerValue = $("root:Packages:Refl_SimpleTool:"+tempName)
3341                        HigherValue = LowerValue
3342                endfor
3343        endfor
3344        For(j=0;j<ItemsInList(ListOfVariables);j+=1)
3345                tempName = stringFromList(j,ListOfVariables)+num2str(WhichLayer)
3346                NVAR Value = $("root:Packages:Refl_SimpleTool:"+tempName)
3347                Value = 0
3348        endfor
3349        NumberOfLayers=NumberOfLayers+1
3350        IR2R_TabPanelControl("",WhichLayer-1)
3351        Execute("TabControl DistTabs, win= IR2R_ReflSimpleToolMainPanel, value= "+num2str(WhichLayer-1))
3352        Execute("PopupMenu NumberOfLevels, win=IR2R_ReflSimpleToolMainPanel, popmatch = \""+num2str(NumberOfLayers)+"\"")       
3353        setDataFolder OldDf     
3354        DoAlert 0, "Layer "+num2str(WhichLayer)+" was inserted, layers were shifted higher as needed. All parameters of inserted layer are set to 0. Fix before continuing"
3355end
3356
3357///******************************************************************************************
3358///******************************************************************************************
3359///******************************************************************************************
3360///******************************************************************************************
3361
3362Function IR2R_InsRemoveLayers() : Panel
3363        PauseUpdate; Silent 1           // building window...
3364        NewPanel /K=1 /W=(389,217,687,427) as "Insert/ Remove Layers"
3365        DoWindow/C IR2R_InsertRemoveLayers
3366        SetDrawLayer UserBack
3367        SetDrawEnv fsize= 14,fstyle= 3,textrgb= (1,4,52428)
3368        DrawText 35,28,"Reflectivity Insert/Remove layer"
3369        DrawText 11,44,"Here you can remove or insert layer."
3370        DrawText 11,62,"Cannot insert layer if current num layers = 8. "
3371        DrawText 11,81,"Other layers will be moved as needed."
3372        DrawText 11,100,"Do NOT use to add/remove highest layer."
3373        string tempStr="\""
3374        variable i
3375        NVAR NumberOfLayers = root:Packages:Refl_SimpleTool:NumberOfLayers
3376        For(i=1;i<=NumberOfLayers;i+=1)
3377                tempStr+=num2str(i)+";"
3378        endfor
3379        tempStr+="\""
3380        PopupMenu SelectLayerToChange,pos={12,120},size={177,20},title="Select Layer to insert/remove   "
3381        PopupMenu SelectLayerToChange,help={"Select layer to remove or insert."}
3382        PopupMenu SelectLayerToChange,mode=1,mode=1,value= #tempStr
3383        Button RemoveLayer,pos={20,160},size={120,20},proc=IR2R_RemAddLayersButtonProc,title="Remove Layer"
3384        Button RemoveLayer,help={"Remove selected layer, move higher layers down. "}
3385        Button AddLayer,pos={153,160},size={120,20},proc=IR2R_RemAddLayersButtonProc,title="Add Layer"
3386        Button AddLayer,help={"Add layer in this position, move higher layers up."}
3387end
3388
3389
3390///******************************************************************************************
3391///******************************************************************************************
3392///******************************************************************************************
3393///******************************************************************************************
Note: See TracBrowser for help on using the repository browser.