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

Last change on this file since 1055 was 1055, checked in by srkline, 5 years ago

LOTS of changes to accommodate the beam center being reported in cm rather than pixels. Required a lot of changes to VCALC (to fill in simulated data), and in the reading and interpreting of data for display, and most importantly, the calculation of q.

There may still be a few residual bugs with this. I am still re-testing with new sample data sets.

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