source: sans/Dev/trunk/NCNR_User_Procedures/Reduction/VSANS/V_Protocol_Reduction.ipf @ 1111

Last change on this file since 1111 was 1111, checked in by srkline, 4 years ago

two significant changes:

1- in the averaging, before the data is finally written out, duplicate q-values (within 0.1%) are averaged so that duplicate q-values do not appear in the data file. This has a very bad effect on the calculation of the smearing matrix (dq=0).

2-for the data from the back (high res) detector, two steps have been added to the processing at the point where the data is converted to WORK. First, a constant read noise value of 200 cts/pixel is subtracted (found from average of multiple runs with beam off) Second, a 3x3 median filter is applied to the whole image to eliminate the stray bright pixels. Some are saturatd, some are simply outliers. Very effective.

File size: 101.3 KB
Line 
1#pragma TextEncoding = "MacRoman"
2#pragma rtGlobals=1             // Use modern global access method.
3#pragma version=5.0
4#pragma IgorVersion=7
5
6//************************
7
8//
9//*************************
10//////////////////////////////////
11//
12//              KEYWORD=<value> lists used in protocol definitions
13//
14//              KEYWORDS are ALWAYS capitalized, and yes, it does matter
15//
16//              for ABSOLUTE parameters
17//              (4) possible keywords, all with numerical values
18//              TSTAND=value            transmission of the standard
19//              DSTAND=value            thickness of the standard, in centimeters
20//              IZERO=value             I(q=0) value for the standard, in normalized neutron counts
21//              XSECT=value             calibrated cross-section of the standard sample
22//
23//              For calibration with a transmission file, set TSTAND, DSTAND, and XSECT to 1.0
24//              and set IZERO to KAPPA (defined in Tania's handout, or in documentation of MRED_KAP on VAX)
25//
26//
27//              For AVERAGE and for DRAWING
28//                      DRAWING routines only use a subset of the total list, since saving, naming, etc. don't apply
29//              (10) possible keywords, some numerical, some string values
30//              AVTYPE=string           string from set {Circular,Annular,Rectangular,Sector,2D_ASCII,QxQy_ASCII,PNG_Graphic;Sector_PlusMinus;}
31//              PHI=value                       azimuthal angle (-90,90)
32//              DPHI=value                      +/- angular range around phi for average
33//              WIDTH=value             total width of rectangular section, in pixels
34//              SIDE=string             string from set {left,right,both} **note NOT capitalized
35
36//              QCENTER=value           q-value (1/A) of center of annulus for annular average
37//              QDELTA=value            (+/-) width of annulus centered at QCENTER, in units of q
38//              DETGROUP=value  string with "F" or "M" to name the detector group where the annulus lies.
39
40//              PLOT=string             string from set {Yes,No} = truth of generating plot of averaged data
41//              SAVE=string             string from set {Yes,No} = truth of saving averaged data to disk, now with "Concatenate"  or "Individual"
42//              NAME=string             string from set {Auto,Manual} = Automatic name generation or Manual(dialog)
43//
44//
45//    BINTYPE=string (VSANS binning type) "One;Two;Four;Slit Mode;", as defined by ksBinTypeStr
46//
47//
48//              For work.DRK usage:
49//              **the list is COMMA delimited, separator is =
50//              DRK=none,DRKMODE=0,
51//              DRK=name                        is the name of the file, must be a full name, expected to be raw data
52//              DRKMODE=value           is a numeric value (0 or 10 to add to the Correct(mode) switch (unused?)
53//
54//////////////////////////////////
55
56
57//main entry procedure for initialzing and displaying the protocol panel
58// initilaizes folders and globals as needed
59//
60Proc V_ReductionProtocolPanel()
61        DoWindow/F V_ProtocolPanel
62        if(V_flag==0)
63                V_InitProtocolPanel()
64                V_ProtocolPanel()
65        Endif
66End
67
68//initialization procedure for the protocol panel
69//note that :gAbsStr is also shared (common global) to that used in
70//the questionnare form of the protcol (see protocol.ipf)
71//
72Proc V_InitProtocolPanel()
73
74        if(exists("     root:Packages:NIST:VSANS:CatVSHeaderInfo:Filenames") == 0)
75                Abort "You must generate a file catalog before building protocols"
76        endif
77       
78        //set up the global variables needed for the protocol panel
79        //global strings to put in a temporary protocol textwave
80        Variable ii=0
81        String waveStr="tempProtocol"
82        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
83        Make/O/T/N=(kNumProtocolSteps) $"root:Packages:NIST:VSANS:Globals:Protocols:tempProtocol" = ""
84
85        String/G root:Packages:NIST:VSANS:Globals:Protocols:gSAM="ask"
86        String/G root:Packages:NIST:VSANS:Globals:Protocols:gBGD="ask"
87        String/G root:Packages:NIST:VSANS:Globals:Protocols:gEMP="ask"
88        String/G root:Packages:NIST:VSANS:Globals:Protocols:gDIV="ask"
89        String/G root:Packages:NIST:VSANS:Globals:Protocols:gMASK="ask"
90        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr="ask"
91        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAVE="AVTYPE=Circular;SAVE=Yes - Concatenate;NAME=Auto;PLOT=No;BINTYPE=F4-M4-B;"
92        String/G root:Packages:NIST:VSANS:Globals:Protocols:gDRK="DRK=none,DRKMODE=0,"
93       
94        // global strings for trimming data are initialized in the main VSANS initilization
95        //  in case the trimming is done before the protocol panel is opened
96       
97        SetDataFolder root:
98       
99End
100
101
102//button procedure to reset the panel seletctions/checks...etc...
103//to reflect the choices in a previously saved protocol
104// - parses through the protocol and resets the appropriate global strings and
105//updates the panel display
106//
107Function V_RecallProtocolButton(ctrlName) : ButtonControl
108        String ctrlName
109
110        //will reset panel values based on a previously saved protocol
111        //pick a protocol wave from the Protocols folder
112        //MUST move to Protocols folder to get wavelist
113        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
114        Execute "V_PickAProtocol()"
115       
116        //get the selected protocol wave choice through a global string variable
117        SVAR protocolName = root:Packages:NIST:VSANS:Globals:Protocols:gProtoStr
118
119        //If "CreateNew" was selected, ask user to try again
120        if(cmpstr("CreateNew",protocolName) == 0)
121                Abort "CreateNew is for making a new Protocol. Select a previously saved Protocol"
122        Endif
123       
124        //reset the panel based on the protocol textwave (currently a string)
125        V_ResetToSavedProtocol(protocolName)
126       
127        SetDataFolder root:
128        return(0)
129End
130
131//deletes the selected protocol from the list and from memory
132//
133Function V_DeleteProtocolButton(ctrlName) : ButtonControl
134        String ctrlName
135
136        //put up a list of protocols and pick one
137        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
138//      Execute "DeleteAProtocol()"
139        String Protocol=""
140        Prompt Protocol "Delete A Protocol",popup, V_DeletableProtocols()
141        DoPrompt "Select protocol to delete",protocol
142        If(V_flag==1)
143                return(0)
144        endif
145
146        //If "CreateNew, Base, DoAll, or tempProtocol" was selected, do nothing
147        strswitch(protocol)
148                case "CreateNew":
149                        break
150                case "DoAll":
151                        break
152                case "Base":
153                        break
154                case "tempProtocol":
155                        break
156                default:
157                        //delete the protocol
158                        KillWaves/Z $protocol
159        endswitch
160       
161        SetDataFolder root:
162        return(0)
163End
164
165//
166//function that actually parses the protocol specified by nameStr
167//which is just the name of the wave, without a datafolder path
168//
169// TODO
170//  -- update this for 12 steps
171//
172Function V_ResetToSavedProtocol(nameStr)
173        String nameStr
174       
175        //allow special cases of Base and DoAll Protocols to be recalled to panel - since they "ask"
176        //and don't need paths
177       
178        String catPathStr
179        PathInfo catPathName
180        catPathStr=S_path
181       
182        //SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols              //on windows, data folder seems to get reset (erratically) to root:
183        Wave/T w=$("root:Packages:NIST:VSANS:Globals:Protocols:" + nameStr)
184       
185        String fullPath="",comma=",",list="",nameList="",PathStr="",item=""
186        Variable ii=0,numItems,checked,specialProtocol
187       
188        if((cmpstr(nameStr,"Base")==0) || (cmpstr(nameStr,"DoAll")==0))
189                specialProtocol = 1
190        else
191                specialProtocol = 0
192        Endif
193       
194        //background
195        checked = 1
196        nameList = w[0]
197        If(cmpstr(nameList,"none") ==0)
198                checked = 0
199        Endif
200
201        //set the global string to display and checkbox
202        String/G root:Packages:NIST:VSANS:Globals:Protocols:gBGD = nameList
203        CheckBox prot_check win=V_ProtocolPanel,value=checked
204       
205        //empty
206        checked = 1
207        nameList = w[1]
208        If(cmpstr(nameList,"none") ==0)
209                checked = 0
210        Endif
211
212        //set the global string to display and checkbox
213        String/G root:Packages:NIST:VSANS:Globals:Protocols:gEMP = nameList
214        CheckBox prot_check_1 win=V_ProtocolPanel,value=checked
215       
216        //DIV file
217        checked = 1
218        nameList = w[2]
219        If(cmpstr(nameList,"none") ==0)
220                checked = 0
221        Endif
222
223        //set the global string to display and checkbox
224        String/G root:Packages:NIST:VSANS:Globals:Protocols:gDIV = nameList
225        CheckBox prot_check_2 win=V_ProtocolPanel,value=checked
226       
227        //Mask file
228        checked = 1
229        nameList = w[3]
230        If(cmpstr(nameList,"none") ==0)
231                checked = 0
232        Endif
233
234        //set the global string to display and checkbox
235        String/G root:Packages:NIST:VSANS:Globals:Protocols:gMASK = nameList
236        CheckBox prot_check_3 win=V_ProtocolPanel,value=checked
237       
238        //4 = abs parameters
239        list = w[4]
240        numItems = ItemsInList(list,";")
241        checked = 1
242        if(numitems == 4 || numitems == 5)              //allow for protocols with no SDEV list item
243                //correct number of parameters, assume ok
244                String/G root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr = list
245                CheckBox prot_check_9 win=V_ProtocolPanel,value=checked
246        else
247                item = StringFromList(0,list,";")
248                if(cmpstr(item,"none")==0)
249                        checked = 0
250                        list = "none"
251                        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr = list
252                        CheckBox prot_check_9 win=V_ProtocolPanel,value=checked
253                else
254                        //force to "ask"
255                        checked = 1
256                        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr = "ask"
257                        CheckBox prot_check_9 win=V_ProtocolPanel,value=checked
258                Endif
259        Endif
260       
261        //5 = averaging choices
262        list = w[5]
263        item = StringByKey("AVTYPE",list,"=",";")
264        if(cmpstr(item,"none") == 0)
265                checked = 0
266                String/G root:Packages:NIST:VSANS:Globals:Protocols:gAVE = "none"
267                CheckBox prot_check_5 win=V_ProtocolPanel,value=checked
268        else
269                checked = 1
270                String/G root:Packages:NIST:VSANS:Globals:Protocols:gAVE = list
271                CheckBox prot_check_5 win=V_ProtocolPanel,value=checked
272        Endif
273       
274//      //6 = DRK choice
275//      list = w[6]
276//      item = StringByKey("DRK",list,"=",",")
277//      //print list,item
278//      if(cmpstr(item,"none") == 0)
279//              checked = 0
280//              String/G root:Packages:NIST:VSANS:Globals:Protocols:gDRK = list
281//              CheckBox prot_check_6 win=V_ProtocolPanel,value=checked
282//      else
283//              checked = 1
284//              String/G root:Packages:NIST:VSANS:Globals:Protocols:gDRK = list
285//              CheckBox prot_check_6 win=V_ProtocolPanel,value=checked
286//      Endif
287       
288        //7 = beginning trim points
289        SVAR gBegPtsStr=root:Packages:NIST:VSANS:Globals:Protocols:gBegPtsStr
290        gBegPtsStr = w[7]
291        //8 = end trim points
292        SVAR gEndPtsStr=root:Packages:NIST:VSANS:Globals:Protocols:gEndPtsStr
293        gEndPtsStr = w[8]
294       
295        //9 = unused
296        //10 = unused
297        //11 = unused
298
299
300        //all has been reset, get out
301        Return (0)
302End
303
304//button action procedure that simply closes the panel
305//
306Function V_DoneProtocolButton(ctrlName) : ButtonControl
307        String ctrlName
308
309        //will gracefully close and exit the protocol panel
310       
311        DoWindow/K V_ProtocolPanel
312End
313
314//button action procedure that saves the current choices on the panel
315//as a named protocol, for later recall
316//asks for a valid name, then creates a protocol from the panel choices
317//creates a wave, and sets the current protocol name to this new protocol
318//
319//now allows the user the choice to overwrite a protocol
320//
321Function V_SaveProtocolButton(ctrlName) : ButtonControl
322        String ctrlName
323
324        Variable notDone=1, newProto=1
325        //will prompt for protocol name, and save the protocol as a text wave
326        //prompt for name of new protocol wave to save
327        do
328                Execute "V_AskForName()"
329                SVAR newProtocol = root:Packages:NIST:VSANS:Globals:Protocols:gNewStr
330               
331                //make sure it's a valid IGOR name
332                newProtocol = CleanupName(newProtocol,0)        //strict naming convention
333                String/G root:Packages:NIST:VSANS:Globals:Protocols:gNewStr=newProtocol         //reassign, if changed
334                Print "newProtocol = ",newProtocol
335               
336                SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
337                if(WaveExists( $("root:Packages:NIST:VSANS:Globals:Protocols:" + newProtocol) ) == 1)
338                        //wave already exists
339                        DoAlert 1,"That name is already in use. Do you wish to overwrite the existing protocol?"
340                        if(V_Flag==1)
341                                notDone = 0
342                                newProto = 0
343                        else
344                                notDone = 1
345                        endif
346                else
347                        //name is good
348                        notDone = 0
349                Endif
350        while(notDone)
351       
352        //current data folder is  root:Packages:NIST:VSANS:Globals:Protocols
353        if(newProto)
354                Make/O/T/N=(kNumProtocolSteps) $("root:Packages:NIST:VSANS:Globals:Protocols:" + newProtocol)
355        Endif
356       
357        Variable err
358        err = V_MakeProtocolFromPanel( $("root:Packages:NIST:VSANS:Globals:Protocols:" + newProtocol) )
359        if(err)
360                DoAlert 0,"BGD and EMP files do not have the same configuration. No protocol saved."
361                KillWaves/Z $("root:Packages:NIST:VSANS:Globals:Protocols:" + newProtocol)
362        else
363                String/G  root:Packages:NIST:VSANS:Globals:Protocols:gProtoStr = newProtocol
364        endif
365        //the data folder WAS changed above, this must be reset to root:
366        SetDatafolder root:
367End
368
369//function that does the guts of reading the panel controls and globals
370//to create the necessary text fields for a protocol
371//Wave/T w (input) is an empty text wave of 8 elements for the protocol
372//on output, w[] is filled with the protocol strings as needed from the panel
373//
374// TODO
375// -- update for 12 points
376//
377// returns error==1 if files (emp, bgd) are not of the same configuration
378//
379Function V_MakeProtocolFromPanel(w)
380        Wave/T w
381       
382        //construct the protocol text wave form the panel
383        //it is to be parsed by ExecuteProtocol() for the actual data reduction
384        PathInfo catPathName                    //this is where the files came from
385        String pathstr=S_path,tempStr,curList
386        Variable checked,ii,numItems
387       
388        //look for checkbox, then take each item in list and prepend the path
389        //w[0] = background
390        ControlInfo/W=V_ProtocolPanel prot_check
391        checked = V_value
392        if(checked)
393                //build the list
394                //just read the global
395                SVAR str=root:Packages:NIST:VSANS:Globals:Protocols:gBGD
396                if(cmpstr(str,"ask")==0)
397                        w[0] = str              //just ask
398                else
399                        tempstr = V_ParseRunNumberList(str)
400                        if(strlen(tempStr)==0)
401                                return(1)                               //error parsing list
402                        else
403                                w[0] = tempstr
404                                str = tempstr           //set the protocol and the global
405                        endif
406                endif
407        else
408                //none used - set textwave (and global?)
409                w[0] = "none"
410                String/G root:Packages:NIST:VSANS:Globals:Protocols:gBGD = "none"
411        endif
412       
413        //w[1] = empty
414        ControlInfo/W=V_ProtocolPanel prot_check_1
415        checked = V_value
416        if(checked)
417                //build the list
418                //just read the global
419                SVAR str=root:Packages:NIST:VSANS:Globals:Protocols:gEMP
420                if(cmpstr(str,"ask")==0)
421                        w[1] = str
422                else
423                        tempstr = V_ParseRunNumberList(str)
424                        if(strlen(tempStr)==0)
425                                return(1)
426                        else
427                                w[1] = tempstr
428                                str=tempStr
429                        endif
430                endif
431        else
432                //none used - set textwave (and global?)
433                w[1] = "none"
434                String/G root:Packages:NIST:VSANS:Globals:Protocols:gEMP = "none"
435        endif
436       
437        //w[2] = div file
438        ControlInfo/W=V_ProtocolPanel prot_check_2
439        checked = V_value
440        if(checked)
441                //build the list
442                //just read the global
443                SVAR str=root:Packages:NIST:VSANS:Globals:Protocols:gDIV
444                if(cmpstr(str,"ask")==0)
445                        w[2] = str
446                else
447                        tempStr = V_ParseRunNumberList(str)
448                        if(strlen(tempStr)==0)
449                                return(1)
450                        else
451                                w[2] = tempstr
452                                str=tempstr
453                        endif
454                endif
455        else
456                //none used - set textwave (and global?)
457                w[2] = "none"
458                String/G root:Packages:NIST:VSANS:Globals:Protocols:gDIV = "none"
459        endif
460       
461        //w[3] = mask file
462        ControlInfo/W=V_ProtocolPanel prot_check_3
463        checked = V_value
464        if(checked)
465                //build the list
466                //just read the global
467                SVAR str=root:Packages:NIST:VSANS:Globals:Protocols:gMASK
468                if(cmpstr(str,"ask")==0)
469                        w[3] = str
470                else
471                        tempstr = V_ParseRunNumberList(str)
472                        if(strlen(tempstr)==0)
473                                return(1)
474                        else
475                                w[3] = tempstr
476                                str = tempstr
477                        endif
478                endif
479        else
480                //none used - set textwave (and global?)
481                w[3] = "none"
482                String/G root:Packages:NIST:VSANS:Globals:Protocols:gMASK = "none"
483        endif
484       
485        //w[4] = abs parameters
486        ControlInfo/W=V_ProtocolPanel prot_check_9
487        checked = V_value
488        if(checked)
489                //build the list
490                //just read the global
491                SVAR str=root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr
492                w[4] = str
493        else
494                //none used - set textwave (and global?)
495                w[4] = "none"
496                String/G root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr = "none"
497        endif
498       
499        //w[5] = averaging choices
500        ControlInfo/W=V_ProtocolPanel prot_check_5                      //do the average?
501        checked = V_value
502        if(checked)
503                //just read the global
504                SVAR avestr=root:Packages:NIST:VSANS:Globals:Protocols:gAVE
505                w[5] = avestr
506        else
507                //none used - set textwave
508                w[5] = "AVTYPE=none;"
509        endif
510       
511        //w[6]
512        //work.DRK information
513        SVAR drkStr=root:Packages:NIST:VSANS:Globals:Protocols:gDRK
514        w[6] = drkStr
515       
516        //w[7]
517        // beginning trim points
518        SVAR gBegPtsStr=root:Packages:NIST:VSANS:Globals:Protocols:gBegPtsStr
519        w[7] = gBegPtsStr
520       
521        //w[8]
522        // End trim points
523        SVAR gEndPtsStr=root:Packages:NIST:VSANS:Globals:Protocols:gEndPtsStr   
524        w[8] = gEndPtsStr
525       
526        //w[9]
527        //collimation type (filled in at averaging?)
528        w[9] = ""
529        //w[10]
530        //currently unused
531        w[10] = ""
532        //w[11]
533        //currently unused
534        w[11] = ""
535
536
537//      check that w[0](BGD) and w[1](EMP) are from matching configurations
538        if(cmpstr(w[0],"none")==0 || cmpstr(w[0],"ask")==0)
539                // no file specified for BGD, so no issues
540                return(0)
541        endif
542        if(cmpstr(w[1],"none")==0 || cmpstr(w[1],"ask")==0)
543                // no file specified for EMP, so no issues
544                return(0)
545        endif
546        Variable matchOK
547        // returns 1 for match , 0 if no match
548        matchOK = V_RawFilesMatchConfig(StringFromList(0, w[0], ","),StringFromList(0, w[1], ","))
549       
550        return(!matchOK)
551End
552
553
554//
555Function V_PickSAMButton(ctrlName) : ButtonControl
556        String ctrlName
557
558
559End
560
561
562
563
564//
565// TODO
566// -- identifying "intent" using V_get can be very slow, since it reads in each and every data file.
567//   grep is a lot faster, but there can be a lot of false "hits" unless I do it correctly.
568//
569//
570//      //grep through what text I can find in the VAX binary
571//      // Grep Note: the \\b sequences limit matches to a word boundary before and after
572//      // "boondoggle", so "boondoggles" and "aboondoggle" won't match.
573//      if(gRadioVal == 2)
574//              for(ii=0;ii<num;ii+=1)
575//                      item=StringFromList(ii, newList , ";")
576////                    Grep/P=catPathName/Q/E=("(?i)\\b"+match+"\\b") item
577//                      Grep/P=catPathName/Q/E=("(?i)"+match) item
578//                      if( V_value )   // at least one instance was found
579////                            Print "found ", item,ii
580//                              list += item + ";"
581//                      endif
582//              endfor
583//
584//              newList = list
585//      endif
586
587// match is the string to look for in the search
588// 0 is a flag to tell it to look in the file catalog (the fastest method)
589// Other options are to grep, or to read the intent field in every file
590Function/S V_GetSAMList()
591
592//      String match="SAMPLE"
593//      String list = V_getFileIntentList(match,0)
594
595        String intent = "SAMPLE"
596        String purpose = "SCATTERING"
597        String list = V_getFileIntentPurposeList(intent,purpose,0)
598
599//      Printf "SAM files = %s\r",list 
600        return(list)
601end
602
603
604Function/S V_GetBGDList()
605
606        String intent="BLOCKED BEAM"
607        String purpose="SCATTERING"
608//      String list = V_getFileIntentList(match,0)
609        String list = V_getFileIntentPurposeList(intent,purpose,0)
610       
611//      Printf "BGD files = %s\r",list 
612        return(list)
613end
614
615//
616// V_getFileIntentPurposeList(intent,purpose,method)
617Function/S V_GetEMPList()
618
619        String intent="EMPTY CELL"
620        String purpose="SCATTERING"
621//      String list = V_getFileIntentList(match,0)
622        String list = V_getFileIntentPurposeList(intent,purpose,0)
623
624
625//      Printf "EMP files = %s\r",list 
626        return(list)
627end
628
629
630//
631// TODO
632// -- decide on the way to locate the blocked beam files. Is the enumerated text of the intent
633//    sufficiently unique to locate the file?
634// -- can I use the Data Catalog waves to locate the files  - faster?
635//    (fails if the catalog has not been read in recently enough)
636//
637//
638Function/S V_PickBGDButton(ctrlName) : ButtonControl
639        String ctrlName
640
641        String list="",item="",fname,newList,intent
642        Variable ii,num
643       
644        PathInfo catPathName
645        String path = S_path
646
647        String match="BLOCKED BEAM"
648
649//v_tic()
650// get the list from the file catalog (=0.0007s)
651//     
652        WAVE/T fileNameW = root:Packages:NIST:VSANS:CatVSHeaderInfo:Filenames
653        WAVE/T intentW = root:Packages:NIST:VSANS:CatVSHeaderInfo:Intent
654       
655        Variable np = numpnts(intentW)
656        for(ii=0;ii<np;ii+=1)
657                if(cmpstr(intentW[ii],match)==0)
658                        list += fileNameW[ii] + ";"
659                endif           
660        endfor
661       
662        List = SortList(List,";",0)
663        Printf "BGD files = %s\r",list 
664//v_toc()       
665       
666       
667////v_tic()                     // from grep = 3.3s
668//      newList = V_GetRawDataFileList()
669//      num=ItemsInList(newList)
670//     
671////    for(ii=0;ii<num;ii+=1)
672////            item=StringFromList(ii, newList , ";")
673////            fname = path + item
674////            intent = V_getReduction_intent(fname)
675////            if(cmpstr(intent,"BLOCKED BEAM") == 0)
676////                    list += item + ";"
677////            endif
678////
679////    endfor
680//      list = ""       
681//      for(ii=0;ii<num;ii+=1)
682//              item=StringFromList(ii, newList , ";")
683//              Grep/P=catPathName/Q/E=("(?i)"+match) item
684//              if( V_value )   // at least one instance was found
685////                            Print "found ", item,ii
686//                      list += item + ";"
687//              endif
688//      endfor
689//             
690//             
691//      List = SortList(List,";",0)
692//      Printf "BGD files = %s\r",list
693////v_toc()
694       
695        return(list)
696End
697
698
699//
700Function/S V_PickEMPButton(ctrlName) : ButtonControl
701        String ctrlName
702        String list="",item="",fname,newList,intent
703        Variable ii,num
704       
705        PathInfo catPathName
706        String path = S_path
707
708        String match="EMPTY CELL"
709
710// get the list from the file catalog (=0.0007s)
711//     
712        WAVE/T fileNameW = root:Packages:NIST:VSANS:CatVSHeaderInfo:Filenames
713        WAVE/T intentW = root:Packages:NIST:VSANS:CatVSHeaderInfo:Intent
714       
715        Variable np = numpnts(intentW)
716        for(ii=0;ii<np;ii+=1)
717                if(cmpstr(intentW[ii],match)==0)
718                        list += fileNameW[ii] + ";"
719                endif           
720        endfor
721       
722        List = SortList(List,";",0)
723        Printf "EMP files = %s\r",list 
724
725
726//     
727//      newList = V_GetRawDataFileList()
728//      num=ItemsInList(newList)
729//     
730////    for(ii=0;ii<num;ii+=1)
731////            item=StringFromList(ii, newList , ";")
732////            fname = path + item
733////            intent = V_getReduction_intent(fname)
734////            if(cmpstr(intent,"EMPTY CELL") == 0)
735////                    list += item + ";"
736////            endif
737////
738////    endfor
739//
740//      for(ii=0;ii<num;ii+=1)
741//              item=StringFromList(ii, newList , ";")
742//              Grep/P=catPathName/Q/E=("(?i)"+match) item
743//              if( V_value )   // at least one instance was found
744////                            Print "found ", item,ii
745//                      list += item + ";"
746//              endif
747//
748//      endfor
749//             
750//      List = SortList(List,";",0)
751//      Printf "EMP files = %s\r",list
752       
753        return(list)
754End
755
756
757//
758Function/S V_PickEMPBeamButton(ctrlName) : ButtonControl
759        String ctrlName
760        String list="",item="",fname,newList,intent
761        Variable ii,num
762       
763        PathInfo catPathName
764        String path = S_path
765
766        String match="OPEN BEAM"
767
768// get the list from the file catalog (=0.0007s)
769//     
770        WAVE/T fileNameW = root:Packages:NIST:VSANS:CatVSHeaderInfo:Filenames
771        WAVE/T intentW = root:Packages:NIST:VSANS:CatVSHeaderInfo:Intent
772       
773        Variable np = numpnts(intentW)
774        for(ii=0;ii<np;ii+=1)
775                if(cmpstr(intentW[ii],match)==0)
776                        list += fileNameW[ii] + ";"
777                endif           
778        endfor
779       
780        List = SortList(List,";",0)
781        Printf "EMP Beam files = %s\r",list     
782
783
784       
785        return(list)
786End
787
788
789// TODO
790// -- find proper way to search for these files
791// -- they *may* be written to the file header(reduction block)
792// -- or grep for VSANS_DIV (in the title)
793Function/S V_GetDIVList()
794
795        String list="",item="",fname,newList,intent
796        Variable ii,num,val
797       
798        PathInfo catPathName
799        String path = S_path
800       
801        newList = V_Get_NotRawDataFileList()
802//      newList = V_RemoveEXTFromList(newlist,"hst")            // remove the event files
803//      newList = V_RemoveEXTFromList(newlist,"ave")            // remove the ave files
804//      newList = V_RemoveEXTFromList(newlist,"abs")            // remove the abs files
805//      newList = V_RemoveEXTFromList(newlist,"phi")            // remove the phi files
806//      newList = V_RemoveEXTFromList(newlist,"pxp")            // remove the pxp files
807//      newList = V_RemoveEXTFromList(newlist,"DS_Store")               // remove the DS_Store file (OSX only)
808
809        num=ItemsInList(newList)
810       
811// keep only DIV files in the list
812        num=ItemsInList(newList)
813
814        String matchStr="*_DIV_*"               // this is part of the title of a VSANS _DIV_ file
815        for(ii=0;ii<num;ii+=1)
816                item=StringFromList(ii, newList , ";")
817                val = stringmatch(item,matchStr)
818                if( val )       // true if the string did match
819                                list += item + ";"
820                endif
821
822        endfor
823
824        List = SortList(List,";",0)
825
826//
827//      String match="DIV"
828//      for(ii=0;ii<num;ii+=1)
829//              item=StringFromList(ii, newList , ";")
830//              Grep/P=catPathName/Q/E=("(?i)\\b"+match+"\\b") item
831////            Grep/P=catPathName/Q/E=("(?i)"+match) item
832//              if( V_value )   // at least one instance was found
833////                            Print "found ", item,ii
834////                    if(strsearch(item,"pxp",0,2) == -1)             //does NOT contain .pxp (the current experiment will be a match)
835//                              list += item + ";"
836////                    endif
837//              endif
838//      endfor
839//             
840
841        return(list)
842end
843
844
845Function/S V_GetMSKList()
846
847        String list="",item="",fname,newList,intent
848        Variable ii,num,val
849       
850        PathInfo catPathName
851        String path = S_path
852       
853        newList = V_Get_NotRawDataFileList()
854//      newList = V_RemoveEXTFromList(newlist,"hst")            // remove the event files
855//      newList = V_RemoveEXTFromList(newlist,"ave")            // remove the ave files
856//      newList = V_RemoveEXTFromList(newlist,"abs")            // remove the abs files
857//      newList = V_RemoveEXTFromList(newlist,"phi")            // remove the phi files
858//      newList = V_RemoveEXTFromList(newlist,"pxp")            // remove the pxp files
859//      newList = V_RemoveEXTFromList(newlist,"png")            // remove the png files
860//      newList = V_RemoveEXTFromList(newlist,"jpg")            // remove the jpg files
861//      newList = V_RemoveEXTFromList(newlist,"DS_Store")               // remove the DS_Store file (OSX only)
862
863// keep only MASK files in the list
864        num=ItemsInList(newList)
865
866        String matchStr="*_MASK_*"              // this is part of the title of a VSANS _MASK_ file
867        for(ii=0;ii<num;ii+=1)
868                item=StringFromList(ii, newList , ";")
869                val = stringmatch(item,matchStr)
870                if( val )       // true if the string did match
871                                list += item + ";"
872                endif
873
874        endfor
875               
876        List = SortList(List,";",0)
877       
878
879//
880////    String match="MASK"             // this is part of the title of a VSANS MASK file
881//      String match="VSANS_MASK"               // this is part of the title of a VSANS MASK file
882//      for(ii=0;ii<num;ii+=1)
883//              item=StringFromList(ii, newList , ";")
884//              Grep/P=catPathName/Q/E=("(?i)\\b"+match+"\\b") item
885////            Grep/P=catPathName/Q/E=("(?i)"+match) item
886//              if( V_value )   // at least one instance was found
887////                            Print "found ", item,ii
888////                    if(strsearch(item,"pxp",0,2) == -1)             //does NOT contain .pxp (the current experiment will be a match)
889//                              list += item + ";"
890////                    endif
891//              endif
892//
893//      endfor
894//             
895
896
897        List = SortList(List,";",0)
898
899        return(list)
900end
901
902
903//
904// TODO
905// -- find proper way to search for these files
906// -- they *may* be written to the file header(reduction block)
907// -- or grep for VSANS_MASK (in the title)
908Function/S V_PickMASKButton(ctrlName) : ButtonControl
909        String ctrlName
910        String list="",item="",fname,newList,intent
911        Variable ii,num
912       
913        PathInfo catPathName
914        String path = S_path
915       
916        newList = V_Get_NotRawDataFileList()
917        newList = V_RemoveEXTFromList(newlist,"hst")            // remove the event files
918        num=ItemsInList(newList)
919       
920//      for(ii=0;ii<num;ii+=1)
921//              item=StringFromList(ii, newList , ";")
922//              fname = path + item
923//              intent = V_getReduction_intent(fname)
924//              if(cmpstr(intent,"MASK") == 0)
925//                      list += item + ";"
926//              endif
927//
928//      endfor
929
930        String match="MASK"
931        for(ii=0;ii<num;ii+=1)
932                item=StringFromList(ii, newList , ";")
933                Grep/P=catPathName/Q/E=("(?i)\\b"+match+"\\b") item
934//              Grep/P=catPathName/Q/E=("(?i)"+match) item
935                if( V_value )   // at least one instance was found
936//                              Print "found ", item,ii
937                        list += item + ";"
938                endif
939
940        endfor
941               
942        List = SortList(List,";",0)
943        Printf "MASK files = %s\r",list
944       
945        return(list)   
946
947       
948End
949
950//button action function to reduce one file with the information specified on
951//the panel
952//a temporary protocol is created, even if the fields correspond to a named protocol
953//(only the protocol wave values are written to the data header, but the name is written to the
954//schematic - this could cause some unwanted confusion)
955//
956//if a sample file(s) is selected, only that file(s) will be reduced
957//if no file is selected, the user will be prompted with a standard open
958//dialog to select sample data file(s)
959//
960Function V_ReduceOneButton(ctrlName) : ButtonControl
961        String ctrlName
962
963        //parse the information on the panel and assign to tempProtocol wave (in protocol folder)
964        //and execute
965        String temp="root:Packages:NIST:VSANS:Globals:Protocols:tempProtocol"
966        Wave/T w=$temp
967        Variable ii=0,num=12,err
968        do
969                w[ii] = ""
970                ii+=1
971        while(ii<num)
972       
973       
974        err = V_MakeProtocolFromPanel(w)
975        if(err)
976                DoAlert 0,"BGD and EMP files do not have the same configuration."
977                return(0)
978        endif
979       
980        //the "current" protocol is the "tempProtocol" that was parsed from the panel input
981        //set the global, so that the data writing routine can find the protocol wave (fatal otherwise)
982        String/G root:Packages:NIST:VSANS:Globals:Protocols:gProtoStr="tempProtocol"
983       
984        PathInfo catPathName                    //this is where the files came from
985        String pathstr=S_path,samStr
986       
987        //take the string from the panel
988        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gSAM
989       
990        if( (strlen(tempStr) == 0) || (cmpstr(tempStr,"ask")==0) )
991                //let user select the files
992                tempStr="ask"
993                V_ExecuteProtocol(temp,tempStr)
994                return(0)
995        Else
996                //parse the list of numbers
997                //send only the filenames, without paths
998                samStr = V_ParseRunNumberList(tempStr)
999                If(strlen(samStr)==0)
1000                        DoAlert 0,"The SAM file number cound not be interpreted. Please enter a valid run number or filename"
1001                        return(1)
1002                endif
1003                tempStr=samStr          //reset the global
1004                V_ExecuteProtocol(temp,samStr)
1005                return(0)
1006        endif
1007End
1008
1009
1010//button action function will prompt user for absolute scaling parameters
1011//either from an empty beam file or by manually entering the 4 required values
1012//uses the same function and shared global string as the questionnare form of reduction
1013//in "protocol.ipf" - the string is root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr
1014//
1015Function V_SetABSParamsButton(ctrlName) : ButtonControl
1016        String ctrlName
1017
1018        //will prompt for a list of ABS parameters (4) through a global string variable
1019        if(cmpstr(ctrlName,"pick_ABS_B") == 0)
1020                Execute "V_AskForAbsoluteParams_Quest(1)"
1021        else
1022                Execute "V_AskForAbsoluteParams_Quest(0)"
1023        endif
1024End
1025
1026
1027
1028//the panel recreation macro
1029//
1030Window V_ProtocolPanel()
1031        PauseUpdate; Silent 1           // building window...
1032        NewPanel /W=(1280,332,1630,932) /K=1 as "VSANS Reduction Protocol"
1033        ModifyPanel cbRGB=(56589,50441,50159), fixedSize=1
1034        SetDrawLayer UserBack
1035        DrawLine 3,65,301,65
1036        DrawLine 3,157,301,157
1037        DrawLine 3,208,301,208
1038        DrawLine 3,257,301,257
1039        DrawLine 3,305,301,305
1040        DrawLine 3,350,301,350
1041        DrawLine 3,445,301,445
1042        DrawLine 3,513,301,513
1043        DrawLine 3,396,301,396
1044
1045//
1046        Button button_help,pos={300,2},size={25,20},proc=V_ShowProtoHelp,title="?"
1047        Button button_help,help={"Show the help file for setting up a reduction protocol"}
1048        Button button_quest,pos={20,2},size={150,20},proc=V_ProtocolQuestionnaire,title="Questions"
1049        Button button_quest,help={"Run through the questionnaire for setting up a reduction protocol"}
1050        Button button_quest,disable=2
1051
1052
1053        PopupMenu popup_sam,pos={85,68},size={51,23},proc=V_SAMFilePopMenuProc
1054        PopupMenu popup_sam,mode=1,value= #"V_getSAMList()"     
1055        PopupMenu popup_bkg,pos={85,164},size={51,23},proc=V_BKGFilePopMenuProc
1056        PopupMenu popup_bkg,mode=1,value= #"V_getBGDList()"
1057        PopupMenu popup_emp,pos={85,213},size={51,23},proc=V_EMPFilePopMenuProc
1058        PopupMenu popup_emp,mode=1,value= #"V_getEMPList()"
1059        PopupMenu popup_div,pos={85,263},size={51,23},proc=V_DIVFilePopMenuProc
1060        PopupMenu popup_div,mode=1,value= #"V_getDIVList()"
1061        PopupMenu popup_msk,pos={85,356},size={51,23},proc=V_MSKFilePopMenuProc
1062        PopupMenu popup_msk,mode=1,value= #"V_getMSKList()"     
1063               
1064               
1065        CheckBox prot_check,pos={6,163},size={74,14},title="Background"
1066        CheckBox prot_check,help={"If checked, the specified background file will be included in the data reduction. If the file name is \"ask\", then the user will be prompted for the file"}
1067        CheckBox prot_check,value= 1
1068        CheckBox prot_check_1,pos={6,215},size={71,14},title="Empty Cell"
1069        CheckBox prot_check_1,help={"If checked, the specified empty cell file will be included in the data reduction. If the file name is \"ask\", then the user will be prompted for the file"}
1070        CheckBox prot_check_1,value= 1
1071        CheckBox prot_check_2,pos={6,263},size={72,14},title="Sensitivity"
1072        CheckBox prot_check_2,help={"If checked, the specified detector sensitivity file will be included in the data reduction. If the file name is \"ask\", then the user will be prompted for the file"}
1073        CheckBox prot_check_2,value= 1
1074        CheckBox prot_check_3,pos={6,356},size={43,14},title="Mask"
1075        CheckBox prot_check_3,help={"If checked, the specified mask file will be included in the data reduction. If the file name is \"ask\", then the user will be prompted for the file"}
1076        CheckBox prot_check_3,value= 1
1077        CheckBox prot_check_4,pos={6,70},size={53,14},title="Sample"
1078        CheckBox prot_check_4,help={"If checked, the specified sample file will be included in the data reduction. If the file name is \"ask\", then the user will be prompted for the file"}
1079        CheckBox prot_check_4,value= 1
1080        CheckBox prot_check_5,pos={6,399},size={56,14},title="Average"
1081        CheckBox prot_check_5,help={"If checked, the specified averaging will be performed at the end of the data reduction."}
1082        CheckBox prot_check_5,value= 1 
1083        CheckBox prot_check_9,pos={6,310},size={59,14},title="Absolute"
1084        CheckBox prot_check_9,help={"If checked, absolute calibration will be included in the data reduction. If the parameter list is \"ask\", then the user will be prompted for absolue parameters"}
1085        CheckBox prot_check_9,value= 1
1086       
1087
1088//      Button pick_sam,pos={214,28},size={70,20},proc=V_PickSAMButton,title="set SAM"
1089//      Button pick_sam,help={"This button will set the file selected in the File Catalog table to be the sample file"}
1090//      Button pick_bgd,pos={214,75},size={70,20},proc=V_PickBGDButton,title="set BGD"
1091//      Button pick_bgd,help={"This button will set the file selected in the File Catalog table to be the background file."}
1092//      Button pick_emp,pos={214,125},size={70,20},proc=V_PickEMPButton,title="set EMP"
1093//      Button pick_emp,help={"This button will set the file selected in the File Catalog table to be the empty cell file."}
1094//      Button pick_DIV,pos={214,173},size={70,20},proc=V_PickDIVButton,title="set DIV"
1095//      Button pick_DIV,help={"This button will set the file selected in the File Catalog table to be the sensitivity file."}
1096        Button pick_ABS,pos={264,308},size={80,20},proc=V_SetABSParamsButton,title="set ABS MF"
1097        Button pick_ABS,help={"This button will prompt the user for absolute scaling parameters"}       
1098       
1099        Button pick_ABS_B,pos={264,330},size={80,20},proc=V_SetABSParamsButton,title="set ABS B"
1100        Button pick_ABS_B,help={"This button will prompt the user for absolute scaling parameters"}     
1101//      Button pick_MASK,pos={214,266},size={70,20},proc=V_PickMASKButton,title="set MASK"
1102//      Button pick_MASK,help={"This button will set the file selected in the File Catalog table to be the mask file."}
1103
1104
1105        Button pick_AVE,pos={188,401},size={150,20},proc=V_SetAverageParamsButtonProc,title="set AVERAGE params"
1106        Button pick_AVE,help={"Prompts the user for the type of 1-D averaging to perform, as well as saving options"}
1107
1108       
1109        Button pick_trim,pos={264,454},size={70,20},proc=V_TrimDataProtoButton,title="Trim"
1110        Button pick_trim,help={"This button will prompt the user for trimming parameters"}     
1111       
1112       
1113        SetVariable samStr,pos={6,90},size={250,15},title="file:"
1114        SetVariable samStr,help={"Filename of the sample file(s) to be used in the data reduction"}
1115        SetVariable samStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gSAM           
1116        SetVariable bgdStr,pos={7,186},size={250,15},title="file:"
1117        SetVariable bgdStr,help={"Filename of the background file(s) to be used in the data reduction"}
1118        SetVariable bgdStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gBGD
1119        SetVariable empStr,pos={8,236},size={250,15},title="file:"
1120        SetVariable empStr,help={"Filename of the empty cell file(s) to be used in the data reduction"}
1121        SetVariable empStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gEMP
1122        SetVariable divStr,pos={9,285},size={250,15},title="file:"
1123        SetVariable divStr,help={"Filename of the detector sensitivity file to be used in the data reduction"}
1124        SetVariable divStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gDIV
1125        SetVariable maskStr,pos={9,377},size={250,15},title="file:"
1126        SetVariable maskStr,help={"Filename of the mask file to be used in the data reduction"}
1127        SetVariable maskStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gMASK
1128        SetVariable absStr,pos={7,331},size={250,15},title="parameters:"
1129        SetVariable absStr,help={"Keyword-string of values necessary for absolute scaling of data. Remaining parameters are taken from the sample file."}
1130        SetVariable absStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr
1131        SetVariable aveStr,pos={9,424},size={250,15},title="parameters:"
1132        SetVariable aveStr,help={"Keyword-string of choices used for averaging and saving the 1-D data files"}
1133        SetVariable aveStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gAVE
1134
1135        SetVariable begStr,pos={9,464},size={250,15},title="Beg Trim:"
1136        SetVariable begStr,help={"Keyword-string of choices used for averaging and saving the 1-D data files"}
1137        SetVariable begStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gBegPtsStr
1138        SetVariable endStr,pos={9,484},size={250,15},title="End Trim:"
1139        SetVariable endStr,help={"Keyword-string of choices used for averaging and saving the 1-D data files"}
1140        SetVariable endStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gEndPtsStr
1141
1142
1143       
1144        //only show DRK if user wants to see it
1145        //if global = 1,then show => set disable = 0
1146//      CheckBox prot_check_6,pos={6,363},size={113,14},proc=DrkCheckProc,title="Use DRK correction"
1147//      CheckBox prot_check_6,help={"If checked, the selected file will be used for DRK correction. Typically this is NOT checked"}
1148//      CheckBox prot_check_6,value= 0,disable = (!root:Packages:NIST:gAllowDRK)
1149//      SetVariable drkStr,pos={120,363},size={150,15},title="."
1150//      SetVariable drkStr,help={"DRK detector count file"},disable = (!root:Packages:NIST:gAllowDRK)
1151//      SetVariable drkStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gDRK
1152
1153
1154        Button export_button, size={120,20},pos={125,540},title="Export to Data",proc=V_ExportFileProtocol
1155        Button export_button, help={"Exports the protocol to data file on disk for Importing into another experiment"}
1156        Button import_button, size={120,20},pos={125,562},title="Import from Data",proc=V_ImportFileProtocol
1157        Button import_button,help={"Imports a protocol from a data file on disk for use in this experiment"}
1158        Button recallProt,pos={7,540},size={107,20},proc=V_RecallProtocolButton,title="Recall Protocol"
1159        Button recallProt,help={"Resets the panel to the file choices in  a previously saved protocol"}
1160        Button del_protocol,pos={7,562},size={110,20},proc=V_DeleteProtocolButton,title="Delete Protocol"
1161        Button del_protocol,help={"Use this to delete a previously saved protocol."}
1162        Button done_protocol,pos={285,562},size={45,20},proc=V_DoneProtocolButton,title="Done"
1163        Button done_protocol,help={"This button will close the panel. The panel can be recalled at any time from the SANS menu."}
1164        Button saveProtocol,pos={7,518},size={100,20},proc=V_SaveProtocolButton,title="Save Protocol"
1165        Button saveProtocol,help={"Saves the cerrent selections in the panel to a protocol which can be later recalled"}
1166        Button ReduceOne,pos={240,518},size={100,20},proc=V_ReduceOneButton,title="Reduce A File"
1167        Button ReduceOne,help={"Using the panel selections, the specified sample file will be reduced. If none is specified, the user will be prompted for a sample file"}
1168
1169EndMacro
1170
1171
1172
1173
1174
1175Function V_SAMFilePopMenuProc(pa) : PopupMenuControl
1176        STRUCT WMPopupAction &pa
1177
1178        switch( pa.eventCode )
1179                case 2: // mouse up
1180                        Variable popNum = pa.popNum
1181                        String popStr = pa.popStr
1182                        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gSAM
1183                        tempStr = popStr
1184                        break
1185                case -1: // control being killed
1186                        break
1187        endswitch
1188
1189        return 0
1190End
1191
1192
1193Function V_BKGFilePopMenuProc(pa) : PopupMenuControl
1194        STRUCT WMPopupAction &pa
1195
1196        switch( pa.eventCode )
1197                case 2: // mouse up
1198                        Variable popNum = pa.popNum
1199                        String popStr = pa.popStr
1200                        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gBGD
1201                        tempStr = popStr
1202                        break
1203                case -1: // control being killed
1204                        break
1205        endswitch
1206
1207        return 0
1208End
1209
1210Function V_EMPFilePopMenuProc(pa) : PopupMenuControl
1211        STRUCT WMPopupAction &pa
1212
1213        switch( pa.eventCode )
1214                case 2: // mouse up
1215                        Variable popNum = pa.popNum
1216                        String popStr = pa.popStr
1217                        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gEMP
1218                        tempStr = popStr
1219                        break
1220                case -1: // control being killed
1221                        break
1222        endswitch
1223
1224        return 0
1225End
1226
1227Function V_DIVFilePopMenuProc(pa) : PopupMenuControl
1228        STRUCT WMPopupAction &pa
1229
1230        switch( pa.eventCode )
1231                case 2: // mouse up
1232                        Variable popNum = pa.popNum
1233                        String popStr = pa.popStr
1234                        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gDIV
1235                        tempStr = popStr
1236                        break
1237                case -1: // control being killed
1238                        break
1239        endswitch
1240
1241        return 0
1242End
1243
1244Function V_MSKFilePopMenuProc(pa) : PopupMenuControl
1245        STRUCT WMPopupAction &pa
1246
1247        switch( pa.eventCode )
1248                case 2: // mouse up
1249                        Variable popNum = pa.popNum
1250                        String popStr = pa.popStr
1251                        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gMASK
1252                        tempStr = popStr
1253                        break
1254                case -1: // control being killed
1255                        break
1256        endswitch
1257
1258        return 0
1259End
1260
1261////activated when user checks/unchecks the box
1262////either prompts for a file using a standard dialog, or removes the current file
1263//Function V_DrkCheckProc(ctrlName,checked) : CheckBoxControl
1264//      String ctrlName
1265//      Variable checked                //Desired state, not previous state
1266//
1267//      SVAR drkStr=root:Packages:NIST:VSANS:Globals:Protocols:gDRK
1268//      if(checked==1)
1269//              //print "Unchecked on call"
1270//              //this just asks for the filename, doesn't open the file
1271//              String msgStr="Select the DRK file",fullPath="",fileStr=""
1272//              Variable refnum
1273//             
1274//              Open/D/R/T="????"/M=(msgStr)/P=catPathName refNum
1275//              fullPath = S_FileName           //fname is the full path
1276//              if(cmpstr(fullpath,"")==0)
1277//                      //user cancelled
1278//                      CheckBox prot_check_6,value=0           //keep box unchecked
1279//                      return(0)
1280//              Endif
1281//              fileStr=V_GetFileNameFromPathNoSemi(fullPath)
1282//              //Print fileStr
1283//              //update the global string
1284//              drkStr = ReplaceStringByKey("DRK",drkStr,fileStr,"=",",")
1285//              drkStr = ReplaceNumberByKey("DRKMODE", drkStr, 10 ,"=",",")
1286//      else
1287//              //print "checked on call"
1288//              drkStr="DRK=none,DRKMODE=0,"            //change the global
1289//      endif
1290//     
1291//End
1292
1293
1294Function V_ShowProtoHelp(ctrlName) : ButtonControl
1295        String ctrlName
1296        DisplayHelpTopic/Z/K=1 "VSANS Data Reduction Tutorial[VSANS Reduction Protocol]"
1297        if(V_flag !=0)
1298                DoAlert 0,"The VSANS Data Reduction Tutorial Help file could not be found"
1299        endif
1300End
1301
1302//button action procedure to get the type of average requested by the user
1303//presented as a missing parameter dialog, which is really user-UN-friendly
1304//and will need to be re-thought. Defaults of dialog are set for normal
1305//circular average, so typically click "continue" and proceed
1306//
1307Function V_SetAverageParamsButtonProc(ctrlName) : ButtonControl
1308        String ctrlName
1309       
1310//      Execute "V_GetAvgInfo_Full()"
1311        Execute "V_GetAvgInfo()"
1312       
1313        //set the global string
1314        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr
1315        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAVE = tempStr
1316
1317End
1318
1319// TODO
1320// -- this is a trimmed down version of the "full" set of averaging options
1321//    add to this as needed as I figure out what functionality is appropriate
1322//
1323//procedure called by protocol panel to ask user for average type choices
1324// somewhat confusing and complex, but may be as good as it gets.
1325//
1326//Proc V_GetAvgInfo(av_typ,autoSave,autoName,autoPlot,side,phi,dphi,width,QCtr,QDelta)
1327Proc V_GetAvgInfo(av_typ,autoSave,autoName,binType,qCtr,qDelta,detGroup)
1328        String av_typ,autoSave,AutoName,binType
1329//      Variable phi=0,dphi=10,width=10,Qctr = 0.01,qDelta=10
1330        Variable Qctr=0.1,qDelta=0.01
1331        String detGroup="F"
1332
1333//      Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII;PNG_Graphic;Sector_PlusMinus;"
1334        Prompt av_typ, "Type of Average",popup,"Circular;Narrow_Slit;Annular;"
1335
1336// comment out above line in DEMO_MODIFIED version, and uncomment the line below (to disable PNG save)
1337//      Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII"
1338        Prompt autoSave,"Save files to disk?",popup,"Yes - Concatenate;Yes - Individual;No"
1339        Prompt autoName,"Auto-Name files?",popup,"Auto;Manual"
1340//      Prompt autoPlot,"Plot the averaged Data?",popup,"Yes;No"
1341//      Prompt side,"Include detector halves?",popup,"both;right;left"
1342//      Prompt phi,"Orientation Angle (-90,90) degrees (Rectangular or Sector)"
1343//      Prompt dphi, "Azimuthal range (0,45) degrees (Sector only)"
1344//      Prompt width, "Width of Rectangular average (1,128)"
1345        Prompt binType,"Binning Type?",popup,ksBinTypeStr
1346
1347        Prompt Qctr, "q-value of center of annulus"
1348        Prompt Qdelta,"(+/-) q-width of annulus"
1349        Prompt detGroup,"Group for annulus"
1350       
1351        //assign results of dialog to key=value string, semicolon separated
1352        //do only what is necessary, based on av_typ
1353        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr=""
1354
1355        // TODO:
1356        // hard wired value
1357        String autoPlot = "Yes"
1358       
1359               
1360        // all averages need these values
1361        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "AVTYPE=" + av_typ + ";"
1362        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "SAVE=" + autoSave + ";"
1363        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "NAME=" + autoName + ";"
1364        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "PLOT=" + autoPlot + ";"
1365        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "BINTYPE=" + binType + ";"
1366       
1367//      if(cmpstr(av_typ,"Sector")==0 || cmpstr(av_typ,"Sector_PlusMinus")==0)
1368//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
1369//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
1370//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "DPHI=" + num2str(dphi) + ";"
1371//      Endif
1372//     
1373//      if(cmpstr(av_typ,"Rectangular")==0)
1374//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
1375//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
1376//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "WIDTH=" + num2str(width) + ";"
1377//      Endif
1378//     
1379        if(cmpstr(av_typ,"Annular")==0)
1380                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "QCENTER=" + num2str(QCtr) + ";"
1381                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "QDELTA=" + num2str(QDelta) + ";"
1382                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "DETGROUP=" + detGroup + ";"
1383        Endif
1384End
1385
1386
1387// TODO
1388// -- this is the original(SANS) version, and needs to be updated for VSANS as the averaging options are
1389//    worked out
1390// -- there have been changes made to V_GetAvgInfo() above -- so work from that version, NOT this one.
1391//
1392//
1393//procedure called by protocol panel to ask user for average type choices
1394// somewhat confusing and complex, but may be as good as it gets.
1395//
1396Proc V_GetAvgInfo_Full(av_typ,autoSave,autoName,autoPlot,side,phi,dphi,width,QCtr,QDelta)
1397        String av_typ,autoSave,AutoName,autoPlot,side
1398        Variable phi=0,dphi=10,width=10,Qctr = 0.01,qDelta=10
1399        Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII;PNG_Graphic;Sector_PlusMinus;"
1400// comment out above line in DEMO_MODIFIED version, and uncomment the line below (to disable PNG save)
1401//      Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII"
1402        Prompt autoSave,"Save files to disk?",popup,"Yes;No"
1403        Prompt autoName,"Auto-Name files?",popup,"Auto;Manual"
1404        Prompt autoPlot,"Plot the averaged Data?",popup,"Yes;No"
1405        Prompt side,"Include detector halves?",popup,"both;right;left"
1406        Prompt phi,"Orientation Angle (-90,90) degrees (Rectangular or Sector)"
1407        Prompt dphi, "Azimuthal range (0,45) degrees (Sector only)"
1408        Prompt width, "Width of Rectangular average (1,128)"
1409        Prompt Qctr, "q-value of center of annulus"
1410        Prompt Qdelta,"Pixel width of annulus"
1411
1412        //assign results of dialog to key=value string, semicolon separated
1413        //do only what is necessary, based on av_typ
1414        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr=""
1415       
1416        // all averages need these four values
1417        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "AVTYPE=" + av_typ + ";"
1418        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "SAVE=" + autoSave + ";"
1419        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "NAME=" + autoName + ";"
1420        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "PLOT=" + autoPlot + ";"
1421       
1422        if(cmpstr(av_typ,"Sector")==0 || cmpstr(av_typ,"Sector_PlusMinus")==0)
1423                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
1424                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
1425                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "DPHI=" + num2str(dphi) + ";"
1426        Endif
1427       
1428        if(cmpstr(av_typ,"Rectangular")==0)
1429                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
1430                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
1431                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "WIDTH=" + num2str(width) + ";"
1432        Endif
1433       
1434        if(cmpstr(av_typ,"Annular")==0)
1435                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "QCENTER=" + num2str(QCtr) + ";"
1436                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "QDELTA=" + num2str(QDelta) + ";"
1437        Endif
1438End
1439
1440
1441//prompts the user to pick a previously created protocol from a popup list
1442//of given the option to create a new protocol
1443//the chosen protocol is passed back to the calling procedure by a global string
1444//the popup is presented as a missing parameter dialog (called with empty parameter list)
1445//
1446// MAXROWS is present to exclude the PanelNameW from appearing as a protocol
1447Proc V_PickAProtocol(protocol)
1448        String Protocol
1449        Prompt Protocol "Pick A Protocol",popup, V_RecallableProtocols()
1450       
1451        String/G  root:Packages:NIST:VSANS:Globals:Protocols:gProtoStr = protocol
1452End
1453
1454Proc V_DeleteAProtocol(protocol)
1455        String Protocol
1456//      Prompt Protocol "Delete A Protocol",popup, WaveList("*",";","TEXT:1")
1457        Prompt Protocol "Delete A Protocol",popup, V_DeletableProtocols()
1458
1459        String/G  root:Packages:NIST:VSANS:Globals:Protocols:gProtoStr = protocol
1460End
1461
1462Function/S V_DeletableProtocols()
1463        String list=WaveList("*",";","TEXT:1,MAXROWS:13")
1464
1465        list= RemoveFromList("Base", list  , ";")
1466        list= RemoveFromList("DoAll", list  , ";")
1467        list= RemoveFromList("CreateNew", list  , ";")
1468        list= RemoveFromList("tempProtocol", list  , ";")
1469        list= RemoveFromList("wTTmpWrite", list  , ";")
1470        if(cmpstr(list,"")==0)
1471                list = "_no_protocols_;"
1472        endif
1473       
1474        return(list)
1475End
1476
1477Function/S V_RecallableProtocols()
1478        String list=WaveList("*",";","TEXT:1,MAXROWS:13")
1479
1480//      list= RemoveFromList("Base", list  , ";")
1481//      list= RemoveFromList("DoAll", list  , ";")
1482        list= RemoveFromList("CreateNew", list  , ";")
1483        list= RemoveFromList("tempProtocol", list  , ";")
1484        list= RemoveFromList("wTTmpWrite", list  , ";")
1485        if(cmpstr(list,"")==0)
1486                list = "_no_protocols_;"
1487        endif
1488       
1489        return(list)
1490End
1491
1492
1493//missing parameter dialog to solicit user for a waveStr for the protocol
1494//about to be created
1495//name is passed back as a global string and calling procedure is responsible for
1496//checking for wave conflicts and valid names
1497//
1498Proc V_AskForName(protocol)
1499        String Protocol
1500        Prompt Protocol "Enter a new name for your protocol (no extension)"
1501       
1502        String/G  root:Packages:NIST:VSANS:Globals:Protocols:gNewStr = protocol
1503End
1504
1505//this is a lengthy procedure for sequentially polling the user about what data
1506//reduction steps they want to be performed during the protocol
1507//ensures that a valid protocol name was chosen, then fills out each "item"
1508//(6 total) needed for reduction
1509//it the user cancels at any point, the partial protocol will be deleted
1510//
1511Function V_ProtocolQuestionnaire(ctrlName)
1512        String ctrlName
1513
1514        String filename,cmd
1515        Variable notDone,refnum
1516       
1517        //prompt for name of new protocol wave to save
1518        do
1519                Execute "V_AskForName()"
1520                SVAR newProtoStr = root:Packages:NIST:VSANS:Globals:Protocols:gNewStr
1521               
1522                //make sure it's a valid IGOR name
1523                newProtoStr = CleanupName(newProtoStr,0)        //strict naming convention
1524                String/G root:Packages:NIST:VSANS:Globals:Protocols:gNewStr=newProtoStr         //reassign, if changed
1525                //Print "newProtoStr = ",newProtoStr
1526               
1527                SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
1528                if(WaveExists( $("root:Packages:NIST:VSANS:Globals:Protocols:" + newProtoStr) ) == 1)
1529                        //wave already exists
1530                        DoAlert 0,"that name is already in use. Please pick a new name"
1531                        notDone = 1
1532                else
1533                        //name is  good
1534                        notDone = 0
1535                Endif
1536        while(notDone)
1537       
1538        //Print "protocol questionnaire is "+newProtocol
1539       
1540        //make a new text wave (12 points) and fill it in, in response to questions
1541        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols //(redundant - full wave specs are used)
1542        Make/O/T/N=(kNumProtocolSteps) $("root:Packages:NIST:VSANS:Globals:Protocols:" + newProtoStr)
1543        Wave/T newProtocol = $("root:Packages:NIST:VSANS:Globals:Protocols:" + newProtoStr)
1544        newProtocol = ""
1545       
1546        //ask the questions
1547        /////
1548        //*****Multiple files in these lists are full paths/filenames which may or may not
1549        //have semicolon version numbers in the filename. Therefore, construct the list with
1550        //COMMAS as separators - to avoid messy parsing
1551        ///////
1552       
1553        String fileFilters = "VSANS Data Files (*.ngv,*.h5):.ngv,.h5;"
1554//      fileFilters += "HTML Files (*.htm,*.html):.htm,.html;"
1555        fileFilters += "All Files:.*;"
1556//////////////////////////
1557        String drkStr="",fileStr=""
1558       
1559       
1560//////////////////////////     
1561//      DoAlert 1,"Do you want to correct your data for DRK (beam off) counts?"
1562//      if(V_flag == 1)         //1=yes
1563//              //prompt for DRK  file, but don't actually open it (/D flag)
1564//              Open/D/R/F=fileFilters/M="Select the DRK file"/P=catPathName refnum
1565//              //check for cancel
1566//              if(strlen(S_filename)==0)
1567//                      //user cancelled, abort
1568//                      KillWaves/Z newProtocol
1569//                      SetDataFolder root:
1570//                      Abort "Incomplete protocol has been deleted"
1571//              Endif
1572//              //assign filename (just the name) to [6]
1573//              fileStr = V_GetFileNameFromPathNoSemi(S_filename)
1574//              drkStr = "DRK=none,DRKMODE=0,"
1575//              drkStr = ReplaceStringByKey("DRK",drkStr,fileStr,"=",",")
1576//              drkStr = ReplaceNumberByKey("DRKMODE", drkStr, 10 ,"=",",")     
1577//              newProtocol[6] = drkStr
1578//      else
1579//              //no Work.DRK desired
1580//              newProtocol[6] = "DRK=none,DRKMODE=0,"
1581//      Endif
1582//     
1583////////////
1584       
1585       
1586// TODO:
1587// -- there is a lag in the V_pick() routine as it greps through all of the files. Several seconds even when there
1588//   are 20-ish files. Pre-search for the strings? When to refresh them for new data?   
1589/////////////////
1590        DoAlert 1,"Do you want to subtract background from your data?"
1591        if(V_flag == 1)         //1=yes
1592               
1593                Prompt filename,"BKG File",popup,V_PickBGDButton("")
1594                DoPrompt "Select File",filename
1595                if (V_Flag)
1596                        return 0                                                                        // user canceled
1597                endif
1598//              //assign filename to [0]
1599                newProtocol[0] = V_GetFileNameFromPathNoSemi(fileName)
1600       
1601               
1602// OLD way, using an open file dialog   
1603// and allowing for multiple files to be added together
1604//     
1605//              //prompt for background file, but don't actually open it (/D flag)
1606//              Open/D/R/F=fileFilters/M="Select the Background data file"/P=catPathName refnum
1607//              //check for cancel
1608//              if(strlen(S_filename)==0)
1609//                      //user cancelled, abort
1610//                      KillWaves/Z newProtocol
1611//                      SetDataFolder root:
1612//                      Abort "Incomplete protocol has been deleted"
1613//              Endif
1614//              //assign filename (full path) to [0]
1615//              newProtocol[0] = V_GetFileNameFromPathNoSemi(S_filename)
1616               
1617//              notDone=1
1618//              do
1619//                      //prompt for additional background files
1620//                      DoAlert 1,"Do you want to add another background file?"
1621//                      if(V_flag == 1)         //yes
1622//                              Open/D/R/F=fileFilters/M="Select another Background data file"/P=catPathName refnum
1623//                              //check for cancel
1624//                              if(strlen(S_filename)==0)
1625//                                      //user cancelled, abort ********maybe just break out of the loop here
1626//                                      KillWaves/Z newProtocol
1627//                                      SetDataFolder root:
1628//                                      Abort "Incomplete protocol has been deleted"
1629//                              Endif
1630//                              //assign filename (full path) to [0]
1631//                              newProtocol[0] += "," + V_GetFileNameFromPathNoSemi(S_filename)         //***COMMA separated list
1632//                              notDone = 1             //keep going
1633//                      else
1634//                              notDone = 0                     //no more to add
1635//                      Endif
1636//              While(notDone)
1637//////
1638
1639        else            //no background desired
1640                newProtocol[0] = "none"
1641        Endif
1642       
1643       
1644////////////////////// 
1645        DoAlert 1,"Do you want to subtract empty cell scattering from your data?"
1646        if(V_flag == 1)         //1=yes
1647               
1648                Prompt filename,"EMP File",popup,V_PickEMPButton("")
1649                DoPrompt "Select File",filename
1650                if (V_Flag)
1651                        return 0                                                                        // user canceled
1652                endif
1653//              //assign filename to [1]
1654                newProtocol[1] = V_GetFileNameFromPathNoSemi(fileName)         
1655       
1656
1657               
1658//              //prompt for Empty cell file, but don't actually open it (/D flag)
1659//              Open/D/R/F=fileFilters/M="Select the Empty Cell data file"/P=catPathName refnum
1660//              //check for cancel
1661//              if(strlen(S_filename)==0)
1662//                      //user cancelled, abort
1663//                      KillWaves/Z newProtocol
1664//                      SetDataFolder root:
1665//                      Abort "Incomplete protocol has been deleted"
1666//              Endif
1667//              //assign filename (full path) to [1]
1668//              newProtocol[1] = V_GetFileNameFromPathNoSemi(S_filename)
1669//             
1670//              notDone=1
1671//              do
1672//                      //prompt for additional Empty Cell files
1673//                      DoAlert 1,"Do you want to add another Empty Cell file?"
1674//                      if(V_flag == 1)         //yes
1675//                              Open/D/R/F=fileFilters/M="Select another Empty Cell data file"/P=catPathName refnum
1676//                              //check for cancel
1677//                              if(strlen(S_filename)==0)
1678//                                      //user cancelled, abort ********maybe just break out of the loop here
1679//                                      KillWaves/Z newProtocol
1680//                                      SetDataFolder root:
1681//                                      Abort "Incomplete protocol has been deleted"
1682//                              Endif
1683//                              //assign filename (full path) to [1]
1684//                              newProtocol[1] += "," + V_GetFileNameFromPathNoSemi(S_filename)         //***COMMA separated list
1685//                              notDone = 1             //keep going
1686//                      else
1687//                              notDone = 0                     //no more to add
1688//                      Endif
1689//              While(notDone)
1690
1691
1692        else            //no background desired
1693                newProtocol[1] = "none"
1694        Endif
1695       
1696       
1697//////////////////////////
1698        DoAlert 1,"Do you want to correct your data for detector sensitivity?"
1699       
1700        if(V_flag == 1)         //1=yes
1701               
1702                Prompt filename,"DIV File",popup,V_GetDIVList()
1703                DoPrompt "Select File",filename
1704                if (V_Flag)
1705                        return 0                                                                        // user canceled
1706                endif
1707//              //assign filename to [2]
1708                newProtocol[2] = V_GetFileNameFromPathNoSemi(fileName)
1709               
1710//              //prompt for DIV  file, but don't actually open it (/D flag)
1711//              Open/D/R/F=fileFilters/M="Select the detector sensitivity file"/P=catPathName refnum
1712//              //check for cancel
1713//              if(strlen(S_filename)==0)
1714//                      //user cancelled, abort
1715//                      KillWaves/Z newProtocol
1716//                      SetDataFolder root:
1717//                      Abort "Incomplete protocol has been deleted"
1718//              Endif
1719//              //assign filename (full path) to [2]
1720//              newProtocol[2] = V_GetFileNameFromPathNoSemi(S_filename)
1721               
1722               
1723        else
1724                //no Work.DIV desired
1725                newProtocol[2] = "none"
1726        Endif   
1727//////////////////////////
1728        DoAlert 1,"Do you want to mask your files before averaging?"
1729       
1730        if(V_flag == 1)         //1=yes
1731       
1732                Prompt filename,"MASK File",popup,V_PickMASKButton("")
1733                DoPrompt "Select File",filename
1734                if (V_Flag)
1735                        return 0                                                                        // user canceled
1736                endif
1737//              //assign filename to [3]
1738                newProtocol[3] = V_GetFileNameFromPathNoSemi(fileName)
1739                       
1740//              //prompt for mask  file, but don't actually open it (/D flag)
1741//              Open/D/R/F=fileFilters/M="Select the mask file"/P=catPathName refnum
1742//              //check for cancel
1743//              if(strlen(S_filename)==0)
1744//                      //user cancelled, abort
1745//                      KillWaves/Z newProtocol
1746//                      SetDataFolder root:
1747//                      Abort "Incomplete protocol has been deleted"
1748//              Endif
1749//              //assign filename (full path) to [3]
1750//              newProtocol[3] = V_GetFileNameFromPathNoSemi(S_filename)
1751               
1752               
1753        else
1754                //no MASK desired
1755                newProtocol[3] = "none"
1756        Endif   
1757       
1758        //absolute scaling
1759       
1760        //////////////////////////
1761        //ABS parameters stored as keyword=value string
1762        DoAlert 1,"Do you want absolute scaling?"
1763        if(V_flag == 1)         //1=yes
1764                //missing param - prompt for values, put in semicolon-separated list
1765                Execute "V_AskForAbsoluteParams_Quest()"
1766                SVAR absStr =  root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr
1767                newProtocol[4] = absStr
1768        else
1769                //no absolute scaling desired
1770                newProtocol[4] = "none"
1771        Endif   
1772       
1773        //type of average, plot?, auto/manual naming/saving... put in semicolon separated string
1774        //of KEY=<value> format for easy parsing
1775        //Kewords are: AVTYPE,PHI,DPHI,PLOT,SAVE,NAME,SIDE,WIDTH
1776        //note that AVTYPE,NAME,SIDE have string values, others have numerical values
1777        ///////////////////////
1778        DoAlert 1,"Do you want to average your data to I vs. q?"
1779        if(V_flag == 1)         //1=yes
1780                String/G root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr = ""
1781                Execute "V_GetAvgInfo()"                //will put up missing paramter dialog and do all the work
1782                //:gAvgInfo is reset by the Proc(), copy this string tot he protocol
1783                SVAR tempStr=root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr
1784               
1785                //get a file path for saving files, if desired
1786                /////no - save files to the same data folder as the one with the raw data
1787                //then only one path to manage.
1788                //String yesNo = StringByKey("SAVE", tempStr,"=", ";")
1789                //if(cmpstr("Yes",yesNo) == 0)          //0=yes
1790                        //NewPath/C/M="Select Folder"/O Save_path               //Save_path is the symbolic path
1791                //Endif
1792
1793                newProtocol[5] = tempStr
1794                KillStrings/Z tempStr
1795        else
1796                //no averaging desired
1797                newProtocol[5] = "AVTYPE=none"
1798        Endif
1799       
1800        //returns the name of the newly created (= currently in use) protocol wave through a global
1801        String/G root:Packages:NIST:VSANS:Globals:Protocols:gProtoStr = newProtoStr
1802       
1803        //reset the panel based on the protocol textwave (currently a string)
1804        V_ResetToSavedProtocol(newProtoStr)
1805       
1806        SetDataFolder root:
1807       
1808        return(0)
1809End
1810
1811
1812// TODO
1813// -- this function may not work properly for VSANS, but I haven't tested it yet
1814// -- I'd rather have some sort of display to show the current content of the WORK folders
1815//
1816// -- the global string fileList does not exist, so this will always fail and return zero
1817//
1818//
1819//function to check the work files (to see what's already there)
1820//and compare that with the files that are supposed to be there, according to the
1821//current protocol (to save unnecessary time re-loading files)
1822//
1823//the "type" folder is checked for all files in the list req(ested)Files
1824//note that the list of files is a full path:name;ver, while the
1825//fileList in the folder is just the name (or a list of names)
1826//
1827//returns 0 false, if files are NOT present
1828//or 1 = true, yes, the files are there as requested
1829//
1830Function V_AreFilesThere(type,reqFiles)
1831        String type,reqFiles
1832       
1833        //in general, reqFiles is a list of full paths to files - which MAY include semicolon version numbers
1834        //reqFiles MUST be constructed with COMMAS as list separators, to avoid disaster
1835        //when the version numbers are interpreted as filenames
1836       
1837        //get the number of files requested
1838        Variable nReq,nCur,match,ii
1839        nReq = ItemsInList(reqFiles,",")
1840       
1841        //get the name of the file currently in BGD - in the global fileList
1842        //fileList has NAMES ONLY - since it was derived from the file header
1843        String testStr
1844        testStr = "root:Packages:NIST:"+type+":fileList"
1845        if(Exists(testStr) == 2)                //2 if string variable exists
1846                SVAR curFiles = $testStr
1847        else
1848                //no files currently in type folder, return zero
1849                Return (0)
1850        Endif
1851        //get the number of files already in folder
1852        nCur = ItemsInList(curFiles,";")
1853        If(nCur != nReq)
1854                Return (0)              //quit now, the wrong number of files present
1855        Endif
1856        //right number of files... are the names right...
1857        //check for a match (case-sensitive!!) of each requested file in the curFile string
1858        //need to extract filenames from reqFiles, since they're the full path and name
1859       
1860        ii=0
1861        do
1862                testStr = StringFromList(ii,reqFiles,",")       //testStr is the Nth full path and filename
1863                //testStr = GetFileNameFromPathNoSemi(testStr)  //testStr will now be just the filename
1864                match = stringmatch(curFiles,testStr)
1865                If(!match)
1866                        Return (0)              //req file was not found in curFile list - get out now
1867                Endif
1868                ii+=1
1869        while(ii<nreq)
1870       
1871        Return (1)              //indicate that files are OK, no changes needed
1872End
1873
1874
1875//
1876//will add the files specified in the protocol to the "type" folder
1877//will add multiple files together if more than one file is requested
1878//(list is a comma delimited list of filenames, with NO path information)
1879//
1880// This routine NOW DOES check for the possibility that the filenames may have ";vers" from the
1881// VAX - data should be picked up from Charlotte, where it won't have version numbers.
1882//
1883Function V_AddFilesInList(type,list)
1884        String type,list
1885       
1886        //type is the work folder to put the data into, and list is a COMMA delimited list of paths/names
1887        Variable num,ii,err=0,refNum
1888        String filename,pathStr=""
1889        PathInfo catPathName                    //this is where the files are
1890        pathstr=S_path
1891       
1892        num = ItemsInList(list,",")             // comma delimited list
1893       
1894        ii=0
1895        do
1896                //FindValidFilename only needed in case of vax version numbers
1897                filename = pathStr + V_FindValidFilename(StringFromList(ii,list,","))
1898                Open/Z/R refnum as filename
1899                if(V_flag != 0)         //file not found
1900                        //Print "file not found AddFilesInList()"
1901                        //Print filename
1902                        err = 1
1903                        return(err)
1904                Endif
1905                Close refnum            //file was found and opened, so close it
1906               
1907//              Abort "Find equivalent to ReadHeaderAndData(filename)"
1908//              ReadHeaderAndData(filename)
1909                err = V_LoadHDF5Data(filename,"RAW")   
1910               
1911                if(ii == 0)
1912                        //first pass, wipe out the old contents of the work file
1913                        err =  V_Raw_to_work(type)
1914                else
1915                        err = V_Add_raw_to_work(type)
1916                Endif
1917                ii+=1
1918        while(ii<num)
1919        return(err)
1920End
1921
1922//function will reduce a sample file (or ask for file(s))
1923//using the protocol named as "protoStr" in the Protocols subfolder
1924//samStr is the file(s) or "ask" to force prompt
1925//sequentially proceeds through flowchart, doing reduction steps as needed
1926//show Schematic to debug what steps/values were used
1927//
1928//function is long, but straightforward logic
1929//
1930Function V_ExecuteProtocol(protStr,samStr)
1931        String protStr,samStr
1932        //protStr is the full path to the selected protocol wave
1933        //samStr is either "ask" or the name ONLY ofthe desired sample data file(s) (NO PATH)
1934        WAVE/T prot = $protStr
1935        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
1936       
1937        Variable filesOK,err,notDone
1938        String activeType, msgStr, junkStr, pathStr=""
1939        PathInfo catPathName                    //this is where the files are
1940        pathStr=S_path
1941       
1942//      NVAR useXMLOutput = root:Packages:NIST:gXML_Write
1943       
1944        //Parse the instructions in the prot wave
1945        //0 - bkg
1946        //1 - emp
1947        //2 - div
1948        //3 - mask
1949        //4 - abs params c2-c5
1950        //5 - average params
1951        //6 = DRK file (**out of sequence)
1952        //7 = beginning trim points
1953        //8 = end trim points
1954        //9 = collimation type for reduced data
1955        //10 = unused
1956        //11 = unused
1957
1958//////////////////////////////
1959// DIV
1960//////////////////////////////
1961// for VSANS, DIV is used on each data file as it is converted to WORK, so it needs to be
1962//  the first thing in place, before any data or backgrounds are loaded
1963
1964        //check for work.div file (prot[2])
1965        //load in if needed
1966        // no math is done here, DIV is applied as files are converted to WORK (the first operation in VSANS)
1967        //
1968
1969        // save the state of the DIV preference
1970        NVAR gDoDIVCor = root:Packages:NIST:VSANS:Globals:gDoDIVCor
1971        Variable saved_gDoDIVCor = gDoDIVCor
1972       
1973        err = V_Proto_LoadDIV(prot[2])
1974       
1975        if(err)
1976                SetDataFolder root:
1977                Abort "No file selected, data reduction aborted"
1978        endif
1979
1980//////////////////////////////
1981// SAM
1982//////////////////////////////
1983
1984// TODO:
1985// -- currently does not allow adding RAW data files together, so no parsing is done
1986//       -- NOTE detector corrections (including DIV) are done at the V_Raw_to_Work() step
1987//   So if the DIV is not part of the protocol, be sure to set/reset the global preference
1988//
1989        //prompt for sam data => read raw data, add to sam folder
1990        //or parse file(s) from the input paramter string
1991        activeType = "SAM"
1992        msgStr = "Select sample data"
1993       
1994        err = V_Proto_LoadFile(samStr,activeType,msgStr)
1995        if(err)
1996                PathInfo/S catPathName
1997                SetDataFolder root:
1998                Abort "No file selected, data reduction aborted"
1999        endif
2000       
2001        // TODO
2002        // -- this may not be the most reliable way to pass the file name (for naming of the saved file later)
2003        SVAR file_name = root:file_Name
2004        String samFileLoaded = file_name                //keep a copy of the sample file loaded
2005       
2006        //always update
2007        V_UpdateDisplayInformation(ActiveType)
2008
2009
2010// TODO -- the logic here is flawed
2011// check that the SAM file is of the same configuration as BGD or EMP, if they are used
2012// need to be able to handle all of the permutations AND catch the "ask" cases
2013       
2014        Variable filesMatch=1           //assume OK
2015       
2016        if(cmpstr("none",prot[0])==0 || cmpstr("ask",prot[0])==0)
2017                // BGD not identified, try EMP.
2018                if(cmpstr("none",prot[1])==0 || cmpstr("ask",prot[1])==0)
2019                        // EMP not identified either, no mismatch possible
2020                else
2021                        // compare to EMP
2022                        filesMatch = V_RawFilesMatchConfig(samFileLoaded,StringFromList(0,prot[1],","))
2023                endif
2024        else
2025                // BGD is identified, compare
2026                filesMatch = V_RawFilesMatchConfig(samFileLoaded,StringFromList(0,prot[0],","))
2027        endif
2028
2029        if(filesMatch == 0)
2030                Abort "SAM data is not the same configuration as the protocol."
2031                SetDataFolder root:
2032        endif           
2033
2034
2035
2036//////////////////////////////
2037// BGD
2038//////////////////////////////
2039       
2040        //check for BGD file  -- "ask" might not fail - "ask?" will - ? not allowed in VAX filenames
2041        // add if needed
2042        //use a "case" statement
2043        msgStr = "Select background file"
2044        activeType = "BGD"
2045       
2046        err = V_Proto_LoadFile(prot[0],activeType,msgStr)
2047        if(err)
2048                PathInfo/S catPathName
2049                SetDataFolder root:
2050                Abort "No file selected, data reduction aborted"
2051        endif
2052
2053//      //Loader is in charge of updating, since it knows if data was loaded
2054//      V_UpdateDisplayInformation(ActiveType)
2055
2056
2057//////////////////////////////
2058// EMP
2059////////////////////////////// 
2060       
2061        //check for emp file (prot[1])
2062        // add if needed
2063        msgStr = "Select empty cell data"
2064        activeType = "EMP"
2065       
2066        err = V_Proto_LoadFile(prot[1],activeType,msgStr)
2067        if(err)
2068                PathInfo/S catPathName
2069                SetDataFolder root:
2070                Abort "No file selected, data reduction aborted"
2071        endif
2072
2073//      //Loader is in charge of updating, since it knows if data was loaded
2074//      V_UpdateDisplayInformation(ActiveType)
2075
2076
2077//////////////////////////////
2078// CORRECT
2079//////////////////////////////
2080
2081        //do the CORRECT step based on the answers to emp and bkg subtraction
2082        //by setting the proper"mode"
2083        //1 = both emp and bgd subtraction
2084        //2 = only bgd subtraction
2085        //3 = only emp subtraction
2086        //4 = no subtraction
2087        //additional modes 091301
2088        //11 = emp, bgd, drk
2089        //12 = bgd and drk
2090        //13 = emp and drk
2091        //14 = no subtractions
2092        //work.drk is from proto[6]
2093        //
2094        //subtracting just the DRK data is NOT an option - it doesnt' really make any physical sense
2095        // - in this case, DRK is skipped (equivalent to mode==4)
2096        // automatically accounts for attenuators given the lookup tables and the
2097        //desired subtractions
2098        //Attenuator lookup tables are alredy implemented (NG1 = NG7)
2099        //
2100
2101
2102/////// DRK is SKIPPED
2103       
2104//      //read in the DRK data if necessary
2105//      //only one file, assumed to be RAW data
2106//      //
2107//      String fname="",drkStr=""
2108//      drkStr=StringByKey("DRK",prot[6],"=",",")
2109//      if(cmpstr(drkStr,"none") != 0)
2110//              err = ReadHeaderAndData( (pathStr+drkStr) )
2111//              if(err)
2112//                      PathInfo/S catPathName
2113//                      Abort "reduction sequence aborted"
2114//              endif
2115//              err = V_Raw_to_Work_NoNorm("DRK")
2116//      endif
2117
2118        //dispatch to the proper "mode" of Correct()
2119//      V_Dispatch_to_Correct(bgdStr,empStr,drkStr)
2120        V_Dispatch_to_Correct(prot[0],prot[1],prot[6])
2121       
2122        if(err)
2123                PathInfo/S catPathName
2124                SetDataFolder root:
2125                Abort "error in Correct, called from executeprotocol, normal cor"
2126        endif
2127        activeType = "COR"
2128
2129// always update - COR will always be generated
2130        V_UpdateDisplayInformation(ActiveType)         
2131
2132
2133//////////////////////////////
2134//  ABSOLUTE SCALE
2135//////////////////////////////
2136
2137        err = V_Proto_ABS_Scale(prot[4],activeType)             //activeType is pass-by-reference and updated IF ABS is used
2138       
2139        if(err)
2140                SetDataFolder root:
2141                Abort "Error in V_Absolute_Scale(), called from V_ExecuteProtocol"
2142        endif
2143//      activeType = "ABS"
2144
2145
2146//////////////////////////////
2147// MASK
2148//////////////////////////////
2149//
2150// DONE
2151//              x- fill in the "ask" step
2152//  x- none is OK, except if the kill fails for any reason
2153// x- the regular case of the file name specified by the protocol works correctly
2154// x- don't create a null mask if not used, it will handle the error and print out that the mask is missing
2155//
2156//mask data if desired (mask is applied when the data is binned to I(q)) and is
2157//not done explicitly here
2158       
2159        //check for mask
2160        //doesn't change the activeType
2161        V_Proto_ReadMask(prot[3])
2162
2163       
2164//////////////////////////////
2165// AVERAGING
2166//////////////////////////////
2167
2168        // average/save data as specified
2169        //Parse the keyword=<Value> string as needed, based on AVTYPE
2170       
2171        //average/plot first
2172        String av_type = StringByKey("AVTYPE",prot[5],"=",";")
2173        If(cmpstr(av_type,"none") != 0)
2174                If (cmpstr(av_type,"")==0)              //if the key could not be found... (if "ask" the string)
2175                        //get the averaging parameters from the user, as if the set button was hit in the panel
2176                        V_SetAverageParamsButtonProc("dummy")           //from "ProtocolAsPanel"
2177                        SVAR tempAveStr = root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr
2178                        av_type = StringByKey("AVTYPE",tempAveStr,"=",";")
2179                else
2180                        //there is info in the string, use the protocol
2181                        //set the global keyword-string to prot[5]
2182                        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr = prot[5]
2183                Endif
2184        Endif
2185
2186
2187        String detGroup = StringByKey("DETGROUP",prot[5],"=",";")               //only for annular, null if not present
2188
2189       
2190//convert the folder to linear scale before averaging, then revert by calling the window hook
2191// (not needed for VSANS, data is always linear scale)
2192
2193//
2194// (DONE)
2195// -x this generates a "Bin Type Not Found" error if reducing only to a 2D level (like for DIV)
2196//              because binTypeStr is null
2197        String binTypeStr = StringByKey("BINTYPE",prot[5],"=",";")
2198        // plotting is not really necessary, and the graph may not be open - so skip for now?
2199        Variable binType
2200        // only get the binning type if user asks for averaging
2201        If(cmpstr(av_type,"none") != 0)
2202                binType = V_BinTypeStr2Num(binTypeStr)
2203                if(binType == 0)
2204                                Abort "Binning mode not found in V_QBinAllPanels() "// when no case matches
2205                endif
2206        endif
2207
2208
2209// identify the collimation type
2210// this will be a string used to determine how the resolution information is to be calculated
2211// and written to the reduced data file
2212//
2213// possible values are:
2214//
2215// pinhole
2216// pinhole_whiteBeam
2217// narrowSlit
2218// narrowSlit_whiteBeam
2219// convergingPinholes
2220//
2221
2222        String collimationStr
2223        collimationStr = V_IdentifyCollimation(activeType)
2224       
2225
2226////////////////////////////////////////
2227// DISPATCH TO AVERAGING
2228/////////////////////////////////////////
2229//
2230// TODO:
2231// -- do I calculate the proper resolution here?, YES, I've already decoded the binning type
2232//   and the averaging type has been specified by the protocol.
2233//
2234// so currently, the resolution is calculated every time that the data is averaged (in VC_fDoBinning_QxQy2D)
2235//
2236// -- if I calculate the resolution here, then the Trimming routines must be updated
2237//    to trim the resolution waves also. This will work for the columns present in
2238//    pinhole resolution, but anything using the matrix method - it won't work - and I'll need
2239//    a different solution
2240//
2241
2242        V_Proto_doAverage(prot[5],av_type,activeType,binType,collimationStr)
2243
2244
2245
2246////////////////////////
2247// PLOT THE DATA
2248////////////////////////
2249
2250        V_Proto_doPlot(prot[5],av_type,activeType,binType,detGroup)
2251       
2252       
2253
2254////////////////////   
2255// SAVE THE DATA
2256////////////////////
2257
2258//
2259// x- how do I get the sample file name?
2260//    local variable samFileLoaded is the file name loaded (contains the extension)
2261//
2262// V_Proto_SaveFile(avgStr,activeType,samFileLoaded,av_type,binType,detGroup,trimBegStr,trimEndStr)
2263
2264        prot[9] = collimationStr
2265
2266        V_Proto_SaveFile(prot[5],activeType,samFileLoaded,av_type,binType,detGroup,prot[7],prot[8])
2267       
2268//////////////////////////////
2269// DONE WITH THE PROTOCOL
2270////////////////////////////// 
2271       
2272        // reset any global preferences that I had changed
2273        gDoDIVCor = saved_gDoDIVCor
2274       
2275       
2276        Return(0)
2277End
2278
2279
2280
2281
2282
2283//missing parameter dialog to solicit the 4 absolute intensity parameters
2284//from the user
2285//values are passed back as a global string variable (keyword=value)
2286//
2287Proc V_AskForAbsoluteParams(c2,c3,c4,c5,I_err,back_values)
2288        Variable c2=1,c3=1,c4=1e8,c5=1,I_err=1
2289        String back_values="no"
2290        Prompt c2, "Standard Transmission"
2291        Prompt c3, "Standard Thickness (cm)"
2292        Prompt c4, "I(0) from standard fit (normalized to 1E8 monitor cts)"
2293        Prompt c5, "Standard Cross-Section (cm-1)"
2294        Prompt I_err, "error in I(q=0) (one std dev)"
2295        prompt back_values, "are these values for the back detector (yes/no)?"
2296       
2297        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2298       
2299        if(cmpstr(back_values,"no")==0)
2300                gAbsStr = ReplaceStringByKey("TSTAND",gAbsStr,num2str(c2),"=",";")
2301                gAbsStr = ReplaceStringByKey("DSTAND",gAbsStr,num2str(c3),"=",";")
2302                gAbsStr = ReplaceStringByKey("IZERO",gAbsStr,num2str(c4),"=",";")
2303                gAbsStr = ReplaceStringByKey("XSECT",gAbsStr,num2str(c5),"=",";")
2304                gAbsStr = ReplaceStringByKey("SDEV",gAbsStr,num2str(I_err),"=",";")
2305        else
2306                gAbsStr = ReplaceStringByKey("TSTAND_B",gAbsStr,num2str(c2),"=",";")
2307                gAbsStr = ReplaceStringByKey("DSTAND_B",gAbsStr,num2str(c3),"=",";")
2308                gAbsStr = ReplaceStringByKey("IZERO_B",gAbsStr,num2str(c4),"=",";")
2309                gAbsStr = ReplaceStringByKey("XSECT_B",gAbsStr,num2str(c5),"=",";")
2310                gAbsStr = ReplaceStringByKey("SDEV_B",gAbsStr,num2str(I_err),"=",";")
2311        endif
2312       
2313
2314        SetDataFolder root:
2315End
2316
2317
2318//
2319// DONE
2320// x- fill in all of the functionality for calculation from direct beam
2321//  and verify that the calculations are numerically correct
2322//
2323//asks the user for absolute scaling information. the user can either
2324//enter the necessary values in manually (missing parameter dialog)
2325//or the user can select an empty beam file from a standard open dialog
2326//if an empty beam file is selected, the "kappa" value is automatically calculated
2327//in either case, the global keyword=value string is set.
2328//
2329//
2330// if isBack == 1, then the values are for the back panel
2331// AND there are different steps that must be done to subtract off
2332//  the read noise of the CCDs
2333//
2334Function V_AskForAbsoluteParams_Quest(isBack)   
2335        Variable isBack
2336       
2337        Variable err,loc,refnum
2338       
2339        Variable ii
2340       
2341        Variable kappa=1
2342        Variable kappa_err
2343               
2344        //get the necessary variables for the calculation of kappa
2345        Variable countTime,monCnt,sdd,pixel_x,pixel_y
2346        String detStr,junkStr,errStr
2347
2348        Variable empAttenFactor,        emp_atten_err
2349       
2350        //get the XY box and files
2351        Variable x1,x2,y1,y2,emptyCts,empty_ct_err
2352        String emptyFileName,tempStr,divFileName,detPanel_toSum
2353               
2354        //ask user if he wants to use a transmision file for absolute scaling
2355        //or if he wants to enter his own information
2356        err = V_UseStdOrEmpForABS()
2357        //DoAlert 1,"<Yes> to enter your own values, <No> to select an empty beam flux file"
2358        If ( err==1 )
2359                //secondary standard selected, prompt for values
2360                Execute "V_AskForAbsoluteParams()"              //missing parameters
2361        else
2362                //empty beam flux file selected, prompt for file, and use this to calculate KAPPA
2363
2364                // DONE
2365                // x- need an empty beam file name
2366                //
2367                Prompt emptyFileName,"Empty Beam File",popup,V_PickEMPBeamButton("")
2368                DoPrompt "Select File",emptyFileName
2369                if (V_Flag)
2370                        return 0                                                                        // user canceled
2371                endif
2372
2373                // DONE
2374                // x- need panel
2375                // x- now, look for the value in the file, if not there, ask
2376               
2377                detPanel_toSum = V_getReduction_BoxPanel(emptyFileName)
2378                if(strlen(detPanel_toSum) > 2)
2379                        // it's the error message
2380                        Prompt detPanel_toSum,"Panel with Direct Beam",popup,ksDetectorListAll
2381                        DoPrompt "Select Panel",detPanel_toSum
2382                        if (V_Flag)
2383                                return 0                                                                        // user canceled
2384                        endif
2385                endif
2386               
2387                //need the detector sensitivity file - make a guess, allow to override
2388                Prompt divFileName,"DIV File",popup,V_GetDIVList()
2389                DoPrompt "Select File",divFileName
2390                if (V_Flag)
2391                        return 0                                                                        // user canceled
2392                endif
2393                V_LoadHDF5Data(divFileName,"DIV")
2394
2395
2396                WAVE xyBoxW = V_getBoxCoordinates(emptyFileName)
2397
2398               
2399                // load in the data, and use all of the corrections, especially DIV
2400                // (be sure the corrections are actually set to "on", don't assume that they are)
2401                // save preferences for file loading
2402                Variable savDivPref,savSAPref
2403                NVAR gDoDIVCor = root:Packages:NIST:VSANS:Globals:gDoDIVCor
2404                savDivPref = gDoDIVCor
2405                NVAR gDoSolidAngleCor = root:Packages:NIST:VSANS:Globals:gDoSolidAngleCor
2406                savSAPref = gDoSolidAngleCor
2407               
2408                // set local preferences
2409                gDoDIVCor = 1
2410                gDoSolidAngleCor = 1
2411               
2412                V_LoadAndPlotRAW_wName(emptyFileName)
2413
2414                V_UpdateDisplayInformation("RAW")       
2415               
2416                // do the DIV correction
2417                if (gDoDIVCor == 1)
2418                        // need extra check here for file existence
2419                        // if not in DIV folder, load.
2420                        // if unable to load, skip correction and report error (Alert?) (Ask to Load?)
2421                        Print "Doing DIV correction"// for "+ detStr
2422                        for(ii=0;ii<ItemsInList(ksDetectorListAll);ii+=1)
2423                                detStr = StringFromList(ii, ksDetectorListAll, ";")
2424                                Wave w = V_getDetectorDataW("RAW",detStr)
2425                                Wave w_err = V_getDetectorDataErrW("RAW",detStr)
2426                               
2427                                V_DIVCorrection(w,w_err,detStr,"RAW")           // do the correction in-place
2428                        endfor
2429                else
2430                        Print "DIV correction NOT DONE"         // not an error since correction was unchecked
2431                endif
2432               
2433                // and determine box sum and error
2434                // store these locally
2435               
2436
2437                // x- need to get the panel string for the sum.
2438                // x- the detector string is currently hard-wired
2439//              detStr = "MR"
2440
2441
2442                emptyCts = V_SumCountsInBox(xyBoxW[0],xyBoxW[1],xyBoxW[2],xyBoxW[3],empty_ct_err,"RAW",detPanel_toSum)
2443
2444                Print "empty counts = ",emptyCts
2445                Print "empty err/counts = ",empty_ct_err/emptyCts
2446
2447                // if it's the back panel, find the read noise to subtract
2448                // shift the marquee to the right to (hopefully) a blank spot
2449                Variable noiseCts,noiseCtsErr,delta
2450                if(isBack)
2451                        delta = xyBoxW[1] - xyBoxW[0]
2452                        noiseCts = V_SumCountsInBox(xyBoxW[1],xyBoxW[1]+delta,xyBoxW[2],xyBoxW[3],noiseCtsErr,"RAW",detPanel_toSum)
2453
2454                        print "average read noise per pixel = ",noiseCts/(xyBoxW[1]-xyBoxW[0])/(xyBoxW[3]-xyBoxW[2])
2455                        Print "read noise counts = ",noiseCts
2456                        Print "read noise err/counts = ",noiseCtsErr/noiseCts
2457                       
2458                        emptyCts -= noiseCts
2459                        empty_ct_err = sqrt(empty_ct_err^2 + noiseCtsErr^2)
2460                       
2461                        Print "adjusted empty counts = ",emptyCts
2462                        Print "adjusted err/counts = ",empty_ct_err/emptyCts
2463                endif
2464
2465//
2466                // x- get all of the proper values for the calculation
2467                // -x currently the attenuation is incorrect
2468                //   such that kappa_err = 1*kappa
2469                // x- verify the calculation (no solid angle needed??)
2470                               
2471                // get the attenuation factor for the empty beam
2472                //  -- the attenuation is not written by NICE to the file
2473                //  so I need to calculate it myself from the tables
2474                //
2475//              empAttenFactor = V_getAttenuator_transmission(emptyFileName)
2476//              emp_atten_err = V_getAttenuator_trans_err(emptyFileName)
2477                empAttenFactor = V_CalculateAttenuationFactor(emptyFileName)
2478                emp_atten_err = V_CalculateAttenuationError(emptyFileName)
2479                               
2480                countTime = V_getCount_time(emptyFileName)
2481               
2482                // TODO
2483                // -- not sure if this is the correct monitor count to use
2484                monCnt = V_getBeamMonNormData("RAW")
2485               
2486                pixel_x = V_getDet_x_pixel_size("RAW",detPanel_toSum)
2487                pixel_x /= 10           //convert mm to cm, since sdd in cm
2488                pixel_y = V_getDet_y_pixel_size("RAW",detPanel_toSum)
2489                pixel_y /= 10           //convert mm to cm, since sdd in cm
2490                sdd = V_getDet_ActualDistance("RAW",detPanel_toSum)
2491               
2492//              kappa = emptyCts/countTime/empAttenFactor*1.0e8/(monCnt/countTime)*(pixel_x*pixel_y/sdd^2)
2493                kappa = emptyCts/countTime/empAttenFactor*1.0e8/(monCnt/countTime)
2494               
2495               
2496                kappa_err = (empty_ct_err/emptyCts)^2 + (emp_atten_err/empAttenFactor)^2
2497                kappa_err = sqrt(kappa_err) * kappa
2498               
2499                // x- set the parameters in the global string
2500                junkStr = num2str(kappa)
2501                errStr = num2Str(kappa_err)
2502               
2503                String strToExecute=""
2504               
2505                if(isBack)
2506                        sprintf strToExecute, "V_AskForAbsoluteParams(1,1,%g,1,%g,\"%s\")",kappa,kappa_err,"yes"        //no missing parameters, no dialog
2507                else
2508                        sprintf strToExecute, "V_AskForAbsoluteParams(1,1,%g,1,%g,\"%s\")",kappa,kappa_err,"no" //no missing parameters, no dialog
2509                endif
2510//              print strToExecute
2511                Execute strToExecute
2512
2513                Printf "Kappa was successfully calculated as = %g +/- %g (%g %)\r",kappa,kappa_err,(kappa_err/kappa)*100
2514       
2515                // restore preferences on exit
2516                gDoDIVCor = savDivPref
2517                gDoSolidAngleCor = savSAPref
2518
2519        Endif
2520       
2521End
2522
2523Function V_UserSelectBox_Continue(ctrlName) :buttonControl
2524        String ctrlName
2525       
2526        DoWindow/K junkWindow           //kill panel
2527end
2528
2529Function V_SelectABS_XYBox(x1,x2,y1,y2)
2530        Variable &x1,&x2,&y1,&y2
2531       
2532        Variable err=0
2533       
2534        Variable/G root:V_marquee=1             //sets the sneaky bit to automatically update marquee coords
2535        Variable/G root:V_left,root:V_right,root:V_bottom,root:V_top    //must be global for auto-update
2536        DoWindow/F SANS_Data
2537        NewPanel/K=2 /W=(139,341,382,432) as "Select the primary beam"
2538        DoWindow/C junkWindow
2539        AutoPositionWindow/E/M=1/R=SANS_Data
2540       
2541        Drawtext 21,20 ,"Select the primary beam with the"
2542        DrawText 21,40, "marquee and press continue"
2543        Button button0,pos={80,58},size={92,20},title="Continue"
2544        Button button0,proc=V_UserSelectBox_Continue
2545       
2546        PauseForUser junkWindow,SANS_Data
2547       
2548        DoWindow/F SANS_Data
2549
2550        //GetMarquee left,bottom                        //not needed
2551        NVAR V_left=V_left
2552        NVAR V_right=V_right
2553        NVAR V_bottom=V_bottom
2554        NVAR V_top=V_top
2555       
2556        x1 = V_left
2557        x2 = V_right
2558        y1 = V_bottom
2559        y2 = V_top
2560//      Print "new values,before rounding = ",x1,x2,y1,y2
2561
2562// TODO -- replace this call
2563//      KeepSelectionInBounds(x1,x2,y1,y2)
2564        //Print "new values = ",x1,x2,y1,y2
2565       
2566        KillVariables/Z root:V_Marquee,root:V_left,root:V_right,root:V_bottom,root:V_top
2567        if((x1-x2)==0 || (y1-y2)==0)
2568                err=1
2569        endif
2570        return(err)
2571End
2572
2573Function V_UseStdOrEmpForABS()
2574               
2575        NewPanel/K=2 /W=(139,341,402,448) as "Absolute Scaling"
2576        DoWindow/C junkABSWindow
2577        ModifyPanel cbRGB=(57346,65535,49151)
2578        SetDrawLayer UserBack
2579        SetDrawEnv fstyle= 1
2580        DrawText 21,20,"Method of absolute calibration"
2581        Button button0,pos={52,33},size={150,20},proc=V_UserSelectABS_Continue,title="Empty Beam Flux"
2582        Button button1,pos={52,65},size={150,20},proc=V_UserSelectABS_Continue,title="Secondary Standard"
2583       
2584        PauseForUser junkABSWindow
2585        NVAR val = root:Packages:NIST:VSANS:Globals:tmpAbsVal
2586        return(val)
2587End
2588
2589//returns 0 if button0 (empty beam flux)
2590// or 1 if secondary standard
2591Function V_UserSelectABS_Continue(ctrlName) :buttonControl
2592        String ctrlName
2593       
2594        variable val=0
2595        If(cmpstr(ctrlName,"button0")==0)
2596                val=0           
2597        else
2598                val=1
2599        endif
2600//      print "val = ",ctrlName,val
2601        Variable/G root:Packages:NIST:VSANS:Globals:tmpAbsVal = val
2602        DoWindow/K junkABSWindow                //kill panel
2603        return(0)
2604end
2605
2606
2607Function V_TrimDataProtoButton(ctrlName) :buttonControl
2608        String ctrlName
2609       
2610        Execute "V_CombineDataGraph()"
2611        return(0)
2612end
2613
2614//
2615// export protocol to a data file
2616//
2617//
2618Function V_ExportFileProtocol(ctrlName) : ButtonControl
2619        String ctrlName
2620// get a list of protocols
2621        String Protocol=""
2622        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2623        Prompt Protocol "Pick A Protocol",popup, V_DeletableProtocols()
2624        DoPrompt "Pick A Protocol to Export",Protocol
2625        if(V_flag==1)
2626                //Print "user cancel"
2627                SetDatafolder root:
2628                return(1)
2629        endif
2630
2631        String fileName = V_DoSaveFileDialog("pick the file to write to")
2632        print fileName
2633//     
2634        if(strlen(fileName) == 0)
2635                return(0)
2636        endif
2637
2638        V_writeReductionProtocolWave(fileName,$("root:Packages:NIST:VSANS:Globals:Protocols:"+Protocol) )
2639
2640        setDataFolder root:
2641        return(0)
2642
2643End
2644
2645//
2646// imports a protocol from a file on disk into the protocols folder
2647//
2648//
2649Function V_ImportFileProtocol(ctrlName) : ButtonControl
2650        String ctrlName
2651
2652//      SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2653
2654        String fullPath,fileName
2655        fullPath = DoOpenFileDialog("Import Protocol from file")
2656        print fullPath
2657//     
2658        if(strlen(fullPath) == 0)
2659                return(0)
2660        endif
2661       
2662        fileName = ParseFilePath(0, fullPath, ":", 1, 0)                        //just the file name at the end of the full path
2663       
2664        Wave/T tmpW = V_getReductionProtocolWave(fileName)
2665        if(numpnts(tmpW) == 0)
2666                DoAlert 0,"No protocol wave has been saved to this data file"
2667                return(0)
2668        endif
2669       
2670        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2671        String newName
2672        newName = CleanupName(fileName,0) + "_proto"
2673        duplicate/o tmpw $newName
2674       
2675       
2676        SetDataFolder root:
2677        return(0)
2678end
2679
2680
2681// currently not used - and not updated to 12 point protocols (5/2017)
2682//
2683//save the protocol as an IGOR text wave (.itx)
2684//
2685//
2686Function V_ExportProtocol(ctrlName) : ButtonControl
2687        String ctrlName
2688// get a list of protocols
2689        String Protocol=""
2690        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2691        Prompt Protocol "Pick A Protocol",popup, WaveList("*",";","")
2692        DoPrompt "Pick A Protocol to Export",Protocol
2693        if(V_flag==1)
2694                //Print "user cancel"
2695                SetDatafolder root:
2696                return(1)
2697        endif
2698//get the selection, or exit
2699        Wave/T pW= $protocol
2700        Make/O/T/N=13 tw
2701// save in the proper format (must write manually, for demo version)
2702        tw[0] = "IGOR"
2703        tw[1] = "WAVES/T \t"+protocol
2704        tw[2] = "BEGIN"
2705        tw[3,10] = "\t\""+pW[p-3]+"\""
2706        tw[11] = "END"
2707        tw[12] = "X SetScale/P x 0,1,\"\","+protocol+"; SetScale y 0,0,\"\","+protocol
2708       
2709        Variable refnum
2710        String fullPath
2711       
2712        PathInfo/S catPathName
2713        fullPath = DoSaveFileDialog("Export Protocol as",fname=Protocol,suffix="")
2714        If(cmpstr(fullPath,"")==0)
2715                //user cancel, don't write out a file
2716                Close/A
2717                Abort "no Protocol file was written"
2718        Endif
2719
2720        //actually open the file
2721        Open refNum as fullpath+".itx"
2722       
2723        wfprintf refnum, "%s\r", tw
2724        Close refnum
2725        //Print "all is well  ",protocol
2726        KillWaves/Z tw
2727        setDataFolder root:
2728        return(0)
2729
2730End
2731
2732
2733// currently not used - and not updated to 12 point protocols (5/2017)
2734//imports a protocol from disk into the protocols folder
2735//
2736// will overwrite existing protocols if necessary
2737//
2738//
2739Function V_ImportProtocol(ctrlName) : ButtonControl
2740        String ctrlName
2741
2742        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2743
2744        String fullPath
2745       
2746        PathInfo/S catPathName
2747        fullPath = DoOpenFileDialog("Import Protocol")
2748        If(cmpstr(fullPath,"")==0)
2749                //user cancel, don't write out a file
2750                Close/A
2751                Abort "no protocol was loaded"
2752        Endif
2753       
2754        LoadWave/O/T fullPath
2755       
2756        SetDataFolder root:
2757        return(0)
2758end
2759
2760
2761///////////////////////////////////////
2762//
2763// individual steps in the protocol
2764//
2765//////////////////////////////////////
2766
2767Function V_Proto_LoadDIV(protStr)
2768        String protStr
2769       
2770        String divFileName = "",junkStr="",pathStr=""
2771        PathInfo catPathName                    //this is where the files are
2772        pathStr=S_path
2773
2774        If(cmpstr("none",protStr)!=0)           // if !0, then there's a file requested
2775                If(cmpstr("ask",protStr) == 0)
2776                        //ask user for file
2777//                       junkStr = PromptForPath("Select the detector sensitivity file")
2778                        Prompt divFileName,"DIV File",popup,V_GetDIVList()
2779                        DoPrompt "Select File",divFileName
2780
2781                        If(strlen(divFileName)==0)
2782                                //
2783                                return(1)               //error
2784//                              SetDataFolder root:
2785//                              Abort "No file selected, data reduction aborted"
2786                        Endif
2787                        V_LoadHDF5Data(divFileName,"DIV")
2788                else
2789                        //assume it's a path, and that the first (and only) item is the path:file
2790                        //list processing is necessary to remove any final comma
2791                        junkStr = pathStr + StringFromList(0, protStr,"," )
2792                        V_LoadHDF5Data(junkStr,"DIV")
2793                Endif
2794       
2795        else
2796        // DIV step is being skipped
2797                NVAR gDoDIVCor = root:Packages:NIST:VSANS:Globals:gDoDIVCor
2798//              Variable saved_gDoDIVCor = gDoDIVCor
2799                gDoDIVCor = 0                   // protocol says to turn it off for now (reset later)
2800        Endif
2801       
2802        return(0)
2803End
2804
2805//
2806// fileStr is the file name (or list of names)
2807// activeType is the target work folder
2808// msgStr is the string for the prompt
2809//
2810Function V_Proto_LoadFile(fileStr,activeType,msgStr)
2811        String fileStr,activeType,msgStr
2812       
2813        Variable err,filesOK,notDone
2814       
2815        //Ask for Type file or parse
2816        do
2817                if((cmpstr(fileStr,"ask") == 0) || (cmpstr(fileStr,"")==0) )            //zero if strings are equal
2818                        err = V_LoadHDF5Data("","RAW")          //will prompt for file
2819                        if(err)
2820                                return(err)     //error
2821                                //PathInfo/S catPathName
2822                                //Abort "reduction sequence aborted"
2823                        endif
2824                        V_UpdateDisplayInformation("RAW")                       //display the new type of data that was loaded
2825                        err =  V_Raw_to_work(activeType)                //this is the first file (default)
2826                        //Ask for another TYPE file
2827                        do
2828                                DoAlert 1,"Do you want to add another "+activeType+" file?"
2829                                if(V_flag == 1)         //yes
2830                                        err = V_LoadHDF5Data("","RAW")          //will prompt for file
2831                                        if(err)
2832                                                return(1)               //error
2833                                                //PathInfo/S catPathName
2834                                                //Abort "reduction sequence aborted"
2835                                        endif
2836                                        V_UpdateDisplayInformation("RAW")                       //display the new type of data that was loaded
2837                                        err = V_Add_raw_to_work(activeType)
2838                                        notDone = 1
2839                                else
2840                                        notDone = 0
2841                                endif
2842                        while(notDone)
2843                        //Loader is in charge of updating, since it knows if data was loaded
2844                        V_UpdateDisplayInformation(ActiveType)
2845                        break
2846                Endif
2847                //"none" is not an option - you always need a sample file - "none" will never return zero
2848                //if not "ask" AND not "none" then try to parse the filenames
2849                If((cmpstr(fileStr,"none") != 0) && (cmpstr(fileStr,"ask") != 0))
2850                        //filesOK = AreFilesThere(activeType,fileStr)           //return 1 if correct files are already there
2851                        filesOK = 0             // Feb 2008, always force a reload of files. Maybe slow, but always correct
2852                        if(!filesOK)
2853                                //add the correct file(s) to Type
2854                               
2855                                // TODO: only one file is allowed currently
2856                                err = V_AddFilesInList(activeType,fileStr)
2857                               
2858                                if(err)
2859                                        //Print "fileStr = ",fileStr
2860                                        DoAlert 0, fileStr + " file not found, reset file"
2861                                        return(err)             //error
2862                                Endif
2863                        Endif
2864                        //Loader is in charge of updating, since it knows if data was loaded
2865                        V_UpdateDisplayInformation(ActiveType)
2866                Endif
2867        While(0)
2868       
2869
2870       
2871        return(0)
2872End
2873
2874Function V_Dispatch_to_Correct(bgdStr,empStr,drkStr)
2875        String bgdStr,empStr,drkStr
2876       
2877        Variable mode=4,val,err
2878       
2879        if( (cmpstr("none",bgdStr) == 0)        && (cmpstr("none",empStr) == 0) )
2880        //no subtraction (mode = 4),
2881                mode = 4
2882        Endif
2883        If((cmpstr(bgdStr,"none") != 0) && (cmpstr(empStr,"none") == 0))
2884                //subtract BGD only
2885                mode=2
2886        Endif
2887        If((cmpstr(bgdStr,"none") == 0) && (cmpstr(empStr,"none") != 0))
2888                //subtract EMP only
2889                mode=3
2890        Endif
2891        If((cmpstr(bgdStr,"none") != 0) && (cmpstr(empStr,"none") != 0))
2892                // bkg and emp subtraction are to be done (BOTH not "none")
2893                mode=1
2894        Endif
2895//      activeType = "COR"
2896        //add in DRK mode (0= not used, 10 = used)
2897        // TODO: DRK has been de-activated for now
2898//      val = NumberByKey("DRKMODE",drkStr,"=","," )
2899//      mode += val
2900
2901//              print "mode = ",mode
2902
2903        err = V_Correct(mode)
2904        if(err)
2905                return(err)
2906//              SetDataFolder root:
2907//              Abort "error in Correct, called from executeprotocol, normal cor"
2908        endif
2909
2910//      //Loader is in charge of updating, since it knows if data was loaded
2911//      V_UpdateDisplayInformation("COR")
2912
2913       
2914        return(0)
2915End
2916
2917
2918
2919
2920Function V_Proto_ABS_Scale(absStr,activeType)
2921        String absStr,&activeType
2922       
2923        Variable c2,c3,c4,c5,kappa_err,err
2924        //do absolute scaling if desired
2925
2926        if(cmpstr("none",absStr)!=0)
2927                if(cmpstr("ask",absStr)==0)
2928//                      //get the params from the user
2929//                      Execute "V_AskForAbsoluteParams_Quest()"
2930//                      //then from the list
2931//                      SVAR junkAbsStr = root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr
2932//                      c2 = NumberByKey("TSTAND", junkAbsStr, "=", ";")        //parse the list of values
2933//                      c3 = NumberByKey("DSTAND", junkAbsStr, "=", ";")
2934//                      c4 = NumberByKey("IZERO", junkAbsStr, "=", ";")
2935//                      c5 = NumberByKey("XSECT", junkAbsStr, "=", ";")
2936//                      kappa_err = NumberByKey("SDEV", junkAbsStr, "=", ";")
2937                else
2938                        //get the parames from the list
2939                        c2 = NumberByKey("TSTAND", absStr, "=", ";")    //parse the list of values
2940                        c3 = NumberByKey("DSTAND", absStr, "=", ";")
2941                        c4 = NumberByKey("IZERO", absStr, "=", ";")
2942                        c5 = NumberByKey("XSECT", absStr, "=", ";")
2943                        kappa_err = NumberByKey("SDEV", absStr, "=", ";")
2944                Endif
2945                //get the sample trans and thickness from the activeType folder
2946//              Variable c0 = V_getSampleTransmission(activeType)               //sample transmission
2947//              Variable c1 = V_getSampleThickness(activeType)          //sample thickness
2948               
2949                err = V_Absolute_Scale(activeType,absStr)
2950                if(err)
2951                        return(err)
2952                        SetDataFolder root:
2953                        Abort "Error in V_Absolute_Scale(), called from V_ExecuteProtocol"
2954                endif
2955                activeType = "ABS"
2956                V_UpdateDisplayInformation(ActiveType)                  //update before breaking from loop
2957        Endif
2958       
2959        return(0)
2960End
2961
2962
2963Function V_Proto_ReadMask(maskStr)
2964        String maskStr
2965       
2966        //check for mask
2967        //doesn't change the activeType
2968        String mskFileName="",pathStr=""
2969        PathInfo catPathName                    //this is where the files are
2970        pathStr=S_path
2971               
2972        if(cmpstr("none",maskStr)!=0)
2973                If(cmpstr("ask",maskStr)==0)
2974                        //get file from user
2975                        // x- fill in the get file prompt, and handle the result
2976                        Prompt mskFileName,"MASK File",popup,V_PickMASKButton("")
2977                        DoPrompt "Select File",mskFileName
2978//                      if (V_Flag)
2979//                              return 0                                                                        // user cancelled
2980//                      endif
2981
2982                        If(strlen(mskFileName)==0)              //use cancelled
2983                                //if none desired, make sure that the old mask is deleted
2984                                KillDataFolder/Z root:Packages:NIST:VSANS:MSK:
2985                                NewDataFolder/O root:Packages:NIST:VSANS:MSK
2986                               
2987                                DoAlert 0,"No Mask file selected, data not masked"
2988                        else
2989                                //read in the file from the selection
2990                                V_LoadHDF5Data(mskFileName,"MSK")
2991                        Endif
2992                else
2993                        //just read it in from the protocol
2994                        //list processing is necessary to remove any final comma
2995                        mskFileName = pathStr + StringFromList(0, maskStr,"," )
2996                        V_LoadHDF5Data(mskFileName,"MSK")
2997                Endif
2998               
2999        else
3000                //if none desired, make sure that the old mask is deleted
3001// TODO
3002// x- clean out the data folder
3003// x- note that V_KillNamedDataFolder() points to RawVSANS, and won't work
3004// -- what happens if the kill fails? need error handling
3005//
3006                KillDataFolder/Z root:Packages:NIST:VSANS:MSK:
3007                NewDataFolder/O root:Packages:NIST:VSANS:MSK
3008
3009        Endif
3010       
3011        return(0)
3012End
3013
3014
3015Function V_Proto_doAverage(avgStr,av_type,activeType,binType,collimationStr)
3016        String avgStr,av_type,activeType
3017        Variable binType
3018        String collimationStr
3019       
3020       
3021        strswitch(av_type)      //dispatch to the proper routine to average to 1D data
3022                case "none":           
3023                        //still do nothing
3024                        // set binType and binTypeStr to bad flags
3025                        String binTypeStr = "none"
3026                        binType = -999999
3027                        break                   
3028
3029                case "Circular":
3030                        V_QBinAllPanels_Circular(activeType,binType,collimationStr)             // this does a default circular average
3031                        break
3032                       
3033                case "Sector":
3034//                      CircularAverageTo1D(activeType)
3035                        break
3036                case "Sector_PlusMinus":
3037//                      Sector_PlusMinus1D(activeType)
3038                        break
3039                case "Rectangular":
3040//                      RectangularAverageTo1D(activeType)
3041                        break
3042
3043                case "Annular":
3044                        String detGroup = StringByKey("DETGROUP",avgStr,"=",";")
3045                        Variable qCtr_Ann = NumberByKey("QCENTER",avgStr,"=",";")
3046                        Variable qWidth = NumberByKey("QDELTA",avgStr,"=",";")
3047                        V_QBinAllPanels_Annular(activeType,detGroup,qCtr_Ann,qWidth)
3048                        break
3049
3050                case "Narrow_Slit":
3051                        V_QBinAllPanels_Slit(activeType,binType)                // this does a tall, narrow slit average
3052                        break
3053                       
3054                case "2D_ASCII":       
3055                        //do nothing
3056                        break
3057                case "QxQy_ASCII":
3058                        //do nothing
3059                        break
3060                case "PNG_Graphic":
3061                        //do nothing
3062                        break
3063                default:       
3064                        //do nothing
3065        endswitch
3066
3067       
3068        return(0)
3069End
3070
3071
3072
3073
3074
3075Function V_Proto_doPlot(plotStr,av_type,activeType,binType,detGroup)
3076        String plotStr,av_type,activeType
3077        Variable binType
3078        String detGroup
3079       
3080        String doPlot = StringByKey("PLOT",plotStr,"=",";")
3081       
3082        If( (cmpstr(doPlot,"Yes")==0) && (cmpstr(av_type,"none") != 0) )       
3083               
3084                strswitch(av_type)      //dispatch to the proper routine to PLOT 1D data
3085                        case "none":           
3086                                //still do nothing
3087                                break                   
3088
3089                        case "Circular":
3090                                V_PlotData_Panel()              //this brings the plot window to the front, or draws it (ONLY)
3091                                V_Update1D_Graph(activeType,binType)            //update the graph, data was already binned                             
3092                                break
3093                        case "Sector":
3094        //                      CircularAverageTo1D(activeType)
3095                                break
3096                        case "Sector_PlusMinus":
3097        //                      Sector_PlusMinus1D(activeType)
3098                                break
3099                        case "Rectangular":
3100        //                      RectangularAverageTo1D(activeType)
3101                                break
3102
3103                        case "Annular":
3104                                V_Phi_Graph_Proc(activeType,detGroup)
3105                                break
3106
3107                        case "Narrow_Slit":
3108                        // these are the same plotting routines as for standard circular average
3109                                V_PlotData_Panel()              //this brings the plot window to the front, or draws it (ONLY)
3110                                V_Update1D_Graph(activeType,binType)            //update the graph, data was already binned
3111                                break
3112                       
3113                        case "2D_ASCII":       
3114                                //do nothing
3115                                break
3116                        case "QxQy_ASCII":
3117                                //do nothing
3118                                break
3119                        case "PNG_Graphic":
3120                                //do nothing
3121                                break
3122                        default:       
3123                                //do nothing
3124                endswitch
3125
3126        endif           // end of plotting switch
3127       
3128        return(0)
3129end
3130
3131
3132Function V_Proto_SaveFile(avgStr,activeType,samFileLoaded,av_type,binType,detGroup,trimBegStr,trimEndStr)
3133        String avgStr,activeType,samFileLoaded,av_type
3134        Variable binType
3135        String detGroup,trimBegStr,trimEndStr
3136       
3137        String fullpath = "", newfileName=""
3138        String saveType = StringByKey("SAVE",avgStr,"=",";")            //does user want to save data?
3139
3140        If( (cmpstr(saveType[0,2],"Yes")==0) && (cmpstr(av_type,"none") != 0) )         
3141                //then save
3142                newFileName = RemoveEnding(samFileLoaded,".nxs.ngv")
3143               
3144                //pick ABS or AVE extension
3145                String exten = activeType
3146                if(cmpstr(exten,"ABS") != 0)
3147                        exten = "AVE"
3148                endif
3149//              if(cmpstr(av_type,"2D_ASCII") == 0)
3150//                      exten = "ASC"
3151//              endif
3152//              if(cmpstr(av_type,"QxQy_ASCII") == 0)
3153//                      exten = "DAT"
3154//              endif
3155               
3156//              // add an "x" to the file extension if the output is XML
3157//              // currently (2010), only for ABS and AVE (1D) output
3158//              if( cmpstr(exten,"ABS") == 0 || cmpstr(exten,"AVE") == 0 )
3159//                      if(useXMLOutput == 1)
3160//                              exten += "x"
3161//                      endif
3162//              endif
3163                               
3164                //Path is catPathName, symbolic path
3165                //if this doesn't exist, a dialog will be presented by setting dialog = 1
3166                //
3167                Variable dialog = 0
3168
3169                PathInfo/S catPathName
3170                String item = StringByKey("NAME",avgStr,"=",";")                //Auto or Manual naming
3171                String autoname = StringByKey("AUTONAME",avgStr,"=",";")                //autoname -  will get empty string if not present
3172                If((cmpstr(item,"Manual")==0) || (cmpstr(newFileName,"") == 0))
3173                        //manual name if requested or if no name can be derived from header
3174                        fullPath = newfileName + "."+ exten //puts possible new name or null string in dialog
3175                        dialog = 1              //force dialog for user to enter name
3176                else
3177                        //auto-generate name and prepend path - won't put up any dialogs since it has all it needs
3178                        //use autoname if present
3179                        if (cmpstr(autoname,"") != 0)
3180                                fullPath = S_Path + autoname + "." +exten
3181                        else
3182                                fullPath = S_Path + newFileName+"." + exten
3183                        endif   
3184                Endif
3185                //
3186                strswitch(av_type)     
3187                        case "Annular":
3188                                V_fWrite1DAnnular("root:Packages:NIST:VSANS:",activeType,detGroup,newFileName+".phi")
3189                                Print "data written to:  "+ newFileName+".phi"
3190
3191                                break
3192
3193                        case "Circular":                //in SANS, this was the default, but is dangerous, so make it explicit here
3194                        case "Sector":          // TODO: this falls through - which luckily works for now...
3195                        case "Rectangular":             // TODO: this falls through - which luckily works for now...
3196                        case "Narrow_Slit":             // TODO: this falls through - which luckily works for now...
3197
3198// no VSANS support of XML output at this point                 
3199//                              if (useXMLOutput == 1)
3200//                                      WriteXMLWaves_W_Protocol(activeType,fullPath,dialog)
3201//                              else
3202//                                      WriteWaves_W_Protocol(activeType,fullpath,dialog)
3203//                              endif
3204//
3205                                if(cmpstr(saveType,"Yes - Concatenate")==0)
3206                                        V_Trim1DDataStr(activeType,binType,trimBegStr,trimEndStr)                       // x- passing null strings uses global or default trim values
3207
3208                                        V_ConcatenateForSave("root:Packages:NIST:VSANS:",activeType,"",binType)         // this removes q=0 point, concatenates, sorts
3209                               
3210                                        V_RemoveDuplicateQvals("root:Packages:NIST:VSANS:",activeType)          // works with the "tmp_x" waves from concatenateForSave
3211//                                      prot[9] = collimationStr
3212                                       
3213                                        V_Write1DData("root:Packages:NIST:VSANS:",activeType,newFileName+"."+exten)             //don't pass the full path, just the name
3214                               
3215                                endif
3216                               
3217                                if(cmpstr(saveType,"Yes - Individual")==0)
3218                                        // remove the q=0 point from the back detector, if it's there
3219                                        // does not trim any other points from the data
3220                                        V_RemoveQ0_B(activeType)
3221                                        V_Write1DData_ITX("root:Packages:NIST:VSANS:",activeType,newFileName,binType)
3222                                endif
3223                                Print "data written to:  "+ newFileName+"."+exten
3224
3225                                break
3226       
3227                               
3228                                case "2D_ASCII":
3229//                              Fast2DExport(activeType,fullPath,dialog)
3230                                break
3231                        case "QxQy_ASCII":
3232//                              QxQy_Export(activeType,fullPath,dialog)
3233                                break
3234                        case "PNG_Graphic":
3235//                              SaveAsPNG(activeType,fullpath,dialog)
3236                                break
3237
3238                        default:
3239                                DoAlert 0, "av_type not found in dispatch to write file"
3240                endswitch
3241               
3242        Endif   
3243        return(0)
3244End
3245
3246
Note: See TracBrowser for help on using the repository browser.