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

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

Created Beta versions after February2020 (now using X.YZ1-9 numbers.
Set for desktop USAXS default use of Gauss peak profile fitting.

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