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

Last change on this file was 1249, checked in by srkline, 2 years ago

minor changes - can't find the diff command in TortoiseSVN...

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