source: trunk/expgui

Last change on this file was 1251, checked in by toby, 9 years ago

use svn ps svn:eol-style "native" * to change line ends

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