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

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

Added functions to check that files in a protocol, including the sample data are all from the same configuration. In SANS, the only flag was a beam center mismatch. In VSANS, a more complete check of the configuration in necessary.

Changed all instances of calls to the read and normalize the monitor count to use the "norm"al monitor, not the value listed in the Control block.

File size: 98.9 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        //currently unused
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
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//      for(ii=0;ii<num;ii+=1)
812//              item=StringFromList(ii, newList , ";")
813//              fname = path + item
814//              intent = V_getReduction_intent(fname)
815//              if(cmpstr(intent,"SENSITIVITY") == 0)
816//                      list += item + ";"
817//              endif
818//
819//      endfor
820
821        String match="DIV"
822        for(ii=0;ii<num;ii+=1)
823                item=StringFromList(ii, newList , ";")
824                Grep/P=catPathName/Q/E=("(?i)\\b"+match+"\\b") item
825//              Grep/P=catPathName/Q/E=("(?i)"+match) item
826                if( V_value )   // at least one instance was found
827//                              Print "found ", item,ii
828//                      if(strsearch(item,"pxp",0,2) == -1)             //does NOT contain .pxp (the current experiment will be a match)
829                                list += item + ";"
830//                      endif
831                endif
832        endfor
833               
834        List = SortList(List,";",0)
835
836        return(list)
837end
838
839
840Function/S V_GetMSKList()
841
842        String list="",item="",fname,newList,intent
843        Variable ii,num
844       
845        PathInfo catPathName
846        String path = S_path
847       
848        newList = V_Get_NotRawDataFileList()
849        newList = V_RemoveEXTFromList(newlist,"hst")            // remove the event files
850        newList = V_RemoveEXTFromList(newlist,"ave")            // remove the ave files
851        newList = V_RemoveEXTFromList(newlist,"abs")            // remove the abs files
852        newList = V_RemoveEXTFromList(newlist,"phi")            // remove the phi files
853        newList = V_RemoveEXTFromList(newlist,"pxp")            // remove the pxp files
854        newList = V_RemoveEXTFromList(newlist,"DS_Store")               // remove the DS_Store file (OSX only)
855       
856        num=ItemsInList(newList)
857       
858//      for(ii=0;ii<num;ii+=1)
859//              item=StringFromList(ii, newList , ";")
860//              fname = path + item
861//              intent = V_getReduction_intent(fname)
862//              if(cmpstr(intent,"SENSITIVITY") == 0)
863//                      list += item + ";"
864//              endif
865//
866//      endfor
867
868//      String match="MASK"             // this is part of the title of a VSANS MASK file
869        String match="VSANS_MASK"               // this is part of the title of a VSANS MASK file
870        for(ii=0;ii<num;ii+=1)
871                item=StringFromList(ii, newList , ";")
872                Grep/P=catPathName/Q/E=("(?i)\\b"+match+"\\b") item
873//              Grep/P=catPathName/Q/E=("(?i)"+match) item
874                if( V_value )   // at least one instance was found
875//                              Print "found ", item,ii
876//                      if(strsearch(item,"pxp",0,2) == -1)             //does NOT contain .pxp (the current experiment will be a match)
877                                list += item + ";"
878//                      endif
879                endif
880
881        endfor
882               
883        List = SortList(List,";",0)
884
885        return(list)
886end
887
888
889//
890// TODO
891// -- find proper way to search for these files
892// -- they *may* be written to the file header(reduction block)
893// -- or grep for VSANS_MASK (in the title)
894Function/S V_PickMASKButton(ctrlName) : ButtonControl
895        String ctrlName
896        String list="",item="",fname,newList,intent
897        Variable ii,num
898       
899        PathInfo catPathName
900        String path = S_path
901       
902        newList = V_Get_NotRawDataFileList()
903        newList = V_RemoveEXTFromList(newlist,"hst")            // remove the event files
904        num=ItemsInList(newList)
905       
906//      for(ii=0;ii<num;ii+=1)
907//              item=StringFromList(ii, newList , ";")
908//              fname = path + item
909//              intent = V_getReduction_intent(fname)
910//              if(cmpstr(intent,"MASK") == 0)
911//                      list += item + ";"
912//              endif
913//
914//      endfor
915
916        String match="MASK"
917        for(ii=0;ii<num;ii+=1)
918                item=StringFromList(ii, newList , ";")
919                Grep/P=catPathName/Q/E=("(?i)\\b"+match+"\\b") item
920//              Grep/P=catPathName/Q/E=("(?i)"+match) item
921                if( V_value )   // at least one instance was found
922//                              Print "found ", item,ii
923                        list += item + ";"
924                endif
925
926        endfor
927               
928        List = SortList(List,";",0)
929        Printf "MASK files = %s\r",list
930       
931        return(list)   
932
933       
934End
935
936//button action function to reduce one file with the information specified on
937//the panel
938//a temporary protocol is created, even if the fields correspond to a named protocol
939//(only the protocol wave values are written to the data header, but the name is written to the
940//schematic - this could cause some unwanted confusion)
941//
942//if a sample file(s) is selected, only that file(s) will be reduced
943//if no file is selected, the user will be prompted with a standard open
944//dialog to select sample data file(s)
945//
946Function V_ReduceOneButton(ctrlName) : ButtonControl
947        String ctrlName
948
949        //parse the information on the panel and assign to tempProtocol wave (in protocol folder)
950        //and execute
951        String temp="root:Packages:NIST:VSANS:Globals:Protocols:tempProtocol"
952        Wave/T w=$temp
953        Variable ii=0,num=12,err
954        do
955                w[ii] = ""
956                ii+=1
957        while(ii<num)
958       
959       
960        err = V_MakeProtocolFromPanel(w)
961        if(err)
962                DoAlert 0,"BGD and EMP files do not have the same configuration."
963                return(0)
964        endif
965       
966        //the "current" protocol is the "tempProtocol" that was parsed from the panel input
967        //set the global, so that the data writing routine can find the protocol wave (fatal otherwise)
968        String/G root:Packages:NIST:VSANS:Globals:Protocols:gProtoStr="tempProtocol"
969       
970        PathInfo catPathName                    //this is where the files came from
971        String pathstr=S_path,samStr
972       
973        //take the string from the panel
974        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gSAM
975       
976        if( (strlen(tempStr) == 0) || (cmpstr(tempStr,"ask")==0) )
977                //let user select the files
978                tempStr="ask"
979                V_ExecuteProtocol(temp,tempStr)
980                return(0)
981        Else
982                //parse the list of numbers
983                //send only the filenames, without paths
984                samStr = V_ParseRunNumberList(tempStr)
985                If(strlen(samStr)==0)
986                        DoAlert 0,"The SAM file number cound not be interpreted. Please enter a valid run number or filename"
987                        return(1)
988                endif
989                tempStr=samStr          //reset the global
990                V_ExecuteProtocol(temp,samStr)
991                return(0)
992        endif
993End
994
995
996//button action function will prompt user for absolute scaling parameters
997//either from an empty beam file or by manually entering the 4 required values
998//uses the same function and shared global string as the questionnare form of reduction
999//in "protocol.ipf" - the string is root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr
1000//
1001Function V_SetABSParamsButton(ctrlName) : ButtonControl
1002        String ctrlName
1003
1004        //will prompt for a list of ABS parameters (4) through a global string variable
1005       
1006        Execute "V_AskForAbsoluteParams_Quest()"
1007       
1008End
1009
1010
1011
1012//the panel recreation macro
1013//
1014Window V_ProtocolPanel()
1015        PauseUpdate; Silent 1           // building window...
1016        NewPanel /W=(1280,332,1630,932) /K=1 as "VSANS Reduction Protocol"
1017        ModifyPanel cbRGB=(56589,50441,50159), fixedSize=1
1018        SetDrawLayer UserBack
1019        DrawLine 3,65,301,65
1020        DrawLine 3,157,301,157
1021        DrawLine 3,208,301,208
1022        DrawLine 3,257,301,257
1023        DrawLine 3,305,301,305
1024        DrawLine 3,350,301,350
1025        DrawLine 3,445,301,445
1026        DrawLine 3,513,301,513
1027        DrawLine 3,396,301,396
1028
1029//
1030        Button button_help,pos={300,2},size={25,20},proc=V_ShowProtoHelp,title="?"
1031        Button button_help,help={"Show the help file for setting up a reduction protocol"}
1032        Button button_quest,pos={20,2},size={150,20},proc=V_ProtocolQuestionnaire,title="Questions"
1033        Button button_quest,help={"Run through the questionnaire for setting up a reduction protocol"}
1034        Button button_quest,disable=2
1035
1036
1037        PopupMenu popup_sam,pos={85,68},size={51,23},proc=V_SAMFilePopMenuProc
1038        PopupMenu popup_sam,mode=1,value= #"V_getSAMList()"     
1039        PopupMenu popup_bkg,pos={85,164},size={51,23},proc=V_BKGFilePopMenuProc
1040        PopupMenu popup_bkg,mode=1,value= #"V_getBGDList()"
1041        PopupMenu popup_emp,pos={85,213},size={51,23},proc=V_EMPFilePopMenuProc
1042        PopupMenu popup_emp,mode=1,value= #"V_getEMPList()"
1043        PopupMenu popup_div,pos={85,263},size={51,23},proc=V_DIVFilePopMenuProc
1044        PopupMenu popup_div,mode=1,value= #"V_getDIVList()"
1045        PopupMenu popup_msk,pos={85,356},size={51,23},proc=V_MSKFilePopMenuProc
1046        PopupMenu popup_msk,mode=1,value= #"V_getMSKList()"     
1047               
1048               
1049        CheckBox prot_check,pos={6,163},size={74,14},title="Background"
1050        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"}
1051        CheckBox prot_check,value= 1
1052        CheckBox prot_check_1,pos={6,215},size={71,14},title="Empty Cell"
1053        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"}
1054        CheckBox prot_check_1,value= 1
1055        CheckBox prot_check_2,pos={6,263},size={72,14},title="Sensitivity"
1056        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"}
1057        CheckBox prot_check_2,value= 1
1058        CheckBox prot_check_3,pos={6,356},size={43,14},title="Mask"
1059        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"}
1060        CheckBox prot_check_3,value= 1
1061        CheckBox prot_check_4,pos={6,70},size={53,14},title="Sample"
1062        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"}
1063        CheckBox prot_check_4,value= 1
1064        CheckBox prot_check_5,pos={6,399},size={56,14},title="Average"
1065        CheckBox prot_check_5,help={"If checked, the specified averaging will be performed at the end of the data reduction."}
1066        CheckBox prot_check_5,value= 1 
1067        CheckBox prot_check_9,pos={6,310},size={59,14},title="Absolute"
1068        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"}
1069        CheckBox prot_check_9,value= 1
1070       
1071
1072//      Button pick_sam,pos={214,28},size={70,20},proc=V_PickSAMButton,title="set SAM"
1073//      Button pick_sam,help={"This button will set the file selected in the File Catalog table to be the sample file"}
1074//      Button pick_bgd,pos={214,75},size={70,20},proc=V_PickBGDButton,title="set BGD"
1075//      Button pick_bgd,help={"This button will set the file selected in the File Catalog table to be the background file."}
1076//      Button pick_emp,pos={214,125},size={70,20},proc=V_PickEMPButton,title="set EMP"
1077//      Button pick_emp,help={"This button will set the file selected in the File Catalog table to be the empty cell file."}
1078//      Button pick_DIV,pos={214,173},size={70,20},proc=V_PickDIVButton,title="set DIV"
1079//      Button pick_DIV,help={"This button will set the file selected in the File Catalog table to be the sensitivity file."}
1080        Button pick_ABS,pos={264,308},size={70,20},proc=V_SetABSParamsButton,title="set ABS"
1081        Button pick_ABS,help={"This button will prompt the user for absolute scaling parameters"}       
1082//      Button pick_MASK,pos={214,266},size={70,20},proc=V_PickMASKButton,title="set MASK"
1083//      Button pick_MASK,help={"This button will set the file selected in the File Catalog table to be the mask file."}
1084
1085
1086        Button pick_AVE,pos={188,401},size={150,20},proc=V_SetAverageParamsButtonProc,title="set AVERAGE params"
1087        Button pick_AVE,help={"Prompts the user for the type of 1-D averaging to perform, as well as saving options"}
1088
1089       
1090        Button pick_trim,pos={264,454},size={70,20},proc=V_TrimDataProtoButton,title="Trim"
1091        Button pick_trim,help={"This button will prompt the user for trimming parameters"}     
1092       
1093       
1094        SetVariable samStr,pos={6,90},size={250,15},title="file:"
1095        SetVariable samStr,help={"Filename of the sample file(s) to be used in the data reduction"}
1096        SetVariable samStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gSAM           
1097        SetVariable bgdStr,pos={7,186},size={250,15},title="file:"
1098        SetVariable bgdStr,help={"Filename of the background file(s) to be used in the data reduction"}
1099        SetVariable bgdStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gBGD
1100        SetVariable empStr,pos={8,236},size={250,15},title="file:"
1101        SetVariable empStr,help={"Filename of the empty cell file(s) to be used in the data reduction"}
1102        SetVariable empStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gEMP
1103        SetVariable divStr,pos={9,285},size={250,15},title="file:"
1104        SetVariable divStr,help={"Filename of the detector sensitivity file to be used in the data reduction"}
1105        SetVariable divStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gDIV
1106        SetVariable maskStr,pos={9,377},size={250,15},title="file:"
1107        SetVariable maskStr,help={"Filename of the mask file to be used in the data reduction"}
1108        SetVariable maskStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gMASK
1109        SetVariable absStr,pos={7,331},size={250,15},title="parameters:"
1110        SetVariable absStr,help={"Keyword-string of values necessary for absolute scaling of data. Remaining parameters are taken from the sample file."}
1111        SetVariable absStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr
1112        SetVariable aveStr,pos={9,424},size={250,15},title="parameters:"
1113        SetVariable aveStr,help={"Keyword-string of choices used for averaging and saving the 1-D data files"}
1114        SetVariable aveStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gAVE
1115
1116        SetVariable begStr,pos={9,464},size={250,15},title="Beg Trim:"
1117        SetVariable begStr,help={"Keyword-string of choices used for averaging and saving the 1-D data files"}
1118        SetVariable begStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gBegPtsStr
1119        SetVariable endStr,pos={9,484},size={250,15},title="End Trim:"
1120        SetVariable endStr,help={"Keyword-string of choices used for averaging and saving the 1-D data files"}
1121        SetVariable endStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gEndPtsStr
1122
1123
1124       
1125        //only show DRK if user wants to see it
1126        //if global = 1,then show => set disable = 0
1127//      CheckBox prot_check_6,pos={6,363},size={113,14},proc=DrkCheckProc,title="Use DRK correction"
1128//      CheckBox prot_check_6,help={"If checked, the selected file will be used for DRK correction. Typically this is NOT checked"}
1129//      CheckBox prot_check_6,value= 0,disable = (!root:Packages:NIST:gAllowDRK)
1130//      SetVariable drkStr,pos={120,363},size={150,15},title="."
1131//      SetVariable drkStr,help={"DRK detector count file"},disable = (!root:Packages:NIST:gAllowDRK)
1132//      SetVariable drkStr,limits={-Inf,Inf,0},value= root:Packages:NIST:VSANS:Globals:Protocols:gDRK
1133
1134
1135        Button export_button, size={120,20},pos={125,540},title="Export to Data",proc=V_ExportFileProtocol
1136        Button export_button, help={"Exports the protocol to data file on disk for Importing into another experiment"}
1137        Button import_button, size={120,20},pos={125,562},title="Import from Data",proc=V_ImportFileProtocol
1138        Button import_button,help={"Imports a protocol from a data file on disk for use in this experiment"}
1139        Button recallProt,pos={7,540},size={107,20},proc=V_RecallProtocolButton,title="Recall Protocol"
1140        Button recallProt,help={"Resets the panel to the file choices in  a previously saved protocol"}
1141        Button del_protocol,pos={7,562},size={110,20},proc=V_DeleteProtocolButton,title="Delete Protocol"
1142        Button del_protocol,help={"Use this to delete a previously saved protocol."}
1143        Button done_protocol,pos={285,562},size={45,20},proc=V_DoneProtocolButton,title="Done"
1144        Button done_protocol,help={"This button will close the panel. The panel can be recalled at any time from the SANS menu."}
1145        Button saveProtocol,pos={7,518},size={100,20},proc=V_SaveProtocolButton,title="Save Protocol"
1146        Button saveProtocol,help={"Saves the cerrent selections in the panel to a protocol which can be later recalled"}
1147        Button ReduceOne,pos={240,518},size={100,20},proc=V_ReduceOneButton,title="Reduce A File"
1148        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"}
1149
1150EndMacro
1151
1152
1153
1154
1155
1156Function V_SAMFilePopMenuProc(pa) : PopupMenuControl
1157        STRUCT WMPopupAction &pa
1158
1159        switch( pa.eventCode )
1160                case 2: // mouse up
1161                        Variable popNum = pa.popNum
1162                        String popStr = pa.popStr
1163                        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gSAM
1164                        tempStr = popStr
1165                        break
1166                case -1: // control being killed
1167                        break
1168        endswitch
1169
1170        return 0
1171End
1172
1173
1174Function V_BKGFilePopMenuProc(pa) : PopupMenuControl
1175        STRUCT WMPopupAction &pa
1176
1177        switch( pa.eventCode )
1178                case 2: // mouse up
1179                        Variable popNum = pa.popNum
1180                        String popStr = pa.popStr
1181                        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gBGD
1182                        tempStr = popStr
1183                        break
1184                case -1: // control being killed
1185                        break
1186        endswitch
1187
1188        return 0
1189End
1190
1191Function V_EMPFilePopMenuProc(pa) : PopupMenuControl
1192        STRUCT WMPopupAction &pa
1193
1194        switch( pa.eventCode )
1195                case 2: // mouse up
1196                        Variable popNum = pa.popNum
1197                        String popStr = pa.popStr
1198                        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gEMP
1199                        tempStr = popStr
1200                        break
1201                case -1: // control being killed
1202                        break
1203        endswitch
1204
1205        return 0
1206End
1207
1208Function V_DIVFilePopMenuProc(pa) : PopupMenuControl
1209        STRUCT WMPopupAction &pa
1210
1211        switch( pa.eventCode )
1212                case 2: // mouse up
1213                        Variable popNum = pa.popNum
1214                        String popStr = pa.popStr
1215                        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gDIV
1216                        tempStr = popStr
1217                        break
1218                case -1: // control being killed
1219                        break
1220        endswitch
1221
1222        return 0
1223End
1224
1225Function V_MSKFilePopMenuProc(pa) : PopupMenuControl
1226        STRUCT WMPopupAction &pa
1227
1228        switch( pa.eventCode )
1229                case 2: // mouse up
1230                        Variable popNum = pa.popNum
1231                        String popStr = pa.popStr
1232                        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gMASK
1233                        tempStr = popStr
1234                        break
1235                case -1: // control being killed
1236                        break
1237        endswitch
1238
1239        return 0
1240End
1241
1242////activated when user checks/unchecks the box
1243////either prompts for a file using a standard dialog, or removes the current file
1244//Function V_DrkCheckProc(ctrlName,checked) : CheckBoxControl
1245//      String ctrlName
1246//      Variable checked                //Desired state, not previous state
1247//
1248//      SVAR drkStr=root:Packages:NIST:VSANS:Globals:Protocols:gDRK
1249//      if(checked==1)
1250//              //print "Unchecked on call"
1251//              //this just asks for the filename, doesn't open the file
1252//              String msgStr="Select the DRK file",fullPath="",fileStr=""
1253//              Variable refnum
1254//             
1255//              Open/D/R/T="????"/M=(msgStr)/P=catPathName refNum
1256//              fullPath = S_FileName           //fname is the full path
1257//              if(cmpstr(fullpath,"")==0)
1258//                      //user cancelled
1259//                      CheckBox prot_check_6,value=0           //keep box unchecked
1260//                      return(0)
1261//              Endif
1262//              fileStr=V_GetFileNameFromPathNoSemi(fullPath)
1263//              //Print fileStr
1264//              //update the global string
1265//              drkStr = ReplaceStringByKey("DRK",drkStr,fileStr,"=",",")
1266//              drkStr = ReplaceNumberByKey("DRKMODE", drkStr, 10 ,"=",",")
1267//      else
1268//              //print "checked on call"
1269//              drkStr="DRK=none,DRKMODE=0,"            //change the global
1270//      endif
1271//     
1272//End
1273
1274
1275Function V_ShowProtoHelp(ctrlName) : ButtonControl
1276        String ctrlName
1277        DisplayHelpTopic/Z/K=1 "VSANS Data Reduction Tutorial[VSANS Reduction Protocol]"
1278        if(V_flag !=0)
1279                DoAlert 0,"The VSANS Data Reduction Tutorial Help file could not be found"
1280        endif
1281End
1282
1283//button action procedure to get the type of average requested by the user
1284//presented as a missing parameter dialog, which is really user-UN-friendly
1285//and will need to be re-thought. Defaults of dialog are set for normal
1286//circular average, so typically click "continue" and proceed
1287//
1288Function V_SetAverageParamsButtonProc(ctrlName) : ButtonControl
1289        String ctrlName
1290       
1291//      Execute "V_GetAvgInfo_Full()"
1292        Execute "V_GetAvgInfo()"
1293       
1294        //set the global string
1295        SVAR tempStr = root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr
1296        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAVE = tempStr
1297
1298End
1299
1300// TODO
1301// -- this is a trimmed down version of the "full" set of averaging options
1302//    add to this as needed as I figure out what functionality is appropriate
1303//
1304//procedure called by protocol panel to ask user for average type choices
1305// somewhat confusing and complex, but may be as good as it gets.
1306//
1307//Proc V_GetAvgInfo(av_typ,autoSave,autoName,autoPlot,side,phi,dphi,width,QCtr,QDelta)
1308Proc V_GetAvgInfo(av_typ,autoSave,autoName,binType,qCtr,qDelta,detGroup)
1309        String av_typ,autoSave,AutoName,binType
1310//      Variable phi=0,dphi=10,width=10,Qctr = 0.01,qDelta=10
1311        Variable Qctr=0.1,qDelta=0.01
1312        String detGroup="F"
1313
1314//      Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII;PNG_Graphic;Sector_PlusMinus;"
1315        Prompt av_typ, "Type of Average",popup,"Circular;Narrow_Slit;Annular;"
1316
1317// comment out above line in DEMO_MODIFIED version, and uncomment the line below (to disable PNG save)
1318//      Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII"
1319        Prompt autoSave,"Save files to disk?",popup,"Yes - Concatenate;Yes - Individual;No"
1320        Prompt autoName,"Auto-Name files?",popup,"Auto;Manual"
1321//      Prompt autoPlot,"Plot the averaged Data?",popup,"Yes;No"
1322//      Prompt side,"Include detector halves?",popup,"both;right;left"
1323//      Prompt phi,"Orientation Angle (-90,90) degrees (Rectangular or Sector)"
1324//      Prompt dphi, "Azimuthal range (0,45) degrees (Sector only)"
1325//      Prompt width, "Width of Rectangular average (1,128)"
1326        Prompt binType,"Binning Type?",popup,ksBinTypeStr
1327
1328        Prompt Qctr, "q-value of center of annulus"
1329        Prompt Qdelta,"(+/-) q-width of annulus"
1330        Prompt detGroup,"Group for annulus"
1331       
1332        //assign results of dialog to key=value string, semicolon separated
1333        //do only what is necessary, based on av_typ
1334        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr=""
1335
1336        // TODO:
1337        // hard wired value
1338        String autoPlot = "Yes"
1339       
1340               
1341        // all averages need these values
1342        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "AVTYPE=" + av_typ + ";"
1343        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "SAVE=" + autoSave + ";"
1344        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "NAME=" + autoName + ";"
1345        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "PLOT=" + autoPlot + ";"
1346        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "BINTYPE=" + binType + ";"
1347       
1348//      if(cmpstr(av_typ,"Sector")==0 || cmpstr(av_typ,"Sector_PlusMinus")==0)
1349//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
1350//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
1351//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "DPHI=" + num2str(dphi) + ";"
1352//      Endif
1353//     
1354//      if(cmpstr(av_typ,"Rectangular")==0)
1355//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
1356//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
1357//              root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "WIDTH=" + num2str(width) + ";"
1358//      Endif
1359//     
1360        if(cmpstr(av_typ,"Annular")==0)
1361                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "QCENTER=" + num2str(QCtr) + ";"
1362                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "QDELTA=" + num2str(QDelta) + ";"
1363                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "DETGROUP=" + detGroup + ";"
1364        Endif
1365End
1366
1367
1368// TODO
1369// -- this is the original(SANS) version, and needs to be updated for VSANS as the averaging options are
1370//    worked out
1371// -- there have been changes made to V_GetAvgInfo() above -- so work from that version, NOT this one.
1372//
1373//
1374//procedure called by protocol panel to ask user for average type choices
1375// somewhat confusing and complex, but may be as good as it gets.
1376//
1377Proc V_GetAvgInfo_Full(av_typ,autoSave,autoName,autoPlot,side,phi,dphi,width,QCtr,QDelta)
1378        String av_typ,autoSave,AutoName,autoPlot,side
1379        Variable phi=0,dphi=10,width=10,Qctr = 0.01,qDelta=10
1380        Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII;PNG_Graphic;Sector_PlusMinus;"
1381// comment out above line in DEMO_MODIFIED version, and uncomment the line below (to disable PNG save)
1382//      Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII"
1383        Prompt autoSave,"Save files to disk?",popup,"Yes;No"
1384        Prompt autoName,"Auto-Name files?",popup,"Auto;Manual"
1385        Prompt autoPlot,"Plot the averaged Data?",popup,"Yes;No"
1386        Prompt side,"Include detector halves?",popup,"both;right;left"
1387        Prompt phi,"Orientation Angle (-90,90) degrees (Rectangular or Sector)"
1388        Prompt dphi, "Azimuthal range (0,45) degrees (Sector only)"
1389        Prompt width, "Width of Rectangular average (1,128)"
1390        Prompt Qctr, "q-value of center of annulus"
1391        Prompt Qdelta,"Pixel width of annulus"
1392
1393        //assign results of dialog to key=value string, semicolon separated
1394        //do only what is necessary, based on av_typ
1395        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr=""
1396       
1397        // all averages need these four values
1398        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "AVTYPE=" + av_typ + ";"
1399        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "SAVE=" + autoSave + ";"
1400        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "NAME=" + autoName + ";"
1401        root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "PLOT=" + autoPlot + ";"
1402       
1403        if(cmpstr(av_typ,"Sector")==0 || cmpstr(av_typ,"Sector_PlusMinus")==0)
1404                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
1405                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
1406                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "DPHI=" + num2str(dphi) + ";"
1407        Endif
1408       
1409        if(cmpstr(av_typ,"Rectangular")==0)
1410                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
1411                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
1412                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "WIDTH=" + num2str(width) + ";"
1413        Endif
1414       
1415        if(cmpstr(av_typ,"Annular")==0)
1416                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "QCENTER=" + num2str(QCtr) + ";"
1417                root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr += "QDELTA=" + num2str(QDelta) + ";"
1418        Endif
1419End
1420
1421
1422//prompts the user to pick a previously created protocol from a popup list
1423//of given the option to create a new protocol
1424//the chosen protocol is passed back to the calling procedure by a global string
1425//the popup is presented as a missing parameter dialog (called with empty parameter list)
1426//
1427// MAXROWS is present to exclude the PanelNameW from appearing as a protocol
1428Proc V_PickAProtocol(protocol)
1429        String Protocol
1430        Prompt Protocol "Pick A Protocol",popup, V_RecallableProtocols()
1431       
1432        String/G  root:Packages:NIST:VSANS:Globals:Protocols:gProtoStr = protocol
1433End
1434
1435Proc V_DeleteAProtocol(protocol)
1436        String Protocol
1437//      Prompt Protocol "Delete A Protocol",popup, WaveList("*",";","TEXT:1")
1438        Prompt Protocol "Delete A Protocol",popup, V_DeletableProtocols()
1439
1440        String/G  root:Packages:NIST:VSANS:Globals:Protocols:gProtoStr = protocol
1441End
1442
1443Function/S V_DeletableProtocols()
1444        String list=WaveList("*",";","TEXT:1,MAXROWS:13")
1445
1446        list= RemoveFromList("Base", list  , ";")
1447        list= RemoveFromList("DoAll", list  , ";")
1448        list= RemoveFromList("CreateNew", list  , ";")
1449        list= RemoveFromList("tempProtocol", list  , ";")
1450        list= RemoveFromList("wTTmpWrite", list  , ";")
1451        if(cmpstr(list,"")==0)
1452                list = "_no_protocols_;"
1453        endif
1454       
1455        return(list)
1456End
1457
1458Function/S V_RecallableProtocols()
1459        String list=WaveList("*",";","TEXT:1,MAXROWS:13")
1460
1461//      list= RemoveFromList("Base", list  , ";")
1462//      list= RemoveFromList("DoAll", list  , ";")
1463        list= RemoveFromList("CreateNew", list  , ";")
1464        list= RemoveFromList("tempProtocol", list  , ";")
1465        list= RemoveFromList("wTTmpWrite", list  , ";")
1466        if(cmpstr(list,"")==0)
1467                list = "_no_protocols_;"
1468        endif
1469       
1470        return(list)
1471End
1472
1473
1474//missing parameter dialog to solicit user for a waveStr for the protocol
1475//about to be created
1476//name is passed back as a global string and calling procedure is responsible for
1477//checking for wave conflicts and valid names
1478//
1479Proc V_AskForName(protocol)
1480        String Protocol
1481        Prompt Protocol "Enter a new name for your protocol (no extension)"
1482       
1483        String/G  root:Packages:NIST:VSANS:Globals:Protocols:gNewStr = protocol
1484End
1485
1486//this is a lengthy procedure for sequentially polling the user about what data
1487//reduction steps they want to be performed during the protocol
1488//ensures that a valid protocol name was chosen, then fills out each "item"
1489//(6 total) needed for reduction
1490//it the user cancels at any point, the partial protocol will be deleted
1491//
1492Function V_ProtocolQuestionnaire(ctrlName)
1493        String ctrlName
1494
1495        String filename,cmd
1496        Variable notDone,refnum
1497       
1498        //prompt for name of new protocol wave to save
1499        do
1500                Execute "V_AskForName()"
1501                SVAR newProtoStr = root:Packages:NIST:VSANS:Globals:Protocols:gNewStr
1502               
1503                //make sure it's a valid IGOR name
1504                newProtoStr = CleanupName(newProtoStr,0)        //strict naming convention
1505                String/G root:Packages:NIST:VSANS:Globals:Protocols:gNewStr=newProtoStr         //reassign, if changed
1506                //Print "newProtoStr = ",newProtoStr
1507               
1508                SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
1509                if(WaveExists( $("root:Packages:NIST:VSANS:Globals:Protocols:" + newProtoStr) ) == 1)
1510                        //wave already exists
1511                        DoAlert 0,"that name is already in use. Please pick a new name"
1512                        notDone = 1
1513                else
1514                        //name is  good
1515                        notDone = 0
1516                Endif
1517        while(notDone)
1518       
1519        //Print "protocol questionnaire is "+newProtocol
1520       
1521        //make a new text wave (12 points) and fill it in, in response to questions
1522        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols //(redundant - full wave specs are used)
1523        Make/O/T/N=(kNumProtocolSteps) $("root:Packages:NIST:VSANS:Globals:Protocols:" + newProtoStr)
1524        Wave/T newProtocol = $("root:Packages:NIST:VSANS:Globals:Protocols:" + newProtoStr)
1525        newProtocol = ""
1526       
1527        //ask the questions
1528        /////
1529        //*****Multiple files in these lists are full paths/filenames which may or may not
1530        //have semicolon version numbers in the filename. Therefore, construct the list with
1531        //COMMAS as separators - to avoid messy parsing
1532        ///////
1533       
1534        String fileFilters = "VSANS Data Files (*.ngv,*.h5):.ngv,.h5;"
1535//      fileFilters += "HTML Files (*.htm,*.html):.htm,.html;"
1536        fileFilters += "All Files:.*;"
1537//////////////////////////
1538        String drkStr="",fileStr=""
1539       
1540       
1541//////////////////////////     
1542//      DoAlert 1,"Do you want to correct your data for DRK (beam off) counts?"
1543//      if(V_flag == 1)         //1=yes
1544//              //prompt for DRK  file, but don't actually open it (/D flag)
1545//              Open/D/R/F=fileFilters/M="Select the DRK file"/P=catPathName refnum
1546//              //check for cancel
1547//              if(strlen(S_filename)==0)
1548//                      //user cancelled, abort
1549//                      KillWaves/Z newProtocol
1550//                      SetDataFolder root:
1551//                      Abort "Incomplete protocol has been deleted"
1552//              Endif
1553//              //assign filename (just the name) to [6]
1554//              fileStr = V_GetFileNameFromPathNoSemi(S_filename)
1555//              drkStr = "DRK=none,DRKMODE=0,"
1556//              drkStr = ReplaceStringByKey("DRK",drkStr,fileStr,"=",",")
1557//              drkStr = ReplaceNumberByKey("DRKMODE", drkStr, 10 ,"=",",")     
1558//              newProtocol[6] = drkStr
1559//      else
1560//              //no Work.DRK desired
1561//              newProtocol[6] = "DRK=none,DRKMODE=0,"
1562//      Endif
1563//     
1564////////////
1565       
1566       
1567// TODO:
1568// -- there is a lag in the V_pick() routine as it greps through all of the files. Several seconds even when there
1569//   are 20-ish files. Pre-search for the strings? When to refresh them for new data?   
1570/////////////////
1571        DoAlert 1,"Do you want to subtract background from your data?"
1572        if(V_flag == 1)         //1=yes
1573               
1574                Prompt filename,"BKG File",popup,V_PickBGDButton("")
1575                DoPrompt "Select File",filename
1576                if (V_Flag)
1577                        return 0                                                                        // user canceled
1578                endif
1579//              //assign filename to [0]
1580                newProtocol[0] = V_GetFileNameFromPathNoSemi(fileName)
1581       
1582               
1583// OLD way, using an open file dialog   
1584// and allowing for multiple files to be added together
1585//     
1586//              //prompt for background file, but don't actually open it (/D flag)
1587//              Open/D/R/F=fileFilters/M="Select the Background data file"/P=catPathName refnum
1588//              //check for cancel
1589//              if(strlen(S_filename)==0)
1590//                      //user cancelled, abort
1591//                      KillWaves/Z newProtocol
1592//                      SetDataFolder root:
1593//                      Abort "Incomplete protocol has been deleted"
1594//              Endif
1595//              //assign filename (full path) to [0]
1596//              newProtocol[0] = V_GetFileNameFromPathNoSemi(S_filename)
1597               
1598//              notDone=1
1599//              do
1600//                      //prompt for additional background files
1601//                      DoAlert 1,"Do you want to add another background file?"
1602//                      if(V_flag == 1)         //yes
1603//                              Open/D/R/F=fileFilters/M="Select another Background data file"/P=catPathName refnum
1604//                              //check for cancel
1605//                              if(strlen(S_filename)==0)
1606//                                      //user cancelled, abort ********maybe just break out of the loop here
1607//                                      KillWaves/Z newProtocol
1608//                                      SetDataFolder root:
1609//                                      Abort "Incomplete protocol has been deleted"
1610//                              Endif
1611//                              //assign filename (full path) to [0]
1612//                              newProtocol[0] += "," + V_GetFileNameFromPathNoSemi(S_filename)         //***COMMA separated list
1613//                              notDone = 1             //keep going
1614//                      else
1615//                              notDone = 0                     //no more to add
1616//                      Endif
1617//              While(notDone)
1618//////
1619
1620        else            //no background desired
1621                newProtocol[0] = "none"
1622        Endif
1623       
1624       
1625////////////////////// 
1626        DoAlert 1,"Do you want to subtract empty cell scattering from your data?"
1627        if(V_flag == 1)         //1=yes
1628               
1629                Prompt filename,"EMP File",popup,V_PickEMPButton("")
1630                DoPrompt "Select File",filename
1631                if (V_Flag)
1632                        return 0                                                                        // user canceled
1633                endif
1634//              //assign filename to [1]
1635                newProtocol[1] = V_GetFileNameFromPathNoSemi(fileName)         
1636       
1637
1638               
1639//              //prompt for Empty cell file, but don't actually open it (/D flag)
1640//              Open/D/R/F=fileFilters/M="Select the Empty Cell data file"/P=catPathName refnum
1641//              //check for cancel
1642//              if(strlen(S_filename)==0)
1643//                      //user cancelled, abort
1644//                      KillWaves/Z newProtocol
1645//                      SetDataFolder root:
1646//                      Abort "Incomplete protocol has been deleted"
1647//              Endif
1648//              //assign filename (full path) to [1]
1649//              newProtocol[1] = V_GetFileNameFromPathNoSemi(S_filename)
1650//             
1651//              notDone=1
1652//              do
1653//                      //prompt for additional Empty Cell files
1654//                      DoAlert 1,"Do you want to add another Empty Cell file?"
1655//                      if(V_flag == 1)         //yes
1656//                              Open/D/R/F=fileFilters/M="Select another Empty Cell data file"/P=catPathName refnum
1657//                              //check for cancel
1658//                              if(strlen(S_filename)==0)
1659//                                      //user cancelled, abort ********maybe just break out of the loop here
1660//                                      KillWaves/Z newProtocol
1661//                                      SetDataFolder root:
1662//                                      Abort "Incomplete protocol has been deleted"
1663//                              Endif
1664//                              //assign filename (full path) to [1]
1665//                              newProtocol[1] += "," + V_GetFileNameFromPathNoSemi(S_filename)         //***COMMA separated list
1666//                              notDone = 1             //keep going
1667//                      else
1668//                              notDone = 0                     //no more to add
1669//                      Endif
1670//              While(notDone)
1671
1672
1673        else            //no background desired
1674                newProtocol[1] = "none"
1675        Endif
1676       
1677       
1678//////////////////////////
1679        DoAlert 1,"Do you want to correct your data for detector sensitivity?"
1680       
1681        if(V_flag == 1)         //1=yes
1682               
1683                Prompt filename,"DIV File",popup,V_GetDIVList()
1684                DoPrompt "Select File",filename
1685                if (V_Flag)
1686                        return 0                                                                        // user canceled
1687                endif
1688//              //assign filename to [2]
1689                newProtocol[2] = V_GetFileNameFromPathNoSemi(fileName)
1690               
1691//              //prompt for DIV  file, but don't actually open it (/D flag)
1692//              Open/D/R/F=fileFilters/M="Select the detector sensitivity file"/P=catPathName refnum
1693//              //check for cancel
1694//              if(strlen(S_filename)==0)
1695//                      //user cancelled, abort
1696//                      KillWaves/Z newProtocol
1697//                      SetDataFolder root:
1698//                      Abort "Incomplete protocol has been deleted"
1699//              Endif
1700//              //assign filename (full path) to [2]
1701//              newProtocol[2] = V_GetFileNameFromPathNoSemi(S_filename)
1702               
1703               
1704        else
1705                //no Work.DIV desired
1706                newProtocol[2] = "none"
1707        Endif   
1708//////////////////////////
1709        DoAlert 1,"Do you want to mask your files before averaging?"
1710       
1711        if(V_flag == 1)         //1=yes
1712       
1713                Prompt filename,"MASK File",popup,V_PickMASKButton("")
1714                DoPrompt "Select File",filename
1715                if (V_Flag)
1716                        return 0                                                                        // user canceled
1717                endif
1718//              //assign filename to [3]
1719                newProtocol[3] = V_GetFileNameFromPathNoSemi(fileName)
1720                       
1721//              //prompt for mask  file, but don't actually open it (/D flag)
1722//              Open/D/R/F=fileFilters/M="Select the mask file"/P=catPathName refnum
1723//              //check for cancel
1724//              if(strlen(S_filename)==0)
1725//                      //user cancelled, abort
1726//                      KillWaves/Z newProtocol
1727//                      SetDataFolder root:
1728//                      Abort "Incomplete protocol has been deleted"
1729//              Endif
1730//              //assign filename (full path) to [3]
1731//              newProtocol[3] = V_GetFileNameFromPathNoSemi(S_filename)
1732               
1733               
1734        else
1735                //no MASK desired
1736                newProtocol[3] = "none"
1737        Endif   
1738       
1739        //absolute scaling
1740       
1741        //////////////////////////
1742        //ABS parameters stored as keyword=value string
1743        DoAlert 1,"Do you want absolute scaling?"
1744        if(V_flag == 1)         //1=yes
1745                //missing param - prompt for values, put in semicolon-separated list
1746                Execute "V_AskForAbsoluteParams_Quest()"
1747                SVAR absStr =  root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr
1748                newProtocol[4] = absStr
1749        else
1750                //no absolute scaling desired
1751                newProtocol[4] = "none"
1752        Endif   
1753       
1754        //type of average, plot?, auto/manual naming/saving... put in semicolon separated string
1755        //of KEY=<value> format for easy parsing
1756        //Kewords are: AVTYPE,PHI,DPHI,PLOT,SAVE,NAME,SIDE,WIDTH
1757        //note that AVTYPE,NAME,SIDE have string values, others have numerical values
1758        ///////////////////////
1759        DoAlert 1,"Do you want to average your data to I vs. q?"
1760        if(V_flag == 1)         //1=yes
1761                String/G root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr = ""
1762                Execute "V_GetAvgInfo()"                //will put up missing paramter dialog and do all the work
1763                //:gAvgInfo is reset by the Proc(), copy this string tot he protocol
1764                SVAR tempStr=root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr
1765               
1766                //get a file path for saving files, if desired
1767                /////no - save files to the same data folder as the one with the raw data
1768                //then only one path to manage.
1769                //String yesNo = StringByKey("SAVE", tempStr,"=", ";")
1770                //if(cmpstr("Yes",yesNo) == 0)          //0=yes
1771                        //NewPath/C/M="Select Folder"/O Save_path               //Save_path is the symbolic path
1772                //Endif
1773
1774                newProtocol[5] = tempStr
1775                KillStrings/Z tempStr
1776        else
1777                //no averaging desired
1778                newProtocol[5] = "AVTYPE=none"
1779        Endif
1780       
1781        //returns the name of the newly created (= currently in use) protocol wave through a global
1782        String/G root:Packages:NIST:VSANS:Globals:Protocols:gProtoStr = newProtoStr
1783       
1784        //reset the panel based on the protocol textwave (currently a string)
1785        V_ResetToSavedProtocol(newProtoStr)
1786       
1787        SetDataFolder root:
1788       
1789        return(0)
1790End
1791
1792
1793// TODO
1794// -- this function may not work properly for VSANS, but I haven't tested it yet
1795// -- I'd rather have some sort of display to show the current content of the WORK folders
1796//
1797// -- the global string fileList does not exist, so this will always fail and return zero
1798//
1799//
1800//function to check the work files (to see what's already there)
1801//and compare that with the files that are supposed to be there, according to the
1802//current protocol (to save unnecessary time re-loading files)
1803//
1804//the "type" folder is checked for all files in the list req(ested)Files
1805//note that the list of files is a full path:name;ver, while the
1806//fileList in the folder is just the name (or a list of names)
1807//
1808//returns 0 false, if files are NOT present
1809//or 1 = true, yes, the files are there as requested
1810//
1811Function V_AreFilesThere(type,reqFiles)
1812        String type,reqFiles
1813       
1814        //in general, reqFiles is a list of full paths to files - which MAY include semicolon version numbers
1815        //reqFiles MUST be constructed with COMMAS as list separators, to avoid disaster
1816        //when the version numbers are interpreted as filenames
1817       
1818        //get the number of files requested
1819        Variable nReq,nCur,match,ii
1820        nReq = ItemsInList(reqFiles,",")
1821       
1822        //get the name of the file currently in BGD - in the global fileList
1823        //fileList has NAMES ONLY - since it was derived from the file header
1824        String testStr
1825        testStr = "root:Packages:NIST:"+type+":fileList"
1826        if(Exists(testStr) == 2)                //2 if string variable exists
1827                SVAR curFiles = $testStr
1828        else
1829                //no files currently in type folder, return zero
1830                Return (0)
1831        Endif
1832        //get the number of files already in folder
1833        nCur = ItemsInList(curFiles,";")
1834        If(nCur != nReq)
1835                Return (0)              //quit now, the wrong number of files present
1836        Endif
1837        //right number of files... are the names right...
1838        //check for a match (case-sensitive!!) of each requested file in the curFile string
1839        //need to extract filenames from reqFiles, since they're the full path and name
1840       
1841        ii=0
1842        do
1843                testStr = StringFromList(ii,reqFiles,",")       //testStr is the Nth full path and filename
1844                //testStr = GetFileNameFromPathNoSemi(testStr)  //testStr will now be just the filename
1845                match = stringmatch(curFiles,testStr)
1846                If(!match)
1847                        Return (0)              //req file was not found in curFile list - get out now
1848                Endif
1849                ii+=1
1850        while(ii<nreq)
1851       
1852        Return (1)              //indicate that files are OK, no changes needed
1853End
1854
1855
1856//
1857//will add the files specified in the protocol to the "type" folder
1858//will add multiple files together if more than one file is requested
1859//(list is a comma delimited list of filenames, with NO path information)
1860//
1861// This routine NOW DOES check for the possibility that the filenames may have ";vers" from the
1862// VAX - data should be picked up from Charlotte, where it won't have version numbers.
1863//
1864Function V_AddFilesInList(type,list)
1865        String type,list
1866       
1867        //type is the work folder to put the data into, and list is a COMMA delimited list of paths/names
1868        Variable num,ii,err=0,refNum
1869        String filename,pathStr=""
1870        PathInfo catPathName                    //this is where the files are
1871        pathstr=S_path
1872       
1873        num = ItemsInList(list,",")             // comma delimited list
1874       
1875        ii=0
1876        do
1877                //FindValidFilename only needed in case of vax version numbers
1878                filename = pathStr + V_FindValidFilename(StringFromList(ii,list,","))
1879                Open/Z/R refnum as filename
1880                if(V_flag != 0)         //file not found
1881                        //Print "file not found AddFilesInList()"
1882                        //Print filename
1883                        err = 1
1884                        return(err)
1885                Endif
1886                Close refnum            //file was found and opened, so close it
1887               
1888//              Abort "Find equivalent to ReadHeaderAndData(filename)"
1889//              ReadHeaderAndData(filename)
1890                err = V_LoadHDF5Data(filename,"RAW")   
1891               
1892                if(ii == 0)
1893                        //first pass, wipe out the old contents of the work file
1894                        err =  V_Raw_to_work(type)
1895                else
1896                        err = V_Add_raw_to_work(type)
1897                Endif
1898                ii+=1
1899        while(ii<num)
1900        return(err)
1901End
1902
1903//function will reduce a sample file (or ask for file(s))
1904//using the protocol named as "protoStr" in the Protocols subfolder
1905//samStr is the file(s) or "ask" to force prompt
1906//sequentially proceeds through flowchart, doing reduction steps as needed
1907//show Schematic to debug what steps/values were used
1908//
1909//function is long, but straightforward logic
1910//
1911Function V_ExecuteProtocol(protStr,samStr)
1912        String protStr,samStr
1913        //protStr is the full path to the selected protocol wave
1914        //samStr is either "ask" or the name ONLY ofthe desired sample data file(s) (NO PATH)
1915        WAVE/T prot = $protStr
1916        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
1917       
1918        Variable filesOK,err,notDone
1919        String activeType, msgStr, junkStr, pathStr=""
1920        PathInfo catPathName                    //this is where the files are
1921        pathStr=S_path
1922       
1923//      NVAR useXMLOutput = root:Packages:NIST:gXML_Write
1924       
1925        //Parse the instructions in the prot wave
1926        //0 - bkg
1927        //1 - emp
1928        //2 - div
1929        //3 - mask
1930        //4 - abs params c2-c5
1931        //5 - average params
1932        //6 = DRK file (**out of sequence)
1933        //7 = beginning trim points
1934        //8 = end trim points
1935        //9 = collimation type for reduced data
1936        //10 = unused
1937        //11 = unused
1938
1939//////////////////////////////
1940// DIV
1941//////////////////////////////
1942// for VSANS, DIV is used on each data file as it is converted to WORK, so it needs to be
1943//  the first thing in place, before any data or backgrounds are loaded
1944
1945        //check for work.div file (prot[2])
1946        //load in if needed
1947        // no math is done here, DIV is applied as files are converted to WORK (the first operation in VSANS)
1948        //
1949
1950        // save the state of the DIV preference
1951        NVAR gDoDIVCor = root:Packages:NIST:VSANS:Globals:gDoDIVCor
1952        Variable saved_gDoDIVCor = gDoDIVCor
1953       
1954        err = V_Proto_LoadDIV(prot[2])
1955       
1956        if(err)
1957                SetDataFolder root:
1958                Abort "No file selected, data reduction aborted"
1959        endif
1960
1961//////////////////////////////
1962// SAM
1963//////////////////////////////
1964
1965// TODO:
1966// -- currently does not allow adding RAW data files together, so no parsing is done
1967//       -- NOTE detector corrections (including DIV) are done at the V_Raw_to_Work() step
1968//   So if the DIV is not part of the protocol, be sure to set/reset the global preference
1969//
1970        //prompt for sam data => read raw data, add to sam folder
1971        //or parse file(s) from the input paramter string
1972        activeType = "SAM"
1973        msgStr = "Select sample data"
1974       
1975        err = V_Proto_LoadFile(samStr,activeType,msgStr)
1976        if(err)
1977                PathInfo/S catPathName
1978                SetDataFolder root:
1979                Abort "No file selected, data reduction aborted"
1980        endif
1981       
1982        // TODO
1983        // -- this may not be the most reliable way to pass the file name (for naming of the saved file later)
1984        SVAR file_name = root:file_Name
1985        String samFileLoaded = file_name                //keep a copy of the sample file loaded
1986       
1987        //always update
1988        V_UpdateDisplayInformation(ActiveType)
1989
1990
1991// TODO -- the logic here is flawed
1992// check that the SAM file is of the same configuration as BGD or EMP, if they are used
1993// need to be able to handle all of the permutations AND catch the "ask" cases
1994       
1995        Variable filesMatch=1           //assume OK
1996       
1997        if(cmpstr("none",prot[0])==0 || cmpstr("ask",prot[0])==0)
1998                // BGD not identified, try EMP.
1999                if(cmpstr("none",prot[1])==0 || cmpstr("ask",prot[1])==0)
2000                        // EMP not identified either, no mismatch possible
2001                else
2002                        // compare to EMP
2003                        filesMatch = V_RawFilesMatchConfig(samFileLoaded,StringFromList(0,prot[1],","))
2004                endif
2005        else
2006                // BGD is identified, compare
2007                filesMatch = V_RawFilesMatchConfig(samFileLoaded,StringFromList(0,prot[0],","))
2008        endif
2009
2010        if(filesMatch == 0)
2011                Abort "SAM data is not the same configuration as the protocol."
2012                SetDataFolder root:
2013        endif           
2014
2015
2016
2017//////////////////////////////
2018// BGD
2019//////////////////////////////
2020       
2021        //check for BGD file  -- "ask" might not fail - "ask?" will - ? not allowed in VAX filenames
2022        // add if needed
2023        //use a "case" statement
2024        msgStr = "Select background file"
2025        activeType = "BGD"
2026       
2027        err = V_Proto_LoadFile(prot[0],activeType,msgStr)
2028        if(err)
2029                PathInfo/S catPathName
2030                SetDataFolder root:
2031                Abort "No file selected, data reduction aborted"
2032        endif
2033
2034//      //Loader is in charge of updating, since it knows if data was loaded
2035//      V_UpdateDisplayInformation(ActiveType)
2036
2037
2038//////////////////////////////
2039// EMP
2040////////////////////////////// 
2041       
2042        //check for emp file (prot[1])
2043        // add if needed
2044        msgStr = "Select empty cell data"
2045        activeType = "EMP"
2046       
2047        err = V_Proto_LoadFile(prot[1],activeType,msgStr)
2048        if(err)
2049                PathInfo/S catPathName
2050                SetDataFolder root:
2051                Abort "No file selected, data reduction aborted"
2052        endif
2053
2054//      //Loader is in charge of updating, since it knows if data was loaded
2055//      V_UpdateDisplayInformation(ActiveType)
2056
2057
2058//////////////////////////////
2059// CORRECT
2060//////////////////////////////
2061
2062        //do the CORRECT step based on the answers to emp and bkg subtraction
2063        //by setting the proper"mode"
2064        //1 = both emp and bgd subtraction
2065        //2 = only bgd subtraction
2066        //3 = only emp subtraction
2067        //4 = no subtraction
2068        //additional modes 091301
2069        //11 = emp, bgd, drk
2070        //12 = bgd and drk
2071        //13 = emp and drk
2072        //14 = no subtractions
2073        //work.drk is from proto[6]
2074        //
2075        //subtracting just the DRK data is NOT an option - it doesnt' really make any physical sense
2076        // - in this case, DRK is skipped (equivalent to mode==4)
2077        // automatically accounts for attenuators given the lookup tables and the
2078        //desired subtractions
2079        //Attenuator lookup tables are alredy implemented (NG1 = NG7)
2080        //
2081
2082
2083/////// DRK is SKIPPED
2084       
2085//      //read in the DRK data if necessary
2086//      //only one file, assumed to be RAW data
2087//      //
2088//      String fname="",drkStr=""
2089//      drkStr=StringByKey("DRK",prot[6],"=",",")
2090//      if(cmpstr(drkStr,"none") != 0)
2091//              err = ReadHeaderAndData( (pathStr+drkStr) )
2092//              if(err)
2093//                      PathInfo/S catPathName
2094//                      Abort "reduction sequence aborted"
2095//              endif
2096//              err = V_Raw_to_Work_NoNorm("DRK")
2097//      endif
2098
2099        //dispatch to the proper "mode" of Correct()
2100//      V_Dispatch_to_Correct(bgdStr,empStr,drkStr)
2101        V_Dispatch_to_Correct(prot[0],prot[1],prot[6])
2102       
2103        if(err)
2104                PathInfo/S catPathName
2105                SetDataFolder root:
2106                Abort "error in Correct, called from executeprotocol, normal cor"
2107        endif
2108        activeType = "COR"
2109
2110// always update - COR will always be generated
2111        V_UpdateDisplayInformation(ActiveType)         
2112
2113
2114//////////////////////////////
2115//  ABSOLUTE SCALE
2116//////////////////////////////
2117
2118        err = V_Proto_ABS_Scale(prot[4],activeType)             //activeType is pass-by-reference and updated IF ABS is used
2119       
2120        if(err)
2121                SetDataFolder root:
2122                Abort "Error in V_Absolute_Scale(), called from V_ExecuteProtocol"
2123        endif
2124//      activeType = "ABS"
2125
2126
2127//////////////////////////////
2128// MASK
2129//////////////////////////////
2130//
2131// DONE
2132//              x- fill in the "ask" step
2133//  x- none is OK, except if the kill fails for any reason
2134// x- the regular case of the file name specified by the protocol works correctly
2135// x- don't create a null mask if not used, it will handle the error and print out that the mask is missing
2136//
2137//mask data if desired (mask is applied when the data is binned to I(q)) and is
2138//not done explicitly here
2139       
2140        //check for mask
2141        //doesn't change the activeType
2142        V_Proto_ReadMask(prot[3])
2143
2144       
2145//////////////////////////////
2146// AVERAGING
2147//////////////////////////////
2148
2149        // average/save data as specified
2150        //Parse the keyword=<Value> string as needed, based on AVTYPE
2151       
2152        //average/plot first
2153        String av_type = StringByKey("AVTYPE",prot[5],"=",";")
2154        If(cmpstr(av_type,"none") != 0)
2155                If (cmpstr(av_type,"")==0)              //if the key could not be found... (if "ask" the string)
2156                        //get the averaging parameters from the user, as if the set button was hit in the panel
2157                        V_SetAverageParamsButtonProc("dummy")           //from "ProtocolAsPanel"
2158                        SVAR tempAveStr = root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr
2159                        av_type = StringByKey("AVTYPE",tempAveStr,"=",";")
2160                else
2161                        //there is info in the string, use the protocol
2162                        //set the global keyword-string to prot[5]
2163                        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAvgInfoStr = prot[5]
2164                Endif
2165        Endif
2166
2167
2168        String detGroup = StringByKey("DETGROUP",prot[5],"=",";")               //only for annular, null if not present
2169
2170       
2171//convert the folder to linear scale before averaging, then revert by calling the window hook
2172// (not needed for VSANS, data is always linear scale)
2173
2174//
2175// (DONE)
2176// -x this generates a "Bin Type Not Found" error if reducing only to a 2D level (like for DIV)
2177//              because binTypeStr is null
2178        String binTypeStr = StringByKey("BINTYPE",prot[5],"=",";")
2179        // plotting is not really necessary, and the graph may not be open - so skip for now?
2180        Variable binType
2181        // only get the binning type if user asks for averaging
2182        If(cmpstr(av_type,"none") != 0)
2183                binType = V_BinTypeStr2Num(binTypeStr)
2184                if(binType == 0)
2185                                Abort "Binning mode not found in V_QBinAllPanels() "// when no case matches
2186                endif
2187        endif
2188
2189
2190// identify the collimation type
2191// this will be a string used to determine how the resolution information is to be calculated
2192// and written to the reduced data file
2193//
2194// possible values are:
2195//
2196// pinhole
2197// pinhole_whiteBeam
2198// narrowSlit
2199// narrowSlit_whiteBeam
2200// convergingPinholes
2201//
2202
2203        String collimationStr
2204        collimationStr = V_IdentifyCollimation(activeType)
2205       
2206
2207////////////////////////////////////////
2208// DISPATCH TO AVERAGING
2209/////////////////////////////////////////
2210//
2211// TODO:
2212// -- do I calculate the proper resolution here?, YES, I've already decoded the binning type
2213//   and the averaging type has been specified by the protocol.
2214//
2215// so currently, the resolution is calculated every time that the data is averaged (in VC_fDoBinning_QxQy2D)
2216//
2217// -- if I calculate the resolution here, then the Trimming routines must be updated
2218//    to trim the resolution waves also. This will work for the columns present in
2219//    pinhole resolution, but anything using the matrix method - it won't work - and I'll need
2220//    a different solution
2221//
2222
2223        V_Proto_doAverage(prot[5],av_type,activeType,binType,collimationStr)
2224
2225
2226
2227////////////////////////
2228// PLOT THE DATA
2229////////////////////////
2230
2231        V_Proto_doPlot(prot[5],av_type,activeType,binType,detGroup)
2232       
2233       
2234
2235////////////////////   
2236// SAVE THE DATA
2237////////////////////
2238
2239//
2240// x- how do I get the sample file name?
2241//    local variable samFileLoaded is the file name loaded (contains the extension)
2242//
2243// V_Proto_SaveFile(avgStr,activeType,samFileLoaded,av_type,binType,detGroup,trimBegStr,trimEndStr)
2244
2245        prot[9] = collimationStr
2246
2247        V_Proto_SaveFile(prot[5],activeType,samFileLoaded,av_type,binType,detGroup,prot[7],prot[8])
2248       
2249//////////////////////////////
2250// DONE WITH THE PROTOCOL
2251////////////////////////////// 
2252       
2253        // reset any global preferences that I had changed
2254        gDoDIVCor = saved_gDoDIVCor
2255       
2256       
2257        Return(0)
2258End
2259
2260
2261
2262
2263
2264//missing parameter dialog to solicit the 4 absolute intensity parameters
2265//from the user
2266//values are passed back as a global string variable (keyword=value)
2267//
2268Proc V_AskForAbsoluteParams(c2,c3,c4,c5,I_err)
2269        Variable c2=1,c3=1,c4=1e8,c5=1,I_err=1
2270        Prompt c2, "Standard Transmission"
2271        Prompt c3, "Standard Thickness (cm)"
2272        Prompt c4, "I(0) from standard fit (normalized to 1E8 monitor cts)"
2273        Prompt c5, "Standard Cross-Section (cm-1)"
2274        Prompt I_err, "error in I(q=0) (one std dev)"
2275       
2276        String/G root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr=""
2277       
2278        root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr = "TSTAND="+num2str(c2)
2279        root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr +=  ";" + "DSTAND="+num2str(c3)
2280        root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr +=  ";" + "IZERO="+num2str(c4)
2281        root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr +=  ";" + "XSECT="+num2str(c5)
2282        root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr +=  ";" + "SDEV="+num2str(I_err)
2283       
2284End
2285
2286
2287//
2288// DONE
2289// x- fill in all of the functionality for calculation from direct beam
2290//  and verify that the calculations are numerically correct
2291//
2292//asks the user for absolute scaling information. the user can either
2293//enter the necessary values in manually (missing parameter dialog)
2294//or the user can select an empty beam file from a standard open dialog
2295//if an empty beam file is selected, the "kappa" value is automatically calculated
2296//in either case, the global keyword=value string is set.
2297//
2298Function V_AskForAbsoluteParams_Quest()
2299       
2300        Variable err,loc,refnum
2301       
2302        Variable ii
2303       
2304        Variable kappa=1
2305        Variable kappa_err
2306               
2307        //get the necessary variables for the calculation of kappa
2308        Variable countTime,monCnt,sdd,pixel_x,pixel_y
2309        String detStr,junkStr,errStr
2310
2311        Variable empAttenFactor,        emp_atten_err
2312       
2313        //get the XY box and files
2314        Variable x1,x2,y1,y2,emptyCts,empty_ct_err
2315        String emptyFileName,tempStr,divFileName,detPanel_toSum
2316               
2317        //ask user if he wants to use a transmision file for absolute scaling
2318        //or if he wants to enter his own information
2319        err = V_UseStdOrEmpForABS()
2320        //DoAlert 1,"<Yes> to enter your own values, <No> to select an empty beam flux file"
2321        If ( err==1 )
2322                //secondary standard selected, prompt for values
2323                Execute "V_AskForAbsoluteParams()"              //missing parameters
2324        else
2325                //empty beam flux file selected, prompt for file, and use this to calculate KAPPA
2326
2327                // DONE
2328                // x- need an empty beam file name
2329                //
2330                Prompt emptyFileName,"Empty Beam File",popup,V_PickEMPBeamButton("")
2331                DoPrompt "Select File",emptyFileName
2332                if (V_Flag)
2333                        return 0                                                                        // user canceled
2334                endif
2335
2336                // DONE
2337                // x- need panel
2338                // x- now, look for the value in the file, if not there, ask
2339               
2340                detPanel_toSum = V_getReduction_BoxPanel(emptyFileName)
2341                if(strlen(detPanel_toSum) > 2)
2342                        // it's the error message
2343                        Prompt detPanel_toSum,"Panel with Direct Beam",popup,ksDetectorListAll
2344                        DoPrompt "Select Panel",detPanel_toSum
2345                        if (V_Flag)
2346                                return 0                                                                        // user canceled
2347                        endif
2348                endif
2349               
2350                //need the detector sensitivity file - make a guess, allow to override
2351                Prompt divFileName,"DIV File",popup,V_GetDIVList()
2352                DoPrompt "Select File",divFileName
2353                if (V_Flag)
2354                        return 0                                                                        // user canceled
2355                endif
2356                V_LoadHDF5Data(divFileName,"DIV")
2357
2358
2359                WAVE xyBoxW = V_getBoxCoordinates(emptyFileName)
2360
2361               
2362                // load in the data, and use all of the corrections, especially DIV
2363                // (be sure the corrections are actually set to "on", don't assume that they are)
2364                // save preferences for file loading
2365                Variable savDivPref,savSAPref
2366                NVAR gDoDIVCor = root:Packages:NIST:VSANS:Globals:gDoDIVCor
2367                savDivPref = gDoDIVCor
2368                NVAR gDoSolidAngleCor = root:Packages:NIST:VSANS:Globals:gDoSolidAngleCor
2369                savSAPref = gDoSolidAngleCor
2370               
2371                // set local preferences
2372                gDoDIVCor = 1
2373                gDoSolidAngleCor = 1
2374               
2375                V_LoadAndPlotRAW_wName(emptyFileName)
2376                // convert raw->SAM
2377//              V_Raw_to_work("SAM")
2378//              V_UpdateDisplayInformation("SAM")       
2379                V_UpdateDisplayInformation("RAW")       
2380               
2381                // do the DIV correction
2382                if (gDoDIVCor == 1)
2383                        // need extra check here for file existence
2384                        // if not in DIV folder, load.
2385                        // if unable to load, skip correction and report error (Alert?) (Ask to Load?)
2386                        Print "Doing DIV correction"// for "+ detStr
2387                        for(ii=0;ii<ItemsInList(ksDetectorListAll);ii+=1)
2388                                detStr = StringFromList(ii, ksDetectorListAll, ";")
2389                                Wave w = V_getDetectorDataW("RAW",detStr)
2390                                Wave w_err = V_getDetectorDataErrW("RAW",detStr)
2391                               
2392                                V_DIVCorrection(w,w_err,detStr,"RAW")           // do the correction in-place
2393                        endfor
2394                else
2395                        Print "DIV correction NOT DONE"         // not an error since correction was unchecked
2396                endif
2397               
2398                // and determine box sum and error
2399                // store these locally
2400               
2401
2402                // x- need to get the panel string for the sum.
2403                // x- the detector string is currently hard-wired
2404//              detStr = "MR"
2405
2406                emptyCts = V_SumCountsInBox(xyBoxW[0],xyBoxW[1],xyBoxW[2],xyBoxW[3],empty_ct_err,"RAW",detPanel_toSum)
2407
2408                Print "empty counts = ",emptyCts
2409                Print "empty err/counts = ",empty_ct_err/emptyCts
2410
2411//
2412                // x- get all of the proper values for the calculation
2413                // -x currently the attenuation is incorrect
2414                //   such that kappa_err = 1*kappa
2415                // x- verify the calculation (no solid angle needed??)
2416                               
2417                // get the attenuation factor for the empty beam
2418                //  -- the attenuation is not written by NICE to the file
2419                //  so I need to calculate it myself from the tables
2420                //
2421//              empAttenFactor = V_getAttenuator_transmission(emptyFileName)
2422//              emp_atten_err = V_getAttenuator_trans_err(emptyFileName)
2423                empAttenFactor = V_CalculateAttenuationFactor(emptyFileName)
2424                emp_atten_err = V_CalculateAttenuationError(emptyFileName)
2425                               
2426                countTime = V_getCount_time(emptyFileName)
2427               
2428                // TODO
2429                // -- not sure if this is the correct monitor count to use
2430                monCnt = V_getBeamMonNormData("RAW")
2431               
2432                pixel_x = V_getDet_x_pixel_size("RAW",detPanel_toSum)
2433                pixel_x /= 10           //convert mm to cm, since sdd in cm
2434                pixel_y = V_getDet_y_pixel_size("RAW",detPanel_toSum)
2435                pixel_y /= 10           //convert mm to cm, since sdd in cm
2436                sdd = V_getDet_ActualDistance("RAW",detPanel_toSum)
2437               
2438//              kappa = emptyCts/countTime/empAttenFactor*1.0e8/(monCnt/countTime)*(pixel_x*pixel_y/sdd^2)
2439                kappa = emptyCts/countTime/empAttenFactor*1.0e8/(monCnt/countTime)
2440               
2441               
2442                kappa_err = (empty_ct_err/emptyCts)^2 + (emp_atten_err/empAttenFactor)^2
2443                kappa_err = sqrt(kappa_err) * kappa
2444               
2445                // x- set the parameters in the global string
2446                junkStr = num2str(kappa)
2447                errStr = num2Str(kappa_err)
2448                Execute "V_AskForAbsoluteParams(1,1,"+junkStr+",1,"+errStr+")"          //no missing parameters, no dialog
2449               
2450
2451                Printf "Kappa was successfully calculated as = %g +/- %g (%g %)\r",kappa,kappa_err,(kappa_err/kappa)*100
2452       
2453                // restore preferences on exit
2454                gDoDIVCor = savDivPref
2455                gDoSolidAngleCor = savSAPref
2456
2457        Endif
2458       
2459End
2460
2461Function V_UserSelectBox_Continue(ctrlName) :buttonControl
2462        String ctrlName
2463       
2464        DoWindow/K junkWindow           //kill panel
2465end
2466
2467Function V_SelectABS_XYBox(x1,x2,y1,y2)
2468        Variable &x1,&x2,&y1,&y2
2469       
2470        Variable err=0
2471       
2472        Variable/G root:V_marquee=1             //sets the sneaky bit to automatically update marquee coords
2473        Variable/G root:V_left,root:V_right,root:V_bottom,root:V_top    //must be global for auto-update
2474        DoWindow/F SANS_Data
2475        NewPanel/K=2 /W=(139,341,382,432) as "Select the primary beam"
2476        DoWindow/C junkWindow
2477        AutoPositionWindow/E/M=1/R=SANS_Data
2478       
2479        Drawtext 21,20 ,"Select the primary beam with the"
2480        DrawText 21,40, "marquee and press continue"
2481        Button button0,pos={80,58},size={92,20},title="Continue"
2482        Button button0,proc=V_UserSelectBox_Continue
2483       
2484        PauseForUser junkWindow,SANS_Data
2485       
2486        DoWindow/F SANS_Data
2487
2488        //GetMarquee left,bottom                        //not needed
2489        NVAR V_left=V_left
2490        NVAR V_right=V_right
2491        NVAR V_bottom=V_bottom
2492        NVAR V_top=V_top
2493       
2494        x1 = V_left
2495        x2 = V_right
2496        y1 = V_bottom
2497        y2 = V_top
2498//      Print "new values,before rounding = ",x1,x2,y1,y2
2499
2500// TODO -- replace this call
2501//      KeepSelectionInBounds(x1,x2,y1,y2)
2502        //Print "new values = ",x1,x2,y1,y2
2503       
2504        KillVariables/Z root:V_Marquee,root:V_left,root:V_right,root:V_bottom,root:V_top
2505        if((x1-x2)==0 || (y1-y2)==0)
2506                err=1
2507        endif
2508        return(err)
2509End
2510
2511Function V_UseStdOrEmpForABS()
2512               
2513        NewPanel/K=2 /W=(139,341,402,448) as "Absolute Scaling"
2514        DoWindow/C junkABSWindow
2515        ModifyPanel cbRGB=(57346,65535,49151)
2516        SetDrawLayer UserBack
2517        SetDrawEnv fstyle= 1
2518        DrawText 21,20,"Method of absolute calibration"
2519        Button button0,pos={52,33},size={150,20},proc=V_UserSelectABS_Continue,title="Empty Beam Flux"
2520        Button button1,pos={52,65},size={150,20},proc=V_UserSelectABS_Continue,title="Secondary Standard"
2521       
2522        PauseForUser junkABSWindow
2523        NVAR val = root:Packages:NIST:VSANS:Globals:tmpAbsVal
2524        return(val)
2525End
2526
2527//returns 0 if button0 (empty beam flux)
2528// or 1 if secondary standard
2529Function V_UserSelectABS_Continue(ctrlName) :buttonControl
2530        String ctrlName
2531       
2532        variable val=0
2533        If(cmpstr(ctrlName,"button0")==0)
2534                val=0           
2535        else
2536                val=1
2537        endif
2538//      print "val = ",ctrlName,val
2539        Variable/G root:Packages:NIST:VSANS:Globals:tmpAbsVal = val
2540        DoWindow/K junkABSWindow                //kill panel
2541        return(0)
2542end
2543
2544
2545Function V_TrimDataProtoButton(ctrlName) :buttonControl
2546        String ctrlName
2547       
2548        Execute "V_CombineDataGraph()"
2549        return(0)
2550end
2551
2552//
2553// export protocol to a data file
2554//
2555//
2556Function V_ExportFileProtocol(ctrlName) : ButtonControl
2557        String ctrlName
2558// get a list of protocols
2559        String Protocol=""
2560        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2561        Prompt Protocol "Pick A Protocol",popup, V_DeletableProtocols()
2562        DoPrompt "Pick A Protocol to Export",Protocol
2563        if(V_flag==1)
2564                //Print "user cancel"
2565                SetDatafolder root:
2566                return(1)
2567        endif
2568
2569        String fileName = V_DoSaveFileDialog("pick the file to write to")
2570        print fileName
2571//     
2572        if(strlen(fileName) == 0)
2573                return(0)
2574        endif
2575
2576        V_writeReductionProtocolWave(fileName,$("root:Packages:NIST:VSANS:Globals:Protocols:"+Protocol) )
2577
2578        setDataFolder root:
2579        return(0)
2580
2581End
2582
2583//
2584// imports a protocol from a file on disk into the protocols folder
2585//
2586//
2587Function V_ImportFileProtocol(ctrlName) : ButtonControl
2588        String ctrlName
2589
2590//      SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2591
2592        String fullPath,fileName
2593        fullPath = DoOpenFileDialog("Import Protocol from file")
2594        print fullPath
2595//     
2596        if(strlen(fullPath) == 0)
2597                return(0)
2598        endif
2599       
2600        fileName = ParseFilePath(0, fullPath, ":", 1, 0)                        //just the file name at the end of the full path
2601       
2602        Wave/T tmpW = V_getReductionProtocolWave(fileName)
2603        if(numpnts(tmpW) == 0)
2604                DoAlert 0,"No protocol wave has been saved to this data file"
2605                return(0)
2606        endif
2607       
2608        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2609        String newName
2610        newName = CleanupName(fileName,0) + "_proto"
2611        duplicate/o tmpw $newName
2612       
2613       
2614        SetDataFolder root:
2615        return(0)
2616end
2617
2618
2619// currently not used - and not updated to 12 point protocols (5/2017)
2620//
2621//save the protocol as an IGOR text wave (.itx)
2622//
2623//
2624Function V_ExportProtocol(ctrlName) : ButtonControl
2625        String ctrlName
2626// get a list of protocols
2627        String Protocol=""
2628        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2629        Prompt Protocol "Pick A Protocol",popup, WaveList("*",";","")
2630        DoPrompt "Pick A Protocol to Export",Protocol
2631        if(V_flag==1)
2632                //Print "user cancel"
2633                SetDatafolder root:
2634                return(1)
2635        endif
2636//get the selection, or exit
2637        Wave/T pW= $protocol
2638        Make/O/T/N=13 tw
2639// save in the proper format (must write manually, for demo version)
2640        tw[0] = "IGOR"
2641        tw[1] = "WAVES/T \t"+protocol
2642        tw[2] = "BEGIN"
2643        tw[3,10] = "\t\""+pW[p-3]+"\""
2644        tw[11] = "END"
2645        tw[12] = "X SetScale/P x 0,1,\"\","+protocol+"; SetScale y 0,0,\"\","+protocol
2646       
2647        Variable refnum
2648        String fullPath
2649       
2650        PathInfo/S catPathName
2651        fullPath = DoSaveFileDialog("Export Protocol as",fname=Protocol,suffix="")
2652        If(cmpstr(fullPath,"")==0)
2653                //user cancel, don't write out a file
2654                Close/A
2655                Abort "no Protocol file was written"
2656        Endif
2657
2658        //actually open the file
2659        Open refNum as fullpath+".itx"
2660       
2661        wfprintf refnum, "%s\r", tw
2662        Close refnum
2663        //Print "all is well  ",protocol
2664        KillWaves/Z tw
2665        setDataFolder root:
2666        return(0)
2667
2668End
2669
2670
2671// currently not used - and not updated to 12 point protocols (5/2017)
2672//imports a protocol from disk into the protocols folder
2673//
2674// will overwrite existing protocols if necessary
2675//
2676//
2677Function V_ImportProtocol(ctrlName) : ButtonControl
2678        String ctrlName
2679
2680        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2681
2682        String fullPath
2683       
2684        PathInfo/S catPathName
2685        fullPath = DoOpenFileDialog("Import Protocol")
2686        If(cmpstr(fullPath,"")==0)
2687                //user cancel, don't write out a file
2688                Close/A
2689                Abort "no protocol was loaded"
2690        Endif
2691       
2692        LoadWave/O/T fullPath
2693       
2694        SetDataFolder root:
2695        return(0)
2696end
2697
2698
2699///////////////////////////////////////
2700//
2701// individual steps in the protocol
2702//
2703//////////////////////////////////////
2704
2705Function V_Proto_LoadDIV(protStr)
2706        String protStr
2707       
2708        String divFileName = "",junkStr="",pathStr=""
2709        PathInfo catPathName                    //this is where the files are
2710        pathStr=S_path
2711
2712        If(cmpstr("none",protStr)!=0)           // if !0, then there's a file requested
2713                If(cmpstr("ask",protStr) == 0)
2714                        //ask user for file
2715//                       junkStr = PromptForPath("Select the detector sensitivity file")
2716                        Prompt divFileName,"DIV File",popup,V_GetDIVList()
2717                        DoPrompt "Select File",divFileName
2718
2719                        If(strlen(divFileName)==0)
2720                                //
2721                                return(1)               //error
2722//                              SetDataFolder root:
2723//                              Abort "No file selected, data reduction aborted"
2724                        Endif
2725                        V_LoadHDF5Data(divFileName,"DIV")
2726                else
2727                        //assume it's a path, and that the first (and only) item is the path:file
2728                        //list processing is necessary to remove any final comma
2729                        junkStr = pathStr + StringFromList(0, protStr,"," )
2730                        V_LoadHDF5Data(junkStr,"DIV")
2731                Endif
2732       
2733        else
2734        // DIV step is being skipped
2735                NVAR gDoDIVCor = root:Packages:NIST:VSANS:Globals:gDoDIVCor
2736//              Variable saved_gDoDIVCor = gDoDIVCor
2737                gDoDIVCor = 0                   // protocol says to turn it off for now (reset later)
2738        Endif
2739       
2740        return(0)
2741End
2742
2743//
2744// fileStr is the file name (or list of names)
2745// activeType is the target work folder
2746// msgStr is the string for the prompt
2747//
2748Function V_Proto_LoadFile(fileStr,activeType,msgStr)
2749        String fileStr,activeType,msgStr
2750       
2751        Variable err,filesOK,notDone
2752       
2753        //Ask for Type file or parse
2754        do
2755                if((cmpstr(fileStr,"ask") == 0) || (cmpstr(fileStr,"")==0) )            //zero if strings are equal
2756                        err = V_LoadHDF5Data("","RAW")          //will prompt for file
2757                        if(err)
2758                                return(err)     //error
2759                                //PathInfo/S catPathName
2760                                //Abort "reduction sequence aborted"
2761                        endif
2762                        V_UpdateDisplayInformation("RAW")                       //display the new type of data that was loaded
2763                        err =  V_Raw_to_work(activeType)                //this is the first file (default)
2764                        //Ask for another TYPE file
2765                        do
2766                                DoAlert 1,"Do you want to add another "+activeType+" file?"
2767                                if(V_flag == 1)         //yes
2768                                        err = V_LoadHDF5Data("","RAW")          //will prompt for file
2769                                        if(err)
2770                                                return(1)               //error
2771                                                //PathInfo/S catPathName
2772                                                //Abort "reduction sequence aborted"
2773                                        endif
2774                                        V_UpdateDisplayInformation("RAW")                       //display the new type of data that was loaded
2775                                        err = V_Add_raw_to_work(activeType)
2776                                        notDone = 1
2777                                else
2778                                        notDone = 0
2779                                endif
2780                        while(notDone)
2781                        //Loader is in charge of updating, since it knows if data was loaded
2782                        V_UpdateDisplayInformation(ActiveType)
2783                        break
2784                Endif
2785                //"none" is not an option - you always need a sample file - "none" will never return zero
2786                //if not "ask" AND not "none" then try to parse the filenames
2787                If((cmpstr(fileStr,"none") != 0) && (cmpstr(fileStr,"ask") != 0))
2788                        //filesOK = AreFilesThere(activeType,fileStr)           //return 1 if correct files are already there
2789                        filesOK = 0             // Feb 2008, always force a reload of files. Maybe slow, but always correct
2790                        if(!filesOK)
2791                                //add the correct file(s) to Type
2792                               
2793                                // TODO: only one file is allowed currently
2794                                err = V_AddFilesInList(activeType,fileStr)
2795                               
2796                                if(err)
2797                                        //Print "fileStr = ",fileStr
2798                                        DoAlert 0, fileStr + " file not found, reset file"
2799                                        return(err)             //error
2800                                Endif
2801                        Endif
2802                        //Loader is in charge of updating, since it knows if data was loaded
2803                        V_UpdateDisplayInformation(ActiveType)
2804                Endif
2805        While(0)
2806       
2807
2808       
2809        return(0)
2810End
2811
2812Function V_Dispatch_to_Correct(bgdStr,empStr,drkStr)
2813        String bgdStr,empStr,drkStr
2814       
2815        Variable mode=4,val,err
2816       
2817        if( (cmpstr("none",bgdStr) == 0)        && (cmpstr("none",empStr) == 0) )
2818        //no subtraction (mode = 4),
2819                mode = 4
2820        Endif
2821        If((cmpstr(bgdStr,"none") != 0) && (cmpstr(empStr,"none") == 0))
2822                //subtract BGD only
2823                mode=2
2824        Endif
2825        If((cmpstr(bgdStr,"none") == 0) && (cmpstr(empStr,"none") != 0))
2826                //subtract EMP only
2827                mode=3
2828        Endif
2829        If((cmpstr(bgdStr,"none") != 0) && (cmpstr(empStr,"none") != 0))
2830                // bkg and emp subtraction are to be done (BOTH not "none")
2831                mode=1
2832        Endif
2833//      activeType = "COR"
2834        //add in DRK mode (0= not used, 10 = used)
2835        // TODO: DRK has been de-activated for now
2836//      val = NumberByKey("DRKMODE",drkStr,"=","," )
2837//      mode += val
2838
2839//              print "mode = ",mode
2840
2841        err = V_Correct(mode)
2842        if(err)
2843                return(err)
2844//              SetDataFolder root:
2845//              Abort "error in Correct, called from executeprotocol, normal cor"
2846        endif
2847
2848//      //Loader is in charge of updating, since it knows if data was loaded
2849//      V_UpdateDisplayInformation("COR")
2850
2851       
2852        return(0)
2853End
2854
2855
2856
2857
2858Function V_Proto_ABS_Scale(absStr,activeType)
2859        String absStr,&activeType
2860       
2861        Variable c2,c3,c4,c5,kappa_err,err
2862        //do absolute scaling if desired
2863//              DoAlert 0,"Abs step incomplete"
2864
2865        if(cmpstr("none",absStr)!=0)
2866                if(cmpstr("ask",absStr)==0)
2867                        //get the params from the user
2868                        Execute "V_AskForAbsoluteParams_Quest()"
2869                        //then from the list
2870                        SVAR junkAbsStr = root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr
2871                        c2 = NumberByKey("TSTAND", junkAbsStr, "=", ";")        //parse the list of values
2872                        c3 = NumberByKey("DSTAND", junkAbsStr, "=", ";")
2873                        c4 = NumberByKey("IZERO", junkAbsStr, "=", ";")
2874                        c5 = NumberByKey("XSECT", junkAbsStr, "=", ";")
2875                        kappa_err = NumberByKey("SDEV", junkAbsStr, "=", ";")
2876                else
2877                        //get the parames from the list
2878                        c2 = NumberByKey("TSTAND", absStr, "=", ";")    //parse the list of values
2879                        c3 = NumberByKey("DSTAND", absStr, "=", ";")
2880                        c4 = NumberByKey("IZERO", absStr, "=", ";")
2881                        c5 = NumberByKey("XSECT", absStr, "=", ";")
2882                        kappa_err = NumberByKey("SDEV", absStr, "=", ";")
2883                Endif
2884                //get the sample trans and thickness from the activeType folder
2885                Variable c0 = V_getSampleTransmission(activeType)               //sample transmission
2886                Variable c1 = V_getSampleThickness(activeType)          //sample thickness
2887               
2888                err = V_Absolute_Scale(activeType,c0,c1,c2,c3,c4,c5,kappa_err)
2889                if(err)
2890                        return(err)
2891                        SetDataFolder root:
2892                        Abort "Error in V_Absolute_Scale(), called from V_ExecuteProtocol"
2893                endif
2894                activeType = "ABS"
2895                V_UpdateDisplayInformation(ActiveType)                  //update before breaking from loop
2896        Endif
2897       
2898        return(0)
2899End
2900
2901
2902Function V_Proto_ReadMask(maskStr)
2903        String maskStr
2904       
2905        //check for mask
2906        //doesn't change the activeType
2907        String mskFileName="",pathStr=""
2908        PathInfo catPathName                    //this is where the files are
2909        pathStr=S_path
2910               
2911        if(cmpstr("none",maskStr)!=0)
2912                If(cmpstr("ask",maskStr)==0)
2913                        //get file from user
2914                        // x- fill in the get file prompt, and handle the result
2915                        Prompt mskFileName,"MASK File",popup,V_PickMASKButton("")
2916                        DoPrompt "Select File",mskFileName
2917//                      if (V_Flag)
2918//                              return 0                                                                        // user cancelled
2919//                      endif
2920
2921                        If(strlen(mskFileName)==0)              //use cancelled
2922                                //if none desired, make sure that the old mask is deleted
2923                                KillDataFolder/Z root:Packages:NIST:VSANS:MSK:
2924                                NewDataFolder/O root:Packages:NIST:VSANS:MSK
2925                               
2926                                DoAlert 0,"No Mask file selected, data not masked"
2927                        else
2928                                //read in the file from the selection
2929                                V_LoadHDF5Data(mskFileName,"MSK")
2930                        Endif
2931                else
2932                        //just read it in from the protocol
2933                        //list processing is necessary to remove any final comma
2934                        mskFileName = pathStr + StringFromList(0, maskStr,"," )
2935                        V_LoadHDF5Data(mskFileName,"MSK")
2936                Endif
2937               
2938        else
2939                //if none desired, make sure that the old mask is deleted
2940// TODO
2941// x- clean out the data folder
2942// x- note that V_KillNamedDataFolder() points to RawVSANS, and won't work
2943// -- what happens if the kill fails? need error handling
2944//
2945                KillDataFolder/Z root:Packages:NIST:VSANS:MSK:
2946                NewDataFolder/O root:Packages:NIST:VSANS:MSK
2947
2948        Endif
2949       
2950        return(0)
2951End
2952
2953
2954Function V_Proto_doAverage(avgStr,av_type,activeType,binType,collimationStr)
2955        String avgStr,av_type,activeType
2956        Variable binType
2957        String collimationStr
2958       
2959       
2960        strswitch(av_type)      //dispatch to the proper routine to average to 1D data
2961                case "none":           
2962                        //still do nothing
2963                        // set binType and binTypeStr to bad flags
2964                        String binTypeStr = "none"
2965                        binType = -999999
2966                        break                   
2967
2968                case "Circular":
2969                        V_QBinAllPanels_Circular(activeType,binType,collimationStr)             // this does a default circular average
2970                        break
2971                       
2972                case "Sector":
2973//                      CircularAverageTo1D(activeType)
2974                        break
2975                case "Sector_PlusMinus":
2976//                      Sector_PlusMinus1D(activeType)
2977                        break
2978                case "Rectangular":
2979//                      RectangularAverageTo1D(activeType)
2980                        break
2981
2982                case "Annular":
2983                        String detGroup = StringByKey("DETGROUP",avgStr,"=",";")
2984                        Variable qCtr_Ann = NumberByKey("QCENTER",avgStr,"=",";")
2985                        Variable qWidth = NumberByKey("QDELTA",avgStr,"=",";")
2986                        V_QBinAllPanels_Annular(activeType,detGroup,qCtr_Ann,qWidth)
2987                        break
2988
2989                case "Narrow_Slit":
2990                        V_QBinAllPanels_Slit(activeType,binType)                // this does a tall, narrow slit average
2991                        break
2992                       
2993                case "2D_ASCII":       
2994                        //do nothing
2995                        break
2996                case "QxQy_ASCII":
2997                        //do nothing
2998                        break
2999                case "PNG_Graphic":
3000                        //do nothing
3001                        break
3002                default:       
3003                        //do nothing
3004        endswitch
3005
3006       
3007        return(0)
3008End
3009
3010
3011
3012
3013
3014Function V_Proto_doPlot(plotStr,av_type,activeType,binType,detGroup)
3015        String plotStr,av_type,activeType
3016        Variable binType
3017        String detGroup
3018       
3019        String doPlot = StringByKey("PLOT",plotStr,"=",";")
3020       
3021        If( (cmpstr(doPlot,"Yes")==0) && (cmpstr(av_type,"none") != 0) )       
3022               
3023                strswitch(av_type)      //dispatch to the proper routine to PLOT 1D data
3024                        case "none":           
3025                                //still do nothing
3026                                break                   
3027
3028                        case "Circular":
3029                                V_PlotData_Panel()              //this brings the plot window to the front, or draws it (ONLY)
3030                                V_Update1D_Graph(activeType,binType)            //update the graph, data was already binned                             
3031                                break
3032                        case "Sector":
3033        //                      CircularAverageTo1D(activeType)
3034                                break
3035                        case "Sector_PlusMinus":
3036        //                      Sector_PlusMinus1D(activeType)
3037                                break
3038                        case "Rectangular":
3039        //                      RectangularAverageTo1D(activeType)
3040                                break
3041
3042                        case "Annular":
3043                                V_Phi_Graph_Proc(activeType,detGroup)
3044                                break
3045
3046                        case "Narrow_Slit":
3047                        // these are the same plotting routines as for standard circular average
3048                                V_PlotData_Panel()              //this brings the plot window to the front, or draws it (ONLY)
3049                                V_Update1D_Graph(activeType,binType)            //update the graph, data was already binned
3050                                break
3051                       
3052                        case "2D_ASCII":       
3053                                //do nothing
3054                                break
3055                        case "QxQy_ASCII":
3056                                //do nothing
3057                                break
3058                        case "PNG_Graphic":
3059                                //do nothing
3060                                break
3061                        default:       
3062                                //do nothing
3063                endswitch
3064
3065        endif           // end of plotting switch
3066       
3067        return(0)
3068end
3069
3070
3071Function V_Proto_SaveFile(avgStr,activeType,samFileLoaded,av_type,binType,detGroup,trimBegStr,trimEndStr)
3072        String avgStr,activeType,samFileLoaded,av_type
3073        Variable binType
3074        String detGroup,trimBegStr,trimEndStr
3075       
3076        String fullpath = "", newfileName=""
3077        String saveType = StringByKey("SAVE",avgStr,"=",";")            //does user want to save data?
3078
3079        If( (cmpstr(saveType[0,2],"Yes")==0) && (cmpstr(av_type,"none") != 0) )         
3080                //then save
3081                newFileName = RemoveEnding(samFileLoaded,".nxs.ngv")
3082               
3083                //pick ABS or AVE extension
3084                String exten = activeType
3085                if(cmpstr(exten,"ABS") != 0)
3086                        exten = "AVE"
3087                endif
3088//              if(cmpstr(av_type,"2D_ASCII") == 0)
3089//                      exten = "ASC"
3090//              endif
3091//              if(cmpstr(av_type,"QxQy_ASCII") == 0)
3092//                      exten = "DAT"
3093//              endif
3094               
3095//              // add an "x" to the file extension if the output is XML
3096//              // currently (2010), only for ABS and AVE (1D) output
3097//              if( cmpstr(exten,"ABS") == 0 || cmpstr(exten,"AVE") == 0 )
3098//                      if(useXMLOutput == 1)
3099//                              exten += "x"
3100//                      endif
3101//              endif
3102                               
3103                //Path is catPathName, symbolic path
3104                //if this doesn't exist, a dialog will be presented by setting dialog = 1
3105                //
3106                Variable dialog = 0
3107
3108                PathInfo/S catPathName
3109                String item = StringByKey("NAME",avgStr,"=",";")                //Auto or Manual naming
3110                String autoname = StringByKey("AUTONAME",avgStr,"=",";")                //autoname -  will get empty string if not present
3111                If((cmpstr(item,"Manual")==0) || (cmpstr(newFileName,"") == 0))
3112                        //manual name if requested or if no name can be derived from header
3113                        fullPath = newfileName + "."+ exten //puts possible new name or null string in dialog
3114                        dialog = 1              //force dialog for user to enter name
3115                else
3116                        //auto-generate name and prepend path - won't put up any dialogs since it has all it needs
3117                        //use autoname if present
3118                        if (cmpstr(autoname,"") != 0)
3119                                fullPath = S_Path + autoname + "." +exten
3120                        else
3121                                fullPath = S_Path + newFileName+"." + exten
3122                        endif   
3123                Endif
3124                //
3125                strswitch(av_type)     
3126                        case "Annular":
3127                                V_fWrite1DAnnular("root:Packages:NIST:VSANS:",activeType,detGroup,newFileName+".phi")
3128                                Print "data written to:  "+ newFileName+".phi"
3129
3130                                break
3131
3132                        case "Circular":                //in SANS, this was the default, but is dangerous, so make it explicit here
3133                        case "Sector":          // TODO: this falls through - which luckily works for now...
3134                        case "Rectangular":             // TODO: this falls through - which luckily works for now...
3135                        case "Narrow_Slit":             // TODO: this falls through - which luckily works for now...
3136
3137// no VSANS support of XML output at this point                 
3138//                              if (useXMLOutput == 1)
3139//                                      WriteXMLWaves_W_Protocol(activeType,fullPath,dialog)
3140//                              else
3141//                                      WriteWaves_W_Protocol(activeType,fullpath,dialog)
3142//                              endif
3143//
3144                                if(cmpstr(saveType,"Yes - Concatenate")==0)
3145                                        V_Trim1DDataStr(activeType,binType,trimBegStr,trimEndStr)                       // x- passing null strings uses global or default trim values
3146
3147                                        V_ConcatenateForSave("root:Packages:NIST:VSANS:",activeType,"",binType)         // this removes q=0 point, concatenates, sorts
3148                               
3149//                                      prot[9] = collimationStr
3150                                       
3151                                        V_Write1DData("root:Packages:NIST:VSANS:",activeType,newFileName+"."+exten)             //don't pass the full path, just the name
3152                               
3153                                endif
3154                               
3155                                if(cmpstr(saveType,"Yes - Individual")==0)
3156                                        // remove the q=0 point from the back detector, if it's there
3157                                        // does not trim any other points from the data
3158                                        V_RemoveQ0_B(activeType)
3159                                        V_Write1DData_ITX("root:Packages:NIST:VSANS:",activeType,newFileName,binType)
3160                                endif
3161                                Print "data written to:  "+ newFileName+"."+exten
3162
3163                                break
3164       
3165                               
3166                                case "2D_ASCII":
3167//                              Fast2DExport(activeType,fullPath,dialog)
3168                                break
3169                        case "QxQy_ASCII":
3170//                              QxQy_Export(activeType,fullPath,dialog)
3171                                break
3172                        case "PNG_Graphic":
3173//                              SaveAsPNG(activeType,fullpath,dialog)
3174                                break
3175
3176                        default:
3177                                DoAlert 0, "av_type not found in dispatch to write file"
3178                endswitch
3179               
3180        Endif   
3181        return(0)
3182End
3183
3184
Note: See TracBrowser for help on using the repository browser.