source: trunk/User Procedures/Irena/IR1_Main.ipf @ 857

Last change on this file since 857 was 857, checked in by ilavsky, 22 months ago

Working on MultiDataFit? tool

File size: 164.9 KB
Line 
1#pragma TextEncoding = "UTF-8"
2#pragma rtGlobals = 3   // Use strict wave reference mode and runtime bounds checking
3#pragma version=2.691
4#pragma IgorVersion=7.05
5
6//DO NOT renumber Main files every time, these are main release numbers...
7//define manual date and release verison
8constant CurrentIrenaVersionNumber = 2.691
9
10//*************************************************************************\
11//* Copyright (c) 2005 - 2019, Argonne National Laboratory
12//* This file is distributed subject to a Software License Agreement found
13//* in the file LICENSE that is included with this distribution.
14//*************************************************************************/
15
16
17//2.691 Beta version after February2020 release
18//2.69  Removed 14 ipf files to reduce clutter.
19//                      Combined with IR1_CreateFldrStrctr.ipf, IR1_Functions.ipf
20//                      added 3DModels, 4D aggregate and Two Phase ssytems.
21//                      POV/PDB import and fixes for 3D Models
22//                      Added Anisotropy analsysis (Hermans orienational parameter)
23//                      Create QRS folder structure should now handle also QIS data.
24//                      Add print in history which version has compiled, Useful info later when debugging.
25//2.68   Beta version. New 64-bit xops for OSX.
26//2.67  heavily modified Size Distribution (added power law background). First official Igor 8 release.
27//                      Nexus exporter - changed to use 1/angstrom for Q as sasView below 4.1.2 (probably below 4.3 at least) cannot convert Q units on import.
28//                      Unified fit - modified how the limits and steps are handled when user set value to 0. Fixed Uncertainty analysis in Unified fit which seems to have failed on Igor 8.
29//2.66   Converted all procedure files to UTF8 to prevent text encoding issues.
30//                      Fixed Case spelling of USAXS Error data to SMR_Error and DSM_Error
31//                      Plotting tool I - added control which enforces maximum number of items in legend (default=30). If more waves are in graph, legend gets decimated by necessary integer(2, 3, 4,...). First and last are always included. This presents selection of data names when too many data sets are used.
32//                      MergeData - added ability to fit-extrapolate data 1 at high q end and added possibility to fit arbitrary combination of merging parameters. Lots of changes. More capable and more complicated.
33//                      Unified Fit - added button "Copy/Swap level" which will move content of existing level to another level.
34//                      Checked that - with reduced functionality - code will work without Github distributed xops.
35//                      Tested and fixed for Igor 8 beta version.
36//2.65   Promoted requriements to 7.05 due to bug in HDF5 support at lower versions
37//                      Added simple recording to my web site about version checking for statistical purposes. Records Irena version, Igor platform and version. 
38//                      added resizing back to prior size of panel after user closes and opens the panel.
39//                      Removed most DoWIndows/K and repalced with KillWIndow and number of smaller changes.
40//2.64 Updated CheckForUpdate to check on Github for latest release version
41//                      #pragma IgorVersion=7.00
42//                      removed Modeling I cocde (IR1S_ functions). Moved stuff around.
43//2.63 update to 2.62 with on lin ehelp and Igor 6 only.
44//2.62 Nexus support and other fixes, added check for desktop resolution
45//2.61 fox for WIndows resolution in resizing panels
46//2.60 added ShowResizeControlsPanel. 
47//2.60 modified GUI preferences handling. Was reseting, wrong logic.
48//
49//2.59 changed check for update procedure to check http first, tehn ftp, and the fail.
50//2.59 added WAXS tool - first releae to users. Simple fits are not made visible to users yet.
51//2.59 to be done... Added development version of Simple fits - new well structured tool for simplistic fits on SAS data.
52//2.58 Added MergeData tool. 
53//2.58 Added YouTube movies page.
54//2.57 Many fixes to Modeling II mainly.
55//2.56 fixed ListProRoutine which had troubles with links, 2.55 never released.
56//2.55 changed FIt Power law with cursors - follows now the user font size and does not have units (would depend on calibration). Linear fit now also sues User fonts.
57//2.55 moved Zoom and set limits to GraphMarquee menu, changed the ZoomAndSetLimits to be dynamic menu item
58//2.54 version release, January 2014
59//2.53  Added check for platform when opening Igor experiment. GUI fonts are really crazy if these are not fixed
60//2.52 Summer 2013 release.
61//              modified Manual and Manuscript download routine to use http. ftp was failing, not sure why.
62//              changed all web addresses to new (xray.aps.anl.gov)
63//2.51 added check for update to run every 30 days and remind users about proper citations.
64//2.51 added Guinier-Porod model (beta version of the tool)
65//2.50 major update, added uncertainity estimation to Sizes and Modeling II. Reflectivity changes.
66//2.49 Minor fixes
67//2.48 Fixed GUI font/size issues on WIndows 7, Plotting tool I 3D upgrades, moved Modeling I to "Other tools"
68//2.47 New mailing list, movie & 3D graphs in Plotting tool I and other many fixes.
69//2.46 lots of small fixes, added easy access to scripting tool and few other changes.
70//2.45 Added features to Data manipulation II and Reflectivity. Updated manual.
71//2.44 minor fix Modeling II, Addition of controls of Modeling II to Scripting tool, other fixes.
72//2.43 add functions to handle modified panels between updates.
73//2.41 and 2.42, minor updates
74//2.40 added Unified level as Form factor and other fixes and improvements
75//2.39 added license for ANL
76
77// notes from IR1_CreateFlderStrctr.ipf
78//2.06 changed to use MoveWave and handle also QR data. Needs to be tested for QR data
79//2.05 changed back to rtGlobals=2, need to check code much more to make it 3
80//2.04 minor fix for liberal names users keep using
81//2.03 converted to rtGlobals=3
82//2.02 removed all font and font size from panel definitions to enable user control
83//2.01 added license for ANL
84
85//notes from IR1_Functions.ipf
86//2.08 fixes to PorodsNOtebook logging requested by Dale
87//2.07 added Ardell distributions support
88//2.06 moved in this file some functions from retired Modeling I support - these are needed by other tools.
89//2.05 added few missing window names which need to be killed when Kill all ..." is invoked.
90//2.04 added IR2R_InsertRemoveLayers in the KillAllPanels
91//2.03 changed min size to 1A sicne many users are using really high q data.
92//2.02 modified by adding Shultz-Zimm distribution, JIL, 3/17/2011
93//2.01 added license for ANL
94
95//This macro file is part of Igor macros package called "Irena",
96//the full package should be available from usaxs.xray.aps.anl.gov/
97//this package contains
98// Igor functions for modeling of SAS from various distributions of scatterers...
99
100//Jan Ilavsky,  2010
101
102//please, read Readme in the distribution zip file with more details on the program
103//report any problems to: ilavsky@aps.anl.gov
104
105//this file contains distribution related functions, at this time
106// there are three type of distributions: LSW (Pete's request), LogNormal and Gauss (Normal)
107//each requires 3 parameters, but LSW uses only the location, Normal uses two - location and scale (=width)
108//only Log-normal uses all three - location, scale and shape. But all three require the three parametser - for simplicity
109//Each distribution has two forms - probability distribution and cumulative distribution
110//finaly, there is function used to generate distribution of diameters for each of the distributions. Lot of parameters, see the function
111
112//Log-Normal and Normal (here called Gauss) distributions defined by NIST Engineering Statistics Handbook (http://www.itl.nist.gov/div898/handbook/index.htm)
113//LSW distribution, based on Lifshitz, Slyozov, and Wagner theory as used in paper by Naser, Kuruvilla, and Smith: Compositional Effects
114// on Grain Growth During Liquid Phase Sintering in Microgravity, found on web site www.space.gc.ca/science/space_science/paper_reports/spacebound97/materials_science....
115
116
117
118// from version 2.26 I skipped numbers to match the current Irena version number (2.38)
119
120//report any problems to: ilavsky@aps.anl.gov
121//Comment for me: Limit yourself to less than 30 items in the menu, Windows are limited to 30 items. Note: "---" counts as one item!
122//comment - add these:          IN2G_PrintDebugStatement(IrenaDebugLevel, 5,"")
123//and these                                             IN2G_PrintDebugStatement(IrenaDebugLevel, 0..5 ,"Error message")
124
125
126Menu "GraphMarquee", dynamic
127     IR2_MenuItemForGraph("Zoom And Set Limits","GeneralGraph"),/Q, ZoomAndSetLimits()
128        //"Zoom and set limits", ZoomAndSetLimits()
129End
130
131Menu "SAS"
132        help = {"Irena SAS modeling macros, version 2.54 released 1/5/2014 by Jan Ilavsky"}
133        Submenu "Data import & export"
134                "Import ASCII SAS data", IR1I_ImportSASASCIIDataMain()
135                help={"Import Small-angle scattering data from ASCII file into Igor for use with macros"}
136                "Import ASCII WAXS or other data", IR1I_ImportOtherASCIIMain()
137                help={"Import Other type data from ASCII file into Igor for use with macros"}
138                "Import Nexus canSAS data", IR1I_ImportNexusCanSASMain()
139                help={"Import data from Nexus CanSAS conforming data sets"}
140                "Import canSAS XML data", CS_XMLGUIImportDataMain(defaultType="QRS",defaultQUnits="1/A")
141                help={"Import data from XML CanSAS conforming data sets"}
142                "---"
143                "Export Nexus canSAS or ASCII data", IR2E_UniversalDataExport()
144                help = {"This is tool for export of any 2-3 column data sets as ASCII."}
145        End
146        "---"
147        Submenu "Data Manipulation"
148                "Data manipulation I [one or two data sets]",  IR1D_DataManipulation()
149                help={"Merge data sets, rebin for same Q, etc..."}
150                "Data manipulation II [many data sets]", IR3M_DataManipulationII()
151                help={"Manipulate - for now only average - many data sets"}
152                "Merge two data sets", IR3D_DataMerging()
153                help={"Merge two data sets - two segments at different q ranges"}
154                "Data mining [extract information]", IR2M_GetDataMiner()
155                help={"Data miner to find various data and plot various waves"}
156        end
157        "---"
158        "Plotting I", IR1P_GeneralPlotTool()
159        help = {"Plotting tool with wide functionality, hopefully"}
160        "Plotting II", IR2D_DWSPlotToolMain()
161        help = {"Plotting tool which controls any top graph"}
162        "Multi Sample Plot-Fit - under developement", IR3L_MultiSaPlotFit()
163        help={"Plotting and fitting of multiple SAS data. Developement for now. Do not use. "}
164                SubMenu "Support Tools for plots and tables"
165                "Draw Line Of Any Slope", IR2P_DrawLineOfAnySlope()
166                "Draw Line Of -4 Slope",  IR2P_DrawLineOf4Slope()
167                "Draw Line Of -3 Slope",  IR2P_DrawLineOf3Slope()
168                "Draw Line Of -2 Slope",  IR2P_DrawLineOf2Slope()
169                "Make log-log graph decade limits", IR2P_MakeLogLogGraphDecLim()
170                "--"
171                "Fit Line With Cursors", IR2P_FitLineWithCursors()
172                "Fit Power Law with Cursors", IR2P_FitPowerLawWithCursors()
173                "--"
174               "Clone top window with data", IN2G_CloneWindow()
175                End
176        "---"
177        //"Multi Sample Fit - under developement", IR3L_MultiSaPlotFit()
178        //help={"Plotting and fitting of multiple SAS data. Developement for now. Do not use. "}
179        "Unified Fit", IR1A_UnifiedModel()
180        help = {"Modeling of SAS by modeling Guinier and Power law dependecies, based on Unified model by Gregg Beaucage"}
181        "Size Distribution", IR1R_Sizes()
182        help = {"SAS evaluation by regularization and maximum entropy fitting using spheroids"}
183        "Modeling",IR2L_Main()
184        help = {"Complicated modeling of SAS with Least square fitting or genetic optimization, allows multiple data input and is much more flexible than LSqF. Much more complicated also!)"}
185        "Gunier Porod Fit", IR3GP_Main()
186        help = {"Modeling of SAS as Guinier and Power law dependecies, based on Gunier-Porod model by Bualem Hammouda"}
187        "Fractals model", IR1V_FractalsModel()
188        help = {"Modeling of SAS by combining mass and surface fractal dependecies, based on model by Andrew Allen"}
189        "Analytical models", IR2H_GelsMainFnct()
190        help={"Debye-Bueche, Teubner-Strey model"}
191        "Small-Angle Diffraction", IR2D_MainSmallAngleDiff()
192        help={"Modeling of small angle diffraction - up to 6 peaks and Powerlaw background"}
193        "Powder Diffraction fitting = WAXS", IR3W_WAXS()
194        help={"Tool for analysis of WAXS/Powder diffraction data. Developement version for public."}
195        "Pair distance dist. fnct.", IR2Pr_MainPDDF()
196        help={"Calculate pair distribution function using various methods"}
197        "Reflectivity", IR2R_ReflectivitySimpleToolMain()
198        help={"Simple reflectivity model using Parrat's recursive code."}
199        SubMenu "3D Models"
200                "Mass Fractal Aggregate", IR3A_MassFractalAggregate()
201                //"Two Phase Solids", IR3T_TwoPhaseSystem()
202                //"Display 3D data", IR3A_Display3DData()
203                //"Import POV or PDB", IR3P_ImportPOVPDB()
204        end
205        SubMenu "Anisotropy"
206                "Anisotropy analysis (HOP)", IR3N_AnisotropicSystems()
207        end
208        "---"
209        "Scattering contrast calculator", IR1K_ScattCont2()
210        help={"Calculator for scattering contrast. Both X rays and neutrons. Anomalous effects available."}
211        "Config fonts, uncertainties, names",IR2C_ConfigMain()
212        help={"Configure default values for GUI Panels and Graph common items, such as font sizes and font types"}
213
214        SubMenu "Support tools"
215                        "Evaluate Size Distributions", IR1G_EvaluateONESample()
216                        help = {"Not fully finished GUI to evaluate results from methods producing size distributions"}
217                        "Scripting tool",  IR2S_ScriptingTool()
218                        help = {"Scripting tool enabes to run some tools on multiple data sets."}
219                        "Desmearing", IR1B_DesmearingMain()
220                        help={"Remove slit smearing using Lake method"}
221                        "Show Results notebook", IR1_CreateResultsNbk()
222                        help={"Shows notebook in which tools can create record of the results with graphs"}
223                        "Create QRS folder structure", IR1F_CreateFldrStrctMain()
224                        help={"Create folder structure for users with QRS data in one folder, so Irena can work well"}
225                        "Show SAS logbook", IR1_PullUpLoggbook()
226                        help = {"Some of these macros make ongoing record of what is done, you'll find it here..."}
227                        "Export To XLS File Panel", ExportToXLSFilePanel()
228                        help={"This is tool for Unified fit, made by Gragg Beaucage. For help, contact him..."}
229                End
230                Submenu "Help, About, Manuals, Remove Irena"
231                        "About", IR1_AboutPanel()
232                        help={"Get Panel with info about this release of Irena macros"}
233                        "Check for updates", IR2C_CheckIrenaUpdate(1)
234                        help={"Run Check for update and present citations to use in publications"}     
235                        "Check Igor display size", IN2G_CheckForGraphicsSetting(1)
236                        help={"Check if current display area is suitable for the code"}
237                        "---"
238                        "Open Irena Web page ", IR2_OpenIrenaPage()
239                        help={"Opens Irena web page in the browser "}
240                        "Open Irena web manual", IN2G_OpenWebManual("")
241                        help={"Opens Irena web manual in default web bropwser."}
242                        "Open Form and Structure Factor description", IR2T_LoadFFDescription()
243                        help={"Opens Description of included form factors and structure factors"}
244                        "Open Irena manuscript", IR2_GetIrenaManuscript()
245                        help={"Open or download using ftp and open Irena J. Appl. Cryst manuscript"}
246                        //"---"
247                        "Irena Mailing list signup and options", IR2_SignUpForMailingList()
248                        help={"Opens web page in the browser where you can sing up or control options for Irena_users mailing list."}
249                        "Open Youtube page with help movies", IR2_OpenYouTubeMoviePage()
250                        help={"Opens YouTube page in the browser where different movies showing use of Irena are available"}
251                        //"Open Web page with help movies", IR2_OpenHelpMoviePage()
252                        //help={"Opens web page in the browser where different movies showing use of Irena can be downloaded"}
253                        "Submit e-mail with bug or feature request", IR2C_SendEMailBugReport()
254                        help={"This will open your e-mail browser with some info and address. Use to submit info to me. "}
255                        "---"
256                        "Kill all Irena panels and graphs", IR1_KillGraphsAndPanels()
257                        help = {"If you have just too much mess with many open panels and graphs, this will close them all..."}
258                        "Remove Irena Package", IR1_RemoveSASMac()
259                        help={"Removes Irena macros from current Igor experiment"}
260                end
261end
262Menu "Macros", dynamic
263        IR2_MacrosMenuItem()
264end
265
266Function/S IR2_MacrosMenuItem()
267        if((Exists("ShowResizeControlsPanel")==6))
268                return "ShowResizeControlsPanel"
269        else
270                return ""
271        endif
272end
273
274//****************************************************************************************
275//****************************************************************************************
276//****************************************************************************************
277Function/S IR2_MenuItemForGraph(menuItem, onlyForThisGraph)
278        String menuItem, onlyForThisGraph
279        String topGraph=WinName(0,1,1)
280        if( CmpStr(topGraph,onlyForThisGraph) == 0 )
281                return menuItem
282        endif
283        return ""       // disappearing menu item
284End
285//****************************************************************************************
286//****************************************************************************************
287//****************************************************************************************
288
289static Function AfterCompiledHook( )                    //check if all windows are up to date to match their code
290
291        //these are tools which have been upgraded to this functionality
292        string WindowProcNames="LSQF2_MainPanel=IR2L_MainCheckVersion;IR2H_ControlPanel=IR2H_MainCheckVersion;DataMiningTool=IR2M_MainCheckVersion;DataManipulationII=IR3M_MainCheckVersion;"
293        WindowProcNames+="IR1I_ImportData=IR1I_MainCheckVersion;IR2S_ScriptingToolPnl=IR2S_MainCheckVersion;IR1R_SizesInputPanel=IR1R_MainCheckVersion;IR1A_ControlPanel=IR1A_MainCheckVersion;"
294        WindowProcNames+="IR1P_ControlPanel=IR1P_MainCheckVersion;IR2R_ReflSimpleToolMainPanel=IR2R_MainCheckVersion;IR3DP_MainPanel=IR3GP_MainCheckVersion;"
295        WindowProcNames+="IR1V_ControlPanel=IR1V_MainCheckVersion;IR2D_ControlPanel=IR2D_MainCheckVersion;IR2Pr_ControlPanel=IR2Pr_MainCheckVersion;UnivDataExportPanel=IR2E_MainCheckVersion;"
296        WindowProcNames+="IR1D_DataManipulationPanel=IR1D_MainCheckVersion;IR3D_DataMergePanel=IR3D_MainCheckVersion;IR3W_WAXSPanel=IR3W_MainCheckVersion;"
297        WindowProcNames+="IR2D_DWSGraphPanel=IR2D_DWSMainCheckVersion;IR1I_ImportOtherASCIIData=IR1I_MainCheckVersion2;IR1I_MainCheckVersionNexus=IR1I_ImportNexusCanSASData;"
298        WindowProcNames+="UnifiedEvaluationPanel=IR2U_MainCheckVersion;FractalAggregatePanel=IR3A_MainCheckVersion;TwoPhaseSystems=IR3T_MainCheckVersion;"
299        WindowProcNames+="POVPDBPanel=IR3P_MainCheckVersion;AnisotropicSystemsPanel=IR3N_MainCheckVersion;"
300 
301        IR2C_CheckWIndowsProcVersions(WindowProcNames)
302        IR2C_CheckIrenaUpdate(0)
303        IN2G_CheckPlatformGUIFonts()
304        IN2G_CheckForGraphicsSetting(0)
305        IN2G_ResetSizesForALlPanels(WindowProcNames)
306
307        //and print in history which version of codeis being used for future reference.
308        string file= StringFromList((ItemsInList(FunctionPath("LoadIrenaSASMacros"), ":")-1), FunctionPath("LoadIrenaSASMacros"), ":")
309        String path = RemoveFromList(file, FunctionPath("LoadIrenaSASMacros") , ":")
310        NewPath /O/Q TmpPathToIgorProcs  , path
311        variable version = IN2G_FindVersionOfSingleFile(file,"TmpPathToIgorProcs")
312        print "*** >>>  Irena version: "+num2str(version)+", compiled on "+date()+"  "+time()
313       
314       
315end
316//****************************************************************************************
317//****************************************************************************************
318//****************************************************************************************
319 
320Function IR2C_CheckWIndowsProcVersions(WindowProcNames)
321        string WindowProcNames
322       
323        variable i 
324        string PanelName
325        String ProcedureName
326        For(i=0;i<ItemsInList(WindowProcNames);i+=1)
327                PanelName = StringFromList(0, StringFromList(i, WindowProcNames, ";")  , "=")
328                ProcedureName = StringFromList(1, StringFromList(i, WindowProcNames, ";")  , "=")
329                DoWIndow $(PanelName)
330                if(V_Flag)
331                        Execute (ProcedureName+"()")
332                endif
333        endfor
334       
335end
336///////////////////////////////////////////
337//****************************************************************************************
338//              Default variables and strings
339//
340//      these are known at this time:
341//              Variables=LegendSize;TagSize;AxisLabelSize;
342//              Strings=FontType;
343//
344//      how to use:
345//      When needed insert font size through lookup function - e.g., IN2G_LkUpDfltVar("LegendSize")
346//      or for font type IN2G_LkUpDfltStr("FontType")
347//      NOTE: Both return string values, because that is what is generally needed!!!!
348// further variables and strings can be added, but need to be added to control panel too...
349//      see example in : IR1_LogLogPlotU()  in this procedure file...
350
351
352//***********************************************************
353//***********************************************************
354//***********************************************************
355//***********************************************************
356Function IR1_UpdatePanelVersionNumber(panelName, CurentProcVersion, AddResizeHookFunction)
357        string panelName
358        variable CurentProcVersion
359        variable AddResizeHookFunction                  //set to 0 for no, 1 for simple Irena one and 2 for Wavemetrics one
360        DoWIndow $panelName
361        if(V_Flag)
362                GetWindow $(panelName), note
363                SetWindow $(panelName), note=S_value+";"+"IrenaProcVersion:"+num2str(CurentProcVersion)+";"
364                if(AddResizeHookFunction==1)
365                        IN2G_PanelAppendSizeRecordNote(panelName)
366                        SetWindow $panelName,hook(ResizePanelControls)=IN2G_PanelResizePanelSize
367                        IN2G_ResetPanelSize(panelName,1)
368                        STRUCT WMWinHookStruct s
369                        s.eventcode=6
370                        s.winName=panelName
371                        IN2G_PanelResizePanelSize(s)
372                endif
373        endif
374end
375//***********************************************************
376//***********************************************************
377Function IR1_CheckPanelVersionNumber(panelName, CurentProcVersion)
378        string panelName
379        variable CurentProcVersion
380
381        DoWIndow $panelName
382        if(V_Flag)     
383                GetWindow $(panelName), note
384                if(stringmatch(stringbyKey("IrenaProcVersion",S_value),num2str(CurentProcVersion))) //matches
385                        return 1
386                else
387                        return 0
388                endif
389        else
390                return 1
391        endif
392end
393
394//**********************************************************************************************************
395//**********************************************************************************************************
396//this is added into selection in Marquee.
397//if run, sets limits to marquee selection and switches into manual mode for axis range
398Function ZoomAndSetLimits()
399        //this will zoom graph and set limits to the appropriate numbers
400        GetMarquee/K left, bottom
401        if(!stringmatch(S_MarqueeWin"GeneralGraph"))
402                return 0       
403        endif
404        SVAR ListOfGraphFormating=root:Packages:GeneralplottingTool:ListOfGraphFormating
405        ListOfGraphFormating=ReplaceStringByKey("Axis left auto",ListOfGraphFormating,"0","=" )
406        ListOfGraphFormating=ReplaceStringByKey("Axis bottom auto",ListOfGraphFormating,"0","=" )
407        ListOfGraphFormating=ReplaceStringByKey("Axis left min",ListOfGraphFormating,num2str(V_bottom),"=" )
408        ListOfGraphFormating=ReplaceStringByKey("Axis left max",ListOfGraphFormating,num2str(V_top),"=" )
409        ListOfGraphFormating=ReplaceStringByKey("Axis bottom min",ListOfGraphFormating,num2str(V_left),"=" )
410        ListOfGraphFormating=ReplaceStringByKey("Axis bottom max",ListOfGraphFormating,num2str(V_right),"=" )
411        IR1P_SynchronizeListAndVars()
412        IR1P_UpdateGenGraph()
413end
414//***********************************************************
415//***********************************************************
416//***********************************************************
417//***********************************************************
418//***********************************************************
419
420Function IR2C_ConfigMain()              //call configuration routine
421        IN2G_ConfigMain()
422end
423
424
425//***********************************************************
426//***********************************************************
427//***********************************************************
428
429////***********************************************************
430//***********************************************************
431//***********************************************************
432
433Function IR2C_SendEMailBugReport()
434
435        string url, separator
436        if(stringmatch(StringByKey("OS", IgorInfo(3) , ":" , ";"), "*Macintosh*" ))
437                separator="\n"
438        else
439                separator="%0A"
440        endif
441        url="mailto:ilavsky@aps.anl.gov?subject=Irena ver "+num2str(CurrentIrenaVersionNumber)+" bug or user comment"
442        url+="&body=The problem or bug occurred on "+separator
443        url+="IgorInfo(0) = "+IgorInfo(0)+separator
444        url+="IgorInfo(3) = "+IgorInfo(3)+separator+separator
445        url+="Please attach notes about the bug or request for new features. If necessary attach your Igor experiment. Thank You J.I."+separator
446        BrowseURL url
447end
448
449//***********************************************************
450//***********************************************************
451//***********************************************************
452//***********************************************************
453//***********************************************************
454///////////////////////////////////////////
455
456Proc IR2P_FitLineWithCursors()
457
458        string destwavename="fit_"+CsrWave(A)
459        CurveFit line CsrWaveRef(A)(xcsr(A),xcsr(B)) /X=CsrXWaveRef(A) /D
460        Tag/C/N=Curvefitres/F=0/A=MC $destwavename, 0.5*numpnts($destwavename), "\Z"+IN2G_LkUpDfltVar("LegendSize")+"Linear fit parameters are: \ry="+num2str(W_coef[0])+"+ x *"+num2str(W_coef[1])
461end
462//*****************************************
463//*****************************************
464//*****************************************
465
466Proc IR2P_FitPowerLawWithCursors()
467
468        string olddf=GetDataFolder(1)
469        NewDataFolder/O/S root:Packages:FittingData
470       
471        string name="MyFitWave"
472        string LegendName="Curvefitres"
473       
474        variable freeDestNum=IR2P_FindFreeDestWaveNumber(name)
475        name=name +num2istr(freeDestNum)
476        LegendName=LegendName+num2istr(freeDestNum)
477        Make/D/O/N=(numpnts($(getWavesDataFolder(CsrWaveRef(A),2)))) LogYFitData, $name
478        $name=NaN
479        Make/D/O/N=(numpnts($(getWavesDataFolder(CsrXWaveRef(A),2)))) LogXFitData
480        LogXFitData=log($(getWavesDataFolder(CsrXWaveRef(A),2)))
481        LogYFitData=log($(getWavesDataFolder(CsrWaveRef(A),2)))
482        CurveFit line LogYFitData(xcsr(A),xcsr(B)) /X=LogXFitData /D=$name
483               
484        IR2P_LogPowerWithNaNsRetained($name)
485       
486        //here we will try to figure out, if the data are plotted wrt to left or right axis...
487        string YwvName=CsrWave(A)
488        string AxType=StringByKey("AXISFLAGS", TraceInfo("",YwvName,0) )//this checks only for first occurence of the wave with this name
489        //this needs to be made more clever, other axis and other occurences of the wave with the name...
490        if (cmpstr(AxType,"/R")==0)
491                Append/R $name vs CsrXWaveRef(A)
492        else
493                Append $name vs CsrXWaveRef(A)
494        endif
495        Modify lsize($name)=2
496        String pw=num2str(K1),pr=num2str(10^K0),DIN=num2str((V_siga*10^K0)/2.3026),ca=num2str(pcsr(A)),cb=num2str(pcsr(B)),gf=num2str(V_Pr),DP=num2str(V_sigb)
497        string LSs=IN2G_LkUpDfltVar("LegendSize")
498        Tag/C/N=$LegendName/F=0/A=MC  $name, (pcsr(A)+pcsr(B))/2, "\Z"+LSs+"Power Law Slope= "+pw+"\Z"+LSs+" ± "+DP+"\Z"+LSs+"\rPrefactor= "+pr+"\Z"+LSs+" ± "+DIN+"\Z"+LSs+"\rx Cursor A::B= "+ca+"\Z"+LSs+" :: "+cb+"\Z"+LSs+"\rGoodness of fit= "+gf
499
500        KillWaves/Z LogYFitData, LogXFitData
501
502        SetDataFolder $olddf
503end
504//*****************************************
505//*****************************************
506//*****************************************
507
508Function IR2P_FindFreeDestWaveNumber(name)
509        string name
510       
511        variable i=0
512        Do
513                if (exists(name+num2istr(i))==0)
514                        return i
515                endif
516        i+=1
517        while (i<50)
518end
519//*****************************************
520//*****************************************
521//*****************************************
522
523Function IR2P_LogPowerWithNaNsRetained(MyFitWave)
524        wave MyFitWave
525       
526        variable PointsNumber=numpnts(MyFitWave)
527        variable i=0
528        Do
529                if (numtype(MyFitWave[i])==0)
530                        MyFitWave[i]=10^(MyFitWave[i])
531                endif
532        i+=1
533        while (i<PointsNumber)
534end
535//*****************************************
536//*****************************************
537//*****************************************
538
539Function IR2P_DrawLineOf3Slope()
540        IR2P_DrawLineOfRequiredSlope(3,3,1,"-3")
541End
542
543//*****************************************
544//*****************************************
545//*****************************************
546
547Function IR2P_DrawLineOf2Slope()
548        IR2P_DrawLineOfRequiredSlope(2,2,1,"-2")
549End
550//*****************************************
551
552Function IR2P_DrawLineOf4Slope()
553        IR2P_DrawLineOfRequiredSlope(4,4,1,"-4")
554End
555//*****************************************
556Function IR2P_DrawLineOfAnySlope()
557
558        Variable lineslope,YourNumber,qlabel
559        string label1
560        Prompt lineslope, "Enter slope of line, or select Your number",Popup,"M1;M2;M3;M4;M5;M3.5;M4.5;M2.5;M1.5;Your Number;Vertical;Horizontal;5/3"
561        Prompt YourNumber,"If Your number above selected, enter here a number for the slope:"
562        Prompt qlabel,"Add a Label?",popup,"Power From Above;My own;No"
563        Prompt label1,"If Yes, then here type your label?"
564
565        DoPrompt "Draw line of any slope, select parameters", lineslope, Yournumber, qlabel, label1
566        if (V_Flag)
567                        Abort
568        endif
569        Silent 1
570        do
571                if(lineslope==12)
572                        lineslope=0
573                        break
574                endif
575                if(lineslope==10)
576                        lineslope=YourNumber
577                        break
578                endif
579                if(lineslope==6)
580                        lineslope=3.5
581                        break
582                endif
583                if(lineslope==7)
584                        lineslope=4.5
585                        break
586                endif
587                if(lineslope==8)
588                        lineslope=2.5
589                        break
590                endif
591                if(lineslope==9)
592                        lineslope=1.5
593                        break
594                endif
595                if(lineslope==13)
596                        lineslope=5/3
597                        break
598                endif
599                break
600        while(1)
601
602        IR2P_DrawLineOfRequiredSlope(LineSlope,YourNumber,qLabel,label1)
603end
604
605
606Function IR2P_DrawLineOfRequiredSlope(LineSlope,YourNumber,qLabel,label1)
607        Variable lineslope,YourNumber,qlabel
608        string label1
609       
610        if(wintype("")!=1)
611                Abort "Top window is not graph, make sure the top window is graph before use of this function"
612        endif
613       
614        SetDrawEnv xcoord= bottom,ycoord= left,save
615        variable X_start, Y_start
616        getAxis bottom
617        X_start=ceil((floor(log(V_max))+floor(log(V_min)))/2)
618        getAxis left
619        Y_start=ceil((ceil(log(V_max))+ceil(log(V_min)))/2)
620        if(lineslope==11)                                                                                                               //Vertical
621                drawline 10^(X_start),10^(Y_start),10^(X_start+1),10^(Y_start)
622        else
623                drawline 10^(X_start),10^(Y_start),10^(X_start+1),10^(Y_start-lineslope)
624        endif
625        if(qlabel==2)
626                SetDrawEnv fname= "Times",fstyle= 1;DelayUpdate
627                DrawText 10^(X_start),10^(Y_start-1),Label1
628        else
629                if(qlabel==1)//use power from above
630                        SetDrawEnv fname= "Times",fstyle= 1;DelayUpdate
631                        DrawText 10^(X_start),10^(Y_start-1),("-"+num2str(lineslope))
632                endif
633        endif
634EndMacro
635
636
637
638//*****************************************************************************************************************
639//*****************************************************************************************************************
640//*****************************************************************************************************************
641Function IR2_GetIrenaManuscript()
642
643                string WhereIsManuscript
644                string WhereAreProcedures=RemoveEnding(FunctionPath(""),"IR1_Main.ipf")
645                String ManuscriptPath = ParseFilePath(5,"IrenaManuscript.pdf","*",0,0)
646        String cmd
647        print "Irena manuscript reference: "
648        print "Jan Ilavsky and Pete R. Jemian, Irena: tool suite for modeling and analysis of small-angle scattering"
649        print "Journal of Applied Crystallography (2009), 42, 347-353"
650        variable refnum
651        GetFileFolderInfo/Z=1/Q WhereAreProcedures+ManuscriptPath
652        variable foundIt=V_Flag
653        if(foundIt!=0)
654        NewPath/O/Q tempPath, WhereAreProcedures
655                DoAlert 1,  "Local copy of manuscript not found. Should Igor try to download from APS public web site?"
656                if(V_Flag==1)
657//                      string url="ftp://ftp.xray.aps.anl.gov/pub/usaxs/IrenaManuscript.pdf"
658//                      FTPDownload /O/V=7/P=tempPath/Z url, "IrenaManuscript.pdf"     
659//                      if(V_flag!=0)   //ftp failed...
660//                              Abort "ftp of manuscript failed, please send e-mail to author to get your copy"
661//                      endif
662                        //string url="ftp://ftp.xray.aps.anl.gov/pub/usaxs/Irena Manual.pdf"           
663                        string httpPath =  ReplaceString(" ", "http://ftp.xray.aps.anl.gov/usaxs/IrenaManuscript.pdf", "%20")           //handle just spaces here...
664                        String fileBytes, tempPathStr
665                        Variable error = GetRTError(1)
666                         fileBytes = FetchURL(httpPath)
667                         error = GetRTError(1)
668                         sleep/S 0.2
669                         if(error!=0)
670                                 print "Manuscript download FAILED, please download from directly from Irena web page "
671                        else
672                                Open/P=tempPath  refNum as "IrenaManuscript.pdf"
673                                FBinWrite refNum, fileBytes
674                                Close refNum
675                                SetFileFolderInfo/P=tempPath/RO=0  "IrenaManuscript.pdf"               
676                        endif
677                else
678                        abort
679                endif
680                killPath tempPath
681        endif
682       
683       
684        if (stringmatch(IgorInfo(2), "*Macintosh*"))
685               sprintf cmd "tell application \"Finder\" to open \"%s\"",WhereAreProcedures+ManuscriptPath
686               ExecuteScriptText cmd
687                if (strlen(S_value)>2)
688//                      DoAlert 0, S_value
689                endif
690
691        else
692                WhereAreProcedures=ParseFilePath(5,WhereAreProcedures,"*",0,0)
693                WhereIsManuscript = "\"" + WhereAreProcedures+ManuscriptPath+"\""
694                NewNotebook/F=0 /N=NewBatchFile
695                Notebook NewBatchFile, text=WhereIsManuscript//+"\r"
696                SaveNotebook/O NewBatchFile as SpecialDirPath("Temporary", 0, 1, 0 )+"StartManual.bat"
697                KillWIndow/Z NewBatchFile
698                ExecuteScriptText "\""+SpecialDirPath("Temporary", 0, 1, 0 )+"StartManual.bat\""
699        endif
700
701
702end
703
704//*****************************************************************************************************************
705//*****************************************************************************************************************
706//Function IR2_OpenIrenaManual()
707//      //this function writes batch file and starts the manual.
708//      //we need to write following batch file: "C:\Program Files\WaveMetrics\Igor Pro Folder\User Procedures\Irena\Irena manual.pdf"
709//      //on Mac we just fire up the Finder with Mac type path...
710//      DoAlert /T="PDF manuals removed" 0, "pdf manuals are not distributed with the packages anymore. Use web manuals. If needed download pdf file from the web"
711//      //check where we run...
712//              //string WhereIsIgor
713//              //pathInfo Igor
714////            string WhereIsManual
715////            string WhereAreProcedures=RemoveEnding(FunctionPath(""),"IR1_Main.ipf")
716////            String manualPath = ParseFilePath(5,"Irena Manual.pdf","*",0,0)
717////            String cmd
718////   
719////    variable refnum
720////    GetFileFolderInfo/Z=1/Q WhereAreProcedures+manualPath
721////    variable foundIt=V_Flag
722////    variable ManualModDate=V_modificationDate
723////    printf "The current manual date is: %+015.4f\r", V_modificationDate
724////    if(ManualModDate>0)
725////            //print  V_modificationDate
726////            print "Found version of Manual is from : " + secs2Date(ManualModDate,1)
727////    endif
728////    if(foundIt!=0 || ManualModDate<CurrentManualDateInSecs)
729////            NewPath/O/Q tempPath, WhereAreProcedures
730////            DoAlert 1,  "Local copy of manual not found or is obsolete. Should Igor try to download from APS public web site?"
731////            if(V_Flag==1)
732////                    //string url="ftp://ftp.xray.aps.anl.gov/pub/usaxs/Irena Manual.pdf"           
733////                    string httpPath =  ReplaceString(" ", "http://ftp.xray.aps.anl.gov/usaxs/Irena Manual.pdf", "%20")              //handle just spaces here...
734////                    String fileBytes, tempPathStr
735////                    Variable error = GetRTError(1)
736////                     fileBytes = FetchURL(httpPath)
737////                     error = GetRTError(1)
738////                     sleep/S 0.2
739////                     if(error!=0)
740////                             print "Manual download FAILED, please download from directly from Irena web page "
741////                    else
742////                            Open/P=tempPath  refNum as "Irena Manual.pdf"
743////                            FBinWrite refNum, fileBytes
744////                            Close refNum
745////                            SetFileFolderInfo/P=tempPath/RO=0  "Irena Manual.pdf"           
746////                    endif
747////            else
748////                    abort
749////            endif
750////            killPath tempPath       
751////    endif
752////   
753////    if (stringmatch(IgorInfo(2), "*Macintosh*"))
754////             //  manualPath = "User Procedures:Irena:Irena manual.pdf"
755////               sprintf cmd "tell application \"Finder\" to open \"%s\"",WhereAreProcedures+manualPath
756////               ExecuteScriptText cmd
757////                    if (strlen(S_value)>2)
758//////                  DoAlert 0, S_value
759////            endif
760////
761////    else
762////            //manualPath = "User Procedures\Irena\Irena manual.pdf"
763////            //WhereIsIgor=WhereIsIgor[0,1]+"\\"+IN2G_ChangePartsOfString(WhereIsIgor[2,inf],":","\\")
764////            WhereAreProcedures=ParseFilePath(5,WhereAreProcedures,"*",0,0)
765////            whereIsManual = "\"" + WhereAreProcedures+manualPath+"\""
766////            NewNotebook/F=0 /N=NewBatchFile
767////            Notebook NewBatchFile, text=whereIsManual//+"\r"
768////            SaveNotebook/O NewBatchFile as SpecialDirPath("Temporary", 0, 1, 0 )+"StartManual.bat"
769////            KillWIndow/Z NewBatchFile
770////            ExecuteScriptText "\""+SpecialDirPath("Temporary", 0, 1, 0 )+"StartManual.bat\""
771////    endif
772//end
773////*****************************************************************************************************************
774//*****************************************************************************************************************
775Function IR2_OpenHelpMoviePage()
776        DoAlert 1,"Your web browser will open page with help movies. OK? (You must have QuickTime installed)"
777        if(V_flag==1)
778                //BrowseURL "http://usaxs.xray.aps.anl.gov/staff/ilavsky/IrenaHelpMovies.html"
779                BrowseURL "https://www.youtube.com/channel/UCDTzjGr3mAbRi3O4DJG7xHA/feed"
780        endif
781End
782
783Function IR2_OpenYouTubeMoviePage()
784        DoAlert 1,"Your web browser will open Youtube page with help movies. OK?"
785        if(V_flag==1)
786                BrowseURL "https://www.youtube.com/channel/UCDTzjGr3mAbRi3O4DJG7xHA/feed"
787        endif
788End
789
790
791
792Function IR2_OpenIrenaPage()
793        DoAlert 1,"Your web browser will Irena home page. OK?"
794        if(V_flag==1)
795                BrowseURL "https://usaxs.xray.aps.anl.gov/software/irena"
796        endif
797End
798
799Function IR2_SignUpForMailingList()
800        DoAlert 1,"Your web browser will open page with the page where you can control your maling list options. OK?"
801        if(V_flag==1)
802                BrowseURL "https://mailman.aps.anl.gov/mailman/listinfo/irena_users"
803        endif
804End
805
806
807
808//*****************************************************************************************************************
809//*****************************************************************************************************************
810//*****************************************************************************************************************
811
812
813Function IR1_AboutPanel()
814        KillWIndow/Z About_Irena_1_Macros
815//      PauseUpdate; Silent 1           // building window...
816        NewPanel/K=1 /W=(173.25,50,580,460)/N=About_Irena_1_Macros as "About Irena Macros"
817        SetDrawLayer UserBack
818        SetDrawEnv fsize= 20,fstyle= 1,textrgb= (16384,28160,65280)
819        DrawText 23,30,"Irena macros for Igor Pro 7 & 8"
820        SetDrawEnv fsize= 16,textrgb= (16384,28160,65280)
821        DrawText 100,60,"@ ANL, 2018"
822        DrawText 10,80,"release "+num2str(CurrentIrenaVersionNumber)
823        DrawText 11,100,"To get help please contact: ilavsky@aps.anl.gov"
824        SetDrawEnv textrgb= (0,0,65535)
825        DrawText 11,120,"http://usaxs.xray.aps.anl.gov/staff/ilavsky/irena.htm"
826        SetDrawEnv fsize= 14, fstyle=1
827        DrawText 11,148,"Reference: Jan Ilavsky and Pete R. Jemian"
828        SetDrawEnv fsize= 14, fstyle=1
829        DrawText 11,168,"J Appl Crystallogr (2009), 42, 347-353"
830
831        DrawText 11,195,"Size distribution by Pete Jemian: jemian@anl.gov"
832        DrawText 11,215,"Unified model by Gregg Beaucage: gbeaucag@uceng.uc.edu"
833        DrawText 11,230," Beaucage, G. (1995). J Appl Crystallogr 28, 717-728."
834        DrawText 11,250," Fractals model by Andrew Allen: Andrew.Allen@nist.gov"
835        DrawText 11,265," Allen, A. J. (2005). J Am Ceram Soc 88, 1367-1381. "
836        DrawText 11,285," Reflectivity & Genetic Optimization by Andrew Nelson "
837        DrawText 11,300," (Australian Nuclear Science and Technology Organisation) "
838        DrawText 11,315,"             Nelson, A. (2006). J Appl Crystallogr 39, 273-276."
839        DrawText 11,330,"             andyfaff@gmail.com"
840        DrawText 11,350,"Selected Structure & Form Factors refs: "
841        DrawText 11,365,"       Kline, S. R. (2006). J Appl Crystallogr 39, 895-900"
842        DrawText 11,380,"http://www.ncnr.nist.gov/programs/sans/data/data_red.html"
843// (). 
844end
845
846//*****************************************************************************************************************
847//*****************************************************************************************************************
848//*****************************************************************************************************************
849//*****************************************************************************************************************
850//*****************************************************************************************************************
851
852
853Function IR1_RemoveSASMac()
854                Execute/P "IR1_KillGraphsAndPanels()"
855                Execute/P "DELETEINCLUDE \"IR1_Loader\""
856                SVAR strChagne=root:Packages:SASItem1Str
857                strChagne= "Load Irena SAS Macros"
858                BuildMenu "SAS"
859                Execute/P "COMPILEPROCEDURES "
860end
861
862
863
864//*****************************************************************************************************************
865//*****************************************************************************************************************
866//*****************************************************************************************************************
867//*****************************************************************************************************************
868////*****************************************************************************************************************
869////*****************************************************************************************************************
870////*****************************************************************************************************************
871////*****************************************************************************************************************
872////*****************************************************************************************************************
873//
874//Function IR1S_Initialize()
875//      //function, which creates the folder for SAS modeling and creates the strings and variables
876//     
877//      string oldDf=GetDataFolder(1)
878//     
879//      NewDataFolder/O/S root:Packages
880//      NewdataFolder/O/S root:Packages:SAS_Modeling
881//     
882//      string ListOfVariables
883//      string ListOfStrings
884//     
885//      //here define the lists of variables and strings needed, separate names by ;...
886//     
887//      ListOfVariables="UseIndra2Data;UseQRSdata;NumberOfDistributions;DisplayVD;DisplayND;CurrentTab;UseInterference;UseLSQF;UseGenOpt;"
888//      ListOfVariables+="Dist1NumberOfPoints;Dist1Contrast;Dist1Location;Dist1Scale;Dist1Shape;Dist1Mean;Dist1Median;Dist1Mode;Dist1LocHighLimit;Dist1LocLowLimit;Dist1ScaleHighLimit;Dist1ScaleLowLimit;"
889//      ListOfVariables+="Dist1ShapeHighLimit;Dist1ShapeLowLimit;Dist1LocStep;Dist1ShapeStep;Dist1ScaleStep;Dist1FitShape;Dist1FitLocation;Dist1FitScale;Dist1VolFraction;"
890//      ListOfVariables+="Dist1VolHighLimit;Dist1VolLowLimit;Dist1FitVol;Dist1NegligibleFraction;Dist1ScatShapeParam1;Dist1ScatShapeParam2;Dist1ScatShapeParam3;Dist1FWHM;"
891//      ListOfVariables+="Dist2NumberOfPoints;Dist2Contrast;Dist2Location;Dist2Scale;Dist2Shape;Dist2Mean;Dist2Median;Dist2Mode;Dist2LocHighLimit;Dist2LocLowLimit;Dist2ScaleHighLimit;Dist2ScaleLowLimit;"
892//      ListOfVariables+="Dist2ShapeHighLimit;Dist2ShapeLowLimit;Dist2LocStep;Dist2ShapeStep;Dist2ScaleStep;Dist2FitShape;Dist2FitLocation;Dist2FitScale;Dist2VolFraction;"
893//      ListOfVariables+="Dist2VolHighLimit;Dist2VolLowLimit;Dist2FitVol;Dist2NegligibleFraction;Dist2ScatShapeParam1;Dist2ScatShapeParam2;Dist2ScatShapeParam3;Dist2FWHM;"
894//      ListOfVariables+="Dist3NumberOfPoints;Dist3Contrast;Dist3Location;Dist3Scale;Dist3Shape;Dist3Mean;Dist3Median;Dist3Mode;Dist3LocHighLimit;Dist3LocLowLimit;Dist3ScaleHighLimit;Dist3ScaleLowLimit;"
895//      ListOfVariables+="Dist3ShapeHighLimit;Dist3ShapeLowLimit;Dist3LocStep;Dist3ShapeStep;Dist3ScaleStep;Dist3FitShape;Dist3FitLocation;Dist3FitScale;Dist3VolFraction;"
896//      ListOfVariables+="Dist3VolHighLimit;Dist3VolLowLimit;Dist3FitVol;Dist3NegligibleFraction;Dist3ScatShapeParam1;Dist3ScatShapeParam2;Dist3ScatShapeParam3;Dist3FWHM;"
897//      ListOfVariables+="Dist4NumberOfPoints;Dist4Contrast;Dist4Location;Dist4Scale;Dist4Shape;Dist4Mean;Dist4Median;Dist4Mode;Dist4LocHighLimit;Dist4LocLowLimit;Dist4ScaleHighLimit;Dist4ScaleLowLimit;"
898//      ListOfVariables+="Dist4ShapeHighLimit;Dist4ShapeLowLimit;Dist4LocStep;Dist4ShapeStep;Dist4ScaleStep;Dist4FitShape;Dist4FitLocation;Dist4FitScale;Dist4VolFraction;"
899//      ListOfVariables+="Dist4VolHighLimit;Dist4VolLowLimit;Dist4FitVol;Dist4NegligibleFraction;Dist4ScatShapeParam1;Dist4ScatShapeParam2;Dist4ScatShapeParam3;Dist4FWHM;"
900//      ListOfVariables+="Dist5NumberOfPoints;Dist5Contrast;Dist5Location;Dist5Scale;Dist5Shape;Dist5Mean;Dist5Median;Dist5Mode;Dist5LocHighLimit;Dist5LocLowLimit;Dist5ScaleHighLimit;Dist5ScaleLowLimit;"
901//      ListOfVariables+="Dist5ShapeHighLimit;Dist5ShapeLowLimit;Dist5LocStep;Dist5ShapeStep;Dist5ScaleStep;Dist5FitShape;Dist5FitLocation;Dist5FitScale;Dist5VolFraction;"
902//      ListOfVariables+="Dist5VolHighLimit;Dist5VolLowLimit;Dist5FitVol;Dist5NegligibleFraction;Dist5ScatShapeParam1;Dist5ScatShapeParam2;Dist5ScatShapeParam3;Dist5FWHM;"
903//      ListOfVariables+="SASBackground;SASBackgroundStep;FitSASBackground;UseNumberDistribution;UseVolumeDistribution;UpdateAutomatically;"
904//      ListOfVariables+="SASBackgroundError;Dist1LocationError;Dist1ScaleError;Dist1ShapeError;Dist1VolFractionError;"
905//      ListOfVariables+="Dist1LocationError;Dist1ScaleError;Dist1ShapeError;Dist1VolFractionError;"
906//      ListOfVariables+="Dist2LocationError;Dist2ScaleError;Dist2ShapeError;Dist2VolFractionError;"
907//      ListOfVariables+="Dist3LocationError;Dist3ScaleError;Dist3ShapeError;Dist3VolFractionError;"
908//      ListOfVariables+="Dist4LocationError;Dist4ScaleError;Dist4ShapeError;Dist4VolFractionError;"
909//      ListOfVariables+="Dist5LocationError;Dist5ScaleError;Dist5ShapeError;Dist5VolFractionError;"
910//      ListOfVariables+="Dist1UseInterference;Dist1InterferencePhi;Dist1InterferenceEta;Dist1InterferencePhiLL;Dist1InterferencePhiHL;Dist1InterferenceEtaLL;Dist1InterferenceEtaHL;"
911//      ListOfVariables+="Dist2UseInterference;Dist2InterferencePhi;Dist2InterferenceEta;Dist2InterferencePhiLL;Dist2InterferencePhiHL;Dist2InterferenceEtaLL;Dist2InterferenceEtaHL;"
912//      ListOfVariables+="Dist3UseInterference;Dist3InterferencePhi;Dist3InterferenceEta;Dist3InterferencePhiLL;Dist3InterferencePhiHL;Dist3InterferenceEtaLL;Dist3InterferenceEtaHL;"
913//      ListOfVariables+="Dist4UseInterference;Dist4InterferencePhi;Dist4InterferenceEta;Dist4InterferencePhiLL;Dist4InterferencePhiHL;Dist4InterferenceEtaLL;Dist4InterferenceEtaHL;"
914//      ListOfVariables+="Dist5UseInterference;Dist5InterferencePhi;Dist5InterferenceEta;Dist5InterferencePhiLL;Dist5InterferencePhiHL;Dist5InterferenceEtaLL;Dist5InterferenceEtaHL;"
915//      ListOfVariables+="Dist1FitInterferencePhi;Dist2FitInterferencePhi;Dist3FitInterferencePhi;Dist4FitInterferencePhi;Dist5FitInterferencePhi;"
916//      ListOfVariables+="Dist1FitInterferenceETA;Dist2FitInterferenceETA;Dist3FitInterferenceETA;Dist4FitInterferenceETA;Dist5FitInterferenceETA;"
917//      ListOfVariables+="Dist1InterferencePhiError;Dist1InterferenceEtaError;Dist2InterferencePhiError;Dist2InterferenceEtaError;"
918//      ListOfVariables+="Dist3InterferencePhiError;Dist3InterferenceEtaError;Dist4InterferencePhiError;Dist4InterferenceEtaError;"
919//      ListOfVariables+="Dist5InterferencePhiError;Dist5InterferenceEtaError;"
920//      ListOfVariables+="UseSlitSmearedData;SlitLength;"       
921//      //Ok add chance to fit the shape parameters
922//      ListOfVariables+="Dist1FitScatShapeParam1;Dist1ScatShapeParam1LowLimit;Dist1ScatShapeParam1HighLimit;Dist1FitScatShapeParam2;Dist1ScatShapeParam2LowLimit;Dist1ScatShapeParam2HighLimit;Dist1FitScatShapeParam3;Dist1ScatShapeParam3LowLimit;Dist1ScatShapeParam3HighLimit;"
923//      ListOfVariables+="Dist2FitScatShapeParam1;Dist2ScatShapeParam1LowLimit;Dist2ScatShapeParam1HighLimit;Dist2FitScatShapeParam2;Dist2ScatShapeParam2LowLimit;Dist2ScatShapeParam2HighLimit;Dist2FitScatShapeParam3;Dist2ScatShapeParam3LowLimit;Dist2ScatShapeParam3HighLimit;"
924//      ListOfVariables+="Dist3FitScatShapeParam1;Dist3ScatShapeParam1LowLimit;Dist3ScatShapeParam1HighLimit;Dist3FitScatShapeParam2;Dist3ScatShapeParam2LowLimit;Dist3ScatShapeParam2HighLimit;Dist3FitScatShapeParam3;Dist3ScatShapeParam3LowLimit;Dist3ScatShapeParam3HighLimit;"
925//      ListOfVariables+="Dist4FitScatShapeParam1;Dist4ScatShapeParam1LowLimit;Dist4ScatShapeParam1HighLimit;Dist4FitScatShapeParam2;Dist4ScatShapeParam2LowLimit;Dist4ScatShapeParam2HighLimit;Dist4FitScatShapeParam3;Dist4ScatShapeParam3LowLimit;Dist4ScatShapeParam3HighLimit;"
926//      ListOfVariables+="Dist5FitScatShapeParam1;Dist5ScatShapeParam1LowLimit;Dist5ScatShapeParam1HighLimit;Dist5FitScatShapeParam2;Dist5ScatShapeParam2LowLimit;Dist5ScatShapeParam2HighLimit;Dist5FitScatShapeParam3;Dist5ScatShapeParam3LowLimit;Dist5ScatShapeParam3HighLimit;"
927//      ListOfVariables+="Dist1ScatShapeParam4;Dist1ScatShapeParam5;"
928//      ListOfVariables+="Dist2ScatShapeParam4;Dist2ScatShapeParam5;"
929//      ListOfVariables+="Dist3ScatShapeParam4;Dist3ScatShapeParam5;"
930//      ListOfVariables+="Dist4ScatShapeParam4;Dist4ScatShapeParam5;"
931//      ListOfVariables+="Dist5ScatShapeParam4;Dist5ScatShapeParam5;"
932//      ListOfVariables+="Dist1ScatShapeParam1Error;Dist1ScatShapeParam2Error;Dist1ScatShapeParam3Error;"
933//      ListOfVariables+="Dist2ScatShapeParam1Error;Dist2ScatShapeParam2Error;Dist2ScatShapeParam3Error;"
934//      ListOfVariables+="Dist3ScatShapeParam1Error;Dist3ScatShapeParam2Error;Dist3ScatShapeParam3Error;"
935//      ListOfVariables+="Dist4ScatShapeParam1Error;Dist4ScatShapeParam2Error;Dist4ScatShapeParam3Error;"
936//      ListOfVariables+="Dist5ScatShapeParam1Error;Dist5ScatShapeParam2Error;Dist5ScatShapeParam3Error;WallThicknessSpreadInFract;"
937//      ListOfVariables+="Dist1UserFFParam1;Dist1UserFFParam2;Dist1UserFFParam3;Dist1UserFFParam4;Dist1UserFFParam5;"
938//      ListOfVariables+="Dist2UserFFParam1;Dist2UserFFParam2;Dist2UserFFParam3;Dist2UserFFParam4;Dist2UserFFParam5;"
939//      ListOfVariables+="Dist3UserFFParam1;Dist3UserFFParam2;Dist3UserFFParam3;Dist3UserFFParam4;Dist3UserFFParam5;"
940//      ListOfVariables+="Dist4UserFFParam1;Dist4UserFFParam2;Dist4UserFFParam3;Dist4UserFFParam4;Dist4UserFFParam5;"
941//      ListOfVariables+="Dist5UserFFParam1;Dist5UserFFParam2;Dist5UserFFParam3;Dist5UserFFParam4;Dist5UserFFParam5;"
942//
943//      ListOfStrings="DataFolderName;IntensityWaveName;QWavename;ErrorWaveName;"
944//      ListOfStrings+="Dist1ShapeModel;Dist1DistributionType;Dist1UserFormFactorFnct;Dist1UserVolumeFnct;"
945//      ListOfStrings+="Dist2ShapeModel;Dist2DistributionType;Dist2UserFormFactorFnct;Dist2UserVolumeFnct;"
946//      ListOfStrings+="Dist3ShapeModel;Dist3DistributionType;Dist3UserFormFactorFnct;Dist3UserVolumeFnct;"
947//      ListOfStrings+="Dist4ShapeModel;Dist4DistributionType;Dist4UserFormFactorFnct;Dist4UserVolumeFnct;"
948//      ListOfStrings+="Dist5ShapeModel;Dist5DistributionType;Dist5UserFormFactorFnct;Dist5UserVolumeFnct;"
949//     
950//      String/g GaussEquation="P(x)=(1/(Width*sqrt(2*pi)) * exp(-(x-Mean)^2/(2*Width^2))"
951//      String/g LogNormalEquation="P(x)=(1/((x-Min)*Mean*sqrt(2*pi)) * exp(-ln((x-Mean)/sdev)^2/(2*sdev^2))"
952//      String/g LSWEquation="P(x)=A*(loc^2*exp(-loc/(1.5-loc)))/((1.5-loc)^(11/3)*(3+loc)^(7/3))"
953//      String/g PowerLawEquation="P(x)= x ^ -(1+(6-slope))"
954//     
955//      variable i
956//      //and here we create them
957//      for(i=0;i<itemsInList(ListOfVariables);i+=1)   
958//              IN2G_CreateItem("variable",StringFromList(i,ListOfVariables))
959//      endfor         
960//                             
961//      for(i=0;i<itemsInList(ListOfStrings);i+=1)     
962//              IN2G_CreateItem("string",StringFromList(i,ListOfStrings))
963//      endfor 
964//      //cleanup after possible previous fitting stages...
965//      Wave/Z CoefNames=root:Packages:SAS_Modeling:CoefNames
966//      Wave/Z CoefficientInput=root:Packages:SAS_Modeling:CoefficientInput
967//      KillWaves/Z CoefNames, CoefficientInput
968//     
969//      IR1S_SetInitialValues()
970//end
971//
972//
973////*****************************************************************************************************************
974////*****************************************************************************************************************
975////*****************************************************************************************************************
976////*****************************************************************************************************************
977////*****************************************************************************************************************
978//
979//Function IR1S_SetInitialValues()
980//      //and here set default values...
981//
982//      string OldDf=getDataFolder(1)
983//      setDataFolder root:Packages:SAS_Modeling
984//      NVAR UseQRSData=root:Packages:SAS_Modeling:UseQRSData
985//      NVAR UseIndra2data=root:Packages:SAS_Modeling:UseIndra2data
986//      NVAR NumberOfDistributions=root:Packages:SAS_Modeling:NumberOfDistributions
987//      NVAR DisplayND=root:Packages:SAS_Modeling:DisplayND
988//      NVAR DisplayVD=root:Packages:SAS_Modeling:DisplayVD
989//      NVAR FitSASBackground=root:Packages:SAS_Modeling:FitSASBackground
990//      NVAR UseNumberDistribution=root:Packages:SAS_Modeling:UseNumberDistribution
991//      NVAR UseVolumeDistribution=root:Packages:SAS_Modeling:UseVolumeDistribution                                             
992//      NVAR UpdateAutomatically=root:Packages:SAS_Modeling:UpdateAutomatically
993//     
994//      if (UseQRSData)
995//              UseIndra2data=0
996//      endif
997//      NumberOfDistributions=0
998//      DisplayND=0
999//      DisplayVD=1
1000//     
1001//      if (FitSASBackground==0)
1002//              FitSASBackground=1
1003//      endif
1004//     
1005//      if (UseNumberDistribution==0 && UseVolumeDistribution==0)
1006//               UseVolumeDistribution=1
1007//               UseNumberDistribution=0
1008//      endif
1009//             
1010//      NVAR UseLSQF
1011//      NVAR UseGenOpt
1012//      if(UseLSQF+UseGenOpt!=1)
1013//              UseLSQF=1
1014//              UseGenOpt=0
1015//      endif
1016//     
1017//      UpdateAutomatically=0
1018//
1019//      //and here we set distribution specific parameters....
1020//     
1021//      IR1S_SetInitialValuesForAdist(1)        //dist 1
1022//      IR1S_SetInitialValuesForAdist(2)        //dist 2
1023//      IR1S_SetInitialValuesForAdist(3)        //dist 3
1024//      IR1S_SetInitialValuesForAdist(4)        //dist 4
1025//      IR1S_SetInitialValuesForAdist(5)        //dist 5
1026//
1027//      setDataFolder oldDF
1028//     
1029//end   
1030//
1031//
1032////*****************************************************************************************************************
1033////*****************************************************************************************************************
1034////*****************************************************************************************************************
1035////*****************************************************************************************************************
1036////*****************************************************************************************************************
1037//
1038//Function IR1S_SetInitialValuesForAdist(distNum)
1039//      variable distNum
1040//      //default values for distribution 1
1041//      string OldDf=GetDataFolder(1)
1042//     
1043//      setDataFOlder root:Packages:SAS_Modeling
1044//     
1045//      SVAR testStr =$("Dist"+num2str(distNum)+"UserFormFactorFnct")
1046//      if(strlen(testStr)<1)
1047//              testStr = "IR1T_ExampleSphereFFPoints"
1048//      endif
1049//      SVAR testStr =$("Dist"+num2str(distNum)+"UserVolumeFnct")
1050//      if(strlen(testStr)<1)
1051//              testStr = "IR1T_ExampleSphereVolume"
1052//      endif
1053//     
1054//      NVAR testVar=$("Dist"+num2str(distNum)+"NumberOfPoints")
1055//      if (testVar==0)
1056//               testVar=50
1057//      endif
1058//      NVAR testVar=$("Dist"+num2str(distNum)+"ScatShapeParam1")
1059//      if(testVar==0)
1060//               testVar=1
1061//      endif
1062//      NVAR testVar=$("Dist"+num2str(distNum)+"ScatShapeParam2")
1063//      if (testVar==0)
1064//               testVar=1
1065//      endif
1066//      NVAR testVar=$("Dist"+num2str(distNum)+"ScatShapeParam3")
1067//      if (testVar==0)
1068//               testVar=1
1069//      endif
1070//     
1071//      NVAR testVar=$("Dist"+num2str(distNum)+"NegligibleFraction")
1072//      if (testVar==0)
1073//               testVar=0.01
1074//      endif
1075//      NVAR testVar=$("Dist"+num2str(distNum)+"VolHighLimit")
1076//      if (testVar==0)
1077//               testVar=0.99
1078//      endif
1079//      NVAR testVar=$("Dist"+num2str(distNum)+"VolLowLimit")
1080//      if (testVar==0)
1081//               testVar=0.00001
1082//      endif
1083//      NVAR testVar=$("Dist"+num2str(distNum)+"VolFraction")
1084//      if (testVar==0)
1085//               testVar=0.05
1086//      endif
1087//      NVAR testVar=$("Dist"+num2str(distNum)+"FitVol")
1088//      if (testVar==0)
1089//               testVar=1
1090//      endif
1091//      NVAR testVar=$("Dist"+num2str(distNum)+"FitShape")
1092//      if (testVar==0)
1093//               testVar=1
1094//      endif
1095//      NVAR testVar=$("Dist"+num2str(distNum)+"FitLocation")
1096//      if (testVar==0)
1097//               testVar=0
1098//      endif
1099//      NVAR testVar=$("Dist"+num2str(distNum)+"FitScale")
1100//      if (testVar==0)
1101//               testVar=1
1102//      endif
1103//      NVAR testVar=$("Dist"+num2str(distNum)+"Contrast")
1104//      if (testVar==0)
1105//               testVar=100
1106//      endif
1107//      NVAR testVar=$("Dist"+num2str(distNum)+"Scale")
1108//      if (testVar==0)
1109//              if (distNum==1)
1110//                               testVar=100
1111//              endif
1112//              if (distNum==2)
1113//                               testVar=400
1114//              endif
1115//              if (distNum==3)
1116//                               testVar=800
1117//              endif
1118//              if (distNum==4)
1119//                               testVar=1600
1120//              endif
1121//              if (distNum==5)
1122//                               testVar=3200
1123//              endif
1124//      endif
1125//      NVAR testVar=$("Dist"+num2str(distNum)+"Location")
1126//      if (testVar==0)
1127//               testVar=0
1128//      endif
1129//      NVAR testVar=$("Dist"+num2str(distNum)+"Shape")
1130//      if (testVar==0)
1131//               testVar=0.5
1132//      endif
1133//      NVAR testVar=$("Dist"+num2str(distNum)+"LocHighLimit")
1134//      if (testVar==0)
1135//               testVar=1000000
1136//      endif
1137//      NVAR testVar=$("Dist"+num2str(distNum)+"LocLowLimit")
1138//      if (testVar==0)
1139//               testVar=10
1140//      endif
1141//      NVAR testVar=$("Dist"+num2str(distNum)+"ScaleHighLimit")
1142//      if (testVar==0)
1143//               testVar=100000
1144//      endif
1145//      NVAR testVar=$("Dist"+num2str(distNum)+"ScaleLowLimit")
1146//      if (testVar==0)
1147//               testVar=5
1148//      endif
1149//      NVAR testVar=$("Dist"+num2str(distNum)+"ShapeHighLimit")
1150//      if (testVar==0)
1151//               testVar=0.9
1152//      endif
1153//      NVAR testVar=$("Dist"+num2str(distNum)+"ShapeLowLimit")
1154//      if (testVar==0)
1155//               testVar=0.1
1156//      endif
1157//      NVAR testVar=$("Dist"+num2str(distNum)+"LocStep")
1158//      if (testVar==0)
1159//               testVar=50
1160//      endif
1161//      NVAR testVar=$("Dist"+num2str(distNum)+"ShapeStep")
1162//      if (testVar==0)
1163//               testVar=0.1
1164//      endif
1165//      NVAR testVar=$("Dist"+num2str(distNum)+"ScaleStep")
1166//      if (testVar==0)
1167//               testVar=10
1168//      endif
1169//      SVAR testStr=$("Dist"+num2str(distNum)+"ShapeModel")
1170//      if(strlen(testStr)==0)
1171//              testStr="spheroid"
1172//      endif
1173//      SVAR testStr=$("Dist"+num2str(distNum)+"DistributionType")
1174//      if(strlen(testStr)==0)
1175//              testStr="LogNormal"
1176//      endif
1177//     
1178//      NVAR testVar=$("Dist"+num2str(distNum)+"FitScatShapeParam1")
1179//      if (testVar==0)
1180//               testVar=0
1181//      endif
1182//      NVAR testVar=$("Dist"+num2str(distNum)+"FitScatShapeParam2")
1183//      if (testVar==0)
1184//               testVar=0
1185//      endif
1186//      NVAR testVar=$("Dist"+num2str(distNum)+"FitScatShapeParam3")
1187//      if (testVar==0)
1188//               testVar=0
1189//      endif
1190//      NVAR testVar=$("Dist"+num2str(distNum)+"UseInterference")
1191//      if (testVar==0)
1192//               testVar=0
1193//      endif
1194//      NVAR testVar=$("Dist"+num2str(distNum)+"InterferencePhi")
1195//      if (testVar==0)
1196//               testVar=1
1197//      endif
1198//      NVAR testVar=$("Dist"+num2str(distNum)+"InterferencePhiHL")
1199//      if (testVar==0)
1200//               testVar=8
1201//      endif
1202//      NVAR testVar=$("Dist"+num2str(distNum)+"InterferenceEta")
1203//      if (testVar==0)
1204//               testVar=200
1205//      endif
1206//      NVAR testVar=$("Dist"+num2str(distNum)+"InterferenceEtaLL")
1207//      if (testVar==0)
1208//               testVar=0
1209//      endif
1210//      NVAR testVar=$("Dist"+num2str(distNum)+"InterferenceEtaHL")
1211//      if (testVar==0)
1212//               testVar=10000
1213//      endif
1214//
1215//      setDataFolder oldDf
1216//end
1217//
1218
1219//*****************************************************************************************************************
1220//*****************************************************************************************************************
1221//*****************************************************************************************************************
1222//*****************************************************************************************************************
1223//*****************************************************************************************************************
1224
1225Function IR1_GraphMeasuredData(Package)
1226        string Package  //tells me, if this is called from Unified or LSQF
1227        //this function graphs data into the various graphs as needed
1228       
1229        string oldDf=GetDataFolder(1)
1230        setDataFolder root:Packages:SAS_Modeling
1231        SVAR DataFolderName
1232        SVAR IntensityWaveName
1233        SVAR QWavename
1234        SVAR ErrorWaveName
1235        variable cursorAposition, cursorBposition
1236       
1237        //fix for liberal names
1238        IntensityWaveName = PossiblyQuoteName(IntensityWaveName)
1239        QWavename = PossiblyQuoteName(QWavename)
1240        ErrorWaveName = PossiblyQuoteName(ErrorWaveName)
1241       
1242        WAVE/Z test=$(DataFolderName+IntensityWaveName)
1243        if (!WaveExists(test))
1244                abort "Error in IntensityWaveName wave selection"
1245        endif
1246        cursorAposition=0
1247        cursorBposition=numpnts(test)-1
1248        WAVE/Z test=$(DataFolderName+QWavename)
1249        if (!WaveExists(test))
1250                abort "Error in QWavename wave selection"
1251        endif
1252        WAVE/Z test=$(DataFolderName+ErrorWaveName)
1253        if (!WaveExists(test))
1254                abort "Error in ErrorWaveName wave selection"
1255        endif
1256        Duplicate/O $(DataFolderName+IntensityWaveName), OriginalIntensity
1257        Duplicate/O $(DataFolderName+QWavename), OriginalQvector
1258        Duplicate/O $(DataFolderName+ErrorWaveName), OriginalError
1259        Redimension/D OriginalIntensity, OriginalQvector, OriginalError
1260        wavestats /Q OriginalQvector
1261        if(V_min<0)
1262                OriginalQvector = OriginalQvector[p]<=0 ? NaN : OriginalQvector[p]
1263        endif
1264        IN2G_RemoveNaNsFrom3Waves(OriginalQvector,OriginalIntensity, OriginalError)
1265        NVAR/Z SubtractBackground=root:Packages:SAS_Modeling:SubtractBackground
1266        if(NVAR_Exists(SubtractBackground) && (cmpstr(Package,"Unified")==0))
1267                OriginalIntensity =OriginalIntensity - SubtractBackground
1268        endif
1269        NVAR/Z UseSlitSmearedData=root:Packages:SAS_Modeling:UseSlitSmearedData
1270        if(NVAR_Exists(UseSlitSmearedData) && (cmpstr(Package,"LSQF")==0))
1271                if(UseSlitSmearedData)
1272                        NVAR SlitLength=root:Packages:SAS_Modeling:SlitLength
1273                        variable tempSL=NumberByKey("SlitLength", note(OriginalIntensity) , "=" , ";")
1274                        if(numtype(tempSL)==0)
1275                                SlitLength=tempSL
1276                        endif
1277                endif
1278        endif
1279        NVAR/Z UseSMRData=root:Packages:SAS_Modeling:UseSMRData
1280        if(NVAR_Exists(UseSMRData) && (cmpstr(Package,"Unified")==0))
1281                if(UseSMRData)
1282                        NVAR SlitLengthUnif=root:Packages:SAS_Modeling:SlitLengthUnif
1283                        variable tempSL1=NumberByKey("SlitLength", note(OriginalIntensity) , "=" , ";")
1284                        if(numtype(tempSL1)==0)
1285                                SlitLengthUnif=tempSL1
1286                        endif
1287                endif
1288        endif
1289       
1290       
1291        if (cmpstr(Package,"Unified")==0)               //called from unified
1292                KillWIndow/Z IR1_LogLogPlotU
1293                Execute ("IR1_LogLogPlotU()")
1294        elseif (cmpstr(Package,"LSQF")==0)
1295                DoWindow IR1_LogLogPlotLSQF
1296                if (V_flag)
1297                        cursorAposition=pcsr(A,"IR1_LogLogPlotLSQF")
1298                        cursorBposition=pcsr(B,"IR1_LogLogPlotLSQF")
1299                        KillWIndow/Z IR1_LogLogPlotLSQF
1300                endif
1301                Execute ("IR1_LogLogPlotLSQF()")
1302                cursor/P/W=IR1_LogLogPlotLSQF A, OriginalIntensity,cursorAposition
1303                cursor/P/W=IR1_LogLogPlotLSQF B, OriginalIntensity,cursorBposition
1304        endif
1305       
1306        Duplicate/O $(DataFolderName+IntensityWaveName), OriginalIntQ4
1307        Duplicate/O $(DataFolderName+QWavename), OriginalQ4
1308        Duplicate/O $(DataFolderName+ErrorWaveName), OriginalErrQ4
1309        Redimension/D OriginalIntQ4, OriginalQ4, OriginalErrQ4
1310        wavestats /Q OriginalQ4
1311        if(V_min<0)
1312                OriginalQ4 = OriginalQ4[p]<=0 ? NaN : OriginalQ4[p]
1313        endif
1314        IN2G_RemoveNaNsFrom3Waves(OriginalQ4,OriginalIntQ4, OriginalErrQ4)
1315
1316        if(NVAR_Exists(SubtractBackground) && (cmpstr(Package,"Unified")==0))
1317                OriginalIntQ4 =OriginalIntQ4 - SubtractBackground
1318        endif
1319       
1320        OriginalQ4=OriginalQ4^4
1321        OriginalIntQ4=OriginalIntQ4*OriginalQ4
1322        OriginalErrQ4=OriginalErrQ4*OriginalQ4
1323
1324        if (cmpstr(Package,"Unified")==0)               //called from unified
1325                KillWIndow/Z IR1_IQ4_Q_PlotU
1326                Execute ("IR1_IQ4_Q_PlotU()")
1327        elseif (cmpstr(Package,"LSQF")==0)
1328                KillWIndow/Z IR1_IQ4_Q_PlotLSQF
1329                Execute ("IR1_IQ4_Q_PlotLSQF()")
1330        endif
1331        setDataFolder oldDf
1332end
1333
1334
1335//*****************************************************************************************************************
1336//*****************************************************************************************************************
1337//*****************************************************************************************************************
1338//*****************************************************************************************************************
1339//*****************************************************************************************************************
1340
1341Proc  IR1_IQ4_Q_PlotLSQF()
1342        PauseUpdate; Silent 1           // building window...
1343        String fldrSav= GetDataFolder(1)
1344        SetDataFolder root:Packages:SAS_Modeling:
1345        Display /W=(283.5,228.5,761.25,383)/K=1  OriginalIntQ4 vs OriginalQvector as "IQ4_Q_Plot"
1346        DoWIndow/C IR1_IQ4_Q_PlotLSQF
1347        ModifyGraph mode(OriginalIntQ4)=3
1348        ModifyGraph msize(OriginalIntQ4)=1
1349        ModifyGraph log=1
1350        ModifyGraph mirror=1
1351        Label left "\\Z"+IN2G_LkUpDfltVar("AxisLabelSize")+"Intensity * Q^4"
1352        Label bottom "\\Z"+IN2G_LkUpDfltVar("AxisLabelSize")+"Q [A\\S-1\\M]"
1353        ErrorBars/Y=1 OriginalIntQ4 Y,wave=(OriginalErrQ4,OriginalErrQ4)
1354        TextBox/C/N=DateTimeTag/F=0/A=RB/E=2/X=2.00/Y=1.00 "\\Z07"+date()+", "+time()   
1355        TextBox/C/N=SampleNameTag/F=0/A=LB/E=2/X=2.00/Y=1.00 "\\Z07"+DataFolderName+IntensityWaveName   
1356        //and now some controls
1357//      ControlBar 30
1358//      Button SaveStyle size={80,20}, pos={50,5},proc=IR1U_StyleButtonCotrol,title="Save Style"
1359//      Button ApplyStyle size={80,20}, pos={150,5},proc=IR1U_StyleButtonCotrol,title="Apply Style"
1360        SetDataFolder fldrSav
1361        Execute/P("AutoPositionWindow/M=1 /R=IR1_LogLogPlotLSQF IR1_IQ4_Q_PlotLSQF")
1362        Execute/P("Dowindow/F IR1_LogLogPlotLSQF")
1363EndMacro
1364
1365
1366//*****************************************************************************************************************
1367//*****************************************************************************************************************
1368//*****************************************************************************************************************
1369//*****************************************************************************************************************
1370//*****************************************************************************************************************
1371
1372//Window IR1_IQ4_Q_PlotLSQF() : Graph
1373//      PauseUpdate; Silent 1           // building window...
1374//      String fldrSav= GetDataFolder(1)
1375//      SetDataFolder root:Packages:SAS_Modeling:
1376//      Display /W=(295.5,237.5,753.75,421.25)/K=1  OriginalIntQ4 vs OriginalQvector as "IQ4_Q_Plot"
1377//      SetDataFolder fldrSav
1378//      ModifyGraph mode=3
1379//      ModifyGraph msize=1
1380//      ModifyGraph log=1
1381//      ModifyGraph mirror=1
1382//      Label left "Intensity * Q^4"
1383//      Label bottom "Q [A\\S-1\\M]"
1384//      Legend/W=IR1_IQ4_Q_Plot/N=text0/J/F=0/A=MC/X=-29.74/Y=37.76 "\\s(OriginalIntQ4) Experimental intensity * Q^4"
1385//      ErrorBars/Y=1 OriginalIntQ4 Y,wave=(:Packages:SAS_Modeling:OriginalErrQ4,:Packages:SAS_Modeling:OriginalErrQ4)
1386//      //and now some controls
1387//      ControlBar 30
1388//      Button SaveStyle size={80,20}, pos={50,5},proc=IR1U_StyleButtonCotrol,title="Save Style"
1389//      Button ApplyStyle size={80,20}, pos={150,5},proc=IR1U_StyleButtonCotrol,title="Apply Style"
1390//EndMacro
1391
1392
1393//*****************************************************************************************************************
1394//*****************************************************************************************************************
1395//*****************************************************************************************************************
1396//*****************************************************************************************************************
1397//*****************************************************************************************************************
1398
1399Proc  IR1_LogLogPlotLSQF()
1400        PauseUpdate; Silent 1           // building window...
1401        String fldrSav= GetDataFolder(1)
1402        SetDataFolder root:Packages:SAS_Modeling:
1403        Display /W=(282.75,37.25,759.75,208.25)/K=1  OriginalIntensity vs OriginalQvector as "LogLogPlot"
1404        DoWIndow/C IR1_LogLogPlotLSQF
1405        ModifyGraph mode(OriginalIntensity)=3
1406        ModifyGraph msize(OriginalIntensity)=1
1407        ModifyGraph log=1
1408        ModifyGraph mirror=1
1409        ShowInfo
1410        Label left "\\Z"+IN2G_LkUpDfltVar("AxisLabelSize")+"Intensity [cm\\S-1\\M]"
1411        Label bottom "\\Z"+IN2G_LkUpDfltVar("AxisLabelSize")+"Q [A\\S-1\\M]"
1412        Legend/W=IR1_LogLogPlotLSQF/N=text0/J/F=0/A=MC/X=32.03/Y=38.79 "\\F"+IN2G_LkUpDfltStr("FontType")+"\\Z"+IN2G_LkUpDfltVar("LegendSize")+"\\s(OriginalIntensity) Experimental intensity"
1413        ErrorBars/Y=1 OriginalIntensity Y,wave=(OriginalError,OriginalError)
1414        //and now some controls
1415        TextBox/C/N=DateTimeTag/F=0/A=RB/E=2/X=2.00/Y=1.00 "\\Z07"+date()+", "+time()   
1416        TextBox/C/N=SampleNameTag/F=0/A=LB/E=2/X=2.00/Y=1.00 "\\Z07"+DataFolderName+IntensityWaveName   
1417//      ControlBar 30
1418//      Button SaveStyle size={80,20}, pos={50,5},proc=IR1U_StyleButtonCotrol,title="Save Style"
1419//      Button ApplyStyle size={80,20}, pos={150,5},proc=IR1U_StyleButtonCotrol,title="Apply Style"
1420        SetDataFolder fldrSav
1421        Execute /P("AutoPositionWindow/M=0 /R=IR1R_ControlPanel IR1_LogLogPlotLSQF")
1422EndMacro
1423
1424
1425//*****************************************************************************************************************
1426//*****************************************************************************************************************
1427//*****************************************************************************************************************
1428//*****************************************************************************************************************
1429//*****************************************************************************************************************
1430
1431Function IR1_CopyDataBackToFolder(StandardOrUser)
1432        string StandardOrUser
1433        //here we need to copy the final data back to folder
1434        //before that we need to also attach note to teh waves with the results
1435       
1436        string OldDf=getDataFOlder(1)
1437        setDataFolder root:Packages:SAS_Modeling
1438       
1439        Wave Distdiameters=root:Packages:SAS_Modeling:Distdiameters
1440        Wave TotalNumberDist=root:Packages:SAS_Modeling:TotalNumberDist
1441        Wave TotalVolumeDist=root:Packages:SAS_Modeling:TotalVolumeDist
1442        Wave DistModelIntensity=root:Packages:SAS_Modeling:DistModelIntensity
1443        Wave ModelQvector=root:Packages:SAS_Modeling:ModelQvector
1444       
1445        NVAR NumberOfDistributions=root:Packages:SAS_Modeling:NumberOfDistributions
1446        SVAR DataFolderName=root:Packages:SAS_Modeling:DataFolderName
1447       
1448        string UsersComment, ExportSeparateDistributions
1449        UsersComment="Result from Modeling "+date()+"  "+time()
1450        ExportSeparateDistributions="No"
1451        Prompt UsersComment, "Modify comment to be saved with these results"
1452        Prompt ExportSeparateDistributions, "Export separately populations data", popup, "No;Yes"
1453        DoPrompt "Need input for saving data", UsersComment, ExportSeparateDistributions
1454        if (V_Flag)
1455                abort
1456        endif
1457
1458        Duplicate/O Distdiameters, tempDistdiameters
1459        Duplicate/O TotalNumberDist, tempTotalNumberDist
1460        Duplicate/O TotalVolumeDist, tempTotalVolumeDist
1461        Duplicate/O DistModelIntensity, tempDistModelIntensity
1462        Duplicate/O ModelQvector, tempModelQvector
1463        string ListOfWavesForNotes="tempDistdiameters;tempTotalNumberDist;tempTotalVolumeDist;tempDistModelIntensity;tempModelQvector;"
1464
1465        IR1_AppendWaveNote(ListOfWavesForNotes,StandardOrUser)          //append wave notes
1466       
1467        variable j,i
1468        If(cmpstr(ExportSeparateDistributions,"Yes")==0)
1469                for(j=1;j<=NumberOfDistributions;j+=1)          //copy local populations
1470                        Wave tempDia=$("Dist"+num2str(j)+"diameters")           
1471                        Wave tempNumDis=$("Dist"+num2str(j)+"NumberDist")               
1472                        Wave tempVolDist=$("Dist"+num2str(j)+"VolumeDist")     
1473                        Duplicate/O tempDia, $("tempDist"+num2str(j)+"diameters")               
1474                        Duplicate/O tempNumDis, $("tempDist"+num2str(j)+"NumberDist")           
1475                        Duplicate/O tempVolDist, $("tempDist"+num2str(j)+"VolumeDist") 
1476                        ListOfWavesForNotes="tempDist"+num2str(j)+"diameters;tempDist"+num2str(j)+"NumberDist;tempDist"+num2str(j)+"VolumeDist;"
1477                        IR1_AppendWNOfDist(j,ListOfWavesForNotes, StandardOrUser)
1478                endfor
1479        endif
1480
1481        //need to change direction if user uses modeling here...
1482        if(stringmatch(DataFolderName,"root:Packages*"))
1483                string NewDataFolderStr="root:SASModels:"
1484                string tempNewDatFldrName=""
1485                Prompt NewDataFolderStr, "Trying to save model to Packages folder, suggest change the folder"
1486                DoPrompt "Override the data saving target",  NewDataFolderStr
1487                if(V_Flag)
1488                        abort
1489                endif
1490                SetDataFolder root:
1491                if(!Stringmatch(NewDataFolderStr[Strlen(NewDataFolderStr)-1],":"))
1492                        NewDataFolderStr+=":"
1493                endif   
1494                for(i=0;i<ItemsInList(NewDataFolderStr,":");i+=1)
1495                        if(!StringMatch(StringFromList(i,NewDataFolderStr,":"),"root"))
1496                                NewDataFolder/O/S $(StringFromList(i,NewDataFolderStr,":"))
1497                        endif
1498                        tempNewDatFldrName+=possiblyQuoteName(StringFromList(i,NewDataFolderStr,":"))+":"
1499                endfor
1500                setDataFolder $tempNewDatFldrName
1501        else
1502                setDataFolder $DataFolderName   
1503        endif
1504        string tempname
1505        variable ii=0
1506        For(ii=0;ii<1000;ii+=1)
1507                tempname="ModelingDiameters_"+num2str(ii)
1508                if (checkname(tempname,1)==0)
1509                        break
1510                endif
1511        endfor
1512        Duplicate /O tempDistdiameters, $tempname
1513        Wave MytempWave=$tempname
1514        IN2G_AppendorReplaceWaveNote(tempname,"UsersComment",UsersComment)
1515        IN2G_AppendorReplaceWaveNote(tempname,"Wname",tempname)
1516        IN2G_AppendorReplaceWaveNote(tempname,"Units","A")
1517        Redimension/D MytempWave
1518       
1519        tempname="ModelingNumberDistribution_"+num2str(ii)
1520        Duplicate /O tempTotalNumberDist, $tempname
1521        Wave MytempWave=$tempname
1522        IN2G_AppendorReplaceWaveNote(tempname,"UsersComment",UsersComment)
1523        IN2G_AppendorReplaceWaveNote(tempname,"Wname",tempname)
1524        IN2G_AppendorReplaceWaveNote(tempname,"Units","1/cm3")
1525        Redimension/D MytempWave
1526       
1527        tempname="ModelingVolumeDistribution_"+num2str(ii)
1528        Duplicate /O tempTotalVolumeDist, $tempname
1529        Wave MytempWave=$tempname
1530        IN2G_AppendorReplaceWaveNote(tempname,"UsersComment",UsersComment)
1531        IN2G_AppendorReplaceWaveNote(tempname,"Wname",tempname)
1532        IN2G_AppendorReplaceWaveNote(tempname,"Units","fraction")
1533        Redimension/D MytempWave
1534       
1535        tempname="ModelingIntensity_"+num2str(ii)
1536        Duplicate /O tempDistModelIntensity, $tempname
1537        Wave MytempWave=$tempname
1538        IN2G_AppendorReplaceWaveNote(tempname,"UsersComment",UsersComment)
1539        IN2G_AppendorReplaceWaveNote(tempname,"Wname",tempname)
1540        IN2G_AppendorReplaceWaveNote(tempname,"Units","cm-1")
1541        Redimension/D MytempWave
1542       
1543        tempname="ModelingQvector_"+num2str(ii)
1544        Duplicate /O tempModelQvector, $tempname
1545        Wave MytempWave=$tempname
1546        IN2G_AppendorReplaceWaveNote(tempname,"UsersComment",UsersComment)
1547        IN2G_AppendorReplaceWaveNote(tempname,"Wname",tempname)
1548        IN2G_AppendorReplaceWaveNote(tempname,"Units","A-1")
1549        Redimension/D MytempWave
1550
1551        If(cmpstr(ExportSeparateDistributions,"Yes")==0)
1552                for(j=1;j<=NumberOfDistributions;j+=1)          //copy local populations
1553                        Wave tempDia=$("root:Packages:SAS_Modeling:tempDist"+num2str(j)+"diameters")           
1554                        Wave tempNumDis=$("root:Packages:SAS_Modeling:tempDist"+num2str(j)+"NumberDist")               
1555                        Wave tempVolDist=$("root:Packages:SAS_Modeling:tempDist"+num2str(j)+"VolumeDist")       
1556       
1557                        tempname="ModelingDia_Pop"+num2str(j)+"_"+num2str(ii)
1558                        Duplicate/O tempDia, $tempname
1559                        Wave MytempWave=$tempname
1560                        IN2G_AppendorReplaceWaveNote(tempname,"DataFolderInIgor",DataFolderName)
1561                        IN2G_AppendorReplaceWaveNote(tempname,"UsersComment",UsersComment)
1562                        IN2G_AppendorReplaceWaveNote(tempname,"Wname",tempname)
1563                        IN2G_AppendorReplaceWaveNote(tempname,"Units","A-1")
1564                        Redimension/D MytempWave
1565                               
1566                        tempname="ModelingNumDist_Pop"+num2str(j)+"_"+num2str(ii)
1567                        Duplicate/O tempNumDis, $tempname
1568                        Wave MytempWave=$tempname
1569                        IN2G_AppendorReplaceWaveNote(tempname,"DataFolderInIgor",DataFolderName)
1570                        IN2G_AppendorReplaceWaveNote(tempname,"UsersComment",UsersComment)
1571                        IN2G_AppendorReplaceWaveNote(tempname,"Wname",tempname)
1572                        IN2G_AppendorReplaceWaveNote(tempname,"Units","1/cm3")
1573                        Redimension/D MytempWave
1574       
1575                        tempname="ModelingVolDist_Pop"+num2str(j)+"_"+num2str(ii)
1576                        Duplicate/O tempVolDist, $tempname
1577                        Wave MytempWave=$tempname
1578                        IN2G_AppendorReplaceWaveNote(tempname,"DataFolderInIgor",DataFolderName)
1579                        IN2G_AppendorReplaceWaveNote(tempname,"UsersComment",UsersComment)
1580                        IN2G_AppendorReplaceWaveNote(tempname,"Wname",tempname)
1581                        IN2G_AppendorReplaceWaveNote(tempname,"Units","fraction")
1582                        Redimension/D MytempWave
1583                       
1584                        KillWaves/Z tempVolDist, tempNumDis, tempDia
1585                endfor
1586        endif
1587        setDataFolder root:Packages:SAS_Modeling
1588
1589        Killwaves/Z tempDistdiameters,tempTotalNumberDist,tempTotalVolumeDist, tempDistModelIntensity, tempModelQvector
1590        setDataFolder OldDf
1591end
1592
1593
1594//*****************************************************************************************************************
1595//*****************************************************************************************************************
1596//*****************************************************************************************************************
1597//*****************************************************************************************************************
1598//*****************************************************************************************************************
1599
1600Function IR1_AppendWaveNote(ListOfWavesForNotes, StandardOrUser)
1601        string ListOfWavesForNotes, StandardOrUser
1602       
1603        string oldDf=GetDataFolder(1)
1604        setDataFolder root:Packages:SAS_Modeling
1605
1606        NVAR NumberOfDistributions=root:Packages:SAS_Modeling:NumberOfDistributions
1607
1608        NVAR SASBackground=root:Packages:SAS_Modeling:SASBackground
1609        NVAR FitSASBackground=root:Packages:SAS_Modeling:FitSASBackground
1610        NVAR UseNumberDistribution=root:Packages:SAS_Modeling:UseNumberDistribution
1611        NVAR UseInterference=root:Packages:SAS_Modeling:UseInterference
1612        NVAR UseSlitSmearedData=root:Packages:SAS_Modeling:UseSlitSmearedData
1613        NVAR SlitLength=root:Packages:SAS_Modeling:SlitLength
1614        SVAR DataFolderName=root:Packages:SAS_Modeling:DataFolderName
1615        string ExperimentName=IgorInfo(1)
1616        variable i, cursorAposition, cursorBposition
1617        For(i=0;i<ItemsInList(ListOfWavesForNotes);i+=1)
1618
1619                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"IgorExperimentName",ExperimentName)
1620                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"DataFolderinIgor",DataFolderName)
1621               
1622                if (cmpstr(StandardOrUser,"standard")==0)
1623                        if (UseNumberDistribution)
1624                                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"DistributionTypeModelled", "Number distribution")   
1625                        else
1626                                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes), "DistributionTypeModelled", "Volume distribution") 
1627                        endif   
1628                else
1629                                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes), "DistributionTypeModelled","User defined distributions used, modified volume and diameters")                       
1630                endif
1631                //handle the cursors
1632                CursorAPosition=pcsr(A, "IR1_LogLogPlotLSQF")
1633                CursorBPosition=pcsr(B, "IR1_LogLogPlotLSQF")
1634                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"CursorAPosition",num2str(CursorAPosition))
1635                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"CursorBPosition",num2str(CursorBPosition))
1636               
1637                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"NumberOfModelledDistributions",num2str(NumberOfDistributions))
1638                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"UseInterference",num2str(UseInterference))
1639                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"UseSlitSmearedData",num2str(UseSlitSmearedData))
1640                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"SlitLength",num2str(SlitLength))
1641
1642                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"SASBackground",num2str(SASBackground))
1643                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"FitSASBackground",num2str(FitSASBackground))
1644        endfor
1645
1646        For(i=1;i<=NumberOfDistributions;i+=1)
1647                IR1_AppendWNOfDist(i,ListOfWavesForNotes, StandardOrUser)
1648        endfor
1649
1650        setDataFolder oldDF
1651
1652end
1653
1654
1655//*****************************************************************************************************************
1656//*****************************************************************************************************************
1657//*****************************************************************************************************************
1658//*****************************************************************************************************************
1659//*****************************************************************************************************************
1660
1661Function IR1_AppendWNOfDist(DistNum,ListOfWavesForNotes, StandardOrUser)
1662        variable DistNum
1663        string ListOfWavesForNotes, StandardOrUser
1664       
1665        string oldDf=GetDataFolder(1)
1666        setDataFolder root:Packages:SAS_Modeling
1667
1668        NVAR DistVolFraction=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"VolFraction")
1669        NVAR DistVolFractionError=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"VolFractionError")
1670        NVAR DistScatShapeParam1=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"ScatShapeParam1")
1671        NVAR DistScatShapeParam2=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"ScatShapeParam2")
1672        NVAR DistScatShapeParam3=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"ScatShapeParam3")
1673        NVAR DistScatShapeParam4=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"ScatShapeParam4")
1674        NVAR DistScatShapeParam5=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"ScatShapeParam5")
1675        SVAR DistShapeModel=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"ShapeModel")
1676
1677        if (cmpstr(StandardOrUser,"standard")==0)
1678                NVAR DistNumberOfPoints=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"NumberOfPoints")
1679                NVAR DistContrast=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"Contrast")
1680                NVAR DistLocation=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"Location")
1681                NVAR DistScale=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"Scale")
1682                NVAR DistShape=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"Shape")
1683                NVAR DistLocationError=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"LocationError")
1684                NVAR DistScaleError=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"ScaleError")
1685                NVAR DistShapeError=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"ShapeError")
1686                SVAR DistDistributionType=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"DistributionType")
1687                NVAR DistNegligibleFraction= $("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"NegligibleFraction")
1688                NVAR DistUseInterference= $("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"UseInterference")
1689                NVAR DistInterferencePhi= $("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"InterferencePhi")
1690                NVAR DistInterferenceEta= $("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"InterferenceEta")
1691                NVAR DistInterferencePhiError= $("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"InterferencePhiError")
1692                NVAR DistInterferenceEtaError= $("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"InterferenceEtaError")
1693                NVAR DistFitInterferencePhi= $("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"FitInterferencePhi")
1694                NVAR DistFitInterferenceEta= $("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"FitInterferenceEta")
1695                NVAR DistFitShape= $("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"FitShape")
1696                NVAR DistFitLocation= $("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"FitLocation")
1697                NVAR DistFitScale= $("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"FitScale")
1698                NVAR DistFitVol= $("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"FitVol")
1699        else
1700                NVAR DistDiamAddition=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"DiamAddition")
1701                NVAR DistDiamMulitplier=$("root:Packages:SAS_Modeling:Dist"+num2str(DistNum)+"DiamMulitplier")
1702        endif           
1703       
1704        SVAR GaussEquation=root:Packages:SAS_Modeling:GaussEquation
1705        SVAR LogNormalEquation=root:Packages:SAS_Modeling:LogNormalEquation
1706        SVAR LSWEquation=root:Packages:SAS_Modeling:LSWEquation
1707        SVAR PowerLawEquation=root:Packages:SAS_Modeling:PowerLawEquation
1708       
1709        variable i
1710        For(i=0;i<ItemsInList(ListOfWavesForNotes);i+=1)
1711                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"ShapeModel",DistShapeModel)
1712                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"ScatShapeParam1",num2str(DistScatShapeParam1))
1713                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"ScatShapeParam2",num2str(DistScatShapeParam2))
1714                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"ScatShapeParam3",num2str(DistScatShapeParam3))
1715                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"ScatShapeParam4",num2str(DistScatShapeParam4))
1716                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"ScatShapeParam5",num2str(DistScatShapeParam5))
1717
1718                if (cmpstr(StandardOrUser,"standard")==0)
1719                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"DistributionType",DistDistributionType)
1720                        if (cmpstr(DistDistributionType,"Gauss")==0)
1721                                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"Formula",GaussEquation)             
1722                        endif
1723                        if (cmpstr(DistDistributionType,"LSW")==0)
1724                                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"Formula",LSWEquation)               
1725                        endif
1726                        if (cmpstr(DistDistributionType,"LogNormal")==0)
1727                                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"Formula",LogNormalEquation)         
1728                        endif
1729                        if (cmpstr(DistDistributionType,"PowerLaw")==0)
1730                                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"Formula",PowerLawEquation)         
1731                        endif
1732                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"NegligibleFraction",num2str(DistNegligibleFraction))
1733
1734                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"FitShape",num2str(DistFitShape))
1735                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"FitLocation",num2str(DistFitLocation))
1736                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"FitScale",num2str(DistFitScale))
1737                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"FitVol",num2str(DistFitVol))
1738                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"VolFraction",num2str(DistVolFraction))
1739                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"Location",num2str(DistLocation))
1740                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"Scale",num2str(DistScale))
1741                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"Shape",num2str(DistShape))
1742                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"VolFractionError",num2str(DistVolFractionError))
1743                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"LocationError",num2str(DistLocationError))
1744                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"ScaleError",num2str(DistScaleError))
1745                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"ShapeError",num2str(DistShapeError))
1746                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"NumberOfPoints",num2str(DistNumberOfPoints))
1747                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"Contrast",num2str(DistContrast))
1748                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"DistributionType",DistDistributionType)
1749                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"UseInterference",num2str(DistUseInterference))
1750                        if (DistUseInterference)
1751                                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"InterferencePhi",num2str(DistInterferencePhi))
1752                                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"InterferenceEta",num2str(DistInterferenceEta))
1753                                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"InterferencePhiError",num2str(DistInterferencePhiError))
1754                                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"InterferenceEtaError",num2str(DistInterferenceEtaError))
1755                                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"FitInterferencePhi",num2str(DistFitInterferencePhi))
1756                                IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"FitInterferenceEta",num2str(DistFitInterferenceEta))
1757                        endif
1758                else
1759                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"VolFraction",num2str(DistVolFraction))
1760                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"DiamAddition",num2str(DistDiamAddition))
1761                        IN2G_AppendorReplaceWaveNote(stringFromList(i,ListOfWavesForNotes),"Dist"+num2str(DistNum)+"DiamMultiplier",num2str(DistDiamMulitplier))
1762                endif
1763        endfor
1764
1765        setDataFolder OldDf
1766end
1767
1768
1769//*****************************************************************************************************************
1770//*****************************************************************************************************************
1771//*****************************************************************************************************************
1772//*****************************************************************************************************************
1773//*****************************************************************************************************************
1774
1775Function IR1_ExportASCIIResults(standardOrUser)
1776        string standardOrUser                   //"standard" or "User", depending where called from...
1777
1778        //here we need to copy the export results out of Igor
1779        //before that we need to also attach note to teh waves with the results
1780       
1781        string OldDf=getDataFOlder(1)
1782        setDataFolder root:Packages:SAS_Modeling
1783       
1784        Wave Distdiameters=root:Packages:SAS_Modeling:Distdiameters
1785        Wave TotalNumberDist=root:Packages:SAS_Modeling:TotalNumberDist
1786        Wave TotalVolumeDist=root:Packages:SAS_Modeling:TotalVolumeDist
1787       
1788        NVAR NumberOfDistributions=root:Packages:SAS_Modeling:NumberOfDistributions
1789        SVAR DataFolderName=root:Packages:SAS_Modeling:DataFolderName
1790       
1791        Duplicate/O Distdiameters, tempDistdiameters
1792        Duplicate/O TotalNumberDist, tempTotalNumberDist
1793        Duplicate/O TotalVolumeDist, tempTotalVolumeDist
1794        string ListOfWavesForNotes="tempDistdiameters;tempTotalNumberDist;tempTotalVolumeDist;"
1795       
1796        IR1_AppendWaveNote(ListOfWavesForNotes, standardOrUser)
1797       
1798        string Comments="Record of Data evaluation with Irena SAS modeling macros;" +note(tempDistdiameters)+"diameters[A]\t\tNumberDist[1/cm3]\t\tVolumeDist[cm3/cm3]\r"
1799        variable pos=0
1800        variable ComLength=strlen(Comments)
1801        Do
1802                pos=strsearch(Comments, ";", pos+5)
1803                Comments=Comments[0,pos-1]+"\r#\t"+Comments[pos+1,inf]
1804        while (pos>0)
1805
1806        string filename1
1807        filename1=StringFromList(ItemsInList(DataFolderName,":")-1, DataFolderName,":")+"_SAS_model.txt"
1808        variable refnum
1809
1810        Open/D/T=".txt"/M="Select file to save data to" refnum as filename1
1811        filename1=S_filename
1812        if (strlen(filename1)==0)
1813                abort
1814        endif
1815
1816       
1817        String nb = "Notebook0"
1818        NewNotebook/N=$nb/F=0/V=0/K=0/W=(5.25,40.25,558,408.5) as "ExportData"
1819        Notebook $nb defaultTab=20, statusWidth=238, pageMargins={72,72,72,72}
1820        Notebook $nb font="Arial", fSize=10, fStyle=0, textRGB=(0,0,0)
1821        Notebook $nb text=Comments[1,strlen(Comments)-2]       
1822       
1823       
1824        SaveNotebook $nb as filename1
1825        DoWindow /K $nb
1826        Save/A/G/M="\r\n" tempDistdiameters,tempTotalNumberDist,tempTotalVolumeDist as filename1         
1827       
1828
1829
1830        Killwaves/Z tempDistdiameters,tempTotalNumberDist,tempTotalVolumeDist
1831        setDataFolder OldDf
1832end
1833       
1834
1835//****************************************************************
1836//****************************************************************
1837//***********************************
1838//***********************************
1839
1840Function IR2C_CheckIrenaUpdate(CalledFromMenu)
1841        variable CalledFromMenu
1842
1843        IN2G_ReadIrenaGUIPackagePrefs(0)
1844        NVAR LastUpdateCheckIrena=root:Packages:IrenaConfigFolder:LastUpdateCheckIrena 
1845        if(datetime - LastUpdateCheckIrena >30 * 24 * 60 * 60 || CalledFromMenu)
1846                        //call check version procedure and advise user on citations
1847                        IR2C_CheckVersions()
1848                        IN2G_SubmitCheckRecordToWeb("Irena "+num2str(CurrentIrenaVersionNumber))
1849                        LastUpdateCheckIrena = datetime
1850                        IN2G_SaveIrenaGUIPackagePrefs(0)
1851                        IN2G_GetAndDisplayUpdateMessage()
1852        endif
1853        if (str2num(stringByKey("IGORVERS",IgorInfo(0)))<7.05)
1854                        DoAlert /T="Igor update message :"  0, "Igor has been updated to version 7.05 or higher. Please, update your Igor to the latest version." 
1855                        BrowseURL "http://www.wavemetrics.com/support/versions.htm"
1856        endif
1857       
1858end
1859
1860//****************************************************************
1861//****************************************************************
1862static Function IR2C_CheckVersions()
1863        string PackageString   
1864        //create list of Igor procedure files on this machine
1865        IN2G_ListIgorProcFiles()
1866        DoWIndow CheckForIrenaUpdatePanel
1867        if(V_Flag)
1868                DoWIndow/F CheckForIrenaUpdatePanel                                                             
1869        else
1870                Execute("CheckForIrenaUpdatePanel()")                   
1871        endif
1872        //Irena code
1873        string OldDf=GetDataFolder(1)
1874        //create location for the results waves...
1875        NewDataFolder/O/S root:Packages
1876        NewDataFolder/O/S root:Packages:UseProcedureFiles
1877        variable/g InstalledIrenaVersion
1878        variable/g WebIrenaVersion             
1879        InstalledIrenaVersion = IN2G_FindFileVersion("Boot Irena1 modeling.ipf")       
1880        WebIrenaVersion = IN2G_CheckForNewVersion("Irena")
1881        if(numtype(WebIrenaVersion)!=0)
1882                Print "Check for latest Irena version failed. Check your Internet connection. Try later again..."
1883        endif
1884        //DeleteFile /Z /P=tempPath "Boot Irena1 modeling.ipf" 
1885        SetDataFOlder OldDf
1886end     
1887
1888//****************************************************************
1889//****************************************************************
1890//***********************************
1891//***********************************
1892
1893
1894//Motofit paper [J. Appl. Cryst. 39, 273-276]
1895//http://scripts.iucr.org/cgi-bin/paper?S0021889806005073
1896//J. Appl. Cryst. (2006). 39, 273-276    [ doi:10.1107/S0021889806005073 ]
1897//A. Nelson, Co-refinement of multiple-contrast neutron/X-ray reflectivity data using MOTOFIT
1898//
1899
1900
1901
1902Function IR2C_CheckVersionButtonProc(ba) : ButtonControl
1903        STRUCT WMButtonAction &ba
1904
1905        switch( ba.eventCode )
1906                case 2: // mouse up
1907                        // click code here
1908                        if(stringmatch(ba.ctrlName,"OpenIrenaWebPage"))
1909                                //open web page with Irena
1910                                BrowseURL "https://usaxs.xray.aps.anl.gov/software/irena"
1911                        endif
1912                        if(stringmatch(ba.ctrlName,"OpenIrenaManuscriptWebPage"))
1913                                //open web page with Irena
1914                                BrowseURL "http://dx.doi.org/10.1107/S0021889809002222"
1915                        endif
1916                        if(stringmatch(ba.ctrlName,"OpenGCManuscriptWebPage"))
1917                                //doi:10.1007/s11661-009-9950-x
1918                                BrowseURL "http://www.jomgateway.net/ArticlePage.aspx?DOI=10.1007/s11661-009-9950-x"
1919                        endif
1920                        if(stringmatch(ba.ctrlName,"OpenMotofitManuscriptWebPage"))
1921                                //doi:10.1007/s11661-009-9950-x
1922                                BrowseURL "http://scripts.iucr.org/cgi-bin/paper?S0021889806005073"
1923                        endif
1924                        if(stringmatch(ba.ctrlName,"OpenUFManuscriptWebPage"))
1925                                BrowseURL "http://scripts.iucr.org/cgi-bin/paper?S0021889895005292"
1926                        endif           
1927                       
1928                        break
1929                case -1: // control being killed
1930                        break
1931        endswitch
1932
1933        return 0
1934End
1935//****************************************************************
1936//****************************************************************
1937//***********************************
1938//***********************************
1939
1940Window CheckForIrenaUpdatePanel() : Panel
1941        PauseUpdate; Silent 1           // building window...
1942        NewPanel /W=(116,68,880,550)/K=1 as "Irena check for updates"
1943        SetDrawLayer UserBack
1944        SetDrawEnv fsize= 20,fstyle= 3,textrgb= (0,0,65535)
1945        DrawText 114,37,"Once-per-month reminder to check for Irena update"
1946        SetDrawEnv fsize= 14,fstyle= 3,textrgb= (65535,0,0)
1947        DrawText 27,110,"Reminder: When publishing data analyzed using Irena package, please cite following manuscripts:"
1948        SetDrawEnv textrgb= (0,0,65535)
1949        DrawText 27,133,"J. Ilavsky and P. Jemian, Irena: tool suite for modeling and analysis of small- angle scattering "
1950        SetDrawEnv textrgb= (0,0,65535)
1951        DrawText 27,158,"J. Appl. Cryst. (2009). 42, 347–353"
1952        SetDrawEnv textrgb= (0,0,65535)
1953        DrawText 27,205,"Glassy Carbon Absolute Int. Calibration: F. Zhang, J. Ilavsky, G. G. Long, J. P.G. Quintana, "
1954        SetDrawEnv textrgb= (0,0,65535)
1955        DrawText 27,230,"A. J. Allen, and P. Jemian, Glassy Carbon as an Absolute Intensity Calibration Standard"
1956        SetDrawEnv textrgb= (0,0,65535)
1957        DrawText 27,255,"for Small-Angle Scattering, MMTA, DOI: 10.1007/s11661-009-9950-x"
1958        SetDrawEnv textrgb= (0,0,65535)
1959        DrawText 27,320,"Reflectivity: A. Nelson, Co-refinement of multiple-contrast neutron/X-ray reflectivity"
1960        SetDrawEnv textrgb= (0,0,65535)
1961        DrawText 27,345,"data using MOTOFIT, Appl. Cryst. (2006). 39, 273-276"
1962        SetDrawEnv textrgb= (0,0,65535)
1963        DrawText 27,390,"Unified Fit: G. Beaucage, Approximations Leading to a Unified Exponential/Power-Law "
1964        SetDrawEnv textrgb= (0,0,65535)
1965        DrawText 27,415,"Approach to Small-Angle Scattering, J. Appl. Cryst. (1995). 28, 717-728"
1966
1967        SetDrawEnv fstyle= 2,fsize= 10,textrgb= (0,0,0)
1968        DrawText 10,470,"This tool runs automatically every 30 days on each computer. It can be also called from the SAS sub-menu as \"Check for updates\""
1969
1970        SetVariable InstalledIrenaVersion,pos={48,56},size={199,15},bodyWidth=100,title="Installed Irena Version"
1971        SetVariable InstalledIrenaVersion,help={"This is the current Irena version installed"}
1972        SetVariable InstalledIrenaVersion,fStyle=1
1973        SetVariable InstalledIrenaVersion,limits={0,0,0},value= root:Packages:UseProcedureFiles:InstalledIrenaVersion,noedit= 1
1974        SetVariable WebIrenaVersion,pos={297,56},size={183,15},bodyWidth=100,title="Web Irena Version"
1975        SetVariable WebIrenaVersion,help={"This is the current Irena version installed"}
1976        SetVariable WebIrenaVersion,fStyle=1
1977        SetVariable WebIrenaVersion,limits={0,0,0},value= root:Packages:UseProcedureFiles:WebIrenaVersion,noedit= 1
1978        Button OpenIrenaWebPage,pos={551,53},size={150,20},proc=IR2C_CheckVersionButtonProc,title="Open Irena web page"
1979        Button OpenIrenaManuscriptWebPage,pos={551,143},size={150,20},proc=IR2C_CheckVersionButtonProc,title="Manuscript web page"
1980        Button OpenGCManuscriptWebPage,pos={551,240},size={150,20},proc=IR2C_CheckVersionButtonProc,title="Manuscript web page"
1981        Button OpenMotofitManuscriptWebPage,pos={551,325},size={150,20},proc=IR2C_CheckVersionButtonProc,title="Manuscript web page"
1982        Button OpenUFManuscriptWebPage,pos={551,402},size={150,20},proc=IR2C_CheckVersionButtonProc,title="Manuscript web page"
1983EndMacro
1984//****************************************************************
1985//****************************************************************
1986//***********************************
1987//***********************************
1988//              IR1F_CreateFldrStrctMain
1989//****************************************************************
1990//****************************************************************
1991
1992
1993
1994
1995Function IR1F_CreateFldrStrctMain()
1996
1997        IN2G_CheckScreenSize("height",450)
1998        IR1F_InitializeCreateFldrStrct()
1999        KillWIndow/Z IR1F_CreateQRSFldrStructure
2000        Execute ("IR1F_CreateQRSFldrStructure()")
2001       
2002end
2003
2004
2005//************************************************************************************************************
2006//************************************************************************************************************
2007//************************************************************************************************************
2008//************************************************************************************************************
2009
2010Proc IR1F_CreateQRSFldrStructure()
2011        PauseUpdate; Silent 1           // building window...
2012        NewPanel /K=1/W=(135,98,551.25,392.75) as "Create QRS Folder Structure"
2013        DoWIndow/C IR1F_CreateQRSFldrStructure
2014        SetDrawLayer UserBack
2015        SetDrawEnv fsize= 16,fstyle= 3,textrgb= (0,0,65280)
2016        DrawText 64,30,"Create folder structure for QRS data"
2017        PopupMenu SelectFolderWithData,pos={19,49},size={171,21},proc=IR1F_PopMenuProc,title="Select folder with data :"
2018        PopupMenu SelectFolderWithData,mode=1,popvalue="---",value= #"\"---;\"+IR3D_GenStringOfFolders(\"root:\",0, 1,0,0,\"\")"
2019        SetVariable NewFolderForData,pos={16,88},size={380,19},proc=IR1F_SetVarProc,title="Where to create new data folders?"
2020        SetVariable NewFolderForData,value= root:Packages:CreateFldrStructure:NewFldrPath
2021        Button CreateFolders,pos={124,177},size={150,20}, proc=IR1F_ButtonProc,title="Convert structure"
2022        SetVariable BackupFolder,pos={45,128},size={350,19},proc=IR1F_SetVarProc,title="Backup old data to"
2023        SetVariable BackupFolder,value= root:Packages:CreateFldrStructure:NewBackupFldr
2024EndMacro
2025
2026//************************************************************************************************************
2027//************************************************************************************************************
2028//************************************************************************************************************
2029//************************************************************************************************************
2030
2031
2032Function IR1F_PopMenuProc(ctrlName,popNum,popStr) : PopupMenuControl
2033        String ctrlName
2034        Variable popNum
2035        String popStr
2036
2037        if (cmpstr(ctrlName,"SelectFolderWithData")==0)
2038                SVAR FolderWithData=root:Packages:CreateFldrStructure:FolderWithData
2039                FolderWithData = popStr
2040       
2041        endif
2042End
2043
2044//************************************************************************************************************
2045//************************************************************************************************************
2046//************************************************************************************************************
2047//************************************************************************************************************
2048
2049Function IR1F_SetVarProc(ctrlName,varNum,varStr,varName) : SetVariableControl
2050        String ctrlName
2051        Variable varNum
2052        String varStr
2053        String varName
2054       
2055        if(cmpstr("NewFolderForData",ctrlName)==0)
2056       
2057        endif
2058        if(cmpstr("BackupFolder",ctrlName)==0)
2059       
2060        endif
2061
2062       
2063End
2064
2065//************************************************************************************************************
2066//************************************************************************************************************
2067//************************************************************************************************************
2068//************************************************************************************************************
2069
2070Function IR1F_ButtonProc(ctrlName) : ButtonControl
2071        String ctrlName
2072       
2073        if(cmpstr(ctrlName,"CreateFolders")==0)
2074                IR1F_CreateFolders()
2075        endif
2076
2077End
2078
2079//************************************************************************************************************
2080//************************************************************************************************************
2081//************************************************************************************************************
2082//************************************************************************************************************
2083
2084
2085Function  IR1F_InitializeCreateFldrStrct()
2086
2087        NewDataFolder/O/S root:Packages
2088        NewDataFolder/O/S root:Packages:CreateFldrStructure
2089       
2090        string ListOfStrings
2091        ListOfStrings = "ListOfDataAvailable;FolderWithData;NewFldrPath;NewBackupFldr;"
2092
2093        variable i
2094        //and here we create them
2095        for(i=0;i<itemsInList(ListOfStrings);i+=1)     
2096                IN2G_CreateItem("string",StringFromList(i,ListOfStrings))
2097                SVAR test = $(StringFromList(i,ListOfStrings))
2098                test = ""
2099        endfor         
2100
2101        //set starting values here
2102        SVAR NewFldrPath
2103        NewFldrPath = "root:SAS:"
2104        SVAR NewBackupFldr
2105        NewBackupFldr = "root:SAS_Data_Backup:"
2106end     
2107
2108//************************************************************************************************************
2109//************************************************************************************************************
2110//************************************************************************************************************
2111//************************************************************************************************************
2112
2113Function  IR1F_CreateFolders()
2114
2115        SVAR ListOfDataAvailable=root:Packages:CreateFldrStructure:ListOfDataAvailable
2116        SVAR FolderWithData=root:Packages:CreateFldrStructure:FolderWithData
2117        SVAR NewFldrPath=root:Packages:CreateFldrStructure:NewFldrPath
2118        SVAR NewBackupFldr=root:Packages:CreateFldrStructure:NewBackupFldr
2119
2120        //first let's see if there are any data available for conversion
2121        ListOfDataAvailable=IR1F_CreateListQRSOfData(FolderWithData)
2122       
2123        if(strlen(NewBackupFldr)>0)
2124                IR1F_BackupData(ListOfDataAvailable, FolderWithData, NewBackupFldr)
2125        endif
2126       
2127       
2128        IR1F_MoveData(ListOfDataAvailable, FolderWithData,NewFldrPath )
2129       
2130end
2131
2132//************************************************************************************************************
2133//************************************************************************************************************
2134//************************************************************************************************************
2135//************************************************************************************************************
2136
2137
2138Function        IR1F_MoveData(ListOfDataAvailable, FolderWithData,NewFldrPath )
2139        string ListOfDataAvailable, FolderWithData,NewFldrPath
2140       
2141        string OldDf
2142        OldDf = getDataFOlder(1)
2143       
2144        variable i
2145        string RWvname,QWvName,SWvName, SaFldrName
2146        if(cmpstr(":",NewFldrPath[strlen(NewFldrPath)-1] )!=0)
2147                NewFldrPath+=":"
2148        endif
2149        variable numberOfFldrLevels=ItemsInList(NewFldrPath,":")
2150       
2151        setDataFolder root:
2152        for(i=0;i<numberOfFldrLevels;i+=1)
2153                if(cmpstr(StringFromList(i, NewFldrPath ,":"),"root")!=0)
2154                        NewDataFolder /O/S $(StringFromList(i, NewFldrPath ,":"))
2155                endif
2156        endfor
2157        //QRS data
2158        For(i=0;i<ItemsInList(ListOfDataAvailable);i+=1)
2159                setDataFolder FolderWithData
2160                RWvname = StringFromList(i, ListOfDataAvailable)
2161                QWvName = "Q"+RWvname[1,inf]
2162                SWvName = "S"+RWvname[1,inf]
2163                SaFldrName = RWvname[1,inf]
2164                if(cmpstr(SaFldrName[0],"_")==0)
2165                        SaFldrName=SaFldrName[1,inf]
2166                endif
2167                Wave/Z RWave = $RWvname
2168                Wave/Z QWave = $QWvname
2169                Wave/Z SWave = $SWvname
2170                if(WaveExists(RWave) && WaveExists(QWave) &&WaveExists(SWave))
2171                        SetDataFolder NewFldrPath
2172                        if(DataFolderExists(SaFldrName))
2173                                SaFldrName=UniqueName(SaFldrName,11,0)
2174                                SaFldrName=CleanupName(SaFldrName, 0 )
2175                        endif
2176                        NewDataFolder/O/S $(SaFldrName)
2177                        Wave/Z testR= $(RWvname)
2178                        Wave/Z testQ= $(QWvname)
2179                        Wave/Z testS= $(SWvname)
2180                        if((!WaveExists(testR))&&(!WaveExists(testQ))&&(!WaveExists(testS)))           
2181                                MoveWave RWave, $(RWvname)
2182                                MoveWave QWave, $(QWvname)
2183                                MoveWave SWave, $(SWvname)
2184                        else
2185                                Print "Cannot move waves into folder : "+SaFldrName+" since there are already waves with same name"
2186                        endif
2187                        //KillWaves/Z RWave, QWave, SWave
2188                elseif(WaveExists(RWave) && WaveExists(QWave))
2189                        SetDataFolder NewFldrPath
2190                        if(DataFolderExists(SaFldrName))
2191                                SaFldrName=UniqueName(SaFldrName,11,0)
2192                                SaFldrName=CleanupName(SaFldrName, 0 )
2193                        endif
2194                        NewDataFolder/O/S $(SaFldrName)
2195                        Wave/Z testR= $(RWvname)
2196                        Wave/Z testQ= $(QWvname)
2197                        if((!WaveExists(testR))&&(!WaveExists(testQ)))         
2198                                MoveWave RWave, $(RWvname)
2199                                MoveWave QWave, $(QWvname)
2200                        else
2201                                Print "Cannot move waves into folder : "+SaFldrName+" since there are already waves with same name"
2202                        endif
2203                        //KillWaves/Z RWave, QWave, SWave
2204                endif
2205        endfor
2206        //QIS data
2207        For(i=0;i<ItemsInList(ListOfDataAvailable);i+=1)
2208                setDataFolder FolderWithData
2209                RWvname = StringFromList(i, ListOfDataAvailable)
2210                QWvName = RWvname[0,strlen(RWvname)-2]+"Q"
2211                SWvName = RWvname[0,strlen(RWvname)-2]+"S"
2212                SaFldrName = RWvname[0,strlen(RWvname)-2]
2213                if(cmpstr(SaFldrName[strlen(RWvname)-2],"_")==0)
2214                        SaFldrName=SaFldrName[0,strlen(RWvname)-3]
2215                endif
2216                Wave/Z RWave = $RWvname
2217                Wave/Z QWave = $QWvname
2218                Wave/Z SWave = $SWvname
2219                if(WaveExists(RWave) && WaveExists(QWave) &&WaveExists(SWave))
2220                        SetDataFolder NewFldrPath
2221                        if(DataFolderExists(SaFldrName))
2222                                SaFldrName=UniqueName(SaFldrName,11,0)
2223                                SaFldrName=CleanupName(SaFldrName, 0 )
2224                        endif
2225                        NewDataFolder/O/S $(SaFldrName)
2226                        Wave/Z testR= $(RWvname)
2227                        Wave/Z testQ= $(QWvname)
2228                        Wave/Z testS= $(SWvname)
2229                        if((!WaveExists(testR))&&(!WaveExists(testQ))&&(!WaveExists(testS)))           
2230                                MoveWave RWave, $(RWvname)
2231                                MoveWave QWave, $(QWvname)
2232                                MoveWave SWave, $(SWvname)
2233                        else
2234                                Print "Cannot move waves into folder : "+SaFldrName+" since there are already waves with same name"
2235                        endif
2236                        //KillWaves/Z RWave, QWave, SWave
2237                elseif(WaveExists(RWave) && WaveExists(QWave))
2238                        SetDataFolder NewFldrPath
2239                        if(DataFolderExists(SaFldrName))
2240                                SaFldrName=UniqueName(SaFldrName,11,0)
2241                                SaFldrName=CleanupName(SaFldrName, 0 )
2242                        endif
2243                        NewDataFolder/O/S $(SaFldrName)
2244                        Wave/Z testR= $(RWvname)
2245                        Wave/Z testQ= $(QWvname)
2246                        if((!WaveExists(testR))&&(!WaveExists(testQ)))         
2247                                MoveWave RWave, $(RWvname)
2248                                MoveWave QWave, $(QWvname)
2249                        else
2250                                Print "Cannot move waves into folder : "+SaFldrName+" since there are already waves with same name"
2251                        endif
2252                        //KillWaves/Z RWave, QWave, SWave
2253                endif
2254        endfor
2255
2256        setDataFolder OldDf
2257
2258end
2259
2260//************************************************************************************************************
2261//************************************************************************************************************
2262//************************************************************************************************************
2263//************************************************************************************************************
2264
2265Function IR1F_BackupData(ListOfDataAvailable, FolderWithData, NewBackupFldr)
2266        string ListOfDataAvailable, FolderWithData, NewBackupFldr
2267       
2268        string OldDf
2269        OldDf = getDataFOlder(1)
2270       
2271        variable i
2272        string RWvname,QWvName,SWvName
2273        if(cmpstr(":",NewBackupFldr[strlen(NewBackupFldr)-1] )!=0)
2274                NewBackupFldr+=":"
2275        endif
2276        variable numberOfFldrLevels=ItemsInList(NewBackupFldr,":")
2277       
2278        setDataFolder root:
2279        for(i=0;i<numberOfFldrLevels;i+=1)
2280                if(cmpstr(StringFromList(i, NewBackupFldr ,":"),"root")!=0)
2281                        NewDataFolder /O/S $(StringFromList(i, NewBackupFldr ,":"))
2282                endif
2283        endfor
2284       
2285        setDataFolder FolderWithData
2286        //QRS DATA
2287        For(i=0;i<ItemsInList(ListOfDataAvailable);i+=1)
2288                RWvname = StringFromList(i, ListOfDataAvailable)
2289                QWvName = "Q"+RWvname[1,inf]
2290                SWvName = "S"+RWvname[1,inf]
2291                Wave/Z RWave = $RWvname
2292                Wave/Z QWave = $QWvname
2293                Wave/Z SWave = $SWvname
2294                if(WaveExists(RWave) && WaveExists(QWave) &&WaveExists(SWave))
2295                        Duplicate /O RWave, $(NewBackupFldr+possiblyquotename(RWvname))
2296                        Duplicate /O QWave, $(NewBackupFldr+possiblyquotename(QWvname))
2297                        Duplicate /O SWave, $(NewBackupFldr+possiblyquotename(SWvname))
2298                elseif(WaveExists(RWave) && WaveExists(QWave))
2299                        Duplicate /O RWave, $(NewBackupFldr+possiblyquotename(RWvname))
2300                        Duplicate /O QWave, $(NewBackupFldr+possiblyquotename(QWvname))
2301                endif
2302        endfor 
2303        //QIS data
2304        For(i=0;i<ItemsInList(ListOfDataAvailable);i+=1)
2305                RWvname = StringFromList(i, ListOfDataAvailable)
2306                QWvName = RWvname[0,strlen(RWvname)-2]+"Q"
2307                SWvName = RWvname[0,strlen(RWvname)-2]+"S"
2308                Wave/Z RWave = $RWvname
2309                Wave/Z QWave = $QWvname
2310                Wave/Z SWave = $SWvname
2311                if(WaveExists(RWave) && WaveExists(QWave) &&WaveExists(SWave))
2312                        Duplicate /O RWave, $(NewBackupFldr+possiblyquotename(RWvname))
2313                        Duplicate /O QWave, $(NewBackupFldr+possiblyquotename(QWvname))
2314                        Duplicate /O SWave, $(NewBackupFldr+possiblyquotename(SWvname))
2315                elseif(WaveExists(RWave) && WaveExists(QWave))
2316                        Duplicate /O RWave, $(NewBackupFldr+possiblyquotename(RWvname))
2317                        Duplicate /O QWave, $(NewBackupFldr+possiblyquotename(QWvname))
2318                endif
2319        endfor 
2320       
2321        setDataFOlder OldDf
2322end
2323
2324//************************************************************************************************************
2325//************************************************************************************************************
2326//************************************************************************************************************
2327//************************************************************************************************************
2328
2329Function/T IR1F_CreateListQRSOfData(FolderWithData)
2330        string FolderWithData
2331       
2332        string OldDf=GetDataFOlder(1)
2333        setDataFolder FolderWithData
2334       
2335        variable NumberOfAllWaves=CountObjects(FolderWithData, 1 )
2336        variable i
2337        string ListOfQRSWaves, TempRWaveName, TempQWaveName, TempSWaveName
2338        ListOfQRSWaves = ""
2339        string AllWaves=IN2G_CreateListOfItemsInFolder(FolderWithData, 2)
2340        //GetIndexedObjName(FolderWithData, 1, i )
2341        FOr(i=0;i<=NumberOfAllWaves;i+=1)
2342                TempRWaveName = StringFromList(i, AllWaves)
2343                if (cmpstr(TempRWaveName[0],"R")==0)    //the wave starts with R
2344                        TempQWaveName="Q"+TempRWaveName[1,inf]
2345                        TempSWaveName="S"+TempRWaveName[1,inf]
2346                        Wave/Z testQ=$(TempQWaveName)
2347                        Wave/Z testS=$(TempSWaveName)
2348                        if(WaveExists(testQ) && WaveExists(testS))
2349                                ListOfQRSWaves+=TempRWaveName+";"
2350                        elseif(WaveExists(testQ))
2351                                ListOfQRSWaves+=TempRWaveName+";"
2352                        endif           
2353                endif
2354        endfor
2355        //next try to handle QIS data
2356        FOr(i=0;i<=NumberOfAllWaves;i+=1)
2357                TempRWaveName = StringFromList(i, AllWaves)
2358                print TempRWaveName[strlen(TempRWaveName)-2,inf],"I"
2359                if (cmpstr(TempRWaveName[strlen(TempRWaveName)-1],"I")==0)      //the wave ends with i
2360                        TempQWaveName=TempRWaveName[0,strlen(TempRWaveName)-2]+"Q"
2361                        TempSWaveName=TempRWaveName[0,strlen(TempRWaveName)-2]+"S"
2362                        Wave/Z testQ=$(TempQWaveName)
2363                        Wave/Z testS=$(TempSWaveName)
2364                        if(WaveExists(testQ) && WaveExists(testS))
2365                                ListOfQRSWaves+=TempRWaveName+";"
2366                        elseif(WaveExists(testQ))
2367                                ListOfQRSWaves+=TempRWaveName+";"
2368                        endif           
2369                endif
2370        endfor
2371
2372        setDataFolder OldDf
2373        return ListOfQRSWaves
2374
2375end
2376
2377//************************************************************************************************************
2378//************************************************************************************************************
2379//************************************************************************************************************
2380//************************************************************************************************************
2381//*****************************************************************************************************************
2382//*****************************************************************************************************************
2383//*****************************************************************************************************************
2384//*****************************************************************************************************************
2385//*****************************************************************************************************************
2386
2387//****************   LSW   ***********************************************************
2388Function IR1_LSWProbability(x,location,scale, shape)
2389                variable x, location,scale, shape
2390        //this function calculates probability for LSW distribution
2391       
2392        variable result, reducedX
2393       
2394        reducedX=x/location
2395       
2396        result=(81/(2^(5/3))) * (reducedX^2 * exp(-1*(reducedX/(1.5-reducedX) ) ) ) / ( (1.5-reducedX)^(11/3) * (3+reducedX)^(7/3) )
2397       
2398        //this funny distribution reaches values (integral under the curve) of location
2399        //so we need to renormalize...
2400
2401        if (numtype(result)!=0)
2402                result=0
2403        endif
2404       
2405        return result/location
2406
2407end
2408
2409
2410//*****************************************************************************************************************
2411//*****************************************************************************************************************
2412//*****************************************************************************************************************
2413//*****************************************************************************************************************
2414//*****************************************************************************************************************
2415
2416Function IR1_LSWCumulative(xx,location,scale, shape)
2417                variable xx, location,scale, shape
2418        //this function calculates probability for LSW distribution
2419        //I do not have cumulative probability function, so it is done numerically... More complex and much more annoying...
2420        string OldDf=GetDataFolder(1)
2421        SetDataFolder root:Packages:SAS_Modeling
2422                       
2423        variable result, pointsNeeded=ceil(xx/30+30)
2424        //points neede is at least 30 and max out around 370 for 10000 A location
2425        make/D /O/N=(PointsNeeded) temp_LSWwav
2426       
2427        SetScale/P x 10,(xx/(numpnts(temp_LSWwav)-3)),"", temp_LSWwav   
2428        //this sets scale so the model wave x scale covers area from 10 A over the needed point...
2429       
2430        temp_LSWwav=IR1_LSWProbability(pnt2x(temp_LSWwav, p ),location,scale, shape)
2431       
2432        integrate /T temp_LSWwav
2433        //and at this point the temp_LSWwav has integral values in it...
2434        result = temp_LSWwav(xx) //here we get the value interpolated (linearly) for the needed point...
2435        KillWaves temp_LSWwav
2436        setDataFolder OldDf
2437        return result
2438end
2439
2440 
2441
2442//*****************************************************************************************************************
2443//*****************************************************************************************************************
2444//*****************************************************************************************************************
2445//*****************************************************************************************************************
2446//*****************************************************************************************************************
2447
2448//****************   Normal (Gauss) distribution   ***********************************************************
2449
2450Function IR1_GaussProbability(x,location,scale, shape)
2451                variable x, location,scale, shape
2452        //this function calculates probability for Gauss (normal) distribution
2453       
2454        variable result
2455       
2456        result=(exp(-((x-location)^2)/(2*scale^2)))/(scale*(sqrt(2*pi)))
2457
2458        if (numtype(result)!=0)
2459                result=0
2460        endif
2461       
2462        return result
2463end
2464
2465//*****************************************************************************************************************
2466//*****************************************************************************************************************
2467//*****************************************************************************************************************
2468//*****************************************************************************************************************
2469//*****************************************************************************************************************
2470
2471Function IR1_SchulzZimmProbability(x,MeanPos,Width, shape)
2472                variable x, MeanPos,Width, shape
2473        //this function calculates probability for Schulz-Zimm distribution
2474        //finished 3/17/2011, seems to work. 
2475        variable result, a, b
2476       
2477        b = 1/(width/(2*MeanPos))^2
2478        a = b / MeanPos
2479       
2480        if(b<70)
2481                result=( (a^(b+1))/gamma(b+1) * x^b / exp(a*x) )
2482        else                    //do it in logs to avoid large numbers
2483                result=exp(    (b+1)*ln(a)-  gammln(b+1) + B*ln(x) - (a*x) )
2484        endif
2485
2486        if (numtype(result)!=0)
2487                result=0
2488        endif
2489       
2490        return result
2491end
2492//*****************************************************************************************************************
2493//*****************************************************************************************************************
2494//*****************************************************************************************************************
2495//*****************************************************************************************************************
2496//*****************************************************************************************************************
2497
2498threadsafe Function IR1_ArdellProbNormalized(xval,MeanPos,np,NoP)
2499        variable xval, MeanPos,np, NoP
2500        //this function calculates probability for A
2501        variable result
2502        result = IR1_ArdellProbability(xval,MeanPos,np,NoP)
2503        Make/Free/N=200 NormWave
2504        variable start = max(1, MeanPos/20 )
2505        SetScale/I x  start, MeanPos*3,"", NormWave
2506        multithread NormWave = IR1_ArdellProbability(x,MeanPos,np,NoP)
2507        variable Normval = area(NormWave)
2508        return result / Normval
2509end     
2510
2511threadsafe Function IR1_ArdellProbability(x,MeanPos,np,NoP)
2512                variable x, MeanPos,np, NoP
2513        //this function calculates probability for Ardell distribution
2514        variable result, zp
2515        zp = x/MeanPos
2516        result = -3*Ardell_F(zp,np)*exp(Ardell_P(zp,np))       
2517        return result
2518end
2519
2520
2521
2522threadsafe static Function Ardell_F(zp,np)
2523        variable zp, np
2524        //note np = 2 to 3
2525        // zp = r/r0 = 0 - 3 max.
2526       
2527        variable result
2528        result = (zp*(np-1))^(np-1)
2529        result = result/((np^np * (zp-1))-(zp^np * (np-1)^(np-1)))
2530       
2531        return result
2532end
2533
2534threadsafe static Function Ardell_P(xp,np)
2535        variable xp, np
2536        make/Free tmpAF
2537        SetScale/I x 0,xp,"", tmpAF
2538        tmpAF = Ardell_F(x,np)
2539        return area(tmpAF)
2540end
2541
2542//*****************************************************************************************************************
2543//*****************************************************************************************************************
2544//*****************************************************************************************************************
2545//*****************************************************************************************************************
2546//*****************************************************************************************************************
2547
2548threadsafe Function IR1_ArdellCumulative(xpos,location,scale, shape)
2549        variable xpos, location,scale, shape
2550        //this function calcualtes cumulative probabliltiy for Ardell distribution
2551        //only scale is useful parameters here ans is 2-3...
2552        variable result
2553        Make/O/N=200/Free TempPWave, TepNorWave
2554        variable start = max(1, location/20 )
2555        start = min(start,xpos)
2556        SetScale/I x start,xpos,"", TempPWave
2557        SetScale/I x start,3*location,"", TepNorWave
2558        multithread TempPWave =  IR1_ArdellProbability(x,location,scale, shape)
2559        multithread TepNorWave =  IR1_ArdellProbability(x,location,scale, shape)
2560        result = area(TempPWave)/area(TepNorWave)
2561        return result
2562end
2563
2564//*****************************************************************************************************************
2565//*****************************************************************************************************************
2566//*****************************************************************************************************************
2567//*****************************************************************************************************************
2568//*****************************************************************************************************************
2569
2570Function IR1_SZCumulative(xpos,location,scale, shape)
2571        variable xpos, location,scale, shape
2572        //this function calcualtes cumulative probabliltiy for SZ distribution
2573        //until I find the formula for SZ I will use numberical method, slower but should work...
2574       
2575        variable result
2576        Make/O/N=500/Free tempSZDistWv
2577        SetScale/I x 0,xpos,"", tempSZDistWv
2578        tempSZDistWv =  IR1_SchulzZimmProbability(x,location,scale, shape)
2579//      doupdate
2580        result = area(tempSZDistWv  )
2581        return result
2582end
2583
2584
2585//*****************************************************************************************************************
2586//*****************************************************************************************************************
2587//*****************************************************************************************************************
2588//*****************************************************************************************************************
2589//*****************************************************************************************************************
2590
2591Function IR1_GaussCumulative(x,location,scale, shape)
2592        variable x, location,scale, shape
2593        //this function calcualtes cumulative probabliltiy for gauss (normal) distribution
2594       
2595        variable result, ReducedX
2596       
2597        ReducedX=(x-location)/scale
2598       
2599        result = (erf(ReducedX/sqrt(2))+1)/2
2600       
2601        return result
2602end
2603//*****************************************************************************************************************
2604//*****************************************************************************************************************
2605//*****************************************************************************************************************
2606//*****************************************************************************************************************
2607//*****************************************************************************************************************
2608
2609Function IR1_PowerLawCumulative(x, shape,startx,endx)
2610        variable x, endx,startx, shape
2611        //this function calculates cumulative probability for log-normal distribution
2612       
2613        variable result
2614       
2615        Make/O/N=1000 TempCumWv
2616        SetScale/I x startx, endx, TempCumWv
2617        TempCumWv = x^(-(7-shape))
2618       
2619        result = area(TempCumWv,startx, x)/area(TempCumWv,startx, endx)
2620        KillWaves TempCumWv
2621
2622        return result
2623
2624
2625end
2626//*****************************************************************************************************************
2627//*****************************************************************************************************************
2628//*****************************************************************************************************************
2629//*****************************************************************************************************************
2630//*****************************************************************************************************************
2631
2632Function IR1_PowerLawProbability(x, shape,diameterswv)
2633        variable x,  shape
2634        wave diameterswv
2635       
2636        //this function calculates cumulative probability for log-normal distribution
2637        duplicate/O diameterswv, tempCalcWvPowerLaw
2638       
2639        variable result
2640       
2641        tempCalcWvPowerLaw =  diameterswv^(-(7-shape))
2642        result =  (x^(-(7-shape))) / areaXY(diameterswv, tempCalcWvPowerLaw, 0, inf )
2643        killwaves/Z tempCalcWvPowerLaw
2644       
2645        return result
2646
2647
2648end
2649
2650
2651//*****************************************************************************************************************
2652//*****************************************************************************************************************
2653//*****************************************************************************************************************
2654//*****************************************************************************************************************
2655//*****************************************************************************************************************
2656
2657
2658//****************   Log-Normal distribution   ***********************************************************
2659
2660Function IR1_LogNormProbability(x,location,scale, shape)
2661        variable x, location, scale, shape
2662        //this function calculates probability for log-normal distribution
2663       
2664        variable result
2665       
2666        result = exp(-1*( ln( (x-location) / scale) )^2 / (2*shape^2) ) / (shape*sqrt(2*pi)*(x-location))
2667        if (numtype(result)!=0)
2668                result=0
2669        endif
2670        return result   
2671end     
2672
2673
2674
2675//*****************************************************************************************************************
2676//*****************************************************************************************************************
2677//*****************************************************************************************************************
2678//*****************************************************************************************************************
2679//*****************************************************************************************************************
2680
2681Function IR1_LogNormCumulative(x,location,scale, shape)
2682        variable x, location, scale, shape
2683        //this function calculates cumulative probability for log-normal distribution
2684       
2685        variable result, ReducedX
2686       
2687        ReducedX=(x-location)/scale
2688       
2689        result = (erf((ln(ReducedX)/shape)/sqrt(2))+1)/2
2690        if(numtype(result)!=0)
2691                result=0
2692        endif
2693
2694        return result
2695end
2696
2697
2698
2699//*****************************************************************************************************************
2700//*****************************************************************************************************************
2701////*****************************************************************************************************************
2702////*****************************************************************************************************************
2703////*****************************************************************************************************************
2704////*****************************************************************************************************************
2705////*****************************************************************************************************************
2706//
2707//
2708Function IR1L_AppendAnyText(TextToBeInserted)           //this function checks for existance of notebook
2709        string TextToBeInserted                                         //and appends text to the end of the notebook
2710        Silent 1
2711        TextToBeInserted=TextToBeInserted+"\r"
2712    SVAR/Z nbl=root:Packages:SAS_Modeling:NotebookName
2713        if(SVAR_exists(nbl))
2714                if (strsearch(WinList("*",";","WIN:16"),nbl,0)!=-1)                             //Logs data in Logbook
2715                        Notebook $nbl selection={endOfFile, endOfFile}
2716                        Notebook $nbl text=TextToBeInserted
2717                endif
2718        endif
2719end
2720
2721Function IR1L_AppendAnyPorodText(TextToBeInserted)              //**DWS
2722        string TextToBeInserted                                         //and appends text to the end of the notebook
2723        Silent 1
2724        TextToBeInserted=TextToBeInserted+"\r"
2725   SVAR/Z nbl=root:Packages:Irena_AnalUnifFit:PorodNotebookName
2726        if(SVAR_exists(nbl))
2727                if (strsearch(WinList("*",";","WIN:16"),nbl,0)==-1)                             //Create PorodAnalysisResults notebook if necessary
2728                        IR1_CreatePorodLogbook()               
2729                endif
2730                Notebook $nbl selection={endOfFile, endOfFile}
2731                Notebook $nbl text=TextToBeInserted             
2732        endif
2733end
2734//
2735//
2736//
2737//
2738Function IR1_PullUpLoggbook()
2739
2740        if(!DataFolderExists("root:Packages:SAS_Modeling"))
2741                abort "Notebook does not exist, folder does not exist,nothing exists... Did not initialize properly"
2742        endif
2743
2744        SVAR/Z nbl=root:Packages:SAS_Modeling:NotebookName
2745        if(!Svar_Exists(nbL))
2746                abort "Notebook does not exist, folder does not exist,nothing exists... Did not initialize properly"
2747        endif
2748        string nbLL=nbl
2749//      string nbLL="SAS_FitLog"
2750        Silent 1
2751        if (strsearch(WinList("*",";","WIN:16"),nbLL,0)!=-1)            ///Logbook exists
2752                DoWindow/F $nbLL
2753        endif
2754
2755end
2756//
2757Function IR1_CreatePorodLogbook()//***DWS
2758
2759        SVAR/Z nb=root:Packages:Irena_AnalUnifFit:PorodNotebookName
2760        if(!SVAR_Exists(nb))
2761                NewDataFolder/O root:Packages
2762                NewDataFolder/O root:Packages:Irena_AnalUnifFit
2763                String/G root:Packages:Irena_AnalUnifFit:PorodNotebookName=""
2764                SVAR nb=root:Packages:Irena_AnalUnifFit:PorodNotebookName
2765                nb="PorodAnalysisResults"
2766        endif
2767        Silent 1
2768        if (strsearch(WinList("*",";","WIN:16"),nb,0)!=-1)              ///Logbook exists
2769                DoWindow/HIDE=1 $nb
2770        else
2771                NewNotebook/N=$nb/F=1/V=0/K=3/W=(83,131,1766,800) as "PorodAnalysisResults"
2772                Notebook $nb defaultTab=144, statusWidth=238
2773                Notebook $nb showRuler=1, rulerUnits=1, updating={1, 60}
2774                Notebook $nb newRuler=Normal, justification=0, margins={0,0,468}, spacing={0,0,0}, tabs={180,252+1*8192,360+3*8192}, rulerDefaults={"Arial",10,0,(0,0,0)}
2775                Notebook $nb newRuler=logbookRuler, justification=0, margins={0,0,1578}, spacing={0,0,0}, tabs={204+1*8192,258+1*8192,319+1*8192,388+1*8192,432+1*8192,503+1*8192,580+1*8192,665+1*8192,746+1*8192,839+1*8192,912+1*8192,980+1*8192,1035+1*8192,1097+1*8192,1167+1*8192,1268+1*8192,1377+1*8192,1476+1*8192}, rulerDefaults={"Arial",14,1,(0,0,0)}
2776                Notebook $nb ruler=logbookRuler, fSize=10
2777                Notebook $nb text="rWave\tMethod\tStart\tEnd\tUseCsrs\tB[cm-1A-4]\tQv[Cm-1A-3 ]\tpiB/Q[m2/cm3]\tMinDens[g/cm3]\tMajDens[g/cm3]\tS"
2778                Notebook $nb text="amDens[g/cm3]\tphimin\tSv[m2/cm3]\tSm[m2/g]\tMinChord[A]\tMajChord[A]\t10^-10xSLmin[cm/g]\t10^-10xSLmaj[cm/g]\r"
2779                Notebook $nb fSize=-1
2780                Notebook $nb text="rWv\tMeth\tStart\tEnd\tCsrs\tB\tQv\tpiBoQ\tMinDen\tMajDen\tSamDen\tphimin\tSv\tSm\tMinCh\tMajCh\tSLmin \tSLmaj\r"
2781                Notebook $nb text="\r"
2782                DoWindow/HIDE=0 $nb
2783        endif
2784end
2785//
2786////*****************************************************************************************************************
2787////*****************************************************************************************************************
2788////*****************************************************************************************************************
2789////*****************************************************************************************************************
2790////*****************************************************************************************************************
2791//
2792
2793Function IR1_InsertDateAndTime(nbl)
2794        string nbl
2795       
2796        Silent 1
2797        string bucket11
2798        Variable now=datetime
2799        bucket11=Secs2Date(now,0)+",  "+Secs2Time(now,0) +"\r"
2800        //SVAR nbl=root:Packages:SAS_Modeling:NotebookName
2801        Notebook $nbl selection={endOfFile, endOfFile}
2802        Notebook $nbl text=bucket11
2803end
2804//
2805////*****************************************************************************************************************
2806////*****************************************************************************************************************
2807////*****************************************************************************************************************
2808////*****************************************************************************************************************
2809////*****************************************************************************************************************
2810////*****************************************************************************************************************
2811//*****************************************************************************************************************
2812//*****************************************************************************************************************
2813//
2814//Function IR1S_UpdateModeMedianMean()
2815//
2816//      NVAR NumberOfDistributions=root:Packages:SAS_Modeling:NumberOfDistributions
2817//     
2818//      variable i
2819//      For (i=1;i<=NumberOfDistributions;i+=1)
2820//              IR1S_UpdtSeparateMMM(i)
2821//      endfor
2822//end
2823//
2824//
2825Function IR1_CreateLoggbook()
2826
2827        SVAR/Z nbl=root:Packages:SAS_Modeling:NotebookName
2828        if(!SVAR_Exists(nbl))
2829                NewDataFolder/O root:Packages
2830                NewDataFolder/O root:Packages:SAS_Modeling
2831                String/G root:Packages:SAS_Modeling:NotebookName=""
2832                SVAR nbl=root:Packages:SAS_Modeling:NotebookName
2833                nbL="SAS_FitLog"
2834        endif
2835       
2836        string nbLL=nbl
2837       
2838        Silent 1
2839        if (strsearch(WinList("*",";","WIN:16"),nbL,0)!=-1)             ///Logbook exists
2840                DoWindow/B $nbl
2841        else
2842                NewNotebook/K=3/V=0/N=$nbl/F=1/V=1/W=(235.5,44.75,817.5,592.25) as nbl+": Irena Log"
2843                Notebook $nbl defaultTab=144, statusWidth=238, pageMargins={72,72,72,72}
2844                Notebook $nbl showRuler=1, rulerUnits=1, updating={1, 60}
2845                Notebook $nbl newRuler=Normal, justification=0, margins={0,0,468}, spacing={0,0,0}, tabs={2.5*72, 3.5*72 + 8192, 5*72 + 3*8192}, rulerDefaults={"Arial",10,0,(0,0,0)}
2846                Notebook $nbl ruler=Normal; Notebook $nbl  justification=1, rulerDefaults={"Arial",14,1,(0,0,0)}
2847                Notebook $nbl text="This is log results of processing SAS data with Irena package.\r"
2848                Notebook $nbl text="\r"
2849                Notebook $nbl ruler=Normal
2850                IR1_InsertDateAndTime(nbl)
2851        endif
2852
2853end
2854
2855
2856//*****************************************************************************************************************
2857//*****************************************************************************************************************
2858//*****************************************************************************************************************
2859//*****************************************************************************************************************
2860//*****************************************************************************************************************
2861//
2862//Function IR1S_UpdtSeparateMMM(distNum)
2863//      Variable distNum
2864//
2865//      string OldDf=GetDataFolder(1)
2866//      SetDataFolder root:Packages:SAS_Modeling
2867//
2868//      NVAR DistMean=$("root:Packages:SAS_Modeling:Dist"+num2str(distNum)+"Mean")
2869//      NVAR DistMedian=$("root:Packages:SAS_Modeling:Dist"+num2str(distNum)+"Median")
2870//      NVAR DistMode=$("root:Packages:SAS_Modeling:Dist"+num2str(distNum)+"Mode")
2871//      NVAR DistLocation=$("root:Packages:SAS_Modeling:Dist"+num2str(distNum)+"Location")
2872//      NVAR DistScale=$("root:Packages:SAS_Modeling:Dist"+num2str(distNum)+"Scale")
2873//      NVAR DistShape=$("root:Packages:SAS_Modeling:Dist"+num2str(distNum)+"Shape")
2874//      NVAR DistFWHM=$("root:Packages:SAS_Modeling:Dist"+num2str(distNum)+"FWHM")
2875//      SVAR DistDistributionType=$("root:Packages:SAS_Modeling:Dist"+num2str(distNum)+"DistributionType")
2876//      NVAR UseNumberDistribution=root:Packages:SAS_Modeling:UseNumberDistribution
2877//
2878//      Wave Distdiameters=$("root:Packages:SAS_Modeling:Dist"+num2str(distNum)+"diameters")
2879//     
2880//      Duplicate/O Distdiameters, Temp_Probability, Temp_Cumulative, Another_temp
2881//      Redimension/D Temp_Probability, Temp_Cumulative, Another_temp
2882//              if (cmpstr(DistDistributionType,"LogNormal")==0)
2883//                      Temp_Probability=IR1_LogNormProbability(Distdiameters,DistLocation,DistScale, DistShape)
2884//                      Temp_Cumulative=IR1_LogNormCumulative(Distdiameters,DistLocation,DistScale, DistShape)
2885//              endif
2886//              if (cmpstr(DistDistributionType,"Gauss")==0)
2887//                      Temp_Probability=IR1_GaussProbability(Distdiameters,DistLocation,DistScale, DistShape)
2888//                      Temp_Cumulative=IR1_GaussCumulative(Distdiameters,DistLocation,DistScale, DistShape)
2889//              endif
2890//              if (cmpstr(DistDistributionType,"LSW")==0)
2891//                      Temp_Probability=IR1_LSWProbability(Distdiameters,DistLocation,DistScale, DistShape)
2892//                      Temp_Cumulative=IR1_LSWCumulative(Distdiameters,DistLocation,DistScale, DistShape)
2893//              endif
2894//              if (cmpstr(DistDistributionType,"PowerLaw")==0)
2895//                      Temp_Probability=NaN
2896//                      Temp_Cumulative=NaN
2897//              endif
2898//
2899//     
2900//              Another_temp=Distdiameters*Temp_Probability
2901//              DistMean=areaXY(Distdiameters, Another_temp,0,inf)                                      //Sum P(R)*R*deltaR
2902//              DistMedian=Distdiameters[BinarySearchInterp(Temp_Cumulative, 0.5 )]             //R for which cumulative probability=0.5
2903//              FindPeak/P/Q Temp_Probability
2904//              DistMode=Distdiameters[V_PeakLoc]                                                               //location of maximum on the P(R)
2905//             
2906//              DistFWHM=IR1_FindFWHM(Temp_Probability,Distdiameters)                           //Ok, this is monkey approach
2907//
2908//              if (cmpstr(DistDistributionType,"PowerLaw")==0)
2909//                      DistFWHM=NaN
2910//                      DistMode=NaN
2911//                      DistMedian=NaN
2912//                      DistMean=NaN
2913//              endif
2914//      DoWindow IR1S_ControlPanel
2915//      if (V_Flag)
2916//              SetVariable $("DIS"+num2str(distNum)+"_Mode"),value= $("root:Packages:SAS_Modeling:Dist"+num2str(distNum)+"Mode"), format="%.1f", win=IR1S_ControlPanel
2917//              SetVariable $("DIS"+num2str(distNum)+"_Median"),value= $("root:Packages:SAS_Modeling:Dist"+num2str(distNum)+"Median"), format="%.1f", win=IR1S_ControlPanel
2918//              SetVariable $("DIS"+num2str(distNum)+"_Mean"),value= $("root:Packages:SAS_Modeling:Dist"+num2str(distNum)+"Mean"), format="%.1f", win=IR1S_ControlPanel
2919//              SetVariable $("DIS"+num2str(distNum)+"_FWHM"),value= $("root:Packages:SAS_Modeling:Dist"+num2str(distNum)+"FWHM"), format="%.1f", win=IR1S_ControlPanel
2920//      endif
2921//      DoWindow IR1U_ControlPanel
2922//      if (V_Flag)
2923//              SetVariable $("DIS"+num2str(distNum)+"_Mode"),value= $("root:Packages:SAS_Modeling:Dist"+num2str(distNum)+"Mode"), format="%.1f", win=IR1U_ControlPanel
2924//              SetVariable $("DIS"+num2str(distNum)+"_Median"),value= $("root:Packages:SAS_Modeling:Dist"+num2str(distNum)+"Median"), format="%.1f", win=IR1U_ControlPanel
2925//              SetVariable $("DIS"+num2str(distNum)+"_Mean"),value= $("root:Packages:SAS_Modeling:Dist"+num2str(distNum)+"Mean"), format="%.1f", win=IR1U_ControlPanel
2926//              SetVariable $("DIS"+num2str(distNum)+"_FWHM"),value= $("root:Packages:SAS_Modeling:Dist"+num2str(distNum)+"FWHM"), format="%.1f", win=IR1U_ControlPanel
2927//      endif
2928//     
2929//     
2930//      KillWaves/Z Temp_Probability, Temp_Cumulative, Another_Temp
2931//
2932//      setDataFolder OldDf
2933//end
2934
2935
2936//*****************************************************************************************************************
2937//*****************************************************************************************************************
2938//*****************************************************************************************************************
2939//*****************************************************************************************************************
2940//*****************************************************************************************************************
2941
2942Function IR1_FindFWHM(IntProbWave,DiaWave)
2943        wave IntProbWave,DiaWave
2944
2945//      string OldDf=GetDataFolder(1)
2946//      SetDataFolder root:Packages:SAS_Modeling
2947
2948        wavestats/Q IntProbWave
2949       
2950        variable maximum=V_max
2951        variable maxLoc=V_maxLoc
2952        Duplicate/O/R=[0,maxLoc] IntProbWave, temp_wv1
2953        Duplicate/O/R=[0,maxLoc] DiaWave, temp_RWwv1
2954       
2955        Duplicate/O/R=[maxLoc, numpnts(IntProbWave)-1] IntProbWave temp_wv2
2956        Duplicate/O/R=[maxLoc, numpnts(IntProbWave)-1] DiaWave, temp_RWwv2
2957       
2958        variable tempMin=BinarySearchInterp(temp_wv1, (maximum/2) )
2959        variable tmpMax=BinarySearchInterp(temp_wv2, (maximum/2) )
2960        variable MinD
2961        variable MaxD
2962        if(tempMin>0 && tempMin<numpnts(temp_wv1))
2963                MinD=temp_RWwv1[tempMin]
2964        else
2965                MinD=0
2966        endif
2967        if(tmpMax>0  && tmpMax<numpnts(temp_wv2))
2968                MaxD=temp_RWwv2[tmpMax]
2969        else
2970                MaxD=0
2971        endif
2972        KillWaves/Z temp_wv2, temp_wv1,temp_RWwv1,temp_RWwv2
2973
2974//      setDataFolder OldDf
2975       
2976        return abs(MaxD-MinD)
2977end
2978
2979
2980//*****************************************************************************************************************
2981//*****************************************************************************************************************
2982//*****************************************************************************************************************
2983//*****************************************************************************************************************
2984//*****************************************************************************************************************
2985
2986//****************   This calculates distribution of diameters and needed for the probability distribution   ***********************************************************
2987
2988Function IR1_GenerateDiametersDist(MyFunction, OutputWaveName, numberOfPoints, myprecision, location,scale, shape)
2989        string MyFunction, OutputWaveName
2990        variable numberOfPoints, myprecision, location,scale, shape
2991        //
2992        //  Important : this wave will be produced in current folder
2993        //
2994        //this function generates non-regular distribution of diameters for distributions
2995        //Myfunction can now be Gauss, LSW, or LogNormal
2996        //OutputWaveName is string with wave name. The wave is created with numberOfPoints number of points and existing one, if exists, is overwritten
2997        // my precision is value (~0.001 for example) which denotes how low probability we want to neglect (P<precision and P>(1-precision) are neglected
2998        //location, scale, shape are values for the probability distributions
2999       
3000        //logic: we start in the median and walk towards low (high) values. When cumulative value is smaller (larger) than precision (1-precision)
3001        //we end. If we walk out of reasonable values (10A and 10^15A), we stop.
3002       
3003        //first we need to find step, which we will use to step from median
3004        string OldDf=GetDataFolder(1)
3005        SetDataFolder root:Packages:SAS_Modeling
3006
3007
3008        variable startx, endx, guess, Step, mode, tempVal, tempResult
3009       
3010        if (cmpstr("Gauss",MyFunction)==0)
3011                Step=scale*0.02                                 //standard deviation
3012        endif
3013        if (cmpstr("LSW",MyFunction)==0)
3014                Step=location*0.3                               //just some step for this distribution
3015        endif
3016        if (cmpstr("LogNormal",MyFunction)==0)
3017                Step=4*sqrt(exp(shape^2)*(exp(shape^2)-1))      //standard deviation
3018        endif
3019        if (cmpstr("PowerLaw",MyFunction)==0)
3020                Step=500        //a number here
3021        endif
3022       
3023        //now we need to find the median
3024
3025        if (cmpstr("Gauss",MyFunction)==0)
3026                mode=location   //=median
3027        endif
3028        if (cmpstr("LSW",MyFunction)==0)
3029                mode=location   //close to median, who really cares where we start as long as it is close...
3030        endif
3031        if (cmpstr("LogNormal",MyFunction)==0)
3032                mode=location+scale/(exp(shape^2))      //=median
3033        endif
3034        if (cmpstr("PowerLaw",MyFunction)==0)
3035                mode=500                                // a number
3036        endif
3037        // look for minimum
3038        //now we can start at median and go step by step and end when the
3039        //cumulative function is smaller than the myprecision
3040       
3041        variable minimumXPossible=1   //if it should be smaller than 2A, it is nonsence...
3042       
3043        tempVal=mode
3044       
3045        do
3046                tempVal=tempVal-Step                    //OK, this way we should make always one more step over the limit...
3047
3048                if (tempVal<minimumXPossible)
3049                        tempVal=minimumXPossible
3050                endif
3051
3052                if (cmpstr("Gauss",MyFunction)==0)
3053                        tempResult=IR1_GaussCumulative(tempVal,location,scale, shape)
3054                endif
3055                if (cmpstr("LSW",MyFunction)==0)
3056                        tempResult=IR1_LSWCumulative(tempVal,location,scale, shape)
3057                endif
3058                if (cmpstr("LogNormal",MyFunction)==0)
3059                        tempResult=IR1_LogNormCumulative(tempVal,location,scale, shape)
3060                endif
3061                if (cmpstr("PowerLaw",MyFunction)==0)           //this funny function exists over whole size range possible....
3062                        tempResult=0
3063                        tempVal=minimumXPossible
3064                endif
3065               
3066        while ((tempResult>myprecision)&&(tempVal>minimumXPossible))                   
3067
3068        startx = tempVal
3069        //and this will be needed lower, in case when we have distributions attempting to get into negative diameters...
3070        variable startCumTrgts=myprecision
3071        if (startx==minimumXPossible)   //in this case we run into negative values and overwrote the startX values
3072                        if (cmpstr("Gauss",MyFunction)==0)
3073                                startCumTrgts=IR1_GaussCumulative(minimumXPossible,location,scale, shape)
3074                        endif
3075                        if (cmpstr("LSW",MyFunction)==0)
3076                                startCumTrgts=IR1_LSWCumulative(minimumXPossible,location,scale, shape)
3077                        endif
3078                        if (cmpstr("LogNormal",MyFunction)==0)
3079                                startCumTrgts=IR1_LogNormCumulative(minimumXPossible,location,scale, shape)
3080                        endif
3081                        if (cmpstr("PowerLaw",MyFunction)==0)
3082                                startCumTrgts=myprecision
3083                        endif
3084        endif
3085
3086        //now we need to calculate the endx
3087
3088        variable maximumXPossible=1e15  //maximum, fixed for giant number due to use of the code for light scattering
3089               
3090        tempVal=mode
3091       
3092        do
3093                tempVal=tempVal+Step            //again, whould be one step larger than needed...
3094                if (tempVal>maximumXPossible)
3095                        tempVal=maximumXPossible
3096                endif
3097
3098                if (cmpstr("Gauss",MyFunction)==0)
3099                        tempResult=IR1_GaussCumulative(tempVal,location,scale, shape)
3100                endif
3101                if (cmpstr("LSW",MyFunction)==0)
3102                        tempResult = 1
3103                        tempVal = 1.5 * location //this distribution does not exist over this value...
3104                endif
3105                if (cmpstr("LogNormal",MyFunction)==0)
3106                        tempResult=IR1_LogNormCumulative(tempVal,location,scale, shape)
3107                endif
3108                if (cmpstr("PowerLaw",MyFunction)==0)
3109                        maximumXPossible=1e7
3110                        tempResult=1
3111                        tempVal=maximumXPossible
3112                endif
3113
3114        while ((tempResult<(1-myprecision))&&(tempVal<maximumXPossible))                       
3115       
3116        endx = tempVal
3117
3118        //and now we can start making the the data.
3119        // First we will create a wave with equally distributed values between myprecision and 1-myprecision : Temp_CumulTargets
3120        //We will also create waves with 3*as many points with diameters between startx and endx (Temp_diameters) and with appropriate cumulative distribution (Temp_CumulativeWave)
3121        //then we will look for which diameters we get the cumulative numbers in Temp_CumulTargets and put these in output wave
3122       
3123        Make/D /N=(numberOfPoints) /O Temp_CumulTargets, $OutputWaveName
3124        Make/D /N=(3*numberOfPoints) /O Temp_CumulativeWave,Temp_diameters
3125       
3126        Wave DistributiondiametersWave=$OutputWaveName
3127       
3128        Temp_diameters=startx+p*(endx-startx)/(3*numberOfPoints-1)                      //this puts the proper diameters distribution in the temp diameters wave
3129       
3130        Temp_CumulTargets=startCumTrgts+p*(1-myprecision-startCumTrgts)/(numberOfPoints-1) //this puts equally spaced values between myprecision and (1-myprecision) in this wave
3131       
3132        //calculate the cumulative waves
3133        if (cmpstr("Gauss",MyFunction)==0)
3134                Temp_CumulativeWave=IR1_GaussCumulative(Temp_diameters,location,scale, shape)
3135        endif
3136        if (cmpstr("LSW",MyFunction)==0)
3137                Temp_CumulativeWave=IR1_LSWCumulative(Temp_diameters,location,scale, shape)
3138                Temp_CumulativeWave[numpnts(Temp_CumulativeWave)-1]=1   //last point is NaN, we need to make it 1
3139        endif
3140        if (cmpstr("LogNormal",MyFunction)==0)
3141                Temp_CumulativeWave=IR1_LogNormCumulative(Temp_diameters,location,scale, shape)
3142        endif
3143        if (cmpstr("PowerLaw",MyFunction)==0)
3144                Temp_CumulativeWave=IR1_PowerLawCumulative(Temp_diameters,shape,startx,endx)
3145        endif
3146       
3147                //and now the difficult part - get the diameterss, which are unequally spaced, but whose probability for the distribution are equally spaced...
3148                DistributionDiametersWave=interp(Temp_CumulTargets, Temp_CumulativeWave, Temp_diameters )
3149        variable temp
3150        if (cmpstr("PowerLaw",MyFunction)==0) //the code above fails for this distribution type, we need to create new diameters...
3151                //DistributionDiametersWave=startx+log(p)*(endx-startx)/log(numberOfPoints)
3152                //temp=log(startx)+p*((log(endx)-log(startx))/(numberOfPoints-1))
3153                DistributionDiametersWave=10^(log(startx)+p*((log(endx)-log(startx))/(numberOfPoints-1)))
3154        endif
3155
3156       
3157        //and now cleanup
3158       
3159        KillWaves/Z Temp_CumulTargets //, myTest
3160        KillWaves/Z Temp_CumulativeWave,Temp_diameters
3161
3162        setDataFolder OldDf
3163       
3164end
3165
3166
3167
3168//*****************************************************************************************************************
3169//*****************************************************************************************************************
3170//*****************************************************************************************************************
3171//*****************************************************************************************************************
3172//*****************************************************************************************************************
3173
3174//**********************************************************************************************************
3175
3176Function IR1_KillGraphsAndPanels()
3177
3178
3179
3180        String ListOfWindows
3181        ListOfWindows = "UnivDataExportPanel;TempExportGraph;ExportNoteDisplay;IR1G_OneSampleEvaluationGraph;MIPDataGraph;IR2D_LogLogPlotSAD;"
3182        ListOfWindows += "IR2D_ControlPanel;IR2H_SI_Q2_PlotGels;IR2H_IQ4_Q_PlotGels;IR2H_LogLogPlotGels;IR2H_ControlPanel;Shape_Model_Input_Panel;"
3183        ListOfWindows += "IR1S_InterferencePanel;IR1K_AnomCalcPnl;IR1G_OneSampleEvaluationGraph;IR1K_ScatteringContCalc;IR1F_CreateQRSFldrStructure;"
3184        ListOfWindows += "IR1B_DesmearingControlPanel;TrimGraph;SmoothGraph;CheckTheBackgroundExtns;DesmearingProcess;SmoothGraphDSM;"
3185        ListOfWindows += "IR1Y_ScatteringContrastPanel;About_Irena_1_Macros;IR1R_SizesInputPanel;IR1_LogLogPlotU;IR1_LogLogPlotLSQF;IR1P_ChangeGraphDetailsPanel;"
3186        ListOfWindows += "IR1_IQ4_Q_PlotU;IR1_IQ4_Q_PlotLSQF;IR1_Model_Distributions;IR1S_ControlPanel;IR1P_ControlPanel;IR1U_ControlPanel;"
3187        ListOfWindows += "IR1A_ControlPanel;IR1R_SizesInputGraph;IR1P_PlottingTool;GeneralGraph;IR1P_ControlPanel;IR1P_RemoveDataPanel;"
3188        ListOfWindows += "IR1P_ModifyDataPanel;IR1P_RemoveDataPanel;IR1P_StoreGraphsCtrlPnl;IR1D_DataManipulationPanel;IR1D_DataManipulationGraph;"
3189        ListOfWindows += "IR1I_ImportData;IR1V_ControlPanel;IR1V_LogLogPlotV;IR1V_IQ4_Q_PlotV;IR2S_ScriptingToolPnl;IR2Pr_PDFInputGraph;IR2Pr_ControlPanel;"
3190        ListOfWindows += "PlotingToolWaterfallGrph;LSQF2_MainPanel;LSQF_MainGraph;GraphSizeDistributions;LSQF_ResidualsGraph;Irena_Gizmo;GizmoControlPanel;"
3191        ListOfWindows += "DataMiningTool;ItemsInFolderPanel;ItemsInFolderPanel_DMII;DataManipulationII;IR2R_InsertRemoveLayers;PlotingToolContourGrph;"
3192        ListOfWindows += "FormFactorControlScreen;StructureFactorControlScreen;UnifiedEvaluationPanel;IR2H_ResidualsPlot;IR1P_StylesManagementPanel;"
3193        ListOfWindows += "ModelingII_Results;LSQF_IQ4vsQGraph;IR2L_ResSmearingPanel;IR1P_MoreToolsPanel;IR1R_SizeDistImportFitPanel;"
3194        ListOfWindows += "TwoPhaseSystemData;TwoPhaseSolidGizmo;TwoPhaseSystems;FractalAggregatePanel;MassFractalAggregateView;TwoPhaseSolid2DImage;"
3195        ListOfWindows += "IR3D_DataMergePanel;"
3196       
3197       
3198        variable i
3199        string TempNm
3200        For(i=0;i<ItemsInList(ListOfWindows);i+=1)
3201                TempNm = stringFromList(i,ListOfWindows)
3202                KillWIndow/Z $TempNm
3203        endfor
3204end
3205
3206////*****************************************************************************************************************
3207////*****************************************************************************************************************
3208////*****************************************************************************************************************
3209////*****************************************************************************************************************
3210////*****************************************************************************************************************
3211//
3212Function/T IR1_ReturnListQRSFolders(ListOfQFolders, AllowQROnly)
3213        string ListOfQFolders
3214        variable AllowQROnly
3215       
3216        string result, tempStringQ, tempStringR, tempStringS, nowFolder,oldDf
3217        oldDf=GetDataFolder(1)
3218        variable i, j
3219        string tempStr
3220        result=""
3221        For(i=0;i<ItemsInList(ListOfQFolders);i+=1)
3222                NowFolder= stringFromList(i,ListOfQFolders)
3223                setDataFolder NowFolder
3224                tempStr=IN2G_ConvertDataDirToList(DataFolderDir(2))
3225                tempStringQ=IR2P_ListOfWavesOfType("q*",tempStr)+IR2P_ListOfWavesOfType("d*",tempStr)+IR2P_ListOfWavesOfType("t*",tempStr)+IR2P_ListOfWavesOfType("m*",tempStr)
3226                tempStringR=IR2P_ListOfWavesOfType("r*",tempStr)
3227                tempStringS=IR2P_ListOfWavesOfType("s*",tempStr)
3228                For (j=0;j<ItemsInList(tempStringQ);j+=1)
3229                        if(AllowQROnly)
3230                                if (stringMatch(tempStringR,"*r"+StringFromList(j,tempStringQ)[1,inf]+";*"))
3231                                        result+=NowFolder+";"
3232                                        break
3233                                endif
3234                        else
3235                                if (stringMatch(tempStringR,"*r"+StringFromList(j,tempStringQ)[1,inf]+";*") && stringMatch(tempStringS,"*s"+StringFromList(j,tempStringQ)[1,inf]+";*"))
3236                                        result+=NowFolder+";"
3237                                        break
3238                                endif
3239                        endif
3240                endfor
3241                               
3242        endfor
3243        setDataFOlder oldDf
3244        return result
3245
3246end
3247
3248
3249////*****************************************************************************************************************
3250////*****************************************************************************************************************
3251////*****************************************************************************************************************
3252////*****************************************************************************************************************
3253////*****************************************************************************************************************
3254////
3255////Function/T IR1_ListOfWavesOfType(type,ListOfWaves)
3256////            string type, ListOfWaves
3257////           
3258////            variable i
3259////            string tempresult=""
3260////            for (i=0;i<ItemsInList(ListOfWaves);i+=1)
3261////                    if (stringMatch(StringFromList(i,ListOfWaves),type+"*"))
3262////                            tempresult+=StringFromList(i,ListOfWaves)+";"
3263////                    endif
3264////            endfor
3265////
3266////    return tempresult
3267////end
3268//
3269////*****************************************************************************************************************
3270////*****************************************************************************************************************
3271////*****************************************************************************************************************
3272////*****************************************************************************************************************
3273////*****************************************************************************************************************
3274
3275Function/T IR1_ListIndraWavesForPopups(WhichWave,WhereAreControls,IncludeSMR,OneOrTwo)
3276        string WhichWave,WhereAreControls
3277        variable IncludeSMR, OneOrtwo           //if IncludeSMR=-1 then ONLY SMR data!
3278
3279        string AllWavesInt
3280        string AllWavesQ       
3281        string AllWavesE       
3282        if(OneOrTwo==1)
3283                 AllWavesInt = IR1_ListOfWaves("DSM_Int",WhereAreControls,abs(IncludeSMR),0)   
3284                 AllWavesQ = IR1_ListOfWaves("DSM_Qvec",WhereAreControls,abs(IncludeSMR),0)     
3285                 AllWavesE = IR1_ListOfWaves("DSM_Error",WhereAreControls,abs(IncludeSMR),0)   
3286        else
3287                 AllWavesInt = IR1_ListOfWaves2("DSM_Int",WhereAreControls,abs(IncludeSMR),0)   
3288                 AllWavesQ = IR1_ListOfWaves2("DSM_Qvec",WhereAreControls,abs(IncludeSMR),0)   
3289                 AllWavesE = IR1_ListOfWaves2("DSM_Error",WhereAreControls,abs(IncludeSMR),0)   
3290        endif
3291       
3292        string SelectedInt=""
3293        string SelectedQ=""
3294        string SelectedE=""
3295        string result
3296        //M_BKG_Int
3297        if(stringmatch(AllWavesInt, "*M_BKG_Int*") && stringmatch(AllWavesQ, "*M_BKG_Qvec*")  && stringmatch(AllWavesE, "*M_BKG_Error*") )             
3298                SelectedInt+="M_BKG_Int;"
3299                SelectedQ+="M_BKG_Qvec;"
3300                SelectedE+="M_BKG_Error;"
3301        endif
3302        if(stringmatch(AllWavesInt, "*BKG_Int*") && stringmatch(AllWavesQ, "*BKG_Qvec*")  && stringmatch(AllWavesE, "*BKG_Error*") )           
3303                SelectedInt+="BKG_Int;"
3304                SelectedQ+="BKG_Qvec;"
3305                SelectedE+="BKG_Error;"
3306        endif
3307        if(stringmatch(AllWavesInt, "*M_DSM_Int*") && stringmatch(AllWavesQ, "*M_DSM_Qvec*")  && stringmatch(AllWavesE, "*M_DSM_Error*") )             
3308                SelectedInt+="M_DSM_Int;"
3309                SelectedQ+="M_DSM_Qvec;"
3310                SelectedE+="M_DSM_Error;"       
3311        endif
3312        if(stringmatch(AllWavesInt, "*DSM_Int*") &&stringmatch( AllWavesQ, "*DSM_Qvec*")  && stringmatch(AllWavesE, "*DSM_Error*") )           
3313                SelectedInt+="DSM_Int;"
3314                SelectedQ+="DSM_Qvec;"
3315                SelectedE+="DSM_Error;"
3316        endif
3317        if(IncludeSMR && stringmatch(AllWavesInt, "*M_SMR_Int*") &&stringmatch( AllWavesQ, "*M_SMR_Qvec*")  &&stringmatch( AllWavesE, "*M_SMR_Error*") )               
3318                SelectedInt+="M_SMR_Int;"
3319                SelectedQ+="M_SMR_Qvec;"
3320                SelectedE+="M_SMR_Error;"       
3321        endif
3322        if(IncludeSMR && stringmatch(AllWavesInt, "*SMR_Int*") && stringmatch(AllWavesQ, "*SMR_Qvec*")  && stringmatch(AllWavesE, "*SMR_Error*") )             
3323                SelectedInt+="SMR_Int;"
3324                SelectedQ+="SMR_Qvec;"
3325                SelectedE+="SMR_Error;"
3326        endif   
3327        if((IncludeSMR==-1))
3328                SelectedInt=""
3329                SelectedQ=""
3330                SelectedE=""   
3331        endif
3332        if((IncludeSMR==-1) && stringmatch(AllWavesInt, "*SMR_Int*") && stringmatch(AllWavesQ, "*SMR_Qvec*")  && stringmatch(AllWavesE, "*SMR_Error*") )               
3333                SelectedInt+="SMR_Int;"
3334                SelectedQ+="SMR_Qvec;"
3335                SelectedE+="SMR_Error;"
3336        endif   
3337        if((IncludeSMR==-1) && stringmatch(AllWavesInt, "*M_SMR_Int*") &&stringmatch( AllWavesQ, "*M_SMR_Qvec*")  &&stringmatch( AllWavesE, "*M_SMR_Error*") )         
3338                SelectedInt+="M_SMR_Int;"
3339                SelectedQ+="M_SMR_Qvec;"
3340                SelectedE+="M_SMR_Error;"       
3341        endif
3342
3343        SelectedE+="---;"
3344        if(cmpstr(whichWave,"DSM_Int")==0)
3345                result = SelectedInt
3346        elseif(cmpstr(whichWave,"DSM_Qvec")==0)
3347                result = SelectedQ
3348        else
3349                result = SelectedE     
3350        endif
3351        if (strlen(result)<1)
3352                result="---;"
3353        endif
3354        return result
3355end
3356
3357////*****************************************************************************************************************
3358////*****************************************************************************************************************
3359////*****************************************************************************************************************
3360////*****************************************************************************************************************
3361////*****************************************************************************************************************
3362//
3363Function/T IR1_ListOfWaves(WaveTp,WhereAreControls, IncludeSMRData, AllowQRDataOnly)
3364        string WaveTp, WhereAreControls
3365        variable  IncludeSMRData, AllowQRDataOnly
3366       
3367        //      if UseIndra2Structure = 1 we are using Indra2 data, else return all waves
3368       
3369        string result="", tempresult="", dataType="", tempStringQ="", tempStringR="", tempStringS=""
3370        SVAR FldrNm=$("root:Packages:"+WhereAreControls+":DataFolderName")
3371        NVAR Indra2Dta=$("root:Packages:"+WhereAreControls+":UseIndra2Data")
3372        NVAR QRSdata=$("root:Packages:"+WhereAreControls+":UseQRSData")
3373        variable i,j
3374               
3375        if (Indra2Dta)
3376                result=IN2G_CreateListOfItemsInFolder(FldrNm,2)
3377                if(stringMatch(result,"*"+WaveTp+"*"))
3378                        tempresult=""
3379                        for (i=0;i<ItemsInList(result);i+=1)
3380                                if (stringMatch(StringFromList(i,result),"*"+WaveTp+"*"))
3381                                        tempresult+=StringFromList(i,result)+";"
3382                                endif
3383                        endfor
3384                endif
3385                if (cmpstr(WaveTp,"DSM_Int")==0)
3386                        For (j=0;j<ItemsInList(result);j+=1)
3387                                if (stringMatch(StringFromList(j,result),"*BKG_Int*"))
3388                                        tempresult+=StringFromList(j,result)+";"
3389                                endif
3390                                if(IncludeSMRData)
3391                                        if (stringMatch(StringFromList(j,result),"*SMR_Int*"))
3392                                                tempresult+=StringFromList(j,result)+";"
3393                                        endif                           
3394                                endif
3395                        endfor
3396                elseif(cmpstr(WaveTp,"DSM_Qvec")==0)
3397                        For (j=0;j<ItemsInList(result);j+=1)
3398                                if (stringMatch(StringFromList(j,result),"*BKG_Qvec*"))
3399                                        tempresult+=StringFromList(j,result)+";"
3400                                endif
3401                                if(IncludeSMRData)
3402                                        if (stringMatch(StringFromList(j,result),"*SMR_Qvec*"))
3403                                                tempresult+=StringFromList(j,result)+";"
3404                                        endif                           
3405                                endif
3406                        endfor
3407                else
3408                        For (j=0;j<ItemsInList(result);j+=1)
3409                                if (stringMatch(StringFromList(j,result),"*BKG_Error*"))
3410                                        tempresult+=StringFromList(j,result)+";"
3411                                endif
3412                                if(IncludeSMRData)
3413                                        if (stringMatch(StringFromList(j,result),"*SMR_Error*"))
3414                                                tempresult+=StringFromList(j,result)+";"
3415                                        endif                           
3416                                endif
3417                        endfor
3418        endif
3419                        result=tempresult
3420        elseif(QRSData)
3421                result=""                       //IN2G_CreateListOfItemsInFolder(FldrNm,2)
3422                tempStringQ=IR2P_ListOfWavesOfType("q",IN2G_CreateListOfItemsInFolder(FldrNm,2))
3423                tempStringR=IR2P_ListOfWavesOfType("r",IN2G_CreateListOfItemsInFolder(FldrNm,2))
3424                tempStringS=IR2P_ListOfWavesOfType("s",IN2G_CreateListOfItemsInFolder(FldrNm,2))
3425               
3426                if (cmpstr(WaveTp,"DSM_Int")==0)
3427//                      dataType="r"
3428                        For (j=0;j<ItemsInList(tempStringR);j+=1)
3429                                if(AllowQRDataOnly)
3430                                        if (stringMatch(tempStringQ,"*q"+StringFromList(j,tempStringR)[1,inf]+";*"))
3431                                                result+=StringFromList(j,tempStringR)+";"
3432                                        endif
3433                                else
3434                                        if (stringMatch(tempStringQ,"*q"+StringFromList(j,tempStringR)[1,inf]+";*") && stringMatch(tempStringS,"*s"+StringFromList(j,tempStringR)[1,inf]+";*"))
3435                                                result+=StringFromList(j,tempStringR)+";"
3436                                        endif
3437                                endif
3438                        endfor
3439                elseif(cmpstr(WaveTp,"DSM_Qvec")==0)
3440//                      dataType="q"
3441                        For (j=0;j<ItemsInList(tempStringQ);j+=1)
3442                                if(AllowQRDataOnly)
3443                                        if (stringMatch(tempStringR,"*r"+StringFromList(j,tempStringQ)[1,inf]+";*"))
3444                                                result+=StringFromList(j,tempStringQ)+";"
3445                                        endif
3446                                else
3447                                        if (stringMatch(tempStringR,"*r"+StringFromList(j,tempStringQ)[1,inf]+";*") && stringMatch(tempStringS,"*s"+StringFromList(j,tempStringQ)[1,inf]+";*"))
3448                                                result+=StringFromList(j,tempStringQ)+";"
3449                                        endif
3450                                endif   
3451                        endfor
3452                else
3453//                      dataType="s"                   
3454                        For (j=0;j<ItemsInList(tempStringS);j+=1)
3455                                if(AllowQRDataOnly)
3456                                        //nonsense...
3457                                else
3458                                        if (stringMatch(tempStringR,"*r"+StringFromList(j,tempStringS)[1,inf]+";*") && stringMatch(tempStringQ,"*q"+StringFromList(j,tempStringS)[1,inf]+";*"))
3459                                                result+=StringFromList(j,tempStringS)+";"
3460                                        endif
3461                                endif
3462                        endfor
3463                endif
3464        else
3465                result=IN2G_CreateListOfItemsInFolder(FldrNm,2)
3466        endif
3467       
3468        return result
3469end
3470
3471Function/T IR1_ListOfWaves2(WaveTp,WhereAreControls, IncludeSMRData,AllowQRDataOnly)
3472        string WaveTp, WhereAreControls
3473        variable IncludeSMRData, AllowQRDataOnly
3474       
3475        //      if UseIndra2Structure = 1 we are using Indra2 data, else return all waves
3476       
3477        string result, tempresult, dataType, tempStringQ, tempStringR, tempStringS
3478        SVAR FldrNm=$("root:Packages:"+WhereAreControls+":DataFolderName2")
3479        NVAR Indra2Dta=$("root:Packages:"+WhereAreControls+":UseIndra2Data2")
3480        NVAR QRSdata=$("root:Packages:"+WhereAreControls+":UseQRSData2")
3481        variable i,j
3482        tempresult=""
3483               
3484        if (Indra2Dta)
3485                result=IN2G_CreateListOfItemsInFolder(FldrNm,2)
3486                if(stringMatch(result,"*"+WaveTp+"*"))
3487                        for (i=0;i<ItemsInList(result);i+=1)
3488                                if (stringMatch(StringFromList(i,result),"*"+WaveTp+"*"))
3489                                        tempresult+=StringFromList(i,result)+";"
3490                                endif
3491                        endfor
3492                endif
3493                if (cmpstr(WaveTp,"DSM_Int")==0)
3494                        For (j=0;j<ItemsInList(result);j+=1)
3495                                if (stringMatch(StringFromList(j,result),"*BKG_Int*"))
3496                                        tempresult+=StringFromList(j,result)+";"
3497                                endif
3498                                if(IncludeSMRData)
3499                                        if (stringMatch(StringFromList(j,result),"*SMR_Int*"))
3500                                                tempresult+=StringFromList(j,result)+";"
3501                                        endif                           
3502                                endif
3503                        endfor
3504                elseif(cmpstr(WaveTp,"DSM_Qvec")==0)
3505                        For (j=0;j<ItemsInList(result);j+=1)
3506                                if (stringMatch(StringFromList(j,result),"*BKG_Qvec*"))
3507                                        tempresult+=StringFromList(j,result)+";"
3508                                endif
3509                                if(IncludeSMRData)
3510                                        if (stringMatch(StringFromList(j,result),"*SMR_Qvec*"))
3511                                                tempresult+=StringFromList(j,result)+";"
3512                                        endif                           
3513                                endif
3514                        endfor
3515                else
3516                        For (j=0;j<ItemsInList(result);j+=1)
3517                                if (stringMatch(StringFromList(j,result),"*BKG_Error*"))
3518                                        tempresult+=StringFromList(j,result)+";"
3519                                endif
3520                                if(IncludeSMRData)
3521                                        if (stringMatch(StringFromList(j,result),"*SMR_Error*"))
3522                                                tempresult+=StringFromList(j,result)+";"
3523                                        endif                           
3524                                endif
3525                        endfor
3526                        result=tempresult
3527                endif
3528        elseif(QRSData)
3529                result=""                       //IN2G_CreateListOfItemsInFolder(FldrNm,2)
3530                tempStringQ=IR2P_ListOfWavesOfType("q",IN2G_CreateListOfItemsInFolder(FldrNm,2))
3531                tempStringR=IR2P_ListOfWavesOfType("r",IN2G_CreateListOfItemsInFolder(FldrNm,2))
3532                tempStringS=IR2P_ListOfWavesOfType("s",IN2G_CreateListOfItemsInFolder(FldrNm,2))
3533               
3534                if (cmpstr(WaveTp,"DSM_Int")==0)
3535//                      dataType="r"
3536                        For (j=0;j<ItemsInList(tempStringR);j+=1)
3537                                if(AllowQRDataOnly)
3538                                        if (stringMatch(tempStringQ,"*q"+StringFromList(j,tempStringR)[1,inf]+";*"))
3539                                                result+=StringFromList(j,tempStringR)+";"
3540                                        endif
3541                                else
3542                                        if (stringMatch(tempStringQ,"*q"+StringFromList(j,tempStringR)[1,inf]+";*") && stringMatch(tempStringS,"*s"+StringFromList(j,tempStringR)[1,inf]+";*"))
3543                                                result+=StringFromList(j,tempStringR)+";"
3544                                        endif
3545                                endif
3546                        endfor
3547                elseif(cmpstr(WaveTp,"DSM_Qvec")==0)
3548//                      dataType="q"
3549                        For (j=0;j<ItemsInList(tempStringQ);j+=1)
3550                                if(AllowQRDataOnly)
3551                                        if (stringMatch(tempStringR,"*r"+StringFromList(j,tempStringQ)[1,inf]+";*"))
3552                                                result+=StringFromList(j,tempStringQ)+";"
3553                                        endif
3554                                else
3555                                        if (stringMatch(tempStringR,"*r"+StringFromList(j,tempStringQ)[1,inf]+";*") && stringMatch(tempStringS,"*s"+StringFromList(j,tempStringQ)[1,inf]+";*"))
3556                                                result+=StringFromList(j,tempStringQ)+";"
3557                                        endif
3558                                endif   
3559                        endfor
3560                else
3561//                      dataType="s"                   
3562                        For (j=0;j<ItemsInList(tempStringS);j+=1)
3563                                if(AllowQRDataOnly)
3564                                        //nonsense...
3565                                else
3566                                        if (stringMatch(tempStringR,"*r"+StringFromList(j,tempStringS)[1,inf]+";*") && stringMatch(tempStringQ,"*q"+StringFromList(j,tempStringS)[1,inf]+";*"))
3567                                                result+=StringFromList(j,tempStringS)+";"
3568                                        endif
3569                                endif
3570                        endfor
3571                endif
3572        else
3573                result=IN2G_CreateListOfItemsInFolder(FldrNm,2)
3574        endif
3575       
3576        return result
3577end
3578
Note: See TracBrowser for help on using the repository browser.