source: sans/SANSReduction/branches/kline_29MAR07/Put in User Procedures/SANS_Reduction_v5.00/ProtocolAsPanel.ipf @ 80

Last change on this file since 80 was 80, checked in by srkline, 15 years ago

Redefinition of SANS data reader functions (main entry points)
More commenting of NCNR_DataReadWrite.ipf

File size: 73.1 KB
Line 
1#pragma rtGlobals=1             // Use modern global access method.
2#pragma version=5.0
3#pragma IgorVersion=4.0
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/K=1 "SANS Data Reduction Tutorial[Build a Data Reduction Protocol]"
935End
936
937//button action procedure to get the type of average requested by the user
938//presented as a missing parameter dialog, which is really user-UN-friendly
939//and will need to be re-thought. Defaults of dialog are set for normal
940//circular average, so typically click "continue" and proceed
941//
942Function SetAverageParamsButtonProc(ctrlName) : ButtonControl
943        String ctrlName
944       
945        Execute "GetAvgInfo()"
946       
947        //set the global string
948        SVAR tempStr = root:myGlobals:Protocols:gAvgInfoStr
949        String/G root:myGlobals:Protocols:gAVE = tempStr
950
951End
952
953//procedure called by protocol panel to ask user for average type choices
954// somewhat confusing and complex, but may be as good as it gets.
955//
956Proc GetAvgInfo(av_typ,autoSave,autoName,autoPlot,side,phi,dphi,width,QCtr,QDelta)
957        String av_typ,autoSave,AutoName,autoPlot,side
958        Variable phi=0,dphi=10,width=10,Qctr = 0.01,qDelta=10
959        Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII;PNG_Graphic"
960// comment out above line in DEMO_MODIFIED version, and uncomment the line below (to disable PNG save)
961//      Prompt av_typ, "Type of Average",popup,"Circular;Sector;Rectangular;Annular;2D_ASCII;QxQy_ASCII"
962        Prompt autoSave,"Save files to disk?",popup,"Yes;No"
963        Prompt autoName,"Auto-Name files?",popup,"Auto;Manual"
964        Prompt autoPlot,"Plot the averaged Data?",popup,"Yes;No"
965        Prompt side,"Include detector halves?",popup,"both;right;left"
966        Prompt phi,"Orientation Angle (-90,90) degrees (Rectangular or Sector)"
967        Prompt dphi, "Azimuthal range (0,45) degrees (Sector only)"
968        Prompt width, "Width of Rectangular average (1,128)"
969        Prompt Qctr, "q-value of center of annulus"
970        Prompt Qdelta,"Pixel width of annulus"
971
972        //assign results of dialog to key=value string, semicolon separated
973        //do only what is necessary, based on av_typ
974        String/G root:myGlobals:Protocols:gAvgInfoStr=""
975       
976        // all averages need these four values
977        root:myGlobals:Protocols:gAvgInfoStr += "AVTYPE=" + av_typ + ";"
978        root:myGlobals:Protocols:gAvgInfoStr += "SAVE=" + autoSave + ";"
979        root:myGlobals:Protocols:gAvgInfoStr += "NAME=" + autoName + ";"
980        root:myGlobals:Protocols:gAvgInfoStr += "PLOT=" + autoPlot + ";"
981       
982        if(cmpstr(av_typ,"Sector")==0)
983                root:myGlobals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
984                root:myGlobals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
985                root:myGlobals:Protocols:gAvgInfoStr += "DPHI=" + num2str(dphi) + ";"
986        Endif
987       
988        if(cmpstr(av_typ,"Rectangular")==0)
989                root:myGlobals:Protocols:gAvgInfoStr += "SIDE=" + side + ";"
990                root:myGlobals:Protocols:gAvgInfoStr += "PHI=" + num2str(phi) + ";"
991                root:myGlobals:Protocols:gAvgInfoStr += "WIDTH=" + num2str(width) + ";"
992        Endif
993       
994        if(cmpstr(av_typ,"Annular")==0)
995                root:myGlobals:Protocols:gAvgInfoStr += "QCENTER=" + num2str(QCtr) + ";"
996                root:myGlobals:Protocols:gAvgInfoStr += "QDELTA=" + num2str(QDelta) + ";"
997        Endif
998End
999
1000//not used????
1001//checks the syntax of all of the file fields in the panel
1002Function CheckProtocolSyntax(ctrlName) : ButtonControl
1003        String ctrlName
1004       
1005        String retStr=""
1006        //SAM
1007        SVAR list = root:myGlobals:Protocols:gSAM
1008        retStr = ParseRunNumberList(list)
1009        if(strlen(retStr)==0)
1010                //error
1011                Print "SAM Syntax Error"
1012                return(1)
1013        else
1014                list = retStr
1015                Print "SAM syntax OK"
1016        Endif
1017
1018        //MASK
1019        SVAR list = root:myGlobals:Protocols:gMASK
1020        retStr = ParseRunNumberList(list)
1021       
1022End
1023//*************
1024
1025
1026
1027//
1028// Procedure files for creating and executing a data reduction protocol
1029//
1030//**** ONLY invoked from the MAIN PANEL**** NOT REALLY EVER USED ******
1031//Procedure for reducing a sample file (multiple added files) with a specified
1032//protocol. User may create a new protocol, and will be prompted
1033//for information "questionnare-style" where the user must know the
1034//filenames for empty cell, background...etc.. as they will be presented
1035//with standard file open dialogs to select each file desired for use in the
1036//new protocol
1037//once a protocol is selected (or created) the uer is propmted for sample data
1038// and the file is processed through the protocol.
1039//
1040Proc ReduceAFile()
1041
1042        String protocolName="",waveStr="",samStr = "ask"
1043        Variable err
1044       
1045        //pick a protocol wave from the Protocols folder
1046        //must switch to protocols folder to get wavelist (missing parameter)
1047        SetDataFolder root:myGlobals:Protocols
1048        PickAProtocol()
1049       
1050        //get the selected protocol wave choice through a global string variable
1051        protocolName = root:myGlobals:Protocols:gProtoStr
1052       
1053        //If "CreateNew" was selected, go to the questionnare, to make a new set
1054        //and put the name of the new Protocol wave in gProtoStr
1055        if(cmpstr("CreateNew",protocolName) == 0)
1056                ProtocolQuestionnare()
1057                protocolName = root:myGlobals:Protocols:gProtoStr
1058        Endif
1059       
1060        //give the full path:name to the executeProtocol function
1061        waveStr = "root:myGlobals:Protocols:"+protocolName
1062        //samStr is set at top to "ask", since this is the action always desired from "ReduceAFile"
1063       
1064        ExecuteProtocol(waveStr,samStr)
1065       
1066        //return data folder to root before Macro is done
1067        SetDataFolder root:
1068       
1069End
1070
1071
1072//prompts the user to pick a previously created protocol from a popup list
1073//of given the option to create a new protocol
1074//the chosen protocol is passed back to the calling procedure by a global string
1075//the popup is presented as a missing parameter dialog (called with empty parameter list)
1076//
1077Proc PickAProtocol(protocol)
1078        String Protocol
1079        Prompt Protocol "Pick A Protocol",popup, WaveList("*",";","")
1080       
1081        String/G  root:myGlobals:Protocols:gProtoStr = protocol
1082End
1083
1084Proc DeleteAProtocol(protocol)
1085        String Protocol
1086//      Prompt Protocol "Delete A Protocol",popup, WaveList("*",";","")
1087        Prompt Protocol "Delete A Protocol",popup, DeletableProtocols()
1088
1089        String/G  root:myGlobals:Protocols:gProtoStr = protocol
1090End
1091
1092Function/S DeletableProtocols()
1093        String list=WaveList("*",";","")
1094
1095        list= RemoveFromList("Base", list  , ";")
1096        list= RemoveFromList("DoAll", list  , ";")
1097        list= RemoveFromList("CreateNew", list  , ";")
1098        list= RemoveFromList("tempProtocol", list  , ";")
1099        if(cmpstr(list,"")==0)
1100                list = "_no_protocols_;"
1101        endif
1102       
1103        return(list)
1104End
1105
1106//missing paramater dialog to solicit user for a waveStr for the protocol
1107//about to be created
1108//name is passed back as a global string and calling procedure is responsible for
1109//checking for wave conflicts and valid names
1110//
1111Proc AskForName(protocol)
1112        String Protocol
1113        Prompt Protocol "Enter a new name for your protocol (no extension)"
1114       
1115        String/G  root:myGlobals:Protocols:gNewStr = protocol
1116End
1117
1118//this is a lengthy procedure for sequentially polling the user about what data
1119//reduction steps they want to be performed during the protocol
1120//ensures that a valid protocol name was chosen, then fills out each "item"
1121//(6 total) needed for reduction
1122//it the user cancels at any point, the partial protocol will be deleted
1123//
1124Function ProtocolQuestionnare()
1125        String filename,cmd
1126        Variable notDone,refnum
1127       
1128        //prompt for name of new protocol wave to save
1129        do
1130                Execute "AskForName()"
1131                SVAR newProtoStr = root:myGlobals:Protocols:gNewStr
1132               
1133                //make sure it's a valid IGOR name
1134                newProtoStr = CleanupName(newProtoStr,0)        //strict naming convention
1135                String/G root:myGlobals:Protocols:gNewStr=newProtoStr           //reassign, if changed
1136                //Print "newProtoStr = ",newProtoStr
1137               
1138                SetDataFolder root:myGlobals:Protocols
1139                if(WaveExists( $("root:myGlobals:Protocols:" + newProtoStr) ) == 1)
1140                        //wave already exists
1141                        DoAlert 0,"that name is already in use. Please pick a new name"
1142                        notDone = 1
1143                else
1144                        //name is  good
1145                        notDone = 0
1146                Endif
1147        while(notDone)
1148       
1149        //Print "protocol questionnare is "+newProtocol
1150       
1151        //make a new text wave (6 points) and fill it in, in response to questions
1152        SetDataFolder root:myGlobals:Protocols //(redundant - full wave specs are used)
1153        Make/O/T/N=8 $("root:myGlobals:Protocols:" + newProtoStr)
1154        Wave/T newProtocol = $("root:myGlobals:Protocols:" + newProtoStr)
1155       
1156        //ask the questions
1157        /////
1158        //*****Multiple files in these lists are full paths/filenames which may or may not
1159        //have semicolon version numbers in the filename. Therefore, construct the list with
1160        //COMMAS as separators - to avoid messy parsing
1161        ///////
1162       
1163       
1164//////////////////////////
1165        String drkStr="",fileStr=""
1166        DoAlert 1,"Do you want to correct your data for DRK (beam off) counts?"
1167        if(V_flag == 1)         //1=yes
1168                //prompt for DRK  file, but don't actually open it (/D flag)
1169                Open/D/R/T="TEXT????"/M="Select the DRK file"/P=catPathName refnum
1170                //check for cancel
1171                if(strlen(S_filename)==0)
1172                        //user cancelled, abort
1173                        KillWaves/Z newProtocol
1174                        SetDataFolder root:
1175                        Abort "Incomplete protocol has been deleted"
1176                Endif
1177                //assign filename (just the name) to [6]
1178                fileStr = GetFileNameFromPathNoSemi(S_filename)
1179                drkStr = "DRK=none,DRKMODE=0,"
1180                drkStr = ReplaceStringByKey("DRK",drkStr,fileStr,"=",",")
1181                drkStr = ReplaceNumberByKey("DRKMODE", drkStr, 10 ,"=",",")     
1182                newProtocol[6] = drkStr
1183        else
1184                //no Work.DRK desired
1185                newProtocol[6] = "DRK=none,DRKMODE=0,"
1186        Endif
1187       
1188////////////
1189       
1190/////////////////
1191        DoAlert 1,"Do you want to subtract background from your data?"
1192        if(V_flag == 1)         //1=yes
1193                //prompt for background file, but don't actually open it (/D flag)
1194                Open/D/R/T="TEXT????"/M="Select the Background data file"/P=catPathName refnum
1195                //check for cancel
1196                if(strlen(S_filename)==0)
1197                        //user cancelled, abort
1198                        KillWaves/Z newProtocol
1199                        SetDataFolder root:
1200                        Abort "Incomplete protocol has been deleted"
1201                Endif
1202                //assign filename (full path) to [0]
1203                newProtocol[0] = GetFileNameFromPathNoSemi(S_filename)
1204               
1205                notDone=1
1206                do
1207                        //prompt for additional background files
1208                        DoAlert 1,"Do you want to add another background file?"
1209                        if(V_flag == 1)         //yes
1210                                Open/D/R/T="TEXT????"/M="Select another Background data file"/P=catPathName refnum
1211                                //check for cancel
1212                                if(strlen(S_filename)==0)
1213                                        //user cancelled, abort ********maybe just break out of the loop here
1214                                        KillWaves/Z newProtocol
1215                                        SetDataFolder root:
1216                                        Abort "Incomplete protocol has been deleted"
1217                                Endif
1218                                //assign filename (full path) to [0]
1219                                newProtocol[0] += "," + GetFileNameFromPathNoSemi(S_filename)           //***COMMA separated list
1220                                notDone = 1             //keep going
1221                        else
1222                                notDone = 0                     //no more to add
1223                        Endif
1224                While(notDone)
1225        else            //no background desired
1226                newProtocol[0] = "none"
1227        Endif
1228////////////////////// 
1229        DoAlert 1,"Do you want to subtract empty cell scattering from your data?"
1230        if(V_flag == 1)         //1=yes
1231                //prompt for Empty cell file, but don't actually open it (/D flag)
1232                Open/D/R/T="TEXT????"/M="Select the Empty Cell data file"/P=catPathName refnum
1233                //check for cancel
1234                if(strlen(S_filename)==0)
1235                        //user cancelled, abort
1236                        KillWaves/Z newProtocol
1237                        SetDataFolder root:
1238                        Abort "Incomplete protocol has been deleted"
1239                Endif
1240                //assign filename (full path) to [1]
1241                newProtocol[1] = GetFileNameFromPathNoSemi(S_filename)
1242               
1243                notDone=1
1244                do
1245                        //prompt for additional Empty Cell files
1246                        DoAlert 1,"Do you want to add another Empty Cell file?"
1247                        if(V_flag == 1)         //yes
1248                                Open/D/R/T="TEXT????"/M="Select another Empty Cell data file"/P=catPathName refnum
1249                                //check for cancel
1250                                if(strlen(S_filename)==0)
1251                                        //user cancelled, abort ********maybe just break out of the loop here
1252                                        KillWaves/Z newProtocol
1253                                        SetDataFolder root:
1254                                        Abort "Incomplete protocol has been deleted"
1255                                Endif
1256                                //assign filename (full path) to [1]
1257                                newProtocol[1] += "," + GetFileNameFromPathNoSemi(S_filename)           //***COMMA separated list
1258                                notDone = 1             //keep going
1259                        else
1260                                notDone = 0                     //no more to add
1261                        Endif
1262                While(notDone)
1263        else            //no background desired
1264                newProtocol[1] = "none"
1265        Endif
1266//////////////////////////
1267        DoAlert 1,"Do you want to correct your data for detector sensitivity?"
1268        if(V_flag == 1)         //1=yes
1269                //prompt for DIV  file, but don't actually open it (/D flag)
1270                Open/D/R/T="TEXT????"/M="Select the detector sensitivity file"/P=catPathName refnum
1271                //check for cancel
1272                if(strlen(S_filename)==0)
1273                        //user cancelled, abort
1274                        KillWaves/Z newProtocol
1275                        SetDataFolder root:
1276                        Abort "Incomplete protocol has been deleted"
1277                Endif
1278                //assign filename (full path) to [2]
1279                newProtocol[2] = GetFileNameFromPathNoSemi(S_filename)
1280        else
1281                //no Work.DIV desired
1282                newProtocol[2] = "none"
1283        Endif   
1284//////////////////////////
1285        DoAlert 1,"Do you want to mask your files before averaging?"
1286        if(V_flag == 1)         //1=yes
1287                //prompt for mask  file, but don't actually open it (/D flag)
1288                Open/D/R/T="TEXT????MASK"/M="Select the mask file"/P=catPathName refnum
1289                //check for cancel
1290                if(strlen(S_filename)==0)
1291                        //user cancelled, abort
1292                        KillWaves/Z newProtocol
1293                        SetDataFolder root:
1294                        Abort "Incomplete protocol has been deleted"
1295                Endif
1296                //assign filename (full path) to [3]
1297                newProtocol[3] = GetFileNameFromPathNoSemi(S_filename)
1298        else
1299                //no MASK desired
1300                newProtocol[3] = "none"
1301        Endif   
1302       
1303        //absolute scaling
1304       
1305        //////////////////////////
1306        //ABS parameters stored as keyword=value string
1307        DoAlert 1,"Do you want absolute scaling?"
1308        if(V_flag == 1)         //1=yes
1309                //missing param - prompt for values, put in semicolon-separated list
1310                Execute "AskForAbsoluteParams_Quest()"
1311                SVAR absStr =  root:myGlobals:Protocols:gAbsStr
1312                newProtocol[4] = absStr
1313        else
1314                //no absolute scaling desired
1315                newProtocol[4] = "none"
1316        Endif   
1317       
1318        //type of average, plot?, auto/manual naming/saving... put in semicolon separated string
1319        //of KEY=<value> format for easy parsing
1320        //Kewords are: AVTYPE,PHI,DPHI,PLOT,SAVE,NAME,SIDE,WIDTH
1321        //note that AVTYPE,NAME,SIDE have string values, others have numerical values
1322        ///////////////////////
1323        DoAlert 1,"Do you want to average your data to I vs. q?"
1324        if(V_flag == 1)         //1=yes
1325                String/G root:myGlobals:Protocols:gAvgInfoStr = ""
1326                Execute "GetAvgInfo()"          //will put up missing paramter dialog and do all the work
1327                //:gAvgInfo is reset by the Proc(), copy this string tot he protocol
1328                SVAR tempStr=root:myGlobals:Protocols:gAvgInfoStr
1329               
1330                //get a file path for saving files, if desired
1331                /////no - save files to the same data folder as the one with the raw data
1332                //then only one path to manage.
1333                //String yesNo = StringByKey("SAVE", tempStr,"=", ";")
1334                //if(cmpstr("Yes",yesNo) == 0)          //0=yes
1335                        //NewPath/C/M="Select Folder"/O Save_path               //Save_path is the symbolic path
1336                //Endif
1337
1338                newProtocol[5] = tempStr
1339                KillStrings/Z tempStr
1340        else
1341                //no averaging desired
1342                newProtocol[5] = "AVTYPE=none"
1343        Endif
1344       
1345        //returns the name of the newly created (= currently in use) protocol wave through a global
1346        String/G root:myGlobals:Protocols:gProtoStr = newProtoStr
1347End
1348
1349//function to check the work files (to see what's already there)
1350//and compare that with the files that are supposed to be there, according to the
1351//current protocol (to save unnecessary time re-loading files)
1352//
1353//the "type" folder is checked for all files in the list req(ested)Files
1354//note that the list of files is a full path:name;ver, while the
1355//fileList in the folder is just the name (or a list of names)
1356//
1357//returns 0 false, if files are NOT present
1358//or 1 = true, yes, the files are there as requested
1359//
1360Function AreFilesThere(type,reqFiles)
1361        String type,reqFiles
1362       
1363        //in general, reqFiles is a list of full paths to files - which MAY include semicolon version numbers
1364        //reqFiles MUST be constructed with COMMAS as list separators, to avoid disaster
1365        //when the version numbers are interpreted as filenames
1366       
1367        //get the number of files requested
1368        Variable nReq,nCur,match,ii
1369        nReq = ItemsInList(reqFiles,",")
1370       
1371        //get the name of the file currently in BGD - in the global fileList
1372        //fileList has NAMES ONLY - since it was derived from the file header
1373        String testStr
1374        testStr = "root:"+type+":fileList"
1375        if(Exists(testStr) == 2)                //2 if string variable exists
1376                SVAR curFiles = $testStr
1377        else
1378                //no files currently in type folder, return zero
1379                Return (0)
1380        Endif
1381        //get the number of files already in folder
1382        nCur = ItemsInList(curFiles,";")
1383        If(nCur != nReq)
1384                Return (0)              //quit now, the wrong number of files present
1385        Endif
1386        //right number of files... are the names right...
1387        //check for a match (case-sensitive!!) of each requested file in the curFile string
1388        //need to extract filenames from reqFiles, since they're the full path and name
1389       
1390        ii=0
1391        do
1392                testStr = StringFromList(ii,reqFiles,",")       //testStr is the Nth full path and filename
1393                //testStr = GetFileNameFromPathNoSemi(testStr)  //testStr will now be just the filename
1394                match = stringmatch(curFiles,testStr)
1395                If(!match)
1396                        Return (0)              //req file was not found in curFile list - get out now
1397                Endif
1398                ii+=1
1399        while(ii<nreq)
1400       
1401        Return (1)              //indicate that files are OK, no changes needed
1402End
1403
1404//will add the files specified in the protocol to the "type" folder
1405//will add multiple files together if more than one file is requested
1406//(list is a comma delimited list of filenames, with NO path information)
1407//
1408// This routine NOW DOES check for the possibility that the filenames may have ";vers" from the
1409// VAX - data should be picked up from Charlotte, where it won't have version numbers.
1410//
1411Function AddFilesInList(type,list)
1412        String type,list
1413       
1414        //type is the work folder to put the data into, and list is a COMMA delimited list of paths/names
1415        Variable num,ii,err=0,refNum
1416        String filename,pathStr=""
1417        PathInfo catPathName                    //this is where the files are
1418        pathstr=S_path
1419       
1420        num = ItemsInList(list,",")             // comma delimited list
1421       
1422        ii=0
1423        do
1424                //FindValidFilename only needed in case of vax version numbers
1425                filename = pathStr + FindValidFilename(StringFromList(ii,list,","))
1426                Open/Z/R refnum as filename
1427                if(V_flag != 0)         //file not found
1428                        //Print "file not found AddFilesInList()"
1429                        //Print filename
1430                        err = 1
1431                        return(err)
1432                Endif
1433                Close refnum            //file was found and opened, so close it
1434                ReadHeaderAndData(filename)
1435                if(ii == 0)
1436                        //first pass, wipe out the old contents of the work file
1437                        err =  Raw_to_work(type)
1438                else
1439                        err = Add_raw_to_work(type)
1440                Endif
1441                ii+=1
1442        while(ii<num)
1443        return(err)
1444End
1445
1446//function will reduce a sample file (or ask for file(s))
1447//using the protocol named as "protoStr" in the Protocols subfolder
1448//samStr is the file(s) or "ask" to force prompt
1449//sequentially proceeds through flowchart, doing reduction steps as needed
1450//show Schematic to debug what steps/values were used
1451//
1452//function is long, but straightforward logic
1453//
1454Function ExecuteProtocol(protStr,samStr)
1455        String protStr,samStr
1456        //protStr is the full path to the selected protocol wave
1457        //samStr is either "ask" or the name ONLY ofthe desired sample data file(s) (NO PATH)
1458        WAVE/T prot = $protStr
1459        SetDataFolder root:myGlobals:Protocols
1460       
1461        Variable filesOK,err,notDone
1462        String activeType, msgStr, junkStr, pathStr=""
1463        PathInfo catPathName                    //this is where the files are
1464        pathStr=S_path
1465       
1466       
1467        //Parse the instructions in the prot wave
1468        //0 - bkg
1469        //1 - emp
1470        //2 - div
1471        //3 - mask
1472        //4 - abs params c2-c5
1473        //5 - average params
1474        //6 = DRK file (**out of sequence)
1475       
1476        //prompt for sam data => read raw data, add to sam folder
1477        //or parse file(s) from the input paramter string
1478        activeType = "SAM"
1479        msgStr = "Select sample data"
1480        //Ask for SAM file or parse
1481        do
1482                if((cmpstr(samStr,"ask") == 0) || (cmpstr(samStr,"")==0) )              //zero if strings are equal
1483                        err = LoadRawSANSData(msgStr)           //will prompt for file
1484                        if(err)
1485                                PathInfo/S catPathName
1486                                Abort "reduction sequence aborted"
1487                        endif
1488                        err =  Raw_to_work(activeType)          //this is the first file (default)
1489                        //Ask for another SAM file
1490                        do
1491                                DoAlert 1,"Do you want to add another Sample file?"
1492                                if(V_flag == 1)         //yes
1493                                        err = LoadRawSANSData(msgStr)           //will prompt for file
1494                                        if(err)
1495                                                PathInfo/S catPathName
1496                                                Abort "reduction sequence aborted"
1497                                        endif
1498                                        err = Add_raw_to_work(activeType)
1499                                        notDone = 1
1500                                else
1501                                        notDone = 0
1502                                endif
1503                        while(notDone)
1504                        break
1505                Endif
1506                //"none" is not an option - you always need a sample file - "none" will never return zero
1507                //if not "ask" AND not "none" then try to parse the filenames
1508                If((cmpstr(samStr,"none") != 0) && (cmpstr(samStr,"ask") != 0))
1509                        filesOK = AreFilesThere(activeType,samStr)              //return 1 if correct files are already there
1510                        if(!filesOK)
1511                                //add the correct file(s) to SAM
1512                                err = AddFilesInList(activeType,samStr)
1513                                if(err)
1514                                        //Print "samstr = ",samStr
1515                                        Abort "SAM file not found, reset SAM file"
1516                                Endif
1517                        Endif
1518                Endif
1519        While(0)
1520        //always update
1521        UpdateDisplayInformation(ActiveType)
1522       
1523        //check for bkg file  -- "ask" might not fail - "ask?" will - ? not allowed in VAX filenames
1524        // add if needed
1525        //use a "case" statement
1526        msgStr = "Select background file"
1527        activeType = "BGD"
1528        do
1529                if(cmpstr(prot[0],"ask") == 0)          //zero if strings are equal
1530                        err = LoadRawSANSData(msgStr)           //will prompt for file
1531                        if(err)
1532                                PathInfo/S catPathName
1533                                Abort "reduction sequence aborted"
1534                        endif
1535                        err =  Raw_to_work(activeType)          //this is the first file (default)
1536                        //Ask for another BGD file
1537                        do
1538                                DoAlert 1,"Do you want to add another Background file?"
1539                                if(V_flag == 1)         //yes
1540                                        err = LoadRawSANSData(msgStr)           //will prompt for file
1541                                        if(err)
1542                                                PathInfo/S catPathName
1543                                                Abort "reduction sequence aborted"
1544                                        endif
1545                                        err = Add_raw_to_work(activeType)
1546                                        notDone = 1
1547                                else
1548                                        notDone = 0
1549                                endif
1550                        while(notDone)
1551                        UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1552                        break
1553                Endif
1554                If(cmpstr(prot[0],"none") == 0)
1555                        //clean out the BKG folder?
1556                        //KillDataFolder root:BKG
1557                        //NewDataFolder/O root:BKG
1558                        break
1559                Endif
1560                //if not "ask" AND not "none" then try to parse the filenames
1561                If((cmpstr(prot[0],"none") != 0) && (cmpstr(prot[0],"ask") != 0))
1562                        filesOK = AreFilesThere(activeType,prot[0])
1563                        if(!filesOK)
1564                                //add the correct file(s) to BGD
1565                                err = AddFilesInList(activeType,prot[0])
1566                                If(err)
1567                                        Abort "BGD file not found. Reset BGD file list"
1568                                Endif
1569                        Endif
1570                        UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1571                Endif
1572        While(0)
1573       
1574       
1575        //check for emp file (prot[1])
1576        // add if needed
1577        msgStr = "Select empty cell data"
1578        activeType = "EMP"
1579        do
1580                if(cmpstr(prot[1],"ask") == 0)
1581                        err = LoadRawSANSData(msgStr)           //will prompt for file
1582                        if(err)
1583                                PathInfo/S catPathName
1584                                Abort "reduction sequence aborted"
1585                        endif
1586                        err =  Raw_to_work(activeType)          //this is the first file (default)
1587                        //Ask for another EMP file
1588                        do
1589                                DoAlert 1,"Do you want to add another Empty Cell file?"
1590                                if(V_flag == 1)         //yes
1591                                        err = LoadRawSANSData(msgStr)           //will prompt for file
1592                                        if(err)
1593                                                PathInfo/S catPathName
1594                                                Abort "reduction sequence aborted"
1595                                        endif
1596                                        err = Add_raw_to_work(activeType)
1597                                        notDone = 1
1598                                else
1599                                        notDone = 0
1600                                endif
1601                        while(notDone)
1602                        UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1603                        break
1604                Endif
1605                If(cmpstr(prot[1],"none") == 0)
1606                        //clean out the EMP folder?
1607                        //KillDataFolder root:EMP
1608                        //NewDataFolder/O root:EMP
1609                        break
1610                Endif
1611                //if not "ask" AND not "none" then try to parse the filenames
1612                If((cmpstr(prot[1],"none") != 0) && (cmpstr(prot[1],"ask") != 0))
1613                        filesOK = AreFilesThere(activeType,prot[1])
1614                        if(!filesOK)
1615                                //add the correct file(s) to BGD
1616                                err = AddFilesInList(activeType,prot[1])
1617                                If(err)
1618                                        Abort "EMP file not found. Reset EMP file list"
1619                                Endif
1620                        Endif
1621                        UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1622                Endif
1623        While(0)
1624       
1625        //do the CORRECT step based on the answers to emp and bkg subtraction
1626        //by setting the proper"mode"
1627        //1 = both emp and bgd subtraction
1628        //2 = only bgd subtraction
1629        //3 = only emp subtraction
1630        //4 = no subtraction
1631        //additional modes 091301
1632        //11 = emp, bgd, drk
1633        //12 = bgd and drk
1634        //13 = emp and drk
1635        //14 = no subtractions
1636        //work.drk is from proto[6]
1637        //
1638        //subtracting just the DRK data is NOT an option - it doesnt' really make any physical sense
1639        // - in this case, DRK is skipped (equivalent to mode==4)
1640        // automatically accounts for attenuators given the lookup tables and the
1641        //desired subtractions
1642        //Attenuator lookup tables are alredy implemented (NG1 = NG7)
1643        //
1644       
1645        //read in the DRK data if necessary
1646        //only one file, assumed to be RAW data
1647        //
1648        String fname="",drkStr=""
1649        drkStr=StringByKey("DRK",prot[6],"=",",")
1650        if(cmpstr(drkStr,"none") != 0)
1651                err = ReadHeaderAndData( (pathStr+drkStr) )
1652                if(err)
1653                        PathInfo/S catPathName
1654                        Abort "reduction sequence aborted"
1655                endif
1656                err = Raw_to_Work_NoNorm("DRK")
1657        endif
1658       
1659        //dispatch to the proper "mode" of Correct()
1660        Variable mode=4,val
1661        do
1662                if( (cmpstr("none",prot[0]) == 0)       && (cmpstr("none",prot[1]) == 0) )
1663                        //no subtraction (mode = 4),
1664                        mode = 4
1665                Endif
1666                If((cmpstr(prot[0],"none") != 0) && (cmpstr(prot[1],"none") == 0))
1667                        //subtract BGD only
1668                        mode=2
1669                Endif
1670                If((cmpstr(prot[0],"none") == 0) && (cmpstr(prot[1],"none") != 0))
1671                        //subtract EMP only
1672                        mode=3
1673                Endif
1674                If((cmpstr(prot[0],"none") != 0) && (cmpstr(prot[1],"none") != 0))
1675                        // bkg and emp subtraction are to be done (BOTH not "none")
1676                        mode=1
1677                Endif
1678                activeType = "COR"
1679                //add in DRK mode (0= no used, 10 = used)
1680                val = NumberByKey("DRKMODE",prot[6],"=","," )
1681                mode += val
1682//              print "mode = ",mode
1683                err = Correct(mode)
1684                if(err)
1685                        SetDataFolder root:
1686                        Abort "error in Correct, called from executeprotocol, normal cor"
1687                endif
1688                UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1689        While(0)
1690       
1691        //check for work.div file (prot[2])
1692        //add if needed
1693        // can't properly check the filename - so for now add and divide, if anything other than "none"
1694        //do/skip divide step based on div answer
1695        If(cmpstr("none",prot[2])!=0)           // if !0, then there's a file requested
1696                If(cmpstr("ask",prot[2]) == 0)
1697                        //ask user for file
1698                         junkStr = PromptForPath("Select the detector sensitivity file")
1699                        If(strlen(junkStr)==0)
1700                                SetDataFolder root:
1701                                Abort "No file selected, data reduction aborted"
1702                        Endif
1703                         ReadHeaderAndWork("DIV", junkStr)
1704                else
1705                        //assume it's a path, and that the first (and only) item is the path:file
1706                        //list processing is necessary to remove any final comma
1707                        junkStr = pathStr + StringFromList(0, prot[2],"," )
1708                        ReadHeaderAndWork("DIV",junkStr)
1709                Endif
1710                //got a DIV file, select the proper type of work data to DIV (= activeType)
1711                err = Divide_work(activeType)           //returns err = 1 if data doesn't exist in specified folders
1712                If(err)
1713                        SetDataFolder root:
1714                        Abort "data missing in DIV step, call from executeProtocol"
1715                Endif
1716                activeType = "CAL"
1717                UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1718        Endif
1719       
1720        Variable c2,c3,c4,c5
1721        //do absolute scaling if desired
1722        if(cmpstr("none",prot[4])!=0)
1723                if(cmpstr("ask",prot[4])==0)
1724                        //get the params from the user
1725                        Execute "AskForAbsoluteParams_Quest()"
1726                        //then from the list
1727                        SVAR junkAbsStr = root:myGlobals:Protocols:gAbsStr
1728                        c2 = NumberByKey("TSTAND", junkAbsStr, "=", ";")        //parse the list of values
1729                        c3 = NumberByKey("DSTAND", junkAbsStr, "=", ";")
1730                        c4 = NumberByKey("IZERO", junkAbsStr, "=", ";")
1731                        c5 = NumberByKey("XSECT", junkAbsStr, "=", ";")
1732                else
1733                        //get the parames from the list
1734                        c2 = NumberByKey("TSTAND", prot[4], "=", ";")   //parse the list of values
1735                        c3 = NumberByKey("DSTAND", prot[4], "=", ";")
1736                        c4 = NumberByKey("IZERO", prot[4], "=", ";")
1737                        c5 = NumberByKey("XSECT", prot[4], "=", ";")
1738                Endif
1739                //get the sample trans and thickness from the activeType folder
1740                String destStr = "root:"+activeType+":realsread"
1741                Wave dest = $destStr
1742                Variable c0 = dest[4]           //sample transmission
1743                Variable c1 = dest[5]           //sample thickness
1744               
1745                err = Absolute_Scale(activeType,c0,c1,c2,c3,c4,c5)
1746                if(err)
1747                        SetDataFolder root:
1748                        Abort "Error in Absolute_Scale(), called from executeProtocol"
1749                endif
1750                activeType = "ABS"
1751                UpdateDisplayInformation(ActiveType)            //update before breaking from loop
1752        Endif
1753       
1754        //check for mask
1755        //add mask if needed
1756        // can't properly check the filename - so for now always add
1757        //doesn't change the activeType
1758        if(cmpstr("none",prot[3])!=0)
1759                If(cmpstr("ask",prot[3])==0)
1760                        //get file from user
1761                        junkStr = PromptForPath("Select Mask file")
1762                        If(strlen(junkStr)==0)
1763                                //no selection of mask file is not a fatal error, keep going, and let cirave()
1764                                //make a "null" mask
1765                                //if none desired, make sure that the old mask is deleted
1766                                //junkStr = GetDataFolder(1)
1767                                //SetDataFolder root:MSK
1768                                KillWaves/Z root:MSK:data
1769                                //SetDataFolder junkStr
1770                                DoAlert 0,"No Mask file selected, data not masked"
1771                        else
1772                                //read in the file from the dialog
1773                                ReadMCID_MASK(junkStr)
1774                        Endif
1775                else
1776                        //just read it in from the protocol
1777                        //list processing is necessary to remove any final comma
1778                        junkStr = pathStr + StringFromList(0, prot[3],"," )
1779                        ReadMCID_MASK(junkStr)
1780                Endif
1781        else
1782                //if none desired, make sure that the old mask is deleted
1783                //junkStr = GetDataFolder(1)
1784                //SetDataFolder root:MSK
1785                KillWaves/Z root:MSK:data
1786                //SetDataFolder junkStr
1787        Endif
1788       
1789        //mask data if desired (this is done automatically  in the average step) and is
1790        //not done explicitly here (if no mask in MSK folder, a null mask is created and "used")
1791       
1792        // average/save data as specified
1793       
1794        //Parse the keyword=<Value> string as needed, based on AVTYPE
1795       
1796        //average/plot first
1797        String av_type = StringByKey("AVTYPE",prot[5],"=",";")
1798        If(cmpstr(av_type,"none") != 0)
1799                If (cmpstr(av_type,"")==0)              //if the key could not be found... (if "ask" the string)
1800                        //get the averaging parameters from the user, as if the set button was hit
1801                        //in the panel
1802                        SetAverageParamsButtonProc("dummy")             //from "ProtocolAsPanel"
1803                        SVAR tempAveStr = root:myGlobals:Protocols:gAvgInfoStr
1804                        av_type = StringByKey("AVTYPE",tempAveStr,"=",";")
1805                else
1806                        //there is info in the string, use the protocol
1807                        //set the global keyword-string to prot[5]
1808                        String/G root:myGlobals:Protocols:gAvgInfoStr = prot[5]
1809                Endif
1810        Endif
1811       
1812        //convert the folder to linear scale before averaging, then revert by calling the window hook
1813        ConvertFolderToLinearScale(activeType)
1814       
1815        strswitch(av_type)      //dispatch to the proper routine to average to 1D data
1816                case "none":           
1817                        //still do nothing
1818                        break                   
1819                case "2D_ASCII":       
1820                        //do nothing
1821                        break
1822                case "QxQy_ASCII":
1823                        //do nothing
1824                        break
1825                case "PNG_Graphic":
1826                        //do nothing
1827                        break
1828                case "Rectangular":
1829                        RectangularAverageTo1D(activeType)
1830                        break
1831                case "Annular":
1832                        AnnularAverageTo1D(activeType)
1833                        break
1834                case "Circular":
1835                        CircularAverageTo1D(activeType)
1836                        break
1837                case "Sector":
1838                        CircularAverageTo1D(activeType)
1839                        break
1840                default:       
1841                        //do nothing
1842        endswitch
1843///// end of averaging dispatch
1844        // put data back on log or lin scale as set by default
1845        fRawWindowHook()
1846       
1847        //save data if desired
1848        String fullpath = "", newfileName=""
1849        String item = StringByKey("SAVE",prot[5],"=",";")               //does user want to save data?
1850        If( (cmpstr(item,"Yes")==0) && (cmpstr(av_type,"none") != 0) )         
1851                //then save
1852                //get name from textwave of the activeType dataset
1853                String textStr = "root:"+activeType+":textread"
1854                Wave/T textPath = $textStr
1855                If(WaveExists(textPath) == 1)
1856                        newFileName = GetNameFromHeader(textPath[0])
1857                else
1858                        newFileName = ""                        //if the header is missing?
1859                        //Print "can't read the header - newfilename is null"
1860                Endif
1861               
1862                //pick ABS or AVE extension
1863                String exten = activeType
1864                if(cmpstr(exten,"ABS") != 0)
1865                        exten = "AVE"
1866                endif
1867                if(cmpstr(av_type,"2D_ASCII") == 0)
1868                        exten = "ASC"
1869                endif
1870                if(cmpstr(av_type,"QxQy_ASCII") == 0)
1871                        exten = "DAT"
1872                endif
1873               
1874                //Path is catPathName, symbolic path
1875                //if this doesn't exist, a dialog will be presented by setting dialog = 1
1876                Variable dialog = 0
1877                PathInfo/S catPathName
1878                item = StringByKey("NAME",prot[5],"=",";")              //Auto or Manual naming
1879                If((cmpstr(item,"Manual")==0) || (cmpstr(newFileName,"") == 0))
1880                        //manual name if requested or if no name can be derived from header
1881                        fullPath = newfileName + "."+ exten //puts possible new name or null string in dialog
1882                        dialog = 1              //force dialog for user to enter name
1883                else
1884                        //auto-generate name and prepend path - won't put up any dialogs since it has all it needs
1885                        fullPath = S_Path + newFileName+ "." + exten   
1886                Endif
1887                //
1888                strswitch(av_type)     
1889                        case "Annular":
1890                                WritePhiave_W_Protocol(activeType,fullPath,dialog)
1891                                break
1892                        case "2D_ASCII":
1893                                Fast2DExport(activeType,fullPath,dialog)
1894                                break
1895                        case "QxQy_ASCII":
1896                                QxQy_Export(activeType,fullPath,dialog)
1897                                break
1898                        case "PNG_Graphic":
1899                                SaveAsPNG(activeType,fullpath,dialog)
1900                                break
1901                        default:
1902                                WriteWaves_W_Protocol(activeType,fullpath,dialog)
1903                endswitch
1904               
1905                //Print "data written to:  "+ fullpath
1906        Endif
1907       
1908        //done with everything in protocol list
1909        Return(0)
1910End
1911
1912//updates the currently displayed information to the data in "type"
1913//data folder - changes the title of the window and the global of the
1914//currently displayed data type - the recreation macro does the work
1915//
1916Function UpdateDisplayInformation(type)
1917        String type
1918
1919        String newTitle = "WORK_"+type
1920        DoWindow/F SANS_Data
1921        DoWindow/T SANS_Data, newTitle
1922        KillStrings/Z newTitle
1923       
1924        //need to update the display with "data" from the correct dataFolder
1925        //reset the current displaytype to "type"
1926        String/G root:myGlobals:gDataDisplayType=Type
1927       
1928        fRawWindowHook()
1929       
1930        //no error
1931        Return(0)
1932End
1933
1934//missing parameter dialog to solicit the 4 absolute intensity parameters
1935//from the user
1936//values are passed back as a global string variable (keyword=value)
1937//
1938Proc AskForAbsoluteParams(c2,c3,c4,c5)
1939        Variable c2=0.95,c3=0.1,c4=1,c5=32.0
1940        Prompt c2, "Standard Transmission"
1941        Prompt c3, "Standard Thickness (cm)"
1942        Prompt c4, "I(0) from standard fit (normalized to 1E8 monitor cts)"
1943        Prompt c5, "Standard Cross-Section (cm-1)"
1944       
1945        String/G root:myGlobals:Protocols:gAbsStr=""
1946       
1947        root:myGlobals:Protocols:gAbsStr = "TSTAND="+num2str(c2)
1948        root:myGlobals:Protocols:gAbsStr +=  ";" + "DSTAND="+num2str(c3)
1949        root:myGlobals:Protocols:gAbsStr +=  ";" + "IZERO="+num2str(c4)
1950        root:myGlobals:Protocols:gAbsStr +=  ";" + "XSECT="+num2str(c5)
1951       
1952End
1953
1954//asks the user for absolute scaling information. the user can either
1955//enter the 4 necessary values in manually (missing parameter dialog)
1956//or the user can select an empty beam file from a standard open dialog
1957//if an empty beam file is selected, the "kappa" value is automatically calculated
1958//in either case, the global keyword=value string is set.
1959//
1960//Proc AskForAbsoluteParams_Quest()
1961Function AskForAbsoluteParams_Quest()   
1962       
1963        Variable err, isNG5=0,loc,refnum
1964        //ask user if he wants to use a transmision file for absolute scaling
1965        //or if he wants to enter his own information
1966        DoAlert 1,"<Yes> to enter your own values, <No> to select an empty beam flux file"
1967        If ( (V_Flag==1) )
1968                //yes selected, prompt for values
1969                Execute "AskForAbsoluteParams()"                //missing parameters
1970        else
1971                //no selected, prompt for file, and use this to calculate KAPPA
1972                Variable kappa=1
1973               
1974                //ask for file and read it into RAW
1975                //will cancel if no file is selected
1976                err = LoadRawSANSData("select the empty beam file")             //reads and displays the RAW data
1977                if(err)
1978                        PathInfo/S catPathName
1979                        Abort "reduction sequence aborted"
1980                endif
1981                       
1982                Wave/T tw=$"root:RAW:TextRead"
1983                Wave rw=$"root:RAW:RealsRead"
1984                Wave iw=$"root:RAW:IntegersRead"
1985                String acctStr = tw[3]
1986                //NG5 attenuator transmission is assumed to be the same as the table for NG7
1987                       
1988                //get the necessary variables for the calculation of kappa
1989                Variable detCnt,countTime,attenTrans,monCnt,sdd,pixel
1990                String detStr=tw[9]
1991                pixel = DetectorPixelResolution(acctStr,detStr)         //get the pixel size from the file information
1992                countTime = iw[1]
1993                //detCnt = rw[2]                //080802 -use sum of data, not scaler from header
1994                monCnt = rw[0]
1995                sdd = rw[18]
1996                sdd *=100               //convert from meters to cm
1997                               
1998                //lookup table for transmission factor
1999                //determine which instrument the measurement was done on from acctStr
2000                Variable lambda = rw[26]
2001                Variable attenNo = rw[3]
2002                attenTrans = AttenuationFactor(acctStr,lambda,attenNo)
2003                //Print "attenTrans = ",attenTrans
2004               
2005                //get the XY box, if needed
2006                Variable x1,x2,y1,y2
2007                String filename=tw[0],tempStr
2008                err = GetXYBoxFromFile(filename,x1,x2,y1,y2)            //xy's are passed/returned by reference
2009                Print x1,x2,y1,y2
2010
2011                if( ((x1-x2)==0) || ((y1-y2)==0) )      //need to re-select the box
2012                        err = SelectABS_XYBox(x1,x2,y1,y2)              //this will pause for user input
2013                        if(err)
2014                                Abort "Box not selected properly - Please re-set the ABS parameters"
2015                        Endif
2016                        //box is OK, write box values to file
2017                        PathInfo/S catPathName
2018                        String tempName = S_Path + FindValidFilename(filename)
2019                        WriteXYBoxToHeader(tempName,x1,x2,y1,y2)
2020                else
2021                        //give option to override
2022                        tempStr = "X=("+num2str(x1)+","+num2str(x2)+") Y=("+num2str(y1)+","+num2str(y2)+")"
2023                        DoAlert 1,"The current box is "+tempStr+".  Do you want to override these values?"
2024                        //Print v_flag
2025                        if(V_flag==1)   //1==yes, override
2026                                err = SelectABS_XYBox(x1,x2,y1,y2)
2027                                if(err)
2028                                        Abort "Box not selected properly -Please re-set the ABS parameters"
2029                                Endif
2030                        endif
2031                Endif
2032                Printf "Using Box X(%d,%d),Y(%d,%d)\r",x1,x2,y1,y2
2033               
2034                //need the detector sensitivity file - make a guess, allow to override
2035                String junkStr=""
2036                if(! waveexists($"root:DIV:data"))
2037                         junkStr = PromptForPath("Select the detector sensitivity file")
2038                        If(strlen(junkStr)==0)
2039                                SetDataFolder root:
2040                                Abort "No file selected, data reduction aborted"
2041                        Endif
2042                         ReadHeaderAndWork("DIV", junkStr)
2043                endif
2044                //toggle SANS_Data to linear display if needed, so that we're working with linear scaled data
2045                ControlInfo/W=SANS_Data bisLog
2046                if(V_Flag==1)
2047                        Log_Lin("bisLog")       
2048                endif   
2049                Wave divData = $"root:div:Data"
2050                Wave data = $"root:raw:data"            //this will be the linear data
2051                // correct by detector sensitivity
2052                data /= divData
2053               
2054                // now do the sum, only in the box     
2055//              detCnt = sum($"root:raw:data", -inf, inf )
2056//              Print "box is now ",x1,x2,y1,y2
2057                detCnt = SumCountsInBox(x1,x2,y1,y2,"RAW")
2058                //             
2059                kappa = detCnt/countTime/attenTrans*1.0e8/(monCnt/countTime)*(pixel/sdd)^2
2060                junkStr = num2str(kappa)
2061                // set the parameters in the global string
2062                Execute "AskForAbsoluteParams(1,1,"+junkStr+",1)"               //no missing parameters, no dialog
2063               
2064                //should wipe out the data in the RAW folder, since it's not really RAW now
2065                DoWindow/K SANS_Data
2066                // SRK JUL 2006 don't clear the contents - just kill the window to force new data to be loaded
2067                // - obsucre bug if "ask" in ABS section of protocol clears RAW folder, then Q-axes can't be set from RAW:RealsRead
2068                //ClearDataFolder("RAW")       
2069        Endif
2070        Print "Kappa was successfully calculated as = ",kappa
2071End
2072
2073Function UserSelectBox_Continue(ctrlName) :buttonControl
2074        String ctrlName
2075       
2076        DoWindow/K junkWindow           //kill panel
2077end
2078
2079Function SelectABS_XYBox(x1,x2,y1,y2)
2080        Variable &x1,&x2,&y1,&y2
2081       
2082        Variable err=0
2083       
2084        Variable/G root:V_marquee=1             //sets the sneaky bit to automatically update marquee coords
2085        Variable/G root:V_left,root:V_right,root:V_bottom,root:V_top    //must be global for auto-update
2086        DoWindow/F SANS_Data
2087        NewPanel/K=2 /W=(139,341,382,432) as "Select the primary beam"
2088        DoWindow/C junkWindow
2089        AutoPositionWindow/E/M=1/R=SANS_Data
2090       
2091        Drawtext 21,20 ,"Select the primary beam with the"
2092        DrawText 21,40, "marquee and press continue"
2093        Button button0,pos={80,58},size={92,20},title="Continue"
2094        Button button0,proc=UserSelectBox_Continue
2095       
2096        PauseForUser junkWindow,SANS_Data
2097       
2098        DoWindow/F SANS_Data
2099
2100        //GetMarquee left,bottom                        //not needed
2101        NVAR V_left=V_left
2102        NVAR V_right=V_right
2103        NVAR V_bottom=V_bottom
2104        NVAR V_top=V_top
2105       
2106        x1 = V_left
2107        x2 = V_right
2108        y1 = V_bottom
2109        y2 = V_top
2110//      Print "new values,before rounding = ",x1,x2,y1,y2
2111        KeepSelectionInBounds(x1,x2,y1,y2)
2112        //Print "new values = ",x1,x2,y1,y2
2113       
2114        KillVariables/Z root:V_Marquee,root:V_left,root:V_right,root:V_bottom,root:V_top
2115        if((x1-x2)==0 || (y1-y2)==0)
2116                err=1
2117        endif
2118        return(err)
2119End
2120
2121//save the protocol as an IGOR text wave (.itx)
2122//
2123//
2124Function ExportProtocol(ctrlName) : ButtonControl
2125        String ctrlName
2126// get a list of protocols
2127        String Protocol=""
2128        SetDataFolder root:myGlobals:Protocols
2129        Prompt Protocol "Pick A Protocol",popup, WaveList("*",";","")
2130        DoPrompt "Pick A Protocol to Export",Protocol
2131        if(V_flag==1)
2132                //Print "user cancel"
2133                SetDatafolder root:
2134                return(1)
2135        endif
2136//get the selection, or exit
2137        Wave/T pW= $protocol
2138        Make/O/T/N=13 tw
2139// save in the proper format (must write manually, for demo version)
2140        tw[0] = "IGOR"
2141        tw[1] = "WAVES/T \t"+protocol
2142        tw[2] = "BEGIN"
2143        tw[3,10] = "\t\""+pW[p-3]+"\""
2144        tw[11] = "END"
2145        tw[12] = "X SetScale/P x 0,1,\"\","+protocol+"; SetScale y 0,0,\"\","+protocol
2146       
2147        Variable refnum
2148        String fullPath
2149       
2150        PathInfo/S catPathName
2151        fullPath = DoSaveFileDialog("Export Protocol as")
2152        If(cmpstr(fullPath,"")==0)
2153                //user cancel, don't write out a file
2154                Close/A
2155                Abort "no Protocol file was written"
2156        Endif
2157
2158        //actually open the file
2159        Open refNum as fullpath+".itx"
2160       
2161        wfprintf refnum, "%s\r", tw
2162        Close refnum
2163        //Print "all is well  ",protocol
2164        KillWaves/Z tw
2165        setDataFolder root:
2166        return(0)
2167
2168End
2169
2170//imports a protocol from disk into the protocols folder
2171//
2172// will overwrite existing protocols if necessary
2173//
2174//
2175Function ImportProtocol(ctrlName) : ButtonControl
2176        String ctrlName
2177
2178        SetDataFolder root:myGlobals:Protocols
2179
2180        String fullPath
2181       
2182        PathInfo/S catPathName
2183        fullPath = DoOpenFileDialog("Import Protocol")
2184        If(cmpstr(fullPath,"")==0)
2185                //user cancel, don't write out a file
2186                Close/A
2187                Abort "no protocol was loaded"
2188        Endif
2189       
2190        LoadWave/O/T fullPath
2191       
2192        SetDataFolder root:
2193        return(0)
2194end
Note: See TracBrowser for help on using the repository browser.