source: branches/sandbox/expgui @ 1019

Last change on this file since 1019 was 1019, checked in by toby, 12 years ago

Fix Save as bug

  • Property svn:keywords set to Author Date Revision Id
File size: 159.5 KB
Line 
1#!/bin/sh
2# the next line restarts this script using wish found in the path\
3exec wish "$0" "$@"
4# If this does not work, change the #!/usr/bin/wish line below
5# to reflect the actual wish location and delete all preceeding lines
6#
7# (delete here and above)
8#!/usr/bin/wish
9# $Id: expgui 1019 2010-10-05 18:56:54Z toby $
10set expgui(Revision) {$Revision: 1019 $ $Date: 2010-10-05 18:56:54 +0000 (Tue, 05 Oct 2010) $}
11
12package require Tk
13
14# to do:
15#
16# need to change heading and button label depending on where getExpFileName
17# is called from?
18#
19# global background editing & profile work differently: should both
20# start out blank with a "load from option"?
21#
22# idea:
23# a scroll list for all histogram refinement flags ; click on takes you to the
24# appropriate menu.
25#
26# idea:
27#   change cell parameters to labels and have a edit cell button
28#   that enforces metric symmetry
29#
30# to allow "global" access on phase page
31#   change buttons from radio to multiple
32#   -- or display all 9 cell flag/damps and all atoms
33#   make editMultipleRecords work with multiple phases, also cell flag/damp
34#   blank cell entries
35#   add phase to atom number in listing
36#   DisplayAllAtoms needs to loop over phases
37#
38# idea: load more than one bank from a multi-bank .RAW file
39#
40if {$tcl_version < 8.0} {
41    tk_dialog .expFileErrorMsg "Version Error" \
42            "EXPGUI requires Tcl/Tk version 8.0 or higher" error 0 "Exit"
43    exit
44}
45
46# the shell variable tells expgui to act as a shell for GSAS
47# as well as edit the EXP file. In no-shell mode, it can
48# only be used to edit the .EXP file as a callable program
49set expgui(shell) 1
50catch {if $env(EXPGUI_NOSHELL) {set expgui(shell) 0}}
51
52set expgui(expfile) {}
53if {$argv != ""} {
54    if {[string match *noshell* [string tolower $argv]]} {
55        # I doubt that noshell mode is used by anyone
56        set expgui(shell) 0
57        set expgui(expfile)  [lindex $argv 1]
58    } else {
59        set expgui(expfile)  [lindex $argv 0]
60    }
61}
62
63set expgui(curhist) {}
64set expmap(powderlist) {}
65set expgui(bkgcolor1) #fdf
66
67set expgui(debug) 0
68catch {if $env(DEBUG) {set expgui(debug) 1}}
69#set expgui(debug) 1
70
71# location for web pages, if not found locally
72set expgui(website) 11bm.xor.aps.anl.gov/expguidoc/
73# default for archive mode = on
74set expgui(archive) 1
75# default for autoexec load = off
76set expgui(autoexpload) 0
77# default for execprompt = on
78set expgui(execprompt) 1
79# default for autostart GRWND = off
80set expgui(autoGRWND) 0
81# by default expgui is iconified while GENLES, etc runs
82set expgui(autoiconify) 1
83# default for show EXPTOOL output = off
84set expgui(showexptool) 0
85# save the name of the wish executable
86set wishshell [info nameofexecutable] 
87# misc constants
88set txtvw(font) "Courier"
89set expgui(font) 14
90set liveplot(hst) 1
91set liveplot(legend) 1
92set expgui(filesort) 1
93set expgui(initstring) {}
94# use a separate window for DISAGL (default)
95set expgui(disaglSeparateBox) 1
96set expgui(DefaultPeakType) 0
97# default: keep current atoms when replacing a phase
98set expgui(DeleteAllAtoms) 0
99# flags for running POWPREF
100set expgui(needpowpref) 0
101set expgui(needpowpref_why) ""
102# on Mac associate a app with .EXP file (on by default)
103set expgui(MacAssignApp) 1
104#=============================================================================
105#----------------------------------------------------------------
106# where are we?
107set expgui(script) [info script]
108# translate links -- go six levels deep
109foreach i {1 2 3 4 5 6} {
110    if {[file type $expgui(script)] == "link"} {
111        set link [file readlink $expgui(script)]
112        if { [file  pathtype  $link] == "absolute" } {
113            set expgui(script) $link
114        } {
115            set expgui(script) [file dirname $expgui(script)]/$link
116        }
117    } else {
118        break
119    }
120}
121# fixup relative paths
122if {[file pathtype $expgui(script)] == "relative"} {
123    set expgui(script) [file join [pwd] $expgui(script)]
124}
125# save the package installation location; fix if possible, warn later (after
126# routines are sourced)
127set scriptdir [
128               set expgui(scriptdir) [file dirname $expgui(script) ]
129               ]
130
131if {[string first " " $expgui(scriptdir)] != -1} {
132    if {$tcl_platform(platform) == "windows"} {
133        # translate to the windows 8.3 version, if supported for this drive
134        set expgui(scriptdir) [file attributes $expgui(scriptdir) -shortname]
135    }
136}
137set expgui(gsasdir) [file dirname $expgui(scriptdir)]
138set expgui(gsasexe) [file join $expgui(gsasdir) exe]
139set expgui(docdir) [file join $expgui(scriptdir) doc]
140#----------------------------------------------------------------
141# use EXPGUI directory for packages
142lappend auto_path $expgui(scriptdir)
143#----------------------------------------------------------------
144source [file join $expgui(scriptdir) opts.tcl]
145# fetch EXP file processing routines
146source [file join $expgui(scriptdir) readexp.tcl]
147# commands for running GSAS programs
148source [file join $expgui(scriptdir) gsascmds.tcl]
149# contents of GSAS menus
150source [file join $expgui(scriptdir) gsasmenu.tcl]
151# commands for adding phases, histograms & atoms
152source [file join $expgui(scriptdir) addcmds.tcl]
153# commands for preferred orientation
154source [file join $expgui(scriptdir) orient.tcl]
155# setting data range/excluded regions
156source [file join $expgui(scriptdir) exclinit.tcl]
157#---------------------------------------------------------------------------
158# override options with locally defined values
159lappend filelist [file join $expgui(scriptdir) localconfig]
160if {$tcl_platform(platform) == "windows"} {
161    lappend filelist "c:/gsas.config"
162}
163lappend filelist [file join ~ .gsas_config]
164if {[catch {
165    foreach file $filelist {
166        if [file exists $file] {source $file}
167    }
168} errmsg]} {
169    set msg "Error reading file $file (aka [file nativename $file]): $errmsg"
170    MyMessageBox -parent . -title "Customize warning" \
171        -message $msg -icon warning -type Ignore -default ignore \
172        -helplink "expguierr.html Customizewarning"
173}
174# warn/stop on spaces in install location
175if {[string first " " $scriptdir] != -1} {
176    if {$tcl_platform(platform) == "windows"} {
177        # did the translation it work?
178        if {[string first " " $expgui(scriptdir)] != -1} {
179            update
180            MyMessageBox -parent . -title "Spaces in path" \
181                -message "You are using an install directory with a space in the name ($scriptdir) that on Windows that does not have a corresponding DOS name. Is this on a networked drive? This install location will not work for EXPGUI. Sorry." \
182                -icon warning -type Quit -default quit
183            exit
184        }
185    }
186    set warn 1
187    catch {set warn $expgui(warnonscriptspace)}
188    if $warn {
189        update
190        MyMessageBox -parent . -title "Good luck..." \
191            -message "You are using an install directory with a space in the name ($scriptdir) -- You may encounter bugs in EXPGUI that I am trying to fix. If so, please e-mail enough detail to Brian.Toby@ANL.gov so that I can try to reproduce it." \
192            -icon warning -type Continue -default continue
193        set expgui(warnonscriptspace) 0
194    }
195}
196
197if [catch {package require BWidget}] {
198    set msg "Error loading the BWidget package: This should not happen if you use the version of Tcl/Tk (tcl84+.exe) distributed with EXPGUI"
199    MyMessageBox -parent . -title "BWidget load error" \
200        -message $msg -icon error -type Error -default error \
201        -helplink "debug_tcltk.html"
202    destroy .
203}
204SetTkDefaultOptions $expgui(font)
205#---------------------------------------------------------------------------
206set expgui(resize) 0
207# platform-specific code
208if {$tcl_platform(platform) == "windows" \
209        && $tcl_platform(os) == "Windows 95"} {
210    if {[catch {package require winexec}] && \
211            [catch {package require winutils}]} {
212        MyMessageBox -parent . -title "WINEXEC Error" \
213            -message "Error -- Unable to load the WINEXEC or the WINUTILS package. This is needed in Win-95/-98/-me machines" \
214            -icon error -type Quit -default quit \
215            -helplink "expgui_Win_readme.html Winexec"
216        destroy .
217    }
218}
219if {$tcl_platform(platform) == "windows"} {
220    # check the path -- can DOS use it?
221    if {[string first {\\} $expgui(script) ] != -1} {
222        MyMessageBox -parent . -title "Networked Path" \
223                -message "Note -- You may have problems running EXPGUI/GSAS from a network drive. If you have errors, map $expgui(gsasdir) to a \"drive\" (like F:). (Use \"Map network drive\" to do this.)" \
224                -icon error -type {"Be brave"} -default "be brave" \
225                -helplink "expgui_Win_readme.html NetPath"
226    }
227    # test for error in COMSPEC environment variable setting
228    if {[catch {set env(COMSPEC)}]} { 
229        set env(COMSPEC) {c:\windows\system32\cmd.exe}
230    }
231    if {[auto_execok $env(COMSPEC)] == ""} {
232        set env(COMSPEC) {c:\windows\system32\cmd.exe}
233    }
234    if {[auto_execok $env(COMSPEC)] == ""} {
235        MyMessageBox -parent . -title "cmd.exe not found " \
236            -message "The Windows COMSPEC environment variable is not set correctly. It should point to a copy of cmd.exe (or command.com on -95/-98/-ME). EXPGUI also did not find the file in the most common location (c:\\windows\\system32\\cmd.exe). Please fix: EXPGUI cannot run GSAS programs without this." \
237            -icon "error" -type Sorry -default sorry
238#           -helplink "expguierr.html Customizewarning"
239        return
240    }
241    set expgui(exptool) [file join $expgui(gsasexe) exptool.exe]
242} else {
243    set expgui(exptool) [file join $expgui(gsasexe) exptool]
244    if {$tcl_platform(os) != "Darwin"} {
245        if [catch {set env(GSASBACKSPACE)}] {set env(GSASBACKSPACE) 1}
246    }
247}
248# find the pgplot directory
249if {[file exists [file join $expgui(gsasdir) pgl]]} {
250    set expgui(pgplotdir) [file join $expgui(gsasdir) pgl]
251} elseif {[file exists [file join $expgui(gsasdir) pgplot]]} {
252    set expgui(pgplotdir) [file join $expgui(gsasdir) pgplot]
253} else {
254    MyMessageBox -parent . -title "PGPLOT Error" \
255            -message "Warning -- Unable to find PGPLOT directory. GSAS graphics will not work without this. Is GSAS correctly installed?" \
256            -icon warning -type {"Limp Ahead"} -default "Limp Ahead" \
257            -helplink "expguierr.html NoPGPLOT"
258    set expgui(resize) 1
259    set expgui(pgplotdir) ""
260}
261
262# old code used to fix up bad distributions
263# # do we have a PGPLOT fonts file?
264# # if it is in the "wrong" place/name -- make it "right"
265# if {![file exists [file join $expgui(pgplotdir) grfont.dat]] && \
266#       [file exists [file join $expgui(gsasdir) fonts grfont.dat]]} {
267#     catch {file mkdir $expgui(pgplotdir)}
268#     file copy [file join $expgui(gsasdir) fonts grfont.dat] \
269#           [file join $expgui(pgplotdir)  grfont.dat]
270# }
271# # do we have a PGPLOT fonts file?
272# if {![file exists [file join $expgui(pgplotdir)  grfont.dat]] && \
273#       [file exists [file join $expgui(gsasdir) fonts pgfont.dat]]} {
274#     catch {file mkdir $expgui(pgplotdir)}
275#     file copy [file join $expgui(gsasdir) fonts pgfont.dat] \
276#           [file join $expgui(pgplotdir)  grfont.dat]
277# }
278# # do we have a PGPLOT fonts file?
279# if {![file exists [file join $expgui(pgplotdir)  grfont.dat]] && \
280#       [file exists [file join $expgui(pgplotdir)  pgfont.dat]]} {
281#     file copy [file join $expgui(pgplotdir)  pgfont.dat] \
282#           [file join $expgui(pgplotdir)  grfont.dat]
283# }
284
285if { $expgui(pgplotdir) != "" && \
286         ![file exists [file join $expgui(pgplotdir)  grfont.dat]]} {
287    MyMessageBox -parent . -title "PGPLOT Error" \
288            -message "Warning -- Unable to find file GRFONT.DAT in $expgui(pgplotdir). GSAS graphics will not work. Is GSAS correctly installed?" \
289            -icon warning -type {"Limp Ahead"} -default "Limp Ahead" \
290            -helplink "expguierr.html NoPGPLOT"
291    set expgui(resize) 1
292}
293#---------------------------------------------------------------------------
294if {$expgui(expfile) != ""} {
295    if {[string match -nocase {.o[0-9a-f][0-9a-f]} \
296             [file extension $expgui(expfile)]]} {
297        if {[file exists $expgui(expfile)]} {
298            # this is an archived file -- archive the current .EXP file
299            set expnam [file rootname $expgui(expfile)]
300            # get the last archived version
301            set lastf [lindex [lsort [glob -nocomplain $expnam.{O\[0-9A-F\]\[0-9A-F\]}]] end]
302            if {$lastf == ""} {
303                set num 01
304            } else {
305                regexp {.*\.O([0-9A-F][0-9A-F])$} $lastf a num
306                scan $num %x num
307                if {$num >= 255} {
308                    set num FF
309                } else {
310                    set num [string toupper [format %.2x [incr num]]]
311                }
312            }
313            catch {
314                set newfile $expnam.O$num
315                file rename -force $expnam.EXP $newfile
316                set fp [open $expnam.LST a+]
317                puts $fp "\n----------------------------------------------"
318                puts $fp "     Regressing to archive file [file tail $expgui(expfile)]"
319                puts $fp "     but first archiving [file tail $expnam.EXP] as [file tail $newfile]"
320                puts $fp "----------------------------------------------\n"
321                close $fp
322            }
323            file copy -force $expgui(expfile) $expnam.EXP
324            set expgui(expfile) $expnam.EXP
325        } else {
326            MyMessageBox -parent . -title "File not found" \
327                -message "Warning -- Archive file $expgui(expfile) was not found." \
328                -icon warning -type OK -default ok
329            set expgui(expfile) {}
330        }
331    } else {
332        SetEXPfile $expgui(expfile)
333    }
334}
335if {$expgui(expfile) == ""} {
336    # place the parent window because the getExpFileName window will be centered above it.
337    set xpos 50
338    catch {set xpos $expgui(xpos)}
339    set ypos 50
340    catch {set ypos $expgui(ypos)}
341    set poscntr "nsew"
342    catch {set poscntr $expgui(poscenter)}
343    LocateWindow "." $xpos $ypos $poscntr
344    # windows needed this update before when using tk_getOpenFile.
345    # I am not sure it is still needed.
346    update
347    SetEXPfile [getExpFileName ""]
348    set expgui(resize) 1
349}
350if {$expgui(expfile) == ""} exit
351
352#
353# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
354# <<<<<<<<<<    BEGINNING OF MAIN: GLOBAL AREA FOR DATA EXTRACTION >>>>>>>>>>>
355# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
356# load exp file and set up dialogs
357proc loadexp {expfile} {
358    global expgui expmap entryvar entrycmd tcl_platform
359    set prevexp $expgui(expfile)
360    # is this a compressed archive file?
361    if {[string match {*.O[0-9A-F][0-9A-F]} $expfile]} {
362        set expnam [file rootname $expfile]
363        set ans [MyMessageBox -parent . -title "Load Archived File" \
364                -message "Loading archived version of $expnam. Do you want to continue using the same experiment name or work with the archived version under a new name?" \
365                -icon question -type "{Use New Name} {Continue with current}" \
366                -default {Use New Name} \
367                -helplink "expguierr.html LoadArchived"
368        ]
369        # archive the current .EXP file
370        if {$ans != "use new name" && [file exists $expfile]} {
371            # get the last archived version
372            set lastf [lindex [lsort [glob -nocomplain $expnam.{O\[0-9A-F\]\[0-9A-F\]}]] end]
373            if {$lastf == ""} {
374                set num 01
375            } else {
376                regexp {.*\.O([0-9A-F][0-9A-F])$} $lastf a num
377                scan $num %x num
378                if {$num >= 255} {
379                    set num FF
380                } else {
381                    set num [string toupper [format %.2x [incr num]]]
382                }
383            }
384            catch {
385                set newfile $expnam.O$num
386                file rename -force $expnam.EXP $newfile
387                set fp [open $expnam.LST a+]
388                puts $fp "\n----------------------------------------------"
389                puts $fp "     Regressing to archive file [file tail $expfile]"
390                puts $fp "     but first archiving [file tail $expnam.EXP] as [file tail $newfile]"
391                puts $fp "----------------------------------------------\n"
392                close $fp
393            }
394            file copy -force $expfile $expnam.EXP
395            set expfile $expnam.EXP
396        }
397        if {$ans == "use new name"} {
398            set newexpfile [getExpFileName new]
399            if {$newexpfile == ""} return 
400            file copy -force $expfile $newexpfile
401            catch {cd [string trim [file dirname $expgui(expfile)]]}
402            set expfile [file tail $newexpfile]
403            set expgui(needpowpref) 2
404            set expgui(needpowpref_why) "\tA new .EXP file was created\n" 
405            SetEXPfile $newexpfile
406        } else {
407            SetEXPfile $expfile
408        }
409        if {$expgui(expfile) == ""} {
410            set expgui(expfile) $prevexp
411            return
412        }
413    }
414
415    # change the icon and assign an app to this .EXP file
416    if {$tcl_platform(os) == "Darwin" && $expgui(MacAssignApp)} {
417        MacSetResourceFork $expfile
418    }
419
420    SetEXPfile $expfile
421    if {$expgui(expfile) == ""} {
422        set expgui(expfile) $prevexp
423        return
424    }
425    # read in the .EXP file
426    set fmt [expload $expfile]
427    # if the file was not in the correct format, force a rewrite before use
428    if {$fmt < 0} {
429        # read error
430        return
431    } elseif {$fmt == 1} {
432        set expgui(changed) 0
433    } else {
434        set expgui(changed) 1
435    }
436    mapexp
437    if {$expgui(MacroRunning)} {
438        set expgui(MacroStatus) "?"
439        catch {
440            set expgui(MacroStatus) \
441                "[expinfo cyclesrun] cycles; Chi2=$expgui(LastChi2); $expgui(LastnVars) vars"
442        }
443    }
444
445    set expgui(expModifiedLast) 0
446    catch {
447        set expgui(expModifiedLast) [file mtime $expgui(expfile)]
448    }
449    set expgui(last_History) [string range [string trim [lindex [exphistory last] 1]] 0 50 ]
450    # set the window/icon title
451    wm title . "EXPGUI interface to GSAS: $expfile"
452    set expgui(titleunchanged) 1
453    wm iconname . [file tail $expfile]
454
455    # load current information into EXPGUI pages
456    PaintEXPGUIpages
457
458    # start checking for external changes
459    afterawhile
460}
461
462# [re]load all screens with current state of EXPGUI file
463proc PaintEXPGUIpages {} {
464    global expgui expmap entryvar entrycmd
465    # reset the phase buttons
466    set expgui(curPhase) ""
467    # set the number of phases on the phase page
468    setphases
469
470    # disable the "global options" that don't make sense based on
471    # which histograms present
472    foreach num {1 2 3 4 5} {
473        set flag($num) 0
474    }
475    # save a list of the allowed modes, too
476    set expgui(AllowedHistSelectModes) {0 6}
477    foreach h $expmap(powderlist) {
478        if {[string range $expmap(htype_$h) 2 2] == "T"} {set flag(1) 1}
479        if {[string range $expmap(htype_$h) 1 2] == "NC"} {set flag(2) 1}
480        if {[string range $expmap(htype_$h) 1 2] == "XC" && \
481                [histinfo $h lam2] != 0.0} {set flag(3) 1}
482        if {[string range $expmap(htype_$h) 1 2] == "XC" && \
483                [histinfo $h lam2] == 0.0} {set flag(4) 1}
484        if {[string range $expmap(htype_$h) 1 2] == "XE"} {set flag(5) 1}
485    }
486    foreach num {1 2 3 4 5} \
487            lbl {TOF "CW Neutron" "Alpha12 Xray" "Monochromatic Xray" \
488            "Energy Disp Xray"} {
489        if $flag($num) {
490            $expgui(fm).option.menu.editmode entryconfigure $lbl -state normal
491            lappend expgui(AllowedHistSelectModes) $num
492        } else {
493            $expgui(fm).option.menu.editmode entryconfigure $lbl -state disabled
494        }
495    }
496    # disable traces on entryvar until we are ready
497    set entrycmd(trace) 0
498    trace vdelete entryvar w entvartrace
499
500    # propogate changes on the least squares page
501    set entryvar(cycles) [expinfo cycles]
502    set entrycmd(cycles) "expinfo cycles"
503    set entryvar(mbw) [expinfo mbw]
504    set entrycmd(mbw) "expinfo mbw"
505    # set expgui(globalmode) 0
506    set expgui(printopt) "Print Options ([expinfo print])"
507    set entryvar(title) [expinfo title]
508    global printopts
509    foreach num [array names printopts] {
510        set entrycmd(printopt$num) "printsetting $num"
511        set entryvar(printopt$num) [printsetting $num]
512    }
513    # enable traces on entryvar
514    set entrycmd(trace) 1
515    trace variable entryvar w entvartrace
516
517    # set fo extraction on LS page
518    SetupExtractHist
519    # set convergence criterion
520    InitLSvars
521
522    # update the histogram list & update the page
523    sethistlist
524}
525
526# called to reread the .EXP file
527proc rereadexp {expfile} {
528    global expgui
529    if $expgui(changed) {
530        set decision [tk_dialog .instrSaveData {Save .EXP changes} \
531                {You have made changes to the Experiment. Rereading will cause the changes to be lost. Select an option:} \
532                {} 0 "Save and reread" "Reread without Save" "Cancel reread command"]
533        switch $decision {
534            0 { savearchiveexp }
535            1 { }
536            2 { return }
537        }
538    }
539    loadexp $expgui(expfile)
540}
541
542proc SaveAsFile {} {
543    global expgui
544    global tcl_platform
545    set prevexp $expgui(expfile) 
546    set newexpfile [getExpFileName new]
547    if {$newexpfile == ""} return 
548    SetEXPfile $newexpfile 1
549    if {$expgui(expfile) == ""} {
550        set expgui(expfile) $prevexp
551        return
552    }
553    expwrite $newexpfile
554    # change the icon and assign an app to this .EXP file
555    if {$tcl_platform(os) == "Darwin" && $expgui(MacAssignApp)} {
556        MacSetResourceFork $expgui(expfile)
557    }
558    set expgui(changed) 0
559    set expgui(expModifiedLast) [file mtime $expgui(expfile)]
560    set expgui(last_History) [string range [string trim [lindex [exphistory last] 1]] 0 50 ]
561    # set the window/icon title
562    wm title . $expgui(expfile)
563    set expgui(titleunchanged) 1
564    wm iconname . [file tail $expgui(expfile)]
565    # set convergence criterion
566    InitLSvars
567    set expgui(needpowpref) 2
568    set expgui(needpowpref_why) "\tA new .EXP file was created\n" 
569}
570
571# called to read a different .EXP file
572proc readnewexp {} {
573    global expgui expmap
574    if $expgui(changed) {
575        set decision [tk_dialog .instrSaveData {Save .EXP changes} \
576                {You have made changes to the Experiment. Reading a different file without first saving will cause the changes to be lost. Select an option:} \
577                {} 0 "Save and read" "Read without Save" "Cancel read command"]
578        switch $decision {
579            0 { savearchiveexp }
580            1 {                }
581            2 { return }
582        }
583    }
584    set prevexp $expgui(expfile) 
585    set newexpfile [getExpFileName old]
586    if {$newexpfile == ""} return 
587    SetEXPfile $newexpfile
588    if {$expgui(expfile) == ""} {
589        set expgui(expfile) $prevexp
590        return
591    }
592
593    # switch to the 1st page
594    RaisePage lsFrame
595    set expgui(globalmode) 0
596    loadexp $expgui(expfile)
597
598    # reset the phase selection
599    set expgui(curPhase) {}
600
601    # select the first histogram in the list by default (if there are any)
602    if {[llength $expmap(histlistboxcontents)] > 0} {
603        set expgui(curhist) 0
604    } else {
605        set expgui(curhist) {}
606    }
607    if {[CountHistory] > 100} {
608        DeleteHistoryRecords "This .EXP file has [CountHistory] history records\nErasing most will speed EXPGUI"
609    }
610}
611
612#------------- set up data read/write layer ----------------------
613# trace routine on entryvar
614proc entvartrace {array elem action} {
615    global expgui entrycmd entryvar entrybox
616    if !$entrycmd(trace) return
617   
618    catch {
619        if {$entrycmd($elem) == ""} return
620        incr expgui(changed)
621        if $expgui(debug) {puts "$entrycmd($elem)  set $entryvar($elem) "}
622        if {$entrycmd($elem) == ""} return
623        if [catch {
624            set result [eval $entrycmd($elem) set [list $entryvar($elem)]]
625            if {!$result} {
626                if $expgui(debug) {puts "error with $entrycmd($elem)"}
627                catch {$entrybox($elem) config -fg red}
628            } else {
629                catch {$entrybox($elem) config -fg black}
630                RecordMacroEntry "incr expgui(changed); $entrycmd($elem) set [list $entryvar($elem)]" 1
631            }
632            if {[string match "*atominfo" [lindex $entrycmd($elem) 0]]} {
633                after idle "UpdateAtomLine \
634                        [list [lindex $entrycmd($elem) 2]] \
635                        [lindex $entrycmd($elem) 1]"
636            }
637        } errmsg] {error $errmsg}       
638    }
639}
640
641# disable traces on entryvar until we are ready
642set entrycmd(trace) 0
643trace variable entryvar w entvartrace
644
645#
646#
647#
648##############################################################################
649#####                    #####################################################
650##### PROCEDURES SECTION #####################################################
651#####                    #####################################################
652##############################################################################
653
654# save some of the global options in ~/.gsas_config or ~/gsas.config in Windows
655proc SaveOptions {} {
656    global expgui env tcl_platform graph peakinfo
657    if {$tcl_platform(platform) == "windows"} {
658        set fp [open c:/gsas.config a]
659    } else {
660        set fp [open [file join ~ .gsas_config] a]
661    }
662
663    puts $fp "# EXPGUI saved options from [clock format [clock seconds]]"
664    set itemlist {archive asorttype hsorttype filesort disaglSeparateBox \
665        font autoexpload autoiconify autotick execprompt ShowGENLES}
666    if {$tcl_platform(os) == "Darwin"} {
667        lappend itemlist MacAssignApp
668    }
669    if {$tcl_platform(platform) == "windows" && \
670            $tcl_platform(os) == "Windows 95"} {
671        lappend itemlist autoGRWND
672    }
673    foreach item $itemlist {
674        puts $fp "set expgui($item) [list $expgui($item)]"
675    }
676    if {$tcl_platform(platform) != "windows"} {
677        puts $fp "set env(GSASBACKSPACE) [list $env(GSASBACKSPACE)]"
678    }
679    foreach v {printout legend outname outcmd autoraise color_excl \
680            color_obs color_calc} {
681        puts $fp "set graph($v) [list $graph($v)]"
682    }
683    foreach v {obssym obssize exclsym exclsize} {
684        puts $fp "set peakinfo($v) [list $peakinfo($v)]"
685    }
686    close $fp
687}
688
689# save some of the global options in ~/.gsas_config or ~/gsas.config in Windows
690proc SavePosition {} {
691    global expgui env tcl_platform graph peakinfo
692    if {$tcl_platform(platform) == "windows"} {
693        set fp [open c:/gsas.config a]
694    } else {
695        set fp [open [file join ~ .gsas_config] a]
696    }
697
698    puts $fp "# EXPGUI saved screen position on [clock format [clock seconds]]"
699    puts $fp "set expgui(xpos) [expr {[winfo x .]*100./[winfo screenwidth .]}]"
700    puts $fp "set expgui(ypos) [expr {[winfo y .]*100./[winfo screenheight .]}]"
701    puts $fp "set expgui(poscenter) NW"
702    close $fp
703}
704
705proc About { } {
706    global expgui expmap
707    set version "Revision [lindex $expgui(Revision) 1] (readexp.tcl [lindex $expmap(Revision) 1])"
708    catch {
709        set version "[GetSVNVersion $::expgui(gsasdir)]\ntrack: $::expgui(SVNversion)"
710    }
711    tk_dialog .about {About...} \
712"EXPGUI\n\
713Brian Toby\n\
714APS, Argonne National Laboratory\n\n\
715Not subject to copyright\n\n\
716$version\n\n\
717Cite: B. H. Toby, EXPGUI, a graphical\n\
718user interface for GSAS, J. Appl. Cryst.\n\
71934, 210-21 (2001).
720\n\n\
721Generalized Structure Analysis System\n(GSAS)\n\
722R. B. Von Dreele,\n
723APS, Argonne National Laboratory\n
724and A. C. Larson, Los Alamos (retired)\n\n\
725" \
726        info 0 OK
727}
728proc Cite { } {
729    global expgui expmap
730    tk_dialog .about {Citations...} \
731"If you use EXPGUI, please cite\n\n\
732B.H. Toby, EXPGUI, a graphical\n\
733user interface for GSAS, J. Appl. Cryst.\n\
73434, 210-21 (2001).\n\n\
735as well as\n\n\
736A.C. Larson and R.B. Von Dreele,\n\
737\"General Structure Analysis System (GSAS)\",\n\
738Los Alamos National Laboratory Report\n\
739LAUR 86-748 (2004)." \
740        info 0 OK
741}
742
743# this proc is no longer called, but I am leaving it here as it may
744# be of use in the future
745proc MakeAppleScript {} {
746    global wishshell expgui
747    # create a local script directory, if it does not exist
748    if {![file exists ~/Library/Scripts]} {file mkdir  ~/Library/Scripts}
749    set tmpfile [file nativename ~/tmpscriptfile]
750    set startdir [tk_chooseDirectory -initialdir [pwd] -mustexist 1 \
751                      -title "Choose GSAS starting directory"]
752    if {$startdir == ""} {set startdir "~"}
753    set dir [file nativename  ~/Library/Scripts]
754    if {[set xterm [auto_execok xterm]] == ""} {
755        MyMessageBox -parent . -title "xterm not found " \
756            -message "The AppleScript could not be created because the X11 xterm application was not found. Please correct your path and try again." \
757            -icon "error" -type Sorry -default sorry
758#           -helplink "expguierr.html Customizewarning"
759        return
760    }
761    set file [tk_getSaveFile -initialdir $dir -initialfile EXPGUI.scpt \
762                      -title "Choose location to save script"]
763    set path {$PATH:}
764    append path [file dirname $xterm]
765    set fp [open $tmpfile w]
766    # the applescript starts here
767    puts $fp {on run}
768    puts $fp {  tell application "Finder"}
769    puts $fp {     launch application "X11"}
770    puts $fp {   end tell}
771    puts $fp "  set results to do shell script \"cd $startdir; DISPLAY=:0.0 PATH=$path $wishshell $expgui(script)  > /dev/null 2>&1 &\""
772    puts $fp {end run}
773    # drag & drop
774    puts $fp {on open these_files}
775    puts $fp {  tell application "Finder"}
776    puts $fp {     launch application "X11"}
777    puts $fp {   end tell}
778    puts $fp {  repeat with this_file in these_files}
779    puts $fp "  set results to do shell script \"cd $startdir; DISPLAY=:0.0 PATH=$path $wishshell $expgui(script) \" & the quoted form of the POSIX path of this_file & \" > /dev/null 2>&1 &\""
780    puts $fp {  end repeat}
781    puts $fp {end open}
782    close $fp
783    if {[catch {
784        exec osacompile -l AppleScript -o $file  $tmpfile
785        file delete -force $tmpfile
786        MyMessageBox -parent . -title "AppleScript created" \
787            -message "Script $file created & compiled. You may wish to use the Script Editor to save this as an application" \
788            -icon "info" -type OK -default ok \
789            -helplink "osx.html CompileAppleScript"
790    } errmsg]} {
791        MyMessageBox -parent . -title "AppleScript warning" \
792        -message "An error occurred while attempting to create the script. Please report this bug, including these details:\n$errmsg"\
793            -icon warning -type Ignore -default ignore
794#       -helplink "expguierr.html Customizewarning"
795    }
796}
797
798# this proc gets called when the export coordinate button is pressed
799# it loads export
800proc BuildCoordExpMenu {menu} {
801    global expgui_cmdlist expgui
802    # do this only once
803    $menu config -postcommand {}
804    $menu delete 1 end
805    # add the cif export routine
806    set cmd gsas2cif
807    set action {}
808    catch {set action [lindex $expgui_cmdlist($cmd) 0]}
809    if {$action != "" && $action != "-"} {
810        $menu add command -label $cmd -command [subst $action]
811    }
812    # get a list of files to read
813    set filelist [glob -nocomplain [file join $expgui(scriptdir) export_*.tcl]]
814    foreach file $filelist {
815        source $file
816        $menu add command -label $label -command $action
817    }
818}
819
820# utility export routines for the export_*.tcl files:
821# make a box for export
822proc MakeExportBox {win title webref} {
823    global expmap expgui
824    catch {destroy $win}
825    toplevel $win
826    wm title $win "Export coordinates"
827    if {$webref != ""} {
828        bind $win <Key-F1> $webref
829    }
830    pack [label $win.lbl -text $title] -side top -anchor center
831    pack [frame $win.ps] -side top -anchor w
832    pack [label $win.ps.lbl -text "Select phase: "] -side left
833    foreach num $expmap(phaselist) {
834        pack [button $win.ps.$num -text $num \
835                    -command "SetExportPhase $num $win"] -side left
836    }
837    # leave a place for format-specific items
838    pack [frame $win.special] -side top
839    pack [frame $win.but] -side top -fill x -expand yes
840    pack [button $win.but.1 -text Write -command "destroy $win"] -side left
841    SetExportPhase [lindex $expmap(phaselist) 0] $win
842    pack [button $win.but.2 -text Cancel \
843            -command "set expgui(export_phase) 0;destroy $win"] -side left
844    pack [button $win.but.help -text Help -bg yellow \
845            -command "MakeWWWHelp expgui.html ExportMSI"] \
846            -side right
847}
848
849# set the phase in response to the button
850proc SetExportPhase {num win} {
851    global expmap expgui
852    foreach n $expmap(phaselist) { 
853        if {$n == $num} { 
854            $win.ps.$n config -relief sunken; 
855            set expgui(export_phase) $num 
856        } else { 
857            $win.ps.$n config -relief raised
858        }
859    }
860}
861
862# wait until idle
863proc afterawhile {} {
864    # cancel any other instances of this loop
865    after cancel afterawhile
866    after cancel whenidle
867    after cancel whenidle
868    after idle whenidle
869}
870
871# This is called every 2 seconds to check for changes to the .EXP file
872proc whenidle {} {
873    global expgui tcl_platform
874    if $expgui(titleunchanged) {
875        if {$expgui(changed) != 0} {
876            wm title . "EXPGUI interface to GSAS: $expgui(expfile) (modified)"
877            set expgui(titleunchanged) 0
878        }
879    }
880    if {$expgui(expModifiedLast) == 0} {
881        after 2000 afterawhile
882        return
883    }
884    if {![file exists $expgui(expfile)]} {
885        after 2000 afterawhile
886        return
887    }
888    if {[file mtime $expgui(expfile)] != $expgui(expModifiedLast)} {
889        # we are "locked". Note that whenidle loop will be restarted later
890        if {$tcl_platform(platform) == "windows" && [file exists expgui.lck]} {
891            return
892        }
893        set ans [ReloadExpMsg [file tail $expgui(expfile)] $expgui(changed)]
894
895        if {$ans == 0} {
896            loadexp $expgui(expfile)
897        } elseif {$ans == 1} {
898            # reset the time to the next version
899            set expgui(expModifiedLast) [file mtime $expgui(expfile)]
900        } elseif {$ans == 2} {
901            SaveAsFile
902        }
903    }
904    after 2000 afterawhile
905}
906
907# place a message about changes over the main window
908proc ReloadExpMsg {file changes} {
909    global expgui tcl_platform
910    set msg "File $file has been modified by another program"
911    if {$changes == 1} {
912        append msg " and you have made a change to this version.\n"
913    } elseif {$changes > 0} {
914        append msg " and you have made $changes changes to this version.\n"
915    } else {
916        append msg ".\n"
917    }
918    append msg "Do you want to use the newer (modified) version or continue with the older (previous) version of the file?"
919
920    set w .ask
921    catch {destroy $w}
922    toplevel $w -class Dialog
923    wm title $w "Reload?"
924    wm iconname $w "Reload?"
925    wm protocol $w WM_DELETE_WINDOW { }
926    wm transient $w .
927    bind $w <Key-F1> "MakeWWWHelp expguierr.html Overwrite"
928    pack [button $w.help -text Help -bg yellow \
929            -command "MakeWWWHelp expguierr.html Overwrite"] \
930            -side top -anchor e
931    frame $w.bot
932    pack $w.bot -side bottom
933    frame $w.top -class FixedFont
934    pack $w.top -side top -fill both -expand 1
935    label $w.top.msg -justify left \
936            -wraplength 5i -font {Times 18} \
937            -text $msg 
938    if {$tcl_platform(platform) == "windows"} {
939        $w.top.msg config -font {Times 14}
940    }
941    pack $w.top.msg  -side right -expand 1 -fill both -padx 3m -pady 3m
942    pack [button $w.bot.1 -text "Load new" \
943            -default active -command "set expgui(dialogbutton) 0" \
944            ] -side left -expand 1 -padx 3m -pady 2m
945    pack [button $w.bot.2 -text "Continue with old" \
946            -command "set expgui(dialogbutton) 1"] \
947            -side left -expand 1 -padx 3m -pady 2m
948    if {$changes > 0} {
949        pack [button $w.bot.3 -text "Save edited version" \
950            -command "set expgui(dialogbutton) 2"] \
951            -side left -expand 1 -padx 3m -pady 2m
952    }
953    # Create a binding for <Return> on the dialog
954    bind $w <Return> "$w.bot.1 invoke"
955    wm withdraw $w
956    update idletasks
957
958    # compute widths with a catch, since this has been showing an error
959    # at least for one Mac user
960    set askwid 40
961    catch {set askwid [winfo reqwidth $w]}
962    set askhgt 80
963    catch {set askhgt [winfo reqheight $w]}
964    catch {
965        # for now, always center the message over the main window
966        # center the new window in the middle of the parent
967        set x [expr [winfo x .] + [winfo width .]/2 - \
968                $askwid/2 - [winfo vrootx .]]
969        set y [expr [winfo y .] + [winfo height .]/2 - \
970                $askhgt/2 - [winfo vrooty .]]
971        wm geom $w +$x+$y
972    }
973    wm deiconify $w
974
975    # Grab the focus
976    set oldFocus [focus]
977    set oldGrab [grab current $w]
978    if {[string compare $oldGrab ""]} {
979        set grabStatus [grab status $oldGrab]
980    }
981    catch {grab $w}
982    focus $w.bot.1
983    # for windows rearrange window stacking
984    # -- Removed since this will normally happen after the GSAS program
985    # has finished
986    #if {$tcl_platform(platform) == "windows"} {
987        #lower .
988        #raise $w .
989    #}
990    update idletasks
991
992    tkwait variable expgui(dialogbutton)
993    catch {focus $oldFocus}
994    destroy $w
995    if {[string compare $oldGrab ""]} {
996        if {![string compare $grabStatus "global"]} {
997            catch {grab -global $oldGrab}
998        } else {
999            catch {grab $oldGrab}
1000        }
1001    }
1002    # for windows rearrange window stacking
1003    #if {$tcl_platform(platform) == "windows"} {
1004        #raise .
1005    #}
1006    return $expgui(dialogbutton)
1007}
1008
1009# --------  called to confirm before exiting
1010proc catchQuit {} {
1011    if {[confirmBeforeSave] == "Continue"} {
1012        destroy .
1013    }
1014}
1015# save the .EXP file before exiting?
1016proc confirmBeforeSave {} {
1017    global expgui
1018    if !$expgui(changed) {
1019        return "Continue"
1020    }
1021    set decision [tk_dialog .instrSaveData {Save .EXP changes} \
1022            {You have made changes to the Experiment, but the changes are not saved. Select an option:} \
1023            {} 0 "Save and Exit" "Exit without Save" "Cancel exit command"]
1024    switch $decision {
1025        0 { savearchiveexp;  return "Continue" }
1026        1 {                  return "Continue" }
1027        2 {                  return "Cancel"   }
1028    }
1029}
1030
1031# setup buttons for each phase on the phase page
1032proc setphases {} {
1033    global expgui expmap
1034    eval destroy [winfo children $expgui(phaseFrame).top.ps]
1035    pack [label $expgui(phaseFrame).top.ps.0 -text Phase:] -side left
1036    foreach num $expmap(phaselist) {
1037        pack [button $expgui(phaseFrame).top.ps.$num -text $num \
1038                -command "SelectOnePhase $num" -padx 1.5m] -side left
1039    }
1040    if {[file executable $expgui(exptool)] && \
1041            [llength $expmap(phaselist)]} {
1042        pack [button $expgui(phaseFrame).top.ps.10 \
1043                -text "Replace" -command MakeReplacePhaseBox \
1044                ] -side left
1045    }
1046}
1047
1048# Procedure to respond to changes the phase.
1049#  This loads the "phases" widgets with data corresponding to the selected phase.
1050proc SelectOnePhase {num} {
1051    global entryvar entrycmd entrybox expmap expgui
1052    # if no phase has been selected, select the first one
1053    if {$num == ""} {set num [lindex $expmap(phaselist) 0]}
1054
1055    set crsPhase {}
1056    $expgui(atomxform) config -text "Xform Atoms" -state disabled
1057    foreach n $expmap(phaselist) type $expmap(phasetype) {
1058        if {$n == $num} {
1059            catch {$expgui(phaseFrame).top.ps.$num config -relief sunken}
1060            set crsPhase $num
1061            if {$type == 3} {
1062                set expgui(phasetype) "Magnetic\nOnly"
1063            } elseif {$type == 2} {
1064                set expgui(phasetype) "Magnetic\n& Nuclear"
1065            } elseif {$type == 4} {
1066                set expgui(phasetype) "Macromolecular"
1067            } elseif {$type == 10} {
1068                set expgui(phasetype) "Pawley"
1069            } else {
1070                set expgui(phasetype) ""
1071            }
1072        } else { 
1073            catch {$expgui(phaseFrame).top.ps.$n config -relief raised}
1074        }
1075    }
1076    # no phase is selected
1077    if {$crsPhase == "" || [llength $expmap(phaselist)] == 0} {
1078        # disable traces on entryvar
1079        set entrycmd(trace) 0
1080        set entrycmd(phasename) ""
1081        set entryvar(phasename) ""
1082        foreach ent {a b c alpha beta gamma} {
1083            set entryvar($ent) ""
1084        }
1085        foreach ent {cellref celldamp} {
1086            set entrycmd($ent) ""
1087            set entryvar($ent) ""
1088        }
1089        set expgui(curPhase) {}
1090        # enable traces on entryvar
1091        set entrycmd(trace) 1
1092        $expgui(EditingAtoms) config -text ""
1093        DisplayAtom 0 0
1094        DisplayU 0 0
1095        DisplayRefFlags 0 0
1096        $expgui(atomlistbox) delete 0 end
1097        return
1098    }
1099
1100    # don't reload the last displayed phase
1101    if {$expgui(curPhase) == $crsPhase} return
1102
1103    ##########################################################
1104    # load and display a phase
1105    ##########################################################
1106    # disable traces on entryvar while loading
1107    set entrycmd(trace) 0
1108    # phase title
1109    set entrycmd(phasename) "phaseinfo $crsPhase name"
1110    set entryvar(phasename) [phaseinfo $crsPhase name]
1111    # cell parameters & flags
1112    foreach ent {a b c alpha beta gamma} {
1113        set entryvar($ent) [phaseinfo $crsPhase $ent]
1114    }
1115    foreach ent {cellref celldamp} {
1116        set entrycmd($ent) "phaseinfo $crsPhase $ent"
1117        set entryvar($ent) [phaseinfo $crsPhase $ent]
1118    }
1119
1120    # initialize atoms display & disable
1121    DisplayAtom 0 0
1122    DisplayU 0 0
1123    DisplayRefFlags 0 0
1124    $expgui(EditingAtoms) config -text ""
1125
1126    DisplayAllAtoms $crsPhase
1127
1128    # enable traces on entryvar now
1129    set entrycmd(trace) 1
1130}
1131
1132set expgui(noreenterDisplayAllAtoms) 0
1133# Populate expgui(atomlistbox) (a ScrolledListBox) with atoms
1134# from the selected phase.
1135proc DisplayAllAtoms {curPhase "mode reset"} {
1136    global entryvar entrycmd expmap expgui
1137    # make sure that atomlistboxcontents element exists
1138    if {[catch {set expmap(atomlistboxcontents)}]} {
1139        set expmap(atomlistboxcontents) {}
1140    }
1141    # if it does not show, we don't have a phase or we are already displaying
1142    # don't bother
1143    if {$expgui(pagenow) != "phaseFrame"} return
1144    if {$curPhase == ""} return
1145    if $expgui(noreenterDisplayAllAtoms) return
1146    # prevent reentry
1147    set expgui(noreenterDisplayAllAtoms) 1
1148    # set the current phase
1149    set expgui(curPhase) $curPhase
1150    if {$mode != "reset"} {
1151        # save the scrolled position
1152        set pos [lindex [$expgui(atomlistbox) yview] 0]
1153    } else {
1154        # for reset, do not keep the previously selected atoms
1155        set expgui(selectedatomlist) {}
1156    }
1157    $expgui(atomlistbox) delete 0 end
1158    # displaying a macromolecular phase?
1159    if {[lindex $expmap(phasetype) [expr {$expgui(curPhase) - 1}]] == 4} {
1160        set mm 1
1161        $expgui(phaseFrame).top.ps.10 config -state disabled
1162        $expgui(AddAtomBut)  config -state disabled
1163        pleasewait "loading atoms..."
1164    } else {
1165        set mm 0
1166        if {[file executable $expgui(exptool)]} {
1167            $expgui(phaseFrame).top.ps.10 config -state normal
1168            $expgui(AddAtomBut) config -state normal
1169        }
1170    }
1171
1172    # prepare header info
1173    set maxline I
1174    set phase $expgui(curPhase)
1175    set atomlist {}
1176    set typehead "type  "
1177    set namehead "  name  "
1178    set multhead "Mult"
1179    set coordhead "   "
1180    if {$mm} {
1181        set cmd mmatominfo
1182        set frachead "Occ."
1183    } else {
1184        set cmd atominfo
1185        set frachead "Occupancy"
1186    }
1187    set reshead "res/grp/#"
1188    # sort the atoms, as requested
1189    if  {$expgui(asorttype) == "type"} {
1190        # sort on atom type
1191        set typehead "type* "
1192        foreach atom $expmap(atomlist_$phase) {
1193            lappend atomlist "$atom [$cmd $phase $atom type] $phase"
1194        }
1195        set expmap(atomlistboxcontents) [lsort -ascii -index 1 $atomlist]
1196    } elseif {$expgui(asorttype) == "number"} {
1197        # sort on atom number
1198        set namehead "* name  "
1199        foreach atom $expmap(atomlist_$phase) {
1200            lappend atomlist "$atom $atom $phase"
1201        }
1202        set expmap(atomlistboxcontents) [lsort -integer -index 1 $atomlist]
1203    } elseif {$expgui(asorttype) == "mult"} {
1204        if {$mm} {
1205            set reshead "res*/grp/#"
1206            foreach atom $expmap(atomlist_$phase) {
1207                lappend atomlist "$atom [mmatominfo $phase $atom residue] $phase"
1208            }
1209            set expmap(atomlistboxcontents) [lsort -ascii -index 1 $atomlist]
1210        } else {
1211            # sort on atom number
1212            set multhead "Mlt*"
1213            foreach atom $expmap(atomlist_$phase) {
1214                lappend atomlist "$atom [atominfo $phase $atom mult] $phase"
1215            }
1216            set expmap(atomlistboxcontents) [lsort -integer -decreasing -index 1 $atomlist]
1217        }
1218    } elseif {$expgui(asorttype) == "occupancy"} {
1219        # sort on atom number
1220        if {$mm} {
1221            set frachead "  Occ* "
1222        } else {
1223            set frachead "  Occup* "
1224        }
1225        foreach atom $expmap(atomlist_$phase) {
1226            lappend atomlist "$atom [$cmd $phase $atom frac] $phase"
1227        }
1228        set expmap(atomlistboxcontents) [lsort -real -decreasing -index 1 $atomlist]
1229    } elseif {$expgui(asorttype) == "x"} {
1230        # sort on x
1231        set coordhead "(x*)"
1232        foreach atom $expmap(atomlist_$phase) {
1233            lappend atomlist "$atom [$cmd $phase $atom x] $phase"
1234        }
1235        set expmap(atomlistboxcontents) [lsort -real -index 1 $atomlist]
1236    } elseif {$expgui(asorttype) == "y"} {
1237        # sort on y
1238        set coordhead "(y*)"
1239        foreach atom $expmap(atomlist_$phase) {
1240            lappend atomlist "$atom [$cmd $phase $atom y] $phase"
1241        }
1242        set expmap(atomlistboxcontents) [lsort -real -index 1 $atomlist]
1243    } elseif {$expgui(asorttype) == "z"} {
1244        # sort on z
1245        set coordhead "(z*)"
1246        foreach atom $expmap(atomlist_$phase) {
1247            lappend atomlist "$atom [$cmd $phase $atom z] $phase"
1248        }
1249        set expmap(atomlistboxcontents) [lsort -real -index 1 $atomlist]
1250    } else {
1251        error "Bad expgui(asorttype) = $expgui(asorttype)"
1252    }
1253
1254    set expgui(atomlistboxline) {}
1255    # loop over atoms
1256    foreach tuple $expmap(atomlistboxcontents) {
1257        set atom [lindex $tuple 0]
1258        set phase [lindex $tuple 2]
1259        lappend expgui(atomlistboxline) $atom
1260        $expgui(atomlistbox) insert end \
1261                [FormatAtomLine $atom $phase maxline]
1262    }
1263    $expgui(atomtitle) delete 0 end
1264
1265    # create the header
1266    if {$mm} {
1267        $expgui(atomtitle) insert end [format "%12s %9s  %6s %8s%29s %4s  %s" \
1268                $namehead $reshead $typehead "ref/damp  " \
1269                "fractional coordinates$coordhead" \
1270                "$frachead" \
1271                " Uiso"]
1272        donewait
1273    } elseif {$maxline == "A"} {
1274        $expgui(atomtitle) insert end [format "%10s %6s %8s%29s %9s  %s" \
1275                $namehead $typehead "ref/damp  " \
1276                "fractional coordinates$coordhead" \
1277                "$multhead $frachead" \
1278                " Uiso/Uij                                            "]
1279    } else {
1280        $expgui(atomtitle) insert end [format "%10s %6s %8s%29s %9s  %s" \
1281                $namehead $typehead "ref/damp  " \
1282                "fractional coordinates$coordhead" \
1283                "$multhead $frachead" \
1284                " Uiso"]
1285    }
1286    if {$mode != "reset"} {
1287        # restore the selected items
1288        foreach i $expgui(selectedatomlist) {
1289            $expgui(atomlistbox) selection set $i
1290        }
1291        # restore the last scrolled position
1292        $expgui(atomlistbox) yview moveto $pos
1293    }
1294    # clear the reentry flag
1295    set expgui(noreenterDisplayAllAtoms) 0
1296}
1297
1298proc FormatAtomLine {atom phase maxline_var} {
1299    global expmap
1300    if {[lindex $expmap(phasetype) [expr {$phase - 1}]] == 4} {
1301        foreach type {x u f} {
1302            if {[mmatominfo $phase $atom ${type}ref]} {
1303                append refflag "[string toupper $type][mmatominfo $phase $atom ${type}damp] "
1304            } else {
1305                append refflag " [mmatominfo $phase $atom ${type}damp] "
1306            }   
1307        }
1308        set line [format \
1309                "%5d %-6s %-3s%-2s%4d  %-6s %8s %9.5f%9.5f%9.5f%8.4f %7.4f" \
1310                $atom \
1311                [mmatominfo $phase $atom label] \
1312                [mmatominfo $phase $atom residue] \
1313                [mmatominfo $phase $atom group] \
1314                [mmatominfo $phase $atom resnum] \
1315                [mmatominfo $phase $atom type] \
1316                $refflag \
1317                [mmatominfo $phase $atom x] \
1318                [mmatominfo $phase $atom y] \
1319                [mmatominfo $phase $atom z] \
1320                [mmatominfo $phase $atom frac] \
1321                [mmatominfo $phase $atom Uiso] 
1322        ]
1323    } elseif {[atominfo $phase $atom temptype] == "A"} {
1324        foreach type {x u f} {
1325            if {[atominfo $phase $atom ${type}ref]} {
1326                append refflag "[string toupper $type][atominfo $phase $atom ${type}damp] "
1327            } else {
1328                append refflag " [atominfo $phase $atom ${type}damp] "
1329            }
1330        }
1331        # want to set maxline in parent
1332        upvar $maxline_var maxline
1333        set maxline A
1334        # aniso
1335        set line [format "%3d %-6s %-6s %8s %10.6f%10.6f%10.6f%4d%9.4f" \
1336                $atom \
1337                [atominfo $phase $atom label] \
1338                [atominfo $phase $atom type] \
1339                $refflag \
1340                [atominfo $phase $atom x] \
1341                [atominfo $phase $atom y] \
1342                [atominfo $phase $atom z] \
1343                [atominfo $phase $atom mult] \
1344                [atominfo $phase $atom frac] 
1345        ]
1346        append line [format "  %9.5f%9.5f%9.5f%9.5f%9.5f%9.5f" \
1347                [atominfo $phase $atom U11] \
1348                [atominfo $phase $atom U22] \
1349                [atominfo $phase $atom U33] \
1350                [atominfo $phase $atom U12] \
1351                [atominfo $phase $atom U23] \
1352                [atominfo $phase $atom U13] 
1353        ]
1354    } else {
1355        foreach type {x u f} {
1356            if {[atominfo $phase $atom ${type}ref]} {
1357                append refflag "[string toupper $type][atominfo $phase $atom ${type}damp] "
1358            } else {
1359                append refflag " [atominfo $phase $atom ${type}damp] "
1360            }   
1361        }
1362        set line [format \
1363                "%3d %-6s %-6s %8s %10.6f%10.6f%10.6f%4d%9.4f  %9.5f" \
1364                $atom \
1365                [atominfo $phase $atom label] \
1366                [atominfo $phase $atom type] \
1367                $refflag \
1368                [atominfo $phase $atom x] \
1369                [atominfo $phase $atom y] \
1370                [atominfo $phase $atom z] \
1371                [atominfo $phase $atom mult] \
1372                [atominfo $phase $atom frac] \
1373                [atominfo $phase $atom Uiso] 
1374        ]
1375    }
1376    return $line
1377}
1378
1379# update the display of atom as they are changed
1380proc UpdateAtomLine {atomlist phase} {
1381    global expgui
1382    # for lots of atoms, it is faster to repaint the listbox
1383    if {[llength $atomlist] > 25} {
1384        DisplayAllAtoms $expgui(curPhase) noreset
1385        return
1386    }
1387    foreach atom $atomlist {
1388        set linenum [lsearch -exact $expgui(atomlistboxline) $atom]
1389        $expgui(atomlistbox) delete $linenum
1390        $expgui(atomlistbox) insert $linenum \
1391                [FormatAtomLine $atom $phase maxline]
1392    }
1393    # restore the selected items
1394    foreach i $expgui(selectedatomlist) {
1395        $expgui(atomlistbox) selection set $i
1396    }
1397}
1398
1399# Procedure to select all atoms in response to a right-click
1400proc SelectAllAtoms {} {
1401    global expgui
1402    $expgui(atomlistbox) selection set 0 end
1403    # call editRecord in case trace was called before the selection was made
1404    editRecord
1405}
1406
1407# Procedure to respond to left mouse release in the atoms Pane
1408proc editRecord { args } {
1409    global entrycmd expgui
1410    set expgui(selectedatomlist) [$expgui(atomlistbox) curselection]
1411    # disable traces on entryvar for right now
1412    set entrycmd(trace) 0
1413
1414    if {[llength $expgui(selectedatomlist)] == 0} {
1415        if $expgui(debug) {error "Attempt display non-existent atoms"}
1416    } elseif {[llength $expgui(selectedatomlist)] == 1} {
1417        editOneRecord $expgui(selectedatomlist)
1418    } else {
1419        editMultipleRecords $expgui(selectedatomlist)
1420    }
1421    # reenable traces on entryvar
1422    set entrycmd(trace) 1
1423    # repaint the atoms box in case anything was changed
1424    #    DisplayAllAtoms noreset
1425}
1426
1427proc editOneRecord { AtomIndex } {
1428    global expmap expgui
1429    # make sure that atomlistboxcontents element exists
1430    if {[catch {set expmap(atomlistboxcontents)}]} return
1431
1432    # get atom number & phase
1433    set tuple [lindex $expmap(atomlistboxcontents) $AtomIndex]
1434    set atomnum [lindex $tuple 0]
1435    set p [lindex $tuple 2]
1436    DisplayU $atomnum $p
1437    DisplayAtom $atomnum $p
1438    DisplayRefFlags $atomnum $p
1439    $expgui(EditingAtoms) config -text "Editing atom #$atomnum -- [atominfo $p $atomnum label]"
1440    $expgui(atomxform) config -text "Xform Atom" -state normal
1441}
1442
1443# this will not work for a multi-phase list of atoms (yet)
1444proc editMultipleRecords { AtomIndexList } {
1445    global expmap expgui
1446    # make sure that atomlistboxcontents element exists
1447    if {[catch {set expmap(atomlistboxcontents)}]} return
1448
1449    set numberList {}
1450    # current phase
1451    set p $expgui(curPhase)
1452    foreach AtomIndex $AtomIndexList {
1453        # get atom number & phase
1454        set tuple [lindex $expmap(atomlistboxcontents) $AtomIndex]
1455        lappend numberList [lindex $tuple 0]
1456#       set p [lindex $tuple 2]
1457    }
1458    # this needs to track by phase
1459    $expgui(EditingAtoms) config -text \
1460            "Set refinement options: atoms [CompressList $numberList]"
1461    DisplayU 0 0
1462    DisplayAtom 0 0
1463    # this needs to track by phase
1464    DisplayRefFlags $numberList $p
1465    $expgui(atomxform) config -text "Xform Atoms" -state normal
1466}
1467
1468# format a string of numbers to save space, e.g. "1 2 3 4 6 7 19 13 14 15"
1469# becomes "1-4,6,7,13-15,19"
1470proc CompressList {numberList "max 9999"} {
1471    # format the number list to save space
1472    set lastnum -99
1473    set flist {}
1474    set count 0
1475    set length 0
1476    if [catch {set sortlist [lsort -integer $numberList]}] {return $numberList}
1477    foreach num $sortlist {
1478        set next [expr $lastnum+1]
1479        if {$num != $next} {
1480            if {$count == 0 && $flist != ""} {
1481                if {[string length $flist] - $length > $max} {
1482                    set length [string length $flist]
1483                    append flist ",\n$num"
1484                } else {
1485                    append flist ",$num"
1486                }
1487            } elseif {$count == 1 && $flist != ""} {
1488                if {[string length $flist] - $length > $max} {
1489                    set length [string length $flist]
1490                    append flist ",$lastnum,\n$num"
1491                } else {
1492                    append flist ",$lastnum,$num"
1493                }
1494            } elseif {$flist != ""} {
1495                if {[string length $flist] - $length > $max} {
1496                    set length [string length $flist]
1497                    append flist "-$lastnum,\n$num"
1498                } else {
1499                    append flist "-$lastnum,$num"
1500                }
1501            } else {
1502                append flist "$num"
1503            }
1504            set lastnum $num
1505            set count 0
1506        } else {
1507            incr count
1508            incr lastnum
1509        }
1510    }
1511    if {$count == 1 && $flist != ""} {
1512        append flist ",$lastnum"
1513    } elseif {$flist != "" && $count > 1} {
1514        append flist "-$lastnum"
1515    }
1516    return $flist
1517}
1518
1519# Procedure to display Isotropic or Anisotropic temperature factors
1520#  Changes the display to one entry widget for Isotropic motion OR
1521#   6 entry widgets for Anisotropic motion in Frame3.
1522#   or disables the widet entirly if atom = 0
1523proc DisplayU { atomnum p} {
1524    global expgui entryvar entrycmd expmap
1525    set mm 0
1526    if {$atomnum == 0} {
1527        set iOrA disable
1528    } elseif {[lindex $expmap(phasetype) 0] == 4} {
1529        set mm 1
1530        set iOrA I
1531    } else {
1532        set iOrA [atominfo $p $atomnum temptype]
1533    }
1534
1535    set firstbox [lindex $expgui(anisolabels) 0]
1536    if { $iOrA == "A" } {
1537        $firstbox config -text "U11 "
1538        foreach item $expgui(anisolabels) {
1539            $item config -fg black
1540        }
1541        foreach item $expgui(anisoentry) var {U11 U22 U33 U12 U13 U23} {
1542            set entrycmd($var) "atominfo $p $atomnum $var"
1543            set entryvar($var) [eval $entrycmd($var)]
1544            $item config -fg black -state normal  -bg white
1545        }
1546    } elseif { $iOrA == "I" || $iOrA == "disable"} {
1547        foreach item $expgui(anisolabels) {
1548            $item config -fg $expgui(bkgcolor1)
1549        }
1550        foreach item [lrange $expgui(anisoentry) 1 end] \
1551                var {U22 U33 U12 U13 U23} {
1552            set entrycmd($var) ""
1553            set entryvar($var) ""
1554            $item config -fg $expgui(bkgcolor1) -bg $expgui(bkgcolor1) \
1555                    -state disabled
1556        }
1557        if { $iOrA == "disable"} {
1558            set entrycmd($var) ""
1559            set entryvar($var) ""
1560            [lindex $expgui(anisoentry) 0] config \
1561                    -fg $expgui(bkgcolor1) -bg $expgui(bkgcolor1) \
1562                    -state disabled
1563        } elseif {$mm} {
1564            set entrycmd(U11) "mmatominfo $p $atomnum Uiso"
1565            set entryvar(U11) [eval $entrycmd(U11)]
1566            $firstbox config -text Uiso -fg black
1567            [lindex $expgui(anisoentry) 0] config -fg black -bg white -state normal
1568        } else {
1569            set entrycmd(U11) "atominfo $p $atomnum Uiso"
1570            set entryvar(U11) [eval $entrycmd(U11)]
1571            $firstbox config -text Uiso -fg black
1572            [lindex $expgui(anisoentry) 0] config -fg black -bg white -state normal
1573        }
1574    }
1575}
1576
1577# need to think about multiple phases
1578
1579# Procedure to display refinement flags
1580proc DisplayRefFlags { atomnum p} {
1581    global expgui entryvar entrycmd expmap
1582    if {$atomnum == 0} {
1583        foreach label $expgui(atomreflbl) {
1584            $label config -fg $expgui(bkgcolor1)
1585        }
1586        foreach entry $expgui(atomref) {
1587            $entry config -state disabled \
1588                    -fg $expgui(bkgcolor1) -bg $expgui(bkgcolor1)
1589            # turn off checkbuttons
1590            catch {$entry deselect}
1591
1592        }
1593        return
1594    }
1595    foreach label $expgui(atomreflbl) {
1596        $label config -fg black
1597    }
1598    foreach entry $expgui(atomref) {
1599        $entry config -state normal -fg black -bg $expgui(bkgcolor1)
1600    }
1601    if {[lindex $expmap(phasetype) 0] == 4} {
1602        foreach var {xref uref fref xdamp udamp fdamp}  {
1603            set entrycmd($var) "mmatominfo $p [list $atomnum] $var"
1604            set entryvar($var) [eval $entrycmd($var)]
1605        }
1606    } else {
1607        foreach var {xref uref fref xdamp udamp fdamp}  {
1608            set entrycmd($var) "atominfo $p [list $atomnum] $var"
1609            set entryvar($var) [eval $entrycmd($var)]
1610        }
1611    }
1612}
1613
1614# Procedure to display an atom in the atom edit boxes
1615proc DisplayAtom { atomnum p} {
1616    global expgui entryvar entrycmd expmap
1617    if {$atomnum == 0} {
1618        foreach label $expgui(atomlabels) {
1619            $label config -fg $expgui(bkgcolor1)
1620        }
1621        foreach entry $expgui(atomentry) {
1622            $entry config -state disabled \
1623                    -fg $expgui(bkgcolor1) -bg $expgui(bkgcolor1)
1624        }
1625        return
1626    }
1627    foreach label $expgui(atomlabels) {
1628        $label config -fg black
1629    }
1630    foreach entry $expgui(atomentry) {
1631        $entry config -state normal -fg black -bg white
1632    }
1633    if {[lindex $expmap(phasetype) 0] == 4} {
1634        foreach var {x y z label frac } {
1635            set entrycmd($var) "mmatominfo $p $atomnum $var"
1636            set entryvar($var) [eval $entrycmd($var)]
1637        }
1638    } else {
1639        foreach var {x y z label frac } {
1640            set entrycmd($var) "atominfo $p $atomnum $var"
1641            set entryvar($var) [eval $entrycmd($var)]
1642        }
1643    }
1644}
1645
1646# make a histogram box; used in MakeHistPane,
1647proc MakeHistBox {frm} {
1648    global expgui
1649    grid [label $frm.mode -text "Select a Histogram" \
1650            -bg beige -anchor center -bd 2 -relief raised] \
1651            -row 0 -column 0 -columnspan 2 -sticky ew
1652    bind $frm.mode <Button-1> {
1653        set i [lsearch $expgui(AllowedHistSelectModes) $expgui(globalmode)]
1654        set expgui(globalmode) [lindex \
1655                "$expgui(AllowedHistSelectModes) \
1656                $expgui(AllowedHistSelectModes)" [incr i]]
1657        sethistlist
1658    }
1659    bind $frm.mode <Button-3> {set expgui(globalmode) 0; sethistlist}
1660    grid [listbox $frm.title -height 1 -relief flat \
1661            -exportselection 0 ] -row 1 -column 0 -sticky ew
1662    grid [listbox $frm.lbox -height 10 -width 25 \
1663            -exportselection 0 \
1664            -xscrollcommand "$frm.x set" \
1665            -yscrollcommand "$frm.y set" \
1666            ] -row 2 -column 0 -sticky news
1667    lappend expgui(HistSelectList) $frm
1668    grid [scrollbar $frm.x -orient horizontal \
1669            -command "move2boxesX \" $frm.title $frm.lbox \" " 
1670    ] -row 3 -column 0 -sticky ew
1671    grid [scrollbar $frm.y \
1672            -command "$frm.lbox yview"] \
1673            -row 2 -column 1 -sticky ns
1674    grid columnconfigure $frm 0 -weight 1
1675    grid rowconfigure $frm 2 -weight 1
1676}
1677
1678# update the histogram list
1679# to do: show histogram ref flags?
1680proc sethistlist {} {
1681    global expgui expmap
1682    array set lbl {
1683        1 "Select 1 or more\nTOF Histograms"
1684        2 "Select 1 or more\nCW Neutron Histograms"
1685        3 "Select 1 or more\nAlpha 1,2 X-ray Histograms"
1686        4 "Select 1 or more\nmonochromatic X-ray Histograms"
1687        5 "Select 1 or more Energy\nDispersive X-ray Histograms"
1688        6 "Select 1 or more of\n any type Histograms"
1689    }
1690    foreach lbox $expgui(HistSelectList) {
1691        $lbox.title delete 0 end
1692        $lbox.lbox delete 0 end
1693        if {$expgui(globalmode) != 0} {
1694            $lbox.lbox config -selectmode extended
1695            $lbox.mode config -text $lbl($expgui(globalmode)) -bg yellow
1696        } else {
1697            $lbox.lbox config -selectmode browse
1698            $lbox.mode config -text "Select a histogram" -bg beige
1699        }
1700    }
1701    StageTabUse
1702    # # disable the unallowed pages in all mode
1703    # if {$expgui(globalmode) == 6} {
1704    #   foreach pair $expgui(GlobalModeAllDisable) {
1705    #       if {$expgui(pagenow) == [lindex $pair 0]} {
1706    #           RaisePage lsFrame
1707    #       }
1708    #       eval [lindex $pair 1] -state disabled
1709    #   }
1710    # } else {
1711    #   foreach pair $expgui(GlobalModeAllDisable) {
1712    #       eval [lindex $pair 1] -state normal
1713    #   }
1714    # }
1715    set histlist {}
1716    if  {$expgui(hsorttype) == "type"} {
1717        # sort on histogram type
1718        foreach h [lsort -integer -increasing $expmap(powderlist)] {
1719            lappend histlist "$h [string range $expmap(htype_$h) 1 2]"
1720        }
1721        set expmap(histlistboxcontents) [lsort -ascii -index 1 $histlist]
1722    } elseif {$expgui(hsorttype) == "number"} {
1723        # sort on histogram number
1724        foreach h [lsort -integer -increasing $expmap(powderlist)] {
1725            lappend histlist "$h $h"
1726        }
1727        set expmap(histlistboxcontents) [lsort -integer -index 1 $histlist]
1728    } elseif {$expgui(hsorttype) == "bank"} {
1729        # sort on original bank number
1730        foreach h [lsort -integer -increasing $expmap(powderlist)] {
1731            lappend histlist "$h [histinfo $h bank]"
1732        }
1733        set expmap(histlistboxcontents) [lsort -integer -index 1 $histlist]
1734    } elseif {$expgui(hsorttype) == "angle"} {
1735        # sort on wavelength (CW) or angle (E disp.)
1736        foreach h [lsort -integer -increasing $expmap(powderlist)] {
1737            if {[string range $expmap(htype_$h) 2 2] == "T"} {
1738                set det [format %8.2f [histinfo $h tofangle]]
1739            } elseif {[string range $expmap(htype_$h) 2 2] == "C"} {
1740                set det [format %8.5f [histinfo $h lam1]]
1741            } elseif {[string range $expmap(htype_$h) 2 2] == "E"} {
1742                set det [format %8.2f [histinfo $h lam1]]
1743            } else {
1744                set det {}
1745            }
1746            lappend histlist "$h $det"
1747        }
1748        set expmap(histlistboxcontents) [lsort -real -index 1 $histlist]
1749    }
1750
1751    # title field needs to match longest title
1752    foreach lbox $expgui(HistSelectList) {
1753        $lbox.title insert end [format "%2s %s %4s %8s  %-67s" \
1754                "h#" \
1755                type \
1756                bank \
1757                "ang/wave" \
1758                "    title" \
1759                ]
1760    }
1761    foreach tuple $expmap(histlistboxcontents) {
1762        set h [lindex $tuple 0]
1763
1764        if {$expgui(globalmode) == 1} {
1765            if {[string range $expmap(htype_$h) 2 2] != "T"} continue
1766        } elseif {$expgui(globalmode) == 2} {
1767            if {[string range $expmap(htype_$h) 1 2] != "NC"} continue
1768        } elseif {$expgui(globalmode) == 3} {
1769            if {[string range $expmap(htype_$h) 1 2] != "XC" || \
1770                    [histinfo $h lam2] == 0.0} continue
1771        } elseif {$expgui(globalmode) == 4} {
1772            if {[string range $expmap(htype_$h) 1 2] != "XC" || \
1773                    [histinfo $h lam2] != 0.0} continue
1774        } elseif {$expgui(globalmode) == 5} {
1775            if {[string range $expmap(htype_$h) 1 2] != "XE"} continue
1776        }
1777
1778        if {[string range $expmap(htype_$h) 2 2] == "T"} {
1779            set det [format %8.2f [histinfo $h tofangle]]
1780        } elseif {[string range $expmap(htype_$h) 2 2] == "C"} {
1781            set det [format %8.5f [histinfo $h lam1]]
1782        } elseif {[string range $expmap(htype_$h) 2 2] == "E"} {
1783            set det [format %8.2f [histinfo $h lam1]]
1784        } else {
1785            set det {}
1786        }
1787        foreach lbox $expgui(HistSelectList) {
1788            $lbox.lbox insert end [format "%2d  %s %4d %8s  %-67s" \
1789                    $h \
1790                    [string range $expmap(htype_$h) 1 3] \
1791                    [histinfo $h bank] \
1792                    $det \
1793                    [string range [histinfo $h title] 0 66] \
1794                    ]
1795        }
1796    }
1797    UpdateCurrentPage
1798}
1799
1800proc UpdateCurrentPage {} {
1801    global expgui
1802    foreach set $expgui(frameactionlist) {
1803        if {$expgui(pagenow) == [lindex $set 0]} {catch [lindex $set 1]}
1804    }
1805}
1806
1807#-----------------------------------------------------------------------
1808# ----------- draw Histogram page
1809#-----------------------------------------------------------------------
1810proc DisplayHistogram {} {
1811    global expgui entrycmd entryvar entrybox expmap
1812
1813    # trap if more than one histogram is selected unless global mode
1814    if {$expgui(globalmode) == 0 && [llength $expgui(curhist)] > 1} {
1815        set expgui(curhist) [lindex $expgui(curhist) 0] 
1816    }
1817
1818    # disable the add histogram button if no phases are present
1819    catch {
1820        foreach c [winfo children $expgui(histFrame).bb] {
1821            if {[llength $expmap(phaselist)] == 0} {
1822                $c configure -state disabled
1823            } else {
1824                $c configure -state normal
1825            } 
1826        }
1827    }
1828
1829    # display the selected histograms
1830    $expgui(histFrame).hs.lbox selection clear 0 end
1831    foreach h $expgui(curhist) {
1832        $expgui(histFrame).hs.lbox selection set $h
1833    }
1834
1835    # disable traces on entryvar for right now
1836    set entrycmd(trace) 0
1837
1838    # get histogram list
1839    set histlist {}
1840    foreach item $expgui(curhist) {
1841        lappend histlist [lindex $expmap(powderlist) $item]
1842    }
1843    # must have at least one histogram selected here
1844    if {[llength $histlist] == 0} {
1845        set expgui(backtermlbl) ""
1846        set expgui(backtypelbl) ""
1847        foreach var {bref bdamp absref absdamp} {
1848            set entrycmd($var) ""
1849            set entryvar($var) ""
1850        }
1851        $expgui(histFrame).top.txt config -text "No Selected Histograms"
1852        grid $expgui(histFrame).top -column 1 -row 0 -sticky nsew       
1853        set expgui(bkglbl) ""
1854        set expgui(abslbl) ""
1855        eval destroy [winfo children $expgui(diffBox)]
1856        set entrycmd(trace) 1
1857        return
1858    }
1859
1860    if {$expgui(globalmode) != 0} {
1861        set expgui(backtermlbl) ""
1862        set expgui(backtypelbl) ""
1863        foreach var {bref bdamp absref absdamp} {
1864            set entrycmd($var) "histinfo [list $histlist] $var"
1865            set entryvar($var) [histinfo [lindex $histlist 0] $var]
1866        }
1867    } else {
1868        set hist $histlist
1869        set terms [histinfo $hist backterms]
1870        set expgui(backtermlbl) "($terms terms)"
1871        # background type 3 & 9 have gone away
1872        if {[histinfo $hist backtype] == 3 || [histinfo $hist backtype] == 9} {
1873            MyMessageBox -parent . -title "Background Change" \
1874                -type ok -default ok \
1875                -icon warning \
1876                -message "Background function #[histinfo $hist backtype] is no longer supported -- the function will now be changed to type #1 & the values reset"
1877            histinfo $histlist backtype set 1
1878            RecordMacroEntry "histinfo [list $histlist] backtype set 1" 0
1879            incr expgui(changed)
1880            for {set num 1 } { $num <= $terms } { incr num } {
1881                set var "bterm$num"
1882                histinfo $histlist $var set 0
1883                RecordMacroEntry "histinfo [list $histlist] $var set 0" 0
1884                incr expgui(changed)
1885            }
1886            RecordMacroEntry "incr expgui(changed)" 0
1887        }
1888        set expgui(backtypelbl) "Function type [histinfo $hist backtype]"
1889        foreach var {bref bdamp absref absdamp} {
1890            set entrycmd($var) "histinfo $hist $var"
1891            set entryvar($var) [eval $entrycmd($var)]
1892        }
1893    }
1894    # Top box
1895    catch {destroy $expgui(histFrame).pflag}
1896    if {$expgui(globalmode) != 0} {
1897        $expgui(histFrame).top.txt config \
1898                -text "Selected Histograms: [CompressList $histlist]"
1899        grid $expgui(histFrame).top -column 1 -row 0 -sticky nsew       
1900        set expgui(bkglbl) "Globally Edit Background"
1901        set expgui(abslbl) "Globally Edit Absorption"
1902    } else {
1903        grid forget $expgui(histFrame).top
1904        set expgui(bkglbl) "Edit Background"
1905        set expgui(abslbl) "Edit Abs./Refl."
1906        if {[llength $expmap(phaselist)] > 1} {
1907            TitleFrame $expgui(histFrame).pflag  \
1908                    -borderwidth 4 -side left -relief groove \
1909                    -text "Phase Flags"
1910            set expgui(pflag) [$expgui(histFrame).pflag getframe]
1911            grid $expgui(histFrame).pflag -column 1 -row 1 -sticky nsew
1912            grid rowconfigure $expgui(histFrame) 2 -minsize 35
1913            foreach p $expmap(phaselist) {
1914                pack [checkbutton $expgui(pflag).$p \
1915                        -command "GetPhaseFlags $hist" \
1916                        -variable expgui(pflag$p) -text $p] -side left
1917                if {[lsearch $expmap(phaselist_$hist) $p] == -1} {
1918                    set expgui(pflag$p) 0
1919                } else {
1920                    set expgui(pflag$p) 1
1921                }
1922            }
1923        }
1924    }
1925
1926    # diffractometer constants
1927    foreach var {lam1 lam2 kratio pola ipola ddamp zero \
1928            wref pref dcref daref ratref ttref zref } {
1929        set entrycmd($var) "histinfo [list $histlist] $var"
1930        set entryvar($var) [histinfo [lindex $histlist 0] $var]
1931    }
1932
1933    eval destroy [winfo children $expgui(diffBox)]
1934    if {$expgui(globalmode) == 0} {
1935        if {[string range $expmap(htype_$hist) 2 2] == "T"} {
1936        #------
1937        # TOF |
1938        #------
1939            grid [ label $expgui(diffBox).lDCrc -text "Refine DIFC" ] \
1940                    -column 1 -row 1
1941            grid [ checkbutton $expgui(diffBox).rfDCrc -variable entryvar(dcref) ] \
1942                    -column 2 -row 1
1943            grid [ label $expgui(diffBox).lDCdifc -text DIFC ] \
1944                    -column 3 -row 1 -sticky w
1945            grid [ entry $expgui(diffBox).eDCdifc -textvariable entryvar(lam1) \
1946                    -width 15 ] -column 4 -row 1
1947            set entrybox(lam1) $expgui(diffBox).eDCdifc
1948            #
1949            grid [ label $expgui(diffBox).lDCra -text "Refine DIFA" ] \
1950                    -column 1 -row 2
1951            grid [ checkbutton $expgui(diffBox).rfDCra -variable entryvar(daref) ] \
1952                    -column 2 -row 2
1953            grid [ label $expgui(diffBox).lDCdifa -text DIFA ] \
1954                    -column 3 -row 2
1955            grid [ entry $expgui(diffBox).eDCdifa -textvariable entryvar(lam2) \
1956                    -width 15 ] -column 4 -row 2
1957            set entrybox(lam2) $expgui(diffBox).eDCdifa
1958            #
1959            grid [ label $expgui(diffBox).lDCzero -text "Zero"] \
1960                    -column 3 -row 3
1961            grid [ entry $expgui(diffBox).eDCzero -textvariable entryvar(zero) \
1962                    -width 15 ] -column 4 -row 3
1963            set entrybox(zero) $expgui(diffBox).eDCzero
1964            grid [ label $expgui(diffBox).lDCzref -text "Refine zero" ] \
1965                    -column 1 -row 3 -sticky w
1966            grid [ checkbutton $expgui(diffBox).rfDCzref \
1967                    -variable entryvar(zref) ] -column 2 -row 3
1968        } elseif {[string range $expmap(htype_$hist) 1 2] == "NC"} { 
1969        #---------------
1970        # CW - neutron |
1971        #---------------
1972            grid [ label $expgui(diffBox).lDC1 -text "Refine wave" ] \
1973                    -column 1 -row 1
1974            grid [ checkbutton $expgui(diffBox).rfDC1 -variable entryvar(wref) ] \
1975                    -column 2 -row 1
1976            grid [ label $expgui(diffBox).lDCdifc -text wave ] \
1977                    -column 3 -row 1 -sticky w
1978            grid [ entry $expgui(diffBox).eDCdifc -textvariable entryvar(lam1) \
1979                    -width 15 ] -column 4 -row 1
1980            set entrybox(lam1) $expgui(diffBox).eDCdifc
1981            #
1982            grid [ label $expgui(diffBox).lDCzref -text "Refine zero" ] \
1983                    -column 1 -row 3 -sticky w
1984            grid [ checkbutton $expgui(diffBox).rfDCzref \
1985                    -variable entryvar(zref) ] -column 2 -row 3
1986            grid [ label $expgui(diffBox).lDCzero -text "Zero"] \
1987                    -column 3 -row 3
1988            grid [ entry $expgui(diffBox).eDCzero -textvariable entryvar(zero) \
1989                    -width 15 ] -column 4 -row 3
1990            set entrybox(zero) $expgui(diffBox).eDCzero
1991        } elseif {[string range $expmap(htype_$hist) 1 2] == "XC" && \
1992                [histinfo $hist lam2] == 0.0} {
1993        #--------------------------
1994        # CW - x-ray 1 wavelength |
1995        #--------------------------
1996            grid [ label $expgui(diffBox).lDC1 -text "Refine wave" ] \
1997                    -column 1 -row 1
1998            grid [ checkbutton $expgui(diffBox).rfDC1 -variable entryvar(wref) ] \
1999                    -column 2 -row 1
2000            grid [ label $expgui(diffBox).lDCdifc -text wave ] \
2001                    -column 3 -row 1 -sticky w
2002            grid [ entry $expgui(diffBox).eDCdifc -textvariable entryvar(lam1) \
2003                    -width 15 ] -column 4 -row 1
2004            set entrybox(lam1) $expgui(diffBox).eDCdifc
2005            #
2006            grid [ label $expgui(diffBox).lDCzref -text "Refine zero" ] \
2007                    -column 1 -row 3 -sticky w
2008            grid [ checkbutton $expgui(diffBox).rfDCzref \
2009                    -variable entryvar(zref) ] -column 2 -row 3
2010            grid [ label $expgui(diffBox).lDCzero -text "Zero"] \
2011                    -column 3 -row 3
2012            grid [ entry $expgui(diffBox).eDCzero -textvariable entryvar(zero) \
2013                    -width 15 ] -column 4 -row 3
2014            set entrybox(zero) $expgui(diffBox).eDCzero
2015            #
2016            grid [ label $expgui(diffBox).lDCpref -text "Refine POLA" ] \
2017                    -column 1 -row 4 -sticky w
2018            grid [ checkbutton $expgui(diffBox).rfDCpref \
2019                    -variable entryvar(pref) ] -column 2 -row 4
2020            grid [ label $expgui(diffBox).lDCpola -text POLA ] \
2021                    -column 3 -row 4
2022            grid [ entry $expgui(diffBox).eDCpola \
2023                    -textvariable entryvar(pola) -width 15 ] -column 4 -row 4
2024            set entrybox(pola) $expgui(diffBox).eDCpola
2025            grid [ label $expgui(diffBox).lDCipola -text "IPOLA" ] \
2026                    -column 5 -row 4
2027            grid [ entry $expgui(diffBox).eDCipola -width 2 \
2028                    -textvariable entryvar(ipola)] -column 6 -row 4
2029            set entrybox(ipola) $expgui(diffBox).eDCipola
2030        } elseif {[string range $expmap(htype_$hist) 1 2] == "XC"} {
2031        #---------------------------
2032        # CW - x-ray 2 wavelengths |
2033        #---------------------------
2034            grid [ label $expgui(diffBox).lDCdifc -text wavelengths ] \
2035                    -column 3 -row 1 -sticky w
2036            grid [ entry $expgui(diffBox).eDCdifc -textvariable entryvar(lam1) \
2037                    -width 15 ] -column 4 -row 1
2038            set entrybox(lam1) $expgui(diffBox).eDCdifc
2039            grid [ entry $expgui(diffBox).eDCdifa -textvariable entryvar(lam2) \
2040                    -width 15 ] -column 5 -row 1
2041            set entrybox(lam2) $expgui(diffBox).eDCdifa
2042            #
2043            grid [ label $expgui(diffBox).lDCrref -text "Refine ratio" ] \
2044                    -column 1 -row 2 -sticky w
2045            grid [ checkbutton $expgui(diffBox).rfDCrref \
2046                    -variable entryvar(ratref) ] -column 2 -row 2
2047            grid [ label $expgui(diffBox).lDCratio -text Ratio ] \
2048                    -column 3 -row 2
2049            grid [ entry $expgui(diffBox).eDCkratio \
2050                    -textvariable entryvar(kratio) \
2051                    -width 15 ] -column 4 -row 2
2052            set entrybox(kratio) $expgui(diffBox).eDCkratio
2053            #
2054            grid [ label $expgui(diffBox).lDCzero -text "Zero"] \
2055                    -column 3 -row 3
2056            grid [ entry $expgui(diffBox).eDCzero -textvariable entryvar(zero) \
2057                    -width 15 ] -column 4 -row 3
2058            grid [ label $expgui(diffBox).lDCzref -text "Refine zero" ] \
2059                    -column 1 -row 3 -sticky w
2060            set entrybox(zero) $expgui(diffBox).eDCzero
2061            grid [ checkbutton $expgui(diffBox).rfDCzref \
2062                    -variable entryvar(zref) ] -column 2 -row 3
2063            grid [ label $expgui(diffBox).lDCpref -text "Refine POLA" ] \
2064                    -column 1 -row 4 -sticky w
2065            grid [ checkbutton $expgui(diffBox).rfDCpref \
2066                    -variable entryvar(pref) ] -column 2 -row 4
2067            grid [ label $expgui(diffBox).lDCpola -text POLA ] \
2068                    -column 3 -row 4
2069            grid [ entry $expgui(diffBox).eDCpola \
2070                    -textvariable entryvar(pola) -width 15 ] -column 4 -row 4
2071            set entrybox(pola) $expgui(diffBox).eDCpola
2072            grid [ label $expgui(diffBox).lDCipola -text "IPOLA" ] \
2073                    -column 5 -row 4
2074            grid [ entry $expgui(diffBox).eDCipola -width 2 \
2075                    -textvariable entryvar(ipola)] -column 6 -row 4
2076            set entrybox(ipola) $expgui(diffBox).eDCipola
2077        } elseif {[string range $expmap(htype_$hist) 1 2] == "XE"} {
2078        #-------------
2079        # ED - x-ray |
2080        #-------------
2081            grid [ label $expgui(diffBox).lDC1 -text "Refine 2theta" ] \
2082                    -column 1 -row 1
2083            grid [ checkbutton $expgui(diffBox).rfDC1 -variable entryvar(ttref) ] \
2084                    -column 2 -row 1
2085            grid [ label $expgui(diffBox).lDCdifc -text 2Theta ] \
2086                    -column 3 -row 1 -sticky w
2087            grid [ entry $expgui(diffBox).eDCdifc -textvariable entryvar(lam1) \
2088                    -width 15 ] -column 4 -row 1
2089            set entrybox(lam1) $expgui(diffBox).eDCdifc
2090            #
2091            grid [ label $expgui(diffBox).lDCpref -text "Refine POLA" ] \
2092                    -column 1 -row 4 -sticky w
2093            grid [ checkbutton $expgui(diffBox).rfDCpref \
2094                    -variable entryvar(pref) ] -column 2 -row 4
2095            grid [ label $expgui(diffBox).lDCpola -text POLA ] \
2096                    -column 3 -row 4
2097            grid [ entry $expgui(diffBox).eDCpola \
2098                    -textvariable entryvar(pola) -width 15 ] -column 4 -row 4
2099            set entrybox(pola) $expgui(diffBox).eDCpola
2100            grid [ label $expgui(diffBox).lDCipola -text "IPOLA" ] \
2101                    -column 5 -row 4
2102            grid [ entry $expgui(diffBox).eDCipola -width 2 \
2103                    -textvariable entryvar(ipola)] -column 6 -row 4
2104            set entrybox(ipola) $expgui(diffBox).eDCipola
2105        }
2106    } elseif {$expgui(globalmode) == 1} {
2107        #-------------
2108        # Global TOF |
2109        #-------------
2110        grid [ label $expgui(diffBox).lDCrc -text "Refine DIFC" ] \
2111                -column 1 -row 1
2112        grid [ checkbutton $expgui(diffBox).rfDCrc -variable entryvar(dcref) ] \
2113                -column 2 -row 1
2114        grid [button $expgui(diffBox).bDCdifc -text "Set DIFC Globally" \
2115                -command "editglobalparm histinfo difc {DIFC}"] -column 3 -row 1
2116        #
2117        grid [ label $expgui(diffBox).lDCra -text "Refine DIFA" ] \
2118                -column 1 -row 2
2119        grid [ checkbutton $expgui(diffBox).rfDCra -variable entryvar(daref) ] \
2120                -column 2 -row 2
2121        grid [ button $expgui(diffBox).bDCdifa -text "Set DIFA Globally" \
2122                -command "editglobalparm histinfo difa {DIFA}"] -column 3 -row 2
2123        #
2124        grid [ label $expgui(diffBox).lDCzref -text "Refine zero" ] \
2125                -column 1 -row 3 -sticky w
2126        grid [ checkbutton $expgui(diffBox).rfDCzref \
2127                -variable entryvar(zref) ] -column 2 -row 3
2128        grid [ button $expgui(diffBox).bDCzero -text "Set ZERO Globally" \
2129                -command "editglobalparm histinfo zero {Zero}"] -column 3 -row 3
2130    } elseif {$expgui(globalmode) == 2} {
2131        #--------------------
2132        # Global CW neutron |
2133        #--------------------
2134        grid [ label $expgui(diffBox).lDC1 -text "Refine wave" ] \
2135                -column 1 -row 1
2136        grid [ checkbutton $expgui(diffBox).rfDC1 -variable entryvar(wref) ] \
2137                -column 2 -row 1
2138        grid [button $expgui(diffBox).bDCdifc -text "Set Wave Globally" \
2139                -command "editglobalparm histinfo lam1 Wavelength"] \
2140                -column 3 -row 1
2141        #
2142        grid [ label $expgui(diffBox).lDCzref -text "Refine zero" ] \
2143                -column 1 -row 3 -sticky w
2144        grid [ checkbutton $expgui(diffBox).rfDCzref \
2145                -variable entryvar(zref) ] -column 2 -row 3
2146        grid [button $expgui(diffBox).bDCzero -text "Set Zero Globally" \
2147                -command "editglobalparm histinfo zero Zero"] -column 3 -row 3
2148    } elseif {$expgui(globalmode) == 4} {
2149        #----------------------
2150        # Global CW mono xray |
2151        #----------------------
2152        grid [ label $expgui(diffBox).lDC1 -text "Refine wave" ] \
2153                -column 1 -row 1
2154        grid [ checkbutton $expgui(diffBox).rfDC1 -variable entryvar(wref) ] \
2155                -column 2 -row 1
2156        grid [button $expgui(diffBox).bDCdifc -text "Set Wave Globally" \
2157                -command "editglobalparm histinfo lam1 Wavelength"] \
2158                -column 3 -row 1
2159        #
2160        grid [ label $expgui(diffBox).lDCzref -text "Refine zero" ] \
2161                -column 1 -row 3 -sticky w
2162        grid [ checkbutton $expgui(diffBox).rfDCzref \
2163                -variable entryvar(zref) ] -column 2 -row 3
2164        grid [button $expgui(diffBox).bDCzero -text "Set Zero Globally" \
2165                -command "editglobalparm histinfo zero Zero"] -column 3 -row 3
2166        #
2167        grid [ label $expgui(diffBox).lDCpref -text "Refine POLA" ] \
2168                -column 1 -row 4 -sticky w
2169        grid [ checkbutton $expgui(diffBox).rfDCpref \
2170                -variable entryvar(pref) ] -column 2 -row 4
2171        grid [button $expgui(diffBox).bDCpola -text "Set POLA Globally" \
2172                -command "editglobalparm histinfo pola POLA"] -column 3 -row 4
2173        grid [button $expgui(diffBox).bDCipola -text "Set IPOLA Globally" \
2174                -command "editglobalparm histinfo ipola IPOLA"] -column 4 -row 4
2175    } elseif {$expgui(globalmode) == 3} {
2176        #------------------------
2177        # Global alpha 1,2 xray |
2178        #------------------------
2179        grid [button $expgui(diffBox).bDCl1 -text "Set Wave1 Globally" \
2180                -command "editglobalparm histinfo lam1 {Wavelength 1}"] \
2181                -column 3 -row 1
2182        grid [button $expgui(diffBox).bDCl2 -text "Set Wave2 Globally" \
2183                -command "editglobalparm histinfo lam2 {Wavelength 2}"] \
2184                -column 4 -row 1
2185        #
2186        grid [ label $expgui(diffBox).lDCratref -text "Refine Ratio" ] \
2187                -column 1 -row 2 -sticky w
2188        grid [ checkbutton $expgui(diffBox).rfDCratref \
2189                -variable entryvar(ratref) ] -column 2 -row 2
2190        grid [button $expgui(diffBox).bDCrrat -text "Set Ratio Globally" \
2191                -command "editglobalparm histinfo ratio {Wavelength Ratio}"] \
2192                -column 3 -row 2
2193        #
2194        grid [ label $expgui(diffBox).lDCzref -text "Refine zero" ] \
2195                -column 1 -row 3 -sticky w
2196        grid [ checkbutton $expgui(diffBox).rfDCzref \
2197                -variable entryvar(zref) ] -column 2 -row 3
2198        grid [button $expgui(diffBox).bDCzero -text "Set Zero Globally" \
2199                -command "editglobalparm histinfo zero Zero"] -column 3 -row 3
2200        #
2201        grid [ label $expgui(diffBox).lDCpref -text "Refine POLA" ] \
2202                -column 1 -row 4 -sticky w
2203        grid [ checkbutton $expgui(diffBox).rfDCpref \
2204                -variable entryvar(pref) ] -column 2 -row 4
2205        grid [button $expgui(diffBox).bDCpola -text "Set POLA Globally" \
2206                -command "editglobalparm histinfo pola POLA"] -column 3 -row 4
2207        grid [button $expgui(diffBox).bDCipola -text "Set IPOLA Globally" \
2208                -command "editglobalparm histinfo ipola IPOLA"] -column 4 -row 4
2209    } elseif {$expgui(globalmode) == 5} {
2210        #-----------------
2211        # Global ED xray |
2212        #-----------------
2213        grid [ label $expgui(diffBox).lDC1 -text "Refine 2theta" ] \
2214                -column 1 -row 1
2215        grid [ checkbutton $expgui(diffBox).rfDC1 -variable entryvar(ttref) ] \
2216                -column 2 -row 1
2217        grid [button $expgui(diffBox).bDCdifc -text "Set 2Theta Globally" \
2218                -command "editglobalparm histinfo ratio {Fixed 2Theta}"] \
2219                -column 3 -row 1
2220        #
2221        grid [ label $expgui(diffBox).lDCpref -text "Refine POLA" ] \
2222                -column 1 -row 4 -sticky w
2223        grid [ checkbutton $expgui(diffBox).rfDCpref \
2224                -variable entryvar(pref) ] -column 2 -row 4
2225        grid [button $expgui(diffBox).bDCpola -text "Set POLA Globally" \
2226                -command "editglobalparm histinfo pola POLA"] -column 3 -row 4
2227        grid [button $expgui(diffBox).bDCipola -text "Set IPOLA Globally" \
2228                -command "editglobalparm histinfo ipola IPOLA"] -column 4 -row 4
2229    }
2230    if {$expgui(globalmode) == 0} {
2231        grid [frame $expgui(diffBox).d] -column 5 -row 1 -rowspan 3 \
2232                -columnspan 2 -sticky e
2233    } else {
2234        grid [frame $expgui(diffBox).d] -column 4 -row 2 -rowspan 2 \
2235                -columnspan 2 -sticky e
2236    }
2237    grid [label $expgui(diffBox).d.lDamp -text "Damping  "] \
2238            -column 1 -row 1 
2239    tk_optionMenu $expgui(diffBox).d.om entryvar(ddamp) 0 1 2 3 4 5 6 7 8 9
2240    grid $expgui(diffBox).d.om -column 2 -row 1 
2241    grid columnconfigure $expgui(diffBox) 9  -weight 1
2242    grid columnconfigure $expgui(diffBox) 0  -weight 1
2243    update idletasks
2244    # enable traces on entryvar now
2245    set entrycmd(trace) 1
2246}
2247
2248# this gets the phase flags as set in the expgui(pflag*) elements
2249# (linked to phase flag checkbuttons) and the sets the "HST xx NPHAS" flags
2250# accordingly using SetPhaseFlag
2251proc GetPhaseFlags {hist} {
2252    global expmap expgui
2253    set plist {}
2254    foreach p $expmap(phaselist) {
2255        if {$expgui(pflag$p)} {lappend plist $p}
2256    }
2257    SetPhaseFlag $hist $plist
2258    RecordMacroEntry "SetPhaseFlag [list $hist] [list $plist]" 0
2259    incr expgui(changed)
2260    RecordMacroEntry "incr expgui(changed)" 0
2261    # set the powpref warning (1 = suggested)
2262    set expgui(needpowpref) 2
2263    set msg "Phase flags" 
2264    if {[string first $msg $expgui(needpowpref_why)] == -1} {
2265        append expgui(needpowpref_why) "\t$msg were changed\n"
2266    }
2267    mapexp
2268    # reset the phase selection
2269    set expgui(curPhase) {}
2270}
2271
2272#-----------------------------------------------------------------------
2273# populate the Scaling page
2274#-----------------------------------------------------------------------
2275proc DisplayFrac {} {
2276    global expgui entrycmd entryvar entrybox expmap
2277
2278    # trap if more than one histogram is selected unless global mode
2279    if {$expgui(globalmode) == 0 && [llength $expgui(curhist)] > 1} {
2280        set expgui(curhist) [lindex $expgui(curhist) 0] 
2281    }
2282
2283    # display the selected histograms
2284    $expgui(fracFrame).hs.lbox selection clear 0 end
2285    foreach h $expgui(curhist) {
2286        $expgui(fracFrame).hs.lbox selection set $h
2287    }
2288
2289    # disable traces on entryvar
2290    set entrycmd(trace) 0
2291
2292    # get histogram list
2293    set histlist {}
2294    foreach item $expgui(curhist) {
2295        lappend histlist [lindex $expmap(powderlist) $item]
2296    }
2297
2298    # must have at least one histogram selected here
2299    if {[llength $histlist] == 0} {
2300        foreach var {scale sref sdamp} {
2301            set entrycmd($var) ""
2302            set entryvar($var) ""
2303        }
2304        set parm [grid info $expgui(scaleBox).but1]
2305        if {$parm != ""} {
2306            grid forget  $expgui(scaleBox).but1
2307            eval grid $expgui(scaleBox).ent1 $parm
2308        }
2309        # destroy the contents of the frame
2310        set phaseFractf1 $expgui(FracBox).f
2311        eval destroy [winfo children $phaseFractf1]
2312        # reenable traces on entryvar
2313        set entrycmd(trace) 1
2314        return
2315    }
2316
2317    #--------------
2318    # Scale factor
2319    #--------------
2320    if {$expgui(globalmode) != 0} {
2321        foreach var {scale sref sdamp} {
2322            set entrycmd($var) "histinfo [list $histlist] $var"
2323            set entryvar($var) [histinfo [lindex $histlist 0] $var]
2324        }
2325        # reset scale to black
2326        catch {$entrybox(scale) config -fg black}
2327        set parm [grid info $expgui(scaleBox).ent1]
2328        if {$parm != ""} {
2329            grid forget  $expgui(scaleBox).ent1
2330            eval grid $expgui(scaleBox).but1 $parm
2331        }
2332    } else {
2333        set hist $histlist
2334        foreach var {scale sref sdamp} {
2335            set entrycmd($var) "histinfo $hist $var"
2336            set entryvar($var) [eval $entrycmd($var)]
2337        }
2338        # reset scale to black
2339        catch {$entrybox(scale) config -fg black}
2340        set parm [grid info $expgui(scaleBox).but1]
2341        if {$parm != ""} {
2342            grid forget  $expgui(scaleBox).but1
2343            eval grid $expgui(scaleBox).ent1 $parm
2344        }
2345    }
2346
2347    #----------------
2348    # Phase Fractions
2349    #----------------
2350    set phaseFractf1 $expgui(FracBox).f
2351    # destroy the contents of the frame
2352    eval destroy [winfo children $phaseFractf1]
2353    if {$expgui(globalmode) != 0} {
2354        set txt "Phase Fractions for Histograms: [CompressList $histlist]"
2355    } else {
2356        set txt "Phase Fractions"
2357    }
2358    $expgui(fracFrame).f1.phaseFrac configure -text $txt
2359    # Create the frame inside the canvas, One frame for each Phase.
2360    foreach i {1 2 3 4 5 6 7 8 9} {set phasehistlist($i) ""}
2361    foreach hist $histlist {
2362        foreach i $expmap(phaselist_$hist) {
2363            lappend phasehistlist($i) $hist
2364        }
2365    }
2366    foreach i {1 2 3 4 5 6 7 8 9} {
2367        if {[llength $phasehistlist($i)] == 0} continue
2368        set framePF [frame $phaseFractf1.pF$i -relief groove  -bd 4]
2369        grid $framePF -column 0 -row $i -sticky ew
2370        # Label Heading for each phase.
2371        if {$expgui(globalmode) != 0} {
2372            grid [label $framePF.l1 \
2373                    -text "Phase $i Hist: [CompressList $phasehistlist($i)]"] \
2374                    -column 0 -row 0 -sticky nws
2375            grid [button $framePF.but1 -text "Set Globally" \
2376                    -command "editglobalparm hapinfo frac \"Phase $i Fraction\" \
2377                    [list $phasehistlist($i)] $i" \
2378                    ] -column 1 -row 0
2379            set entrycmd(frref$i) "hapinfo [list $histlist] $i frref"
2380            set entryvar(frref$i) [hapinfo $hist $i frref]
2381            set entrycmd(frdamp$i) "hapinfo [list $histlist] $i frdamp"
2382        } else {
2383            grid [label $framePF.l1  -text "Phase $i"] \
2384                    -column 0 -row 0 -sticky nws
2385            grid [entry $framePF.ent -textvariable entryvar(frac$i) -width 15]\
2386                    -column 1 -row 0
2387            set entrybox(frac$i) $framePF.ent
2388            set entrycmd(frref$i) "hapinfo $hist $i frref"
2389            set entryvar(frref$i) [hapinfo $hist $i frref]
2390            set entrycmd(frdamp$i) "hapinfo $hist $i frdamp"
2391        }
2392        set entrycmd(frac$i) "hapinfo $hist $i frac"
2393        set entryvar(frac$i) [hapinfo $hist $i frac]
2394        grid [label $framePF.l2  -text "  Refine"] \
2395                -column 2 -row 0 -sticky nws
2396        grid [checkbutton $framePF.cb -variable entryvar(frref$i)] \
2397                -column 3 -row 0 -sticky nws
2398        grid [label $framePF.l3  -text "  Damping"] \
2399                -column 4 -row 0 -sticky nws
2400        tk_optionMenu $framePF.tkOptDamp entryvar(frdamp$i) \
2401                0 1 2 3 4 5 6 7 8 9     
2402        set entryvar(frdamp$i) [hapinfo $hist $i frdamp]
2403        grid $framePF.tkOptDamp -row 0 -sticky nsw -column 5
2404    }
2405    # resize the scroll window to match the actual
2406    update idletasks
2407    $expgui(FracBox) config -scrollregion [grid bbox $expgui(FracBox).f]
2408    $expgui(FracBox) config -width [lindex [grid bbox $expgui(FracBox).f] 2]
2409    update idletasks
2410    # enable traces on entryvar now
2411    set entrycmd(trace) 1
2412}
2413
2414#-----------------------------------------------------------------------
2415# display the profile page
2416#-----------------------------------------------------------------------
2417proc DisplayProfile {} {
2418    global expgui entrycmd entryvar entrybox expmap
2419
2420    # trap if more than one histogram is selected unless global mode
2421    if {$expgui(globalmode) == 0 && [llength $expgui(curhist)] > 1} {
2422        set expgui(curhist) [lindex $expgui(curhist) 0] 
2423    }
2424    # display the selected histograms
2425    $expgui(profFrame).hs.lbox selection clear 0 end
2426    foreach h $expgui(curhist) {
2427        $expgui(profFrame).hs.lbox selection set $h
2428    }
2429
2430    # destroy the contents of the frame
2431    eval destroy [winfo children $expgui(ProfileBox).f]
2432    # since the next steps can take a while, do a screen update
2433    update idletasks
2434
2435    if {$expgui(globalmode) == 0} {
2436        # must have at least one histogram selected here
2437        if {[llength $expgui(curhist)] == 0} return
2438        # disable traces on entryvar for right now
2439        set entrycmd(trace) 0
2440        set hist [lindex $expmap(powderlist) $expgui(curhist)]
2441        # no defined histograms?
2442        if {$hist == ""} return
2443        # Create one frame for each Phase.
2444        set ind -1
2445        set htype [string range $expmap(htype_$hist) 2 2]
2446        set zflag 0
2447        if {$htype == "C"} {
2448            set zflag [histinfo $hist zref]
2449        }
2450        foreach i $expmap(phaselist_$hist) {
2451            incr ind
2452            # Label Heading for each phase.
2453            set ptype [string trim [hapinfo $hist $i proftype]]
2454            grid [TitleFrame $expgui(ProfileBox).f.$i \
2455                      -text "Hist $hist -- Phase $i (type $ptype)" \
2456                      -relief groove -bd 2] \
2457                -column 0 -row $ind -sticky ew
2458            set ProfileFrame [$expgui(ProfileBox).f.$i getframe]
2459            grid [frame $ProfileFrame.1] \
2460                -column 0 -row 0 -columnspan 10
2461            pack [label $ProfileFrame.1.l  \
2462                      -text Damping]\
2463                -side left
2464            tk_optionMenu $ProfileFrame.1.tkOptDamp entryvar(pdamp_$i) \
2465                    0 1 2 3 4 5 6 7 8 9
2466            set entrycmd(pdamp_$i) "hapinfo $hist $i pdamp"
2467            set entryvar(pdamp_$i) [hapinfo $hist $i pdamp]
2468            pack $ProfileFrame.1.tkOptDamp -side left
2469            pack [label $ProfileFrame.1.l1 \
2470                    -text "  Peak cutoff"]\
2471                    -side left
2472            pack [entry $ProfileFrame.1.e1  \
2473                    -width 10 -textvariable entryvar(pcut_$i)]\
2474                    -side left
2475            set entrybox(pcut_$i) $ProfileFrame.1.e1
2476            set entrycmd(pcut_$i) "hapinfo $hist $i pcut"
2477            set entryvar(pcut_$i) [hapinfo $hist $i pcut]
2478
2479            pack [button $ProfileFrame.1.b1  \
2480                    -text "Change Type" \
2481                    -command "ChangeProfileType $hist $i"]\
2482                    -side left
2483           
2484            set col -1
2485            set row 1
2486            set nterms [hapinfo $hist $i profterms]
2487            set lbls "dummy [GetProfileTerms $i $hist [expr abs($ptype)]]"
2488            for { set num 1 } { $num <= $nterms } { incr num } {
2489                set term {}
2490                catch {set term [lindex $lbls $num]}
2491                if {$term == ""} {set term $num}
2492                incr col
2493                grid [label $ProfileFrame.l${num}_${i} -text "$term"] \
2494                        -row $row -column $col
2495                incr col
2496                grid [checkbutton $ProfileFrame.ref${num}_${i} \
2497                        -variable entryvar(pref${num}_$i)] -row $row -column $col
2498                set entrycmd(pref${num}_$i) "hapinfo $hist $i pref$num"
2499                set entryvar(pref${num}_$i) [hapinfo $hist $i pref$num]
2500                incr col
2501                grid [entry $ProfileFrame.ent${num}_${i} \
2502                        -textvariable entryvar(pterm${num}_$i)\
2503                        -width 12] -row $row -column $col
2504                set entrybox(pterm${num}_$i) $ProfileFrame.ent${num}_${i}
2505                set entrycmd(pterm${num}_$i) "hapinfo $hist $i pterm$num"
2506                set entryvar(pterm${num}_$i) [hapinfo $hist $i pterm$num]
2507                # disable trns & shft when zero is refined
2508                if {$zflag && ($term == "trns" || $term == "shft")} {
2509                    if {$entryvar(pref${num}_$i)} {
2510                        incr expgui(changed)
2511                        set entryvar(pref${num}_$i) 0
2512                    }
2513                    $ProfileFrame.l${num}_${i} config -fg gray
2514                    $ProfileFrame.ref${num}_${i} config -state disabled
2515                    $ProfileFrame.ent${num}_${i} config -fg gray
2516                }
2517                if {$col > 6} {set col -1; incr row}
2518            }
2519        }
2520        grid columnconfigure $expgui(ProfileBox).f 0 -weight 1
2521    } else {
2522        # get histogram list
2523        set histlist {}
2524        foreach item $expgui(curhist) {
2525            lappend histlist [lindex $expmap(powderlist) $item]
2526        }
2527        # must have at least one histogram selected here
2528        if {[llength $histlist] == 0} return
2529        # disable traces on entryvar for right now
2530        set entrycmd(trace) 0
2531        # loop through histograms & phases, set up an array by phase & profile type
2532        catch {unset prtyparray histarray phasearray}
2533        foreach hist $histlist {
2534            foreach phase $expmap(phaselist_$hist) {
2535                set prtyp [string trim [hapinfo $hist $phase proftype]]
2536                set key ${prtyp}_$phase
2537                lappend prtyparray($key) $hist
2538                lappend histarray($key) $hist
2539                lappend phasearray($key) $phase
2540            }
2541        }
2542       
2543        set ptype ""
2544        set i -1
2545        # loop over all combined phases and profile types, sorted 1st by profile number
2546        foreach key [lsort [array names prtyparray]] {
2547            # split key
2548            scan $key %d_%d prftyp p
2549
2550            if {$ptype != $prftyp || !$expgui(globalphasemode)} {
2551                set ptype $prftyp
2552                set curhistlist $histarray($key)
2553                set curphaslist $phasearray($key)
2554               
2555                set hist1 [lindex $curhistlist 0]
2556                set phase1 [lindex $curphaslist 0]
2557                set nterms [hapinfo $hist1 $phase1 profterms]
2558                set htype [string range $expmap(htype_$hist1) 2 2]
2559                set lbls "dummy [GetProfileTerms $phase1 $hist1 [expr abs($ptype)]]"
2560                # Create a frame for this type
2561                incr i
2562                set boxtitle "Phase $p, hist [CompressList $histarray($key)]"
2563                grid [TitleFrame $expgui(ProfileBox).f.$i \
2564                          -text "(type $ptype)" \
2565                          -relief groove -bd 2] \
2566                    -column 0 -row $i -sticky ew
2567                set ProfileFrame [$expgui(ProfileBox).f.$i getframe]
2568                grid [frame $ProfileFrame.0] \
2569                    -column 0 -row 0 -columnspan 20 -sticky ew
2570                grid [label $ProfileFrame.0.1  \
2571                        -anchor w] -row 0 -column 1
2572                grid [frame $ProfileFrame.1] \
2573                        -column 0 -row 1 -columnspan 20 -sticky ew
2574                grid [label $ProfileFrame.1.2  \
2575                        -text "Damping"] -row 0 -column 2
2576                tk_optionMenu $ProfileFrame.1.tkOptDamp \
2577                        entryvar(pdamp_$i) 0 1 2 3 4 5 6 7 8 9
2578                grid $ProfileFrame.1.tkOptDamp -row 0 -column 3
2579                grid [button $ProfileFrame.1.edit \
2580                        -text "Global Edit"] -row 0 -column 4 -sticky w
2581                set entryvar(pdamp_$i) [hapinfo $hist $phase pdamp]
2582                grid [button $ProfileFrame.1.b1 -text "Change Type"] \
2583                        -row 0 -column 5 -sticky w
2584                set col -1
2585                set row 2
2586                for { set num 1 } { $num <= $nterms } { incr num } {
2587                    set term {}
2588                    catch {set term [lindex $lbls $num]}
2589                    if {$term == ""} {set term $num}
2590                    incr col
2591                    grid [label $ProfileFrame.l${num}_${i} \
2592                            -text "$term"] -row $row -column $col
2593                    incr col
2594                    grid [checkbutton $ProfileFrame.ref${num}_${i} \
2595                            -variable entryvar(pref${num}_$i)] \
2596                            -row $row -column $col
2597                    set entryvar(pref${num}_$i) [hapinfo $hist $phase pref$num]
2598                    if {$col > 10} {set col -1; incr row}
2599                }
2600                grid columnconfigure $expgui(ProfileBox).f 0 -weight 1
2601            } else {
2602                # add to the current entry
2603                eval lappend curhistlist $histarray($key)
2604                eval lappend curphaslist $phasearray($key)
2605                append boxtitle "\nPhase $p, hist [CompressList $histarray($key)]"
2606            }
2607            $ProfileFrame.0.1 config -text $boxtitle
2608            $ProfileFrame.1.edit config -command "\
2609                    EditProfile \"\n$boxtitle\" \
2610                    [list $curhistlist] \
2611                    [list $curphaslist]"
2612            $ProfileFrame.1.b1 config -command "ChangeProfileType \
2613                    [list $curhistlist] [list $curphaslist]" 
2614            set entrycmd(pdamp_$i) "hapinfo \
2615                    [list $curhistlist] \
2616                    [list $curphaslist] pdamp"
2617            for { set num 1 } { $num <= $nterms } { incr num } {
2618                set entrycmd(pref${num}_$i) "hapinfo \
2619                        [list $curhistlist] \
2620                        [list $curphaslist] pref$num"
2621            }
2622        }
2623    }
2624   
2625    # resize the scroll window to match the actual
2626    update idletasks
2627    $expgui(ProfileBox) config -scrollregion [grid bbox $expgui(ProfileBox).f]
2628    $expgui(ProfileBox) config -width [lindex [grid bbox $expgui(ProfileBox).f] 2]
2629    update idletasks
2630    ResizeNotebook
2631    # enable traces on entryvar now
2632    set entrycmd(trace) 1
2633}
2634
2635# process the bit settings in the print options
2636#   bitnum -- the number of the bit to be tested/set starting at 0 for the LSBit
2637proc printsetting {bitnum "action get" "value {}"} {
2638    global entryvar expgui
2639    if {$action == "get"} {
2640        return [expr ([expinfo print] & int(pow(2,$bitnum))) != 0]
2641    } elseif $value {
2642        set newval [expr ([expinfo print] | int(pow(2,$bitnum)))]
2643    } else {
2644        set newval [expr ([expinfo print] & ~int(pow(2,$bitnum)))]
2645    }
2646    expinfo print set $newval
2647    RecordMacroEntry "incr expgui(changed); expinfo print set $newval" 1
2648    set expgui(printopt) "Print Options ([expinfo print])"
2649}
2650
2651# need to respond to mouse presses -- control variable associated with extract Fobs
2652# and set the LeBail extraction flags
2653proc SetupExtractHist {} {
2654    global expgui entrycmd entryvar expmap
2655
2656    # display the selected histograms
2657    $expgui(lsFrame).hs.lbox selection clear 0 end
2658    foreach h $expgui(curhist) {
2659        $expgui(lsFrame).hs.lbox selection set $h
2660    }
2661
2662    # get histogram list
2663    set histlist {}
2664    foreach item $expgui(curhist) {
2665        set hist [lindex $expmap(powderlist) $item]
2666        if {$hist != ""} {lappend histlist $hist}
2667    }
2668    set entrycmd(fobsextract) "histinfo [list $histlist] foextract"
2669    if {[llength $histlist] == 0 || [string trim $histlist] == ""} {
2670        set entrycmd(LBdamp) ""
2671        foreach phase {1 2 3 4 5 6 7 8 9} {
2672            $expgui(FobsExtractFrame).l$phase config -fg grey
2673            set expgui(Fextract$phase) {}
2674            foreach item $expgui(ExtractSettingsRadiobuttons) {
2675                ${item}$phase config -state disabled -bd 1
2676            }
2677        }
2678    } elseif {[llength $histlist] == 1} {
2679        # disable traces on entryvar
2680        set entrycmd(trace) 0
2681        set entryvar(fobsextract) [histinfo $histlist foextract]
2682        set entrycmd(LBdamp) "histinfo $histlist LBdamp"
2683        set entryvar(LBdamp) [histinfo $histlist LBdamp]
2684        foreach phase {1 2 3 4 5 6 7 8 9} {
2685            # is the phase present?
2686            if {[lsearch -exact $expmap(phaselist_$histlist) $phase] == -1} {
2687                $expgui(FobsExtractFrame).l$phase config -fg grey
2688                set expgui(Fextract$phase) {}
2689                foreach item $expgui(ExtractSettingsRadiobuttons) {
2690                    ${item}$phase config -state disabled -bd 1
2691                }
2692            } else {
2693                $expgui(FobsExtractFrame).l$phase config -fg black
2694                foreach item $expgui(ExtractSettingsRadiobuttons) {
2695                    ${item}$phase config -state normal -bd 2
2696                }
2697                set expgui(Fextract$phase) [hapinfo $histlist $phase extmeth]
2698            }
2699        }
2700    } elseif {[llength $histlist] > 1} {
2701        # disable traces on entryvar
2702        set entrycmd(LBdamp) "histinfo [list $histlist] LBdamp"
2703        set entryvar(LBdamp) [histinfo [lindex $histlist 0] LBdamp]
2704        set entrycmd(trace) 0
2705        # multiple histograms need phases in any histogram
2706        foreach phase {1 2 3 4 5 6 7 8 9} {
2707            set gotphase($phase) 0
2708        }           
2709        foreach hist $histlist {
2710            foreach phase $expmap(phaselist_$hist) {
2711                set gotphase($phase) 1
2712            }
2713        }
2714        foreach phase {1 2 3 4 5 6 7 8 9} {
2715            set expgui(Fextract$phase) {}
2716            if $gotphase($phase) {
2717                $expgui(FobsExtractFrame).l$phase config -fg black
2718                foreach item $expgui(ExtractSettingsRadiobuttons) {
2719                    ${item}$phase config -state normal -bd 2
2720                }
2721            } else {
2722                $expgui(FobsExtractFrame).l$phase config -fg grey
2723                foreach item $expgui(ExtractSettingsRadiobuttons) {
2724                    ${item}$phase config -state disabled -bd 1
2725                }
2726            }
2727        }
2728    }
2729    # reenable traces
2730    set entrycmd(trace) 1
2731}
2732# respond to a change in the fobs extraction method for a phase
2733# force the main extraction flag on, if fobs extraction is selected for any phase
2734proc HistExtractSet {phase} {
2735    global expgui entryvar expmap
2736    foreach item $expgui(curhist) {
2737        lappend histlist [lindex $expmap(powderlist) $item]
2738    }
2739    hapinfo $histlist $phase extmeth set $expgui(Fextract$phase)
2740    RecordMacroEntry "incr expgui(changed); hapinfo [list $histlist] $phase extmeth set $expgui(Fextract$phase)" 1
2741    incr expgui(changed)
2742    if {$expgui(Fextract$phase) != 0} {set entryvar(fobsextract) 1}
2743}
2744#---------------------------- Global Edit Functions ------------------------
2745proc editbackground {} {
2746    global expgui expmap entrycmd
2747    set histlist {}
2748    foreach n $expgui(curhist) {
2749        lappend histlist [lindex $expmap(powderlist) $n]
2750    }
2751    if {[llength $histlist] == 0} return
2752
2753    set w .back
2754    catch {destroy $w}
2755    toplevel $w -bg beige
2756    if {$expgui(globalmode) != 0} {
2757        wm title $w "Global Edit Background" 
2758    } else {
2759        wm title $w "Edit Background" 
2760    }
2761   
2762    pack [frame $w.0 -bd 6 -relief groove  -bg beige \
2763            ] -side top -expand yes -fill both
2764    if {[llength $histlist] > 1} {
2765        grid [label $w.0.a \
2766            -text "Setting background terms for histograms [CompressList $histlist]" \
2767            -bg beige] -row 0 -column 0 -columnspan 10
2768    } else {
2769        grid [label $w.0.a \
2770            -text "Setting background terms for histogram $histlist" \
2771            -bg beige] -row 0 -column 0 -columnspan 4
2772        grid [button $w.0.bkg -text "Fit Background\nGraphically" \
2773                -command "QuitEditBackground $w; bkgedit $histlist"] \
2774                -row 0 -column 4 -rowspan 2
2775        grid columnconfig $w.0 0 -weight 1
2776        grid columnconfig $w.0 4 -weight 1
2777    }
2778    set hist [lindex $histlist 0]
2779    grid [label $w.0.b -text "Function type" -bg beige]  -row 1 -column 0 -sticky e
2780
2781    # disable traces on  expgui(backtype) & expgui(backterms) now
2782    set entrycmd(trace) 0
2783
2784    # number of terms
2785    set expgui(backtype) [histinfo $hist backtype]
2786    set expgui(orig_backtype) $expgui(backtype)
2787    set expgui(prev_backtype) $expgui(backtype)
2788    set typemenu [tk_optionMenu $w.0.type expgui(backtype) null]
2789    $typemenu delete 0 end
2790    foreach item {
2791        "1 - Shifted Chebyschev"
2792        "2 - Cosine Fourier series"
2793        "4 - Power series in Q**2n/n!"
2794        "5 - Power series in n!/Q**2n"
2795        "6 - Power series in Q**2n/n! and n!/Q**2n"
2796        "7 - Linear interpolation function"
2797        "8 - Reciprocal interpolation function"
2798    } {
2799        set val [lindex $item 0]
2800        $typemenu insert end radiobutton -variable expgui(backtype) \
2801                -label $item -value $val
2802    }
2803# removed
2804#       "3 - Radial distribution peaks"
2805
2806    grid $w.0.type   -row 1 -column 1
2807    grid [label $w.0.c -text "  Number of terms"  -bg beige] -row 1 -column 2
2808
2809    # function type
2810    set expgui(backterms) [histinfo $hist backterms]
2811    set expgui(orig_backterms) $expgui(backterms) 
2812    set list {}; for {set i 1} {$i <= 36} {incr i} {lappend list $i}
2813    eval tk_optionMenu $w.0.terms expgui(backterms) $list
2814    grid $w.0.terms   -row 1 -column 3 
2815    # enable traces on  expgui(backtype) & expgui(backterms) now
2816    set entrycmd(trace) 1
2817
2818    #set background terms
2819    for {set num 1 } { $num <= 36 } { incr num } {
2820        set var "bterm$num"
2821        set expgui($var) {}
2822        set expgui(orig_$var) {}
2823    }
2824    if {[llength $histlist] == 1} {
2825        for {set num 1 } { $num <= $expgui(backterms) } { incr num } {
2826            set var "bterm$num"
2827            set expgui($var) [histinfo $histlist $var]
2828            set expgui(orig_$var) $expgui($var)
2829        }
2830    }
2831
2832    pack [frame $w.1 -bd 6 -relief groove  -bg beige] -side top \
2833            -expand yes -fill both
2834    ShowBackTerms $w.1
2835
2836    set expgui(temp) {}
2837    pack [frame $w.b -bg beige] -fill x -expand yes -side top
2838    grid [button $w.b.2 -text Continue -command "destroy $w"] -row 0 -column 1
2839    grid [button $w.b.3 -text Cancel \
2840            -command "QuitEditBackground $w"] -row 0 -column 2
2841    grid [button $w.b.help -text Help -bg yellow \
2842            -command "MakeWWWHelp expgui3.html EditBackground"] \
2843            -row 0 -column 4
2844    grid columnconfig $w.b 0 -weight 1
2845    grid columnconfig $w.b 3 -weight 1
2846    bind $w <Key-F1> "MakeWWWHelp expgui3.html EditBackground"
2847    bind $w <Return> "destroy $w"
2848
2849    # force the window to stay on top
2850    putontop $w
2851
2852    focus $w.b.2
2853    tkwait window $w
2854    afterputontop
2855
2856    if {$expgui(temp) != ""} return
2857
2858    if {$expgui(orig_backtype) != $expgui(backtype)} {
2859        histinfo $histlist backtype set $expgui(backtype)
2860        RecordMacroEntry "histinfo [list $histlist] backtype set $expgui(backtype)" 0
2861        incr expgui(changed)
2862    }
2863    if {$expgui(orig_backterms) != $expgui(backterms)} {
2864        histinfo $histlist backterms set $expgui(backterms)
2865        RecordMacroEntry "histinfo [list $histlist] backterms set $expgui(backterms)" 0
2866        incr expgui(changed)
2867    }
2868    for {set num 1 } { $num <= $expgui(backterms) } { incr num } {
2869        set var "bterm$num"
2870        if {$expgui(orig_$var) != $expgui($var)} {
2871            histinfo $histlist $var set $expgui($var)
2872            RecordMacroEntry "histinfo [list $histlist] $var set $expgui($var)" 0
2873            incr expgui(changed)
2874        }
2875    }
2876    RecordMacroEntry "incr expgui(changed)" 0
2877
2878    if {$expgui(globalmode) == 0} {
2879        set expgui(backtypelbl) "Function type [histinfo $hist backtype]"
2880        set expgui(backtermlbl) "([histinfo $hist backterms] terms)"
2881    }
2882}
2883
2884trace variable expgui(backterms) w ChangeBackTerms
2885proc ChangeBackTerms {a b c} {
2886    global entrycmd expgui
2887    if !$entrycmd(trace) return
2888    ShowBackTerms .back.1
2889}
2890
2891trace variable expgui(backtype) w ChangeBackType
2892# reset the terms to 1, 0, 0... when the number of terms increase
2893proc ChangeBackType {a b c} {
2894    global entrycmd expgui
2895    if !$entrycmd(trace) return
2896    if {$expgui(prev_backtype) == $expgui(backtype)} return
2897    set expgui(prev_backtype) $expgui(backtype)
2898    for {set num 1 } { $num <= $expgui(backterms) } { incr num } {
2899        set var "bterm$num"
2900        if {$num == 1} {
2901            set expgui($var) 1.0
2902        } else {
2903            set expgui($var) 0.0
2904        }
2905    }
2906}
2907
2908proc ShowBackTerms {w } {
2909    global expgui expmap
2910    # destroy the contents of the frame
2911    eval destroy [winfo children $w]
2912    set histlist {}
2913    foreach n $expgui(curhist) {
2914        lappend histlist [lindex $expmap(powderlist) $n]
2915    }
2916    set widgetsPerRow 4
2917    for {set rows 2; set num 1 } { $num <= $expgui(backterms) } { incr rows } {
2918        for {set cols 0} { (2*$widgetsPerRow > $cols) && ($num <= $expgui(backterms)) }  { incr num }  {
2919            set var "bterm$num"
2920            grid [label $w.l$num -text $num -bg beige]  \
2921                    -row $rows -column $cols -sticky nes
2922            incr cols
2923            grid [entry $w.e$num -width 15 -textvariable expgui($var) \
2924                    ] -row $rows  -column $cols  -sticky news
2925            incr cols
2926        }
2927    }
2928}
2929
2930proc QuitEditBackground {w} {
2931    global expgui
2932    # lets find out if anything changed
2933    set changed 0
2934    if {$expgui(orig_backtype) != $expgui(backtype)} {
2935        set changed 1
2936    }
2937    if {$expgui(orig_backterms) != $expgui(backterms)} {
2938        set changed 1
2939    }
2940    for {set num 1 } { $num <= $expgui(backterms) } { incr num } {
2941        set var "bterm$num"
2942        if {$expgui(orig_$var) != $expgui($var)} {
2943            set changed 1
2944            break
2945        }
2946    }
2947    if $changed {
2948        set decision [tk_dialog .changes "Abandon Changes" \
2949                "You have made changes to the background. Ok to abandon changes?" \
2950                warning 0 Abandon Keep]
2951        if !$decision {
2952            set expgui(temp) "Quit"
2953            destroy $w
2954        }
2955    } else {
2956        set expgui(temp) "Quit"
2957        destroy $w
2958    }
2959}
2960
2961# this probably needs work
2962proc editglobalparm {cmd variable title "histlist {}" "phase {}"} {
2963    global expgui expmap
2964    set w .global
2965    catch {destroy $w}
2966    toplevel $w -bg beige
2967    wm title $w "Edit Global Parameter"
2968    set expgui(temp) {}
2969    if {[llength $histlist] == 0} {
2970        set hist {}
2971        foreach n $expgui(curhist) {
2972            lappend hist [lindex $expmap(powderlist) $n]
2973        }
2974    } else {
2975        set hist $histlist
2976    }
2977    pack [frame $w.0 -bd 6 -relief groove -bg beige] \
2978            -side top -expand yes -fill both
2979    grid [label $w.0.a -text "Setting $title for histograms [CompressList $hist]"\
2980            -bg beige] \
2981            -row 0 -column 0 -columnspan 10
2982    grid [entry $w.0.b -textvariable expgui(temp)] \
2983            -row 1 -column 0 
2984
2985
2986    pack [frame $w.b -bg beige] -fill x -expand yes -side top
2987    pack [button $w.b.2 -text Continue -command "destroy $w"] -side left
2988    pack [button $w.b.3 -text Cancel -command "set expgui(temp) {}; destroy $w"] -side left
2989    pack [button $w.b.help -text Help -bg yellow \
2990            -command "MakeWWWHelp expgui3.html EditParm"] -side right
2991    bind $w <Key-F1> "MakeWWWHelp expgui3.html EditParm"
2992    bind $w <Return> "destroy $w"
2993
2994    # force the window to stay on top
2995    putontop $w
2996    focus $w.b.2
2997    tkwait window $w
2998    afterputontop
2999
3000    if {$expgui(temp) != ""} {
3001        foreach h $hist {
3002            if {$cmd == "histinfo"} {
3003                histinfo $h $variable set $expgui(temp)
3004                RecordMacroEntry "histinfo $h $variable set $expgui(temp)" 1
3005                incr expgui(changed)
3006                if $expgui(debug) {
3007                    puts "histinfo $h $variable set $expgui(temp)"
3008                }
3009            } elseif {$cmd == "hapinfo"} {
3010                hapinfo $h $phase $variable set $expgui(temp)
3011                RecordMacroEntry "hapinfo $h [list $phase] $variable set $expgui(temp)" 1
3012                incr expgui(changed)
3013                if $expgui(debug) {
3014                    puts "hapinfo $h $phase $variable set $expgui(temp)"
3015                }
3016            } else {
3017                error "$cmd unimplemented"
3018            }
3019        }
3020        RecordMacroEntry "incr expgui(changed)" 0
3021    }
3022}
3023
3024proc EditProfile {title histlist phaselist} {
3025    global expgui expmap entrycmd
3026    set w .back
3027    catch {destroy $w}
3028    toplevel $w -bg beige
3029    wm title $w "Global Edit Profile"
3030    set hist [lindex $histlist 0]
3031    set phase [lindex $phaselist 0]
3032    set ptype [string trim [hapinfo $hist $phase proftype]]
3033    set htype [string range $expmap(htype_$hist) 2 2]
3034    set nterms [hapinfo $hist $phase profterms]
3035   
3036    pack [frame $w.0 -bd 6 -relief groove  -bg beige \
3037            ] -side top -expand yes -fill both
3038    grid [label $w.0.a \
3039            -text "Setting profile terms: $title" \
3040            -bg beige] -row 0 -column 0 -columnspan 10
3041    grid [label $w.0.b -text "Function type $ptype"  -bg beige]  -row 1 -column 0
3042    grid [label $w.0.c -text "  Peak cutoff" -bg beige] -row 1 -column 3 
3043    grid [entry $w.0.d -width 10 ]  -row 1 -column 4
3044    set entrylist {}
3045    lappend entrylist "pcut $w.0.d"
3046
3047    set col -1
3048    set row 1
3049    set lbls "dummy [GetProfileTerms $phase $hist [expr abs($ptype)]]"
3050    pack [frame $w.1 -bd 6 -relief groove  -bg beige \
3051            ] -side top -expand yes -fill both
3052    for { set num 1 } { $num <= $nterms } { incr num } {
3053        set term {}
3054        catch {set term [lindex $lbls $num]}
3055        if {$term == ""} {set term $num}
3056        incr col
3057        grid [label $w.1.l${num} -text "$term" -bg beige] \
3058                -row $row -column $col
3059        incr col
3060        grid [entry $w.1.ent${num} \
3061                -width 14] -row $row -column $col
3062        lappend entrylist "pterm$num $w.1.ent${num}"   
3063        if {$col > 6} {set col -1; incr row}
3064    }
3065    pack [frame $w.b -bg beige] -fill x -expand yes -side top
3066    grid [button $w.b.2 -text Continue \
3067            -command "SetEditProfile [list $entrylist] [list $phaselist] \
3068            [list $histlist] $w"] -row 0 -column 1
3069    grid [button $w.b.3 -text Cancel \
3070            -command "QuitEditProfile $w [list $entrylist]"] -row 0 -column 2
3071    grid [button $w.b.help -text Help -bg yellow \
3072            -command "MakeWWWHelp expgui5.html GlobalEdit"] \
3073            -row 0 -column 4
3074    grid columnconfig $w.b 0 -weight 1
3075    grid columnconfig $w.b 3 -weight 1
3076    bind $w <Key-F1> "MakeWWWHelp expgui5.html GlobalEdit"
3077    bind $w <Return> "QuitEditProfile $w [list $entrylist]"
3078
3079    # force the window to stay on top
3080    putontop $w
3081    focus $w.b.2
3082    tkwait window $w
3083    afterputontop
3084}
3085
3086proc SetEditProfile {entrylist phaselist histlist w} {
3087    global expgui
3088    foreach item $entrylist {
3089        set value [ [lindex $item 1] get ]
3090        if {$value != ""} {
3091            hapinfo $histlist $phaselist [lindex $item 0] set $value
3092            RecordMacroEntry "hapinfo [list $histlist] [list $phaselist] [lindex $item 0] set $value" 1
3093            incr expgui(changed)
3094            RecordMacroEntry "incr expgui(changed)" 0
3095            if $expgui(debug) {
3096                puts "hapinfo [list $phaselist] [list $histlist] [lindex $item 0] set $value"
3097            }
3098        }
3099    }
3100    destroy $w
3101}
3102
3103proc QuitEditProfile {w entrylist} {
3104    global expgui
3105    # lets find out if anything changed
3106    set changed 0
3107    foreach item $entrylist {
3108        if {[ [lindex $item 1] get ] != ""} {set changed 1; break}
3109    }
3110    if $changed {
3111        set decision [tk_dialog .changes "Abandon Changes" \
3112                "You have made changes to the Profile. Ok to abandon changes?" \
3113                warning 0 Abandon Keep]
3114        if !$decision {destroy $w}
3115    } else {
3116        destroy $w
3117    }
3118}
3119
3120# this is called to change the absorption correction mode and to
3121# change the absorption correction model.
3122proc editabsorption {} {
3123    global expgui expmap
3124    set histlist {}
3125    foreach n $expgui(curhist) {
3126        lappend histlist [lindex $expmap(powderlist) $n]
3127    }
3128    if {[llength $histlist] == 0} return
3129
3130    set w .abs
3131    catch {destroy $w}
3132    toplevel $w -bg beige
3133    if {$expgui(globalmode) != 0} {
3134        wm title $w "Global Edit Absorption/Reflectivity" 
3135    } else {
3136        wm title $w "Edit Absorption/Reflectivity"
3137    }
3138   
3139    pack [frame $w.0 -bd 6 -relief groove  -bg beige \
3140            ] -side top -expand yes -fill both
3141    if {[llength $histlist] > 1} {
3142        grid [label $w.0.a \
3143            -text "Changing settings for histograms [CompressList $histlist]" \
3144            -bg beige] -row 0 -column 0 -columnspan 10
3145    } else {
3146        grid [label $w.0.a \
3147            -text "Changing settings for histogram $histlist" \
3148            -bg beige] -row 0 -column 0 -columnspan 4
3149        #grid columnconfig $w.0 4 -weight 1
3150    }
3151    grid rowconfig $w.0 1 -min 10
3152    set hist [lindex $histlist 0]
3153
3154    grid [label $w.0.lb1 -text "Absorption Coefficient(s)" -bg beige] \
3155            -row 2 -column 1  -columnspan 2
3156    grid [label $w.0.lb1a -text "1" -bg beige] -row 3 -column 1
3157    set expgui(abs2box1) $w.0.lb2a
3158    grid [label $w.0.lb2a -text "2" -bg beige] -row 3 -column 2
3159    grid [label $w.0.lb3 -text Absorption\nFunction -bg beige] \
3160            -row 2 -column 6 -rowspan 2 -columnspan 2
3161    grid [entry $w.0.ent1 -textvariable expgui(abscor1) -width 15] \
3162            -row 4 -column 1
3163    set expgui(abs2box2) $w.0.ent2
3164    grid [entry $w.0.ent2 -textvariable expgui(abscor2) -width 15] \
3165            -row 4 -column 2 
3166    trace vdelete expgui(abstype) w AbsSetoptmsg
3167    eval tk_optionMenu $w.0.m1 expgui(abstype) 0 1 2 3 4
3168    trace variable expgui(abstype) w AbsSetoptmsg
3169    grid $w.0.m1 -row 4 -column 6 -columnspan 2
3170    grid [label $w.0.lb8 -textvariable expgui(opttxt) -bg beige \
3171          -wrap 300 -justify left] -row 5 -column 1  -sticky ne -columnspan 7
3172    grid rowconfig $w.0 5 -min 100
3173    # set the values, note the trace on abstype
3174    foreach var {abscor1 abscor2 abstype} {
3175        set expgui($var) [histinfo $hist $var]
3176    }
3177
3178    pack [frame $w.b -bg beige] -fill x -expand yes -side top
3179    grid [button $w.b.2 -text Continue -command "AbsSaveEdit $w [list $histlist]"] \
3180            -row 0 -column 1
3181    grid [button $w.b.3 -text Cancel \
3182            -command "destroy $w"] -row 0 -column 2
3183    grid [button $w.b.help -text Help -bg yellow \
3184            -command "MakeWWWHelp expgui3.html EditAbsorption"] \
3185            -row 0 -column 4
3186    grid columnconfig $w.b 0 -weight 1
3187    grid columnconfig $w.b 3 -weight 1
3188    bind $w <Key-F1> "MakeWWWHelp expgui3.html EditAbsorption"
3189    bind $w <Return> "destroy $w"
3190
3191    # force the window to stay on top
3192    putontop $w
3193
3194    focus $w.b.2
3195    tkwait window $w
3196    afterputontop
3197}
3198
3199proc AbsSetoptmsg {args} {
3200    global expgui
3201    array set opttxt {
3202        0 "Correction for cylindrical samples [Lobanov & Alte da Veiga]. OK for all data types, but not for Bragg-Brentano flat-plate geometry. Set term 1 to mu*R/lambda (TOF: mu*R for lambda=1). For CW x-ray/neutron, do not refine!"
3203        1 "Wavelength-dependent correction for container penetration. Use with TOF & Energy Disp x-ray only."
3204        2 "Surface roughness correction [Pitschke, Hermann & Muttern]. Use with flat-plate reflection geometry (usually Bragg-Brentano) only."
3205        3 "Surface roughness correction, [Suortti]. Use with flat-plate reflection geometry (usually Bragg-Brentano) only."
3206        4 "Flat plate samples in transmission mode. OK for all data types, but not Bragg-Brentano geometry. Term 2 is angle w/r to beam (usually 0). For CW, do not refine."
3207    }
3208    set expgui(opttxt) ""
3209    catch {set expgui(opttxt) [set opttxt($expgui(abstype))]}
3210    switch $expgui(abstype) {
3211        0 -
3212        1 {
3213            $expgui(abs2box1) config -fg gray
3214            $expgui(abs2box2) config -state disabled -fg gray
3215        } 
3216        2 -
3217        3 -
3218        4 {
3219            $expgui(abs2box1) config -fg black
3220            $expgui(abs2box2) config -state normal -fg black
3221        }
3222        default {
3223            set expgui(opttxt) "Please select an absorption function"
3224        }
3225    }
3226}
3227proc AbsSaveEdit {top histlist} {
3228    global expgui expmap
3229    # sanity check: look at the histogram type
3230    set h [lindex $histlist 0]
3231    if {[string range $expmap(htype_$h) 2 2] == "T"} {set flag 1}
3232    if {[string range $expmap(htype_$h) 1 2] == "NC"} {set flag 2}
3233    if {[string range $expmap(htype_$h) 1 2] == "XC" && \
3234            [histinfo $h lam2] != 0.0} {set flag 3}
3235    if {[string range $expmap(htype_$h) 1 2] == "XC" && \
3236            [histinfo $h lam2] == 0.0} {set flag 4}
3237    if {[string range $expmap(htype_$h) 1 2] == "XE"} {set flag 5}
3238
3239    set msg {}
3240    if {$expgui(abstype) == 0 && ($flag == 3 || $flag == 4)} {
3241        set msg "Mode 0 is appropriate for cylindrical (Debye-Scherrer) geometry only"
3242    } elseif {$expgui(abstype) == 1 && ($flag != 1 && $flag != 5)} {
3243        set msg "Mode 1 is appropriate for wavelength-dispersive (TOF/E.D. X-ray) data only"
3244    } elseif {($expgui(abstype) == 2 || $expgui(abstype) == 3) \
3245            && $flag != 3 && $flag != 4} {
3246        set msg "Mode 1 is appropriate for reflection geometry flat-plate (typically Bragg-Brentano) data only"
3247    } elseif {$expgui(abstype) == 4 && $flag <= 3} {
3248        set msg "Mode 4 is appropriate for flat-plate samples in transmission"
3249    }
3250    if {$msg != ""} {
3251        set result [\
3252                MyMessageBox -parent $top -title "Sanity check" \
3253                -type okcancel -default cancel \
3254                -icon warning -helplink "expgui3.html AbsorptionSanity" \
3255                -message "$msg  -- are you sure you want to do this?"]
3256        if {$result == "cancel"} return
3257    }
3258
3259    # validate abscor1 & abscor2 (if needed)
3260    set msg {}
3261    if {![validreal expgui(abscor1) 15 8]} {
3262        set msg "Term 1 is invalid"
3263    }
3264    if {$expgui(abstype) > 1} {
3265        if {![validreal expgui(abscor2) 15 8]} {
3266            if {$msg != ""} {append msg "\n"}
3267            append msg "Term 2 is invalid"
3268        }
3269    }
3270    if {$msg != ""} {
3271        MyMessageBox -parent $top -title "Entry error" \
3272                -type ok -default ok \
3273                -icon warning -helplink "" \
3274                -message "Invalid data entered. Please correct.\n$msg"
3275        return
3276    }
3277   
3278    histinfo $histlist abstype set $expgui(abstype)
3279    RecordMacroEntry "histinfo [list $histlist] abstype set $expgui(abstype)" 0
3280    histinfo $histlist abscor1 set $expgui(abscor1)
3281    RecordMacroEntry "histinfo [list $histlist] abscor1 set $expgui(abscor1)" 0
3282    if {$expgui(abstype) > 1} {
3283        histinfo $histlist abscor2 set $expgui(abscor2)
3284        RecordMacroEntry "histinfo [list $histlist] abscor2 set $expgui(abscor2)" 0
3285    } else {
3286        histinfo $histlist abscor2 set 0.
3287        RecordMacroEntry "histinfo [list $histlist] abscor2 set 0." 0
3288    }
3289    # turn off refinement, just in case they didn't read
3290    if {($expgui(abstype) == 0 || $expgui(abstype) == 1 || $expgui(abstype) == 4) \
3291            && ($flag != 1 && $flag != 5)} {
3292        histinfo $histlist absref set 0
3293        RecordMacroEntry "histinfo [list $histlist] absref set 0" 0
3294    }
3295    incr expgui(changed)
3296    RecordMacroEntry "incr expgui(changed)" 0
3297    destroy $top
3298}
3299
3300##############################################################################
3301##                               #############################################
3302## END OF THE PROCEDURES SECTION #############################################
3303##                               #############################################
3304##############################################################################
3305
3306# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
3307# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<                          <<<<<<<<<<<<<<<<<<<
3308# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<   BEGIN:  GUI SECTION    >>>>>>>>>>>>>>>>>>>
3309# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>                          >>>>>>>>>>>>>>>>>>>
3310# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
3311# A frame for menu items at top of display
3312set expgui(fm) [frame .fm -relief raised -borderwidth 2 -width 150 -height 40]
3313# Pack the menu frame.
3314pack $expgui(fm) -fill x -side top -anchor n
3315
3316# create a button bar
3317pack [frame .bar -relief raised -bd 2 -bg beige] -fill x -side top -anchor n
3318
3319# Creating the notebook and panes
3320
3321# create an array element describing each notebook page
3322# element 0 -- pane name
3323#         1 -- Label on frame
3324#         2 -- initialization command
3325#         3 -- update command
3326#         4 -- 0/1 Use 1 if pane should be disabled in when all histograms
3327#                are selected in global mode, 0 otherwise
3328#         5 -- Web page for pane
3329#         6 -- name anchor on Web page for pane
3330set expgui(notebookpagelist) {
3331    {lsFrame     "LS Controls" \
3332            "" \
3333            SetupExtractHist \
3334            0  expgui1.html ""}
3335    {phaseFrame   Phase        \
3336            "" \
3337            {SelectOnePhase $expgui(curPhase)} \
3338            0  expgui2.html ""}
3339    {histFrame    Powder \
3340            MakeHistPane \
3341            DisplayHistogram \
3342            1  expgui3.html ""}
3343    {singFrame   Single \
3344            "source  [file join $expgui(scriptdir) single.tcl]; MakeSinglePane" \
3345            DisplaySingle \
3346            1  expguiSing.html ""}
3347    {fracFrame    Scaling \
3348            MakeScalingPane \
3349            DisplayFrac \
3350            0  expgui4.html ""}
3351    {profFrame    Profile \
3352            MakeProfilePane \
3353            DisplayProfile \
3354            1  expgui5.html ""}
3355    {consFrame    "Re/Constraints" \
3356            "source [file join $expgui(scriptdir) atomcons.tcl]; MakeConstraintsPane" \
3357            DisplayConstraintsPane \
3358            0  expgui6.html ""}
3359    {orientFrame  "MD Pref Orient" \
3360            MakeOrientPane \
3361            DisplayOrient \
3362            0  expgui7.html MD}
3363    {odfFrame  "SH Pref Orient" \
3364            "source [file join $expgui(scriptdir) odf.tcl]; MakeODFPane" \
3365            DisplayODFPane \
3366            0  expgui7.html ODF}
3367}
3368
3369pack [NoteBook .n -bd 2] -expand yes -fill both
3370# this should not be needed, but for some reason NoteBook is not
3371# using the optionDB
3372catch {.n configure -font [option get .n font Canvas]}
3373foreach item $expgui(notebookpagelist) {
3374    set frm [lindex $item 0]
3375    set expgui($frm) [\
3376            .n insert end $frm -text [lindex $item 1] \
3377            -createcmd "set expgui(pagenow) $frm; [lindex $item 2]" \
3378            -raisecmd "set expgui(pagenow) $frm; [lindex $item 3]"]
3379
3380    # at this time expgui(frameactionlist) is generated
3381    # from expgui(notebookpagelist), but in the future it might
3382    # make sense to use expgui(notebookpagelist) directly
3383    lappend expgui(frameactionlist) "$frm [list [lindex $item 3]]"
3384   
3385    # panes to disable in global "all" mode
3386    if {[lindex $item 4]} {
3387        lappend expgui(GlobalModeAllDisable) "$frm \{.n itemconfigure $frm\}"
3388    }
3389}
3390# procedure to disable tabs when phases or histograms are not defined
3391proc StageTabUse {args} {
3392    global expgui
3393    # reset everything
3394    foreach item [lrange $::expgui(notebookpagelist) 0 end] {
3395        set frm [lindex $item 0]
3396        .n itemconfigure $frm -state normal
3397    }
3398    # disable the unallowed pages in all mode
3399    if {$expgui(globalmode) == 6} {
3400        foreach pair $expgui(GlobalModeAllDisable) {
3401            if {$expgui(pagenow) == [lindex $pair 0]} {
3402                RaisePage lsFrame
3403            }
3404            eval [lindex $pair 1] -state disabled
3405        }
3406    } else {
3407        foreach pair $expgui(GlobalModeAllDisable) {
3408            eval [lindex $pair 1] -state normal
3409        }
3410    }
3411    # no phases are present, one must add a phase 1st
3412    if {[llength $::expmap(phaselist)] == 0} {
3413        foreach item [lrange $::expgui(notebookpagelist) 2 end] {
3414            set frm [lindex $item 0]
3415            .n itemconfigure $frm -state disabled
3416        }
3417        return
3418    }
3419    # do any of the phases have atoms?
3420    set flag 1
3421    foreach phase $::expmap(phaselist) {
3422        if {[array names ::expmap atomlist_$phase] != ""} {
3423            if {[llength $::expmap(atomlist_$phase)] > 0} {
3424                set flag 0
3425                break
3426            }
3427        }
3428    }
3429    # no atoms are present, one must add at least one before continuing
3430    if $flag {
3431        foreach item [lrange $::expgui(notebookpagelist) 2 end] {
3432            set frm [lindex $item 0]
3433            .n itemconfigure $frm -state disabled
3434        }
3435        return
3436    }
3437
3438    # no data is present, one must add a histogram next
3439    if {[llength $::expmap(nhst)] == 0} {
3440        foreach item [lrange $::expgui(notebookpagelist) 4 end] {
3441            set frm [lindex $item 0]
3442            .n itemconfigure $frm -state disabled
3443        }
3444        return
3445    }
3446}
3447# expgui(mapstat) is set by mapexp when it is called
3448# mapexp will be called when the .EXP file is changed (addition of phases, atoms or histograms)
3449trace variable expgui(mapstat) w StageTabUse
3450
3451# this is used to bring up the selected frame
3452proc RaisePage {nextpage} {
3453    global expgui
3454    set expgui(pagenow) $nextpage
3455    .n see $nextpage
3456    .n raise $nextpage
3457}
3458
3459# resize the notebook to fit all the tabs and the largest page
3460proc ResizeNotebook {} {
3461    global expgui
3462    .n compute_size
3463}
3464
3465#----------------------------------------------------------------------------
3466proc MakePhasePane {} {
3467    #\/ \/ \/ \/ \/ \/ \/ BEGINNING OF PHASE PANE CODE \/ \/ \/ \/ \/ \/ \/
3468    global expgui entryvar entrybox entrycmd
3469    frame $expgui(phaseFrame).top
3470    set frameLatt [frame $expgui(phaseFrame).frameLatt]
3471    #  This is a big frame in the Phase notebook pane to hold atomic data.
3472    set fbig [frame $expgui(phaseFrame).fbig -width 180 \
3473            -relief raised -borderwidth 4 -class Coord]
3474    #  This is a frame just below the big frame: for edits
3475    set frame3 [frame $expgui(phaseFrame).frame3 -width 100 \
3476            -relief raised -borderwidth 4 -bg $expgui(bkgcolor1)]
3477
3478    grid $expgui(phaseFrame).top -sticky news -row 0 -column 0 
3479    grid $frameLatt -sticky news -row 2 -column 0 
3480    grid $fbig -sticky news -row 3 -column 0 
3481    # give extra space to the atoms box
3482    grid columnconfigure $expgui(phaseFrame) 0 -weight 1
3483    grid rowconfigure $expgui(phaseFrame) 3 -weight 1
3484    grid $frame3 -sticky news -row 4 -column 0 
3485    grid columnconfigure $expgui(phaseFrame) 0 -weight 1
3486    grid rowconfigure $expgui(phaseFrame) 3 -weight 1
3487    grid [frame  $expgui(phaseFrame).top.ps] -column 0 -row 0 -sticky w
3488    # this is where the buttons will go
3489    pack [label $expgui(phaseFrame).top.ps.0 -text "No Phases"] -side left
3490   
3491    grid [label $expgui(phaseFrame).top.lA -text title: \
3492            -fg blue ] -column 1 -row 0 -sticky e
3493    grid [entry $expgui(phaseFrame).top.lB -textvariable entryvar(phasename) \
3494            -fg blue -width 45] -column 2 -row 0 -sticky e
3495    grid columnconfigure $expgui(phaseFrame).top 1 -weight 1
3496    # ------------- Lattice Parameter Box ------------------
3497    set row 0
3498    foreach col {2 4 6} var {a b c} lbl {a b c} {
3499        grid [label $frameLatt.l$var -text $lbl] \
3500                -column $col -row $row -padx 5 -sticky e
3501        incr col
3502        grid [label $frameLatt.e$var -textvariable entryvar($var) \
3503                -relief groove -bd 2 -width 10] \
3504                -column $col -row $row -padx 5
3505#       grid [entry $frameLatt.e$var -textvariable entryvar($var) -width 10] \
3506#           -column $col -row $row -padx 5
3507#       set entrybox($var) $frameLatt.e$var
3508    }
3509    incr row
3510    foreach col {2 4 6} var {alpha beta gamma} lbl {a b g} {
3511        grid [label $frameLatt.l$var -text $lbl] \
3512                -column $col -row $row -padx 5 -sticky e
3513        set font [$frameLatt.l$var cget -font]
3514        $frameLatt.l$var config -font "Symbol [lrange $font 1 end]"
3515
3516        incr col
3517        grid [label $frameLatt.e$var -textvariable entryvar($var)\
3518                -relief groove -bd 2 -width 10] \
3519            -column $col -row $row -padx 5
3520#       grid [entry $frameLatt.e$var -textvariable entryvar($var) -width 10] \
3521#           -column $col -row $row -padx 5
3522#       set entrybox($var) $frameLatt.e$var
3523    }
3524   
3525    grid [button $frameLatt.edit -text "Edit\nCell" -command EditCellConstants] \
3526            -column 8 -row 0 -rowspan 2 -padx 5 -sticky e
3527    grid [label $frameLatt.lr -text "Refine Cell"] -column 9 -row 0 -padx 5 -sticky e
3528    grid [label $frameLatt.ld -text "Cell damping"] -column 9 -row 1 -padx 5 -sticky e
3529    set cFlag [checkbutton $frameLatt.c -text "" -variable entryvar(cellref)]
3530    grid $cFlag -column 10 -row 0 -padx 5 -sticky e
3531    tk_optionMenu $frameLatt.om entryvar(celldamp) 0 1 2 3 4 5 6 7 8 9
3532    grid $frameLatt.om -column 10 -row 1 -padx 5 -sticky e
3533    grid [label $frameLatt.phasetype -textvariable expgui(phasetype) -fg blue] \
3534            -column 1 -row 0 -rowspan 2
3535    if [file executable $expgui(exptool)] {
3536        grid [button $expgui(phaseFrame).frameLatt.newp \
3537                -text "Add\nPhase" -padx 1.5m -command MakeAddPhaseBox \
3538                ] -column 0 -row 0 -rowspan 2 -sticky w
3539    }
3540    grid columnconfig $frameLatt  1 -weight 1
3541    grid columnconfig $frameLatt  0 -weight 1
3542    #-------------- Begin Atom Coordinates Box  ------------------------------
3543    grid [listbox  $fbig.title -height 1 -relief flat \
3544            -exportselection 0 -bg lightgrey -fg black \
3545            -selectforeground black -selectbackground lightgrey] \
3546            -row 0 -column 0 -sticky ew
3547    set expgui(atomtitle) $fbig.title
3548    bind $expgui(atomtitle) <Button-1> {
3549        set i [lsearch {number type mult x y z occupancy} $expgui(asorttype)]
3550        incr i
3551        set expgui(asorttype) [lindex {number type mult x y z occupancy number} $i]
3552        DisplayAllAtoms $expgui(curPhase)
3553    }
3554    bind $expgui(atomtitle) <Button-3> {set expgui(asorttype) number; DisplayAllAtoms $expgui(curPhase)}
3555
3556    $expgui(atomtitle) configure -selectmode extended
3557    grid [listbox   $fbig.lbox -height 10 \
3558            -exportselection 0 \
3559            -xscrollcommand " $fbig.bscr set"\
3560            -yscrollcommand " $fbig.rscr set"\
3561            ] -row 1 -column 0 -sticky news
3562    set expgui(atomlistbox) $fbig.lbox
3563    $expgui(atomlistbox) configure -selectmode extended
3564    grid [scrollbar $fbig.bscr -orient horizontal \
3565            -command "move2boxesX \" $fbig.title $fbig.lbox \" " \
3566            ] -row 2 -column 0 -sticky ew
3567    grid [scrollbar $fbig.rscr  -command "$fbig.lbox yview" \
3568            ] -row 1 -column 1 -sticky ns
3569    # give extra space to the atoms box
3570    grid columnconfigure $fbig 0 -weight 1
3571    grid rowconfigure $fbig 1 -weight 1
3572   
3573    #   BIND mouse in editbox
3574    bind $expgui(atomlistbox) <ButtonRelease-1>   editRecord
3575    bind $expgui(atomlistbox) <Button-3>   SelectAllAtoms
3576   
3577    #-------------- End Atoms Section  ---------------------------------
3578
3579    # --------------------------- Begin Edit Box ------------------------
3580    grid [set expgui(EditingAtoms) [label $frame3.top -bg $expgui(bkgcolor1) -fg blue]] \
3581            -column 0 -row 0 -padx 2 -pady 3 -columnspan 10 -sticky w
3582    if [file executable $expgui(exptool)] {
3583        button $frame3.newa -text "Add New Atoms" \
3584                -bg $expgui(bkgcolor1) -highlightthickness 0 \
3585                -command {MakeAddAtomsBox $expgui(curPhase)}
3586        grid $frame3.newa -column 11 -row 0
3587        set expgui(AddAtomBut) $frame3.newa
3588    }
3589    button [set expgui(atomxform) $frame3.xa] \
3590            -bg $expgui(bkgcolor1) -highlightthickness 0 \
3591            -command {MakeXformAtomsBox $expgui(curPhase)}
3592    grid $expgui(atomxform) -column 11 -row 1 -sticky ew
3593
3594    set f3l1 [label $frame3.l1 -text "Refinement Flags:" -bg $expgui(bkgcolor1)]
3595    grid $f3l1 -column 0 -row 1 -padx 2 -sticky nsw -pady 3
3596    foreach lbl {X U F} var {xref uref fref} col {1 2 3} {
3597        grid [checkbutton $frame3.cf$col \
3598                -text $lbl -variable entryvar($var) \
3599                -bg $expgui(bkgcolor1) -highlightthickness 0 \
3600                -activebackground $expgui(bkgcolor1)] \
3601                -column $col -row 1 -padx 4 -pady 3 -sticky w
3602    }
3603    set f3l4 [label $frame3.l4 -text "  Damping:" -bg $expgui(bkgcolor1)]
3604    grid $f3l4 -column 4 -row 1 -padx 2 -sticky nsw -pady 3
3605   
3606    set col 4
3607    foreach var {xdamp udamp fdamp} num {2 3 4} lbl {X U F} {
3608        grid [label $frame3.lom$num -text $lbl \
3609                -bg $expgui(bkgcolor1)] \
3610                -column [incr col] -row 1 -padx 2 -pady 3 -sticky w
3611        tk_optionMenu $frame3.om$num entryvar($var) 0 1 2 3 4 5 6 7 8 9
3612        $frame3.om$num config -highlightthickness 0
3613        grid $frame3.om$num -column [incr col] -row 1 -padx 2 -pady 3 -sticky w
3614    }
3615    set expgui(atomreflbl) "$frame3.l1 $frame3.l4 $frame3.lom2 $frame3.lom3 $frame3.lom4 "
3616    set expgui(atomref) "$frame3.cf1 $frame3.cf2 $frame3.cf3 $frame3.om2 $frame3.om3 $frame3.om4"
3617   
3618    set coords [frame $frame3.coords  -width 100 -borderwidth 0  -bg $expgui(bkgcolor1)]
3619    grid $coords -column 0 -row 6 -columnspan 12 -sticky nsew
3620   
3621    set f3l1 [label $frame3.coords.l1 -text "Label" -bg $expgui(bkgcolor1)]
3622    grid $f3l1 -column 0 -row 4 -padx 2 -sticky nsw -pady 3
3623    set expgui(atomlabels) $f3l1
3624
3625    set f3e1 [entry  $frame3.coords.e1 -textvariable entryvar(label) -width 6]
3626    grid $f3e1 -column 1 -row 4 -padx 2 -sticky nsw -pady 3
3627    set expgui(atomentry) $f3e1
3628
3629    set f3l8 [label $frame3.coords.l8 -text "Coordinates" -bg $expgui(bkgcolor1)]
3630    grid $f3l8 -column 2 -row 4 -padx 2 -sticky nsw -pady 3
3631    lappend expgui(atomlabels) $f3l8
3632    set f3l11 [label $frame3.coords.l11 -text "Occupancy" -bg $expgui(bkgcolor1)]
3633    grid $f3l11 -column 6 -row 4 -padx 2 -sticky nsw -pady 3
3634    lappend expgui(atomlabels) $f3l11
3635
3636    foreach var {x y z frac} col {3 4 5 7} {
3637        set entrybox($var) [entry $frame3.coords.e$var \
3638                -textvariable entryvar($var) -width 10]
3639        grid $entrybox($var) -column $col -row 4 -padx 2 -sticky nsw -pady 3
3640        lappend expgui(atomentry) $entrybox($var)
3641    }
3642
3643
3644    set f3f31 [frame $frame3.f3f31  -width 100 -borderwidth 0 -bg $expgui(bkgcolor1)]
3645    grid $f3f31 -column 0 -row 7 -columnspan 12
3646    set expgui(anisolabels) {}
3647    foreach lbl {13 14 15 16 17 18} txt {Uiso U22 U33 U12 U13 U23} {
3648        lappend expgui(anisolabels)  [\
3649                label $f3f31.l$lbl -text $txt -bg $expgui(bkgcolor1)
3650        ]
3651    }
3652    set expgui(anisoentry) {}
3653    foreach i {e13 e14 e15 e16 e17 e18} var {U11 U22 U33 U12 U13 U23} { 
3654        lappend expgui(anisoentry) [\
3655                entry $f3f31.$i -textvariable entryvar($var) \
3656                -width 10]
3657        set entrybox($var) $f3f31.$i
3658    }
3659   
3660    set col 0
3661    foreach item1 $expgui(anisolabels) item2 $expgui(anisoentry) {
3662        grid $item1 -column $col -row 0 -sticky nsw -pady 3
3663        incr col
3664        grid $item2 -column $col -row 0 -sticky nsw -pady 3
3665        incr col
3666    }
3667    # --------------------------- End Edit Box -------------------------
3668   
3669    #/\ /\ /\ /\ /\ /\ /\ END OF PHASE PANE CODE /\ /\ /\ /\ /\ /\ /\ /\ /
3670    # resize in case the pane needs more space
3671    ResizeNotebook
3672}
3673
3674# called to create a window for editing unit cell constants
3675proc EditCellConstants {} {
3676    global expgui entrybox
3677    set spg [phaseinfo $expgui(curPhase) spacegroup]
3678    set laueaxis [GetLaue $spg]
3679    set vary ""
3680    set equivL ""
3681    set equivA ""
3682    switch -exact $laueaxis {
3683        1bar {set vary "a b c alpha beta gamma"}
3684        2/ma {set vary "a b c alpha"}
3685        2/mb {set vary "a b c beta"}
3686        2/mc {set vary "a b c gamma"}
3687        mmm  {set vary "a b c"}
3688        4/m  -
3689        4/mmm {set vary "a c"; set equivL "a b"} 
3690        3barR     -
3691        "3bar mR" {
3692            set vary "a alpha"
3693            set equivL "a b c"
3694            set equivA "alpha beta gamma"
3695        }
3696        3bar    -
3697        3barm1  -
3698        3bar1m  -
3699        6/m     -
3700        6/mmm  {set vary "a c";set equivL "a b"}
3701        "m 3"  -
3702        m3m    {set vary a;set equivL "a b c"}
3703        default {
3704            MyMessageBox -parent . -title "Laue problem" \
3705                    -message "Error processing Laue code: $laueaxis\nError in space group \"$spg\"?\nUnable to edit cell. Fix or use EXPEDT." \
3706                    -icon warning -type OK -default ok \
3707                    -helplink "expguierr.html BadLaue"
3708        }
3709    }
3710    set row 0
3711    set w .cell
3712    toplevel $w -bg beige
3713    wm title $w "Edit Cell Parameters" 
3714#    bind $w <Key-F1> "MakeWWWHelp expgui3.html EditBackground"
3715    bind $w <Return> "set expgui(temp) 1; destroy $w"
3716    pack [label $w.l1 -bg yellow -anchor center -justify center \
3717            -text "Edit unit cell parameters for phase #$expgui(curPhase)" \
3718            ] -side top -expand yes -fill both
3719    pack [label $w.l2 -bg beige -justify left \
3720            -text "title: [phaseinfo $expgui(curPhase) name]\nSpace group: $spg\nLaue class: $laueaxis" \
3721            ] -side top -expand yes -fill both
3722    pack [frame $w.0 -bd 6 -relief groove  -bg beige \
3723            ] -side top -expand yes -fill both
3724    pack [frame $w.b -bg beige] -fill x -expand yes -side top
3725    grid [button $w.b.2 -text Continue -command "set expgui(temp) 1; destroy $w"] -row 0 -column 1
3726    grid [button $w.b.3 -text Cancel \
3727            -command "set expgui(temp) 0; destroy $w"] -row 0 -column 2
3728#    grid [button $w.b.help -text Help -bg yellow \
3729#           -command "MakeWWWHelp expgui3.html EditBackground"] \
3730#           -row 0 -column 4
3731
3732    global tmpvar
3733    trace variable tmpvar w TestCellEdit
3734    foreach ent {a b c alpha beta gamma} {
3735        set tmpvar($ent) [phaseinfo $expgui(curPhase) $ent]
3736    }
3737
3738    set frameLatt $w.0
3739    foreach col {2 4 6} var {a b c} lbl {a b c} {
3740        grid [label $frameLatt.l$var -text $lbl -bg beige] \
3741                -column $col -row $row -padx 5 -sticky e
3742        incr col
3743        if {[lsearch $equivL $var] == -1} {
3744            set v $var
3745        } else {
3746            set v [lindex $equivL 0]
3747        }
3748        if {[lsearch $vary $var] == -1} {
3749            grid [label $frameLatt.e$var -textvariable tmpvar($v) \
3750                    -width 10 -bg beige] \
3751                    -column $col -row $row -padx 5
3752        } else {
3753            grid [entry $frameLatt.e$var -textvariable tmpvar($v) \
3754                    -width 10] -column $col -row $row -padx 5
3755            set entrybox($var) $frameLatt.e$var 
3756        }
3757    }
3758    incr row
3759    foreach col {2 4 6} var {alpha beta gamma} lbl {a b g} {
3760        grid [label $frameLatt.l$var -text $lbl -bg beige] \
3761                -column $col -row $row -padx 5 -sticky e
3762        set font [$frameLatt.l$var cget -font]
3763        $frameLatt.l$var config -font "Symbol [lrange $font 1 end]"
3764
3765        incr col
3766        if {[lsearch $equivA $var] == -1} {
3767            set v $var
3768        } else {
3769            set v [lindex $equivA 0]
3770        }
3771        if {[lsearch $vary $var] == -1} {
3772            grid [label $frameLatt.e$var -textvariable tmpvar($v)\
3773                    -width 10 -bg beige] \
3774                    -column $col -row $row -padx 5
3775        } else {
3776            grid [entry $frameLatt.e$var -textvariable tmpvar($v) \
3777            -width 10] -column $col -row $row -padx 5
3778            set entrybox($var) $frameLatt.e$var 
3779        }
3780    }
3781    putontop $w
3782    tkwait window $w
3783    afterputontop
3784    global entryvar
3785    set change 0
3786    if {$expgui(temp)} {
3787        foreach var {a b c} {
3788            if {[lsearch $equivL $var] == -1} {
3789                set v $var
3790            } else {
3791                set v [lindex $equivL 0]
3792            }
3793            catch {
3794                expr [set val $tmpvar($v)]
3795                if {[phaseinfo $expgui(curPhase) $var] != $val} {
3796                    phaseinfo $expgui(curPhase) $var set $val
3797                    RecordMacroEntry "phaseinfo $expgui(curPhase) $var set $val" 0
3798                    set entryvar($var) $val
3799                    incr expgui(changed)                   
3800                    set change 1
3801                }
3802            }
3803        }
3804        foreach var {alpha beta gamma} {
3805            if {[lsearch $equivA $var] == -1} {
3806                set v $var
3807            } else {
3808                set v [lindex $equivA 0]
3809            }
3810            catch {
3811                expr [set val $tmpvar($v)]
3812                if {[phaseinfo $expgui(curPhase) $var] != $val} {
3813                    phaseinfo $expgui(curPhase) $var set $val
3814                    RecordMacroEntry "phaseinfo $expgui(curPhase) $var set $val" 0
3815                    set entryvar($var) $val
3816                    incr expgui(changed)                   
3817                    set change 1
3818                }
3819            }
3820        }
3821        RecordMacroEntry "incr expgui(changed)" 0
3822        if {$change} {
3823            # set the powpref warning (1 = suggested)
3824            if {$expgui(needpowpref) == 0} {set expgui(needpowpref) 1}
3825            append expgui(needpowpref_why) "\tCell parameters were changed\n"
3826        }
3827    }
3828    unset tmpvar
3829}
3830
3831# highlight errors in unit cell constants
3832proc TestCellEdit {var elem mode} {
3833    global tmpvar entrybox
3834    if {[catch {expr $tmpvar($elem)} errmsg]} {
3835        catch {$entrybox($elem) config -fg red}
3836    } else {
3837        catch {$entrybox($elem) config -fg black}
3838    }
3839}
3840
3841#-----------------------------------------------------------------------------
3842proc MakeHistPane {} {
3843    #v v v v v v v v v v  BEGINNING OF HISTOGRAM PANE CODE v v v v v v v v v v
3844    global expgui
3845   
3846    grid columnconfigure $expgui(histFrame) 0 -weight 1
3847    grid rowconfigure $expgui(histFrame) 1 -weight 1
3848    grid rowconfigure $expgui(histFrame) 2 -weight 1
3849    grid rowconfigure $expgui(histFrame) 3 -weight 1
3850
3851    grid [frame $expgui(histFrame).hs -class HistList] \
3852            -column 0 -row 0 -rowspan 10 -sticky nsew
3853    MakeHistBox $expgui(histFrame).hs
3854    bind $expgui(histFrame).hs.lbox <ButtonRelease-1>  {
3855        set expgui(curhist) [$expgui(histFrame).hs.lbox curselection]
3856        DisplayHistogram
3857    }
3858    bind $expgui(histFrame).hs.lbox <Button-3>  {
3859        if $expgui(globalmode) {
3860            $expgui(histFrame).hs.lbox selection set 0 end
3861            set expgui(curhist) [$expgui(histFrame).hs.lbox curselection]
3862            DisplayHistogram
3863        }
3864    }
3865   
3866    frame $expgui(histFrame).top -borderwidth 4 -relief groove
3867    grid [label $expgui(histFrame).top.txt] -row 0 -column 0
3868    foreach item {backBox diffBox absBox} num {2 3 4} title {Background "Diffractometer Constants" "Absorption/Reflectivity Correction"} {
3869        TitleFrame $expgui(histFrame).$item  \
3870            -borderwidth 4 -side left -relief groove -text $title
3871        set expgui($item) [$expgui(histFrame).$item getframe]
3872        grid $expgui(histFrame).$item -column 1 -row $num -sticky nsew
3873        grid rowconfigure $expgui(histFrame) $num -minsize 100
3874    }
3875    grid [frame $expgui(histFrame).bb] -column 1 -row 6
3876    if [file executable $expgui(exptool)] {
3877        button $expgui(histFrame).bb.newh -text "Add New\nHistogram" \
3878                -command MakeAddHistBox
3879        grid $expgui(histFrame).bb.newh -column 0 -row 1
3880    }
3881    button $expgui(histFrame).bb.excl \
3882            -text "Set Data Limits &\nExcluded Regions" -command excledit
3883    grid $expgui(histFrame).bb.excl -column 1 -row 1
3884
3885    button $expgui(histFrame).bb.use -text "Set Histogram\nUse Flags" \
3886            -command SetHistUseFlags
3887    grid $expgui(histFrame).bb.use -column 2 -row 1
3888
3889    # BACKGROUND information.
3890    # <<<<<<<<<<<<<<<<<<<<<<<<< BACKGROUND  <<<<<<<<<<<<<<<<<<<<<
3891    grid [frame $expgui(backBox).frm1 ] -row 0 -column 0  -columnspan 11
3892    grid [label $expgui(backBox).frm1.lBGType \
3893            -textvariable expgui(backtypelbl)] \
3894            -row 1 -column 0 -sticky nws  -padx 2 -pady 3
3895    grid [label $expgui(backBox).frm1.lBGTerms \
3896            -textvariable expgui(backtermlbl)] \
3897            -row 1 -column 1 -sticky nws  -padx 2 -pady 3
3898    grid [button $expgui(backBox).frm1.edit -textvariable expgui(bkglbl) \
3899            -command editbackground] \
3900            -row 1 -column 2 -columnspan 3 -sticky w -padx 2 -pady 3
3901    grid [frame $expgui(backBox).frm2 ] \
3902            -row 1 -column 0 -columnspan 11 -sticky e
3903    grid [label $expgui(backBox).frm2.lfBG -text "  Refine background" ] \
3904            -row 2 -column 1 -sticky news -padx 4 -pady 3
3905    grid [checkbutton $expgui(backBox).frm2.rfBG -text "" \
3906            -variable  entryvar(bref) ] \
3907            -row 2 -column 2 -sticky news -padx 4 -pady 3
3908    grid [label $expgui(backBox).frm2.lBGDamp -text Damping ] \
3909            -row 2 -column 3 -sticky w    -padx 2 -pady 3
3910    tk_optionMenu $expgui(backBox).frm2.om  entryvar(bdamp) 0 1 2 3 4 5 6 7 8 9
3911    grid $expgui(backBox).frm2.om \
3912            -row 2 -column 4 -sticky news -padx 4 -pady 3 -sticky e
3913    # Absorption information.
3914    grid [label $expgui(absBox).rf1 -text "  Refine Abs./Refl." ] \
3915            -row 2 -column 1 -sticky news -padx 4 -pady 3
3916    grid [checkbutton $expgui(absBox).rf2 -text "" \
3917            -variable  entryvar(absref) ] \
3918            -row 2 -column 2 -sticky news -padx 4 -pady 3
3919    grid [label $expgui(absBox).d1 -text Damping ] \
3920            -row 2 -column 3 -sticky w    -padx 2 -pady 3
3921    tk_optionMenu $expgui(absBox).d2  entryvar(absdamp) 0 1 2 3 4 5 6 7 8 9
3922    grid $expgui(absBox).d2 \
3923            -row 2 -column 4 -sticky news -padx 4 -pady 3 -sticky e
3924    grid [button $expgui(absBox).edit -textvariable expgui(abslbl) \
3925            -command editabsorption] \
3926            -row 2 -column 5 -sticky w -padx 2 -pady 3
3927
3928    #^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^END OF HISTOGRAM PANE CODE ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
3929    # insert the histograms & resize in case the pane needs more space   
3930    sethistlist
3931    ResizeNotebook
3932}
3933###############################################################################
3934proc MakeScalingPane {} {
3935    #v v v v v v v v v v  BEGINNING OF SCALING PANE CODE v v v v v v v v v v
3936    global expgui entryvar entrybox
3937
3938    pack [frame $expgui(fracFrame).hs -class HistList] \
3939            -side left -expand y -fill both
3940    MakeHistBox $expgui(fracFrame).hs
3941    bind $expgui(fracFrame).hs.lbox <ButtonRelease-1> {
3942        set expgui(curhist) [$expgui(fracFrame).hs.lbox curselection]
3943        DisplayFrac
3944    }
3945    bind $expgui(fracFrame).hs.lbox <Button-3>  {
3946        if $expgui(globalmode) {
3947            $expgui(fracFrame).hs.lbox selection set 0 end
3948            set expgui(curhist) [$expgui(fracFrame).hs.lbox curselection]
3949            DisplayFrac
3950        }
3951    }
3952
3953    pack [frame $expgui(fracFrame).f1] -fill both -expand true
3954    # Create a large canvas area containing a frame for each phase in the data set.
3955    # The canvas and vertical scrollbar are inside a frame called f1
3956    TitleFrame $expgui(fracFrame).f1.scaleBox \
3957        -borderwidth 4 -text "Scale Factor"
3958    #       -borderwidth 4 -width 600 -height 100 -label "Scale Factor"
3959    grid $expgui(fracFrame).f1.scaleBox -column 0 -row 0 -sticky nsew -columnspan 2
3960    set expgui(scaleBox)  [$expgui(fracFrame).f1.scaleBox getframe]
3961    grid [label $expgui(scaleBox).histSFLabel -text Scale] \
3962        -row 1 -column 0 -sticky nws  -padx 2 -pady 3
3963    grid [entry $expgui(scaleBox).ent1 -textvariable entryvar(scale) -width 15] \
3964            -row 1 -column 1 -sticky ew -padx 4 -pady 3
3965    set entrybox(scale) $expgui(scaleBox).ent1
3966
3967    button $expgui(scaleBox).but1 -text "Set Globally" \
3968            -command "editglobalparm histinfo scale {Scale Factor}"
3969
3970    grid [label $expgui(scaleBox).histSFRLabel -text " Refine"] \
3971            -row 1 -column 2 -sticky nws  -padx 2 -pady 3
3972    grid [checkbutton $expgui(scaleBox).rf -variable entryvar(sref)] \
3973            -row 1 -column 3 -sticky news -padx 4 -pady 3
3974    grid [label $expgui(scaleBox).lD1 -text "Damping"] \
3975            -row 1 -column 4 -sticky w    -padx 2 -pady 3
3976    tk_optionMenu $expgui(scaleBox).om entryvar(sdamp) 0 1 2 3 4 5 6 7 8 9
3977    grid $expgui(scaleBox).om \
3978            -row 1 -column 5 -sticky news -padx 4 -pady 3
3979    grid columnconfigure $expgui(scaleBox) 6  -weight 1
3980   
3981    grid [TitleFrame $expgui(fracFrame).f1.phaseFrac -bd 4 \
3982              -text "Phase Fractions" -relief groove] \
3983        -sticky news -row 1 -column 0 -columnspan 2
3984    set PhaseFractBox [$expgui(fracFrame).f1.phaseFrac getframe]
3985    grid columnconfigure $expgui(fracFrame).f1 0 -weight 1
3986    grid rowconfigure $expgui(fracFrame).f1 1 -weight 1
3987   
3988    grid [set expgui(FracBox) [canvas $PhaseFractBox.fracBox \
3989            -scrollregion {0 0 5000 500} \
3990            -yscrollcommand "$PhaseFractBox.yscroll set" \
3991            -width 500 -height 350 -bg lightgrey]] \
3992            -sticky  news -row 1 -column 0
3993    grid [scrollbar $PhaseFractBox.yscroll \
3994            -command "$expgui(FracBox) yview" \
3995            -orient vertical] \
3996            -sticky ns -row 1 -column 1
3997    frame $expgui(FracBox).f -bd 0
3998    $expgui(FracBox) create window 0 0 -anchor nw  -window $expgui(FracBox).f
3999
4000    # the rest of the page is created in DisplayFrac
4001
4002    # insert the histograms & resize in case the pane needs more space
4003    sethistlist
4004    ResizeNotebook
4005    # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ END OF SCALING PANE CODE ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
4006}
4007###############################################################################
4008proc MakeProfilePane {} {
4009    global expgui
4010    # v v v v v v v v v v BEGINNING OF PROFILE PANE CODE v v v v v v v v v v v
4011    pack [frame $expgui(profFrame).hs -class HistList] \
4012            -side left -expand y -fill both
4013    MakeHistBox $expgui(profFrame).hs
4014    bind $expgui(profFrame).hs.lbox <ButtonRelease-1> {
4015        set expgui(curhist) [$expgui(profFrame).hs.lbox curselection]
4016        DisplayProfile
4017    }
4018    bind $expgui(profFrame).hs.lbox <Button-3>  {
4019        if $expgui(globalmode) {
4020            $expgui(profFrame).hs.lbox selection set 0 end
4021            set expgui(curhist) [$expgui(profFrame).hs.lbox curselection]
4022            DisplayProfile
4023        }
4024    }
4025
4026    # Create a large canvas area containing a frame for each phase in the data set.
4027    # The canvas and vertical scrollbar are inside a frame called f1
4028    pack [frame $expgui(profFrame).f1] -fill both -expand true
4029    grid [set expgui(ProfileBox) [canvas $expgui(profFrame).f1.profileBox \
4030            -scrollregion {0 0 5000 500} -width 500 -height 350 -bg lightgrey]] \
4031            -sticky  news -row 0 -column 0
4032    grid [scrollbar $expgui(profFrame).f1.yscroll -orient vertical] \
4033            -sticky ns -row 0 -column 1
4034   
4035    $expgui(ProfileBox) config -yscrollcommand "$expgui(profFrame).f1.yscroll set"
4036    $expgui(profFrame).f1.yscroll config -command { $expgui(ProfileBox) yview }
4037   
4038    grid columnconfigure $expgui(profFrame).f1 1 -weight 1
4039    grid rowconfigure $expgui(profFrame).f1 0 -weight 1
4040    frame $expgui(ProfileBox).f -bd 0
4041    $expgui(ProfileBox) create window 0 0 -anchor nw  -window $expgui(ProfileBox).f
4042   
4043    # insert the histograms & resize in case the pane needs more space
4044    sethistlist
4045    ResizeNotebook
4046    # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ END OF PROFILE PANE CODE ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
4047}
4048
4049##############################################################################
4050# v v v v v v v v v v BEGINNING OF LS PANE CODE v v v v v v v v v v v v v
4051array set printopts {
4052    0 "Print the reciprocal metric tensor changes"
4053    1 "Print the correlation matrix"
4054    2 "Print the Least-Squares matrices and vectors"
4055    4 "Print the linear constraint matrices"
4056    5 "Print the applied  shifts and shift factors"
4057    6 "Print the reciprocal metric tensor Var-Covar terms"
4058    7 "Print all parameters for each cycle"
4059    8 "Print summary shift/esd data after last cycle"
4060    9 "Print zero/unit pole figure constraint terms"
4061    10 "Output parameter name, value & esd to file"
4062}
4063pack [frame $expgui(lsFrame).hs -class HistList] \
4064        -side left -expand y -fill both
4065MakeHistBox $expgui(lsFrame).hs
4066bind $expgui(lsFrame).hs.lbox <ButtonRelease-1> {
4067    set expgui(curhist) [$expgui(lsFrame).hs.lbox curselection]
4068    SetupExtractHist
4069}
4070bind $expgui(lsFrame).hs.lbox <Button-3>  {
4071    if $expgui(globalmode) {
4072        $expgui(lsFrame).hs.lbox selection set 0 end
4073        set expgui(curhist) [$expgui(lsFrame).hs.lbox curselection]
4074        SetupExtractHist
4075    }
4076}
4077
4078pack [frame $expgui(lsFrame).f1] -fill both -expand true
4079set row 0
4080grid [label $expgui(lsFrame).f1.his1 -pady 6 -text "Last History:"] -row $row -column 0
4081grid [label $expgui(lsFrame).f1.his2 -relief groove -bd 2 -pady 6 \
4082        -textvariable expgui(last_History)] \
4083        -row $row -column 1 -columnspan 5 -sticky w
4084incr row
4085grid [label $expgui(lsFrame).f1.tit1 -pady 6 -text "Title:"] -row $row -column 0
4086grid [entry $expgui(lsFrame).f1.tit2 \
4087        -textvariable entryvar(title) -width 48] \
4088        -row $row -column 1 -columnspan 5 -sticky w
4089set entrycmd(title) "expinfo title"
4090
4091incr row
4092grid rowconfigure $expgui(lsFrame).f1 $row -weight 1
4093incr row
4094grid [frame $expgui(lsFrame).f1.b -bd 4 -relief groove] \
4095        -row $row -column 0 -columnspan 2 -pady 3  -sticky s
4096grid [label $expgui(lsFrame).f1.b.lcyc -text "Number of Cycles"] -row 0 -column 0
4097grid [entry $expgui(lsFrame).f1.b.ecyc -width 3 \
4098        -textvariable entryvar(cycles)] -row 0 -column 1
4099set entrybox(cycles) $expgui(lsFrame).f1.b.ecyc
4100
4101grid [frame $expgui(lsFrame).f1.cv -bd 4 -relief groove] \
4102        -row $row -column 2 -sticky ew
4103grid [label $expgui(lsFrame).f1.cv.l -text "Convergence Criterion"] \
4104        -row 0 -column 0 -columnspan 2
4105grid [label $expgui(lsFrame).f1.cv.v -textvariable expgui(convlbl)] -row 1 -column 0
4106grid [scale $expgui(lsFrame).f1.cv.s -orient horizontal \
4107        -from -200 -to 200 -showvalue 0 -command SetConv -resolution 10 \
4108        -variable expgui(convg)] -row 1 -column 1
4109
4110incr row
4111grid [menubutton $expgui(lsFrame).f1.lprint -textvariable expgui(printopt) \
4112        -menu $expgui(lsFrame).f1.lprint.menu -bd 4 -relief raised \
4113        ] -row $row -column 0 -columnspan 2 
4114menu $expgui(lsFrame).f1.lprint.menu
4115foreach num [lsort -integer [array names printopts]] {
4116    $expgui(lsFrame).f1.lprint.menu add checkbutton \
4117        -label "$printopts($num) ([expr int(pow(2,$num))])"\
4118        -variable entryvar(printopt$num)
4119}
4120
4121grid [frame $expgui(lsFrame).f1.marq -bd 4 -relief groove] \
4122        -row $row -column 2 -sticky ew
4123grid [label $expgui(lsFrame).f1.marq.l -text "Marquardt Damping"] \
4124        -row 0 -column 0 -columnspan 2
4125grid [label $expgui(lsFrame).f1.marq.v -textvariable expgui(marq)] \
4126        -row 1 -column 0
4127grid [scale $expgui(lsFrame).f1.marq.s -orient horizontal \
4128        -from 1.0 -to 9.99 -showvalue 0 -command SetMarq -resolution 0.01 \
4129        -variable expgui(marq)] -row 1 -column 1
4130
4131incr row
4132grid [frame $expgui(lsFrame).f1.d -bd 4 -relief groove] \
4133        -row $row -column 2 -sticky ew
4134grid [label $expgui(lsFrame).f1.d.lmbw -text "LS matrix bandwidth"] -row 0 -column 0
4135grid [entry $expgui(lsFrame).f1.d.embw -width 4 \
4136        -textvariable entryvar(mbw)] -row 0 -column 1
4137set entrybox(mbw) $expgui(lsFrame).f1.d.embw
4138
4139incr row
4140grid rowconfigure $expgui(lsFrame).f1 $row -weight 1
4141
4142incr row
4143grid [TitleFrame $expgui(lsFrame).f1.a -bd 4 -relief groove \
4144          -text "Reflection Intensity Extraction" \
4145         ] -row $row -column 0 -columnspan 6
4146set expgui(FobsExtractFrame) [$expgui(lsFrame).f1.a getframe]
4147
4148grid [frame $expgui(FobsExtractFrame).c -bd 4 -relief groove] \
4149        -row 0 -column 8 -columnspan 3 -sticky ens
4150grid [label $expgui(FobsExtractFrame).c.fol -text "Extract Fobs"] \
4151        -row 0 -column 2
4152grid [checkbutton $expgui(FobsExtractFrame).c.foc \
4153        -variable entryvar(fobsextract)] -row 0 -column 3
4154
4155grid [frame $expgui(FobsExtractFrame).d -bd 4 -relief groove] \
4156        -row 0 -column 3 -columnspan 5 -sticky ens
4157grid [label $expgui(FobsExtractFrame).d.fol -text "LeBail damping"] \
4158        -row 0 -column 2
4159tk_optionMenu $expgui(FobsExtractFrame).d.d entryvar(LBdamp) \
4160        0 1 2 3 4 5 6 7 8 9
4161grid $expgui(FobsExtractFrame).d.d -row 0 -column 3
4162incr row
4163grid rowconfigure $expgui(lsFrame).f1 $row -weight 1
4164
4165
4166foreach num {1 2 3 4 5 6 7 8 9} {
4167    grid [label $expgui(FobsExtractFrame).l$num -text $num] -row 1 -column $num
4168    grid [radiobutton $expgui(FobsExtractFrame).cc$num \
4169            -command "HistExtractSet $num" \
4170            -variable expgui(Fextract$num) -value 0] \
4171            -row 2 -column $num
4172    grid [radiobutton $expgui(FobsExtractFrame).ca$num \
4173            -command "HistExtractSet $num" \
4174            -variable expgui(Fextract$num) -value 1] \
4175            -row 3 -column $num
4176    grid [radiobutton $expgui(FobsExtractFrame).cb$num \
4177            -command "HistExtractSet $num" \
4178            -variable expgui(Fextract$num) -value 2] \
4179            -row 4 -column $num
4180}
4181set expgui(ExtractSettingsRadiobuttons) $expgui(FobsExtractFrame).cc
4182lappend expgui(ExtractSettingsRadiobuttons) $expgui(FobsExtractFrame).ca
4183lappend expgui(ExtractSettingsRadiobuttons) $expgui(FobsExtractFrame).cb
4184
4185grid [label $expgui(FobsExtractFrame).t \
4186        -text "Extraction\nMethod" -anchor c] \
4187        -column 0 -row 0 -sticky n
4188grid [label $expgui(FobsExtractFrame).t0 -text "(Phase #)" -anchor c] \
4189        -column 10 -row 1 -sticky w
4190grid [label $expgui(FobsExtractFrame).t1 -text "Rietveld" -anchor c] -column 0 -row 2
4191grid [label $expgui(FobsExtractFrame).t2 -text "F(calc) Weighted" -anchor c] -column 0 -row 3
4192grid [label $expgui(FobsExtractFrame).t3 -text "Equally Weighted" -anchor c] -column 0 -row 4
4193grid [label $expgui(FobsExtractFrame).t2a -text "(Model biased)" -anchor c] -column 10 -row 3
4194grid [label $expgui(FobsExtractFrame).t3a -text "(Le Bail method)" -anchor c] -column 10 -row 4
4195
4196proc InitLSvars {} {
4197    global expgui
4198    set expgui(convg) [set expgui(convinit) [expinfo convg]]
4199    set expgui(convlbl) [format %5.2f [expr pow(10,$expgui(convg)/100.)]]
4200    set expgui(marq) [set expgui(marqinit) [expinfo marq]]
4201    set expgui(mbw) [set expgui(mbwinit) [expinfo mbw]]
4202}
4203proc SetConv {x} {
4204    global expgui
4205    if {$x != $expgui(convinit) && $expgui(changed) <= 0} {
4206        incr expgui(changed)
4207        RecordMacroEntry "incr expgui(changed)" 0
4208    }
4209    if {$expgui(changed)} {
4210        expinfo convg set $x
4211        RecordMacroEntry "expinfo convg set $x" 0
4212    }
4213    set expgui(convlbl) [format %5.2f [expr {pow(10,$x/100.)}]]
4214}
4215proc SetMarq {x} {
4216    global expgui
4217    if {$x != $expgui(marqinit) && $expgui(changed) <= 0} {
4218        incr expgui(changed)
4219        RecordMacroEntry "incr expgui(changed)" 0
4220    }
4221    if {$expgui(changed)} {
4222        expinfo marq set $x
4223        RecordMacroEntry "expinfo marq set $x" 0
4224    }
4225}
4226# ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ END OF LS PANE CODE ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
4227#-------------------------------------------------------------------------
4228#-------------------------------------------------------------------------
4229#vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv THE MENU BAR vvvvvvvvvvvvvvvvvvvvvv
4230#---- file menu button
4231menubutton $expgui(fm).file -text File -menu $expgui(fm).file.menu
4232menu $expgui(fm).file.menu
4233if $expgui(debug) {
4234    $expgui(fm).file.menu add command -label "Reset" -command "reset"
4235}
4236if {$expgui(shell)} {
4237    $expgui(fm).file.menu add command -label "Open" -command readnewexp
4238    $expgui(fm).file.menu add command -label "expnam" -command readnewexp
4239}
4240$expgui(fm).file.menu add command -label "Save" -underline 0 \
4241        -command savearchiveexp
4242foreach c {s S} {bind . <Alt-$c> [list savearchiveexp]}
4243$expgui(fm).file.menu add command -label "Save As" \
4244        -command "SaveAsFile"
4245$expgui(fm).file.menu add command -label "Reread .EXP file" \
4246        -command {rereadexp $expgui(expfile)}
4247
4248#---- help menu button
4249menubutton $expgui(fm).help -text Help -menu $expgui(fm).help.menu
4250menu $expgui(fm).help.menu
4251$expgui(fm).help.menu add command -command showhelp -underline 0 \
4252        -label "Help Summary"
4253$expgui(fm).help.menu add command -command MakeWWWHelp  \
4254        -label "Help on current pane"
4255$expgui(fm).help.menu add command -command "MakeWWWHelp menu" \
4256        -label "Help on menu"
4257if {$tcl_platform(platform) == "windows"} {
4258    $expgui(fm).help.menu add command -label "Open console" \
4259        -command {console show}
4260}
4261if {![catch {package require tkcon} errmsg]} {
4262    $expgui(fm).help.menu add command -label "Open tkcon console" \
4263        -command {tkcon show}
4264} elseif {[file exists [file join $expgui(scriptdir) tkcon tkcon.tcl]]} {
4265    $expgui(fm).help.menu add command -label "Open tkcon console" \
4266        -command {source [file join $expgui(scriptdir) tkcon tkcon.tcl]}
4267} else {
4268    $expgui(fm).help.menu add command -label "Turn on debug puts" \
4269        -command {set expgui(debug) 1}
4270}
4271# add update commands to menu
4272if {[file exists [file join  $expgui(gsasdir) .svn]]} {
4273    $expgui(fm).file.menu add command -command CheckAndDoUpdate -label "Update GSAS/EXPGUI"
4274} else {
4275    $expgui(fm).file.menu add command  -state disabled -label "Self-updating not installed"
4276}
4277foreach c {h H} {bind . <Alt-$c> [list showhelp]}
4278# define help actions
4279bind . <Key-F1> MakeWWWHelp
4280$expgui(fm).help.menu add command -label "About..." -command About
4281$expgui(fm).help.menu add command -label "Cite..." -command Cite
4282
4283#---- options menu button
4284menubutton $expgui(fm).option -text Options \
4285        -menu $expgui(fm).option.menu
4286menu $expgui(fm).option.menu
4287
4288if {$expgui(shell)} {
4289    $expgui(fm).option.menu add checkbutton  -label "Archive EXP" \
4290            -variable expgui(archive)
4291    $expgui(fm).option.menu add checkbutton  -label "Use DISAGL window" \
4292            -variable expgui(disaglSeparateBox)
4293    $expgui(fm).option.menu  add checkbutton -label "Autoload EXP" \
4294            -variable expgui(autoexpload)
4295    $expgui(fm).option.menu  add checkbutton -label "Prompt after GSAS run" \
4296            -variable expgui(execprompt)
4297    $expgui(fm).option.menu  add checkbutton -label "Iconify during GSAS" \
4298            -variable expgui(autoiconify)
4299    if {$tcl_platform(platform) == "windows" && \
4300            $tcl_platform(os) == "Windows 95"} {
4301        $expgui(fm).option.menu  add checkbutton -label "Autostart GRWND" \
4302                -variable expgui(autoGRWND)
4303    }
4304}
4305$expgui(fm).option.menu add cascade -menu  $expgui(fm).option.menu.asort \
4306        -label "Sort atoms by"
4307
4308set expgui(asorttype) number
4309menu $expgui(fm).option.menu.asort
4310foreach opt {number type mult x y z occupancy} {
4311    $expgui(fm).option.menu.asort add radiobutton -command {DisplayAllAtoms $expgui(curPhase)}\
4312            -label $opt -value $opt -variable expgui(asorttype) 
4313}
4314
4315$expgui(fm).option.menu add cascade -menu  $expgui(fm).option.menu.hsort \
4316        -label "Sort histograms by"
4317
4318set expgui(hsorttype) number
4319menu $expgui(fm).option.menu.hsort
4320$expgui(fm).option.menu.hsort add radiobutton -command sethistlist \
4321        -label number -value number -variable expgui(hsorttype) 
4322$expgui(fm).option.menu.hsort add radiobutton -command sethistlist \
4323        -label "Histogram type" -value type -variable expgui(hsorttype) 
4324$expgui(fm).option.menu.hsort add radiobutton -command sethistlist \
4325        -label "Bank #" -value bank -variable expgui(hsorttype) 
4326$expgui(fm).option.menu.hsort add radiobutton -command sethistlist \
4327        -label "Angle/Wavelength" -value angle -variable expgui(hsorttype) 
4328
4329#---- Global mode menu button
4330$expgui(fm).option.menu add cascade -menu $expgui(fm).option.menu.editmode \
4331        -label "Multiple hist. selection"
4332menu $expgui(fm).option.menu.editmode
4333$expgui(fm).option.menu.editmode add radiobutton  -label "Off" \
4334        -variable expgui(globalmode) -value 0 \
4335        -command sethistlist
4336$expgui(fm).option.menu.editmode add radiobutton  -label "All" \
4337        -variable expgui(globalmode) -value 6 \
4338        -command sethistlist
4339$expgui(fm).option.menu.editmode add radiobutton  -label "TOF" \
4340        -variable expgui(globalmode) -value 1 \
4341        -command sethistlist
4342$expgui(fm).option.menu.editmode add radiobutton  -label "CW Neutron" \
4343        -variable expgui(globalmode) -value 2  \
4344        -command sethistlist
4345$expgui(fm).option.menu.editmode add radiobutton  -label "Alpha12 Xray" \
4346        -variable expgui(globalmode) -value 3 \
4347        -command sethistlist
4348$expgui(fm).option.menu.editmode add radiobutton  -label "Monochromatic Xray" \
4349        -variable expgui(globalmode) -value 4 \
4350        -command sethistlist
4351$expgui(fm).option.menu.editmode add radiobutton  -label "Energy Disp Xray" \
4352        -variable expgui(globalmode) -value 5 \
4353        -command sethistlist
4354$expgui(fm).option.menu.editmode add separator
4355$expgui(fm).option.menu.editmode add checkbutton \
4356        -label "Group phases together" \
4357        -variable expgui(globalphasemode) \
4358        -command sethistlist
4359
4360set expgui(globalmode) 0
4361set expgui(globalphasemode) 1
4362
4363if {$tcl_platform(platform) == "unix"} {
4364    $expgui(fm).option.menu  add checkbutton -label "Override backspace" \
4365            -variable env(GSASBACKSPACE)
4366}
4367
4368$expgui(fm).option.menu add cascade -menu  $expgui(fm).option.menu.font \
4369        -label "Screen font"
4370menu $expgui(fm).option.menu.font
4371foreach f {10 11 12 13 14 16 18 20 22} {
4372    $expgui(fm).option.menu.font add radiobutton \
4373            -command {SetTkDefaultOptions $expgui(font); ResizeFont .; ResizeNotebook} \
4374        -label $f -value $f -variable expgui(font) -font "Helvetica -$f"
4375}
4376
4377$expgui(fm).option.menu  add checkbutton -label "Show EXPTOOL output" \
4378        -variable expgui(showexptool)
4379$expgui(fm).option.menu add command -label "Save Options" \
4380        -command "SaveOptions"
4381$expgui(fm).option.menu add command -label "Save Position" \
4382        -command "SavePosition"
4383pack $expgui(fm).file $expgui(fm).option -side left  -in $expgui(fm)
4384
4385if {$expgui(shell)} {
4386    foreach menu $expgui(menunames) {
4387        set m [string tolower $menu]
4388        pack [menubutton $expgui(fm).$m -text $menu \
4389                -menu $expgui(fm).$m.menu] -side left
4390        menu $expgui(fm).$m.menu
4391    }
4392}
4393pack $expgui(fm).help  -side right -in $expgui(fm)
4394
4395if {$expgui(shell)} {
4396    # add an export command to the last menu that gets filled in later
4397    $expgui(fm).$m.menu add  cascade -label "Coord Export" \
4398            -menu $expgui(fm).$m.menu.coordexp
4399    menu $expgui(fm).$m.menu.coordexp \
4400            -postcommand "BuildCoordExpMenu $expgui(fm).$m.menu.coordexp"
4401    $expgui(fm).$m.menu.coordexp add command -label "Building menu" \
4402            -state disabled
4403    $expgui(fm).$m.menu.coordexp add command -label "Please wait..." \
4404            -state disabled
4405
4406    $expgui(fm).$m.menu add  cascade -label "CIF Export" \
4407            -menu $expgui(fm).$m.menu.cifexp
4408    menu $expgui(fm).$m.menu.cifexp
4409    $expgui(fm).$m.menu.cifexp add command -label gsas2cif \
4410            -command "runGSASwEXP gsas2cif"
4411    $expgui(fm).$m.menu.cifexp add command -label FillTemplate \
4412            -command "exec $wishshell [file join $expgui(scriptdir) fillcif.tcl] \[file root \[file tail \$expgui(expfile)]]"
4413    $expgui(fm).$m.menu.cifexp add command -label CIFselect \
4414            -command {
4415        if {[info procs CIFselect] == ""} {
4416            source [file join $expgui(scriptdir) cifselect.tcl]
4417        }
4418        CIFselect $expgui(expfile)
4419    }
4420    # add the commands in expgui_menulist
4421    foreach menu [array names expgui_menulist ] {
4422        foreach cmd $expgui_menulist($menu) {
4423            set action {}
4424            set opt {}
4425            catch {set action [lindex $expgui_cmdlist($cmd) 0]}
4426            catch {set opt [lindex $expgui_cmdlist($cmd) 2]}
4427            if {$expgui(debug) && $action == ""} {puts "blank command for $cmd"}
4428            if {$action != "" && $action != "-"} {
4429                eval $expgui(fm).$menu.menu add command \
4430                        -label $cmd $opt -command [list [subst $action]]
4431                if {[lindex $opt 0] == "-underline"} {
4432                    catch {
4433                        set num [lindex $opt 1]
4434                        set key [string range $cmd $num $num]
4435                        bind . <Alt-[string tolower $key]> [subst $action]
4436                        bind . <Alt-[string toupper $key]> [subst $action]
4437                    }
4438                }
4439            }
4440        }
4441    }
4442}
4443
4444# Macro menu
4445$expgui(fm).macro.menu add checkbutton  -label "Record EXPGUI macro" \
4446    -variable expgui(RecordMacro)
4447$expgui(fm).macro.menu add command -label "Add comment to macro" \
4448    -command AddCommentMacroFile
4449$expgui(fm).macro.menu add command -label "Replay macro line-at-a-time" \
4450    -command {ReplayMacroFile 1}
4451$expgui(fm).macro.menu add command -label "Replay macro all at once" \
4452    -command {ReplayMacroFile 0}
4453$expgui(fm).macro.menu add checkbutton  -label "Show GSAS output in window" \
4454    -variable expgui(ShowGENLES)
4455bind . <Control-m> {set expgui(RecordMacro) [expr ! $expgui(RecordMacro)]}
4456set expgui(RecordMacro) 0
4457set expgui(MacroRunning) 0
4458set expgui(MacroStatus) "?"
4459set expgui(ShowGENLES) 1
4460trace variable expgui(RecordMacro) w SetRecordMacroOnOff
4461
4462# setup command help
4463foreach cmd [array names expgui_cmdlist] {
4464    set help {}
4465    catch {set help [lindex $expgui_cmdlist($cmd) 1]}
4466    if {$help == ""} {
4467        if {$expgui(debug)} {puts "no help for $cmd"}
4468    } else {
4469        # remove
4470        regsub -all \x09 $help " " help
4471        # preserve blank lines
4472        regsub -all \x0A\x0A $help "AAA1234567890AAA" help
4473        regsub -all \x0A $help " " help
4474        regsub -all "AAA1234567890AAA" $help \x0A\x0A help
4475        regsub -all " +" $help " " help
4476        set expgui_helplist($cmd) [string trim $help]
4477    }
4478}
4479if {$expgui(shell)} {
4480    # set up button bar
4481    foreach cmd $expgui(buttonlist) {
4482        set action {}
4483        catch {set action [lindex $expgui_cmdlist($cmd) 0]}
4484        if {$expgui(debug) && $action == ""} {puts "blank command for $cmd"}
4485        if {$action != ""} {
4486            pack [eval button .bar.$cmd -bg beige -activebackground yellow \
4487                    -padx 2m -pady 0 \
4488                    -text $cmd -command [list [subst $action]]] -side left
4489        }
4490    }
4491}
4492
4493if {$tcl_platform(os) == "Darwin"} {
4494#    $expgui(fm).file.menu add command -label "Create AppleScript" -command MakeAppleScript
4495    $expgui(fm).option.menu add checkbutton -label "Assign app to .EXP files" \
4496        -variable expgui(MacAssignApp)
4497}
4498$expgui(fm).file.menu add command -label "Exit"  -underline 1 -command catchQuit
4499foreach c {X x} {bind . <Alt-$c> [list catchQuit]}
4500#^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ END OF MENU DEFINITION ^^^^^^^^^^^^^^^^^^^
4501
4502# make the phase pane -- this must be done before setphases
4503# can be called (in loadexp)
4504MakePhasePane
4505
4506# handle indirect exits
4507wm protocol . WM_DELETE_WINDOW catchQuit
4508if {$tcl_platform(platform) != "windows"} {bind . <Control-c> catchQuit}
4509
4510set expgui(pagenow) ""
4511set expgui(curhist) {}
4512set expgui(selectedatomlist) {}
4513
4514loadexp $expgui(expfile)
4515
4516# reset the phase selection
4517set expgui(curPhase) {}
4518# select the first histogram in the list by default (if there are any)
4519if {[llength $expmap(histlistboxcontents)] > 0} {
4520    set expgui(curhist) 0
4521} else {
4522    set expgui(curhist) {}
4523}
4524
4525# execute any local commands for final initialization
4526eval $expgui(initstring)
4527
4528# resize the notebook to fit all the tabs and the largest page
4529ResizeNotebook
4530if {$expgui(resize)} {
4531    # this appears to be needed by OSX
4532    update
4533    #wm geom . [winfo reqwidth .]x[winfo reqheight .]
4534    wm geom . {}
4535}
4536# place the EXPGUI window
4537set xpos 50
4538catch {set xpos $expgui(xpos)}
4539set ypos 50
4540catch {set ypos $expgui(ypos)}
4541set poscntr "nsew"
4542catch {set poscntr $expgui(poscenter)}
4543LocateWindow "." $xpos $ypos $poscntr
4544update
4545RaisePage lsFrame
4546if {[CountHistory] > 200} {
4547    DeleteHistoryRecords "This .EXP file has [CountHistory] history records\nErasing most will speed EXPGUI"
4548}
Note: See TracBrowser for help on using the repository browser.