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

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

FIxes for GetHelp? button and manuals

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