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

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

changes to the USANS procedures to accommodate the re-ordering of the data columns in the raw USANS data that is to be output from NICE, versus what was previously written out by ICP.

A global flag switches between the two reading modes. On startup, the preferences panel is automatically opened to the USANS tab so that the user can immediately set the flag correctly. Currently it defaults to "checked" to read the New data format.

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