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

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

bug fixes for the back detector dimensions and beam center (pixels)

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