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

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

added procedures to output QxQy_ASCII data. Each panel is output into its own file. Output format is the same as for 2D SANS data, including the 2D resolution function. However, reading the data back in with the SANS analysis macros currently does not redimension the data back to the matrix correctly as it assumes a square detector.

I will need to add the X and Y dimensions of each panel into the header, and then make use of these values when they are read in. Also, writing the QxQy? data is quick for the M and F panels ( 0.8 s) but is extremely slow for the back, High-res panel (120 s) since there are 1.1.E6 points there vs. 6144 pts. I'll need to find a way to speed this operation up.

File size: 106.2 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;QxQy_ASCII;"
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        gAbsStr = RemoveFromList("ask",gAbsStr)         //now that values are added, remove "ask"
2407
2408        SetDataFolder root:
2409End
2410
2411
2412//
2413// DONE
2414// x- fill in all of the functionality for calculation from direct beam
2415//  and verify that the calculations are numerically correct
2416//
2417//asks the user for absolute scaling information. the user can either
2418//enter the necessary values in manually (missing parameter dialog)
2419//or the user can select an empty beam file from a standard open dialog
2420//if an empty beam file is selected, the "kappa" value is automatically calculated
2421//in either case, the global keyword=value string is set.
2422//
2423//
2424// if isBack == 1, then the values are for the back panel
2425// AND there are different steps that must be done to subtract off
2426//  the read noise of the CCDs
2427//
2428Function V_AskForAbsoluteParams_Quest(isBack)   
2429        Variable isBack
2430       
2431        Variable err,loc,refnum
2432       
2433        Variable ii
2434       
2435        Variable kappa=1
2436        Variable kappa_err
2437               
2438        //get the necessary variables for the calculation of kappa
2439        Variable countTime,monCnt,sdd,pixel_x,pixel_y
2440        String detStr,junkStr,errStr
2441
2442        Variable empAttenFactor,        emp_atten_err
2443       
2444        //get the XY box and files
2445        Variable x1,x2,y1,y2,emptyCts,empty_ct_err
2446        String emptyFileName,tempStr,divFileName,detPanel_toSum
2447               
2448        //ask user if he wants to use a transmision file for absolute scaling
2449        //or if he wants to enter his own information
2450        err = V_UseStdOrEmpForABS()
2451        //DoAlert 1,"<Yes> to enter your own values, <No> to select an empty beam flux file"
2452        If ( err==1 )
2453                //secondary standard selected, prompt for values
2454                Execute "V_AskForAbsoluteParams()"              //missing parameters
2455        else
2456                //empty beam flux file selected, prompt for file, and use this to calculate KAPPA
2457
2458                // DONE
2459                // x- need an empty beam file name
2460                //
2461                Prompt emptyFileName,"Empty Beam File",popup,V_PickEMPBeamButton("")
2462                DoPrompt "Select File",emptyFileName
2463                if (V_Flag)
2464                        return 0                                                                        // user canceled
2465                endif
2466
2467                // DONE
2468                // x- need panel
2469                // x- now, look for the value in the file, if not there, ask
2470               
2471                detPanel_toSum = V_getReduction_BoxPanel(emptyFileName)
2472                if(strlen(detPanel_toSum) > 2)
2473                        // it's the error message
2474                        Prompt detPanel_toSum,"Panel with Direct Beam",popup,ksDetectorListAll
2475                        DoPrompt "Select Panel",detPanel_toSum
2476                        if (V_Flag)
2477                                return 0                                                                        // user canceled
2478                        endif
2479                endif
2480               
2481                //need the detector sensitivity file - make a guess, allow to override
2482                Prompt divFileName,"DIV File",popup,V_GetDIVList()
2483                DoPrompt "Select File",divFileName
2484                if (V_Flag)
2485                        return 0                                                                        // user canceled
2486                endif
2487                V_LoadHDF5Data(divFileName,"DIV")
2488
2489
2490                WAVE xyBoxW = V_getBoxCoordinates(emptyFileName)
2491
2492               
2493                // load in the data, and use all of the corrections, especially DIV
2494                // (be sure the corrections are actually set to "on", don't assume that they are)
2495                // save preferences for file loading
2496                Variable savDivPref,savSAPref
2497                NVAR gDoDIVCor = root:Packages:NIST:VSANS:Globals:gDoDIVCor
2498                savDivPref = gDoDIVCor
2499                NVAR gDoSolidAngleCor = root:Packages:NIST:VSANS:Globals:gDoSolidAngleCor
2500                savSAPref = gDoSolidAngleCor
2501               
2502                // set local preferences
2503                gDoDIVCor = 1
2504                gDoSolidAngleCor = 1
2505               
2506                V_LoadAndPlotRAW_wName(emptyFileName)
2507
2508                V_UpdateDisplayInformation("RAW")       
2509               
2510                // do the DIV correction
2511                if (gDoDIVCor == 1)
2512                        // need extra check here for file existence
2513                        // if not in DIV folder, load.
2514                        // if unable to load, skip correction and report error (Alert?) (Ask to Load?)
2515                        Print "Doing DIV correction"// for "+ detStr
2516                        for(ii=0;ii<ItemsInList(ksDetectorListAll);ii+=1)
2517                                detStr = StringFromList(ii, ksDetectorListAll, ";")
2518                                Wave w = V_getDetectorDataW("RAW",detStr)
2519                                Wave w_err = V_getDetectorDataErrW("RAW",detStr)
2520                               
2521                                V_DIVCorrection(w,w_err,detStr,"RAW")           // do the correction in-place
2522                        endfor
2523                else
2524                        Print "DIV correction NOT DONE"         // not an error since correction was unchecked
2525                endif
2526               
2527                // and determine box sum and error
2528                // store these locally
2529                Variable tmpReadNoiseLevel,tmpReadNoiseLevel_Err
2530
2531        // TODO: change the math to do the filtering and subtraction both here in this step,
2532        // then determine the patch sum and proper error propogation.
2533        //
2534        // just do the median filter now, do the background subtraction later on the patch
2535                if(isBack)
2536                        Wave w = V_getDetectorDataW("RAW","B")
2537                        NVAR gHighResBinning = root:Packages:NIST:VSANS:Globals:gHighResBinning
2538                        switch(gHighResBinning)
2539                                case 1:
2540                                        tmpReadNoiseLevel = kReadNoiseLevel_bin1                // a constant value
2541                                        tmpReadNoiseLevel_Err = kReadNoiseLevel_Err_bin1                // a constant value
2542                                       
2543                                        MatrixFilter /N=11 /P=1 median w                        //              /P=n flag sets the number of passes (default is 1 pass)
2544                                       
2545                                        Print "*** median noise filter 11x11 applied to the back detector (1 pass) ***"
2546                                        break
2547                                case 4:
2548                                        tmpReadNoiseLevel = kReadNoiseLevel_bin4                // a constant value
2549                                        tmpReadNoiseLevel_Err = kReadNoiseLevel_Err_bin4                // a constant value
2550                                                                       
2551                                        MatrixFilter /N=3 /P=3 median w                 //              /P=n flag sets the number of passes (default is 1 pass)
2552                                       
2553                                        Print "*** median noise filter 3x3 applied to the back detector (3 passes) ***"
2554                                        break
2555                                default:
2556                                        Abort "No binning case matches in V_AskForAbsoluteParams_Quest"
2557                        endswitch
2558                       
2559                endif
2560
2561                emptyCts = V_SumCountsInBox(xyBoxW[0],xyBoxW[1],xyBoxW[2],xyBoxW[3],empty_ct_err,"RAW",detPanel_toSum)
2562
2563                Print "empty counts = ",emptyCts
2564                Print "empty err/counts = ",empty_ct_err/emptyCts
2565
2566                // if it's the back panel, find the read noise to subtract
2567                // shift the marquee to the right to (hopefully) a blank spot
2568                Variable noiseCts,noiseCtsErr,delta,nPixInBox
2569                if(isBack)
2570
2571               
2572//                      delta = xyBoxW[1] - xyBoxW[0]
2573//                      noiseCts = V_SumCountsInBox(xyBoxW[1],xyBoxW[1]+delta,xyBoxW[2],xyBoxW[3],noiseCtsErr,"RAW",detPanel_toSum)
2574//
2575//                      print "average read noise per pixel = ",noiseCts/(xyBoxW[1]-xyBoxW[0])/(xyBoxW[3]-xyBoxW[2])
2576//                      Print "read noise counts = ",noiseCts
2577//                      Print "read noise err/counts = ",noiseCtsErr/noiseCts
2578//                     
2579//                      emptyCts -= noiseCts
2580//                      empty_ct_err = sqrt(empty_ct_err^2 + noiseCtsErr^2)
2581
2582
2583// Instead, use the defined constant values             
2584//              kReadNoiseLevel
2585//              kReadNoiseLevel_Err
2586//
2587                        nPixInBox = (xyBoxW[1] - xyBoxW[0])*(xyBoxW[3]-xyBoxW[2])
2588                        emptyCts -= tmpReadNoiseLevel*nPixInBox
2589                        empty_ct_err = sqrt(empty_ct_err^2 + (tmpReadNoiseLevel_Err*nPixInBox)^2)
2590                                               
2591                        Print "adjusted empty counts = ",emptyCts
2592                        Print "adjusted err/counts = ",empty_ct_err/emptyCts
2593                endif
2594
2595//
2596                // x- get all of the proper values for the calculation
2597                // -x currently the attenuation is incorrect
2598                //   such that kappa_err = 1*kappa
2599                // x- verify the calculation (no solid angle needed??)
2600                               
2601                // get the attenuation factor for the empty beam
2602                //  -- the attenuation is not written by NICE to the file
2603                //  so I need to calculate it myself from the tables
2604                //
2605//              empAttenFactor = V_getAttenuator_transmission(emptyFileName)
2606//              emp_atten_err = V_getAttenuator_trans_err(emptyFileName)
2607                empAttenFactor = V_CalculateAttenuationFactor(emptyFileName)
2608                emp_atten_err = V_CalculateAttenuationError(emptyFileName)
2609                               
2610                countTime = V_getCount_time(emptyFileName)
2611               
2612                // TODO
2613                // -- not sure if this is the correct monitor count to use
2614                monCnt = V_getBeamMonNormData("RAW")
2615               
2616                pixel_x = V_getDet_x_pixel_size("RAW",detPanel_toSum)
2617                pixel_x /= 10           //convert mm to cm, since sdd in cm
2618                pixel_y = V_getDet_y_pixel_size("RAW",detPanel_toSum)
2619                pixel_y /= 10           //convert mm to cm, since sdd in cm
2620                sdd = V_getDet_ActualDistance("RAW",detPanel_toSum)
2621               
2622//              kappa = emptyCts/countTime/empAttenFactor*1.0e8/(monCnt/countTime)*(pixel_x*pixel_y/sdd^2)
2623                kappa = emptyCts/countTime/empAttenFactor*1.0e8/(monCnt/countTime)
2624               
2625               
2626                kappa_err = (empty_ct_err/emptyCts)^2 + (emp_atten_err/empAttenFactor)^2
2627                kappa_err = sqrt(kappa_err) * kappa
2628               
2629                // x- set the parameters in the global string
2630                junkStr = num2str(kappa)
2631                errStr = num2Str(kappa_err)
2632               
2633                String strToExecute=""
2634               
2635                if(isBack)
2636                        sprintf strToExecute, "V_AskForAbsoluteParams(1,1,%g,1,%g,\"%s\")",kappa,kappa_err,"yes"        //no missing parameters, no dialog
2637                else
2638                        sprintf strToExecute, "V_AskForAbsoluteParams(1,1,%g,1,%g,\"%s\")",kappa,kappa_err,"no" //no missing parameters, no dialog
2639                endif
2640//              print strToExecute
2641                Execute strToExecute
2642
2643                Printf "Kappa was successfully calculated as = %g +/- %g (%g %)\r",kappa,kappa_err,(kappa_err/kappa)*100
2644       
2645                // restore preferences on exit
2646                gDoDIVCor = savDivPref
2647                gDoSolidAngleCor = savSAPref
2648
2649        Endif
2650       
2651End
2652
2653Function V_UserSelectBox_Continue(ctrlName) :buttonControl
2654        String ctrlName
2655       
2656        DoWindow/K junkWindow           //kill panel
2657end
2658
2659Function V_SelectABS_XYBox(x1,x2,y1,y2)
2660        Variable &x1,&x2,&y1,&y2
2661       
2662        Variable err=0
2663       
2664        Variable/G root:V_marquee=1             //sets the sneaky bit to automatically update marquee coords
2665        Variable/G root:V_left,root:V_right,root:V_bottom,root:V_top    //must be global for auto-update
2666        DoWindow/F SANS_Data
2667        NewPanel/K=2 /W=(139,341,382,432) as "Select the primary beam"
2668        DoWindow/C junkWindow
2669        AutoPositionWindow/E/M=1/R=SANS_Data
2670       
2671        Drawtext 21,20 ,"Select the primary beam with the"
2672        DrawText 21,40, "marquee and press continue"
2673        Button button0,pos={80,58},size={92,20},title="Continue"
2674        Button button0,proc=V_UserSelectBox_Continue
2675       
2676        PauseForUser junkWindow,SANS_Data
2677       
2678        DoWindow/F SANS_Data
2679
2680        //GetMarquee left,bottom                        //not needed
2681        NVAR V_left=V_left
2682        NVAR V_right=V_right
2683        NVAR V_bottom=V_bottom
2684        NVAR V_top=V_top
2685       
2686        x1 = V_left
2687        x2 = V_right
2688        y1 = V_bottom
2689        y2 = V_top
2690//      Print "new values,before rounding = ",x1,x2,y1,y2
2691
2692// TODO -- replace this call
2693//      KeepSelectionInBounds(x1,x2,y1,y2)
2694        //Print "new values = ",x1,x2,y1,y2
2695       
2696        KillVariables/Z root:V_Marquee,root:V_left,root:V_right,root:V_bottom,root:V_top
2697        if((x1-x2)==0 || (y1-y2)==0)
2698                err=1
2699        endif
2700        return(err)
2701End
2702
2703Function V_UseStdOrEmpForABS()
2704               
2705        NewPanel/K=2 /W=(139,341,402,448) as "Absolute Scaling"
2706        DoWindow/C junkABSWindow
2707        ModifyPanel cbRGB=(57346,65535,49151)
2708        SetDrawLayer UserBack
2709        SetDrawEnv fstyle= 1
2710        DrawText 21,20,"Method of absolute calibration"
2711        Button button0,pos={52,33},size={150,20},proc=V_UserSelectABS_Continue,title="Empty Beam Flux"
2712        Button button1,pos={52,65},size={150,20},proc=V_UserSelectABS_Continue,title="Secondary Standard"
2713       
2714        PauseForUser junkABSWindow
2715        NVAR val = root:Packages:NIST:VSANS:Globals:tmpAbsVal
2716        return(val)
2717End
2718
2719//returns 0 if button0 (empty beam flux)
2720// or 1 if secondary standard
2721Function V_UserSelectABS_Continue(ctrlName) :buttonControl
2722        String ctrlName
2723       
2724        variable val=0
2725        If(cmpstr(ctrlName,"button0")==0)
2726                val=0           
2727        else
2728                val=1
2729        endif
2730//      print "val = ",ctrlName,val
2731        Variable/G root:Packages:NIST:VSANS:Globals:tmpAbsVal = val
2732        DoWindow/K junkABSWindow                //kill panel
2733        return(0)
2734end
2735
2736
2737Function V_TrimDataProtoButton(ctrlName) :buttonControl
2738        String ctrlName
2739       
2740        Execute "V_CombineDataGraph()"
2741        return(0)
2742end
2743
2744//
2745// export protocol to a data file
2746//
2747//
2748Function V_ExportFileProtocol(ctrlName) : ButtonControl
2749        String ctrlName
2750// get a list of protocols
2751        String Protocol=""
2752        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2753        Prompt Protocol "Pick A Protocol",popup, V_DeletableProtocols()
2754        DoPrompt "Pick A Protocol to Export",Protocol
2755        if(V_flag==1)
2756                //Print "user cancel"
2757                SetDatafolder root:
2758                return(1)
2759        endif
2760
2761        String fileName = V_DoSaveFileDialog("pick the file to write to")
2762        print fileName
2763//     
2764        if(strlen(fileName) == 0)
2765                return(0)
2766        endif
2767
2768        V_writeReductionProtocolWave(fileName,$("root:Packages:NIST:VSANS:Globals:Protocols:"+Protocol) )
2769
2770        setDataFolder root:
2771        return(0)
2772
2773End
2774
2775//
2776// imports a protocol from a file on disk into the protocols folder
2777//
2778//
2779Function V_ImportFileProtocol(ctrlName) : ButtonControl
2780        String ctrlName
2781
2782//      SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2783
2784        String fullPath,fileName
2785        fullPath = DoOpenFileDialog("Import Protocol from file")
2786        print fullPath
2787//     
2788        if(strlen(fullPath) == 0)
2789                return(0)
2790        endif
2791       
2792        fileName = ParseFilePath(0, fullPath, ":", 1, 0)                        //just the file name at the end of the full path
2793       
2794        Wave/T tmpW = V_getReductionProtocolWave(fileName)
2795        if(numpnts(tmpW) == 0)
2796                DoAlert 0,"No protocol wave has been saved to this data file"
2797                return(0)
2798        endif
2799       
2800        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2801        String newName
2802        newName = CleanupName(fileName,0) + "_proto"
2803        duplicate/o tmpw $newName
2804       
2805       
2806        SetDataFolder root:
2807        return(0)
2808end
2809
2810
2811// currently not used - and not updated to 12 point protocols (5/2017)
2812//
2813//save the protocol as an IGOR text wave (.itx)
2814//
2815//
2816Function V_ExportProtocol(ctrlName) : ButtonControl
2817        String ctrlName
2818// get a list of protocols
2819        String Protocol=""
2820        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2821        Prompt Protocol "Pick A Protocol",popup, WaveList("*",";","")
2822        DoPrompt "Pick A Protocol to Export",Protocol
2823        if(V_flag==1)
2824                //Print "user cancel"
2825                SetDatafolder root:
2826                return(1)
2827        endif
2828//get the selection, or exit
2829        Wave/T pW= $protocol
2830        Make/O/T/N=13 tw
2831// save in the proper format (must write manually, for demo version)
2832        tw[0] = "IGOR"
2833        tw[1] = "WAVES/T \t"+protocol
2834        tw[2] = "BEGIN"
2835        tw[3,10] = "\t\""+pW[p-3]+"\""
2836        tw[11] = "END"
2837        tw[12] = "X SetScale/P x 0,1,\"\","+protocol+"; SetScale y 0,0,\"\","+protocol
2838       
2839        Variable refnum
2840        String fullPath
2841       
2842        PathInfo/S catPathName
2843        fullPath = DoSaveFileDialog("Export Protocol as",fname=Protocol,suffix="")
2844        If(cmpstr(fullPath,"")==0)
2845                //user cancel, don't write out a file
2846                Close/A
2847                Abort "no Protocol file was written"
2848        Endif
2849
2850        //actually open the file
2851        Open refNum as fullpath+".itx"
2852       
2853        wfprintf refnum, "%s\r", tw
2854        Close refnum
2855        //Print "all is well  ",protocol
2856        KillWaves/Z tw
2857        setDataFolder root:
2858        return(0)
2859
2860End
2861
2862
2863// currently not used - and not updated to 12 point protocols (5/2017)
2864//imports a protocol from disk into the protocols folder
2865//
2866// will overwrite existing protocols if necessary
2867//
2868//
2869Function V_ImportProtocol(ctrlName) : ButtonControl
2870        String ctrlName
2871
2872        SetDataFolder root:Packages:NIST:VSANS:Globals:Protocols
2873
2874        String fullPath
2875       
2876        PathInfo/S catPathName
2877        fullPath = DoOpenFileDialog("Import Protocol")
2878        If(cmpstr(fullPath,"")==0)
2879                //user cancel, don't write out a file
2880                Close/A
2881                Abort "no protocol was loaded"
2882        Endif
2883       
2884        LoadWave/O/T fullPath
2885       
2886        SetDataFolder root:
2887        return(0)
2888end
2889
2890
2891///////////////////////////////////////
2892//
2893// individual steps in the protocol
2894//
2895//////////////////////////////////////
2896
2897Function V_Proto_LoadDIV(protStr)
2898        String protStr
2899       
2900        String divFileName = "",junkStr="",pathStr=""
2901        PathInfo catPathName                    //this is where the files are
2902        pathStr=S_path
2903
2904        If(cmpstr("none",protStr)!=0)           // if !0, then there's a file requested
2905                If(cmpstr("ask",protStr) == 0)
2906                        //ask user for file
2907//                       junkStr = PromptForPath("Select the detector sensitivity file")
2908                        Prompt divFileName,"DIV File",popup,V_GetDIVList()
2909                        DoPrompt "Select File",divFileName
2910
2911                        If(strlen(divFileName)==0)
2912                                //
2913                                return(1)               //error
2914//                              SetDataFolder root:
2915//                              Abort "No file selected, data reduction aborted"
2916                        Endif
2917                        V_LoadHDF5Data(divFileName,"DIV")
2918                else
2919                        //assume it's a path, and that the first (and only) item is the path:file
2920                        //list processing is necessary to remove any final comma
2921                        junkStr = pathStr + StringFromList(0, protStr,"," )
2922                        V_LoadHDF5Data(junkStr,"DIV")
2923                Endif
2924       
2925        else
2926        // DIV step is being skipped
2927                NVAR gDoDIVCor = root:Packages:NIST:VSANS:Globals:gDoDIVCor
2928//              Variable saved_gDoDIVCor = gDoDIVCor
2929                gDoDIVCor = 0                   // protocol says to turn it off for now (reset later)
2930        Endif
2931       
2932        return(0)
2933End
2934
2935//
2936// fileStr is the file name (or list of names)
2937// activeType is the target work folder
2938// msgStr is the string for the prompt
2939//
2940Function V_Proto_LoadFile(fileStr,activeType,msgStr)
2941        String fileStr,activeType,msgStr
2942       
2943        Variable err,filesOK,notDone
2944       
2945        //Ask for Type file or parse
2946        do
2947                if((cmpstr(fileStr,"ask") == 0) || (cmpstr(fileStr,"")==0) )            //zero if strings are equal
2948                        err = V_LoadHDF5Data("","RAW")          //will prompt for file
2949                        if(err)
2950                                return(err)     //error
2951                                //PathInfo/S catPathName
2952                                //Abort "reduction sequence aborted"
2953                        endif
2954                        V_UpdateDisplayInformation("RAW")                       //display the new type of data that was loaded
2955                        err =  V_Raw_to_work(activeType)                //this is the first file (default)
2956                        //Ask for another TYPE file
2957                        do
2958                                DoAlert 1,"Do you want to add another "+activeType+" file?"
2959                                if(V_flag == 1)         //yes
2960                                        err = V_LoadHDF5Data("","RAW")          //will prompt for file
2961                                        if(err)
2962                                                return(1)               //error
2963                                                //PathInfo/S catPathName
2964                                                //Abort "reduction sequence aborted"
2965                                        endif
2966                                        V_UpdateDisplayInformation("RAW")                       //display the new type of data that was loaded
2967                                        err = V_Add_raw_to_work(activeType)
2968                                        notDone = 1
2969                                else
2970                                        notDone = 0
2971                                endif
2972                        while(notDone)
2973                        //Loader is in charge of updating, since it knows if data was loaded
2974                        V_UpdateDisplayInformation(ActiveType)
2975                        break
2976                Endif
2977                //"none" is not an option - you always need a sample file - "none" will never return zero
2978                //if not "ask" AND not "none" then try to parse the filenames
2979                If((cmpstr(fileStr,"none") != 0) && (cmpstr(fileStr,"ask") != 0))
2980                        //filesOK = AreFilesThere(activeType,fileStr)           //return 1 if correct files are already there
2981                        filesOK = 0             // Feb 2008, always force a reload of files. Maybe slow, but always correct
2982                        if(!filesOK)
2983                                //add the correct file(s) to Type
2984                               
2985                                // TODO: only one file is allowed currently
2986                                err = V_AddFilesInList(activeType,fileStr)
2987                               
2988                                if(err)
2989                                        //Print "fileStr = ",fileStr
2990                                        DoAlert 0, fileStr + " file not found, reset file"
2991                                        return(err)             //error
2992                                Endif
2993                        Endif
2994                        //Loader is in charge of updating, since it knows if data was loaded
2995                        V_UpdateDisplayInformation(ActiveType)
2996                Endif
2997        While(0)
2998       
2999
3000       
3001        return(0)
3002End
3003
3004Function V_Dispatch_to_Correct(bgdStr,empStr,drkStr)
3005        String bgdStr,empStr,drkStr
3006       
3007        Variable mode=4,val,err
3008       
3009        if( (cmpstr("none",bgdStr) == 0)        && (cmpstr("none",empStr) == 0) )
3010        //no subtraction (mode = 4),
3011                mode = 4
3012        Endif
3013        If((cmpstr(bgdStr,"none") != 0) && (cmpstr(empStr,"none") == 0))
3014                //subtract BGD only
3015                mode=2
3016        Endif
3017        If((cmpstr(bgdStr,"none") == 0) && (cmpstr(empStr,"none") != 0))
3018                //subtract EMP only
3019                mode=3
3020        Endif
3021        If((cmpstr(bgdStr,"none") != 0) && (cmpstr(empStr,"none") != 0))
3022                // bkg and emp subtraction are to be done (BOTH not "none")
3023                mode=1
3024        Endif
3025//      activeType = "COR"
3026        //add in DRK mode (0= not used, 10 = used)
3027        // TODO: DRK has been de-activated for now
3028//      val = NumberByKey("DRKMODE",drkStr,"=","," )
3029//      mode += val
3030
3031//              print "mode = ",mode
3032
3033        err = V_Correct(mode)
3034        if(err)
3035                return(err)
3036//              SetDataFolder root:
3037//              Abort "error in Correct, called from executeprotocol, normal cor"
3038        endif
3039
3040//      //Loader is in charge of updating, since it knows if data was loaded
3041//      V_UpdateDisplayInformation("COR")
3042
3043       
3044        return(0)
3045End
3046
3047
3048
3049
3050Function V_Proto_ABS_Scale(absStr,activeType)
3051        String absStr,&activeType
3052       
3053        Variable c2,c3,c4,c5,kappa_err,err
3054        //do absolute scaling if desired
3055
3056        if(cmpstr("none",absStr)!=0)
3057                if(cmpstr("ask",absStr)==0)
3058//                      //get the params from the user
3059//                      Execute "V_AskForAbsoluteParams_Quest()"
3060//                      //then from the list
3061//                      SVAR junkAbsStr = root:Packages:NIST:VSANS:Globals:Protocols:gAbsStr
3062//                      c2 = NumberByKey("TSTAND", junkAbsStr, "=", ";")        //parse the list of values
3063//                      c3 = NumberByKey("DSTAND", junkAbsStr, "=", ";")
3064//                      c4 = NumberByKey("IZERO", junkAbsStr, "=", ";")
3065//                      c5 = NumberByKey("XSECT", junkAbsStr, "=", ";")
3066//                      kappa_err = NumberByKey("SDEV", junkAbsStr, "=", ";")
3067                else
3068                        //get the parames from the list
3069                        c2 = NumberByKey("TSTAND", absStr, "=", ";")    //parse the list of values
3070                        c3 = NumberByKey("DSTAND", absStr, "=", ";")
3071                        c4 = NumberByKey("IZERO", absStr, "=", ";")
3072                        c5 = NumberByKey("XSECT", absStr, "=", ";")
3073                        kappa_err = NumberByKey("SDEV", absStr, "=", ";")
3074                Endif
3075                //get the sample trans and thickness from the activeType folder
3076//              Variable c0 = V_getSampleTransmission(activeType)               //sample transmission
3077//              Variable c1 = V_getSampleThickness(activeType)          //sample thickness
3078               
3079                err = V_Absolute_Scale(activeType,absStr)
3080                if(err)
3081                        return(err)
3082                        SetDataFolder root:
3083                        Abort "Error in V_Absolute_Scale(), called from V_ExecuteProtocol"
3084                endif
3085                activeType = "ABS"
3086                V_UpdateDisplayInformation(ActiveType)                  //update before breaking from loop
3087        Endif
3088       
3089        return(0)
3090End
3091
3092
3093Function V_Proto_ReadMask(maskStr)
3094        String maskStr
3095       
3096        //check for mask
3097        //doesn't change the activeType
3098        String mskFileName="",pathStr=""
3099        PathInfo catPathName                    //this is where the files are
3100        pathStr=S_path
3101               
3102        if(cmpstr("none",maskStr)!=0)
3103                If(cmpstr("ask",maskStr)==0)
3104                        //get file from user
3105                        // x- fill in the get file prompt, and handle the result
3106                        Prompt mskFileName,"MASK File",popup,V_PickMASKButton("")
3107                        DoPrompt "Select File",mskFileName
3108//                      if (V_Flag)
3109//                              return 0                                                                        // user cancelled
3110//                      endif
3111
3112                        If(strlen(mskFileName)==0)              //use cancelled
3113                                //if none desired, make sure that the old mask is deleted
3114                                KillDataFolder/Z root:Packages:NIST:VSANS:MSK:
3115                                NewDataFolder/O root:Packages:NIST:VSANS:MSK
3116                               
3117                                DoAlert 0,"No Mask file selected, data not masked"
3118                        else
3119                                //read in the file from the selection
3120                                V_LoadHDF5Data(mskFileName,"MSK")
3121                        Endif
3122                else
3123                        //just read it in from the protocol
3124                        //list processing is necessary to remove any final comma
3125                        mskFileName = pathStr + StringFromList(0, maskStr,"," )
3126                        V_LoadHDF5Data(mskFileName,"MSK")
3127                Endif
3128               
3129        else
3130                //if none desired, make sure that the old mask is deleted
3131// TODO
3132// x- clean out the data folder
3133// x- note that V_KillNamedDataFolder() points to RawVSANS, and won't work
3134// -- what happens if the kill fails? need error handling
3135//
3136                KillDataFolder/Z root:Packages:NIST:VSANS:MSK:
3137                NewDataFolder/O root:Packages:NIST:VSANS:MSK
3138
3139        Endif
3140       
3141        return(0)
3142End
3143
3144
3145Function V_Proto_doAverage(avgStr,av_type,activeType,binType,collimationStr)
3146        String avgStr,av_type,activeType
3147        Variable binType
3148        String collimationStr
3149       
3150       
3151        strswitch(av_type)      //dispatch to the proper routine to average to 1D data
3152                case "none":           
3153                        //still do nothing
3154                        // set binType and binTypeStr to bad flags
3155                        String binTypeStr = "none"
3156                        binType = -999999
3157                        break                   
3158
3159                case "Circular":
3160                        V_QBinAllPanels_Circular(activeType,binType,collimationStr)             // this does a default circular average
3161                        break
3162                       
3163                case "Sector":
3164//                      CircularAverageTo1D(activeType)
3165                        break
3166                case "Sector_PlusMinus":
3167//                      Sector_PlusMinus1D(activeType)
3168                        break
3169                case "Rectangular":
3170//                      RectangularAverageTo1D(activeType)
3171                        break
3172
3173                case "Annular":
3174                        String detGroup = StringByKey("DETGROUP",avgStr,"=",";")
3175                        Variable qCtr_Ann = NumberByKey("QCENTER",avgStr,"=",";")
3176                        Variable qWidth = NumberByKey("QDELTA",avgStr,"=",";")
3177                        V_QBinAllPanels_Annular(activeType,detGroup,qCtr_Ann,qWidth)
3178                        break
3179
3180                case "Narrow_Slit":
3181                        V_QBinAllPanels_Slit(activeType,binType)                // this does a tall, narrow slit average
3182                        break
3183                       
3184                case "2D_ASCII":       
3185                        //do nothing
3186                        break
3187                case "QxQy_ASCII":
3188                        //do nothing
3189                        break
3190                case "PNG_Graphic":
3191                        //do nothing
3192                        break
3193                default:       
3194                        //do nothing
3195        endswitch
3196
3197       
3198        return(0)
3199End
3200
3201
3202
3203
3204
3205Function V_Proto_doPlot(plotStr,av_type,activeType,binType,detGroup)
3206        String plotStr,av_type,activeType
3207        Variable binType
3208        String detGroup
3209       
3210        String doPlot = StringByKey("PLOT",plotStr,"=",";")
3211       
3212        If( (cmpstr(doPlot,"Yes")==0) && (cmpstr(av_type,"none") != 0) )       
3213               
3214                strswitch(av_type)      //dispatch to the proper routine to PLOT 1D data
3215                        case "none":           
3216                                //still do nothing
3217                                break                   
3218
3219                        case "Circular":
3220                                V_PlotData_Panel()              //this brings the plot window to the front, or draws it (ONLY)
3221                                V_Update1D_Graph(activeType,binType)            //update the graph, data was already binned                             
3222                                break
3223                        case "Sector":
3224        //                      CircularAverageTo1D(activeType)
3225                                break
3226                        case "Sector_PlusMinus":
3227        //                      Sector_PlusMinus1D(activeType)
3228                                break
3229                        case "Rectangular":
3230        //                      RectangularAverageTo1D(activeType)
3231                                break
3232
3233                        case "Annular":
3234                                V_Phi_Graph_Proc(activeType,detGroup)
3235                                break
3236
3237                        case "Narrow_Slit":
3238                        // these are the same plotting routines as for standard circular average
3239                                V_PlotData_Panel()              //this brings the plot window to the front, or draws it (ONLY)
3240                                V_Update1D_Graph(activeType,binType)            //update the graph, data was already binned
3241                                break
3242                       
3243                        case "2D_ASCII":       
3244                                //do nothing
3245                                break
3246                        case "QxQy_ASCII":
3247                                //do nothing
3248                                break
3249                        case "PNG_Graphic":
3250                                //do nothing
3251                                break
3252                        default:       
3253                                //do nothing
3254                endswitch
3255
3256        endif           // end of plotting switch
3257       
3258        return(0)
3259end
3260
3261
3262Function V_Proto_SaveFile(avgStr,activeType,samFileLoaded,av_type,binType,detGroup,trimBegStr,trimEndStr)
3263        String avgStr,activeType,samFileLoaded,av_type
3264        Variable binType
3265        String detGroup,trimBegStr,trimEndStr
3266       
3267        String fullpath = "", newfileName=""
3268        String saveType = StringByKey("SAVE",avgStr,"=",";")            //does user want to save data?
3269
3270        If( (cmpstr(saveType[0,2],"Yes")==0) && (cmpstr(av_type,"none") != 0) )         
3271                //then save
3272                newFileName = RemoveEnding(samFileLoaded,".nxs.ngv")
3273               
3274                //pick ABS or AVE extension
3275                String exten = activeType
3276                if(cmpstr(exten,"ABS") != 0)
3277                        exten = "AVE"
3278                endif
3279//              if(cmpstr(av_type,"2D_ASCII") == 0)
3280//                      exten = "ASC"
3281//              endif
3282//              if(cmpstr(av_type,"QxQy_ASCII") == 0)
3283//                      exten = "DAT"
3284//              endif
3285               
3286//              // add an "x" to the file extension if the output is XML
3287//              // currently (2010), only for ABS and AVE (1D) output
3288//              if( cmpstr(exten,"ABS") == 0 || cmpstr(exten,"AVE") == 0 )
3289//                      if(useXMLOutput == 1)
3290//                              exten += "x"
3291//                      endif
3292//              endif
3293                               
3294                //Path is catPathName, symbolic path
3295                //if this doesn't exist, a dialog will be presented by setting dialog = 1
3296                //
3297                Variable dialog = 0
3298
3299                PathInfo/S catPathName
3300                String item = StringByKey("NAME",avgStr,"=",";")                //Auto or Manual naming
3301                String autoname = StringByKey("AUTONAME",avgStr,"=",";")                //autoname -  will get empty string if not present
3302                If((cmpstr(item,"Manual")==0) || (cmpstr(newFileName,"") == 0))
3303                        //manual name if requested or if no name can be derived from header
3304                        fullPath = newfileName + "."+ exten //puts possible new name or null string in dialog
3305                        dialog = 1              //force dialog for user to enter name
3306                else
3307                        //auto-generate name and prepend path - won't put up any dialogs since it has all it needs
3308                        //use autoname if present
3309                        if (cmpstr(autoname,"") != 0)
3310                                fullPath = S_Path + autoname + "." +exten
3311                        else
3312                                fullPath = S_Path + newFileName+"." + exten
3313                        endif   
3314                Endif
3315                //
3316                strswitch(av_type)     
3317                        case "Annular":
3318                                V_fWrite1DAnnular("root:Packages:NIST:VSANS:",activeType,detGroup,newFileName+".phi")
3319                                Print "data written to:  "+ newFileName+".phi"
3320
3321                                break
3322
3323                        case "Circular":                //in SANS, this was the default, but is dangerous, so make it explicit here
3324                        case "Sector":          // TODO: this falls through - which luckily works for now...
3325                        case "Rectangular":             // TODO: this falls through - which luckily works for now...
3326                        case "Narrow_Slit":             // TODO: this falls through - which luckily works for now...
3327
3328// no VSANS support of XML output at this point                 
3329//                              if (useXMLOutput == 1)
3330//                                      WriteXMLWaves_W_Protocol(activeType,fullPath,dialog)
3331//                              else
3332//                                      WriteWaves_W_Protocol(activeType,fullpath,dialog)
3333//                              endif
3334//
3335                                if(cmpstr(saveType,"Yes - Concatenate")==0)
3336                                        V_Trim1DDataStr(activeType,binType,trimBegStr,trimEndStr)                       // x- passing null strings uses global or default trim values
3337
3338                                        V_ConcatenateForSave("root:Packages:NIST:VSANS:",activeType,"",binType)         // this removes q=0 point, concatenates, sorts
3339                               
3340                                        V_RemoveDuplicateQvals("root:Packages:NIST:VSANS:",activeType)          // works with the "tmp_x" waves from concatenateForSave
3341//                                      prot[9] = collimationStr
3342                                       
3343                                        V_Write1DData("root:Packages:NIST:VSANS:",activeType,newFileName+"."+exten)             //don't pass the full path, just the name
3344                               
3345                                endif
3346                               
3347                                if(cmpstr(saveType,"Yes - Individual")==0)
3348                                        // remove the q=0 point from the back detector, if it's there
3349                                        // does not trim any other points from the data
3350                                        V_RemoveQ0_B(activeType)
3351                                        V_Write1DData_ITX("root:Packages:NIST:VSANS:",activeType,newFileName,binType)
3352                                endif
3353                                Print "data written to:  "+ newFileName+"."+exten
3354
3355                                break
3356       
3357                               
3358                                case "2D_ASCII":
3359//                              Fast2DExport(activeType,fullPath,dialog)
3360                                break
3361                        case "QxQy_ASCII":
3362                                fullPath = S_Path + newFileName+".DAT"
3363                                V_QxQy_Export(activeType,fullPath,newFileName,dialog)
3364                                break
3365                        case "PNG_Graphic":
3366//                              SaveAsPNG(activeType,fullpath,dialog)
3367                                break
3368
3369                        default:
3370                                DoAlert 0, "av_type not found in dispatch to write file"
3371                endswitch
3372               
3373        Endif   
3374        return(0)
3375End
3376
3377
Note: See TracBrowser for help on using the repository browser.