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

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

extensive changes to accomodate 1x1 binning of the HighRes? detector. It is implemented as a global flag. Currently only 4x4 and 1x1 are allowed. 1x1 has never been tested in reality, only simulated data - so my assumed dimensions may not be correct. look for TODOHIGHRES in the file for places that may need to be updated for different file dimensions. Testing of the simulated data is proving to be excruciatingly slow, but passable for a test. Speed optimization will be needed if this is the final solution. Memory management will also be an issue since every "copy" of the highRes matrix is enormous. Carry as few of these around as possible in the future to keep the experiment size to something reasonable.

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