source: branches/sandbox/expgui @ 1021

Last change on this file since 1021 was 1021, checked in by chlake, 12 years ago

add disagl edit & viewer

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