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

Last change on this file since 932 was 932, checked in by ilavsky, 2 years ago

Add Size distribution analysis to SImple fits

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