source: sans/Dev/trunk/NCNR_User_Procedures/Reduction/SANS/ProtocolAsPanel.ipf @ 575

Last change on this file since 575 was 575, checked in by srkline, 13 years ago

Added ANSTO files to the repository for SANS reduction

Changed #include files for each facility to have a #define SYMBOL at the top to allow small facility-specific changes in the main body of the code that are controlled with compiler directives

File size: 75.9 KB
Line 
1#pragma rtGlobals=1             // Use modern global access method.
2#pragma version=5.0
3#pragma IgorVersion=6.1
4
5//************************
6//      Vers. 1.2 092101
7//
8//7/2001 converted protocols to simply use the filenames, rather than the path:filename
9//this should allow portability of the protocols between machines
10//**ALL** protocols now depend on the path "catPathName"
11//
12//procedure files for construction of protocols interactively,
13//selecting files from the CAT/VSHORT table, rather than picking blindly
14//from a dialog - the process of selecting/setting files is not as
15//transparent as it could be for new users
16//
17//*************************
18//////////////////////////////////
19//
20//              KEYWORD=<value> lists used in protocol definitions
21//
22//              KEYWORDS are ALWAYS capitalized, and yes, it does matter
23//
24//              for ABSOLUTE parameters
25//              (4) possible keywords, all with numerical values
26//              TSTAND=value            transmission of the standard
27//              DSTAND=value            thickness of the standard, in centimeters
28//              IZERO=value             I(q=0) value for the standard, in normalized neutron counts
29//              XSECT=value             calibrated cross-section of the standard sample
30//
31//              For calibration with a transmission file, set TSTAND, DSTAND, and XSECT to 1.0
32//              and set IZERO to KAPPA (defined in Tania's handout, or in documentation of MRED_KAP on VAX)
33//
34//
35//              For AVERAGE and for DRAWING
36//                      DRAWING routines only use a subset of the total list, since saving, naming, etc. don't apply
37//              (10) possible keywords, some numerical, some string values
38//              AVTYPE=string           string from set {Circular,Annular,Rectangular,Sector,2D_ASCII,QxQy_ASCII,PNG_Graphic}
39//              PHI=value                       azimuthal angle (-90,90)
40//              DPHI=value                      +/- angular range around phi for average
41//              WIDTH=value             total width of rectangular section, in pixels
42//              SIDE=string             string from set {left,right,both} **note NOT capitalized
43//              QCENTER=value           q-value (1/A) of center of annulus for annular average
44//              QDELTA=value            total width of annulus centered at QCENTER
45//              PLOT=string             string from set {Yes,No} = truth of generating plot of averaged data
46//              SAVE=string             string from set {Yes,No} = truth of saving averaged data to disk
47//              NAME=string             string from set {Auto,Manual} = Automatic name generation or Manual(dialog)
48//
49//
50//              For work.DRK usage:
51//              **the list is COMMA delimited, soparator is =
52//              DRK=none,DRKMODE=0,
53//              DRK=name                        is the name of the file, must be a full name, expected to be raw data
54//              DRKMODE=value           is a numeric value (0 or 10 to add to the Correct(mode) switch (unused?)
55//
56//////////////////////////////////
57
58
59//main entry procedure for initialzing and displaying the protocol panel
60// initilaizes folders and globals as needed
61//
62Proc ReductionProtocolPanel()
63        DoWindow/F ProtocolPanel
64        if(V_flag==0)
65                InitProtocolPanel()
66                ProtocolPanel()
67        Endif
68End
69
70//initialization procedure for the protocol panel
71//note that :gAbsStr is also shared (common global) to that used in
72//the questionnare form of the protcol (see protocol.ipf)
73//
74//0901, uses 8 points in protocol wave
75Proc InitProtocolPanel()
76
77        //set up the global variables needed for the protocol panel
78        //global strings to put in a temporary protocol textwave
79        Variable ii=0,nsteps=8
80        String waveStr="tempProtocol"
81        SetDataFolder root:myGlobals:Protocols
82        Make/O/T/N=(nsteps) $"root:myGlobals:Protocols:tempProtocol" = ""
83
84        String/G root:myGlobals:Protocols:gSAM="ask"
85        String/G root:myGlobals:Protocols:gBGD="ask"
86        String/G root:myGlobals:Protocols:gEMP="ask"
87        String/G root:myGlobals:Protocols:gDIV="ask"
88        String/G root:myGlobals:Protocols:gMASK="ask"
89        String/G root:myGlobals:Protocols:gAbsStr="ask"
90        String/G root:myGlobals:Protocols:gAVE="AVTYPE=Circular;SAVE=Yes;NAME=Auto;PLOT=Yes;"
91        String/G root:myGlobals:Protocols:gDRK="DRK=none,DRKMODE=0,"
92       
93        SetDataFolder root:
94       
95End
96
97//button control to create a CAT/SHORT notebook listing of all data files
98//in the selected folder (catPathName)
99//
100Function DoCatShort(ctrlName) : ButtonControl
101        String ctrlName
102
103        Execute "BuildCatVeryShortTable()"
104       
105End
106
107//button procedure to reset the panel seletctions/checks...etc...
108//to reflect the choices in a previously saved protocol
109// - parses through the protocol and resets the appropriate global strings and
110//updates the panel display
111//
112Function RecallProtocolButton(ctrlName) : ButtonControl
113        String ctrlName
114
115        //will reset panel values based on a previously saved protocol
116        //pick a protocol wave from the Protocols folder
117        //MUST move to Protocols folder to get wavelist
118        SetDataFolder root:myGlobals:Protocols
119        Execute "PickAProtocol()"
120       
121        //get the selected protocol wave choice through a global string variable
122        SVAR protocolName = root:myGlobals:Protocols:gProtoStr
123
124        //If "CreateNew" was selected, ask user to try again
125        if(cmpstr("CreateNew",protocolName) == 0)
126                Abort "CreateNew is for making a new Protocol. Select a previously saved Protocol"
127        Endif
128       
129        //reset the panel based on the protocol textwave (currently a string)
130        ResetToSavedProtocol(protocolName)
131       
132        SetDataFolder root:
133        return(0)
134End
135
136//deletes the selected protocol from the list and from memory
137//
138Function DeleteProtocolButton(ctrlName) : ButtonControl
139        String ctrlName
140
141        //put up a list of protocols and pick one
142        SetDataFolder root:myGlobals:Protocols
143//      Execute "DeleteAProtocol()"
144        String Protocol=""
145        Prompt Protocol "Delete A Protocol",popup, DeletableProtocols()
146        DoPrompt "Select protocol to delete",protocol
147        If(V_flag==1)
148                return(0)
149        endif
150
151        //If "CreateNew, Base, DoAll, or tempProtocol" was selected, do nothing
152        strswitch(protocol)
153                case "CreateNew":
154                        break
155                case "DoAll":
156                        break
157                case "Base":
158                        break
159                case "tempProtocol":
160                        break
161                default:
162                        //delete the protocol
163                        KillWaves/Z $protocol
164        endswitch
165       
166        SetDataFolder root:
167        return(0)
168End
169
170
171//function that actually parses the protocol specified by nameStr
172//which is just the name of the wave, without a datafolder path
173//
174Function ResetToSavedProtocol(nameStr)
175        String nameStr
176       
177        //allow special cases of Base and DoAll Protocols to be recalled to panel - since they "ask"
178        //and don't need paths
179       
180        String catPathStr
181        PathInfo catPathName
182        catPathStr=S_path
183       
184        //SetDataFolder root:myGlobals:Protocols                //on windows, data folder seems to get reset (erratically) to root:
185        Wave/T w=$("root:myGlobals:Protocols:" + nameStr)
186       
187        String fullPath="",comma=",",list="",nameList="",PathStr="",item=""
188        Variable ii=0,numItems,checked,specialProtocol
189       
190        if((cmpstr(nameStr,"Base")==0) || (cmpstr(nameStr,"DoAll")==0))
191                specialProtocol = 1
192        else
193                specialProtocol = 0
194        Endif
195       
196        //background
197        checked = 1
198        nameList = w[0]
199        If(cmpstr(nameList,"none") ==0)
200                checked = 0
201        Endif
202
203        //set the global string to display and checkbox
204        String/G root:myGlobals:Protocols:gBGD = nameList
205        CheckBox prot_check win=ProtocolPanel,value=checked
206       
207        //empty
208        checked = 1
209        nameList = w[1]
210        If(cmpstr(nameList,"none") ==0)
211                checked = 0
212        Endif
213
214        //set the global string to display and checkbox
215        String/G root:myGlobals:Protocols:gEMP = nameList
216        CheckBox prot_check_1 win=ProtocolPanel,value=checked
217       
218        //DIV file
219        checked = 1
220        nameList = w[2]
221        If(cmpstr(nameList,"none") ==0)
222                checked = 0
223        Endif
224
225        //set the global string to display and checkbox
226        String/G root:myGlobals:Protocols:gDIV = nameList
227        CheckBox prot_check_2 win=ProtocolPanel,value=checked
228       
229        //Mask file
230        checked = 1
231        nameList = w[3]
232        If(cmpstr(nameList,"none") ==0)
233                checked = 0
234        Endif
235
236        //set the global string to display and checkbox
237        String/G root:myGlobals:Protocols:gMASK = nameList
238        CheckBox prot_check_3 win=ProtocolPanel,value=checked
239       
240        //4 = abs parameters
241        list = w[4]
242        numItems = ItemsInList(list,";")
243        checked = 1
244        if(numitems == 4)
245                //correct number of parameters, assume ok
246                String/G root:myGlobals:Protocols:gAbsStr = list
247                CheckBox prot_check_9 win=ProtocolPanel,value=checked
248        else
249                item = StringFromList(0,list,";")
250                if(cmpstr(item,"none")==0)
251                        checked = 0
252                        list = "none"
253                        String/G root:myGlobals:Protocols:gAbsStr = list
254                        CheckBox prot_check_9 win=ProtocolPanel,value=checked
255                else
256                        //force to "ask"
257                        checked = 1
258                        String/G root:myGlobals:Protocols:gAbsStr = "ask"
259                        CheckBox prot_check_9 win=ProtocolPanel,value=checked
260                Endif
261        Endif
262       
263        //5 = averaging choices
264        list = w[5]
265        item = StringByKey("AVTYPE",list,"=",";")
266        if(cmpstr(item,"none") == 0)
267                checked = 0
268                String/G root:myGlobals:Protocols:gAVE = "none"
269                CheckBox prot_check_5 win=ProtocolPanel,value=checked
270        else
271                checked = 1
272                String/G root:myGlobals:Protocols:gAVE = list
273                CheckBox prot_check_5 win=ProtocolPanel,value=checked
274        Endif
275       
276        //6 = DRK choice
277        list = w[6]
278        item = StringByKey("DRK",list,"=",",")
279        //print list,item
280        if(cmpstr(item,"none") == 0)
281                checked = 0
282                String/G root:myGlobals:Protocols:gDRK = list
283                CheckBox prot_check_6 win=ProtocolPanel,value=checked
284        else
285                checked = 1
286                String/G root:myGlobals:Protocols:gDRK = list
287                CheckBox prot_check_6 win=ProtocolPanel,value=checked
288        Endif
289       
290        //7 = unused
291       
292        //all has been reset, get out
293        Return (0)
294End
295
296//button action procedure that simply closes the panel
297//
298Function DoneProtocolButton(ctrlName) : ButtonControl
299        String ctrlName
300
301        //will gracefully close and exit the protocol panel
302       
303        DoWindow/K ProtocolPanel
304End
305
306//button action procedure that saves the current choices on the panel
307//as a named protocol, for later recall
308//asks for a valid name, then creates a protocol from the panel choices
309//creates a wave, and sets the current protocol name to this new protocol
310//
311//now allows the user the choice to overwrite a protocol
312//
313Function SaveProtocolButton(ctrlName) : ButtonControl
314        String ctrlName
315
316        Variable notDone=1, newProto=1
317        //will prompt for protocol name, and save the protocol as a text wave
318        //prompt for name of new protocol wave to save
319        do
320                Execute "AskForName()"
321                SVAR newProtocol = root:myGlobals:Protocols:gNewStr
322               
323                //make sure it's a valid IGOR name
324                newProtocol = CleanupName(newProtocol,0)        //strict naming convention
325                String/G root:myGlobals:Protocols:gNewStr=newProtocol           //reassign, if changed
326                Print "newProtocol = ",newProtocol
327               
328                SetDataFolder root:myGlobals:Protocols
329                if(WaveExists( $("root:myGlobals:Protocols:" + newProtocol) ) == 1)
330                        //wave already exists
331                        DoAlert 1,"That name is already in use. Do you wish to overwrite the existing protocol?"
332                        if(V_Flag==1)
333                                notDone = 0
334                                newProto = 0
335                        else
336                                notDone = 1
337                        endif
338                else
339                        //name is good
340                        notDone = 0
341                Endif
342        while(notDone)
343       
344        //current data folder is  root:myGlobals:Protocols
345        if(newProto)
346                Make/O/T/N=8 $("root:myGlobals:Protocols:" + newProtocol)
347        Endif
348       
349        MakeProtocolFromPanel( $("root:myGlobals:Protocols:" + newProtocol) )
350        String/G  root:myGlobals:Protocols:gProtoStr = newProtocol
351       
352        //the data folder WAS changed above, this must be reset to root:
353        SetDatafolder root:
354End
355
356//function that does the guts of reading the panel controls and globals
357//to create the necessary text fields for a protocol
358//Wave/T w (input) is an empty text wave of 8 elements for the protocol
359//on output, w[] is filled with the protocol strings as needed from the panel
360//
361Function MakeProtocolFromPanel(w)
362        Wave/T w
363       
364        //construct the protocol text wave form the panel
365        //it is to be parsed by ExecuteProtocol() for the actual data reduction
366        PathInfo catPathName                    //this is where the files came from
367        String pathstr=S_path,tempStr,curList
368        Variable checked,ii,numItems
369       
370        //look for checkbox, then take each item in list and prepend the path
371        //w[0] = background
372        ControlInfo/W=ProtocolPanel prot_check
373        checked = V_value
374        if(checked)
375                //build the list
376                //just read the global
377                SVAR str=root:myGlobals:Protocols:gBGD
378                if(cmpstr(str,"ask")==0)
379                        w[0] = str              //just ask
380                else
381                        tempstr = ParseRunNumberList(str)
382                        if(strlen(tempStr)==0)
383                                return(1)                               //error parsing list
384                        else
385                                w[0] = tempstr
386                                str = tempstr           //set the protocol and the global
387                        endif
388                endif
389        else
390                //none used - set textwave (and global?)
391                w[0] = "none"
392                String/G root:myGlobals:Protocols:gBGD = "none"
393        endif
394       
395        //w[1] = empty
396        ControlInfo/W=ProtocolPanel prot_check_1
397        checked = V_value
398        if(checked)
399                //build the list
400                //just read the global
401                SVAR str=root:myGlobals:Protocols:gEMP
402                if(cmpstr(str,"ask")==0)
403                        w[1] = str
404                else
405                        tempstr = ParseRunNumberList(str)
406                        if(strlen(tempStr)==0)
407                                return(1)
408                        else
409                                w[1] = tempstr
410                                str=tempStr
411                        endif
412                endif
413        else
414                //none used - set textwave (and global?)
415                w[1] = "none"
416                String/G root:myGlobals:Protocols:gEMP = "none"
417        endif
418       
419        //w[2] = div file
420        ControlInfo/W=ProtocolPanel prot_check_2
421        checked = V_value
422        if(checked)
423                //build the list
424                //just read the global
425                SVAR str=root:myGlobals:Protocols:gDIV
426                if(cmpstr(str,"ask")==0)
427                        w[2] = str
428                else
429                        tempStr = ParseRunNumberList(str)
430                        if(strlen(tempStr)==0)
431                                return(1)
432                        else
433                                w[2] = tempstr
434                                str=tempstr
435                        endif
436                endif
437        else
438                //none used - set textwave (and global?)
439                w[2] = "none"
440                String/G root:myGlobals:Protocols:gDIV = "none"
441        endif
442       
443        //w[3] = mask file
444        ControlInfo/W=ProtocolPanel prot_check_3
445        checked = V_value
446        if(checked)
447                //build the list
448                //just read the global
449                SVAR str=root:myGlobals:Protocols:gMASK
450                if(cmpstr(str,"ask")==0)
451                        w[3] = str
452                else
453                        tempstr = ParseRunNumberList(str)
454                        if(strlen(tempstr)==0)
455                                return(1)
456                        else
457                                w[3] = tempstr
458                                str = tempstr
459                        endif
460                endif
461        else
462                //none used - set textwave (and global?)
463                w[3] = "none"
464                String/G root:myGlobals:Protocols:gMASK = "none"
465        endif
466       
467        //w[4] = abs parameters
468        ControlInfo/W=ProtocolPanel prot_check_9
469        checked = V_value
470        if(checked)
471                //build the list
472                //just read the global
473                SVAR str=root:myGlobals:Protocols:gAbsStr
474                w[4] = str
475        else
476                //none used - set textwave (and global?)
477                w[4] = "none"
478                String/G root:myGlobals:Protocols:gAbsStr = "none"
479        endif
480       
481        //w[5] = averaging choices
482        ControlInfo/W=ProtocolPanel prot_check_5                        //do the average?
483        checked = V_value
484        if(checked)
485                //just read the global
486                SVAR avestr=root:myGlobals:Protocols:gAVE
487                w[5] = avestr
488        else
489                //none used - set textwave
490                w[5] = "AVTYPE=none;"
491        endif
492       
493        //w[6]
494        //work.DRK information
495        SVAR drkStr=root:myGlobals:Protocols:gDRK
496        w[6] = drkStr
497       
498        //w[7]
499        //currently unused
500        w[7] = ""
501       
502        return(0)
503End
504
505
506//button control function to set the background (SAM) file name to the
507//selected name in the CAT/SHORT window
508//the version number of the file need not be selected, it will be added later if needed
509//multiple SAMple files can be added together if the list is not reset
510//
511Function PickSAMButton(ctrlName) : ButtonControl
512        String ctrlName
513
514        //set the SAM file(s) as a global string
515        //multiple files are added as a COMMA separated list of files, w/extension
516        //global string is either null or contains filename(s) on entry
517       
518        //ask to reset the list?
519        DoAlert 1,"Reset the list of sample files?"
520        if(V_flag == 1)
521                String/G root:myGlobals:Protocols:gSAM = ""
522        Endif
523       
524        Variable catVSTableExists, num_sans_files
525        catVSTableExists = WinType("catVSTable")
526        //??BUG?? V_flag returns 1 even if no selection?
527        //check manually for null selection
528        //Print "local v_flag = ",num2str(V_flag)
529        Wave/T LocFilenames = $"root:myGlobals:CatVSHeaderInfo:Filenames"
530        if (catVSTableExists != 0)
531                GetSelection table,CatVSTable,7
532                if(strsearch(S_selection,"Filenames",0) == 0)
533                   //selection OK, add to list
534          Duplicate/O/R=[V_startRow,V_endRow] LocFilenames, filenames
535          Wave/T selectedFiles = $"filenames"
536          num_sans_files = numpnts(selectedFiles)
537                   SVAR temp = root:myGlobals:Protocols:gSAM
538          Variable ii=0
539          do
540            temp = temp+selectedFiles[ii]+","
541            ii+=1
542          while (ii < num_sans_files)
543      Else
544                                DoAlert 0,"Invalid selection from the File Catalog window"
545      Endif
546        else
547                //no selection
548                String/G root:myGlobals:Protocols:gSAM = "ask"
549                DoAlert 0,"No file selected from File Catalog table or no File Catalog table available"
550        Endif
551        return(0)
552End
553
554//button control to set the background (BGD) file name to the
555//selected name in the CAT/SHORT window
556//the version number of the file need not be selected, it will be added later if needed
557//multiple BGD files can be added together if the file list is not reset
558//
559Function PickBGDButton(ctrlName) : ButtonControl
560        String ctrlName
561
562        //set the BGD file(s) as a global string
563        //multiple files are added as a COMMA separated list of files, w/extension
564        //global string is either null or contains filename(s) on entry
565       
566        //ask to reset the list?
567        DoAlert 1,"Reset the list of background files?"
568        if(V_flag == 1)
569                String/G root:myGlobals:Protocols:gBGD = ""
570        Endif
571
572        Variable catVSTableExists, num_sans_files
573        catVSTableExists = WinType("CatVSTable")
574        //??BUG?? V_flag returns 1 even if no selection?
575        //check manually for null selection
576        //Print "local v_flag = ",num2str(V_flag)
577        Wave/T LocFilenames = $"root:myGlobals:CatVSHeaderInfo:Filenames"
578        if (catVSTableExists != 0)
579                GetSelection table,CatVSTable,7
580                if(strsearch(S_selection,"Filenames",0) == 0)
581           //selection OK, add to list
582                   Duplicate/O/R=[V_startRow,V_endRow] LocFilenames, filenames
583                   Wave/T selectedFiles = $"filenames"
584                   num_sans_files = numpnts(selectedFiles)
585                   SVAR temp = root:myGlobals:Protocols:gBGD
586                        Variable ii=0
587                        do
588                                temp = temp+selectedFiles[ii]+","
589                                ii+=1
590                        while (ii < num_sans_files)
591                Else
592                        DoAlert 0,"Invalid selection from the File Catalog table"
593                Endif
594        else
595                //no selection
596                DoAlert 0,"No file selected from File Catalog table or no File Catalog table available"
597        Endif
598       
599End
600
601//button control function to set the background (EMP) file name to the
602//selected name in the CAT/SHORT window
603//the version number of the file need not be selected, it will be added later if needed
604//multiple EMP files can be added together if the file list is not reset
605//
606Function PickEMPButton(ctrlName) : ButtonControl
607        String ctrlName
608
609        //ask to reset the list?
610        DoAlert 1,"Reset the list of empty cell files?"
611        if(V_flag == 1)
612                String/G root:myGlobals:Protocols:gEMP = ""
613        Endif
614       
615        Variable catVSTableExists, num_sans_files
616        catVSTableExists = WinType("catVSTable")
617        //??BUG?? V_flag returns 1 even if no selection?
618        //check manually for null selection
619        //Print "local v_flag = ",num2str(V_flag)
620        Wave/T LocFilenames = $"root:myGlobals:CatVSHeaderInfo:Filenames"
621        if (catVSTableExists != 0)
622                GetSelection table,CatVSTable,7
623                if(strsearch(S_selection,"Filenames",0) == 0)
624                   //selection OK, add to list
625                Duplicate/O/R=[V_startRow,V_endRow] LocFilenames, filenames
626        Wave/T selectedFiles = $"filenames"
627                num_sans_files = numpnts(selectedFiles)
628                SVAR temp = root:myGlobals:Protocols:gEMP
629                        Variable ii=0
630                        do
631                                temp = temp+selectedFiles[ii]+","
632                                ii+=1
633                        while (ii < num_sans_files)
634                Else
635                        DoAlert 0,"Invalid selection from the File Catalog table"
636                Endif
637        else
638                //no selection
639                DoAlert 0,"No file selected from File Catalog table or no File Catalog table available"
640        Endif
641       
642End
643
644//button control function to set the background (DIV) file name to the
645//selected name in the CAT/SHORT window
646//the version number of the file need not be selected, it will be added later if needed
647//there can only be one DIV file for a given protocol
648//
649Function PickDIVButton(ctrlName) : ButtonControl
650        String ctrlName
651
652        //alwys reset the list of DIV files, there can be only one
653        String/G root:myGlobals:Protocols:gDIV = ""
654        Variable catVSTableExists, num_sans_files
655        catVSTableExists = WinType("catVSTable")
656        //??BUG?? V_flag returns 1 even if no selection?
657        //check manually for null selection
658        //Print "local v_flag = ",num2str(V_flag)
659        Wave/T LocFilenames = $"root:myGlobals:CatVSHeaderInfo:Filenames"
660        if (catVSTableExists != 0)
661                GetSelection table,CatVSTable,7
662                if(strsearch(S_selection,"Filenames",0) == 0)
663                   //selection OK, add to list
664        Duplicate/O/R=[V_startRow,V_endRow] LocFilenames, filenames
665                Wave/T selectedFiles = $"filenames"
666           num_sans_files = numpnts(selectedFiles)           
667                   SVAR temp = root:myGlobals:Protocols:gDIV
668                        temp = selectedFiles[0]
669                Else
670                        DoAlert 0,"Invalid selection from the File Catalog table"
671                Endif
672        else
673                //no selection
674                DoAlert 0,"No file selected from File Catalog table or no File Catalog table available"
675        Endif
676       
677End
678
679//button control function to set the background (MSK) file name to the
680//selected name in the CAT/SHORT window
681//the version number of the file need not be selected, it will be added later if needed
682//there can only be one MSK file for a given protocol
683//
684Function PickMASKButton(ctrlName) : ButtonControl
685        String ctrlName
686       
687        //always reset the list of MASK files - ther can be only one
688        String/G root:myGlobals:Protocols:gMASK = ""
689       
690        Variable catVSTableExists, num_sans_files
691        catVSTableExists = WinType("catVSTable")
692        //??BUG?? V_flag returns 1 even if no selection?
693        //check manually for null selection
694        //Print "local v_flag = ",num2str(V_flag)
695        Wave/T LocFilenames = $"root:myGlobals:CatVSHeaderInfo:Filenames"
696        if (catVSTableExists != 0)
697                GetSelection table,CatVSTable,7
698                if(strsearch(S_selection,"Filenames",0) == 0)
699                        //selection OK, add to list
700                Duplicate/O/R=[V_startRow,V_endRow] LocFilenames, filenames
701                Wave/T selectedFiles = $"filenames"
702                num_sans_files = numpnts(selectedFiles)           
703                        SVAR temp = root:myGlobals:Protocols:gMASK
704                        temp = selectedFiles[0]
705        Else
706                        DoAlert 0,"Invalid selection from the File Catalog table"
707                Endif
708        else
709                //no selection
710                DoAlert 0,"No file selected from File Catalog table or no File Catalog table available"
711        Endif
712       
713End
714
715//button action function to reduce one file with the information specified on
716//the panel
717//a temporary protocol is created, even if the fields correspond to a named protocol
718//(only the protocol wave values are written to the data header, but the name is written to the
719//schematic - this could cause some unwanted confusion)
720//
721//if a sample file(s) is selected, only that file(s) will be reduced
722//if no file is selected, the user will be prompted with a standard open
723//dialog to select sample data file(s)
724//
725Function ReduceOneButton(ctrlName) : ButtonControl
726        String ctrlName
727
728        //parse the information on the panel and assign to tempProtocol wave (in protocol folder)
729        //and execute
730        String temp="root:myGlobals:Protocols:tempProtocol"
731        Wave/T w=$temp
732        Variable ii=0,num=8
733        do
734                w[ii] = ""
735                ii+=1
736        while(ii<num)
737       
738        MakeProtocolFromPanel(w)
739
740        //the "current" protocol is the "tempProtocol" that was parsed from the panel input
741        //set the global, so that the data writing routine can find the protocol wave (fatal otherwise)
742        String/G root:myGlobals:Protocols:gProtoStr="tempProtocol"
743       
744        PathInfo catPathName                    //this is where the files came from
745        String pathstr=S_path,samStr
746       
747        //take the string from the panel
748        SVAR tempStr = root:myGlobals:Protocols:gSAM
749       
750        if( (strlen(tempStr) == 0) || (cmpstr(tempStr,"ask")==0) )
751                //let user select the files
752                tempStr="ask"
753                ExecuteProtocol(temp,tempStr)
754                return(0)
755        Else
756                //parse the list of numbers
757                //send only the filenames, without paths
758                samStr = ParseRunNumberList(tempStr)
759                If(strlen(samStr)==0)
760                        DoAlert 0,"The SAM file number cound not be interpreted. Please enter a valid run number or filename"
761                        return(1)
762                endif
763                tempStr=samStr          //reset the global
764                ExecuteProtocol(temp,samStr)
765                return(0)
766        endif
767End
768
769
770//button action function will prompt user for absolute scaling parameters
771//either from an empty beam file or by manually entering the 4 required values
772//uses the same function and shared global string as the questionnare form of reduction
773//in "protocol.ipf" - the string is root:myGlobals:Protocols:gAbsStr
774//
775Function SetABSParamsButton(ctrlName) : ButtonControl
776        String ctrlName
777
778        //will prompt for a list of ABS parameters (4) through a global string variable
779       
780        Execute "AskForAbsoluteParams_Quest()"
781       
782End
783
784//simple button action procedure to bring the CAT/SHORT notebook window to the front
785//in case it's buried behind other windows
786//
787Function ShowCATButton(ctrlName) : ButtonControl
788        String ctrlName
789
790        DoWindow/F CatVSTable
791        if(V_flag==0)
792                DoAlert 0,"There is no File Catalog table window. Use the File Catalog table button to create one."
793        Endif
794       
795End
796
797//the panel recreation macro
798//
799Window ProtocolPanel()
800        PauseUpdate; Silent 1           // building window...
801        NewPanel /W=(553,48,851,500) /K=1 as "Data Reduction Protocol"
802        ModifyPanel cbRGB=(27589,43441,64159), fixedSize=1
803        SetDrawLayer UserBack
804        DrawLine 2,25,300,25
805        DrawLine 2,69,300,69
806        DrawLine 2,120,300,120
807        DrawLine 2,169,300,169
808        DrawLine 2,217,300,217
809        DrawLine 2,262,300,262
810        DrawLine 2,357,300,357
811        DrawLine 2,379,300,379
812        DrawLine 2,308,300,308
813        Button button0,pos={12,2},size={90,20},proc=DoCatShort,title="File Catalog"
814        Button button0,help={"Use this button to generate a catalog of raw data file headers. Select files from the list for EMP, BGD,..."}
815        Button button_help,pos={260,2},size={25,20},proc=ShowProtoHelp,title="?"
816        Button button_help,help={"Show the help file for setting up a reduction protocol"}
817        CheckBox prot_check,pos={5,75},size={74,14},title="Background"
818        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"}
819        CheckBox prot_check,value= 1
820        Button pick_bgd,pos={114,75},size={100,20},proc=PickBGDButton,title="set BGD file"
821        Button pick_bgd,help={"This button will set the file selected in the File Catalog table to be the background file."}
822        Button recallProt,pos={7,406},size={107,20},proc=RecallProtocolButton,title="Recall Protocol"
823        Button recallProt,help={"Resets the panel to the file choices in  a previously saved protocol"}
824        Button del_protocol,pos={7,428},size={110,20},proc=DeleteProtocolButton,title="Delete Protocol"
825        Button del_protocol,help={"Use this to delete a previously saved protocol."}
826        Button done_protocol,pos={225,428},size={45,20},proc=DoneProtocolButton,title="Done"
827        Button done_protocol,help={"This button will close the panel. The panel can be recalled at any time from the SANS menu."}
828        Button saveProtocol,pos={7,384},size={100,20},proc=SaveProtocolButton,title="Save Protocol"
829        Button saveProtocol,help={"Saves the cerrent selections in the panel to a protocol which can be later recalled"}
830        CheckBox prot_check_1,pos={5,127},size={71,14},title="Empty Cell"
831        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"}
832        CheckBox prot_check_1,value= 1
833        CheckBox prot_check_2,pos={6,175},size={72,14},title="Sensitivity"
834        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"}
835        CheckBox prot_check_2,value= 1
836        CheckBox prot_check_3,pos={9,268},size={43,14},title="Mask"
837        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"}
838        CheckBox prot_check_3,value= 1
839        Button pick_emp,pos={113,125},size={100,20},proc=PickEMPButton,title="set EMP file"
840        Button pick_emp,help={"This button will set the file selected in the File Catalog table to be the empty cell file."}
841        Button pick_DIV,pos={114,173},size={100,20},proc=PickDIVButton,title="set DIV file"
842        Button pick_DIV,help={"This button will set the file selected in the File Catalog table to be the sensitivity file."}
843        Button pick_MASK,pos={119,266},size={100,20},proc=PickMASKButton,title="set MASK file"
844        Button pick_MASK,help={"This button will set the file selected in the File Catalog table to be the mask file."}
845        SetVariable bgdStr,pos={7,98},size={250,15},title="file:"
846        SetVariable bgdStr,help={"Filename of the background file(s) to be used in the data reduction"}
847        SetVariable bgdStr,limits={-Inf,Inf,0},value= root:myGlobals:Protocols:gBGD
848        SetVariable empStr,pos={8,148},size={250,15},title="file:"
849        SetVariable empStr,help={"Filename of the empty cell file(s) to be used in the data reduction"}
850        SetVariable empStr,limits={-Inf,Inf,0},value= root:myGlobals:Protocols:gEMP
851        SetVariable divStr,pos={9,197},size={250,15},title="file:"
852        SetVariable divStr,help={"Filename of the detector sensitivity file to be used in the data reduction"}
853        SetVariable divStr,limits={-Inf,Inf,0},value= root:myGlobals:Protocols:gDIV
854        SetVariable maskStr,pos={9,289},size={250,15},title="file:"
855        SetVariable maskStr,help={"Filename of the mask file to be used in the data reduction"}
856        SetVariable maskStr,limits={-Inf,Inf,0},value= root:myGlobals:Protocols:gMASK
857        Button ReduceOne,pos={194,384},size={100,20},proc=ReduceOneButton,title="Reduce A File"
858        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"}
859        CheckBox prot_check_4,pos={5,30},size={53,14},title="Sample"
860        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"}
861        CheckBox prot_check_4,value= 1
862        Button pick_sam,pos={115,28},size={100,20},proc=PickSAMButton,title="set SAM file"
863        Button pick_sam,help={"This button will set the file selected in the File Catalog table to be the sample file"}
864        SetVariable samStr,pos={6,50},size={250,15},title="file:"
865        SetVariable samStr,help={"Filename of the sample file(s) to be used in the data reduction"}
866        SetVariable samStr,limits={-Inf,Inf,0},value= root:myGlobals:Protocols:gSAM
867        Button pick_ABS,pos={115,220},size={110,20},proc=SetABSParamsButton,title="set ABS params"
868        Button pick_ABS,help={"This button will prompt the user for absolute scaling parameters"}
869        CheckBox prot_check_9,pos={7,222},size={59,14},title="Absolute"
870        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"}
871        CheckBox prot_check_9,value= 1
872        SetVariable absStr,pos={7,243},size={250,15},title="parameters:"
873        SetVariable absStr,help={"Keyword-string of values necessary for absolute scaling of data. Remaining parameters are taken from the sample file."}
874        SetVariable absStr,limits={-Inf,Inf,0},value= root:myGlobals:Protocols:gAbsStr
875        Button show_cat,pos={120,2},size={120,20},proc=ShowCATButton,title="Show File Catalog"
876        Button show_cat,help={"Brings the current condensed File Catalog table to the front"}
877        CheckBox prot_check_5,pos={6,311},size={56,14},title="Average"
878        CheckBox prot_check_5,help={"If checked, the specified averaging will be performed at the end of the data reduction."}
879        CheckBox prot_check_5,value= 1
880        Button pick_AVE,pos={108,313},size={150,20},proc=SetAverageParamsButtonProc,title="set AVERAGE params"
881        Button pick_AVE,help={"Prompts the user for the type of 1-D averaging to perform, as well as saving options"}
882        SetVariable aveStr,pos={9,336},size={250,15},title="parameters:"
883        SetVariable aveStr,help={"Keyword-string of choices used for averaging and saving the 1-D data files"}
884        SetVariable aveStr,limits={-Inf,Inf,0},value= root:myGlobals:Protocols:gAVE
885        //only show DRK if user wants to see it
886        //if global = 1,then show => set disable = 0
887        CheckBox prot_check_6,pos={6,363},size={113,14},proc=DrkCheckProc,title="Use DRK correction"
888        CheckBox prot_check_6,help={"If checked, the selected file will be used for DRK correction. Typically this is NOT checked"}
889        CheckBox prot_check_6,value= 0,disable = (!root:myGlobals:gAllowDRK)
890        SetVariable drkStr,pos={120,363},size={150,15},title="."
891        SetVariable drkStr,help={"DRK detector count file"},disable = (!root:myGlobals:gAllowDRK)
892        SetVariable drkStr,limits={-Inf,Inf,0},value= root:myGlobals:Protocols:gDRK
893        Button export_button, size={60,20},pos={125,384},title="Export",proc=ExportProtocol
894        Button export_button, help={"Exports the protocol to disk for Importing into another experiment"}
895        Button import_button, size={60,20},pos={125,406},title="Import",proc=ImportProtocol
896        Button import_button,help={"Imports a protocol from disk for use in this experiment"}
897EndMacro
898
899//activated when user checks/unchecks the box
900//either prompts for a file using a standard dialog, or removes the current file
901Function DrkCheckProc(ctrlName,checked) : CheckBoxControl
902        String ctrlName
903        Variable checked                //Desired state, not previous state
904
905        SVAR drkStr=root:myGlobals:Protocols:gDRK
906        if(checked==1)
907                //print "Unchecked on call"
908                //this just asks for the filename, doesn't open the file
909                String msgStr="Select the DRK file",fullPath="",fileStr=""
910                Variable refnum
911               
912                Open/D/R/T="????"/M=(msgStr)/P=catPathName refNum
913                fullPath = S_FileName           //fname is the full path
914                if(cmpstr(fullpath,"")==0)
915                        //user cancelled
916                        CheckBox prot_check_6,value=0           //keep box unchecked
917                        return(0)
918                Endif
919                fileStr=GetFileNameFromPathNoSemi(fullPath)
920                //Print fileStr
921                //update the global string
922                drkStr = ReplaceStringByKey("DRK",drkStr,fileStr,"=",",")
923                drkStr = ReplaceNumberByKey("DRKMODE", drkStr, 10 ,"=",",")
924        else
925                //print "checked on call"
926                drkStr="DRK=none,DRKMODE=0,"            //change the global
927        endif
928       
929End
930
931
932Function ShowProtoHelp(ctrlName) : ButtonControl
933        String ctrlName
934        DisplayHelpTopic/Z/K=1 "SANS Data Reduction Tutorial[Build a Data Reduction Protocol]"
935        if(V_flag !=0)
936                DoAlert 0,"The SANS Data Reduction Tutorial Help file could not be found"
937        endif
938End
939
940//button action procedure to get the type of average requested by the user
941//presented as a missing parameter dialog, which is really user-UN-friendly
942//and will need to be re-thought. Defaults of dialog are set for normal
943//circular average, so typically click "continue" and proceed
944//
945Function SetAverageParamsButtonProc(ctrlName) : ButtonControl
946        String ctrlName
947       
948        Execute "GetAvgInfo()"
949       
950        //set the global string
951        SVAR tempStr = root:myGlobals:Protocols:gAvgInfoStr
952        String/G root:myGlobals:Protocols:gAVE = tempStr
953
954End
955
956//procedure called by protocol panel to ask user for average type choices
957// somewhat confusing and complex, but may be as good as it gets.
958//
959Proc GetAvgInfo(av_typ,autoSave,autoName,autoPlot,side,phi,dphi,width,QCtr,QDelta)
960        String av_typ,autoSave,AutoName,autoPlot,side
961        Variable phi=0,dphi=10,width=10,Qctr = 0.01,qDelta=10
962        Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII;PNG_Graphic"
963// comment out above line in DEMO_MODIFIED version, and uncomment the line below (to disable PNG save)
964//      Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII"
965        Prompt autoSave,"Save files to disk?",popup,"Yes;No"
966        Prompt autoName,"Auto-Name files?",popup,"Auto;Manual"
967        Prompt autoPlot,"Plot the averaged Data?",popup,"Yes;No"
968        Prompt side,"Include detector halves?",popup,"both;right;left"
969        Prompt phi,"Orientation Angle (-90,90) degrees (Rectangular or Sector)"
970        Prompt dphi, "Azimuthal range (0,45) degrees (Sector only)"
971        Prompt width, "Width of Rectangular average (1,128)"
972        Prompt Qctr, "q-value of center of annulus"
973        Prompt Qdelta,"Pixel width of annulus"
974
975        //assign results of dialog to key=value string, semicolon separated
976        //do only what is necessary, based on av_typ
977        String/G root:myGlobals:Protocols:gAvgInfoStr=""
978       
979        // all averages need these four values
980        root:myGlobals:Protocols:gAvgInfoStr += "AVTYPE=" + av_typ + ";"
981        root:myGlobals:Protocols:gAvgInfoStr += "SAVE=" + autoSave + ";"
982        root:myGlobals:Protocols:gAvgInfoStr += "NAME=" + autoName + ";"
983        root:myGlobals:Protocols:gAvgInfoStr += "PLOT=" + autoPlot + ";"
984       
985        if(cmpstr(av_typ,"Sector")==0)
986                root:myGlobals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
987                root:myGlobals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
988                root:myGlobals:Protocols:gAvgInfoStr += "DPHI=" + num2str(dphi) + ";"
989        Endif
990       
991        if(cmpstr(av_typ,"Rectangular")==0)
992                root:myGlobals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
993                root:myGlobals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
994                root:myGlobals:Protocols:gAvgInfoStr += "WIDTH=" + num2str(width) + ";"
995        Endif
996       
997        if(cmpstr(av_typ,"Annular")==0)
998                root:myGlobals:Protocols:gAvgInfoStr += "QCENTER=" + num2str(QCtr) + ";"
999                root:myGlobals:Protocols:gAvgInfoStr += "QDELTA=" + num2str(QDelta) + ";"
1000        Endif
1001End
1002
1003//not used????
1004//checks the syntax of all of the file fields in the panel
1005Function CheckProtocolSyntax(ctrlName) : ButtonControl
1006        String ctrlName
1007       
1008        String retStr=""
1009        //SAM
1010        SVAR list = root:myGlobals:Protocols:gSAM
1011        retStr = ParseRunNumberList(list)
1012        if(strlen(retStr)==0)
1013                //error
1014                Print "SAM Syntax Error"
1015                return(1)
1016        else
1017                list = retStr
1018                Print "SAM syntax OK"
1019        Endif
1020
1021        //MASK
1022        SVAR list = root:myGlobals:Protocols:gMASK
1023        retStr = ParseRunNumberList(list)
1024       
1025End
1026//*************
1027
1028
1029
1030//
1031// Procedure files for creating and executing a data reduction protocol
1032//
1033//**** ONLY invoked from the MAIN PANEL**** NOT REALLY EVER USED ******
1034//Procedure for reducing a sample file (multiple added files) with a specified
1035//protocol. User may create a new protocol, and will be prompted
1036//for information "questionnare-style" where the user must know the
1037//filenames for empty cell, background...etc.. as they will be presented
1038//with standard file open dialogs to select each file desired for use in the
1039//new protocol
1040//once a protocol is selected (or created) the uer is propmted for sample data
1041// and the file is processed through the protocol.
1042//
1043Proc ReduceAFile()
1044
1045        String protocolName="",waveStr="",samStr = "ask"
1046        Variable err
1047       
1048        //pick a protocol wave from the Protocols folder
1049        //must switch to protocols folder to get wavelist (missing parameter)
1050        SetDataFolder root:myGlobals:Protocols
1051        PickAProtocol()
1052       
1053        //get the selected protocol wave choice through a global string variable
1054        protocolName = root:myGlobals:Protocols:gProtoStr
1055       
1056        //If "CreateNew" was selected, go to the questionnare, to make a new set
1057        //and put the name of the new Protocol wave in gProtoStr
1058        if(cmpstr("CreateNew",protocolName) == 0)
1059                ProtocolQuestionnare()
1060                protocolName = root:myGlobals:Protocols:gProtoStr
1061        Endif
1062       
1063        //give the full path:name to the executeProtocol function
1064        waveStr = "root:myGlobals:Protocols:"+protocolName
1065        //samStr is set at top to "ask", since this is the action always desired from "ReduceAFile"
1066       
1067        ExecuteProtocol(waveStr,samStr)
1068       
1069        //return data folder to root before Macro is done
1070        SetDataFolder root:
1071       
1072End
1073
1074
1075//prompts the user to pick a previously created protocol from a popup list
1076//of given the option to create a new protocol
1077//the chosen protocol is passed back to the calling procedure by a global string
1078//the popup is presented as a missing parameter dialog (called with empty parameter list)
1079//
1080Proc PickAProtocol(protocol)
1081        String Protocol
1082        Prompt Protocol "Pick A Protocol",popup, WaveList("*",";","")
1083       
1084        String/G  root:myGlobals:Protocols:gProtoStr = protocol
1085End
1086
1087Proc DeleteAProtocol(protocol)
1088        String Protocol
1089//      Prompt Protocol "Delete A Protocol",popup, WaveList("*",";","")
1090        Prompt Protocol "Delete A Protocol",popup, DeletableProtocols()
1091
1092        String/G  root:myGlobals:Protocols:gProtoStr = protocol
1093End
1094
1095Function/S DeletableProtocols()
1096        String list=WaveList("*",";","")
1097
1098        list= RemoveFromList("Base", list  , ";")
1099        list= RemoveFromList("DoAll", list  , ";")
1100        list= RemoveFromList("CreateNew", list  , ";")
1101        list= RemoveFromList("tempProtocol", list  , ";")
1102        if(cmpstr(list,"")==0)
1103                list = "_no_protocols_;"
1104        endif
1105       
1106        return(list)
1107End
1108
1109//missing paramater dialog to solicit user for a waveStr for the protocol
1110//about to be created
1111//name is passed back as a global string and calling procedure is responsible for
1112//checking for wave conflicts and valid names
1113//
1114Proc AskForName(protocol)
1115        String Protocol
1116        Prompt Protocol "Enter a new name for your protocol (no extension)"
1117       
1118        String/G  root:myGlobals:Protocols:gNewStr = protocol
1119End
1120
1121//this is a lengthy procedure for sequentially polling the user about what data
1122//reduction steps they want to be performed during the protocol
1123//ensures that a valid protocol name was chosen, then fills out each "item"
1124//(6 total) needed for reduction
1125//it the user cancels at any point, the partial protocol will be deleted
1126//
1127Function ProtocolQuestionnare()
1128        String filename,cmd
1129        Variable notDone,refnum
1130       
1131        //prompt for name of new protocol wave to save
1132        do
1133                Execute "AskForName()"
1134                SVAR newProtoStr = root:myGlobals:Protocols:gNewStr
1135               
1136                //make sure it's a valid IGOR name
1137                newProtoStr = CleanupName(newProtoStr,0)        //strict naming convention
1138                String/G root:myGlobals:Protocols:gNewStr=newProtoStr           //reassign, if changed
1139                //Print "newProtoStr = ",newProtoStr
1140               
1141                SetDataFolder root:myGlobals:Protocols
1142                if(WaveExists( $("root:myGlobals:Protocols:" + newProtoStr) ) == 1)
1143                        //wave already exists
1144                        DoAlert 0,"that name is already in use. Please pick a new name"
1145                        notDone = 1
1146                else
1147                        //name is  good
1148                        notDone = 0
1149                Endif
1150        while(notDone)
1151       
1152        //Print "protocol questionnare is "+newProtocol
1153       
1154        //make a new text wave (6 points) and fill it in, in response to questions
1155        SetDataFolder root:myGlobals:Protocols //(redundant - full wave specs are used)
1156        Make/O/T/N=8 $("root:myGlobals:Protocols:" + newProtoStr)
1157        Wave/T newProtocol = $("root:myGlobals:Protocols:" + newProtoStr)
1158       
1159        //ask the questions
1160        /////
1161        //*****Multiple files in these lists are full paths/filenames which may or may not
1162        //have semicolon version numbers in the filename. Therefore, construct the list with
1163        //COMMAS as separators - to avoid messy parsing
1164        ///////
1165       
1166       
1167//////////////////////////
1168        String drkStr="",fileStr=""
1169        DoAlert 1,"Do you want to correct your data for DRK (beam off) counts?"
1170        if(V_flag == 1)         //1=yes
1171                //prompt for DRK  file, but don't actually open it (/D flag)
1172                Open/D/R/T="TEXT????"/M="Select the DRK file"/P=catPathName refnum
1173                //check for cancel
1174                if(strlen(S_filename)==0)
1175                        //user cancelled, abort
1176                        KillWaves/Z newProtocol
1177                        SetDataFolder root:
1178                        Abort "Incomplete protocol has been deleted"
1179                Endif
1180                //assign filename (just the name) to [6]
1181                fileStr = GetFileNameFromPathNoSemi(S_filename)
1182                drkStr = "DRK=none,DRKMODE=0,"
1183                drkStr = ReplaceStringByKey("DRK",drkStr,fileStr,"=",",")
1184                drkStr = ReplaceNumberByKey("DRKMODE", drkStr, 10 ,"=",",")     
1185                newProtocol[6] = drkStr
1186        else
1187                //no Work.DRK desired
1188                newProtocol[6] = "DRK=none,DRKMODE=0,"
1189        Endif
1190       
1191////////////
1192       
1193/////////////////
1194        DoAlert 1,"Do you want to subtract background from your data?"
1195        if(V_flag == 1)         //1=yes
1196                //prompt for background file, but don't actually open it (/D flag)
1197                Open/D/R/T="TEXT????"/M="Select the Background data file"/P=catPathName refnum
1198                //check for cancel
1199                if(strlen(S_filename)==0)
1200                        //user cancelled, abort
1201                        KillWaves/Z newProtocol
1202                        SetDataFolder root:
1203                        Abort "Incomplete protocol has been deleted"
1204                Endif
1205                //assign filename (full path) to [0]
1206                newProtocol[0] = GetFileNameFromPathNoSemi(S_filename)
1207               
1208                notDone=1
1209                do
1210                        //prompt for additional background files
1211                        DoAlert 1,"Do you want to add another background file?"
1212                        if(V_flag == 1)         //yes
1213                                Open/D/R/T="TEXT????"/M="Select another Background data file"/P=catPathName refnum
1214                                //check for cancel
1215                                if(strlen(S_filename)==0)
1216                                        //user cancelled, abort ********maybe just break out of the loop here
1217                                        KillWaves/Z newProtocol
1218                                        SetDataFolder root:
1219                                        Abort "Incomplete protocol has been deleted"
1220                                Endif
1221                                //assign filename (full path) to [0]
1222                                newProtocol[0] += "," + GetFileNameFromPathNoSemi(S_filename)           //***COMMA separated list
1223                                notDone = 1             //keep going
1224                        else
1225                                notDone = 0                     //no more to add
1226                        Endif
1227                While(notDone)
1228        else            //no background desired
1229                newProtocol[0] = "none"
1230        Endif
1231////////////////////// 
1232        DoAlert 1,"Do you want to subtract empty cell scattering from your data?"
1233        if(V_flag == 1)         //1=yes
1234                //prompt for Empty cell file, but don't actually open it (/D flag)
1235                Open/D/R/T="TEXT????"/M="Select the Empty Cell data file"/P=catPathName refnum
1236                //check for cancel
1237                if(strlen(S_filename)==0)
1238                        //user cancelled, abort
1239                        KillWaves/Z newProtocol
1240                        SetDataFolder root:
1241                        Abort "Incomplete protocol has been deleted"
1242                Endif
1243                //assign filename (full path) to [1]
1244                newProtocol[1] = GetFileNameFromPathNoSemi(S_filename)
1245               
1246                notDone=1
1247                do
1248                        //prompt for additional Empty Cell files
1249                        DoAlert 1,"Do you want to add another Empty Cell file?"
1250                        if(V_flag == 1)         //yes
1251                                Open/D/R/T="TEXT????"/M="Select another Empty Cell data file"/P=catPathName refnum
1252                                //check for cancel
1253                                if(strlen(S_filename)==0)
1254                                        //user cancelled, abort ********maybe just break out of the loop here
1255                                        KillWaves/Z newProtocol
1256                                        SetDataFolder root:
1257                                        Abort "Incomplete protocol has been deleted"
1258                                Endif
1259                                //assign filename (full path) to [1]
1260                                newProtocol[1] += "," + GetFileNameFromPathNoSemi(S_filename)           //***COMMA separated list
1261                                notDone = 1             //keep going
1262                        else
1263                                notDone = 0                     //no more to add
1264                        Endif
1265                While(notDone)
1266        else            //no background desired
1267                newProtocol[1] = "none"
1268        Endif
1269//////////////////////////
1270        DoAlert 1,"Do you want to correct your data for detector sensitivity?"
1271        if(V_flag == 1)         //1=yes
1272                //prompt for DIV  file, but don't actually open it (/D flag)
1273                Open/D/R/T="TEXT????"/M="Select the detector sensitivity file"/P=catPathName refnum
1274                //check for cancel
1275                if(strlen(S_filename)==0)
1276                        //user cancelled, abort
1277                        KillWaves/Z newProtocol
1278                        SetDataFolder root:
1279                        Abort "Incomplete protocol has been deleted"
1280                Endif
1281                //assign filename (full path) to [2]
1282                newProtocol[2] = GetFileNameFromPathNoSemi(S_filename)
1283        else
1284                //no Work.DIV desired
1285                newProtocol[2] = "none"
1286        Endif   
1287//////////////////////////
1288        DoAlert 1,"Do you want to mask your files before averaging?"
1289        if(V_flag == 1)         //1=yes
1290                //prompt for mask  file, but don't actually open it (/D flag)
1291                Open/D/R/T="TEXT????MASK"/M="Select the mask file"/P=catPathName refnum
1292                //check for cancel
1293                if(strlen(S_filename)==0)
1294                        //user cancelled, abort
1295                        KillWaves/Z newProtocol
1296                        SetDataFolder root:
1297                        Abort "Incomplete protocol has been deleted"
1298                Endif
1299                //assign filename (full path) to [3]
1300                newProtocol[3] = GetFileNameFromPathNoSemi(S_filename)
1301        else
1302                //no MASK desired
1303                newProtocol[3] = "none"
1304        Endif   
1305       
1306        //absolute scaling
1307       
1308        //////////////////////////
1309        //ABS parameters stored as keyword=value string
1310        DoAlert 1,"Do you want absolute scaling?"
1311        if(V_flag == 1)         //1=yes
1312                //missing param - prompt for values, put in semicolon-separated list
1313                Execute "AskForAbsoluteParams_Quest()"
1314                SVAR absStr =  root:myGlobals:Protocols:gAbsStr
1315                newProtocol[4] = absStr
1316        else
1317                //no absolute scaling desired
1318                newProtocol[4] = "none"
1319        Endif   
1320       
1321        //type of average, plot?, auto/manual naming/saving... put in semicolon separated string
1322        //of KEY=<value> format for easy parsing
1323        //Kewords are: AVTYPE,PHI,DPHI,PLOT,SAVE,NAME,SIDE,WIDTH
1324        //note that AVTYPE,NAME,SIDE have string values, others have numerical values
1325        ///////////////////////
1326        DoAlert 1,"Do you want to average your data to I vs. q?"
1327        if(V_flag == 1)         //1=yes
1328                String/G root:myGlobals:Protocols:gAvgInfoStr = ""
1329                Execute "GetAvgInfo()"          //will put up missing paramter dialog and do all the work
1330                //:gAvgInfo is reset by the Proc(), copy this string tot he protocol
1331                SVAR tempStr=root:myGlobals:Protocols:gAvgInfoStr
1332               
1333                //get a file path for saving files, if desired
1334                /////no - save files to the same data folder as the one with the raw data
1335                //then only one path to manage.
1336                //String yesNo = StringByKey("SAVE", tempStr,"=", ";")
1337                //if(cmpstr("Yes",yesNo) == 0)          //0=yes
1338                        //NewPath/C/M="Select Folder"/O Save_path               //Save_path is the symbolic path
1339                //Endif
1340
1341                newProtocol[5] = tempStr
1342                KillStrings/Z tempStr
1343        else
1344                //no averaging desired
1345                newProtocol[5] = "AVTYPE=none"
1346        Endif
1347       
1348        //returns the name of the newly created (= currently in use) protocol wave through a global
1349        String/G root:myGlobals:Protocols:gProtoStr = newProtoStr
1350End
1351
1352//function to check the work files (to see what's already there)
1353//and compare that with the files that are supposed to be there, according to the
1354//current protocol (to save unnecessary time re-loading files)
1355//
1356//the "type" folder is checked for all files in the list req(ested)Files
1357//note that the list of files is a full path:name;ver, while the
1358//fileList in the folder is just the name (or a list of names)
1359//
1360//returns 0 false, if files are NOT present
1361//or 1 = true, yes, the files are there as requested
1362//
1363Function AreFilesThere(type,reqFiles)
1364        String type,reqFiles
1365       
1366        //in general, reqFiles is a list of full paths to files - which MAY include semicolon version numbers
1367        //reqFiles MUST be constructed with COMMAS as list separators, to avoid disaster
1368        //when the version numbers are interpreted as filenames
1369       
1370        //get the number of files requested
1371        Variable nReq,nCur,match,ii
1372        nReq = ItemsInList(reqFiles,",")
1373       
1374        //get the name of the file currently in BGD - in the global fileList
1375        //fileList has NAMES ONLY - since it was derived from the file header
1376        String testStr
1377        testStr = "root:Packages:NIST:"+type+":fileList"
1378        if(Exists(testStr) == 2)                //2 if string variable exists
1379                SVAR curFiles = $testStr
1380        else
1381                //no files currently in type folder, return zero
1382                Return (0)
1383        Endif
1384        //get the number of files already in folder
1385        nCur = ItemsInList(curFiles,";")
1386        If(nCur != nReq)
1387                Return (0)              //quit now, the wrong number of files present
1388        Endif
1389        //right number of files... are the names right...
1390        //check for a match (case-sensitive!!) of each requested file in the curFile string
1391        //need to extract filenames from reqFiles, since they're the full path and name
1392       
1393        ii=0
1394        do
1395                testStr = StringFromList(ii,reqFiles,",")       //testStr is the Nth full path and filename
1396                //testStr = GetFileNameFromPathNoSemi(testStr)  //testStr will now be just the filename
1397                match = stringmatch(curFiles,testStr)
1398                If(!match)
1399                        Return (0)              //req file was not found in curFile list - get out now
1400                Endif
1401                ii+=1
1402        while(ii<nreq)
1403       
1404        Return (1)              //indicate that files are OK, no changes needed
1405End
1406
1407//will add the files specified in the protocol to the "type" folder
1408//will add multiple files together if more than one file is requested
1409//(list is a comma delimited list of filenames, with NO path information)
1410//
1411// This routine NOW DOES check for the possibility that the filenames may have ";vers" from the
1412// VAX - data should be picked up from Charlotte, where it won't have version numbers.
1413//
1414Function AddFilesInList(type,list)
1415        String type,list
1416       
1417        //type is the work folder to put the data into, and list is a COMMA delimited list of paths/names
1418        Variable num,ii,err=0,refNum
1419        String filename,pathStr=""
1420        PathInfo catPathName                    //this is where the files are
1421        pathstr=S_path
1422       
1423        num = ItemsInList(list,",")             // comma delimited list
1424       
1425        ii=0
1426        do
1427                //FindValidFilename only needed in case of vax version numbers
1428                filename = pathStr + FindValidFilename(StringFromList(ii,list,","))
1429                Open/Z/R refnum as filename
1430                if(V_flag != 0)         //file not found
1431                        //Print "file not found AddFilesInList()"
1432                        //Print filename
1433                        err = 1
1434                        return(err)
1435                Endif
1436                Close refnum            //file was found and opened, so close it
1437                ReadHeaderAndData(filename)
1438                if(ii == 0)
1439                        //first pass, wipe out the old contents of the work file
1440                        err =  Raw_to_work(type)
1441                else
1442                        err = Add_raw_to_work(type)
1443                Endif
1444                ii+=1
1445        while(ii<num)
1446        return(err)
1447End
1448
1449//function will reduce a sample file (or ask for file(s))
1450//using the protocol named as "protoStr" in the Protocols subfolder
1451//samStr is the file(s) or "ask" to force prompt
1452//sequentially proceeds through flowchart, doing reduction steps as needed
1453//show Schematic to debug what steps/values were used
1454//
1455//function is long, but straightforward logic
1456//
1457Function ExecuteProtocol(protStr,samStr)
1458        String protStr,samStr
1459        //protStr is the full path to the selected protocol wave
1460        //samStr is either "ask" or the name ONLY ofthe desired sample data file(s) (NO PATH)
1461        WAVE/T prot = $protStr
1462        SetDataFolder root:myGlobals:Protocols
1463       
1464        Variable filesOK,err,notDone
1465        String activeType, msgStr, junkStr, pathStr=""
1466        PathInfo catPathName                    //this is where the files are
1467        pathStr=S_path
1468       
1469       
1470        //Parse the instructions in the prot wave
1471        //0 - bkg
1472        //1 - emp
1473        //2 - div
1474        //3 - mask
1475        //4 - abs params c2-c5
1476        //5 - average params
1477        //6 = DRK file (**out of sequence)
1478       
1479        //prompt for sam data => read raw data, add to sam folder
1480        //or parse file(s) from the input paramter string
1481        activeType = "SAM"
1482        msgStr = "Select sample data"
1483        //Ask for SAM file or parse
1484        do
1485                if((cmpstr(samStr,"ask") == 0) || (cmpstr(samStr,"")==0) )              //zero if strings are equal
1486                        err = LoadRawSANSData(msgStr)           //will prompt for file
1487                        if(err)
1488                                PathInfo/S catPathName
1489                                Abort "reduction sequence aborted"
1490                        endif
1491                        UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1492                        err =  Raw_to_work(activeType)          //this is the first file (default)
1493                        //Ask for another SAM file
1494                        do
1495                                DoAlert 1,"Do you want to add another Sample file?"
1496                                if(V_flag == 1)         //yes
1497                                        err = LoadRawSANSData(msgStr)           //will prompt for file
1498                                        if(err)
1499                                                PathInfo/S catPathName
1500                                                Abort "reduction sequence aborted"
1501                                        endif
1502                                        UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1503                                        err = Add_raw_to_work(activeType)
1504                                        notDone = 1
1505                                else
1506                                        notDone = 0
1507                                endif
1508                        while(notDone)
1509                        break
1510                Endif
1511                //"none" is not an option - you always need a sample file - "none" will never return zero
1512                //if not "ask" AND not "none" then try to parse the filenames
1513                If((cmpstr(samStr,"none") != 0) && (cmpstr(samStr,"ask") != 0))
1514                        //filesOK = AreFilesThere(activeType,samStr)            //return 1 if correct files are already there
1515                        filesOK = 0             // Feb 2008, always force a reload of files. Maybe slow, but always correct
1516                        if(!filesOK)
1517                                //add the correct file(s) to SAM
1518                                err = AddFilesInList(activeType,samStr)
1519                                if(err)
1520                                        //Print "samstr = ",samStr
1521                                        Abort "SAM file not found, reset SAM file"
1522                                Endif
1523                        Endif
1524                Endif
1525        While(0)
1526        //always update
1527        UpdateDisplayInformation(ActiveType)
1528       
1529        //check for bkg file  -- "ask" might not fail - "ask?" will - ? not allowed in VAX filenames
1530        // add if needed
1531        //use a "case" statement
1532        msgStr = "Select background file"
1533        activeType = "BGD"
1534        do
1535                if(cmpstr(prot[0],"ask") == 0)          //zero if strings are equal
1536                        err = LoadRawSANSData(msgStr)           //will prompt for file
1537                        if(err)
1538                                PathInfo/S catPathName
1539                                Abort "reduction sequence aborted"
1540                        endif
1541                        UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1542                        err =  Raw_to_work(activeType)          //this is the first file (default)
1543                        //Ask for another BGD file
1544                        do
1545                                DoAlert 1,"Do you want to add another Background file?"
1546                                if(V_flag == 1)         //yes
1547                                        err = LoadRawSANSData(msgStr)           //will prompt for file
1548                                        if(err)
1549                                                PathInfo/S catPathName
1550                                                Abort "reduction sequence aborted"
1551                                        endif
1552                                        UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1553                                        err = Add_raw_to_work(activeType)
1554                                        notDone = 1
1555                                else
1556                                        notDone = 0
1557                                endif
1558                        while(notDone)
1559                        UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1560                        break
1561                Endif
1562                If(cmpstr(prot[0],"none") == 0)
1563                        //clean out the BKG folder?
1564                        //KillDataFolder root:BKG
1565                        //NewDataFolder/O root:BKG
1566                        break
1567                Endif
1568                //if not "ask" AND not "none" then try to parse the filenames
1569                If((cmpstr(prot[0],"none") != 0) && (cmpstr(prot[0],"ask") != 0))
1570                        //filesOK = AreFilesThere(activeType,prot[0])
1571                        filesOK = 0             // Feb 2008, always force a reload of files. Maybe slow, but always correct
1572                        if(!filesOK)
1573                                //add the correct file(s) to BGD
1574                                err = AddFilesInList(activeType,prot[0])
1575                                If(err)
1576                                        Abort "BGD file not found. Reset BGD file list"
1577                                Endif
1578                        Endif
1579                        UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1580                Endif
1581        While(0)
1582       
1583       
1584        //check for emp file (prot[1])
1585        // add if needed
1586        msgStr = "Select empty cell data"
1587        activeType = "EMP"
1588        do
1589                if(cmpstr(prot[1],"ask") == 0)
1590                        err = LoadRawSANSData(msgStr)           //will prompt for file
1591                        if(err)
1592                                PathInfo/S catPathName
1593                                Abort "reduction sequence aborted"
1594                        endif
1595                        UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1596                        err =  Raw_to_work(activeType)          //this is the first file (default)
1597                        //Ask for another EMP file
1598                        do
1599                                DoAlert 1,"Do you want to add another Empty Cell file?"
1600                                if(V_flag == 1)         //yes
1601                                        err = LoadRawSANSData(msgStr)           //will prompt for file
1602                                        if(err)
1603                                                PathInfo/S catPathName
1604                                                Abort "reduction sequence aborted"
1605                                        endif
1606                                        UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1607                                        err = Add_raw_to_work(activeType)
1608                                        notDone = 1
1609                                else
1610                                        notDone = 0
1611                                endif
1612                        while(notDone)
1613                        UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1614                        break
1615                Endif
1616                If(cmpstr(prot[1],"none") == 0)
1617                        //clean out the EMP folder?
1618                        //KillDataFolder root:Packages:NIST:EMP
1619                        //NewDataFolder/O root:Packages:NIST:EMP
1620                        break
1621                Endif
1622                //if not "ask" AND not "none" then try to parse the filenames
1623                If((cmpstr(prot[1],"none") != 0) && (cmpstr(prot[1],"ask") != 0))
1624                        //filesOK = AreFilesThere(activeType,prot[1])
1625                        filesOK = 0             // Feb 2008, always force a reload of files. Maybe slow, but always correct
1626                        if(!filesOK)
1627                                //add the correct file(s) to BGD
1628                                err = AddFilesInList(activeType,prot[1])
1629                                If(err)
1630                                        Abort "EMP file not found. Reset EMP file list"
1631                                Endif
1632                        Endif
1633                        UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1634                Endif
1635        While(0)
1636       
1637        //do the CORRECT step based on the answers to emp and bkg subtraction
1638        //by setting the proper"mode"
1639        //1 = both emp and bgd subtraction
1640        //2 = only bgd subtraction
1641        //3 = only emp subtraction
1642        //4 = no subtraction
1643        //additional modes 091301
1644        //11 = emp, bgd, drk
1645        //12 = bgd and drk
1646        //13 = emp and drk
1647        //14 = no subtractions
1648        //work.drk is from proto[6]
1649        //
1650        //subtracting just the DRK data is NOT an option - it doesnt' really make any physical sense
1651        // - in this case, DRK is skipped (equivalent to mode==4)
1652        // automatically accounts for attenuators given the lookup tables and the
1653        //desired subtractions
1654        //Attenuator lookup tables are alredy implemented (NG1 = NG7)
1655        //
1656       
1657        //read in the DRK data if necessary
1658        //only one file, assumed to be RAW data
1659        //
1660        String fname="",drkStr=""
1661        drkStr=StringByKey("DRK",prot[6],"=",",")
1662        if(cmpstr(drkStr,"none") != 0)
1663                err = ReadHeaderAndData( (pathStr+drkStr) )
1664                if(err)
1665                        PathInfo/S catPathName
1666                        Abort "reduction sequence aborted"
1667                endif
1668                err = Raw_to_Work_NoNorm("DRK")
1669        endif
1670       
1671        //dispatch to the proper "mode" of Correct()
1672        Variable mode=4,val
1673        do
1674                if( (cmpstr("none",prot[0]) == 0)       && (cmpstr("none",prot[1]) == 0) )
1675                        //no subtraction (mode = 4),
1676                        mode = 4
1677                Endif
1678                If((cmpstr(prot[0],"none") != 0) && (cmpstr(prot[1],"none") == 0))
1679                        //subtract BGD only
1680                        mode=2
1681                Endif
1682                If((cmpstr(prot[0],"none") == 0) && (cmpstr(prot[1],"none") != 0))
1683                        //subtract EMP only
1684                        mode=3
1685                Endif
1686                If((cmpstr(prot[0],"none") != 0) && (cmpstr(prot[1],"none") != 0))
1687                        // bkg and emp subtraction are to be done (BOTH not "none")
1688                        mode=1
1689                Endif
1690                activeType = "COR"
1691                //add in DRK mode (0= no used, 10 = used)
1692                val = NumberByKey("DRKMODE",prot[6],"=","," )
1693                mode += val
1694//              print "mode = ",mode
1695                err = Correct(mode)
1696                if(err)
1697                        SetDataFolder root:
1698                        Abort "error in Correct, called from executeprotocol, normal cor"
1699                endif
1700                UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1701        While(0)
1702       
1703        //check for work.div file (prot[2])
1704        //add if needed
1705        // can't properly check the filename - so for now add and divide, if anything other than "none"
1706        //do/skip divide step based on div answer
1707        If(cmpstr("none",prot[2])!=0)           // if !0, then there's a file requested
1708                If(cmpstr("ask",prot[2]) == 0)
1709                        //ask user for file
1710                         junkStr = PromptForPath("Select the detector sensitivity file")
1711                        If(strlen(junkStr)==0)
1712                                SetDataFolder root:
1713                                Abort "No file selected, data reduction aborted"
1714                        Endif
1715                         ReadHeaderAndWork("DIV", junkStr)
1716                else
1717                        //assume it's a path, and that the first (and only) item is the path:file
1718                        //list processing is necessary to remove any final comma
1719                        junkStr = pathStr + StringFromList(0, prot[2],"," )
1720                        ReadHeaderAndWork("DIV",junkStr)
1721                Endif
1722                //got a DIV file, select the proper type of work data to DIV (= activeType)
1723                err = Divide_work(activeType)           //returns err = 1 if data doesn't exist in specified folders
1724                If(err)
1725                        SetDataFolder root:
1726                        Abort "data missing in DIV step, call from executeProtocol"
1727                Endif
1728                activeType = "CAL"
1729                UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1730        Endif
1731       
1732        Variable c2,c3,c4,c5
1733        //do absolute scaling if desired
1734        if(cmpstr("none",prot[4])!=0)
1735                if(cmpstr("ask",prot[4])==0)
1736                        //get the params from the user
1737                        Execute "AskForAbsoluteParams_Quest()"
1738                        //then from the list
1739                        SVAR junkAbsStr = root:myGlobals:Protocols:gAbsStr
1740                        c2 = NumberByKey("TSTAND", junkAbsStr, "=", ";")        //parse the list of values
1741                        c3 = NumberByKey("DSTAND", junkAbsStr, "=", ";")
1742                        c4 = NumberByKey("IZERO", junkAbsStr, "=", ";")
1743                        c5 = NumberByKey("XSECT", junkAbsStr, "=", ";")
1744                else
1745                        //get the parames from the list
1746                        c2 = NumberByKey("TSTAND", prot[4], "=", ";")   //parse the list of values
1747                        c3 = NumberByKey("DSTAND", prot[4], "=", ";")
1748                        c4 = NumberByKey("IZERO", prot[4], "=", ";")
1749                        c5 = NumberByKey("XSECT", prot[4], "=", ";")
1750                Endif
1751                //get the sample trans and thickness from the activeType folder
1752                String destStr = "root:Packages:NIST:"+activeType+":realsread"
1753                Wave dest = $destStr
1754                Variable c0 = dest[4]           //sample transmission
1755                Variable c1 = dest[5]           //sample thickness
1756               
1757                err = Absolute_Scale(activeType,c0,c1,c2,c3,c4,c5)
1758                if(err)
1759                        SetDataFolder root:
1760                        Abort "Error in Absolute_Scale(), called from executeProtocol"
1761                endif
1762                activeType = "ABS"
1763                UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1764        Endif
1765       
1766        //check for mask
1767        //add mask if needed
1768        // can't properly check the filename - so for now always add
1769        //doesn't change the activeType
1770        if(cmpstr("none",prot[3])!=0)
1771                If(cmpstr("ask",prot[3])==0)
1772                        //get file from user
1773                        junkStr = PromptForPath("Select Mask file")
1774                        If(strlen(junkStr)==0)
1775                                //no selection of mask file is not a fatal error, keep going, and let cirave()
1776                                //make a "null" mask
1777                                //if none desired, make sure that the old mask is deleted
1778                                //junkStr = GetDataFolder(1)
1779                                //SetDataFolder root:Packages:NIST:MSK
1780                                KillWaves/Z root:Packages:NIST:MSK:data
1781                                //SetDataFolder junkStr
1782                                DoAlert 0,"No Mask file selected, data not masked"
1783                        else
1784                                //read in the file from the dialog
1785                                ReadMCID_MASK(junkStr)
1786                        Endif
1787                else
1788                        //just read it in from the protocol
1789                        //list processing is necessary to remove any final comma
1790                        junkStr = pathStr + StringFromList(0, prot[3],"," )
1791                        ReadMCID_MASK(junkStr)
1792                Endif
1793        else
1794                //if none desired, make sure that the old mask is deleted
1795                //junkStr = GetDataFolder(1)
1796                //SetDataFolder root:Packages:NIST:MSK
1797                KillWaves/Z root:Packages:NIST:MSK:data
1798                //SetDataFolder junkStr
1799        Endif
1800       
1801        //mask data if desired (this is done automatically  in the average step) and is
1802        //not done explicitly here (if no mask in MSK folder, a null mask is created and "used")
1803       
1804        // average/save data as specified
1805       
1806        //Parse the keyword=<Value> string as needed, based on AVTYPE
1807       
1808        //average/plot first
1809        String av_type = StringByKey("AVTYPE",prot[5],"=",";")
1810        If(cmpstr(av_type,"none") != 0)
1811                If (cmpstr(av_type,"")==0)              //if the key could not be found... (if "ask" the string)
1812                        //get the averaging parameters from the user, as if the set button was hit
1813                        //in the panel
1814                        SetAverageParamsButtonProc("dummy")             //from "ProtocolAsPanel"
1815                        SVAR tempAveStr = root:myGlobals:Protocols:gAvgInfoStr
1816                        av_type = StringByKey("AVTYPE",tempAveStr,"=",";")
1817                else
1818                        //there is info in the string, use the protocol
1819                        //set the global keyword-string to prot[5]
1820                        String/G root:myGlobals:Protocols:gAvgInfoStr = prot[5]
1821                Endif
1822        Endif
1823       
1824        //convert the folder to linear scale before averaging, then revert by calling the window hook
1825        ConvertFolderToLinearScale(activeType)
1826       
1827        strswitch(av_type)      //dispatch to the proper routine to average to 1D data
1828                case "none":           
1829                        //still do nothing
1830                        break                   
1831                case "2D_ASCII":       
1832                        //do nothing
1833                        break
1834                case "QxQy_ASCII":
1835                        //do nothing
1836                        break
1837                case "PNG_Graphic":
1838                        //do nothing
1839                        break
1840                case "Rectangular":
1841                        RectangularAverageTo1D(activeType)
1842                        break
1843                case "Annular":
1844                        AnnularAverageTo1D(activeType)
1845                        break
1846                case "Circular":
1847                        CircularAverageTo1D(activeType)
1848                        break
1849                case "Sector":
1850                        CircularAverageTo1D(activeType)
1851                        break
1852                default:       
1853                        //do nothing
1854        endswitch
1855///// end of averaging dispatch
1856        // put data back on log or lin scale as set by default
1857        fRawWindowHook()
1858       
1859        //save data if desired
1860        String fullpath = "", newfileName=""
1861        String item = StringByKey("SAVE",prot[5],"=",";")               //does user want to save data?
1862        If( (cmpstr(item,"Yes")==0) && (cmpstr(av_type,"none") != 0) )         
1863                //then save
1864                //get name from textwave of the activeType dataset
1865                String textStr = "root:Packages:NIST:"+activeType+":textread"
1866                Wave/T textPath = $textStr
1867                String tempFilename = samStr
1868                If(WaveExists(textPath) == 1)
1869#ifdef QUOKKA
1870                        newFileName = ReplaceString(".nx.hdf", tempFilename, "")
1871#else
1872                        newFileName = UpperStr(GetNameFromHeader(textPath[0]))
1873#endif
1874                else
1875                        newFileName = ""                        //if the header is missing?
1876                        //Print "can't read the header - newfilename is null"
1877                Endif
1878               
1879                //pick ABS or AVE extension
1880                String exten = activeType
1881                if(cmpstr(exten,"ABS") != 0)
1882                        exten = "AVE"
1883                endif
1884                if(cmpstr(av_type,"2D_ASCII") == 0)
1885                        exten = "ASC"
1886                endif
1887                if(cmpstr(av_type,"QxQy_ASCII") == 0)
1888                        exten = "DAT"
1889                endif
1890               
1891                //Path is catPathName, symbolic path
1892                //if this doesn't exist, a dialog will be presented by setting dialog = 1
1893                Variable dialog = 0
1894                PathInfo/S catPathName
1895                item = StringByKey("NAME",prot[5],"=",";")              //Auto or Manual naming
1896                If((cmpstr(item,"Manual")==0) || (cmpstr(newFileName,"") == 0))
1897                        //manual name if requested or if no name can be derived from header
1898                        fullPath = newfileName + "."+ exten //puts possible new name or null string in dialog
1899                        dialog = 1              //force dialog for user to enter name
1900                else
1901                        //auto-generate name and prepend path - won't put up any dialogs since it has all it needs
1902                        fullPath = S_Path + newFileName+ "." + exten   
1903                Endif
1904                //
1905                strswitch(av_type)     
1906                        case "Annular":
1907                                WritePhiave_W_Protocol(activeType,fullPath,dialog)
1908                                break
1909                        case "2D_ASCII":
1910                                Fast2DExport(activeType,fullPath,dialog)
1911                                break
1912                        case "QxQy_ASCII":
1913                                QxQy_Export(activeType,fullPath,dialog)
1914                                break
1915                        case "PNG_Graphic":
1916                                SaveAsPNG(activeType,fullpath,dialog)
1917                                break
1918                        default:
1919                                WriteWaves_W_Protocol(activeType,fullpath,dialog)
1920                                //WriteXMLWaves_W_Protocol(activeType,fullpath,dialog)
1921                endswitch
1922               
1923                //Print "data written to:  "+ fullpath
1924        Endif
1925       
1926        //done with everything in protocol list
1927        Return(0)
1928End
1929
1930//updates the currently displayed information to the data in "type"
1931//data folder - changes the title of the window and the global of the
1932//currently displayed data type - the recreation macro does the work
1933//
1934Function UpdateDisplayInformation(type)
1935        String type
1936
1937        String newTitle = "WORK_"+type
1938        DoWindow/F SANS_Data
1939        DoWindow/T SANS_Data, newTitle
1940        KillStrings/Z newTitle
1941       
1942        //need to update the display with "data" from the correct dataFolder
1943        //reset the current displaytype to "type"
1944        String/G root:myGlobals:gDataDisplayType=Type
1945       
1946        fRawWindowHook()
1947       
1948        //no error
1949        Return(0)
1950End
1951
1952//missing parameter dialog to solicit the 4 absolute intensity parameters
1953//from the user
1954//values are passed back as a global string variable (keyword=value)
1955//
1956Proc AskForAbsoluteParams(c2,c3,c4,c5)
1957        Variable c2=0.95,c3=0.1,c4=1,c5=32.0
1958        Prompt c2, "Standard Transmission"
1959        Prompt c3, "Standard Thickness (cm)"
1960        Prompt c4, "I(0) from standard fit (normalized to 1E8 monitor cts)"
1961        Prompt c5, "Standard Cross-Section (cm-1)"
1962       
1963        String/G root:myGlobals:Protocols:gAbsStr=""
1964       
1965        root:myGlobals:Protocols:gAbsStr = "TSTAND="+num2str(c2)
1966        root:myGlobals:Protocols:gAbsStr +=  ";" + "DSTAND="+num2str(c3)
1967        root:myGlobals:Protocols:gAbsStr +=  ";" + "IZERO="+num2str(c4)
1968        root:myGlobals:Protocols:gAbsStr +=  ";" + "XSECT="+num2str(c5)
1969       
1970End
1971
1972//asks the user for absolute scaling information. the user can either
1973//enter the 4 necessary values in manually (missing parameter dialog)
1974//or the user can select an empty beam file from a standard open dialog
1975//if an empty beam file is selected, the "kappa" value is automatically calculated
1976//in either case, the global keyword=value string is set.
1977//
1978//Proc AskForAbsoluteParams_Quest()
1979Function AskForAbsoluteParams_Quest()   
1980       
1981        Variable err, isNG5=0,loc,refnum
1982        //ask user if he wants to use a transmision file for absolute scaling
1983        //or if he wants to enter his own information
1984        err = UseStdOrEmpForABS()
1985        //DoAlert 1,"<Yes> to enter your own values, <No> to select an empty beam flux file"
1986        If ( err==1 )
1987                //secondary standard selected, prompt for values
1988                Execute "AskForAbsoluteParams()"                //missing parameters
1989        else
1990                //empty beam flux file selected, prompt for file, and use this to calculate KAPPA
1991                Variable kappa=1
1992               
1993                //ask for file and read it into RAW
1994                //will cancel if no file is selected
1995                err = LoadRawSANSData("select the empty beam file")             //reads the RAW data
1996                UpdateDisplayInformation("RAW")                 //display the new type of data that was loaded
1997                if(err)
1998                        PathInfo/S catPathName
1999                        Abort "reduction sequence aborted"
2000                endif
2001                       
2002                Wave/T tw=$"root:Packages:NIST:RAW:TextRead"
2003                Wave rw=$"root:Packages:NIST:RAW:RealsRead"
2004                Wave iw=$"root:Packages:NIST:RAW:IntegersRead"
2005                String acctStr = tw[3]
2006                //NG5 attenuator transmission is assumed to be the same as the table for NG7
2007                       
2008                //get the necessary variables for the calculation of kappa
2009                Variable detCnt,countTime,attenTrans,monCnt,sdd,pixel
2010                String detStr=tw[9]
2011//              pixel = DetectorPixelResolution(acctStr,detStr)         //get the pixel size from the file information
2012                //note that reading the detector pixel size from the header ASSUMES SQUARE PIXELS! - Jan2008
2013                pixel = rw[10]/10                       // header value (X) is in mm, want cm here
2014       
2015                countTime = iw[2]
2016                //detCnt = rw[2]                //080802 -use sum of data, not scaler from header
2017                monCnt = rw[0]
2018                sdd = rw[18]
2019                sdd *=100               //convert from meters to cm
2020                               
2021                //lookup table for transmission factor
2022                //determine which instrument the measurement was done on from acctStr
2023                Variable lambda = rw[26]
2024                Variable attenNo = rw[3]
2025                attenTrans = AttenuationFactor(acctStr,lambda,attenNo)
2026                //Print "attenTrans = ",attenTrans
2027               
2028                //get the XY box, if needed
2029                Variable x1,x2,y1,y2
2030                String filename=tw[0],tempStr
2031                PathInfo/S catPathName
2032                String tempName = S_Path + FindValidFilename(filename)
2033                err = GetXYBoxFromFile(tempName,x1,x2,y1,y2)            //xy's are passed/returned by reference
2034                Print x1,x2,y1,y2
2035
2036                if( ((x1-x2)==0) || ((y1-y2)==0) )      //need to re-select the box
2037                        err = SelectABS_XYBox(x1,x2,y1,y2)              //this will pause for user input
2038                        if(err)
2039                                Abort "Box not selected properly - Please re-set the ABS parameters"
2040                        Endif
2041                        //box is OK, write box values to file
2042                        WriteXYBoxToHeader(tempName,x1,x2,y1,y2)
2043                else
2044                        //give option to override
2045                        tempStr = "X=("+num2str(x1)+","+num2str(x2)+") Y=("+num2str(y1)+","+num2str(y2)+")"
2046                        DoAlert 1,"The current box is "+tempStr+".  Do you want to override these values?"
2047                        //Print v_flag
2048                        if(V_flag==1)   //1==yes, override
2049                                err = SelectABS_XYBox(x1,x2,y1,y2)
2050                                if(err)
2051                                        Abort "Box not selected properly -Please re-set the ABS parameters"
2052                                Endif
2053                        endif
2054                Endif
2055                Printf "Using Box X(%d,%d),Y(%d,%d)\r",x1,x2,y1,y2
2056               
2057                //need the detector sensitivity file - make a guess, allow to override
2058                String junkStr=""
2059                if(! waveexists($"root:Packages:NIST:DIV:data"))
2060                         junkStr = PromptForPath("Select the detector sensitivity file")
2061                        If(strlen(junkStr)==0 || CheckIfRawData(junkStr))               //raw check==1 if RAW, DIV is not
2062                                SetDataFolder root:
2063                                Abort "No DIV (PLEX) file selected. Please use setABSParams again, selecting the empty beam file and then the detector sensitivity (Plex_) file"
2064                        Endif
2065                         ReadHeaderAndWork("DIV", junkStr)
2066                endif
2067                //toggle SANS_Data to linear display if needed, so that we're working with linear scaled data
2068                ControlInfo/W=SANS_Data bisLog
2069                if(V_Flag==1)
2070                        Log_Lin("bisLog")       
2071                endif   
2072                Wave divData = $"root:Packages:NIST:div:Data"
2073                Wave data = $"root:Packages:NIST:raw:data"              //this will be the linear data
2074                // correct by detector sensitivity
2075                data /= divData
2076               
2077                // now do the sum, only in the box     
2078//              detCnt = sum($"root:Packages:NIST:raw:data", -inf, inf )
2079//              Print "box is now ",x1,x2,y1,y2
2080                detCnt = SumCountsInBox(x1,x2,y1,y2,"RAW")
2081                if(cmpstr(tw[9],"ILL   ")==0)
2082                        detCnt /= 4             // for cerca detector, header is right, sum(data) is 4x too large this is usually corrected in the Add step
2083                        pixel *= 1.04                   // correction for true pixel size of the Cerca
2084                endif
2085                //             
2086                kappa = detCnt/countTime/attenTrans*1.0e8/(monCnt/countTime)*(pixel/sdd)^2
2087                junkStr = num2str(kappa)
2088                // set the parameters in the global string
2089                Execute "AskForAbsoluteParams(1,1,"+junkStr+",1)"               //no missing parameters, no dialog
2090               
2091                //should wipe out the data in the RAW folder, since it's not really RAW now
2092                DoWindow/K SANS_Data
2093                // SRK JUL 2006 don't clear the contents - just kill the window to force new data to be loaded
2094                // - obsucre bug if "ask" in ABS section of protocol clears RAW folder, then Q-axes can't be set from RAW:RealsRead
2095                //ClearDataFolder("RAW")
2096                Print "Kappa was successfully calculated as = ",kappa   
2097        Endif
2098       
2099End
2100
2101Function UserSelectBox_Continue(ctrlName) :buttonControl
2102        String ctrlName
2103       
2104        DoWindow/K junkWindow           //kill panel
2105end
2106
2107Function SelectABS_XYBox(x1,x2,y1,y2)
2108        Variable &x1,&x2,&y1,&y2
2109       
2110        Variable err=0
2111       
2112        Variable/G root:V_marquee=1             //sets the sneaky bit to automatically update marquee coords
2113        Variable/G root:V_left,root:V_right,root:V_bottom,root:V_top    //must be global for auto-update
2114        DoWindow/F SANS_Data
2115        NewPanel/K=2 /W=(139,341,382,432) as "Select the primary beam"
2116        DoWindow/C junkWindow
2117        AutoPositionWindow/E/M=1/R=SANS_Data
2118       
2119        Drawtext 21,20 ,"Select the primary beam with the"
2120        DrawText 21,40, "marquee and press continue"
2121        Button button0,pos={80,58},size={92,20},title="Continue"
2122        Button button0,proc=UserSelectBox_Continue
2123       
2124        PauseForUser junkWindow,SANS_Data
2125       
2126        DoWindow/F SANS_Data
2127
2128        //GetMarquee left,bottom                        //not needed
2129        NVAR V_left=V_left
2130        NVAR V_right=V_right
2131        NVAR V_bottom=V_bottom
2132        NVAR V_top=V_top
2133       
2134        x1 = V_left
2135        x2 = V_right
2136        y1 = V_bottom
2137        y2 = V_top
2138//      Print "new values,before rounding = ",x1,x2,y1,y2
2139        KeepSelectionInBounds(x1,x2,y1,y2)
2140        //Print "new values = ",x1,x2,y1,y2
2141       
2142        KillVariables/Z root:V_Marquee,root:V_left,root:V_right,root:V_bottom,root:V_top
2143        if((x1-x2)==0 || (y1-y2)==0)
2144                err=1
2145        endif
2146        return(err)
2147End
2148
2149Function UseStdOrEmpForABS()
2150               
2151        NewPanel/K=2 /W=(139,341,402,448) as "Absolute Scaling"
2152        DoWindow/C junkABSWindow
2153        ModifyPanel cbRGB=(57346,65535,49151)
2154        SetDrawLayer UserBack
2155        SetDrawEnv fstyle= 1
2156        DrawText 21,20,"Method of absolute calibration"
2157        Button button0,pos={52,33},size={150,20},proc=UserSelectABS_Continue,title="Empty Beam Flux"
2158        Button button1,pos={52,65},size={150,20},proc=UserSelectABS_Continue,title="Secondary Standard"
2159       
2160        PauseForUser junkABSWindow
2161        NVAR val = root:myGlobals:tmpAbsVal
2162        return(val)
2163End
2164
2165//returns 0 if button0 (empty beam flux)
2166// or 1 if secondary standard
2167Function UserSelectABS_Continue(ctrlName) :buttonControl
2168        String ctrlName
2169       
2170        variable val=0
2171        If(cmpstr(ctrlName,"button0")==0)
2172                val=0           
2173        else
2174                val=1
2175        endif
2176//      print "val = ",ctrlName,val
2177        Variable/G root:myGlobals:tmpAbsVal = val
2178        DoWindow/K junkABSWindow                //kill panel
2179        return(0)
2180end
2181
2182
2183//save the protocol as an IGOR text wave (.itx)
2184//
2185//
2186Function ExportProtocol(ctrlName) : ButtonControl
2187        String ctrlName
2188// get a list of protocols
2189        String Protocol=""
2190        SetDataFolder root:myGlobals:Protocols
2191        Prompt Protocol "Pick A Protocol",popup, WaveList("*",";","")
2192        DoPrompt "Pick A Protocol to Export",Protocol
2193        if(V_flag==1)
2194                //Print "user cancel"
2195                SetDatafolder root:
2196                return(1)
2197        endif
2198//get the selection, or exit
2199        Wave/T pW= $protocol
2200        Make/O/T/N=13 tw
2201// save in the proper format (must write manually, for demo version)
2202        tw[0] = "IGOR"
2203        tw[1] = "WAVES/T \t"+protocol
2204        tw[2] = "BEGIN"
2205        tw[3,10] = "\t\""+pW[p-3]+"\""
2206        tw[11] = "END"
2207        tw[12] = "X SetScale/P x 0,1,\"\","+protocol+"; SetScale y 0,0,\"\","+protocol
2208       
2209        Variable refnum
2210        String fullPath
2211       
2212        PathInfo/S catPathName
2213        fullPath = DoSaveFileDialog("Export Protocol as")
2214        If(cmpstr(fullPath,"")==0)
2215                //user cancel, don't write out a file
2216                Close/A
2217                Abort "no Protocol file was written"
2218        Endif
2219
2220        //actually open the file
2221        Open refNum as fullpath+".itx"
2222       
2223        wfprintf refnum, "%s\r", tw
2224        Close refnum
2225        //Print "all is well  ",protocol
2226        KillWaves/Z tw
2227        setDataFolder root:
2228        return(0)
2229
2230End
2231
2232//imports a protocol from disk into the protocols folder
2233//
2234// will overwrite existing protocols if necessary
2235//
2236//
2237Function ImportProtocol(ctrlName) : ButtonControl
2238        String ctrlName
2239
2240        SetDataFolder root:myGlobals:Protocols
2241
2242        String fullPath
2243       
2244        PathInfo/S catPathName
2245        fullPath = DoOpenFileDialog("Import Protocol")
2246        If(cmpstr(fullPath,"")==0)
2247                //user cancel, don't write out a file
2248                Close/A
2249                Abort "no protocol was loaded"
2250        Endif
2251       
2252        LoadWave/O/T fullPath
2253       
2254        SetDataFolder root:
2255        return(0)
2256end
Note: See TracBrowser for help on using the repository browser.