source: sans/Dev/branches/nxcansas_writer/NCNR_User_Procedures/Reduction/SANS/NSORT.ipf @ 1200

Last change on this file since 1200 was 1200, checked in by krzywon, 3 years ago

Fix an bug in NSORT and remove an unneeded print statement.

File size: 82.3 KB
Line 
1#pragma rtGlobals=1             // Use modern global access method.
2#pragma version=5.0
3#pragma IgorVersion=6.1
4
5//****************************
6// Vers. 1.2 092101
7//
8// NSORT panel for combining and inter-normalizing 2 or 3 datasets
9// that have previously been averaged
10//
11// MAR 2016 SRK added functionality to combine 4 datasets
12//
13// - handles 3 or 6-column datasets
14// allows manual scaling
15// allows user to interactively delete data points from either end of any datset
16//
17//*********************
18
19//main entry point for displaying the nsort panel
20//initializes folder/globals as needed
21//
22Proc ShowNSORTPanel()
23        DoWindow/F NSORT_Panel
24        if(V_flag==0)
25                InitNSORTPanel()
26                NSORT_Panel()
27        Endif
28        SetDataFolder root:
29        PathInfo/S catPathName
30        String junk = S_path
31        if (V_flag == 0)
32                //path does not exist - no folder selected
33                String/G root:myGlobals:NSORT:gPathStr = "no folder selected"
34        else
35                String/G root:myGlobals:NSORT:gPathStr = junk
36        endif
37        LowQPopMenuProc("",1,"")
38        MedQPopMenuProc("",1,"")
39        HighQPopMenuProc("",1,"")
40        HighestQPopMenuProc("",1,"")
41End
42
43//initializes globals/folder for the NSORT panel as needed
44//all of the globals are stored in root:myGlobals:NSORT folder
45//the globals are the values displayed in the panel
46//
47Proc InitNSORTPanel()
48
49        //set up the global variables needed for the NSORT panel
50        NewDataFolder/O root:myGlobals:NSORT
51        Variable/G root:myGlobals:NSORT:gScale1_2 = 1
52        Variable/G root:myGlobals:NSORT:gScale2_3 = 1
53        Variable/G root:myGlobals:NSORT:gScale3_4 = 1
54        //
55        //save the number of points to trim from beginning/end of the data files
56        //
57        Variable/G root:myGlobals:NSORT:gPtsBeg1 = NumVarOrDefault("root:myGlobals:NSORT:gPtsBeg1", 0 )
58        Variable/G root:myGlobals:NSORT:gPtsEnd1 = NumVarOrDefault("root:myGlobals:NSORT:gPtsEnd1", 0 )
59        Variable/G root:myGlobals:NSORT:gPtsBeg2 = NumVarOrDefault("root:myGlobals:NSORT:gPtsBeg2", 0 )
60        Variable/G root:myGlobals:NSORT:gPtsEnd2 = NumVarOrDefault("root:myGlobals:NSORT:gPtsEnd2", 0 )
61        Variable/G root:myGlobals:NSORT:gPtsBeg3 = NumVarOrDefault("root:myGlobals:NSORT:gPtsBeg3", 0 )
62        Variable/G root:myGlobals:NSORT:gPtsEnd3 = NumVarOrDefault("root:myGlobals:NSORT:gPtsEnd3", 0 )
63        Variable/G root:myGlobals:NSORT:gPtsBeg4 = NumVarOrDefault("root:myGlobals:NSORT:gPtsBeg4", 0 )
64        Variable/G root:myGlobals:NSORT:gPtsEnd4 = NumVarOrDefault("root:myGlobals:NSORT:gPtsEnd4", 0 )
65       
66        Variable/G root:myGlobals:NSORT:gColumns1 = 0
67        Variable/G root:myGlobals:NSORT:gColumns2 = 0
68        Variable/G root:myGlobals:NSORT:gColumns3 = 0
69        Variable/G root:myGlobals:NSORT:gColumns4 = 0
70        Variable/G root:myGlobals:NSORT:gNormToNum = 1
71        String/G root:myGlobals:NSORT:gPathStr = ""
72        String/G root:myGlobals:NSORT:gDataPopList = "none"
73        String/G root:myGlobals:NSORT:gDataPopList_3 = "none"
74       
75        SetDataFolder root:             //(redundant)
76End
77
78//New loader that uses data folders etc...
79//AJJ Jan 2010
80Function LoadDataForNSORT(fileStr,setNum)
81        String fileStr          //full path:name to a valid file
82        Variable setNum //number of set (used for naming) = 0, 1, or 2 (ONLY), (2016) 3 is now valid for 4th data set
83       
84        Variable err=0
85
86        String nm0,nm1,nm2
87        //String firstFileName = S_fileName
88        Variable pt=0,begPts,endPts,numCols
89       
90        NVAR gColumns1 = root:myGlobals:NSORT:gColumns1
91        NVAR gColumns2 = root:myGlobals:NSORT:gColumns2
92        NVAR gColumns3 = root:myGlobals:NSORT:gColumns3
93        NVAR gColumns4 = root:myGlobals:NSORT:gColumns4
94        NVAR begPts1 = root:myGlobals:NSORT:gPtsBeg1
95        NVAR endPts1 = root:myGlobals:NSORT:gPtsEnd1
96        NVAR begPts2 = root:myGlobals:NSORT:gPtsBeg2
97        NVAR endPts2 = root:myGlobals:NSORT:gPtsEnd2
98        NVAR begPts3 = root:myGlobals:NSORT:gPtsBeg3
99        NVAR endPts3 = root:myGlobals:NSORT:gPtsEnd3
100        NVAR begPts4 = root:myGlobals:NSORT:gPtsBeg4
101        NVAR endPts4 = root:myGlobals:NSORT:gPtsEnd4
102       
103        String cmd
104        String typStr= "", trimStr=""
105       
106        switch (setNum)
107                case 1:
108                        sprintf cmd , "A_LoadOneDDataToName(\"%s\",\"%s\",%d,%d)",fileStr,"LowQSet",0,1
109                        Execute cmd
110                        typStr = "LowQSet"
111                        trimStr = "TrimLowQSet"
112                        begPts = begPts1
113                        endPts = endPts1
114                        break
115                case 2:
116                        sprintf cmd , "A_LoadOneDDataToName(\"%s\",\"%s\",%d,%d)",fileStr,"MedQSet",0,1
117                        Execute cmd             
118                        typStr = "MedQSet"
119                        trimStr = "TrimMedQSet"
120                        begPts = begPts2
121                        endPts = endPts2
122                        break
123                case 3:
124                        sprintf cmd , "A_LoadOneDDataToName(\"%s\",\"%s\",%d,%d)",fileStr,"HighQSet",0,1
125                        Execute cmd
126                        typStr = "HighQSet"
127                        trimStr = "TrimHighQSet"
128                        begPts = begPts3
129                        endPts = endPts3
130                        break
131                case 4:
132                        sprintf cmd , "A_LoadOneDDataToName(\"%s\",\"%s\",%d,%d)",fileStr,"HighestQSet",0,1
133                        Execute cmd
134                        typStr = "HighestQSet"
135                        trimStr = "TrimHighestQSet"
136                        begPts = begPts4
137                        endPts = endPts4
138                        break
139        endswitch
140               
141        String typPrefix = "root:"+typStr+":"+typStr
142        String trimPrefix = "root:"+typStr+":"+trimStr
143       
144        if (WaveExists($(typPrefix+"_res")))
145                //6 col data loaded
146//              print "6 col data loaded"
147                numCols = 6
148                Duplicate/O $(typPrefix+"_q") $(trimPrefix+"_q")
149                Duplicate/O $(typPrefix+"_i") $(trimPrefix+"_i")
150                Duplicate/O $(typPrefix+"_s") $(trimPrefix+"_s")
151                Duplicate/O $(typPrefix+"_res") $(trimPrefix+"_res")
152                //Trimmed data set
153//              Duplicate/O $(typPrefix+"_q"),$(trimPrefix+"_q")
154//              Duplicate/O $(typPrefix+"_i"),$(trimPrefix+"_i")
155//              Duplicate/O $(typPrefix+"_s"),$(trimPrefix+"_s")
156                WaveStats/Q $(typPrefix+"_q")                   //get info about the original q-values read in
157                pt = V_npnts-endPts
158                DeletePoints pt,endPts,$(trimPrefix+"_q"),$(trimPrefix+"_i"),$(trimPrefix+"_s"),$(trimPrefix+"_res")    //delete end points first
159                DeletePoints 0,begPts,$(trimPrefix+"_q"),$(trimPrefix+"_i"),$(trimPrefix+"_s"),$(trimPrefix+"_res")     //then delete points from beginning                     
160        else
161                //Assume
162                //3 col data loaded
163//              print "Assuming 3 col data loaded"
164                numcols = 3
165                Duplicate/O $(typPrefix+"_q") $(trimPrefix+"_q")
166                Duplicate/O $(typPrefix+"_i") $(trimPrefix+"_i")
167                Duplicate/O $(typPrefix+"_s") $(trimPrefix+"_s")               
168                //Trimmed data set
169//              Duplicate/O $(typPrefix+"_q"),$(trimPrefix+"_q")
170//              Duplicate/O $(typPrefix+"_i"),$(trimPrefix+"_i")
171//              Duplicate/O $(typPrefix+"_s"),$(trimPrefix+"_s")
172                WaveStats/Q $(typPrefix+"_q")                   //get info about the original q-values read in
173                pt = V_npnts-endPts
174                DeletePoints pt,endPts,$(trimPrefix+"_q"),$(trimPrefix+"_i"),$(trimPrefix+"_s") //delete end points first
175                DeletePoints 0,begPts,$(trimPrefix+"_q"),$(trimPrefix+"_i"),$(trimPrefix+"_s")  //then delete points from beginning                                                     
176        endif
177
178        switch (setNum)
179                case 1:
180                        gColumns1 = numCols
181                        break
182                case 2:
183                        gColumns2 = numCols
184                        break
185                case 3:
186                        gColumns3 = numCols
187                        break
188                case 4:
189                        gColumns4 = numCols
190                        break
191        endswitch
192       
193        return(0)
194       
195End
196
197Function WriteNSORTedFile(q3,i3,sig3,firstFileName,secondFileName,thirdFileName,fourthFileName,normTo,norm12,norm23,norm34,[res])
198        Wave q3,i3,sig3,res
199        String firstFileName,secondFileName,thirdFileName,fourthfileName,normTo
200        Variable norm12,norm23,norm34
201
202        NVAR useXMLOutput = root:Packages:NIST:gXML_Write
203        NVAR useNXcanSASOutput = root:Packages:NIST:gNXcanSAS_Write
204
205        if (useXMLOutput == 1)
206                if(WaveExists(res))
207                        WriteNSORTedXMLFile(q3,i3,sig3,firstFileName,secondFileName,thirdFileName,fourthFileName,normTo,norm12,norm23,norm34,res=res)
208                else
209                        WriteNSORTedXMLFile(q3,i3,sig3,firstFileName,secondFileName,thirdFileName,fourthFileName,normTo,norm12,norm23,norm34)
210                endif
211        elseif (useNXcanSASOutput == 1)
212                if(WaveExists(res))
213                        WriteNSORTedNXcanSASFile(q3,i3,sig3,firstFileName,secondFileName,thirdFileName,fourthFileName,normTo,norm12,norm23,norm34,res=res)
214                else
215                        WriteNSORTedNXcanSASFile(q3,i3,sig3,firstFileName,secondFileName,thirdFileName,fourthFileName,normTo,norm12,norm23,norm34)
216                endif
217        else
218                if(WaveExists(res))
219                        WriteOLDNSORTedFile(q3,i3,sig3,firstFileName,secondFileName,thirdFileName,fourthFileName,normTo,norm12,norm23,norm34,res=res)
220                else
221                        WriteOLDNSORTedFile(q3,i3,sig3,firstFileName,secondFileName,thirdFileName,fourthFileName,normTo,norm12,norm23,norm34)
222                endif           
223        endif
224
225End
226
227
228Function WriteOLDNSORTedFile(q3,i3,sig3,firstFileName,secondFileName,thirdFileName,fourthFileName,normTo,norm12,norm23,norm34,[res])
229        Wave q3,i3,sig3,res
230        String firstFileName,secondFileName,thirdFileName,fourthFileName,normTo
231        Variable norm12,norm23,norm34
232
233        Variable err=0,refNum,numCols,dialog=1
234        String fullPath="",formatStr="",str2
235        //check each wave - else REALLY FATAL error when writing file
236        If(!(WaveExists(q3)))
237                err = 1
238                return err
239        Endif
240        If(!(WaveExists(i3)))
241                err = 1
242                return err
243        Endif
244        If(!(WaveExists(sig3)))
245                err = 1
246                return err
247        Endif
248       
249        if(WaveExists(res))
250                numCols = 6
251        else
252                numCols = 3
253        endif
254       
255// 05SEP05 SRK -- added to automatically combine files from a table - see the end of NSORT.ipf for details
256// - use the flag set in DoCombineFiles() to decide if the table entries should be used
257//Ê Êroot:myGlobals:CombineTable:useTable= (1) (0)
258//if(exists("root:myGlobals:CombineTable:SaveName"))
259        NVAR/Z useTable = root:myGlobals:CombineTable:useTable
260        if(NVAR_Exists(useTable) && useTable==1)
261                SVAR str=root:myGlobals:CombineTable:SaveNameStr        //messy, but pass in as a global
262                fullPath = str
263//              str2 = "Is the file name "+str+" correct?"
264//              DoAlert 1,str2
265//              if(V_flag==1)
266                        dialog=0                //bypass the dialog if the name is good (assumed, since DoAlert is bypassed)
267//              endif
268        endif
269       
270        if(dialog)
271                PathInfo/S catPathName
272                fullPath = DoSaveFileDialog("Save data as",fname="",suffix=".ABS")              //won't actually open the file
273                If(cmpstr(fullPath,"")==0)
274                        //user cancel, don't write out a file
275                        Close/A
276                        Abort "no data file was written"
277                Endif
278                //Print "dialog fullpath = ",fullpath
279        Endif
280       
281//      // read in the header information from each of the combined files and put this information in the file header
282//      String dum,hdr1="none\r\n",hdr2="none\r\n",hdr3="none\r\n"
283//      PathInfo catPathName
284//     
285//      // the first file exists, check anyways
286//      if(cmpstr(firstFileName,"none") !=0)
287//              Open/R refNum as S_Path+firstFileName
288//              FReadLine refNum, dum
289//              FReadLine refNum, hdr1                  //just grab the second line
290//              Close refNum
291//      endif
292//      //second file
293//      if(cmpstr(secondFileName,"none") !=0)
294//              Open/R refNum as S_Path+secondFileName
295//              FReadLine refNum, dum
296//              FReadLine refNum, hdr2                  //just grab the second line
297//              Close refNum
298//      endif
299//      // third file
300//      if(cmpstr(thirdFileName,"none") !=0)
301//              Open/R refNum as S_Path+thirdFileName
302//              FReadLine refNum, dum
303//              FReadLine refNum, hdr3                  //just grab the second line
304//              Close refNum
305//      endif
306
307       
308        //actually open the file
309        Open refNum as fullpath
310       
311        fprintf refnum, "COMBINED FILE CREATED: %s \r\n",date()
312       
313//      fprintf refnum, "FIRST File %s",hdr1            //new, Mar 2008
314//      fprintf refnum, "SECOND File %s",hdr2           //new, Mar 2008
315//      fprintf refnum, "THIRD File %s",hdr3            //new, Mar 2008
316       
317        fprintf refNum, "NSORT-ed   %s\t  +  %s\t  +  %s\t + %s\r\n",firstFileName, secondFileName,thirdFileName,fourthFileName
318        fprintf refNum, "normalized to   %s\r\n",normTo
319        fprintf refNum, "multiplicative factor 1-2 = %12.8g\t multiplicative factor 2-3 = %12.8g\t multiplicative factor 3-4 = %12.8g\r\n",norm12,norm23,norm34
320
321        if (numCols == 3)
322                formatStr = "%15.4g %15.4g %15.4g\r\n"
323                fprintf refnum, "The 3 columns are | Q (1/A) | I(Q) (1/cm) | std. dev. I(Q) (1/cm) |\r\n"
324                wfprintf refnum, formatStr, q3,i3,sig3
325        elseif (numCols == 6)
326                Make/O/N=(dimsize(res,0)) sigq3 = res[p][0]
327                Make/O/N=(dimsize(res,0)) qbar3 = res[p][1]
328                Make/O/N=(dimsize(res,0)) fs3 = res[p][2]
329       
330                formatStr = "%15.4g %15.4g %15.4g %15.4g %15.4g %15.4g\r\n"     
331                fprintf refnum, "The 6 columns are | Q (1/A) | I(Q) (1/cm) | std. dev. I(Q) (1/cm) | sigmaQ | meanQ | ShadowFactor|\r\n"
332                wfprintf refnum, formatStr, q3,i3,sig3,sigq3,qbar3,fs3
333        endif
334       
335        Close refnum
336       
337        Return err
338End
339
340
341//gets the scaling constant to make (best) overlap of the specified datasets
342//the scaling value is an average value of the individual scaling values for
343//every data point (at the low q end) of set 2 that overlaps with set 1
344//(as if set 1 were held fixed)
345//num2 is the highest point number in set 2 that can overlap with set 1
346//(num2+1) individual scaling values are computed
347//wave2 must be multiplied by norm to rescale to wave1
348//the scale factor is the return value
349//
350Function NCNR_GetScalingInOverlap(num2,wave1q,wave1i,wave2q,wave2i)
351        Variable num2           //largest point number of wave2 in overlap region
352        Wave wave1q,wave1i,wave2q,wave2i                //1 = first dataset, 2= second dataset
353
354        Variable ii,ival1,newi,ratio
355        ratio=0
356        ii=0
357        do
358                //get scaling factor at each point of wave 2 in the overlap region
359                newi = interp(wave2q[ii],wave1q,wave1i)         //get the intensity of wave1 at an overlap point
360                ratio += newi/wave2i[ii]                                        //get the scale factor
361                //Print "ratio = ",ratio
362                ii+=1
363        while(ii<=num2)
364        Variable val
365        val = ratio/(num2+1)            // +1 counts for point zero
366        //Print "val = ",val
367
368        Variable tol=1.05                       //5% is the preferred number (for Andrew and Lionel, at least)
369
370        ControlInfo/W=NSORT_Panel WarningCheck
371        if(( V_Value==1 ) && ( (val > tol) || (val < 1/tol) ) )
372                String str=""
373                sprintf str,"The scaling factor is more than a factor of %g from 1. Proceed with caution.\r",tol
374                DoAlert 0,str
375        endif
376       
377        Return val
378End
379
380Function ShowNSORTHelp(ctrlName) : ButtonControl
381        String ctrlName
382        DisplayHelpTopic/Z/K=1 "SANS Data Reduction Tutorial[Sort and Combine Averaged Datasets]"
383        if(V_flag !=0)
384                DoAlert 0,"The SANS Data Reduction Tutorial Help file could not be found"
385        endif
386End
387
388//button action procedure that simply closes the NSORT panel when done
389//and removes the NSORT-specific waves that were created
390// - the graph window must be killed first, so that the waves will not
391//be in use
392//
393Function NSORT_DoneButton(ctrlName) : ButtonControl
394        String ctrlName
395       
396        DoWindow/K NSORT_Panel
397       
398        DoWindow/K NSORT_Graph
399       
400        //clean up the temporary waves in the root: folder
401        SetDataFolder root:
402
403        KillDataFolder/Z LowQSet
404        KillDataFolder/Z MedQSet
405        KillDataFolder/Z HighQSet
406        KillDataFolder/Z HighestQSet
407
408End
409
410//button action procedure that plots dataset specified
411//on an NSORT graph window.
412//switch is on input controlName (low-med-high set)
413//parses partial filename from corresponding popup menu
414//builds a valid filename, loads the data (re-loads if already on graph)
415//and plots twice - once for the full datset (open symbols)
416//and once for the "trimmed" dataset (solid symbols, same color)
417//
418Function Plot_0_Button(ctrlName) : ButtonControl
419        String ctrlName
420
421        String tempName="",partialName=""
422        Variable setNum,err
423        //switch on ctrlName string - Plot_1, Plot_2, Plot_3
424       
425        strswitch(ctrlName)     // string switch
426                case "Plot_1":         
427                        //low-q
428                        setNum = 1
429                        ControlInfo/W=NSORT_Panel popup_1
430                        break
431                case "Plot_2":         
432                        //medium-q
433                        setNum = 2
434                        ControlInfo/W=NSORT_Panel popup_2
435                        break
436                case "Plot_3":         
437                        //high-q
438                        setNum = 3
439                        ControlInfo/W=NSORT_Panel popup_3
440                        break
441                case "Plot_4":         
442                        //highest-q
443                        setNum = 4
444                        ControlInfo/W=NSORT_Panel popup_4
445                        break
446        endswitch
447       
448
449        //find the file from the partial filename
450        If( (cmpstr(S_value,"")==0) || (cmpstr(S_value,"none")==0) )
451                //null selection, or "none" from any popup
452                Abort "no file selected in popup menu"
453        else
454                //selection not null
455                partialName = S_value
456                //Print partialName
457        Endif
458        //get a valid file based on this partialName and catPathName
459        tempName = FindValidFilename(partialName)
460       
461        //prepend path to tempName for read routine
462        PathInfo catPathName
463        tempName = S_path + tempName
464       
465        //load in the data (into the root directory)
466        err = LoadDataForNSORT(tempName,setNum)
467       
468        //bring the plot to the front, and put the new data on it
469        //and put cursors on the plotted dataset
470        //if the dataset is already on the graph, it will have been overwritten and updated by the load routine
471        //actually plot it twice, open(opaque) circles for the full dataset,
472        // then solid (filled) circles for the points actually kept
473        String list="",searchStr=""
474        Variable isOnPlot=0
475       
476//      DoWindow/F NSORT_Graph
477        if(WinType("NSORT_Graph")==0)
478                //no window, create one
479                strswitch(ctrlName)     // string switch
480                        case "Plot_1":         
481                                //low-q
482                                Display/K=1
483                                DoWindow/C NSORT_Graph
484                                DisplayLowSet()
485                                break
486                        case "Plot_2":         
487                                //medium-q
488                                Display/K=1
489                                DoWindow/C NSORT_Graph
490                                DisplayMedSet()
491                                break
492                        case "Plot_3":         
493                                //high-q
494                                Display/K=1
495                                DoWindow/C NSORT_Graph
496                                DisplayHighSet()
497                                break
498                        case "Plot_4":         
499                                //highest-q
500                                Display/K=1
501                                DoWindow/C NSORT_Graph
502                                DisplayHighestSet()
503                                break
504                endswitch
505                Legend
506        else
507                //plot already exists, waves have been updated
508                //make sure that the desired waves are actually on the graph, and add them if they aren't
509                list = TraceNameList("NSORT_Graph",";",1)
510       
511                strswitch(ctrlName)     // string switch
512                        case "Plot_1":         
513                                //low-q
514                                isOnPlot = strsearch(list, "LowQSet_i", 0)              // isOnPlot == -1 if it is NOT found in the list
515                                if(isOnPlot == -1)
516                                        DisplayLowSet()
517                                Endif
518                                break
519                        case "Plot_2":         
520                                //medium-q
521                                isOnPlot = strsearch(list, "MedQSet_i", 0)              // isOnPlot == -1 if it is NOT found in the list
522                                if(isOnPlot == -1)
523                                        DisplayMedSet()
524                                Endif
525                                break
526                        case "Plot_3":         
527                                //high-q
528                                isOnPlot = strsearch(list, "HighQSet_i", 0)             // isOnPlot == -1 if it is NOT found in the list
529                                if(isOnPlot == -1)
530                                        DisplayHighSet()
531                                Endif
532                                break
533                        case "Plot_4":         
534                                //highest-q
535                                isOnPlot = strsearch(list, "HighestQSet_i", 0)          // isOnPlot == -1 if it is NOT found in the list
536                                if(isOnPlot == -1)
537                                        DisplayHighestSet()
538                                Endif
539                                break
540                endswitch       
541       
542        Endif
543       
544       
545        //the stripPoints variable boxes should also update the graph, if necessary
546        return(0)
547End
548
549//adds both highest-q sets (full and trimmed) to the graph, which is
550//assumed to exist along with the high-q waves
551//
552Function DisplayHighestSet()
553        //function assumes that the window "NSORT_Graph" already exists
554//      DoWindow/F NSORT_Graph
555
556        SetDataFolder root:HighestQSet:
557        AppendToGraph/W=NSORT_Graph $"HighestQSet_i" vs $"HighestQSet_q"
558        ModifyGraph/W=NSORT_Graph log=1,mode=3,marker($"HighestQSet_i")=8,msize=2,rgb($"HighestQSet_i")=(65535,32896,0),opaque($"HighestQSet_i")=1
559        ErrorBars/W=NSORT_Graph/T=0 $"HighestQSet_i" Y,wave=($"HighestQSet_s",$"HighestQSet_s")
560        AppendToGraph/W=NSORT_Graph $"TrimHighestQSet_i" vs $"TrimHighestQSet_q"
561        ModifyGraph/W=NSORT_Graph mode($"TrimHighestQSet_i")=3,marker($"TrimHighestQSet_i")=19,msize=2,rgb($"TrimHighestQSet_i")=(65535,32896,0)
562        SetDataFolder root:
563End
564
565//adds both high-q sets (full and trimmed) to the graph, which is
566//assumed to exist along with the high-q waves
567//
568Function DisplayHighSet()
569        //function assumes that the window "NSORT_Graph" already exists
570//      DoWindow/F NSORT_Graph
571
572        SetDataFolder root:HighQSet:
573        AppendToGraph/W=NSORT_Graph $"HighQSet_i" vs $"HighQSet_q"
574        ModifyGraph/W=NSORT_Graph log=1,mode=3,marker($"HighQSet_i")=8,msize=2,rgb($"HighQSet_i")=(0,0,65535),opaque($"HighQSet_i")=1
575        ErrorBars/W=NSORT_Graph/T=0 $"HighQSet_i" Y,wave=($"HighQSet_s",$"HighQSet_s")
576        AppendToGraph/W=NSORT_Graph $"TrimHighQSet_i" vs $"TrimHighQSet_q"
577        ModifyGraph/W=NSORT_Graph mode($"TrimHighQSet_i")=3,marker($"TrimHighQSet_i")=19,msize=2,rgb($"TrimHighQSet_i")=(0,0,65535)
578        SetDataFolder root:
579End
580
581//adds both med-q sets (full and trimmed) to the graph, which is
582//assumed to exist along with the med-q waves
583//
584Function DisplayMedSet()
585        //function assumes that the window "NSORT_Graph" already exists
586//      DoWindow/F NSORT_Graph
587       
588        SetDataFolder root:MedQSet:
589        AppendToGraph/W=NSORT_Graph $"MedQSet_i" vs $"MedQSet_q"
590        ModifyGraph/W=NSORT_Graph log=1,mode=3,marker($"MedQSet_i")=8,msize=2,rgb($"MedQSet_i")=(65535,0,0),opaque($"MedQSet_i")=1
591        ErrorBars/W=NSORT_Graph/T=0 $"MedQSet_i" Y,wave=($"MedQSet_s",$"MedQSet_s")
592        AppendToGraph/W=NSORT_Graph $"TrimMedQSet_i" vs $"TrimMedQSet_q"
593        ModifyGraph/W=NSORT_Graph mode($"TrimMedQSet_i")=3,marker($"TrimMedQSet_i")=19,msize=2,rgb($"TrimMedQSet_i")=(65535,0,0)
594        SetDataFolder root:
595End
596
597//adds both low-q sets (full and trimmed) to the graph, which is
598//assumed to exist along with the low-q waves
599//
600Function DisplayLowSet()
601        //function assumes that the window "NSORT_Graph" already exists
602//      DoWindow/F NSORT_Graph
603
604        SetDataFolder root:LowQSet:
605        AppendToGraph/W=NSORT_Graph $"LowQSet_i" vs $"LowQSet_q"
606        ModifyGraph/W=NSORT_Graph log=1,mode=3,marker($"LowQSet_i")=8,msize=2,rgb($"LowQSet_i")=(2,39321,1),opaque($"LowQSet_i")=1
607        ErrorBars/W=NSORT_Graph/T=0 $"LowQSet_i" Y,wave=($"LowQSet_s",$"LowQSet_s")
608        AppendToGraph/W=NSORT_Graph $"TrimLowQSet_i" vs $"TrimLowQSet_q"
609        ModifyGraph/W=NSORT_Graph mode($"TrimLowQSet_i")=3,marker($"TrimLowQSet_i")=19,msize=2,rgb($"TrimLowQSet_i")=(2,39321,1)
610        ModifyGraph tickUnit(left)=1
611        SetDataFolder root:
612End
613
614//button action procedure to set both the main global of the catPath string
615//and also the duplicate global string used in the NSORT folder
616//after path selected, the popup menus are updated
617//
618Function NSORTPickPathButton(ctrlName) : ButtonControl
619        String ctrlName
620
621        Variable err = PickPath()               //sets global path value
622        SVAR pathStr = root:myGlobals:gCatPathStr
623       
624        //set the global string for NSORT to the selected pathname
625        String/G root:myGlobals:NSORT:gPathStr = pathStr
626       
627        //call each of the popup menu proc's to re-set the menu choices
628        //setting the checkboxes to force update
629//      CheckBox check_0,win=NSORT_Panel,value=1
630//      CheckBox check_1,win=NSORT_Panel,value=1
631//      CheckBox check_2,win=NSORT_Panel,value=1
632        LowQPopMenuProc("popup_1",1,"")
633        MedQPopMenuProc("popup_2",1,"")
634        HighQPopMenuProc("popup_3",1,"")
635        HighestQPopMenuProc("popup_4",1,"")
636       
637End
638
639
640//action procedure associated with the setvar box
641//when a value is entered, the global value is set, and the corresponding dataset
642//is updated on the plot, showing the new result of removing this number of points
643//
644//      SetVar boxes are named beg_N and end_N (so 4th element is the number)
645//
646// 1 == LowQ
647// 2 == MedQ
648// 3 == HighQ
649// 4 == HighestQ
650//
651//"Plot_1" is the low-q button name
652//"Plot_2" is the med-q button name
653//"Plot_3" is the high-q button name
654//"Plot_4" is the high-q button name
655//
656//calling plot_0_Button() responds as if that named button were pressed
657// and gets the proper number to trim directly from the SetVar
658//
659Function SetBegOrEnd(ctrlName,varNum,varStr,varName) : SetVariableControl
660        String ctrlName
661        Variable varNum
662        String varStr
663        String varName
664       
665//  global is automatically updated as the value is entered
666        String numStr= num2Str( str2num(ctrlName[4]) )
667        Plot_0_Button("Plot_"+numStr)
668        DoWindow/F NSORT_Panel
669End
670
671//this will---
672//re-load the data sets (since they may not have been loaded if they were not plotted)
673// apply the scaling to the datasets (so that they will show up in the graph)
674//and actually write the file
675//
676// then "pop" the  lists to get the new file lists with the new name in the list
677//
678Function WriteNSORTFileButton(ctrlName) : ButtonControl
679        String ctrlName
680               
681        // Put here the dialog that says if ANY of the datasets had 3-column data, the results will all have only three columns
682        // Set the number of output columns
683        Variable isAThree = 0, isASix = 0,err
684        String fileStr="",tempName
685
686        NVAR Columns1 = root:myGlobals:NSORT:gColumns1
687        NVAR Columns2 = root:myGlobals:NSORT:gColumns2
688        NVAR Columns3 = root:myGlobals:NSORT:gColumns3
689        NVAR Columns4 = root:myGlobals:NSORT:gColumns4
690        if( (Columns1 == 3) || (Columns2 == 3) || (Columns3 == 3) || (Columns4 == 3))
691                isAThree = 1
692        endif
693        if( (Columns1 == 6) || (Columns2 == 6) || (Columns3 == 6) || (Columns4 == 6))
694                isASix = 1
695        endif
696        if( (isAThree == 1) && (isASix == 1))
697                DoAlert 0, "These files contained a mixture of 3-column and 6-column data.  Only 3 columns were output."
698        endif
699       
700        //is there just one data set? if so, then dispatch to a simpler routine, since no normalization is needed
701        ControlInfo/W=NSORT_Panel popup_2               //if MedQSet is "none", then so is HighQSet and HighestQSet
702        fileStr = S_Value
703        if(cmpstr(fileStr,"none") == 0)
704                // just like in the rescaling routines, always RELOAD the data  !!!
705                //load file1
706                ControlInfo/W=NSORT_Panel popup_1
707                fileStr = S_Value
708                //get a valid file based on this partialName and catPathName
709                tempName = FindValidFilename(fileStr)
710               
711                //prepend path to tempName for read routine
712                PathInfo catPathName
713                tempName = S_path + tempName
714                err = LoadDataForNSORT(tempName,1)
715                //////end load file1
716       
717                //send just the trimmed (LowQ) set to be written out
718                WAVE lowq = $"root:LowQSet:TrimLowQSet_q"
719                WAVE lowi = $"root:LowQSet:TrimLowQSet_i"
720                WAVE lows = $"root:LowQSet:TrimLowQSet_s"
721//              WAVE/Z lowsq = $"root:LowQSet:TrimLowQSet_sq"           //these may not exist
722//              WAVE/Z lowqb = $"root:LowQSet:TrimLowQSet_qb"
723//              WAVE/Z lowfs = $"root:LowQSet:TrimLowQSet_fs"
724                WAVE/Z lowres = $"root:LowQSet:TrimLowQSet_res"
725                NVAR scaleFactor= root:myGlobals:NSORT:gScale1_2
726               
727                //
728                lowi *= scaleFactor
729                lows *= scaleFactor
730               
731                ControlInfo/W=NSORT_Panel PreviewCheck
732                if( V_Value==1 )                //if ==1, just preview and exit
733                        return(0)
734                endif
735                       
736                ControlInfo/W=NSORT_Panel popup_1
737                if(isAThree)
738                        WriteNSORTedFile(lowq,lowi,lows,S_Value,"none","none","none",S_Value,scaleFactor,1,1)
739                else
740                        WriteNSORTedFile(lowq,lowi,lows,S_Value,"none","none","none",S_Value,scaleFactor,1,1,res=lowres)
741                endif
742                //  just get the new list and return - don't actually "pop" the menu, or the selected item will change
743                SVAR popList = root:myGlobals:NSORT:gDataPopList
744                SVAR popList_3 = root:myGlobals:NSORT:gDataPopList_3
745                popList  = ReducedDataFileList("")
746                popList_3 = "none;" +  ReducedDataFileList("")
747                return(0)
748        endif
749               
750               
751        //two or more datasets, combine them
752        //have they been manually or auto-normalized?
753        ControlInfo/W=NSORT_Panel AutoCheck
754        Variable checked = V_Value
755       
756        //do the normalization and update the global scale factors displayed in the Panel
757        err = DoAutoScaleFromPanel(checked)                     // DoAutoScaleFromPanel writes out the datafile
758
759        //  just get the new list - don't actually "pop" the menu, or the selected item will change
760        SVAR popList = root:myGlobals:NSORT:gDataPopList
761        SVAR popList_3 = root:myGlobals:NSORT:gDataPopList_3
762        popList  = ReducedDataFileList("")
763        popList_3 = "none;" +  ReducedDataFileList("")
764       
765        return(0)
766End
767
768//window recreation macro for NSORT Panel
769//
770Window NSORT_Panel()
771        PauseUpdate; Silent 1           // building window...
772        NewPanel /W=(569,69,944,584)//K=2
773        ModifyPanel cbRGB=(49151,53155,65535)
774        ModifyPanel fixedSize=1
775        SetDrawLayer UserBack
776        SetDrawEnv fstyle= 5
777        DrawText 35,20,"NSORT - Rescale and combine 1-D files"
778        DrawLine 0,55,346,55
779        DrawLine 0,128,346,128
780        DrawLine 0,214,346,214
781        DrawLine 0,295,346,295
782        DrawLine 0,372,347,372
783        DrawLine 0,460,346,460
784       
785        SetDrawEnv fstyle= 5
786        DrawText 5,74,"Low Q:"
787        SetDrawEnv fstyle= 5
788        DrawText 5,148,"Medium Q:"
789        SetDrawEnv fstyle= 5
790        DrawText 8,234,"High Q: (or none)"
791        SetDrawEnv fstyle= 5
792        DrawText 8,314,"Highest Q: (or none)"
793        SetDrawEnv fstyle= 4
794        DrawText 178,75,"Delete Points?"
795        SetDrawEnv fstyle= 4
796        DrawText 178,146,"Delete Points?"
797        SetDrawEnv fstyle= 4
798        DrawText 184,236,"Delete Points?"
799        SetDrawEnv fstyle= 4
800        DrawText 184,316,"Delete Points?"
801        DrawText 31,456,"To Manually scale data, enter scale factors above"
802       
803        Button NSORT_Done,pos={274,483},size={50,20},proc=NSORT_DoneButton,title="Done"
804        Button NSORT_Done,help={"closes the panel"}
805        Button Plot_1,pos={279,63},size={50,20},proc=Plot_0_Button,title="Plot"
806        Button Plot_1,help={"Plots the dataset from the popup, showing the full set as open circles and the trimmed set as solid circles"}
807        Button Plot_2,pos={283,144},size={50,20},proc=Plot_0_Button,title="Plot"
808        Button Plot_2,help={"Plots the dataset from the popup, showing the full set as open circles and the trimmed set as solid circles"}
809        Button Plot_3,pos={284,223},size={50,20},proc=Plot_0_Button,title="Plot"
810        Button Plot_3,help={"Plots the dataset from the popup, showing the full set as open circles and the trimmed set as solid circles"}
811        Button Plot_4,pos={284.00,303.00},size={50.00,20.00},proc=Plot_0_Button,title="Plot"
812        Button Plot_4,help={"Plots the dataset from the popup, showing the full set as open circles and the trimmed set as solid circles"}
813
814        Button PathButton,pos={6,26},size={80,20},proc=NSORTPickPathButton,title="Pick Path"
815        Button PathButton,help={"Select the local path to the folder containing your SANS data"}
816        Button helpButton,pos={340,26},size={25,20},proc=ShowNSORTHelp,title="?"
817        Button helpButton,help={"Show the help file for sorting and internormalizing 1-D data sets"}
818        SetVariable setPath,pos={95,29},size={240,14},title="Path:",fSize=10
819        SetVariable setPath,limits={0,0,0},value= root:myGlobals:NSORT:gPathStr
820        SetVariable setPath,help={"The current path to the local folder with SANS data"}
821        SetVariable end_1,pos={182,101},size={80,14},proc=SetBegOrEnd,title="End Pts"
822        SetVariable end_1,fSize=10,help={"How many points to remove from the high-q end of this dataset"}
823        SetVariable end_1,limits={-Inf,Inf,0},value= root:myGlobals:NSORT:gPtsEnd1
824        SetVariable end_2,pos={182,176},size={80,14},proc=SetBegOrEnd,title="End Pts"
825        SetVariable end_2,fSize=10,help={"How many points to remove from the high-q end of this dataset"}
826        SetVariable end_2,limits={-Inf,Inf,0},value= root:myGlobals:NSORT:gPtsEnd2
827        SetVariable end_3,pos={182,269},size={80,14},proc=SetBegOrEnd,title="End Pts"
828        SetVariable end_3,fSize=10,help={"How many points to remove from the high-q end of this dataset"}
829        SetVariable end_3,limits={-Inf,Inf,0},value= root:myGlobals:NSORT:gPtsEnd3
830        SetVariable end_4,pos={182.00,349.00},size={80.00,16.00},proc=SetBegOrEnd,title="End Pts"
831        SetVariable end_4,help={"How many points to remove from the high-q end of this dataset"}
832        SetVariable end_4,fSize=10
833        SetVariable end_4,limits={-inf,inf,0},value= root:myGlobals:NSORT:gPtsEnd4
834        SetVariable beg_1,pos={182,79},size={80,14},proc=SetBegOrEnd,title="Beg Pts"
835        SetVariable beg_1,fSize=10,help={"How many points to remove from the low-q end of this dataset"}
836        SetVariable beg_1,limits={-Inf,Inf,0},value= root:myGlobals:NSORT:gPtsBeg1
837        SetVariable beg_2,pos={182,155},size={80,14},proc=SetBegOrEnd,title="Beg Pts"
838        SetVariable beg_2,fSize=10,help={"How many points to remove from the low-q end of this dataset"}
839        SetVariable beg_2,limits={-Inf,Inf,0},value= root:myGlobals:NSORT:gPtsBeg2
840        SetVariable beg_3,pos={182,246},size={80,14},proc=SetBegOrEnd,title="Beg Pts"
841        SetVariable beg_3,fSize=10,help={"How many points to remove from the low-q end of this dataset"}
842        SetVariable beg_3,limits={-Inf,Inf,0},value= root:myGlobals:NSORT:gPtsBeg3
843        SetVariable beg_4,pos={182.00,326.00},size={80.00,16.00},proc=SetBegOrEnd,title="Beg Pts"
844        SetVariable beg_4,help={"How many points to remove from the low-q end of this dataset"}
845        SetVariable beg_4,fSize=10
846        SetVariable beg_4,limits={-inf,inf,0},value= root:myGlobals:NSORT:gPtsBeg4
847        Button DoCombine,pos={13,483},size={160,20},proc=WriteNSORTFileButton,title="Write Combined File"
848        Button DoCombine,help={"Combine and normalize the selected files as specifed"}
849        SetVariable scale_12,pos={159,381},size={160,14},proc=SetScale_12,title="Mult factor 1-2"
850        SetVariable scale_12,fSize=10,help={"Factor that will multiply medium-q set to scale to low-q set"}
851        SetVariable scale_12,limits={-Inf,Inf,0},value= root:myGlobals:NSORT:gScale1_2
852        SetVariable scale_23,pos={159,401},size={160,14},proc=SetScale_23,title="Mult factor 2-3"
853        SetVariable scale_23,fSize=10,help={"Factor that will multiply high-q set to scale to medium-q set"}
854        SetVariable scale_23,limits={-Inf,Inf,0},value= root:myGlobals:NSORT:gScale2_3
855        SetVariable scale_34,pos={159.00,421.00},size={160.00,16.00},proc=SetScale_34,title="Mult factor 3-4"
856        SetVariable scale_34,help={"Factor that will multiply highest-q set to scale to high-q set"}
857        SetVariable scale_34,fSize=10
858        SetVariable scale_34,limits={-inf,inf,0},value= root:myGlobals:NSORT:gScale3_4
859        CheckBox check1,pos={5,105},size={160,20},proc=CheckProc,title="Normalize to this file",value=1
860        CheckBox check1,help={"If checked, the combined dataset will be normalized to this dataset"}
861        CheckBox check2,pos={5,185},size={160,20},proc=CheckProc,title="Normalize to this file",value=0
862        CheckBox check2,help={"If checked, the combined dataset will be normalized to this dataset"}
863        CheckBox check3,pos={4,270},size={160,20},proc=CheckProc,title="Normalize to this file",value=0
864        CheckBox check3,help={"If checked, the combined dataset will be normalized to this dataset"}
865        CheckBox check4,pos={4.00,350.00},size={107.00,16.00},proc=CheckProc,title="Normalize to this file"
866        CheckBox check4,help={"If checked, the combined dataset will be normalized to this dataset"}
867        CheckBox check4,value= 0
868        PopupMenu popup_1,pos={6,77},size={99,19},proc=LowQPopMenuProc
869        PopupMenu popup_1,mode=1,value= #"root:myGlobals:NSORT:gDataPopList"
870        PopupMenu popup_1,help={"Choose the dataset with the lowest overall q-value (longest detector distance)"}
871        PopupMenu popup_2,pos={6,153},size={99,19},proc=MedQPopMenuProc
872        PopupMenu popup_2,mode=1,value= #"root:myGlobals:NSORT:gDataPopList_3"
873        PopupMenu popup_2,help={"Choose the dataset with the intermediate q-values (\"medium\" detector distance)"}
874        PopupMenu popup_3,pos={6,239},size={99,19},proc=HighQPopMenuProc
875        PopupMenu popup_3,mode=1,value= #"root:myGlobals:NSORT:gDataPopList_3"
876        PopupMenu popup_3,help={"Choose the dataset with the highest overall q-value (shortest detector distance), or NONE if no third set desired"}
877        PopupMenu popup_4,pos={6.00,319.00},size={58.00,23.00},proc=HighestQPopMenuProc
878        PopupMenu popup_4,help={"Choose the dataset with the highest overall q-value (shortest detector distance), or NONE if no fourth set desired"}
879        PopupMenu popup_4,mode=1,popvalue="none",value= #"root:myGlobals:NSORT:gDataPopList_3"
880        CheckBox AutoCheck,pos={14,386},size={100,20},title="Auto Scale",value=0
881        CheckBox AutoCheck,help={"If checked, the scale factor will be automatically determined, if not checked, the current values in the fields will be used"}
882        CheckBox PreviewCheck,pos={15,465},size={74,14},title="Preview Only",value= 0
883        CheckBox WarningCheck,pos={111,465},size={93,14},title="Overlap warning?",value= 1
884EndMacro
885
886//sets the scale factor (multiplicative) between sets 1 and 2
887//re-sets the global variable
888//
889Function SetScale_12(ctrlName,varNum,varStr,varName) : SetVariableControl
890        String ctrlName
891        Variable varNum
892        String varStr
893        String varName
894
895        Variable/G root:myGlobals:NSORT:gScale1_2 = varNum
896       
897End
898
899//sets the scale factor (multiplicative) between sets 2 and 3
900//re-sets the global variable
901//
902Function SetScale_23(ctrlName,varNum,varStr,varName) : SetVariableControl
903        String ctrlName
904        Variable varNum
905        String varStr
906        String varName
907
908        Variable/G root:myGlobals:NSORT:gScale2_3 = varNum
909End
910
911//sets the scale factor (multiplicative) between sets 3 and 4
912//re-sets the global variable
913//
914Function SetScale_34(ctrlName,varNum,varStr,varName) : SetVariableControl
915        String ctrlName
916        Variable varNum
917        String varStr
918        String varName
919
920        Variable/G root:myGlobals:NSORT:gScale3_4 = varNum
921End
922
923//control procedures for the checkboxes to specify which file is to be
924//held fixed (so all other files are normalized to the checked file
925//the three checkboxes behave as "radio buttons" - only one can be checked
926//
927Function CheckProc(ctrlName,checked) : CheckBoxControl
928        String ctrlName
929        Variable checked
930       
931        //controls the three checkboxes to act as "radio buttons" to have only one file to
932        //normalize to.
933        //all three boxes should call this routine
934       
935        //do the "radio button control"
936        do
937                if(cmpstr(ctrlName,"check2") == 0)
938                        CheckBox check1 value=0
939                        CheckBox check2 value=1
940                        CheckBox check3 value=0
941                        CheckBox check4 value=0
942                        Variable/G root:myGlobals:NSORT:gNormToNum = 2
943                        break
944                Endif
945                if(cmpstr(ctrlName,"check3") == 0)
946                        CheckBox check1 value=0
947                        CheckBox check2 value=0
948                        CheckBox check3 value=1
949                        CheckBox check4 value=0
950                        Variable/G root:myGlobals:NSORT:gNormToNum = 3
951                        break
952                Endif
953                if(cmpstr(ctrlName,"check4") == 0)
954                        CheckBox check1 value=0
955                        CheckBox check2 value=0
956                        CheckBox check3 value=0
957                        CheckBox check4 value=1
958                        Variable/G root:myGlobals:NSORT:gNormToNum = 4
959                        break
960                Endif
961                //default case is normalize to file1
962                CheckBox check1 value=1
963                CheckBox check2 value=0
964                CheckBox check3 value=0
965                        CheckBox check4 value=0
966                Variable/G root:myGlobals:NSORT:gNormToNum = 1
967        While(0)
968       
969        ControlUpdate/A/W=NSORT_Panel
970        DoUpdate
971               
972End
973
974//when menu is popped, it gets a valid list to display and updates the control
975//
976// 2002- always refreshes, as new (fast) filter is used
977Function LowQPopMenuProc(ctrlName,popNum,popStr) : PopupMenuControl
978        String ctrlName
979        Variable popNum
980        String popStr
981
982        String/G root:myGlobals:NSORT:gDataPopList = ReducedDataFileList("")
983        ControlUpdate popup_1
984
985        return(0)
986End
987
988//when menu is popped, it gets a valid list to display and updates the control
989//
990Function MedQPopMenuProc(ctrlName,popNum,popStr) : PopupMenuControl
991        String ctrlName
992        Variable popNum
993        String popStr
994               
995        String/G root:myGlobals:NSORT:gDataPopList_3 = "none;" +  ReducedDataFileList("")
996        ControlUpdate popup_2
997        if(cmpstr(popStr,"none")==0)
998                PopupMenu popup_3,mode=1        //force "none" (item #1) to be the selection
999                CheckBox AutoCheck,value=0      //un-check the auto-scale checkbox
1000                DoAlert 0,"You have only one data set. Auto Scaling has been unchecked and Mult Factor 1-2 will be applied to your data. Remember to re-check this as needed"// remind the user of this fact
1001                RemoveFromGraph/Z MedQSet_i,TrimMedQSet_i,HighQSet_i,TrimHighQSet_i             //remove the data from the graph
1002        Endif   
1003        return(0)
1004End
1005
1006//when menu is popped, it gets a valid list to display and updates the control
1007// - will be different, since set 3 can also be "none" if only 2 sets
1008//are to be NSORTed
1009//
1010Function HighQPopMenuProc(ctrlName,popNum,popStr) : PopupMenuControl
1011        String ctrlName
1012        Variable popNum
1013        String popStr
1014
1015        //add the option "none" to the file list (which should already end with a semicolon)
1016        String/G root:myGlobals:NSORT:gDataPopList_3 = "none;" +  ReducedDataFileList("")
1017
1018        ControlUpdate/W=NSORT_Panel popup_3
1019        if(cmpstr(popStr,"none")==0)
1020                RemoveFromGraph/Z HighQSet_i,TrimHighQSet_i             //remove the data from the graph
1021        Endif   
1022        ControlInfo/W=NSORT_Panel popup_2
1023        if(cmpstr(S_Value,"none")==0)
1024                PopupMenu popup_3,win=NSORT_Panel,mode=1        //force "none" (item #1) to be the selection if medium is none
1025        endif
1026        return(0)       
1027End
1028
1029
1030//when menu is popped, it gets a valid list to display and updates the control
1031// - will be different, since set 3 can also be "none" if only 2 sets
1032//are to be NSORTed
1033//
1034Function HighestQPopMenuProc(ctrlName,popNum,popStr) : PopupMenuControl
1035        String ctrlName
1036        Variable popNum
1037        String popStr
1038
1039        //add the option "none" to the file list (which should already end with a semicolon)
1040        String/G root:myGlobals:NSORT:gDataPopList_3 = "none;" +  ReducedDataFileList("")
1041
1042        ControlUpdate/W=NSORT_Panel popup_4
1043        if(cmpstr(popStr,"none")==0)
1044                RemoveFromGraph/Z HighestQSet_i,TrimHighestQSet_i               //remove the data from the graph
1045        Endif   
1046        ControlInfo/W=NSORT_Panel popup_2
1047        if(cmpstr(S_Value,"none")==0)
1048                PopupMenu popup_3,win=NSORT_Panel,mode=1        //force "none" (item #1) to be the selection if medium is none
1049                PopupMenu popup_4,win=NSORT_Panel,mode=1        //force "none" (item #1) to be the selection if medium is none
1050        endif
1051        ControlInfo/W=NSORT_Panel popup_3
1052        if(cmpstr(S_Value,"none")==0)
1053                PopupMenu popup_4,win=NSORT_Panel,mode=1        //force "none" (item #1) to be the selection if medium is none
1054        endif
1055        return(0)       
1056End
1057
1058//be sure to use the "Trim.." datasets that have had the bad points removed
1059//and then do the scaling based on the choices in the panel
1060//input (auto) is a switch
1061//
1062Function DoAutoScaleFromPanel(auto)
1063        Variable auto           //if auto == 1, do the scaling, if 0, use manual scale values
1064
1065        NVAR normTo = root:myGlobals:NSORT:gNormToNum
1066        Variable err=0,setNum,norm12,norm23,norm34
1067        String fileStr="",tempName="",name1="",name2="",name3="",normToStr="",name4=""
1068       
1069//Set the number of output columns
1070        Variable numOutputColumns = 0
1071
1072        NVAR Columns1 = root:myGlobals:NSORT:gColumns1
1073        NVAR Columns2 = root:myGlobals:NSORT:gColumns2
1074        NVAR Columns3 = root:myGlobals:NSORT:gColumns3
1075        NVAR Columns4 = root:myGlobals:NSORT:gColumns4
1076        if( (Columns1 == 3) || (Columns2 == 3) || (Columns3 == 3) || (Columns4 == 3) )
1077                numOutputColumns = 3
1078        else
1079                if( (Columns1 == 6) && (Columns2 == 6) && ((Columns3 == 0) || (Columns3 == 6)) || (Columns4 == 6) )
1080                        numOutputColumns = 6
1081                endif
1082        endif
1083
1084        //rescale 1-2
1085       
1086        //load file1
1087        ControlInfo/W=NSORT_Panel popup_1
1088        fileStr = S_Value
1089        name1 = fileStr
1090        setNum = 1
1091        //get a valid file based on this partialName and catPathName
1092        tempName = FindValidFilename(fileStr)
1093       
1094        //prepend path to tempName for read routine
1095        PathInfo catPathName
1096        tempName = S_path + tempName
1097        err = LoadDataForNSORT(tempName,setNum)
1098        //////end load file1
1099       
1100        //load file2
1101        ControlInfo/W=NSORT_Panel popup_2
1102        fileStr = S_Value
1103        name2 = fileStr
1104        setNum = 2
1105        //get a valid file based on this partialName and catPathName
1106        tempName = FindValidFilename(fileStr)
1107       
1108        //prepend path to tempName for read routine
1109        PathInfo catPathName
1110        tempName = S_path + tempName
1111        err = LoadDataForNSORT(tempName,setNum)
1112        //////end load file2
1113       
1114        //load file3 , if necessary
1115        ControlInfo/W=NSORT_Panel popup_3
1116        fileStr = S_Value
1117        name3 = fileStr
1118        setNum = 3
1119        if(cmpstr(fileStr,"none") == 0)
1120                //do nothing
1121        else
1122                //get a valid file based on this partialName and catPathName
1123                tempName = FindValidFilename(fileStr)
1124       
1125                //prepend path to tempName for read routine
1126                PathInfo catPathName
1127                tempName = S_path + tempName
1128                err = LoadDataForNSORT(tempName,setNum)
1129        Endif
1130        //////end load file3
1131       
1132        //load file4 , if necessary
1133        ControlInfo/W=NSORT_Panel popup_4
1134        fileStr = S_Value
1135        name4 = fileStr
1136        setNum = 4
1137        if(cmpstr(fileStr,"none") == 0)
1138                //do nothing
1139        else
1140                //get a valid file based on this partialName and catPathName
1141                tempName = FindValidFilename(fileStr)
1142       
1143                //prepend path to tempName for read routine
1144                PathInfo catPathName
1145                tempName = S_path + tempName
1146                err = LoadDataForNSORT(tempName,setNum)
1147        Endif
1148        //////end load file4
1149       
1150       
1151        //assign filename of file to normalize to
1152        switch(normTo)
1153                case 1:
1154                        normToStr = name1
1155                        break
1156                case 2:
1157                        normToStr = name2
1158                        break
1159                case 3:
1160                        normToStr = name3
1161                        break
1162                case 4:
1163                        normToStr = name4
1164                        break
1165        endswitch
1166
1167
1168        Variable n1,n2,n12,num2
1169        Variable n3,n123
1170        Variable n4,n1234
1171       
1172   if(numOutputColumns == 3) //Start the 3-column specific stuff here.
1173                //order points in sets 1-2, indexing overlap region
1174                //put result in temporary waves
1175                WaveStats/Q $"root:LowQSet:TrimLowQSet_q"
1176                n1 = V_npnts
1177                WaveStats/Q $"root:MedQSet:TrimMedQSet_q"
1178                n2 = V_npnts
1179                n12 = n1+ n2
1180               
1181                Make/O/N=(n12) q12,i12,sig12
1182                WAVE lowq = $"root:LowQSet:TrimLowQSet_q"
1183                WAVE medq = $"root:MedQSet:TrimMedQSet_q"
1184                WAVE lowi = $"root:LowQSet:TrimLowQSet_i"
1185                WAVE medi =  $"root:MedQSet:TrimMedQSet_i"
1186                WAVE lows = $"root:LowQSet:TrimLowQSet_s"
1187                WAVE meds = $"root:MedQSet:TrimMedQSet_s"
1188                q12[0,n1-1] = lowq[p]
1189                q12[n1,n1+n2-1]= medq[p-n1]
1190                i12[0,n1-1] = lowi[p]
1191                i12[n1,n1+n2-1]= medi[p-n1]
1192                sig12[0,n1-1] = lows[p]
1193                sig12[n1,n1+n2-1]= meds[p-n1]
1194               
1195                Sort q12, q12,i12,sig12
1196                /////////////////
1197               
1198                //find the maximum point number of set 2  in the overlap region
1199                FindLevel/P/Q medq,(lowq[n1-1])
1200                num2 = trunc(V_levelX)
1201                //Print "num2 = ",num2
1202               
1203                if (auto)
1204                        //there must be overlap points to use auto-scaling
1205                        if(numtype(num2) != 0)
1206                                Abort "There are no data points in the overlap region. Either reduce the number of deleted points or use manual scaling."
1207                        endif
1208                        //do auto-scaling of data
1209                        norm12 = NCNR_GetScalingInOverlap(num2,lowq,lowi,medq,medi)
1210                        //Set the global variable for the 1-2 scale factor
1211                        Variable/G root:myGlobals:NSORT:gScale1_2 = norm12
1212                else
1213                        //use the value from the panel ( which is the global)
1214                        NVAR temp12 = root:myGlobals:NSORT:gScale1_2
1215                        norm12 = temp12
1216                Endif
1217               
1218                If(normTo== 2)
1219                        //normalize to second file, so multiply 1st by 1/norm
1220                        norm12 = 1/norm12
1221                        lowi *= norm12
1222                        lows *= norm12
1223                else
1224                        //normalize to first file, OR THIRD FILE so multiply 2nd by norm
1225                        medi *= norm12
1226                        meds *= norm12
1227                Endif
1228               
1229                //Print "NSORT-ed ",name1," + ", name2
1230                //Print "normalized to ",normTo
1231                //Print "multiplicative factor = ",norm12
1232               
1233               
1234                //Make the combined, scaled dataset by overwriting the old sets
1235                Make/O/N=(n12) q12,i12,sig12
1236                q12[0,n1-1] = lowq[p]
1237                q12[n1,n1+n2-1]= medq[p-n1]
1238                i12[0,n1-1] = lowi[p]
1239                i12[n1,n1+n2-1]= medi[p-n1]
1240                sig12[0,n1-1] = lows[p]
1241                sig12[n1,n1+n2-1]= meds[p-n1]
1242               
1243                Sort q12, q12,i12,sig12
1244                //at this point 1-2 are combined
1245               
1246                ControlUpdate/A/W=NSORT_Panel
1247                DoUpdate
1248               
1249                //do we need to continue, or write out the set here and stop?
1250                if(cmpstr(name3,"none") == 0)
1251                        //stop here
1252                        norm23 = 1              //norm23 was not used
1253                        Variable/G root:myGlobals:NSORT:gScale2_3 = 1
1254                        //If any of them have three columns write three column data
1255                       
1256                        ControlInfo/W=NSORT_Panel PreviewCheck
1257                        if( V_Value==0 )                //if zero skip the preview and write out the file
1258                                err=WriteNSORTedFile(q12,i12,sig12,name1,name2,name3,name4,normToStr,norm12,norm23,norm34)
1259                        endif
1260                        //cleanup waves before exiting
1261                        KillWaves/Z q12,i12,sig12
1262                        return err
1263                Endif
1264               
1265                //need to add the third file... which was already loaded at the top of the function
1266                /////
1267                //order points in sets 12-3, indexing overlap region
1268                //put result in temporary waves
1269                WaveStats/Q q12
1270                n12 = V_npnts
1271                WaveStats/Q $"root:HighQSet:TrimHighQSet_q"
1272                n3 = V_npnts
1273                n123 = n12+ n3
1274               
1275                Make/O/N=(n123) q123,i123,sig123
1276                WAVE highq = $"root:HighQSet:TrimHighQSet_q"
1277                WAVE highi = $"root:HighQSet:TrimHighQSet_i"
1278                WAVE highs = $"root:HighQSet:TrimHighQSet_s"
1279       
1280                q123[0,n12-1] = q12[p]
1281                q123[n1,n12+n3-1]= highq[p-n12]
1282                i123[0,n12-1] = i12[p]
1283                i123[n1,n12+n3-1]= highi[p-n12]
1284                sig123[0,n12-1] = sig12[p]
1285                sig123[n1,n12+n3-1]= highs[p-n12]
1286               
1287                Sort q123, q123,i123,sig123
1288                /////////////////
1289               
1290                //find the maximum point number of set 2  in the overlap region
1291                FindLevel/P/Q highq,(q12[n12-1])
1292                num2 = trunc(V_levelX)
1293                //Print "num2 = ",num2
1294               
1295                if (auto)
1296                        //there must be overlap points to use auto-scaling
1297                        if(numtype(num2) != 0)
1298                                Abort "There are no data points in the overlap region. Either reduce the number of deleted points or use manual scaling."
1299                        endif
1300                        //do auto-scaling of data
1301                        norm23 = NCNR_GetScalingInOverlap(num2,q12,i12,highq,highi)
1302                        //Set the global variable for the 12 - 3 scale factor
1303                        Variable/G root:myGlobals:NSORT:gScale2_3 = norm23
1304                else
1305                        //use the value from the panel ( which is the global)
1306                        NVAR temp23 = root:myGlobals:NSORT:gScale2_3
1307                        norm23 = temp23
1308                Endif
1309               
1310                If( (normTo== 1) || (normTo ==2) )
1311                        //normalize to first or second file, so multiply third by norm23
1312                        highi *= norm23
1313                        highs *= norm23
1314                else
1315                        //normalize to THIRD file, 1-2 by 1/norm23
1316                        norm23 = 1/norm23
1317                        i12 *= norm23
1318                        sig12 *= norm23
1319                        // for the display, scale the trimmed sets 1 and 2
1320                        lowi *= norm23
1321                        lows *= norm23
1322                        medi *= norm23
1323                        meds *= norm23
1324                Endif
1325               
1326                ControlUpdate/A/W=NSORT_Panel
1327                DoUpdate
1328
1329                //Print "NSORT-ed ",name1," + ", name2, " + ", name3
1330                //Print "normalized to ",normTo
1331                //Print "multiplicative factor 1-2 = ",norm12," multiplicative factor 12 - 3 = ",norm23
1332               
1333               
1334                Make/O/N=(n123) q123,i123,sig123
1335                q123[0,n12-1] = q12[p]
1336                q123[n12,n12+n3-1]= highq[p-n12]
1337                i123[0,n12-1] = i12[p]
1338                i123[n12,n12+n3-1]= highi[p-n12]
1339                sig123[0,n12-1] = sig12[p]
1340                sig123[n12,n12+n3-1]= highs[p-n12]
1341               
1342                Sort q123, q123,i123,sig123
1343                //at this point 12 - 3 are combined
1344                //write out the set here and stop
1345       
1346                ControlInfo/W=NSORT_Panel PreviewCheck
1347                if( V_Value==0 )                //if zero skip the preview and write out the file
1348                        err=WriteNSORTedFile(q123,i123,sig123,name1,name2,name3,name4,normToStr,norm12,norm23,norm34)
1349                endif
1350                //cleanup waves before exiting
1351                KillWaves/Z q12,i12,sig12,q123,i123,sig123
1352               
1353               
1354                //do we need to continue, or write out the set here and stop?
1355                if(cmpstr(name4,"none") == 0)
1356                        //stop here
1357                        norm34 = 1              //norm34 was not used
1358                        Variable/G root:myGlobals:NSORT:gScale3_4 = 1
1359                        //If any of them have three columns write three column data
1360                       
1361                        ControlInfo/W=NSORT_Panel PreviewCheck
1362                        if( V_Value==0 )                //if zero skip the preview and write out the file
1363                                err=WriteNSORTedFile(q123,i123,sig123,name1,name2,name3,name4,normToStr,norm12,norm23,norm34)
1364                        endif
1365                        //cleanup waves before exiting
1366                        KillWaves/Z q123,i123,sig123
1367                        return err
1368                Endif
1369               
1370                //need to add the fourth file... which was already loaded at the top of the function
1371                /////
1372                //order points in sets 123-4, indexing overlap region
1373                //put result in temporary waves
1374                WaveStats/Q q123
1375                n123 = V_npnts
1376                WaveStats/Q $"root:HighestQSet:TrimHighestQSet_q"
1377                n4 = V_npnts
1378                n1234 = n123 + n4
1379               
1380                Make/O/N=(n1234) q1234,i1234,sig1234
1381                WAVE highestq = $"root:HighestQSet:TrimHighestQSet_q"
1382                WAVE highesti = $"root:HighestQSet:TrimHighestQSet_i"
1383                WAVE highests = $"root:HighestQSet:TrimHighestQSet_s"
1384       
1385                q1234[0,n123-1] = q123[p]
1386                q1234[n12,n123+n4-1]= highestq[p-n123]
1387                i1234[0,n123-1] = i123[p]
1388                i1234[n12,n123+n4-1]= highesti[p-n123]
1389                sig1234[0,n123-1] = sig123[p]
1390                sig1234[n12,n123+n4-1]= highests[p-n123]
1391               
1392                Sort q1234, q1234,i1234,sig1234
1393                /////////////////
1394               
1395                //find the maximum point number of set 2  in the overlap region
1396                FindLevel/P/Q highestq,(q123[n123-1])
1397                num2 = trunc(V_levelX)
1398                //Print "num2 = ",num2
1399               
1400                if (auto)
1401                        //there must be overlap points to use auto-scaling
1402                        if(numtype(num2) != 0)
1403                                Abort "There are no data points in the overlap region. Either reduce the number of deleted points or use manual scaling."
1404                        endif
1405                        //do auto-scaling of data
1406                        norm34 = NCNR_GetScalingInOverlap(num2,q123,i123,highestq,highesti)
1407                        //Set the global variable for the 123 - 4 scale factor
1408                        Variable/G root:myGlobals:NSORT:gScale3_4 = norm34
1409                else
1410                        //use the value from the panel ( which is the global)
1411                        NVAR temp34 = root:myGlobals:NSORT:gScale3_4
1412                        norm34 = temp34
1413                Endif
1414               
1415// normalization
1416                switch (normTo)
1417                        case 1:
1418                        case 2:
1419                        case 3:
1420                                //normalize to first or second or third file, so multiply fourth by norm34
1421                                highesti *= norm34
1422                                highests *= norm34
1423                                break
1424                        case 4:
1425                                //normalize to FOURTH file, 123 by multiplicative factor 1/norm34
1426                                norm34 = 1/norm34
1427                                i123 *= norm34
1428                                sig123 *= norm34
1429                                // for the display, scale the trimmed sets 1 and 2 and 3
1430                                lowi *= norm34
1431                                lows *= norm34
1432                                medi *= norm34
1433                                meds *= norm34
1434                                highi *= norm34
1435                                highs *= norm34
1436                                break
1437                endswitch
1438                               
1439                ControlUpdate/A/W=NSORT_Panel
1440                DoUpdate
1441
1442                //Print "NSORT-ed ",name1," + ", name2, " + ", name3
1443                //Print "normalized to ",normTo
1444                //Print "multiplicative factor 1-2 = ",norm12," multiplicative factor 12 - 3 = ",norm23
1445               
1446               
1447                Make/O/N=(n1234) q1234,i1234,sig1234
1448                q1234[0,n123-1] = q123[p]
1449                q1234[n123,n123+n4-1]= highestq[p-n123]
1450                i1234[0,n123-1] = i123[p]
1451                i1234[n123,n123+n4-1]= highesti[p-n123]
1452                sig1234[0,n123-1] = sig123[p]
1453                sig1234[n123,n123+n4-1]= highests[p-n123]
1454               
1455                Sort q123, q123,i123,sig123
1456                //at this point 12 - 3 are combined
1457                //write out the set here and stop
1458       
1459                ControlInfo/W=NSORT_Panel PreviewCheck
1460                if( V_Value==0 )                //if zero skip the preview and write out the file
1461                        err=WriteNSORTedFile(q123,i123,sig123,name1,name2,name3,name4,normToStr,norm12,norm23,norm34)
1462                endif
1463                //cleanup waves before exiting
1464                KillWaves/Z q12,i12,sig12,q123,i123,sig123
1465               
1466               
1467               
1468               
1469                //combined dataset will already be displayed if the NSORT_Graph is open
1470       
1471                ////////////////
1472                return err
1473   endif // End the 3-column specific stuff here
1474
1475   if(numOutputColumns == 6) // Start the 6-column specific stuff here
1476                //order points in sets 1-2, indexing overlap region
1477                //put result in temporary waves
1478                WaveStats/Q $"root:LowQSet:TrimLowQSet_q"
1479                n1 = V_npnts
1480                WaveStats/Q $"root:MedQSet:TrimMedQSet_q"
1481                n2 = V_npnts
1482                n12 = n1+ n2
1483               
1484                Make/O/N=(n12) q12,i12,sig12,sq12,qb12,fs12
1485                Make/O/N=(n12,3) res12
1486                WAVE lowq = $"root:LowQSet:TrimLowQSet_q"
1487                WAVE medq = $"root:MedQSet:TrimMedQSet_q"
1488                WAVE lowi = $"root:LowQSet:TrimLowQSet_i"
1489                WAVE medi =  $"root:MedQSet:TrimMedQSet_i"
1490                WAVE lows = $"root:LowQSet:TrimLowQSet_s"
1491                WAVE meds = $"root:MedQSet:TrimMedQSet_s"
1492                WAVE lowres = $"root:LowQSet:TrimLowQSet_res"
1493                WAVE medres = $"root:MedQSet:TrimMedQSet_res"
1494               
1495                q12[0,n1-1] = lowq[p]
1496                q12[n1,n1+n2-1]= medq[p-n1]
1497                i12[0,n1-1] = lowi[p]
1498                i12[n1,n1+n2-1]= medi[p-n1]
1499                sig12[0,n1-1] = lows[p]
1500                sig12[n1,n1+n2-1]= meds[p-n1]
1501                sq12[0,n1-1] = lowres[p][0]
1502                sq12[n1,n1+n2-1]= medres[p-n1][0]
1503                qb12[0,n1-1] = lowres[p][1]
1504                qb12[n1,n1+n2-1]= medres[p-n1][1]
1505                fs12[0,n1-1] = lowres[p][2]
1506                fs12[n1,n1+n2-1]= medres[p-n1][2]
1507
1508               
1509                Sort q12, q12,i12,sig12,sq12,qb12,fs12
1510                /////////////////
1511               
1512                //find the maximum point number of set 2  in the overlap region
1513                FindLevel/P/Q medq,(lowq[n1-1])
1514                num2 = trunc(V_levelX)
1515                //Print "num2 = ",num2
1516               
1517                if (auto)
1518                        //there must be overlap points to use auto-scaling
1519                        if(numtype(num2) != 0)
1520                                Abort "There are no data points in the overlap region. Either reduce the number of deleted points or use manual scaling."
1521                        endif
1522                        //do auto-scaling of data
1523                        norm12 = NCNR_GetScalingInOverlap(num2,lowq,lowi,medq,medi)
1524                        //Set the global variable for the 1-2 scale factor
1525                        Variable/G root:myGlobals:NSORT:gScale1_2 = norm12
1526                else
1527                        //use the value from the panel ( which is the global)
1528                        NVAR temp12 = root:myGlobals:NSORT:gScale1_2
1529                        norm12 = temp12
1530                Endif
1531               
1532                If(normTo== 2)
1533                        //normalize to second file, so multiply 1st by 1/norm
1534                        norm12 = 1/norm12
1535                        lowi *= norm12
1536                        lows *= norm12
1537                else
1538                        //normalize to first file, OR THIRD FILE so multiply 2nd by norm
1539                        medi *= norm12
1540                        meds *= norm12
1541                Endif
1542               
1543                //Print "NSORT-ed ",name1," + ", name2
1544                //Print "normalized to ",normTo
1545                //Print "multiplicative factor = ",norm12
1546                ControlUpdate/A/W=NSORT_Panel
1547                DoUpdate
1548
1549               
1550                //Make the combined, scaled dataset by overwriting the old sets
1551                Make/O/N=(n12) q12,i12,sig12,sq12,qb12,fs12
1552                Make/O/N=(n12,3) res12
1553                q12[0,n1-1] = lowq[p]
1554                q12[n1,n1+n2-1]= medq[p-n1]
1555                i12[0,n1-1] = lowi[p]
1556                i12[n1,n1+n2-1]= medi[p-n1]
1557                sig12[0,n1-1] = lows[p]
1558                sig12[n1,n1+n2-1]= meds[p-n1]
1559                sq12[0,n1-1] = lowres[p][0]
1560                sq12[n1,n1+n2-1]= medres[p-n1][0]
1561                qb12[0,n1-1] = lowres[p][1]
1562                qb12[n1,n1+n2-1]= medres[p-n1][1]
1563                fs12[0,n1-1] = lowres[p][2]
1564                fs12[n1,n1+n2-1]= medres[p-n1][2]
1565
1566               
1567                Sort q12, q12,i12,sig12,sq12,qb12,fs12
1568                //at this point 1-2 are combined
1569                //do we need to continue, or write out the set here and stop?
1570                if(cmpstr(name3,"none") == 0)
1571                        //stop here
1572                        norm23 = 1              //norm23 was not used
1573                        Variable/G root:myGlobals:NSORT:gScale2_3 = 1
1574                       
1575                        ControlInfo/W=NSORT_Panel PreviewCheck
1576                        if( V_Value==0 )                //if zero skip the preview and write out the file
1577                                res12[][0] = sq12[p]
1578                                res12[][1] = qb12[p]
1579                                res12[][2] = fs12[p]
1580                                err=WriteNSORTedFile(q12,i12,sig12,name1,name2,name3,name4,normToStr,norm12,norm23,norm34,res=res12)
1581                        endif
1582                        // always clean up waves before exiting
1583                        KillWaves/Z q12,i12,sig12,sq12,qb12,fs12
1584                        return err
1585                Endif
1586               
1587                //need to add the third file... which was already loaded at the top of the function
1588                /////
1589                //order points in sets 12-3, indexing overlap region
1590                //put result in temporary waves
1591                WaveStats/Q q12
1592                n12 = V_npnts
1593                WaveStats/Q $"root:HighQSet:TrimHighQSet_q"
1594                n3 = V_npnts
1595                n123 = n12+ n3
1596               
1597                Make/O/N=(n123) q123,i123,sig123,sq123,qb123,fs123
1598                Make/O/N=(n123,3) res123
1599                WAVE highq = $"root:HighQSet:TrimHighQSet_q"
1600                WAVE highi = $"root:HighQSet:TrimHighQSet_i"
1601                WAVE highs = $"root:HighQSet:TrimHighQSet_s"
1602                WAVE highres = $"root:HighQSet:TrimHighQSet_res"
1603       
1604       
1605                q123[0,n12-1] = q12[p]
1606                q123[n12,n12+n3-1]= highq[p-n12]
1607                i123[0,n12-1] = i12[p]
1608                i123[n12,n12+n3-1]= highi[p-n12]
1609                sig123[0,n12-1] = sig12[p]
1610                sig123[n12,n12+n3-1]= highs[p-n12]
1611                sq123[0,n12-1] = sq12[p]
1612                sq123[n12,n12+n3-1]= highres[p-n12][0]
1613                qb123[0,n12-1] = qb12[p]
1614                qb123[n12,n12+n3-1]= highres[p-n12][1]
1615                fs123[0,n12-1] = fs12[p]
1616                fs123[n12,n12+n3-1]= highres[p-n12][2]
1617
1618               
1619                Sort q123, q123,i123,sig123,sq123,qb123,fs123
1620                /////////////////
1621               
1622                //find the maximum point number of set 2  in the overlap region
1623                FindLevel/P/Q highq,(q12[n12-1])
1624                num2 = trunc(V_levelX)
1625                //Print "num2 = ",num2
1626               
1627                if (auto)
1628                        //there must be overlap points to use auto-scaling
1629                        if(numtype(num2) != 0)
1630                                Abort "There are no data points in the overlap region. Either reduce the number of deleted points or use manual scaling."
1631                        endif
1632                        //do auto-scaling of data
1633                        norm23 = NCNR_GetScalingInOverlap(num2,q12,i12,highq,highi)
1634                        //Set the global variable for the 12 - 3 scale factor
1635                        Variable/G root:myGlobals:NSORT:gScale2_3 = norm23
1636                else
1637                        //use the value from the panel ( which is the global)
1638                        NVAR temp23 = root:myGlobals:NSORT:gScale2_3
1639                        norm23 = temp23
1640                Endif
1641               
1642                If( (normTo== 1) || (normTo ==2) )
1643                        //normalize to first or second file, so multiply third by norm23
1644                        highi *= norm23
1645                        highs *= norm23
1646                else
1647                        //normalize to THIRD file, 1-2 by 1/norm23
1648                        norm23 = 1/norm23
1649                        i12 *= norm23
1650                        sig12 *= norm23
1651                        // for the display, scale the trimmed sets 1 and 2
1652                        lowi *= norm23
1653                        lows *= norm23
1654                        medi *= norm23
1655                        meds *= norm23
1656                Endif
1657               
1658                //Print "NSORT-ed ",name1," + ", name2, " + ", name3
1659                //Print "normalized to ",normTo
1660                //Print "multiplicative factor 1-2 = ",norm12," multiplicative factor 12 - 3 = ",norm23
1661                ControlUpdate/A/W=NSORT_Panel
1662                DoUpdate
1663               
1664                Make/O/N=(n123) q123,i123,sig123
1665                Make/O/N=(n123,3) res123
1666                q123[0,n12-1] = q12[p]
1667                q123[n12,n12+n3-1]= highq[p-n12]
1668                i123[0,n12-1] = i12[p]
1669                i123[n12,n12+n3-1]= highi[p-n12]
1670                sig123[0,n12-1] = sig12[p]
1671                sig123[n12,n12+n3-1]= highs[p-n12]
1672                sq123[0,n12-1] = sq12[p]
1673                sq123[n12,n12+n3-1]= highres[p-n12][0]
1674                qb123[0,n12-1] = qb12[p]
1675                qb123[n12,n12+n3-1]= highres[p-n12][1]
1676                fs123[0,n12-1] = fs12[p]
1677                fs123[n12,n12+n3-1]= highres[p-n12][2]
1678
1679               
1680                Sort q123, q123,i123,sig123,sq123,qb123,fs123
1681                //at this point 12 - 3 are combined
1682               
1683                //do we need to continue, or write out the set here and stop?
1684                if(cmpstr(name4,"none") == 0)
1685                        //stop here
1686               
1687                        ControlInfo/W=NSORT_Panel PreviewCheck
1688                        if( V_Value==0 )                //if zero skip the preview and write out the file
1689                                res123[][0] = sq123[p]
1690                                res123[][1] = qb123[p]
1691                                res123[][2] = fs123[p]
1692                                err=WriteNSORTedFile(q123,i123,sig123,name1,name2,name3,name4,normToStr,norm12,norm23,norm34,res=res123)
1693                        endif
1694                        // always clean up waves before exiting
1695                        KillWaves/Z q12,i12,sig12,q123,i123,sig123,sq123,qb123,fs123 //,res123
1696                        return err
1697                Endif
1698               
1699                // new 2016 - combine the 4th data set
1700
1701                //need to add the fourth file... which was already loaded at the top of the function
1702                /////
1703                //order points in sets 123-4, indexing overlap region
1704                //put result in temporary waves
1705                WaveStats/Q q123
1706                n123 = V_npnts
1707                WaveStats/Q $"root:HighestQSet:TrimHighestQSet_q"
1708                n4 = V_npnts
1709                n1234 = n123 + n4
1710               
1711                Make/O/N=(n1234) q1234,i1234,sig1234,sq1234,qb1234,fs1234
1712                Make/O/N=(n1234,3) res1234
1713                WAVE highestq = $"root:HighestQSet:TrimHighestQSet_q"
1714                WAVE highesti = $"root:HighestQSet:TrimHighestQSet_i"
1715                WAVE highests = $"root:HighestQSet:TrimHighestQSet_s"
1716                WAVE highestres = $"root:HighestQSet:TrimHighestQSet_res"
1717       
1718       
1719                q1234[0,n123-1] = q123[p]
1720                q1234[n123,n123+n4-1]= highestq[p-n123]
1721                i1234[0,n123-1] = i123[p]
1722                i1234[n123,n123+n4-1]= highesti[p-n123]
1723                sig1234[0,n123-1] = sig123[p]
1724                sig1234[n123,n123+n4-1]= highests[p-n123]
1725                sq1234[0,n123-1] = sq123[p]
1726                sq1234[n123,n123+n4-1]= highestres[p-n123][0]
1727                qb1234[0,n123-1] = qb123[p]
1728                qb1234[n123,n123+n4-1]= highestres[p-n123][1]
1729                fs1234[0,n123-1] = fs123[p]
1730                fs1234[n123,n123+n4-1]= highestres[p-n123][2]
1731
1732               
1733                Sort q1234, q1234,i1234,sig1234,sq1234,qb1234,fs1234
1734                /////////////////
1735               
1736                //find the maximum point number of set 2  in the overlap region
1737                FindLevel/P/Q highestq,(q123[n123-1])
1738                num2 = trunc(V_levelX)
1739                //Print "num2 = ",num2
1740               
1741                if (auto)
1742                        //there must be overlap points to use auto-scaling
1743                        if(numtype(num2) != 0)
1744                                Abort "There are no data points in the overlap region. Either reduce the number of deleted points or use manual scaling."
1745                        endif
1746                        //do auto-scaling of data
1747                        norm34 = NCNR_GetScalingInOverlap(num2,q123,i123,highestq,highesti)
1748                        //Set the global variable for the 12 - 3 scale factor
1749                        Variable/G root:myGlobals:NSORT:gScale3_4 = norm34
1750                else
1751                        //use the value from the panel ( which is the global)
1752                        NVAR temp34 = root:myGlobals:NSORT:gScale3_4
1753                        norm34 = temp34
1754                Endif
1755
1756// normalization
1757                switch (normTo)
1758                        case 1:
1759                        case 2:
1760                        case 3:
1761                                //normalize to first or second or third file, so multiply fourth by norm34
1762                                highesti *= norm34
1763                                highests *= norm34
1764                                break
1765                        case 4:
1766                                //normalize to FOURTH file, 123 by multiplicative factor 1/norm34
1767                                norm34 = 1/norm34
1768                                i123 *= norm34
1769                                sig123 *= norm34
1770                                // for the display, scale the trimmed sets 1 and 2 and 3
1771                                lowi *= norm34
1772                                lows *= norm34
1773                                medi *= norm34
1774                                meds *= norm34
1775                                highi *= norm34
1776                                highs *= norm34
1777                                break
1778                endswitch
1779               
1780       
1781                //Print "NSORT-ed ",name1," + ", name2, " + ", name3
1782                //Print "normalized to ",normTo
1783                //Print "multiplicative factor 1-2 = ",norm12," multiplicative factor 12 - 3 = ",norm23
1784                ControlUpdate/A/W=NSORT_Panel
1785                DoUpdate
1786               
1787                Make/O/N=(n1234) q1234,i1234,sig1234
1788                Make/O/N=(n1234,3) res1234
1789                q1234[0,n123-1] = q123[p]
1790                q1234[n123,n123+n4-1]= highestq[p-n123]
1791                i1234[0,n123-1] = i123[p]
1792                i1234[n123,n123+n4-1]= highesti[p-n123]
1793                sig1234[0,n123-1] = sig123[p]
1794                sig1234[n123,n123+n4-1]= highests[p-n123]
1795                sq1234[0,n123-1] = sq123[p]
1796                sq1234[n123,n123+n4-1]= highestres[p-n123][0]
1797                qb1234[0,n123-1] = qb123[p]
1798                qb1234[n123,n123+n4-1]= highestres[p-n123][1]
1799                fs1234[0,n123-1] = fs123[p]
1800                fs1234[n123,n123+n4-1]= highestres[p-n123][2]
1801               
1802                Sort q1234, q1234,i1234,sig1234,sq1234,qb1234,fs1234
1803                //at this point 123 - 4 are combined
1804               
1805//write out the set here and stop
1806                        //stop here
1807       
1808                ControlInfo/W=NSORT_Panel PreviewCheck
1809                if( V_Value==0 )                //if zero skip the preview and write out the file
1810                        res1234[][0] = sq1234[p]
1811                        res1234[][1] = qb1234[p]
1812                        res1234[][2] = fs1234[p]
1813                        err=WriteNSORTedFile(q1234,i1234,sig1234,name1,name2,name3,name4,normToStr,norm12,norm23,norm34,res=res1234)
1814                endif
1815                // always clean up waves before exiting
1816                KillWaves/Z q123,i123,sig123,q1234,i1234,sig1234,sq1234,qb1234,fs1234 //,res1234
1817                return err
1818
1819                //combined dataset will already be displayed if the NSORT_Graph is open
1820       
1821                ////////////////
1822                return err
1823   endif // End the if(6-column) specific stuff here
1824       
1825       
1826End
1827
1828
1829
1830
1831
1832
1833/////////////////////////////////////////////////////////////
1834// testing, may speed up NSORT, NCNR-specific naming scheme of
1835// run numbers and a run prefix
1836//
1837// it is assumed that you are combining data from the current reduction session,
1838// so that the XML y/n hasn't changed.
1839//
1840Function Set3NSORTFiles(low,med,hi,pref)
1841        Variable low,med,hi
1842        String pref
1843       
1844        //make strings from the numbers
1845        String absStr="",ext
1846        Variable popNum
1847        DoWindow/F NSORT_Panel
1848       
1849        SVAR lowQPopStr = root:myGlobals:NSORT:gDataPopList
1850        SVAR medHiQPopStr = root:myGlobals:NSORT:gDataPopList_3
1851       
1852        NVAR useXMLOutput = root:Packages:NIST:gXML_Write
1853        if(useXMLOutput)
1854                ext = ".ABSx"
1855        else
1856                ext = ".ABS"
1857        endif
1858       
1859        //lowQ menu
1860        absStr = pref+RunDigitString(low)+ext
1861        popNum = WhichListItem(absStr,lowQPopStr,";",0)
1862        if(popNum == -1)
1863                Abort "Could not find file: " + absStr +" aborting...  Be sure that your output format is the same as the input"
1864        endif
1865        popNum += 1             // add 1 to get the item number
1866        PopupMenu popup_1,win=NSORT_Panel,mode=(popNum)
1867       
1868        //medQ (a different list for the popup)
1869        absStr = pref+RunDigitString(med)+ext
1870        popNum = WhichListItem(absStr,medHiQPopStr,";",0)
1871        if(popNum == -1)
1872                Abort "Could not find file: "+absStr+" aborting...  Be sure that your output format is the same as the input"
1873        endif
1874        popNum += 1             // add 1 to get the item number
1875        PopupMenu popup_2,win=NSORT_Panel,mode=(popNum)
1876       
1877       
1878        //highQ (same pop list as medQ)
1879        if(hi != 0)
1880                absStr = pref+RunDigitString(hi)+ext
1881                popNum = WhichListItem(absStr,medHiQPopStr,";",0)
1882                if(popNum == -1)
1883                        Abort "Could not find file: "+absStr+" aborting...  Be sure that your output format is the same as the input"
1884                endif
1885                popNum += 1             // add 1 to get the item number
1886                PopupMenu popup_3,win=NSORT_Panel,mode=(popNum)
1887        else
1888                PopupMenu popup_3,win=NSORT_Panel,mode=(1)
1889        endif
1890End
1891
1892/////////////////////////////////////////////////////////////
1893// testing, may speed up NSORT, NCNR-specific naming scheme of
1894// run numbers and a run prefix
1895//
1896// it is assumed that you are combining data from the current reduction session,
1897// so that the XML y/n hasn't changed.
1898//
1899// updated to use 4 files
1900//
1901// TODO:
1902// -- still assuming ABS
1903//
1904Function Set4NSORTFiles(low,med,hi,highest,pref)
1905        Variable low,med,hi,highest
1906        String pref
1907       
1908        //make strings from the numbers
1909        String absStr="",ext
1910        Variable popNum
1911        DoWindow/F NSORT_Panel
1912       
1913        SVAR lowQPopStr = root:myGlobals:NSORT:gDataPopList
1914        SVAR medHiQPopStr = root:myGlobals:NSORT:gDataPopList_3
1915       
1916        NVAR useXMLOutput = root:Packages:NIST:gXML_Write
1917        if(useXMLOutput)
1918                ext = ".ABSx"
1919        else
1920                ext = ".ABS"
1921        endif
1922       
1923        //lowQ menu
1924        absStr = pref+RunDigitString(low)+ext
1925        popNum = WhichListItem(absStr,lowQPopStr,";",0)
1926        if(popNum == -1)
1927                Abort "Could not find file: " + absStr +" aborting...  Be sure that your output format is the same as the input"
1928        endif
1929        popNum += 1             // add 1 to get the item number
1930        PopupMenu popup_1,win=NSORT_Panel,mode=(popNum)
1931       
1932        //medQ (a different list for the popup)
1933        absStr = pref+RunDigitString(med)+ext
1934        popNum = WhichListItem(absStr,medHiQPopStr,";",0)
1935        if(popNum == -1)
1936                Abort "Could not find file: "+absStr+" aborting...  Be sure that your output format is the same as the input"
1937        endif
1938        popNum += 1             // add 1 to get the item number
1939        PopupMenu popup_2,win=NSORT_Panel,mode=(popNum)
1940       
1941       
1942        //highQ (same pop list as medQ)
1943        if(hi != 0)
1944                absStr = pref+RunDigitString(hi)+ext
1945                popNum = WhichListItem(absStr,medHiQPopStr,";",0)
1946                if(popNum == -1)
1947                        Abort "Could not find file: "+absStr+" aborting...  Be sure that your output format is the same as the input"
1948                endif
1949                popNum += 1             // add 1 to get the item number
1950                PopupMenu popup_3,win=NSORT_Panel,mode=(popNum)
1951        else
1952                PopupMenu popup_3,win=NSORT_Panel,mode=(1)
1953        endif
1954       
1955        //highestQ (same pop list as medQ)
1956        if(highest != 0)
1957                absStr = pref+RunDigitString(highest)+ext
1958                popNum = WhichListItem(absStr,medHiQPopStr,";",0)
1959                if(popNum == -1)
1960                        Abort "Could not find file: "+absStr+" aborting...  Be sure that your output format is the same as the input"
1961                endif
1962                popNum += 1             // add 1 to get the item number
1963                PopupMenu popup_4,win=NSORT_Panel,mode=(popNum)
1964        else
1965                PopupMenu popup_4,win=NSORT_Panel,mode=(1)
1966        endif
1967       
1968        return(0)
1969End
1970
1971//more beta procedures - to create a table of scattering runs to combine with NSORT
1972Proc CreateTableToCombine(ctrlName)
1973        String ctrlName
1974       
1975        NewDataFolder/O root:myGlobals:CombineTable
1976//      DoWindow/F CombineTable
1977       
1978        Make/O/T/N=0 $"root:myGlobals:CombineTable:Filenames"
1979        Make/O/T/N=0 $"root:myGlobals:CombineTable:Suffix"
1980        Make/O/T/N=0 $"root:myGlobals:CombineTable:Labels"
1981        Make/O/D/N=0 $"root:myGlobals:CombineTable:SDD"
1982        Make/O/D/N=0 $"root:myGlobals:CombineTable:RunNumber"
1983        Make/O/D/N=0 $"root:myGlobals:CombineTable:IsTrans"
1984
1985
1986        AppendToTable/W=CombinePanel#GroupedFiles root:myGlobals:CombineTable:Labels, root:myGlobals:CombineTable:SDD, root:myGlobals:CombineTable:RunNumber
1987
1988        ModifyTable/W=CombinePanel#GroupedFiles width(:myGlobals:CombineTable:SDD)=40
1989        ModifyTable/W=CombinePanel#GroupedFiles width(:myGlobals:CombineTable:Labels)=180
1990        ModifyTable/W=CombinePanel#GroupedFiles width(Point)=0          //JUN04, remove point numbers - confuses users since point != run
1991
1992
1993        //get a list of all files in the folder, some will be junk version numbers that don't exist     
1994        String list,partialName,tempName,temp=""
1995        list = IndexedFile(catPathName,-1,"????")       //get all files in folder
1996        Variable numitems,ii,ok
1997       
1998        //remove version numbers from semicolon-delimited list
1999        list =  RemoveVersNumsFromList(list)
2000        numitems = ItemsInList(list,";")
2001       
2002        //loop through all of the files in the list, reading CAT/SHORT information if the file is RAW SANS
2003        //***version numbers have been removed***
2004        String str,fullName
2005        Variable lastPoint
2006        ii=0
2007       
2008        Make/T/O/N=0 notRAWlist
2009        do
2010                //get current item in the list
2011                partialName = StringFromList(ii, list, ";")
2012                //get a valid file based on this partialName and catPathName
2013                tempName = FindValidFilename(partialName)
2014                If(cmpstr(tempName,"")==0)              //a null string was returned
2015                        //write to notebook that file was not found
2016                        //if string is not a number, report the error
2017                        if(numtype(str2num(partialName)) == 2)
2018                                str = "this file was not found: "+partialName+"\r\r"
2019                                //Notebook CatWin,font="Times",fsize=12,text=str
2020                        Endif
2021                else
2022                        //prepend path to tempName for read routine
2023                        PathInfo catPathName
2024                        FullName = S_path + tempName
2025                        //make sure the file is really a RAW data file
2026                        ok = CheckIfRawData(fullName)
2027                        if (!ok)
2028                                //write to notebook that file was not a RAW SANS file
2029                                lastPoint = numpnts(notRAWlist)
2030                                InsertPoints lastPoint,1,notRAWlist
2031                                notRAWlist[lastPoint]=tempname
2032                        else
2033                                //go write the header information to the Notebook
2034                                GetHeaderInfoToCombineWave(fullName,tempName)
2035                        Endif
2036                Endif
2037                ii+=1
2038        while(ii<numitems)
2039//Now sort them all based on the suffix data (orders them as collected)
2040//      SortCombineWaves()
2041// sort by label
2042        SortCombineByLabel()
2043// remove the transmission waves
2044//
2045        RemoveTransFilesFromCombine()
2046//
2047        SetDataFolder root:
2048       
2049        Killwaves/Z notRAWlist
2050End
2051
2052
2053Function RemoveTransFilesFromCombine()
2054        Wave/T filenames = $"root:myGlobals:CombineTable:Filenames"
2055        Wave/T suffix = $"root:myGlobals:CombineTable:Suffix"
2056        Wave/T labels = $"root:myGlobals:CombineTable:Labels"
2057        Wave sdd = $"root:myGlobals:CombineTable:SDD"
2058        Wave runnum = $"root:myGlobals:CombineTable:RunNumber"
2059        Wave isTrans = $"root:myGlobals:CombineTable:IsTrans"
2060       
2061        Variable num=numpnts(isTrans),ii
2062        ii=num-1
2063        do
2064                if(isTrans[ii] != 0)
2065                        DeletePoints ii, 1, filenames,suffix,labels,sdd,runnum,isTrans
2066                endif
2067                ii-=1
2068        while(ii>=0)
2069        return(0)
2070End
2071
2072//reads header information and puts it in the appropriate waves for display in the table.
2073//fname is the full path for opening (and reading) information from the file
2074//which alreay was found to exist. sname is the file;vers to be written out,
2075//avoiding the need to re-extract it from fname.
2076Function GetHeaderInfoToCombineWave(fname,sname)
2077        String fname,sname
2078       
2079        String textstr,temp,lbl,date_time,suffix
2080        Variable ctime,lambda,sdd,detcnt,cntrate,refNum,trans,thick,xcenter,ycenter,numatten
2081        Variable lastPoint, beamstop
2082
2083        Wave/T GFilenames = $"root:myGlobals:CombineTable:Filenames"
2084        Wave/T GSuffix = $"root:myGlobals:CombineTable:Suffix"
2085        Wave/T GLabels = $"root:myGlobals:CombineTable:Labels"
2086        Wave GSDD = $"root:myGlobals:CombineTable:SDD"
2087        Wave GRunNumber = $"root:myGlobals:CombineTable:RunNumber"
2088        Wave GIsTrans = $"root:myGlobals:CombineTable:IsTrans"
2089       
2090        lastPoint = numpnts(GLambda)
2091               
2092        InsertPoints lastPoint,1,GFilenames
2093        GFilenames[lastPoint]=sname
2094       
2095        //read the file suffix
2096        InsertPoints lastPoint,1,GSuffix
2097        GSuffix[lastPoint]=getSuffix(fname)
2098
2099        // read the sample.label text field
2100        InsertPoints lastPoint,1,GLabels
2101        GLabels[lastPoint]=getSampleLabel(fname)
2102       
2103        //read in the SDD
2104        InsertPoints lastPoint,1,GSDD
2105        GSDD[lastPoint]= getSDD(fname)
2106
2107        //the run number (not displayed in the table, but carried along)
2108        InsertPoints lastPoint,1,GRunNumber
2109        GRunNumber[lastPoint] = GetRunNumFromFile(sname)
2110
2111        // 0 if the file is a scattering  file, 1 (truth) if the file is a transmission file
2112        InsertPoints lastPoint,1,GIsTrans
2113        GIsTrans[lastPoint]  = isTransFile(fname)               //returns one if beamstop is "out"
2114       
2115        KillWaves/Z w
2116        return(0)
2117End
2118
2119//sorts all of the waves of header information using the suffix (A123)
2120//the result is that all of the data is in the order that it was collected,
2121// regardless of how the prefix or run numbers were changed by the user
2122Function SortCombineWaves()
2123        Wave/T GFilenames = $"root:myGlobals:CombineTable:Filenames"
2124        Wave/T GSuffix = $"root:myGlobals:CombineTable:Suffix"
2125        Wave/T GLabels = $"root:myGlobals:CombineTable:Labels"
2126        Wave GSDD = $"root:myGlobals:CombineTable:SDD"
2127        Wave GRunNumber = $"root:myGlobals:CombineTable:RunNumber"
2128        Wave GIsTrans = $"root:myGlobals:CombineTable:IsTrans"
2129
2130//      Sort GSuffix, GSuffix, GFilenames, GLabels, GDateTime, GSDD, GLambda, GCntTime, GTotCnts, GCntRate, GTransmission, GThickness, GXCenter, GYCenter, GNumAttens,GRunNumber,GIsTrans
2131        Sort GSuffix, GSuffix, GFilenames, GLabels, GSDD, GRunNumber, GIsTrans
2132        return(0)
2133End
2134
2135//sorts all of the waves of header information using the suffix (A123)
2136//the result is that all of the data is in the order that it was collected,
2137// regardless of how the prefix or run numbers were changed by the user
2138Function SortCombineByLabel()
2139        Wave/T GFilenames = $"root:myGlobals:CombineTable:Filenames"
2140        Wave/T GSuffix = $"root:myGlobals:CombineTable:Suffix"
2141        Wave/T GLabels = $"root:myGlobals:CombineTable:Labels"
2142        Wave GSDD = $"root:myGlobals:CombineTable:SDD"
2143        Wave GRunNumber = $"root:myGlobals:CombineTable:RunNumber"
2144        Wave GIsTrans = $"root:myGlobals:CombineTable:IsTrans"
2145
2146        Sort GLabels, GSuffix, GFilenames, GLabels, GSDD, GRunNumber, GIsTrans
2147//      Sort {GLabels, GSDD}, GSuffix, GFilenames, GLabels, GSDD, GRunNumber, GIsTrans          //sort on GLabels, GSDD breaks the tie
2148        return(0)
2149End
2150
2151//main procedure, called from the menu
2152// sets a flag (temporarily) to use the names from the table
2153// during the procedure that writes the data files.
2154//
2155//
2156Function DoCombineFiles(ctrlName)
2157        String ctrlName
2158       
2159       
2160        if(WinType("NSORT_Panel") == 0)
2161                DoAlert 0, "The SORT Panel must be open to combine the files"
2162                return(0)
2163        endif
2164       
2165        DoAlert 1,"Do you have all the assignments set in the bottom table? If not, < No > will exit."
2166        if(V_flag == 2)
2167                return(0)               //no, get out
2168        endif
2169        // pop all of the menus to make sure that they are properly populated
2170        LowQPopMenuProc("",1,"")
2171        MedQPopMenuProc("",1,"")
2172        HighQPopMenuProc("",1,"")
2173        HighestQPopMenuProc("",1,"")
2174       
2175//      String savedDataFolder = GetDataFolder(1)               // save
2176        Wave LowRun = root:myGlobals:CombineTable:LowRun
2177        Wave MediumRun = root:myGlobals:CombineTable:MediumRun
2178        Wave HighRun = root:myGlobals:CombineTable:HighRun
2179        Wave HighestRun = root:myGlobals:CombineTable:HighestRun
2180        Wave/T prefix = root:myGlobals:CombineTable:Prefix
2181        Wave/T saveName = root:myGlobals:CombineTable:saveName
2182
2183        Variable/G root:myGlobals:CombineTable:useTable=1
2184       
2185        Variable num=numpnts(lowRun),ii,lowFile,medFile,hiFile,highestFile
2186        String prefixStr = ""
2187        Pathinfo catPathName
2188        String path=S_Path
2189       
2190        ii=0
2191        do
2192                lowFile = LowRun[ii]
2193                medFile = MediumRun[ii]
2194                hiFile = highRun[ii]
2195                highestFile = highestRun[ii]
2196                prefixStr = prefix[ii]
2197               
2198                Set4NSORTFiles(lowFile,medFile,hiFile,highestFile,prefixStr)            //set the files and pop the NSORT popups
2199               
2200                //pass the new file name in as a global (ugh!)
2201                String/G root:myGlobals:CombineTable:SaveNameStr = path+saveName[ii]
2202                //combine the files and write the data
2203                WriteNSORTFileButton("")
2204               
2205                Print "wrote file : ",path+saveName[ii]
2206                ii+=1
2207        while(ii<num)
2208
2209        Variable/G root:myGlobals:CombineTable:useTable=0               //turn this off immediately
2210       
2211        return(0)
2212End
2213
2214
2215// only respond to clicks in the subwindow (table) rather than everywhere. Hooks can't be set for subwindows
2216//
2217//// Window hook example:
2218//  WINDOW:CombinePanel;HCSPEC:CombinePanel#GroupedFiles;EVENT:mouseup;MOUSEX:152;MOUSEY:143;TICKS:7722029;MODIFIERS:0;
2219//
2220Function CombineTableHook(infoStr)
2221        String infoStr
2222        String event= StringByKey("EVENT",infoStr)
2223        String subwin = StringByKey("HCSPEC",infoStr)
2224//      Print subwin
2225//      Print infoStr
2226//      Print "EVENT= ",event
2227        if(cmpstr(subwin,"CombinePanel#GroupedFiles")==0)
2228                strswitch(event)
2229                        case "mousedown":
2230                                Variable xpix= NumberByKey("MOUSEX",infoStr)
2231                                Variable ypix= NumberByKey("MOUSEY",infoStr)
2232                                Variable modif= NumberByKey("MODIFIERS",infoStr)
2233                                //print modif
2234                                if(modif & 2^1)         //bit 1 set, shift key is down
2235                                        PopupContextualMenu/C=(xpix, ypix) "combine;"
2236                                        strswitch(S_selection)
2237                                                case "combine":
2238                                                        //Print "combine the files"
2239                                                        SendSelectionToTable()
2240                                                        break
2241                                        endswitch               //on selection
2242                                endif
2243                endswitch       // on event
2244        endif
2245        return 0
2246End
2247
2248//ASSUMES 3 FILES!!!!
2249Function SendSelectionToTable()
2250
2251        DoWindow/F CombinePanel
2252        if(V_flag==0)
2253//              Make/O/N=0 $"root:myGlobals:CombineTable:Low"
2254//              Make/O/N=0 $"root:myGlobals:CombineTable:Medium"
2255//              Make/O/N=0 $"root:myGlobals:CombineTable:High"
2256//              Make/O/T/N=0 $"root:myGlobals:CombineTable:Prefix"
2257//              Make/O/T/N=0 $"root:myGlobals:CombineTable:SaveName"
2258//              edit Low,Medium,High,Prefix,SaveName as "Run Numbers to Combine"
2259//              DoWindow/C ToCombine
2260
2261                return(0)
2262               
2263        else
2264                Wave low = $"root:myGlobals:CombineTable:LowRun"
2265                Wave medium = $"root:myGlobals:CombineTable:MediumRun"
2266                Wave high = $"root:myGlobals:CombineTable:HighRun"
2267                Wave highest = $"root:myGlobals:CombineTable:HighestRun"
2268                Wave/T prefix = $"root:myGlobals:CombineTable:Prefix"
2269                Wave/T saveName = $"root:myGlobals:CombineTable:SaveName"
2270               
2271                Wave/T gLabels = $"root:myGlobals:CombineTable:Labels"
2272                Wave gSDD = $"root:myGlobals:CombineTable:SDD"
2273                Wave gRunNumber = $"root:myGlobals:CombineTable:RunNumber"
2274                Wave/T filenames = $"root:myGlobals:CombineTable:FileNames"
2275        endif
2276       
2277        GetSelection table,CombinePanel#GroupedFiles,3
2278//      Print V_startRow, V_endRow
2279       
2280        //prompt for combined name, give the user a chance to cancel
2281        Variable num=V_endRow-V_startRow+1
2282        Variable ii
2283        String saveStr=""
2284        Prompt saveStr,"saved file name for "+ gLabels[V_StartRow]      //+tmpLbl[1]
2285        DoPrompt "Enter the combined file name",saveStr
2286        if(V_flag==1)
2287                return(1)               //user cancel, get out before anything is set
2288        endif
2289
2290        if( !(num==2 || num==3 || num==4) )
2291                Abort "invalid table selection - must select either 2 or 3 or 4 files to combine"
2292        endif
2293        Make/O/T/N=(4) tmpLbl
2294        Make/O/N=(4) tmpSDD,tmpRun
2295       
2296        //initialize with fake values in case 2 or 3 files are combined
2297        tmpLbl = ""
2298        tmpSDD = 0.01           //fake sdd in meters to always be the "highest" Q
2299        tmpRun = 0                      //pass a run number of zero to be later interpreted as "none"
2300       
2301        //fill in the real values from the selection
2302        for(ii=V_startRow;ii<=V_endRow;ii+=1)
2303                tmpLbl[ii-V_startRow] = gLabels[ii]
2304                tmpSDD[ii-V_startRow] = gSDD[ii]
2305                tmpRun[ii-V_startRow] = gRunNumber[ii]
2306        endfor
2307//      if(num==2)      // then "highest" q run needs to be forced to zero
2308//              ii=2
2309//              tmpLbl[ii] = ""
2310//              tmpSDD[ii] = 0.01               //fake sdd in meters to always be the "highest" Q
2311//              tmpRun[ii] = 0                  //pass a run number of zero to be later interpreted as "none"
2312//      endif
2313        Sort tmpSDD, tmpSDD,tmpLbl,tmpRun
2314       
2315//      Print tmpSDD
2316       
2317        num=numpnts(low)
2318        InsertPoints num, 1, low,medium,high,highest,prefix,SaveName
2319        low[num] = tmpRun[3]
2320        medium[num] = tmpRun[2]
2321        high[num] = tmpRun[1]
2322        highest[num] = tmpRun[0]
2323        prefix[num] = GetPrefixStrFromFile(filenames[ii])
2324        saveName[num] = saveStr
2325
2326        KillWaves/Z tmpLbl,tmpRun,tmpSDD
2327        return(0)
2328end
2329
2330
2331////////////////////////
2332// replaces the beta menu items
2333//
2334
2335Proc ShowCombinePanel()
2336        DoWindow/F CombinePanel
2337        if(V_flag==0)
2338                CombinePanel()
2339                CreateTableToCombine("")
2340                DoAlert 1,"Do you want to clear the list of runs and file names to combine?"
2341                TableToCombineAndSave(V_flag==1)                // clear and initialize, if desired
2342        endif
2343end
2344
2345Proc CombinePanel()
2346        PauseUpdate; Silent 1           // building window...
2347        NewPanel /W=(546,442,1197,915) /K=1 as "Sort and Combine Data Files"
2348        ModifyPanel cbRGB=(49151,53155,65535)
2349        DoWindow/C CombinePanel
2350        Button button0_0,pos={20,20},size={160,20},proc=CreateTableToCombine,title="List Files to Combine"
2351        Button button0_1,pos={206,20},size={140,20},proc=DoCombineFiles,title="Combine Files"
2352        Button button0_2,pos={509,40},size={60,20},proc=CombinePanelDone,title="Done"
2353        Button button0_3,pos={522,14},size={30,20},proc=ShowCombineHelp,title="?"
2354        Button button0_4,pos={500,220},size={120,20},proc=ClearCombineTable,title="Clear Table?"
2355        Edit/W=(20,54,368,249)/HOST=#
2356        ModifyTable format=1,width=0
2357        RenameWindow #,GroupedFiles
2358        SetActiveSubwindow ##
2359        Edit/W=(20,263,634,455)/HOST=#
2360        ModifyTable format=1
2361        RenameWindow #,RunNumbersToCombine
2362        SetActiveSubwindow ##
2363        SetWindow kwTopWin hook=CombineTableHook, hookevents=1  // mouse down events
2364EndMacro
2365
2366Proc ShowCombineHelp(ctrlName): ButtonControl
2367        String ctrlName
2368        DisplayHelpTopic/K=1/Z "SANS Data Reduction Tutorial[Batch Combine Data Files]"
2369        if(V_flag !=0)
2370                DoAlert 0,"The SANS Data Reduction Tutorial Help file could not be found"
2371        endif
2372end
2373
2374Function CombinePanelDone(ctrlName)
2375        String ctrlName
2376       
2377        DoWindow/K CombinePanel
2378        return(0)
2379end
2380
2381Function ClearCombineTable(ctrlName)
2382        String ctrlName
2383       
2384        DoAlert 1,"Do you want to clear the list of runs and file names to combine?"
2385        TableToCombineAndSave(V_flag==1)                // clear and initialize, if desired
2386        return(0)
2387end
2388
2389Function TableToCombineAndSave(clear)
2390        Variable clear
2391       
2392        if(clear)
2393                // make the waves and table for the sets to combine
2394                Make/O/N=0 $"root:myGlobals:CombineTable:LowRun"
2395                Make/O/N=0 $"root:myGlobals:CombineTable:MediumRun"
2396                Make/O/N=0 $"root:myGlobals:CombineTable:HighRun"
2397                Make/O/N=0 $"root:myGlobals:CombineTable:HighestRun"
2398                Make/O/T/N=0 $"root:myGlobals:CombineTable:Prefix"
2399                Make/O/T/N=0 $"root:myGlobals:CombineTable:SaveName"
2400        endif
2401        SetDataFolder root:myGlobals:CombineTable
2402       
2403        // make the second table
2404        AppendToTable/W=CombinePanel#RunNumbersToCombine LowRun,MediumRun,HighRun,HighestRun,Prefix,SaveName
2405       
2406        SetDataFolder root:
2407End
2408
2409
2410
2411/////////////////////////////////
2412// currently unused
2413//
2414Proc MakeCombineTable_byName()
2415        NewDataFolder/O root:myGlobals:CombineTable                     //in case it doesn't exist yet
2416        Make/O/T/N=1 lowQfile,medQfile,hiQfile,saveName
2417        Edit/W=(330,148,973,360) lowQfile,medQfile,hiQfile,saveName
2418        ModifyTable format(Point)=1,width(lowQfile)=120,width(medQfile)=120,width(hiQfile)=120
2419        ModifyTable width(saveName)=120
2420End
2421
2422//
2423// currently unused
2424//
2425// Another beta procedure, to allow files to be combined quickly
2426// - make 4 waves (text) with the low, med, hi, and wave names
2427// (if there is no hiQ, then pass a wave with "" for all entries)
2428// - then pass the waves, and the save will work like in the DoCombineFiles
2429//
2430// - the named files must be there - there is no error checking
2431// - the NSORT panel must be open with the proper selections of beg,end and autoscale, etc.
2432//
2433// - could write a little proc to generate a table to fill in and a button to call this
2434// - and then think of quick ways to populate the table with file names (and minimize typos)
2435//
2436Function DoCombineFiles_byName(lowW,medW,hiW,saveW)
2437        Wave/T lowW,medW,hiW,saveW
2438               
2439        if(WinType("NSORT_Panel") == 0)
2440                DoAlert 0, "The SORT Panel must be open to combine the files"
2441                return(0)
2442        endif
2443       
2444        // pop all of the menus to make sure that they are properly populated
2445        LowQPopMenuProc("",1,"")
2446        MedQPopMenuProc("",1,"")
2447        HighQPopMenuProc("",1,"")
2448       
2449        Variable num=numpnts(lowW),ii
2450        String lowFile,medFile,hiFile
2451       
2452        Pathinfo catPathName
2453        String path=S_Path
2454       
2455////////        Make/O/D/N=(numpnts(lowW)) scale_4m
2456        NVAR scale12 = root:myGlobals:NSORT:gScale1_2
2457
2458       
2459// this variable must exist and be set to 1 to be able to automatically name files
2460// and use the global saveNameStr that is passed in
2461// -- turn this off when done   
2462        Variable/G root:myGlobals:CombineTable:useTable=1               
2463
2464        ii=0
2465        do
2466                lowFile = lowW[ii]
2467                medFile = medW[ii]
2468                hiFile = hiW[ii]
2469               
2470                //Set3NSORTFiles(lowFile,medFile,hiFile,prefixStr)              //set the files and pop the NSORT popups
2471                //lowQ menu
2472                PopupMenu popup_1 win=NSORT_Panel,popmatch=lowFile
2473               
2474                // mediumQ menu
2475                if(strlen(medFile)!=0)
2476                        PopupMenu popup_2 win=NSORT_Panel,popmatch=medFile
2477                else
2478                        PopupMenu popup_2,win=NSORT_Panel,popmatch="none"       //set to "none"
2479                endif
2480       
2481                //highQ (same pop list as medQ)
2482                if(strlen(hiFile)!=0)
2483                        PopupMenu popup_3 win=NSORT_Panel,popmatch=hiFile
2484                else
2485                        PopupMenu popup_3,win=NSORT_Panel,popmatch="none"       //set to "none"
2486                endif
2487               
2488               
2489                //pass the new file name in as a global (ugh!)
2490                String/G root:myGlobals:CombineTable:SaveNameStr = path+saveW[ii]
2491                //combine the files and write the data
2492                WriteNSORTFileButton("")
2493               
2494//////          scale_4m[ii] = scale12
2495               
2496                Print "wrote file : ",path+saveW[ii]
2497                ii+=1
2498        while(ii<num)
2499
2500        Variable/G root:myGlobals:CombineTable:useTable=0               //turn this off immediately
2501       
2502        return(0)
2503End
Note: See TracBrowser for help on using the repository browser.