source: trunk/expgui @ 1033

Last change on this file since 1033 was 1033, checked in by toby, 13 years ago

fix writing of abscor2 on all platforms; show abs cor on Histogram panel

  • Property svn:keywords set to Author Date Revision Id
File size: 164.4 KB
Line 
1#!/bin/sh
2# the next line restarts this script using wish found in the path\
3exec wish "$0" "$@"
4# If this does not work, change the #!/usr/bin/wish line below
5# to reflect the actual wish location and delete all preceeding lines
6#
7# (delete here and above)
8#!/usr/bin/wish
9# $Id: expgui 1033 2010-10-28 02:08:37Z toby $
10set expgui(Revision) {$Revision: 1033 $ $Date: 2010-10-28 02:08:37 +0000 (Thu, 28 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        set expgui(abstypelbl) ""
1867        foreach var {bref bdamp absref absdamp} {
1868            set entrycmd($var) "histinfo [list $histlist] $var"
1869            set entryvar($var) [histinfo [lindex $histlist 0] $var]
1870        }
1871    } else {
1872        set hist $histlist
1873        set terms [histinfo $hist backterms]
1874        set expgui(backtermlbl) "($terms terms)"
1875        # background type 3 & 9 have gone away
1876        if {[histinfo $hist backtype] == 3 || [histinfo $hist backtype] == 9} {
1877            MyMessageBox -parent . -title "Background Change" \
1878                -type ok -default ok \
1879                -icon warning \
1880                -message "Background function #[histinfo $hist backtype] is no longer supported -- the function will now be changed to type #1 & the values reset"
1881            histinfo $histlist backtype set 1
1882            RecordMacroEntry "histinfo [list $histlist] backtype set 1" 0
1883            incr expgui(changed)
1884            for {set num 1 } { $num <= $terms } { incr num } {
1885                set var "bterm$num"
1886                histinfo $histlist $var set 0
1887                RecordMacroEntry "histinfo [list $histlist] $var set 0" 0
1888                incr expgui(changed)
1889            }
1890            RecordMacroEntry "incr expgui(changed)" 0
1891        }
1892        set expgui(backtypelbl) "Function type [histinfo $hist backtype]"
1893        foreach var {bref bdamp absref absdamp} {
1894            set entrycmd($var) "histinfo $hist $var"
1895            set entryvar($var) [eval $entrycmd($var)]
1896        }
1897        set abstype [histinfo $hist abstype]
1898        if {$abstype > 1} {
1899            set expgui(abstypelbl) "  Model #$abstype, values: [histinfo $hist abscor1], [histinfo $hist abscor2]"
1900        } else {
1901            set expgui(abstypelbl) "  Model #$abstype, value: [histinfo $hist abscor1]"
1902        }
1903    }
1904    # Top box
1905    catch {destroy $expgui(histFrame).pflag}
1906    if {$expgui(globalmode) != 0} {
1907        $expgui(histFrame).top.txt config \
1908                -text "Selected Histograms: [CompressList $histlist]"
1909        grid $expgui(histFrame).top -column 1 -row 0 -sticky nsew       
1910        set expgui(bkglbl) "Globally Edit Background"
1911        set expgui(abslbl) "Globally Edit Absorption"
1912    } else {
1913        grid forget $expgui(histFrame).top
1914        set expgui(bkglbl) "Edit Background"
1915        set expgui(abslbl) "Edit Abs./Refl."
1916        if {[llength $expmap(phaselist)] > 1} {
1917            TitleFrame $expgui(histFrame).pflag  \
1918                    -borderwidth 4 -side left -relief groove \
1919                    -text "Phase Flags"
1920            set expgui(pflag) [$expgui(histFrame).pflag getframe]
1921            grid $expgui(histFrame).pflag -column 1 -row 1 -sticky nsew
1922            grid rowconfigure $expgui(histFrame) 2 -minsize 35
1923            foreach p $expmap(phaselist) {
1924                pack [checkbutton $expgui(pflag).$p \
1925                        -command "GetPhaseFlags $hist" \
1926                        -variable expgui(pflag$p) -text $p] -side left
1927                if {[lsearch $expmap(phaselist_$hist) $p] == -1} {
1928                    set expgui(pflag$p) 0
1929                } else {
1930                    set expgui(pflag$p) 1
1931                }
1932            }
1933        }
1934    }
1935
1936    # diffractometer constants
1937    foreach var {lam1 lam2 kratio pola ipola ddamp zero \
1938            wref pref dcref daref ratref ttref zref } {
1939        set entrycmd($var) "histinfo [list $histlist] $var"
1940        set entryvar($var) [histinfo [lindex $histlist 0] $var]
1941    }
1942
1943    eval destroy [winfo children $expgui(diffBox)]
1944    if {$expgui(globalmode) == 0} {
1945        if {[string range $expmap(htype_$hist) 2 2] == "T"} {
1946        #------
1947        # TOF |
1948        #------
1949            grid [ label $expgui(diffBox).lDCrc -text "Refine DIFC" ] \
1950                    -column 1 -row 1
1951            grid [ checkbutton $expgui(diffBox).rfDCrc -variable entryvar(dcref) ] \
1952                    -column 2 -row 1
1953            grid [ label $expgui(diffBox).lDCdifc -text DIFC ] \
1954                    -column 3 -row 1 -sticky w
1955            grid [ entry $expgui(diffBox).eDCdifc -textvariable entryvar(lam1) \
1956                    -width 15 ] -column 4 -row 1
1957            set entrybox(lam1) $expgui(diffBox).eDCdifc
1958            #
1959            grid [ label $expgui(diffBox).lDCra -text "Refine DIFA" ] \
1960                    -column 1 -row 2
1961            grid [ checkbutton $expgui(diffBox).rfDCra -variable entryvar(daref) ] \
1962                    -column 2 -row 2
1963            grid [ label $expgui(diffBox).lDCdifa -text DIFA ] \
1964                    -column 3 -row 2
1965            grid [ entry $expgui(diffBox).eDCdifa -textvariable entryvar(lam2) \
1966                    -width 15 ] -column 4 -row 2
1967            set entrybox(lam2) $expgui(diffBox).eDCdifa
1968            #
1969            grid [ label $expgui(diffBox).lDCzero -text "Zero"] \
1970                    -column 3 -row 3
1971            grid [ entry $expgui(diffBox).eDCzero -textvariable entryvar(zero) \
1972                    -width 15 ] -column 4 -row 3
1973            set entrybox(zero) $expgui(diffBox).eDCzero
1974            grid [ label $expgui(diffBox).lDCzref -text "Refine zero" ] \
1975                    -column 1 -row 3 -sticky w
1976            grid [ checkbutton $expgui(diffBox).rfDCzref \
1977                    -variable entryvar(zref) ] -column 2 -row 3
1978        } elseif {[string range $expmap(htype_$hist) 1 2] == "NC"} { 
1979        #---------------
1980        # CW - neutron |
1981        #---------------
1982            grid [ label $expgui(diffBox).lDC1 -text "Refine wave" ] \
1983                    -column 1 -row 1
1984            grid [ checkbutton $expgui(diffBox).rfDC1 -variable entryvar(wref) ] \
1985                    -column 2 -row 1
1986            grid [ label $expgui(diffBox).lDCdifc -text wave ] \
1987                    -column 3 -row 1 -sticky w
1988            grid [ entry $expgui(diffBox).eDCdifc -textvariable entryvar(lam1) \
1989                    -width 15 ] -column 4 -row 1
1990            set entrybox(lam1) $expgui(diffBox).eDCdifc
1991            #
1992            grid [ label $expgui(diffBox).lDCzref -text "Refine zero" ] \
1993                    -column 1 -row 3 -sticky w
1994            grid [ checkbutton $expgui(diffBox).rfDCzref \
1995                    -variable entryvar(zref) ] -column 2 -row 3
1996            grid [ label $expgui(diffBox).lDCzero -text "Zero"] \
1997                    -column 3 -row 3
1998            grid [ entry $expgui(diffBox).eDCzero -textvariable entryvar(zero) \
1999                    -width 15 ] -column 4 -row 3
2000            set entrybox(zero) $expgui(diffBox).eDCzero
2001        } elseif {[string range $expmap(htype_$hist) 1 2] == "XC" && \
2002                [histinfo $hist lam2] == 0.0} {
2003        #--------------------------
2004        # CW - x-ray 1 wavelength |
2005        #--------------------------
2006            grid [ label $expgui(diffBox).lDC1 -text "Refine wave" ] \
2007                    -column 1 -row 1
2008            grid [ checkbutton $expgui(diffBox).rfDC1 -variable entryvar(wref) ] \
2009                    -column 2 -row 1
2010            grid [ label $expgui(diffBox).lDCdifc -text wave ] \
2011                    -column 3 -row 1 -sticky w
2012            grid [ entry $expgui(diffBox).eDCdifc -textvariable entryvar(lam1) \
2013                    -width 15 ] -column 4 -row 1
2014            set entrybox(lam1) $expgui(diffBox).eDCdifc
2015            #
2016            grid [ label $expgui(diffBox).lDCzref -text "Refine zero" ] \
2017                    -column 1 -row 3 -sticky w
2018            grid [ checkbutton $expgui(diffBox).rfDCzref \
2019                    -variable entryvar(zref) ] -column 2 -row 3
2020            grid [ label $expgui(diffBox).lDCzero -text "Zero"] \
2021                    -column 3 -row 3
2022            grid [ entry $expgui(diffBox).eDCzero -textvariable entryvar(zero) \
2023                    -width 15 ] -column 4 -row 3
2024            set entrybox(zero) $expgui(diffBox).eDCzero
2025            #
2026            grid [ label $expgui(diffBox).lDCpref -text "Refine POLA" ] \
2027                    -column 1 -row 4 -sticky w
2028            grid [ checkbutton $expgui(diffBox).rfDCpref \
2029                    -variable entryvar(pref) ] -column 2 -row 4
2030            grid [ label $expgui(diffBox).lDCpola -text POLA ] \
2031                    -column 3 -row 4
2032            grid [ entry $expgui(diffBox).eDCpola \
2033                    -textvariable entryvar(pola) -width 15 ] -column 4 -row 4
2034            set entrybox(pola) $expgui(diffBox).eDCpola
2035            grid [ label $expgui(diffBox).lDCipola -text "IPOLA" ] \
2036                    -column 5 -row 4
2037            grid [ entry $expgui(diffBox).eDCipola -width 2 \
2038                    -textvariable entryvar(ipola)] -column 6 -row 4
2039            set entrybox(ipola) $expgui(diffBox).eDCipola
2040        } elseif {[string range $expmap(htype_$hist) 1 2] == "XC"} {
2041        #---------------------------
2042        # CW - x-ray 2 wavelengths |
2043        #---------------------------
2044            grid [ label $expgui(diffBox).lDCdifc -text wavelengths ] \
2045                    -column 3 -row 1 -sticky w
2046            grid [ entry $expgui(diffBox).eDCdifc -textvariable entryvar(lam1) \
2047                    -width 15 ] -column 4 -row 1
2048            set entrybox(lam1) $expgui(diffBox).eDCdifc
2049            grid [ entry $expgui(diffBox).eDCdifa -textvariable entryvar(lam2) \
2050                    -width 15 ] -column 5 -row 1
2051            set entrybox(lam2) $expgui(diffBox).eDCdifa
2052            #
2053            grid [ label $expgui(diffBox).lDCrref -text "Refine ratio" ] \
2054                    -column 1 -row 2 -sticky w
2055            grid [ checkbutton $expgui(diffBox).rfDCrref \
2056                    -variable entryvar(ratref) ] -column 2 -row 2
2057            grid [ label $expgui(diffBox).lDCratio -text Ratio ] \
2058                    -column 3 -row 2
2059            grid [ entry $expgui(diffBox).eDCkratio \
2060                    -textvariable entryvar(kratio) \
2061                    -width 15 ] -column 4 -row 2
2062            set entrybox(kratio) $expgui(diffBox).eDCkratio
2063            #
2064            grid [ label $expgui(diffBox).lDCzero -text "Zero"] \
2065                    -column 3 -row 3
2066            grid [ entry $expgui(diffBox).eDCzero -textvariable entryvar(zero) \
2067                    -width 15 ] -column 4 -row 3
2068            grid [ label $expgui(diffBox).lDCzref -text "Refine zero" ] \
2069                    -column 1 -row 3 -sticky w
2070            set entrybox(zero) $expgui(diffBox).eDCzero
2071            grid [ checkbutton $expgui(diffBox).rfDCzref \
2072                    -variable entryvar(zref) ] -column 2 -row 3
2073            grid [ label $expgui(diffBox).lDCpref -text "Refine POLA" ] \
2074                    -column 1 -row 4 -sticky w
2075            grid [ checkbutton $expgui(diffBox).rfDCpref \
2076                    -variable entryvar(pref) ] -column 2 -row 4
2077            grid [ label $expgui(diffBox).lDCpola -text POLA ] \
2078                    -column 3 -row 4
2079            grid [ entry $expgui(diffBox).eDCpola \
2080                    -textvariable entryvar(pola) -width 15 ] -column 4 -row 4
2081            set entrybox(pola) $expgui(diffBox).eDCpola
2082            grid [ label $expgui(diffBox).lDCipola -text "IPOLA" ] \
2083                    -column 5 -row 4
2084            grid [ entry $expgui(diffBox).eDCipola -width 2 \
2085                    -textvariable entryvar(ipola)] -column 6 -row 4
2086            set entrybox(ipola) $expgui(diffBox).eDCipola
2087        } elseif {[string range $expmap(htype_$hist) 1 2] == "XE"} {
2088        #-------------
2089        # ED - x-ray |
2090        #-------------
2091            grid [ label $expgui(diffBox).lDC1 -text "Refine 2theta" ] \
2092                    -column 1 -row 1
2093            grid [ checkbutton $expgui(diffBox).rfDC1 -variable entryvar(ttref) ] \
2094                    -column 2 -row 1
2095            grid [ label $expgui(diffBox).lDCdifc -text 2Theta ] \
2096                    -column 3 -row 1 -sticky w
2097            grid [ entry $expgui(diffBox).eDCdifc -textvariable entryvar(lam1) \
2098                    -width 15 ] -column 4 -row 1
2099            set entrybox(lam1) $expgui(diffBox).eDCdifc
2100            #
2101            grid [ label $expgui(diffBox).lDCpref -text "Refine POLA" ] \
2102                    -column 1 -row 4 -sticky w
2103            grid [ checkbutton $expgui(diffBox).rfDCpref \
2104                    -variable entryvar(pref) ] -column 2 -row 4
2105            grid [ label $expgui(diffBox).lDCpola -text POLA ] \
2106                    -column 3 -row 4
2107            grid [ entry $expgui(diffBox).eDCpola \
2108                    -textvariable entryvar(pola) -width 15 ] -column 4 -row 4
2109            set entrybox(pola) $expgui(diffBox).eDCpola
2110            grid [ label $expgui(diffBox).lDCipola -text "IPOLA" ] \
2111                    -column 5 -row 4
2112            grid [ entry $expgui(diffBox).eDCipola -width 2 \
2113                    -textvariable entryvar(ipola)] -column 6 -row 4
2114            set entrybox(ipola) $expgui(diffBox).eDCipola
2115        }
2116    } elseif {$expgui(globalmode) == 1} {
2117        #-------------
2118        # Global TOF |
2119        #-------------
2120        grid [ label $expgui(diffBox).lDCrc -text "Refine DIFC" ] \
2121                -column 1 -row 1
2122        grid [ checkbutton $expgui(diffBox).rfDCrc -variable entryvar(dcref) ] \
2123                -column 2 -row 1
2124        grid [button $expgui(diffBox).bDCdifc -text "Set DIFC Globally" \
2125                -command "editglobalparm histinfo difc {DIFC}"] -column 3 -row 1
2126        #
2127        grid [ label $expgui(diffBox).lDCra -text "Refine DIFA" ] \
2128                -column 1 -row 2
2129        grid [ checkbutton $expgui(diffBox).rfDCra -variable entryvar(daref) ] \
2130                -column 2 -row 2
2131        grid [ button $expgui(diffBox).bDCdifa -text "Set DIFA Globally" \
2132                -command "editglobalparm histinfo difa {DIFA}"] -column 3 -row 2
2133        #
2134        grid [ label $expgui(diffBox).lDCzref -text "Refine zero" ] \
2135                -column 1 -row 3 -sticky w
2136        grid [ checkbutton $expgui(diffBox).rfDCzref \
2137                -variable entryvar(zref) ] -column 2 -row 3
2138        grid [ button $expgui(diffBox).bDCzero -text "Set ZERO Globally" \
2139                -command "editglobalparm histinfo zero {Zero}"] -column 3 -row 3
2140    } elseif {$expgui(globalmode) == 2} {
2141        #--------------------
2142        # Global CW neutron |
2143        #--------------------
2144        grid [ label $expgui(diffBox).lDC1 -text "Refine wave" ] \
2145                -column 1 -row 1
2146        grid [ checkbutton $expgui(diffBox).rfDC1 -variable entryvar(wref) ] \
2147                -column 2 -row 1
2148        grid [button $expgui(diffBox).bDCdifc -text "Set Wave Globally" \
2149                -command "editglobalparm histinfo lam1 Wavelength"] \
2150                -column 3 -row 1
2151        #
2152        grid [ label $expgui(diffBox).lDCzref -text "Refine zero" ] \
2153                -column 1 -row 3 -sticky w
2154        grid [ checkbutton $expgui(diffBox).rfDCzref \
2155                -variable entryvar(zref) ] -column 2 -row 3
2156        grid [button $expgui(diffBox).bDCzero -text "Set Zero Globally" \
2157                -command "editglobalparm histinfo zero Zero"] -column 3 -row 3
2158    } elseif {$expgui(globalmode) == 4} {
2159        #----------------------
2160        # Global CW mono xray |
2161        #----------------------
2162        grid [ label $expgui(diffBox).lDC1 -text "Refine wave" ] \
2163                -column 1 -row 1
2164        grid [ checkbutton $expgui(diffBox).rfDC1 -variable entryvar(wref) ] \
2165                -column 2 -row 1
2166        grid [button $expgui(diffBox).bDCdifc -text "Set Wave Globally" \
2167                -command "editglobalparm histinfo lam1 Wavelength"] \
2168                -column 3 -row 1
2169        #
2170        grid [ label $expgui(diffBox).lDCzref -text "Refine zero" ] \
2171                -column 1 -row 3 -sticky w
2172        grid [ checkbutton $expgui(diffBox).rfDCzref \
2173                -variable entryvar(zref) ] -column 2 -row 3
2174        grid [button $expgui(diffBox).bDCzero -text "Set Zero Globally" \
2175                -command "editglobalparm histinfo zero Zero"] -column 3 -row 3
2176        #
2177        grid [ label $expgui(diffBox).lDCpref -text "Refine POLA" ] \
2178                -column 1 -row 4 -sticky w
2179        grid [ checkbutton $expgui(diffBox).rfDCpref \
2180                -variable entryvar(pref) ] -column 2 -row 4
2181        grid [button $expgui(diffBox).bDCpola -text "Set POLA Globally" \
2182                -command "editglobalparm histinfo pola POLA"] -column 3 -row 4
2183        grid [button $expgui(diffBox).bDCipola -text "Set IPOLA Globally" \
2184                -command "editglobalparm histinfo ipola IPOLA"] -column 4 -row 4
2185    } elseif {$expgui(globalmode) == 3} {
2186        #------------------------
2187        # Global alpha 1,2 xray |
2188        #------------------------
2189        grid [button $expgui(diffBox).bDCl1 -text "Set Wave1 Globally" \
2190                -command "editglobalparm histinfo lam1 {Wavelength 1}"] \
2191                -column 3 -row 1
2192        grid [button $expgui(diffBox).bDCl2 -text "Set Wave2 Globally" \
2193                -command "editglobalparm histinfo lam2 {Wavelength 2}"] \
2194                -column 4 -row 1
2195        #
2196        grid [ label $expgui(diffBox).lDCratref -text "Refine Ratio" ] \
2197                -column 1 -row 2 -sticky w
2198        grid [ checkbutton $expgui(diffBox).rfDCratref \
2199                -variable entryvar(ratref) ] -column 2 -row 2
2200        grid [button $expgui(diffBox).bDCrrat -text "Set Ratio Globally" \
2201                -command "editglobalparm histinfo ratio {Wavelength Ratio}"] \
2202                -column 3 -row 2
2203        #
2204        grid [ label $expgui(diffBox).lDCzref -text "Refine zero" ] \
2205                -column 1 -row 3 -sticky w
2206        grid [ checkbutton $expgui(diffBox).rfDCzref \
2207                -variable entryvar(zref) ] -column 2 -row 3
2208        grid [button $expgui(diffBox).bDCzero -text "Set Zero Globally" \
2209                -command "editglobalparm histinfo zero Zero"] -column 3 -row 3
2210        #
2211        grid [ label $expgui(diffBox).lDCpref -text "Refine POLA" ] \
2212                -column 1 -row 4 -sticky w
2213        grid [ checkbutton $expgui(diffBox).rfDCpref \
2214                -variable entryvar(pref) ] -column 2 -row 4
2215        grid [button $expgui(diffBox).bDCpola -text "Set POLA Globally" \
2216                -command "editglobalparm histinfo pola POLA"] -column 3 -row 4
2217        grid [button $expgui(diffBox).bDCipola -text "Set IPOLA Globally" \
2218                -command "editglobalparm histinfo ipola IPOLA"] -column 4 -row 4
2219    } elseif {$expgui(globalmode) == 5} {
2220        #-----------------
2221        # Global ED xray |
2222        #-----------------
2223        grid [ label $expgui(diffBox).lDC1 -text "Refine 2theta" ] \
2224                -column 1 -row 1
2225        grid [ checkbutton $expgui(diffBox).rfDC1 -variable entryvar(ttref) ] \
2226                -column 2 -row 1
2227        grid [button $expgui(diffBox).bDCdifc -text "Set 2Theta Globally" \
2228                -command "editglobalparm histinfo ratio {Fixed 2Theta}"] \
2229                -column 3 -row 1
2230        #
2231        grid [ label $expgui(diffBox).lDCpref -text "Refine POLA" ] \
2232                -column 1 -row 4 -sticky w
2233        grid [ checkbutton $expgui(diffBox).rfDCpref \
2234                -variable entryvar(pref) ] -column 2 -row 4
2235        grid [button $expgui(diffBox).bDCpola -text "Set POLA Globally" \
2236                -command "editglobalparm histinfo pola POLA"] -column 3 -row 4
2237        grid [button $expgui(diffBox).bDCipola -text "Set IPOLA Globally" \
2238                -command "editglobalparm histinfo ipola IPOLA"] -column 4 -row 4
2239    }
2240    if {$expgui(globalmode) == 0} {
2241        grid [frame $expgui(diffBox).d] -column 5 -row 1 -rowspan 3 \
2242                -columnspan 2 -sticky e
2243    } else {
2244        grid [frame $expgui(diffBox).d] -column 4 -row 2 -rowspan 2 \
2245                -columnspan 2 -sticky e
2246    }
2247    grid [label $expgui(diffBox).d.lDamp -text "Damping  "] \
2248            -column 1 -row 1 
2249    tk_optionMenu $expgui(diffBox).d.om entryvar(ddamp) 0 1 2 3 4 5 6 7 8 9
2250    grid $expgui(diffBox).d.om -column 2 -row 1 
2251    grid columnconfigure $expgui(diffBox) 9  -weight 1
2252    grid columnconfigure $expgui(diffBox) 0  -weight 1
2253    update idletasks
2254    # enable traces on entryvar now
2255    set entrycmd(trace) 1
2256}
2257
2258# this gets the phase flags as set in the expgui(pflag*) elements
2259# (linked to phase flag checkbuttons) and the sets the "HST xx NPHAS" flags
2260# accordingly using SetPhaseFlag
2261proc GetPhaseFlags {hist} {
2262    global expmap expgui
2263    set plist {}
2264    foreach p $expmap(phaselist) {
2265        if {$expgui(pflag$p)} {lappend plist $p}
2266    }
2267    SetPhaseFlag $hist $plist
2268    RecordMacroEntry "SetPhaseFlag [list $hist] [list $plist]" 0
2269    incr expgui(changed)
2270    RecordMacroEntry "incr expgui(changed)" 0
2271    # set the powpref warning (1 = suggested)
2272    set expgui(needpowpref) 2
2273    set msg "Phase flags" 
2274    if {[string first $msg $expgui(needpowpref_why)] == -1} {
2275        append expgui(needpowpref_why) "\t$msg were changed\n"
2276    }
2277    mapexp
2278    # reset the phase selection
2279    set expgui(curPhase) {}
2280}
2281
2282#-----------------------------------------------------------------------
2283# populate the Scaling page
2284#-----------------------------------------------------------------------
2285proc DisplayFrac {} {
2286    global expgui entrycmd entryvar entrybox expmap
2287
2288    # trap if more than one histogram is selected unless global mode
2289    if {$expgui(globalmode) == 0 && [llength $expgui(curhist)] > 1} {
2290        set expgui(curhist) [lindex $expgui(curhist) 0] 
2291    }
2292
2293    # display the selected histograms
2294    $expgui(fracFrame).hs.lbox selection clear 0 end
2295    foreach h $expgui(curhist) {
2296        $expgui(fracFrame).hs.lbox selection set $h
2297    }
2298
2299    # disable traces on entryvar
2300    set entrycmd(trace) 0
2301
2302    # get histogram list
2303    set histlist {}
2304    foreach item $expgui(curhist) {
2305        lappend histlist [lindex $expmap(powderlist) $item]
2306    }
2307
2308    # must have at least one histogram selected here
2309    if {[llength $histlist] == 0} {
2310        foreach var {scale sref sdamp} {
2311            set entrycmd($var) ""
2312            set entryvar($var) ""
2313        }
2314        set parm [grid info $expgui(scaleBox).but1]
2315        if {$parm != ""} {
2316            grid forget  $expgui(scaleBox).but1
2317            eval grid $expgui(scaleBox).ent1 $parm
2318        }
2319        # destroy the contents of the frame
2320        set phaseFractf1 $expgui(FracBox).f
2321        eval destroy [winfo children $phaseFractf1]
2322        # reenable traces on entryvar
2323        set entrycmd(trace) 1
2324        return
2325    }
2326
2327    #--------------
2328    # Scale factor
2329    #--------------
2330    if {$expgui(globalmode) != 0} {
2331        foreach var {scale sref sdamp} {
2332            set entrycmd($var) "histinfo [list $histlist] $var"
2333            set entryvar($var) [histinfo [lindex $histlist 0] $var]
2334        }
2335        # reset scale to black
2336        catch {$entrybox(scale) config -fg black}
2337        set parm [grid info $expgui(scaleBox).ent1]
2338        if {$parm != ""} {
2339            grid forget  $expgui(scaleBox).ent1
2340            eval grid $expgui(scaleBox).but1 $parm
2341        }
2342    } else {
2343        set hist $histlist
2344        foreach var {scale sref sdamp} {
2345            set entrycmd($var) "histinfo $hist $var"
2346            set entryvar($var) [eval $entrycmd($var)]
2347        }
2348        # reset scale to black
2349        catch {$entrybox(scale) config -fg black}
2350        set parm [grid info $expgui(scaleBox).but1]
2351        if {$parm != ""} {
2352            grid forget  $expgui(scaleBox).but1
2353            eval grid $expgui(scaleBox).ent1 $parm
2354        }
2355    }
2356
2357    #----------------
2358    # Phase Fractions
2359    #----------------
2360    set phaseFractf1 $expgui(FracBox).f
2361    # destroy the contents of the frame
2362    eval destroy [winfo children $phaseFractf1]
2363    if {$expgui(globalmode) != 0} {
2364        set txt "Phase Fractions for Histograms: [CompressList $histlist]"
2365    } else {
2366        set txt "Phase Fractions"
2367    }
2368    $expgui(fracFrame).f1.phaseFrac configure -text $txt
2369    # Create the frame inside the canvas, One frame for each Phase.
2370    foreach i {1 2 3 4 5 6 7 8 9} {set phasehistlist($i) ""}
2371    foreach hist $histlist {
2372        foreach i $expmap(phaselist_$hist) {
2373            lappend phasehistlist($i) $hist
2374        }
2375    }
2376    foreach i {1 2 3 4 5 6 7 8 9} {
2377        if {[llength $phasehistlist($i)] == 0} continue
2378        set framePF [frame $phaseFractf1.pF$i -relief groove  -bd 4]
2379        grid $framePF -column 0 -row $i -sticky ew
2380        # Label Heading for each phase.
2381        if {$expgui(globalmode) != 0} {
2382            grid [label $framePF.l1 \
2383                    -text "Phase $i Hist: [CompressList $phasehistlist($i)]"] \
2384                    -column 0 -row 0 -sticky nws
2385            grid [button $framePF.but1 -text "Set Globally" \
2386                    -command "editglobalparm hapinfo frac \"Phase $i Fraction\" \
2387                    [list $phasehistlist($i)] $i" \
2388                    ] -column 1 -row 0
2389            set entrycmd(frref$i) "hapinfo [list $histlist] $i frref"
2390            set entryvar(frref$i) [hapinfo $hist $i frref]
2391            set entrycmd(frdamp$i) "hapinfo [list $histlist] $i frdamp"
2392        } else {
2393            grid [label $framePF.l1  -text "Phase $i"] \
2394                    -column 0 -row 0 -sticky nws
2395            grid [entry $framePF.ent -textvariable entryvar(frac$i) -width 15]\
2396                    -column 1 -row 0
2397            set entrybox(frac$i) $framePF.ent
2398            set entrycmd(frref$i) "hapinfo $hist $i frref"
2399            set entryvar(frref$i) [hapinfo $hist $i frref]
2400            set entrycmd(frdamp$i) "hapinfo $hist $i frdamp"
2401        }
2402        set entrycmd(frac$i) "hapinfo $hist $i frac"
2403        set entryvar(frac$i) [hapinfo $hist $i frac]
2404        grid [label $framePF.l2  -text "  Refine"] \
2405                -column 2 -row 0 -sticky nws
2406        grid [checkbutton $framePF.cb -variable entryvar(frref$i)] \
2407                -column 3 -row 0 -sticky nws
2408        grid [label $framePF.l3  -text "  Damping"] \
2409                -column 4 -row 0 -sticky nws
2410        tk_optionMenu $framePF.tkOptDamp entryvar(frdamp$i) \
2411                0 1 2 3 4 5 6 7 8 9     
2412        set entryvar(frdamp$i) [hapinfo $hist $i frdamp]
2413        grid $framePF.tkOptDamp -row 0 -sticky nsw -column 5
2414    }
2415    # resize the scroll window to match the actual
2416    update idletasks
2417    $expgui(FracBox) config -scrollregion [grid bbox $expgui(FracBox).f]
2418    $expgui(FracBox) config -width [lindex [grid bbox $expgui(FracBox).f] 2]
2419    update idletasks
2420    # enable traces on entryvar now
2421    set entrycmd(trace) 1
2422}
2423
2424#-----------------------------------------------------------------------
2425# display the profile page
2426#-----------------------------------------------------------------------
2427proc DisplayProfile {} {
2428    global expgui entrycmd entryvar entrybox expmap
2429
2430    # trap if more than one histogram is selected unless global mode
2431    if {$expgui(globalmode) == 0 && [llength $expgui(curhist)] > 1} {
2432        set expgui(curhist) [lindex $expgui(curhist) 0] 
2433    }
2434    # display the selected histograms
2435    $expgui(profFrame).hs.lbox selection clear 0 end
2436    foreach h $expgui(curhist) {
2437        $expgui(profFrame).hs.lbox selection set $h
2438    }
2439
2440    # destroy the contents of the frame
2441    eval destroy [winfo children $expgui(ProfileBox).f]
2442    # since the next steps can take a while, do a screen update
2443    update idletasks
2444
2445    if {$expgui(globalmode) == 0} {
2446        # must have at least one histogram selected here
2447        if {[llength $expgui(curhist)] == 0} return
2448        # disable traces on entryvar for right now
2449        set entrycmd(trace) 0
2450        set hist [lindex $expmap(powderlist) $expgui(curhist)]
2451        # no defined histograms?
2452        if {$hist == ""} return
2453        # Create one frame for each Phase.
2454        set ind -1
2455        set htype [string range $expmap(htype_$hist) 2 2]
2456        set zflag 0
2457        if {$htype == "C"} {
2458            set zflag [histinfo $hist zref]
2459        }
2460        foreach i $expmap(phaselist_$hist) {
2461            incr ind
2462            # Label Heading for each phase.
2463            set ptype [string trim [hapinfo $hist $i proftype]]
2464            grid [TitleFrame $expgui(ProfileBox).f.$i \
2465                      -text "Hist $hist -- Phase $i (type $ptype)" \
2466                      -relief groove -bd 2] \
2467                -column 0 -row $ind -sticky ew
2468            set ProfileFrame [$expgui(ProfileBox).f.$i getframe]
2469            grid [frame $ProfileFrame.1] \
2470                -column 0 -row 0 -columnspan 10
2471            pack [label $ProfileFrame.1.l  \
2472                      -text Damping]\
2473                -side left
2474            tk_optionMenu $ProfileFrame.1.tkOptDamp entryvar(pdamp_$i) \
2475                    0 1 2 3 4 5 6 7 8 9
2476            set entrycmd(pdamp_$i) "hapinfo $hist $i pdamp"
2477            set entryvar(pdamp_$i) [hapinfo $hist $i pdamp]
2478            pack $ProfileFrame.1.tkOptDamp -side left
2479            pack [label $ProfileFrame.1.l1 \
2480                    -text "  Peak cutoff"]\
2481                    -side left
2482            pack [entry $ProfileFrame.1.e1  \
2483                    -width 10 -textvariable entryvar(pcut_$i)]\
2484                    -side left
2485            set entrybox(pcut_$i) $ProfileFrame.1.e1
2486            set entrycmd(pcut_$i) "hapinfo $hist $i pcut"
2487            set entryvar(pcut_$i) [hapinfo $hist $i pcut]
2488
2489            pack [button $ProfileFrame.1.b1  \
2490                    -text "Change Type" \
2491                    -command "ChangeProfileType $hist $i"]\
2492                    -side left
2493           
2494            set col -1
2495            set row 1
2496            set nterms [hapinfo $hist $i profterms]
2497            set lbls "dummy [GetProfileTerms $i $hist [expr abs($ptype)]]"
2498            for { set num 1 } { $num <= $nterms } { incr num } {
2499                set term {}
2500                catch {set term [lindex $lbls $num]}
2501                if {$term == ""} {set term $num}
2502                incr col
2503                grid [label $ProfileFrame.l${num}_${i} -text "$term"] \
2504                        -row $row -column $col
2505                incr col
2506                grid [checkbutton $ProfileFrame.ref${num}_${i} \
2507                        -variable entryvar(pref${num}_$i)] -row $row -column $col
2508                set entrycmd(pref${num}_$i) "hapinfo $hist $i pref$num"
2509                set entryvar(pref${num}_$i) [hapinfo $hist $i pref$num]
2510                incr col
2511                grid [entry $ProfileFrame.ent${num}_${i} \
2512                        -textvariable entryvar(pterm${num}_$i)\
2513                        -width 12] -row $row -column $col
2514                set entrybox(pterm${num}_$i) $ProfileFrame.ent${num}_${i}
2515                set entrycmd(pterm${num}_$i) "hapinfo $hist $i pterm$num"
2516                set entryvar(pterm${num}_$i) [hapinfo $hist $i pterm$num]
2517                # disable trns & shft when zero is refined
2518                if {$zflag && ($term == "trns" || $term == "shft")} {
2519                    if {$entryvar(pref${num}_$i)} {
2520                        incr expgui(changed)
2521                        set entryvar(pref${num}_$i) 0
2522                    }
2523                    $ProfileFrame.l${num}_${i} config -fg gray
2524                    $ProfileFrame.ref${num}_${i} config -state disabled
2525                    $ProfileFrame.ent${num}_${i} config -fg gray
2526                }
2527                if {$col > 6} {set col -1; incr row}
2528            }
2529        }
2530        grid columnconfigure $expgui(ProfileBox).f 0 -weight 1
2531    } else {
2532        # get histogram list
2533        set histlist {}
2534        foreach item $expgui(curhist) {
2535            lappend histlist [lindex $expmap(powderlist) $item]
2536        }
2537        # must have at least one histogram selected here
2538        if {[llength $histlist] == 0} return
2539        # disable traces on entryvar for right now
2540        set entrycmd(trace) 0
2541        # loop through histograms & phases, set up an array by phase & profile type
2542        catch {unset prtyparray histarray phasearray}
2543        foreach hist $histlist {
2544            foreach phase $expmap(phaselist_$hist) {
2545                set prtyp [string trim [hapinfo $hist $phase proftype]]
2546                set key ${prtyp}_$phase
2547                lappend prtyparray($key) $hist
2548                lappend histarray($key) $hist
2549                lappend phasearray($key) $phase
2550            }
2551        }
2552       
2553        set ptype ""
2554        set i -1
2555        # loop over all combined phases and profile types, sorted 1st by profile number
2556        foreach key [lsort [array names prtyparray]] {
2557            # split key
2558            scan $key %d_%d prftyp p
2559
2560            if {$ptype != $prftyp || !$expgui(globalphasemode)} {
2561                set ptype $prftyp
2562                set curhistlist $histarray($key)
2563                set curphaslist $phasearray($key)
2564               
2565                set hist1 [lindex $curhistlist 0]
2566                set phase1 [lindex $curphaslist 0]
2567                set nterms [hapinfo $hist1 $phase1 profterms]
2568                set htype [string range $expmap(htype_$hist1) 2 2]
2569                set lbls "dummy [GetProfileTerms $phase1 $hist1 [expr abs($ptype)]]"
2570                # Create a frame for this type
2571                incr i
2572                set boxtitle "Phase $p, hist [CompressList $histarray($key)]"
2573                grid [TitleFrame $expgui(ProfileBox).f.$i \
2574                          -text "(type $ptype)" \
2575                          -relief groove -bd 2] \
2576                    -column 0 -row $i -sticky ew
2577                set ProfileFrame [$expgui(ProfileBox).f.$i getframe]
2578                grid [frame $ProfileFrame.0] \
2579                    -column 0 -row 0 -columnspan 20 -sticky ew
2580                grid [label $ProfileFrame.0.1  \
2581                        -anchor w] -row 0 -column 1
2582                grid [frame $ProfileFrame.1] \
2583                        -column 0 -row 1 -columnspan 20 -sticky ew
2584                grid [label $ProfileFrame.1.2  \
2585                        -text "Damping"] -row 0 -column 2
2586                tk_optionMenu $ProfileFrame.1.tkOptDamp \
2587                        entryvar(pdamp_$i) 0 1 2 3 4 5 6 7 8 9
2588                grid $ProfileFrame.1.tkOptDamp -row 0 -column 3
2589                grid [button $ProfileFrame.1.edit \
2590                        -text "Global Edit"] -row 0 -column 4 -sticky w
2591                set entryvar(pdamp_$i) [hapinfo $hist $phase pdamp]
2592                grid [button $ProfileFrame.1.b1 -text "Change Type"] \
2593                        -row 0 -column 5 -sticky w
2594                set col -1
2595                set row 2
2596                for { set num 1 } { $num <= $nterms } { incr num } {
2597                    set term {}
2598                    catch {set term [lindex $lbls $num]}
2599                    if {$term == ""} {set term $num}
2600                    incr col
2601                    grid [label $ProfileFrame.l${num}_${i} \
2602                            -text "$term"] -row $row -column $col
2603                    incr col
2604                    grid [checkbutton $ProfileFrame.ref${num}_${i} \
2605                            -variable entryvar(pref${num}_$i)] \
2606                            -row $row -column $col
2607                    set entryvar(pref${num}_$i) [hapinfo $hist $phase pref$num]
2608                    if {$col > 10} {set col -1; incr row}
2609                }
2610                grid columnconfigure $expgui(ProfileBox).f 0 -weight 1
2611            } else {
2612                # add to the current entry
2613                eval lappend curhistlist $histarray($key)
2614                eval lappend curphaslist $phasearray($key)
2615                append boxtitle "\nPhase $p, hist [CompressList $histarray($key)]"
2616            }
2617            $ProfileFrame.0.1 config -text $boxtitle
2618            $ProfileFrame.1.edit config -command "\
2619                    EditProfile \"\n$boxtitle\" \
2620                    [list $curhistlist] \
2621                    [list $curphaslist]"
2622            $ProfileFrame.1.b1 config -command "ChangeProfileType \
2623                    [list $curhistlist] [list $curphaslist]" 
2624            set entrycmd(pdamp_$i) "hapinfo \
2625                    [list $curhistlist] \
2626                    [list $curphaslist] pdamp"
2627            for { set num 1 } { $num <= $nterms } { incr num } {
2628                set entrycmd(pref${num}_$i) "hapinfo \
2629                        [list $curhistlist] \
2630                        [list $curphaslist] pref$num"
2631            }
2632        }
2633    }
2634   
2635    # resize the scroll window to match the actual
2636    update idletasks
2637    $expgui(ProfileBox) config -scrollregion [grid bbox $expgui(ProfileBox).f]
2638    $expgui(ProfileBox) config -width [lindex [grid bbox $expgui(ProfileBox).f] 2]
2639    update idletasks
2640    ResizeNotebook
2641    # enable traces on entryvar now
2642    set entrycmd(trace) 1
2643}
2644
2645# process the bit settings in the print options
2646#   bitnum -- the number of the bit to be tested/set starting at 0 for the LSBit
2647proc printsetting {bitnum "action get" "value {}"} {
2648    global entryvar expgui
2649    if {$action == "get"} {
2650        return [expr ([expinfo print] & int(pow(2,$bitnum))) != 0]
2651    } elseif $value {
2652        set newval [expr ([expinfo print] | int(pow(2,$bitnum)))]
2653    } else {
2654        set newval [expr ([expinfo print] & ~int(pow(2,$bitnum)))]
2655    }
2656    expinfo print set $newval
2657    RecordMacroEntry "incr expgui(changed); expinfo print set $newval" 1
2658    set expgui(printopt) "Print Options ([expinfo print])"
2659}
2660
2661# need to respond to mouse presses -- control variable associated with extract Fobs
2662# and set the LeBail extraction flags
2663proc SetupExtractHist {} {
2664    global expgui entrycmd entryvar expmap
2665
2666    # display the selected histograms
2667    $expgui(lsFrame).hs.lbox selection clear 0 end
2668    foreach h $expgui(curhist) {
2669        $expgui(lsFrame).hs.lbox selection set $h
2670    }
2671
2672    # get histogram list
2673    set histlist {}
2674    foreach item $expgui(curhist) {
2675        set hist [lindex $expmap(powderlist) $item]
2676        if {$hist != ""} {lappend histlist $hist}
2677    }
2678    set entrycmd(fobsextract) "histinfo [list $histlist] foextract"
2679    if {[llength $histlist] == 0 || [string trim $histlist] == ""} {
2680        set entrycmd(LBdamp) ""
2681        foreach phase {1 2 3 4 5 6 7 8 9} {
2682            $expgui(FobsExtractFrame).l$phase config -fg grey
2683            set expgui(Fextract$phase) {}
2684            foreach item $expgui(ExtractSettingsRadiobuttons) {
2685                ${item}$phase config -state disabled -bd 1
2686            }
2687        }
2688    } elseif {[llength $histlist] == 1} {
2689        # disable traces on entryvar
2690        set entrycmd(trace) 0
2691        set entryvar(fobsextract) [histinfo $histlist foextract]
2692        set entrycmd(LBdamp) "histinfo $histlist LBdamp"
2693        set entryvar(LBdamp) [histinfo $histlist LBdamp]
2694        foreach phase {1 2 3 4 5 6 7 8 9} {
2695            # is the phase present?
2696            if {[lsearch -exact $expmap(phaselist_$histlist) $phase] == -1} {
2697                $expgui(FobsExtractFrame).l$phase config -fg grey
2698                set expgui(Fextract$phase) {}
2699                foreach item $expgui(ExtractSettingsRadiobuttons) {
2700                    ${item}$phase config -state disabled -bd 1
2701                }
2702            } else {
2703                $expgui(FobsExtractFrame).l$phase config -fg black
2704                foreach item $expgui(ExtractSettingsRadiobuttons) {
2705                    ${item}$phase config -state normal -bd 2
2706                }
2707                set expgui(Fextract$phase) [hapinfo $histlist $phase extmeth]
2708            }
2709        }
2710    } elseif {[llength $histlist] > 1} {
2711        # disable traces on entryvar
2712        set entrycmd(LBdamp) "histinfo [list $histlist] LBdamp"
2713        set entryvar(LBdamp) [histinfo [lindex $histlist 0] LBdamp]
2714        set entrycmd(trace) 0
2715        # multiple histograms need phases in any histogram
2716        foreach phase {1 2 3 4 5 6 7 8 9} {
2717            set gotphase($phase) 0
2718        }           
2719        foreach hist $histlist {
2720            foreach phase $expmap(phaselist_$hist) {
2721                set gotphase($phase) 1
2722            }
2723        }
2724        foreach phase {1 2 3 4 5 6 7 8 9} {
2725            set expgui(Fextract$phase) {}
2726            if $gotphase($phase) {
2727                $expgui(FobsExtractFrame).l$phase config -fg black
2728                foreach item $expgui(ExtractSettingsRadiobuttons) {
2729                    ${item}$phase config -state normal -bd 2
2730                }
2731            } else {
2732                $expgui(FobsExtractFrame).l$phase config -fg grey
2733                foreach item $expgui(ExtractSettingsRadiobuttons) {
2734                    ${item}$phase config -state disabled -bd 1
2735                }
2736            }
2737        }
2738    }
2739    # reenable traces
2740    set entrycmd(trace) 1
2741}
2742# respond to a change in the fobs extraction method for a phase
2743# force the main extraction flag on, if fobs extraction is selected for any phase
2744proc HistExtractSet {phase} {
2745    global expgui entryvar expmap
2746    foreach item $expgui(curhist) {
2747        lappend histlist [lindex $expmap(powderlist) $item]
2748    }
2749    hapinfo $histlist $phase extmeth set $expgui(Fextract$phase)
2750    RecordMacroEntry "incr expgui(changed); hapinfo [list $histlist] $phase extmeth set $expgui(Fextract$phase)" 1
2751    incr expgui(changed)
2752    if {$expgui(Fextract$phase) != 0} {set entryvar(fobsextract) 1}
2753}
2754#---------------------------- Global Edit Functions ------------------------
2755proc editbackground {} {
2756    global expgui expmap entrycmd
2757    set histlist {}
2758    foreach n $expgui(curhist) {
2759        lappend histlist [lindex $expmap(powderlist) $n]
2760    }
2761    if {[llength $histlist] == 0} return
2762
2763    set w .back
2764    catch {destroy $w}
2765    toplevel $w -bg beige
2766    if {$expgui(globalmode) != 0} {
2767        wm title $w "Global Edit Background" 
2768    } else {
2769        wm title $w "Edit Background" 
2770    }
2771   
2772    pack [frame $w.0 -bd 6 -relief groove  -bg beige \
2773            ] -side top -expand yes -fill both
2774    if {[llength $histlist] > 1} {
2775        grid [label $w.0.a \
2776            -text "Setting background terms for histograms [CompressList $histlist]" \
2777            -bg beige] -row 0 -column 0 -columnspan 10
2778    } else {
2779        grid [label $w.0.a \
2780            -text "Setting background terms for histogram $histlist" \
2781            -bg beige] -row 0 -column 0 -columnspan 4
2782        grid [button $w.0.bkg -text "Fit Background\nGraphically" \
2783                -command "QuitEditBackground $w; bkgedit $histlist"] \
2784                -row 0 -column 4 -rowspan 2
2785        grid columnconfig $w.0 0 -weight 1
2786        grid columnconfig $w.0 4 -weight 1
2787    }
2788    set hist [lindex $histlist 0]
2789    grid [label $w.0.b -text "Function type" -bg beige]  -row 1 -column 0 -sticky e
2790
2791    # disable traces on  expgui(backtype) & expgui(backterms) now
2792    set entrycmd(trace) 0
2793
2794    # number of terms
2795    set expgui(backtype) [histinfo $hist backtype]
2796    set expgui(orig_backtype) $expgui(backtype)
2797    set expgui(prev_backtype) $expgui(backtype)
2798    set typemenu [tk_optionMenu $w.0.type expgui(backtype) null]
2799    $typemenu delete 0 end
2800    foreach item {
2801        "1 - Shifted Chebyschev"
2802        "2 - Cosine Fourier series"
2803        "4 - Power series in Q**2n/n!"
2804        "5 - Power series in n!/Q**2n"
2805        "6 - Power series in Q**2n/n! and n!/Q**2n"
2806        "7 - Linear interpolation function"
2807        "8 - Reciprocal interpolation function"
2808    } {
2809        set val [lindex $item 0]
2810        $typemenu insert end radiobutton -variable expgui(backtype) \
2811                -label $item -value $val
2812    }
2813# removed
2814#       "3 - Radial distribution peaks"
2815
2816    grid $w.0.type   -row 1 -column 1
2817    grid [label $w.0.c -text "  Number of terms"  -bg beige] -row 1 -column 2
2818
2819    # function type
2820    set expgui(backterms) [histinfo $hist backterms]
2821    set expgui(orig_backterms) $expgui(backterms) 
2822    set list {}; for {set i 1} {$i <= 36} {incr i} {lappend list $i}
2823    eval tk_optionMenu $w.0.terms expgui(backterms) $list
2824    grid $w.0.terms   -row 1 -column 3 
2825    # enable traces on  expgui(backtype) & expgui(backterms) now
2826    set entrycmd(trace) 1
2827
2828    #set background terms
2829    for {set num 1 } { $num <= 36 } { incr num } {
2830        set var "bterm$num"
2831        set expgui($var) {}
2832        set expgui(orig_$var) {}
2833    }
2834    if {[llength $histlist] == 1} {
2835        for {set num 1 } { $num <= $expgui(backterms) } { incr num } {
2836            set var "bterm$num"
2837            set expgui($var) [histinfo $histlist $var]
2838            set expgui(orig_$var) $expgui($var)
2839        }
2840    }
2841
2842    pack [frame $w.1 -bd 6 -relief groove  -bg beige] -side top \
2843            -expand yes -fill both
2844    ShowBackTerms $w.1
2845
2846    set expgui(temp) {}
2847    pack [frame $w.b -bg beige] -fill x -expand yes -side top
2848    grid [button $w.b.2 -text Continue -command "destroy $w"] -row 0 -column 1
2849    grid [button $w.b.3 -text Cancel \
2850            -command "QuitEditBackground $w"] -row 0 -column 2
2851    grid [button $w.b.help -text Help -bg yellow \
2852            -command "MakeWWWHelp expgui3.html EditBackground"] \
2853            -row 0 -column 4
2854    grid columnconfig $w.b 0 -weight 1
2855    grid columnconfig $w.b 3 -weight 1
2856    bind $w <Key-F1> "MakeWWWHelp expgui3.html EditBackground"
2857    bind $w <Return> "destroy $w"
2858
2859    # force the window to stay on top
2860    putontop $w
2861
2862    focus $w.b.2
2863    tkwait window $w
2864    afterputontop
2865
2866    if {$expgui(temp) != ""} return
2867
2868    if {$expgui(orig_backtype) != $expgui(backtype)} {
2869        histinfo $histlist backtype set $expgui(backtype)
2870        RecordMacroEntry "histinfo [list $histlist] backtype set $expgui(backtype)" 0
2871        incr expgui(changed)
2872    }
2873    if {$expgui(orig_backterms) != $expgui(backterms)} {
2874        histinfo $histlist backterms set $expgui(backterms)
2875        RecordMacroEntry "histinfo [list $histlist] backterms set $expgui(backterms)" 0
2876        incr expgui(changed)
2877    }
2878    for {set num 1 } { $num <= $expgui(backterms) } { incr num } {
2879        set var "bterm$num"
2880        if {$expgui(orig_$var) != $expgui($var)} {
2881            histinfo $histlist $var set $expgui($var)
2882            RecordMacroEntry "histinfo [list $histlist] $var set $expgui($var)" 0
2883            incr expgui(changed)
2884        }
2885    }
2886    RecordMacroEntry "incr expgui(changed)" 0
2887
2888    if {$expgui(globalmode) == 0} {
2889        set expgui(backtypelbl) "Function type [histinfo $hist backtype]"
2890        set expgui(backtermlbl) "([histinfo $hist backterms] terms)"
2891    }
2892}
2893
2894trace variable expgui(backterms) w ChangeBackTerms
2895proc ChangeBackTerms {a b c} {
2896    global entrycmd expgui
2897    if !$entrycmd(trace) return
2898    ShowBackTerms .back.1
2899}
2900
2901trace variable expgui(backtype) w ChangeBackType
2902# reset the terms to 1, 0, 0... when the number of terms increase
2903proc ChangeBackType {a b c} {
2904    global entrycmd expgui
2905    if !$entrycmd(trace) return
2906    if {$expgui(prev_backtype) == $expgui(backtype)} return
2907    set expgui(prev_backtype) $expgui(backtype)
2908    for {set num 1 } { $num <= $expgui(backterms) } { incr num } {
2909        set var "bterm$num"
2910        if {$num == 1} {
2911            set expgui($var) 1.0
2912        } else {
2913            set expgui($var) 0.0
2914        }
2915    }
2916}
2917
2918proc ShowBackTerms {w } {
2919    global expgui expmap
2920    # destroy the contents of the frame
2921    eval destroy [winfo children $w]
2922    set histlist {}
2923    foreach n $expgui(curhist) {
2924        lappend histlist [lindex $expmap(powderlist) $n]
2925    }
2926    set widgetsPerRow 4
2927    for {set rows 2; set num 1 } { $num <= $expgui(backterms) } { incr rows } {
2928        for {set cols 0} { (2*$widgetsPerRow > $cols) && ($num <= $expgui(backterms)) }  { incr num }  {
2929            set var "bterm$num"
2930            grid [label $w.l$num -text $num -bg beige]  \
2931                    -row $rows -column $cols -sticky nes
2932            incr cols
2933            grid [entry $w.e$num -width 15 -textvariable expgui($var) \
2934                    ] -row $rows  -column $cols  -sticky news
2935            incr cols
2936        }
2937    }
2938}
2939
2940proc QuitEditBackground {w} {
2941    global expgui
2942    # lets find out if anything changed
2943    set changed 0
2944    if {$expgui(orig_backtype) != $expgui(backtype)} {
2945        set changed 1
2946    }
2947    if {$expgui(orig_backterms) != $expgui(backterms)} {
2948        set changed 1
2949    }
2950    for {set num 1 } { $num <= $expgui(backterms) } { incr num } {
2951        set var "bterm$num"
2952        if {$expgui(orig_$var) != $expgui($var)} {
2953            set changed 1
2954            break
2955        }
2956    }
2957    if $changed {
2958        set decision [tk_dialog .changes "Abandon Changes" \
2959                "You have made changes to the background. Ok to abandon changes?" \
2960                warning 0 Abandon Keep]
2961        if !$decision {
2962            set expgui(temp) "Quit"
2963            destroy $w
2964        }
2965    } else {
2966        set expgui(temp) "Quit"
2967        destroy $w
2968    }
2969}
2970
2971# this probably needs work
2972proc editglobalparm {cmd variable title "histlist {}" "phase {}"} {
2973    global expgui expmap
2974    set w .global
2975    catch {destroy $w}
2976    toplevel $w -bg beige
2977    wm title $w "Edit Global Parameter"
2978    set expgui(temp) {}
2979    if {[llength $histlist] == 0} {
2980        set hist {}
2981        foreach n $expgui(curhist) {
2982            lappend hist [lindex $expmap(powderlist) $n]
2983        }
2984    } else {
2985        set hist $histlist
2986    }
2987    pack [frame $w.0 -bd 6 -relief groove -bg beige] \
2988            -side top -expand yes -fill both
2989    grid [label $w.0.a -text "Setting $title for histograms [CompressList $hist]"\
2990            -bg beige] \
2991            -row 0 -column 0 -columnspan 10
2992    grid [entry $w.0.b -textvariable expgui(temp)] \
2993            -row 1 -column 0 
2994
2995
2996    pack [frame $w.b -bg beige] -fill x -expand yes -side top
2997    pack [button $w.b.2 -text Continue -command "destroy $w"] -side left
2998    pack [button $w.b.3 -text Cancel -command "set expgui(temp) {}; destroy $w"] -side left
2999    pack [button $w.b.help -text Help -bg yellow \
3000            -command "MakeWWWHelp expgui3.html EditParm"] -side right
3001    bind $w <Key-F1> "MakeWWWHelp expgui3.html EditParm"
3002    bind $w <Return> "destroy $w"
3003
3004    # force the window to stay on top
3005    putontop $w
3006    focus $w.b.2
3007    tkwait window $w
3008    afterputontop
3009
3010    if {$expgui(temp) != ""} {
3011        foreach h $hist {
3012            if {$cmd == "histinfo"} {
3013                histinfo $h $variable set $expgui(temp)
3014                RecordMacroEntry "histinfo $h $variable set $expgui(temp)" 1
3015                incr expgui(changed)
3016                if $expgui(debug) {
3017                    puts "histinfo $h $variable set $expgui(temp)"
3018                }
3019            } elseif {$cmd == "hapinfo"} {
3020                hapinfo $h $phase $variable set $expgui(temp)
3021                RecordMacroEntry "hapinfo $h [list $phase] $variable set $expgui(temp)" 1
3022                incr expgui(changed)
3023                if $expgui(debug) {
3024                    puts "hapinfo $h $phase $variable set $expgui(temp)"
3025                }
3026            } else {
3027                error "$cmd unimplemented"
3028            }
3029        }
3030        RecordMacroEntry "incr expgui(changed)" 0
3031    }
3032}
3033
3034proc EditProfile {title histlist phaselist} {
3035    global expgui expmap entrycmd
3036    set w .back
3037    catch {destroy $w}
3038    toplevel $w -bg beige
3039    wm title $w "Global Edit Profile"
3040    set hist [lindex $histlist 0]
3041    set phase [lindex $phaselist 0]
3042    set ptype [string trim [hapinfo $hist $phase proftype]]
3043    set htype [string range $expmap(htype_$hist) 2 2]
3044    set nterms [hapinfo $hist $phase profterms]
3045   
3046    pack [frame $w.0 -bd 6 -relief groove  -bg beige \
3047            ] -side top -expand yes -fill both
3048    grid [label $w.0.a \
3049            -text "Setting profile terms: $title" \
3050            -bg beige] -row 0 -column 0 -columnspan 10
3051    grid [label $w.0.b -text "Function type $ptype"  -bg beige]  -row 1 -column 0
3052    grid [label $w.0.c -text "  Peak cutoff" -bg beige] -row 1 -column 3 
3053    grid [entry $w.0.d -width 10 ]  -row 1 -column 4
3054    set entrylist {}
3055    lappend entrylist "pcut $w.0.d"
3056
3057    set col -1
3058    set row 1
3059    set lbls "dummy [GetProfileTerms $phase $hist [expr abs($ptype)]]"
3060    pack [frame $w.1 -bd 6 -relief groove  -bg beige \
3061            ] -side top -expand yes -fill both
3062    for { set num 1 } { $num <= $nterms } { incr num } {
3063        set term {}
3064        catch {set term [lindex $lbls $num]}
3065        if {$term == ""} {set term $num}
3066        incr col
3067        grid [label $w.1.l${num} -text "$term" -bg beige] \
3068                -row $row -column $col
3069        incr col
3070        grid [entry $w.1.ent${num} \
3071                -width 14] -row $row -column $col
3072        lappend entrylist "pterm$num $w.1.ent${num}"   
3073        if {$col > 6} {set col -1; incr row}
3074    }
3075    pack [frame $w.b -bg beige] -fill x -expand yes -side top
3076    grid [button $w.b.2 -text Continue \
3077            -command "SetEditProfile [list $entrylist] [list $phaselist] \
3078            [list $histlist] $w"] -row 0 -column 1
3079    grid [button $w.b.3 -text Cancel \
3080            -command "QuitEditProfile $w [list $entrylist]"] -row 0 -column 2
3081    grid [button $w.b.help -text Help -bg yellow \
3082            -command "MakeWWWHelp expgui5.html GlobalEdit"] \
3083            -row 0 -column 4
3084    grid columnconfig $w.b 0 -weight 1
3085    grid columnconfig $w.b 3 -weight 1
3086    bind $w <Key-F1> "MakeWWWHelp expgui5.html GlobalEdit"
3087    bind $w <Return> "QuitEditProfile $w [list $entrylist]"
3088
3089    # force the window to stay on top
3090    putontop $w
3091    focus $w.b.2
3092    tkwait window $w
3093    afterputontop
3094}
3095
3096proc SetEditProfile {entrylist phaselist histlist w} {
3097    global expgui
3098    foreach item $entrylist {
3099        set value [ [lindex $item 1] get ]
3100        if {$value != ""} {
3101            hapinfo $histlist $phaselist [lindex $item 0] set $value
3102            RecordMacroEntry "hapinfo [list $histlist] [list $phaselist] [lindex $item 0] set $value" 1
3103            incr expgui(changed)
3104            RecordMacroEntry "incr expgui(changed)" 0
3105            if $expgui(debug) {
3106                puts "hapinfo [list $phaselist] [list $histlist] [lindex $item 0] set $value"
3107            }
3108        }
3109    }
3110    destroy $w
3111}
3112
3113proc QuitEditProfile {w entrylist} {
3114    global expgui
3115    # lets find out if anything changed
3116    set changed 0
3117    foreach item $entrylist {
3118        if {[ [lindex $item 1] get ] != ""} {set changed 1; break}
3119    }
3120    if $changed {
3121        set decision [tk_dialog .changes "Abandon Changes" \
3122                "You have made changes to the Profile. Ok to abandon changes?" \
3123                warning 0 Abandon Keep]
3124        if !$decision {destroy $w}
3125    } else {
3126        destroy $w
3127    }
3128}
3129
3130# this is called to change the absorption correction mode and to
3131# change the absorption correction model.
3132proc editabsorption {} {
3133    global expgui expmap
3134    set histlist {}
3135    foreach n $expgui(curhist) {
3136        lappend histlist [lindex $expmap(powderlist) $n]
3137    }
3138    if {[llength $histlist] == 0} return
3139
3140    set w .abs
3141    catch {destroy $w}
3142    toplevel $w -bg beige
3143    if {$expgui(globalmode) != 0} {
3144        wm title $w "Global Edit Absorption/Reflectivity" 
3145    } else {
3146        wm title $w "Edit Absorption/Reflectivity"
3147    }
3148   
3149    pack [frame $w.0 -bd 6 -relief groove  -bg beige \
3150            ] -side top -expand yes -fill both
3151    if {[llength $histlist] > 1} {
3152        grid [label $w.0.a \
3153            -text "Changing settings for histograms [CompressList $histlist]" \
3154            -bg beige] -row 0 -column 0 -columnspan 10
3155    } else {
3156        grid [label $w.0.a \
3157            -text "Changing settings for histogram $histlist" \
3158            -bg beige] -row 0 -column 0 -columnspan 4
3159        #grid columnconfig $w.0 4 -weight 1
3160    }
3161    grid rowconfig $w.0 1 -min 10
3162    set hist [lindex $histlist 0]
3163
3164    grid [label $w.0.lb1 -text "Absorption Coefficient(s)" -bg beige] \
3165            -row 2 -column 1  -columnspan 2
3166    grid [label $w.0.lb1a -text "1" -bg beige] -row 3 -column 1
3167    set expgui(abs2box1) $w.0.lb2a
3168    grid [label $w.0.lb2a -text "2" -bg beige] -row 3 -column 2
3169    grid [label $w.0.lb3 -text Absorption\nFunction -bg beige] \
3170            -row 2 -column 6 -rowspan 2 -columnspan 2
3171    grid [entry $w.0.ent1 -textvariable expgui(abscor1) -width 15] \
3172            -row 4 -column 1
3173    set expgui(abs2box2) $w.0.ent2
3174    grid [entry $w.0.ent2 -textvariable expgui(abscor2) -width 15] \
3175            -row 4 -column 2 
3176    trace vdelete expgui(abstype) w AbsSetoptmsg
3177    eval tk_optionMenu $w.0.m1 expgui(abstype) 0 1 2 3 4
3178    trace variable expgui(abstype) w AbsSetoptmsg
3179    grid $w.0.m1 -row 4 -column 6 -columnspan 2
3180    grid [label $w.0.lb8 -textvariable expgui(opttxt) -bg beige \
3181          -wrap 300 -justify left] -row 5 -column 1  -sticky ne -columnspan 7
3182    grid rowconfig $w.0 5 -min 100
3183    # set the values, note the trace on abstype
3184    foreach var {abscor1 abscor2 abstype} {
3185        set expgui($var) [histinfo $hist $var]
3186    }
3187
3188    pack [frame $w.b -bg beige] -fill x -expand yes -side top
3189    grid [button $w.b.2 -text Continue -command "AbsSaveEdit $w [list $histlist]"] \
3190            -row 0 -column 1
3191    grid [button $w.b.3 -text Cancel \
3192            -command "destroy $w"] -row 0 -column 2
3193    grid [button $w.b.help -text Help -bg yellow \
3194            -command "MakeWWWHelp expgui3.html EditAbsorption"] \
3195            -row 0 -column 4
3196    grid columnconfig $w.b 0 -weight 1
3197    grid columnconfig $w.b 3 -weight 1
3198    bind $w <Key-F1> "MakeWWWHelp expgui3.html EditAbsorption"
3199    bind $w <Return> "destroy $w"
3200
3201    # force the window to stay on top
3202    putontop $w
3203
3204    focus $w.b.2
3205    tkwait window $w
3206    afterputontop
3207}
3208
3209proc AbsSetoptmsg {args} {
3210    global expgui
3211    array set opttxt {
3212        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!"
3213        1 "Wavelength-dependent correction for container penetration. Use with TOF & Energy Disp x-ray only."
3214        2 "Surface roughness correction [Pitschke, Hermann & Muttern]. Use with flat-plate reflection geometry (usually Bragg-Brentano) only."
3215        3 "Surface roughness correction, [Suortti]. Use with flat-plate reflection geometry (usually Bragg-Brentano) only."
3216        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."
3217    }
3218    set expgui(opttxt) ""
3219    catch {set expgui(opttxt) [set opttxt($expgui(abstype))]}
3220    switch $expgui(abstype) {
3221        0 -
3222        1 {
3223            $expgui(abs2box1) config -fg gray
3224            $expgui(abs2box2) config -state disabled -fg gray
3225        } 
3226        2 -
3227        3 -
3228        4 {
3229            $expgui(abs2box1) config -fg black
3230            $expgui(abs2box2) config -state normal -fg black
3231        }
3232        default {
3233            set expgui(opttxt) "Please select an absorption function"
3234        }
3235    }
3236}
3237proc AbsSaveEdit {top histlist} {
3238    global expgui expmap
3239    # sanity check: look at the histogram type
3240    set h [lindex $histlist 0]
3241    if {[string range $expmap(htype_$h) 2 2] == "T"} {set flag 1}
3242    if {[string range $expmap(htype_$h) 1 2] == "NC"} {set flag 2}
3243    if {[string range $expmap(htype_$h) 1 2] == "XC" && \
3244            [histinfo $h lam2] != 0.0} {set flag 3}
3245    if {[string range $expmap(htype_$h) 1 2] == "XC" && \
3246            [histinfo $h lam2] == 0.0} {set flag 4}
3247    if {[string range $expmap(htype_$h) 1 2] == "XE"} {set flag 5}
3248
3249    set msg {}
3250    if {$expgui(abstype) == 0 && ($flag == 3 || $flag == 4)} {
3251        set msg "Mode 0 is appropriate for cylindrical (Debye-Scherrer) geometry only"
3252    } elseif {$expgui(abstype) == 1 && ($flag != 1 && $flag != 5)} {
3253        set msg "Mode 1 is appropriate for wavelength-dispersive (TOF/E.D. X-ray) data only"
3254    } elseif {($expgui(abstype) == 2 || $expgui(abstype) == 3) \
3255            && $flag != 3 && $flag != 4} {
3256        set msg "Mode 1 is appropriate for reflection geometry flat-plate (typically Bragg-Brentano) data only"
3257    } elseif {$expgui(abstype) == 4 && $flag <= 3} {
3258        set msg "Mode 4 is appropriate for flat-plate samples in transmission"
3259    }
3260    if {$msg != ""} {
3261        set result [\
3262                MyMessageBox -parent $top -title "Sanity check" \
3263                -type okcancel -default cancel \
3264                -icon warning -helplink "expgui3.html AbsorptionSanity" \
3265                -message "$msg  -- are you sure you want to do this?"]
3266        if {$result == "cancel"} return
3267    }
3268
3269    # validate abscor1 & abscor2 (if needed)
3270    set msg {}
3271    if {![validreal expgui(abscor1) 15 8]} {
3272        set msg "Term 1 is invalid"
3273    }
3274    if {$expgui(abstype) > 1} {
3275        if {![validreal expgui(abscor2) 15 8]} {
3276            if {$msg != ""} {append msg "\n"}
3277            append msg "Term 2 is invalid"
3278        }
3279    }
3280    if {$msg != ""} {
3281        MyMessageBox -parent $top -title "Entry error" \
3282                -type ok -default ok \
3283                -icon warning -helplink "" \
3284                -message "Invalid data entered. Please correct.\n$msg"
3285        return
3286    }
3287   
3288    histinfo $histlist abstype set $expgui(abstype)
3289    RecordMacroEntry "histinfo [list $histlist] abstype set $expgui(abstype)" 0
3290    histinfo $histlist abscor1 set $expgui(abscor1)
3291    RecordMacroEntry "histinfo [list $histlist] abscor1 set $expgui(abscor1)" 0
3292    if {$expgui(abstype) > 1} {
3293        histinfo $histlist abscor2 set $expgui(abscor2)
3294        RecordMacroEntry "histinfo [list $histlist] abscor2 set $expgui(abscor2)" 0
3295    } else {
3296        histinfo $histlist abscor2 set 0.
3297        RecordMacroEntry "histinfo [list $histlist] abscor2 set 0." 0
3298    }
3299    # turn off refinement, just in case they didn't read
3300    if {($expgui(abstype) == 0 || $expgui(abstype) == 1 || $expgui(abstype) == 4) \
3301            && ($flag != 1 && $flag != 5)} {
3302        histinfo $histlist absref set 0
3303        RecordMacroEntry "histinfo [list $histlist] absref set 0" 0
3304    }
3305    incr expgui(changed)
3306    RecordMacroEntry "incr expgui(changed)" 0
3307    destroy $top
3308    DisplayHistogram
3309}
3310
3311##############################################################################
3312##                               #############################################
3313## END OF THE PROCEDURES SECTION #############################################
3314##                               #############################################
3315##############################################################################
3316
3317# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
3318# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<                          <<<<<<<<<<<<<<<<<<<
3319# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<   BEGIN:  GUI SECTION    >>>>>>>>>>>>>>>>>>>
3320# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>                          >>>>>>>>>>>>>>>>>>>
3321# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
3322# A frame for menu items at top of display
3323set expgui(fm) [frame .fm -relief raised -borderwidth 2 -width 150 -height 40]
3324# Pack the menu frame.
3325pack $expgui(fm) -fill x -side top -anchor n
3326
3327# create a button bar
3328pack [frame .bar -relief raised -bd 2 -bg beige] -fill x -side top -anchor n
3329
3330# Creating the notebook and panes
3331
3332# create an array element describing each notebook page
3333# element 0 -- pane name
3334#         1 -- Label on frame
3335#         2 -- initialization command
3336#         3 -- update command
3337#         4 -- 0/1 Use 1 if pane should be disabled in when all histograms
3338#                are selected in global mode, 0 otherwise
3339#         5 -- Web page for pane
3340#         6 -- name anchor on Web page for pane
3341set expgui(notebookpagelist) {
3342    {lsFrame     "LS Controls" \
3343            "" \
3344            SetupExtractHist \
3345            0  expgui1.html ""}
3346    {phaseFrame   Phase        \
3347            "" \
3348            {SelectOnePhase $expgui(curPhase)} \
3349            0  expgui2.html ""}
3350    {histFrame    Histogram \
3351            MakeHistPane \
3352            DisplayHistogram \
3353            1  expgui3.html ""}
3354    {fracFrame    Scaling \
3355            MakeScalingPane \
3356            DisplayFrac \
3357            0  expgui4.html ""}
3358    {profFrame    Profile \
3359            MakeProfilePane \
3360            DisplayProfile \
3361            1  expgui5.html ""}
3362    {consFrame    "Re/Constraints" \
3363            "source [file join $expgui(scriptdir) atomcons.tcl]; MakeConstraintsPane" \
3364            DisplayConstraintsPane \
3365            0  expgui6.html ""}
3366    {orientFrame  "MD Pref Orient" \
3367            MakeOrientPane \
3368            DisplayOrient \
3369            0  expgui7.html MD}
3370    {odfFrame  "SH Pref Orient" \
3371            "source [file join $expgui(scriptdir) odf.tcl]; MakeODFPane" \
3372            DisplayODFPane \
3373            0  expgui7.html ODF}
3374}
3375
3376pack [NoteBook .n -bd 2] -expand yes -fill both
3377# this should not be needed, but for some reason NoteBook is not
3378# using the optionDB
3379catch {.n configure -font [option get .n font Canvas]}
3380foreach item $expgui(notebookpagelist) {
3381    set frm [lindex $item 0]
3382    set expgui($frm) [\
3383            .n insert end $frm -text [lindex $item 1] \
3384            -createcmd "set expgui(pagenow) $frm; [lindex $item 2]" \
3385            -raisecmd "set expgui(pagenow) $frm; [lindex $item 3]"]
3386
3387    # at this time expgui(frameactionlist) is generated
3388    # from expgui(notebookpagelist), but in the future it might
3389    # make sense to use expgui(notebookpagelist) directly
3390    lappend expgui(frameactionlist) "$frm [list [lindex $item 3]]"
3391   
3392    # panes to disable in global "all" mode
3393    if {[lindex $item 4]} {
3394        lappend expgui(GlobalModeAllDisable) "$frm \{.n itemconfigure $frm\}"
3395    }
3396}
3397# procedure to disable tabs when phases or histograms are not defined
3398proc StageTabUse {args} {
3399    global expgui
3400    # reset everything
3401    foreach item [lrange $::expgui(notebookpagelist) 0 end] {
3402        set frm [lindex $item 0]
3403        .n itemconfigure $frm -state normal
3404    }
3405    # disable the unallowed pages in all mode
3406    if {$expgui(globalmode) == 6} {
3407        foreach pair $expgui(GlobalModeAllDisable) {
3408            if {$expgui(pagenow) == [lindex $pair 0]} {
3409                RaisePage lsFrame
3410            }
3411            eval [lindex $pair 1] -state disabled
3412        }
3413    } else {
3414        foreach pair $expgui(GlobalModeAllDisable) {
3415            eval [lindex $pair 1] -state normal
3416        }
3417    }
3418    # no phases are present, one must add a phase 1st
3419    if {[llength $::expmap(phaselist)] == 0} {
3420        foreach item [lrange $::expgui(notebookpagelist) 2 end] {
3421            set frm [lindex $item 0]
3422            .n itemconfigure $frm -state disabled
3423        }
3424        return
3425    }
3426    # do any of the phases have atoms?
3427    set flag 1
3428    foreach phase $::expmap(phaselist) {
3429        if {[array names ::expmap atomlist_$phase] != ""} {
3430            if {[llength $::expmap(atomlist_$phase)] > 0} {
3431                set flag 0
3432                break
3433            }
3434        }
3435    }
3436    # no atoms are present, one must add at least one before continuing
3437    if $flag {
3438        foreach item [lrange $::expgui(notebookpagelist) 2 end] {
3439            set frm [lindex $item 0]
3440            .n itemconfigure $frm -state disabled
3441        }
3442        return
3443    }
3444
3445    # no data is present, one must add a histogram next
3446    if {[llength $::expmap(nhst)] == 0} {
3447        foreach item [lrange $::expgui(notebookpagelist) 4 end] {
3448            set frm [lindex $item 0]
3449            .n itemconfigure $frm -state disabled
3450        }
3451        return
3452    }
3453}
3454# expgui(mapstat) is set by mapexp when it is called
3455# mapexp will be called when the .EXP file is changed (addition of phases, atoms or histograms)
3456trace variable expgui(mapstat) w StageTabUse
3457
3458# this is used to bring up the selected frame
3459proc RaisePage {nextpage} {
3460    global expgui
3461    set expgui(pagenow) $nextpage
3462    .n see $nextpage
3463    .n raise $nextpage
3464}
3465
3466# resize the notebook to fit all the tabs and the largest page
3467proc ResizeNotebook {} {
3468    global expgui
3469    .n compute_size
3470}
3471
3472#----------------------------------------------------------------------------
3473proc MakePhasePane {} {
3474    #\/ \/ \/ \/ \/ \/ \/ BEGINNING OF PHASE PANE CODE \/ \/ \/ \/ \/ \/ \/
3475    global expgui entryvar entrybox entrycmd
3476    frame $expgui(phaseFrame).top
3477    set frameLatt [frame $expgui(phaseFrame).frameLatt]
3478    #  This is a big frame in the Phase notebook pane to hold atomic data.
3479    set fbig [frame $expgui(phaseFrame).fbig -width 180 \
3480            -relief raised -borderwidth 4 -class Coord]
3481    #  This is a frame just below the big frame: for edits
3482    set frame3 [frame $expgui(phaseFrame).frame3 -width 100 \
3483            -relief raised -borderwidth 4 -bg $expgui(bkgcolor1)]
3484
3485    grid $expgui(phaseFrame).top -sticky news -row 0 -column 0 
3486    grid $frameLatt -sticky news -row 2 -column 0 
3487    grid $fbig -sticky news -row 3 -column 0 
3488    # give extra space to the atoms box
3489    grid columnconfigure $expgui(phaseFrame) 0 -weight 1
3490    grid rowconfigure $expgui(phaseFrame) 3 -weight 1
3491    grid $frame3 -sticky news -row 4 -column 0 
3492    grid columnconfigure $expgui(phaseFrame) 0 -weight 1
3493    grid rowconfigure $expgui(phaseFrame) 3 -weight 1
3494    grid [frame  $expgui(phaseFrame).top.ps] -column 0 -row 0 -sticky w
3495    # this is where the buttons will go
3496    pack [label $expgui(phaseFrame).top.ps.0 -text "No Phases"] -side left
3497   
3498    grid [label $expgui(phaseFrame).top.lA -text title: \
3499            -fg blue ] -column 1 -row 0 -sticky e
3500    grid [entry $expgui(phaseFrame).top.lB -textvariable entryvar(phasename) \
3501            -fg blue -width 45] -column 2 -row 0 -sticky e
3502    grid columnconfigure $expgui(phaseFrame).top 1 -weight 1
3503    # ------------- Lattice Parameter Box ------------------
3504    set row 0
3505    foreach col {2 4 6} var {a b c} lbl {a b c} {
3506        grid [label $frameLatt.l$var -text $lbl] \
3507                -column $col -row $row -padx 5 -sticky e
3508        incr col
3509        grid [label $frameLatt.e$var -textvariable entryvar($var) \
3510                -relief groove -bd 2 -width 10] \
3511                -column $col -row $row -padx 5
3512#       grid [entry $frameLatt.e$var -textvariable entryvar($var) -width 10] \
3513#           -column $col -row $row -padx 5
3514#       set entrybox($var) $frameLatt.e$var
3515    }
3516    incr row
3517    foreach col {2 4 6} var {alpha beta gamma} lbl {a b g} {
3518        grid [label $frameLatt.l$var -text $lbl] \
3519                -column $col -row $row -padx 5 -sticky e
3520        set font [$frameLatt.l$var cget -font]
3521        $frameLatt.l$var config -font "Symbol [lrange $font 1 end]"
3522
3523        incr col
3524        grid [label $frameLatt.e$var -textvariable entryvar($var)\
3525                -relief groove -bd 2 -width 10] \
3526            -column $col -row $row -padx 5
3527#       grid [entry $frameLatt.e$var -textvariable entryvar($var) -width 10] \
3528#           -column $col -row $row -padx 5
3529#       set entrybox($var) $frameLatt.e$var
3530    }
3531   
3532    grid [button $frameLatt.edit -text "Edit\nCell" -command EditCellConstants] \
3533            -column 8 -row 0 -rowspan 2 -padx 5 -sticky e
3534    grid [label $frameLatt.lr -text "Refine Cell"] -column 9 -row 0 -padx 5 -sticky e
3535    grid [label $frameLatt.ld -text "Cell damping"] -column 9 -row 1 -padx 5 -sticky e
3536    set cFlag [checkbutton $frameLatt.c -text "" -variable entryvar(cellref)]
3537    grid $cFlag -column 10 -row 0 -padx 5 -sticky e
3538    tk_optionMenu $frameLatt.om entryvar(celldamp) 0 1 2 3 4 5 6 7 8 9
3539    grid $frameLatt.om -column 10 -row 1 -padx 5 -sticky e
3540    grid [label $frameLatt.phasetype -textvariable expgui(phasetype) -fg blue] \
3541            -column 1 -row 0 -rowspan 2
3542    if [file executable $expgui(exptool)] {
3543        grid [button $expgui(phaseFrame).frameLatt.newp \
3544                -text "Add\nPhase" -padx 1.5m -command MakeAddPhaseBox \
3545                ] -column 0 -row 0 -rowspan 2 -sticky w
3546    }
3547    grid columnconfig $frameLatt  1 -weight 1
3548    grid columnconfig $frameLatt  0 -weight 1
3549    #-------------- Begin Atom Coordinates Box  ------------------------------
3550    grid [listbox  $fbig.title -height 1 -relief flat \
3551            -exportselection 0 -bg lightgrey -fg black \
3552            -selectforeground black -selectbackground lightgrey] \
3553            -row 0 -column 0 -sticky ew
3554    set expgui(atomtitle) $fbig.title
3555    bind $expgui(atomtitle) <Button-1> {
3556        set i [lsearch {number type mult x y z occupancy} $expgui(asorttype)]
3557        incr i
3558        set expgui(asorttype) [lindex {number type mult x y z occupancy number} $i]
3559        DisplayAllAtoms $expgui(curPhase)
3560    }
3561    bind $expgui(atomtitle) <Button-3> {set expgui(asorttype) number; DisplayAllAtoms $expgui(curPhase)}
3562
3563    $expgui(atomtitle) configure -selectmode extended
3564    grid [listbox   $fbig.lbox -height 10 \
3565            -exportselection 0 \
3566            -xscrollcommand " $fbig.bscr set"\
3567            -yscrollcommand " $fbig.rscr set"\
3568            ] -row 1 -column 0 -sticky news
3569    set expgui(atomlistbox) $fbig.lbox
3570    $expgui(atomlistbox) configure -selectmode extended
3571    grid [scrollbar $fbig.bscr -orient horizontal \
3572            -command "move2boxesX \" $fbig.title $fbig.lbox \" " \
3573            ] -row 2 -column 0 -sticky ew
3574    grid [scrollbar $fbig.rscr  -command "$fbig.lbox yview" \
3575            ] -row 1 -column 1 -sticky ns
3576    # give extra space to the atoms box
3577    grid columnconfigure $fbig 0 -weight 1
3578    grid rowconfigure $fbig 1 -weight 1
3579   
3580    #   BIND mouse in editbox
3581    bind $expgui(atomlistbox) <ButtonRelease-1>   editRecord
3582    bind $expgui(atomlistbox) <Button-3>   SelectAllAtoms
3583   
3584    #-------------- End Atoms Section  ---------------------------------
3585
3586    # --------------------------- Begin Edit Box ------------------------
3587    grid [set expgui(EditingAtoms) [label $frame3.top -bg $expgui(bkgcolor1) -fg blue]] \
3588            -column 0 -row 0 -padx 2 -pady 3 -columnspan 10 -sticky w
3589    if [file executable $expgui(exptool)] {
3590        button $frame3.newa -text "Add New Atoms" \
3591                -bg $expgui(bkgcolor1) -highlightthickness 0 \
3592                -command {MakeAddAtomsBox $expgui(curPhase)}
3593        grid $frame3.newa -column 11 -row 0
3594        set expgui(AddAtomBut) $frame3.newa
3595    }
3596    button [set expgui(atomxform) $frame3.xa] \
3597            -bg $expgui(bkgcolor1) -highlightthickness 0 \
3598            -command {MakeXformAtomsBox $expgui(curPhase)}
3599    grid $expgui(atomxform) -column 11 -row 1 -sticky ew
3600
3601    set f3l1 [label $frame3.l1 -text "Refinement Flags:" -bg $expgui(bkgcolor1)]
3602    grid $f3l1 -column 0 -row 1 -padx 2 -sticky nsw -pady 3
3603    foreach lbl {X U F} var {xref uref fref} col {1 2 3} {
3604        grid [checkbutton $frame3.cf$col \
3605                -text $lbl -variable entryvar($var) \
3606                -bg $expgui(bkgcolor1) -highlightthickness 0 \
3607                -activebackground $expgui(bkgcolor1)] \
3608                -column $col -row 1 -padx 4 -pady 3 -sticky w
3609    }
3610    set f3l4 [label $frame3.l4 -text "  Damping:" -bg $expgui(bkgcolor1)]
3611    grid $f3l4 -column 4 -row 1 -padx 2 -sticky nsw -pady 3
3612   
3613    set col 4
3614    foreach var {xdamp udamp fdamp} num {2 3 4} lbl {X U F} {
3615        grid [label $frame3.lom$num -text $lbl \
3616                -bg $expgui(bkgcolor1)] \
3617                -column [incr col] -row 1 -padx 2 -pady 3 -sticky w
3618        tk_optionMenu $frame3.om$num entryvar($var) 0 1 2 3 4 5 6 7 8 9
3619        $frame3.om$num config -highlightthickness 0
3620        grid $frame3.om$num -column [incr col] -row 1 -padx 2 -pady 3 -sticky w
3621    }
3622    set expgui(atomreflbl) "$frame3.l1 $frame3.l4 $frame3.lom2 $frame3.lom3 $frame3.lom4 "
3623    set expgui(atomref) "$frame3.cf1 $frame3.cf2 $frame3.cf3 $frame3.om2 $frame3.om3 $frame3.om4"
3624   
3625    set coords [frame $frame3.coords  -width 100 -borderwidth 0  -bg $expgui(bkgcolor1)]
3626    grid $coords -column 0 -row 6 -columnspan 12 -sticky nsew
3627   
3628    set f3l1 [label $frame3.coords.l1 -text "Label" -bg $expgui(bkgcolor1)]
3629    grid $f3l1 -column 0 -row 4 -padx 2 -sticky nsw -pady 3
3630    set expgui(atomlabels) $f3l1
3631
3632    set f3e1 [entry  $frame3.coords.e1 -textvariable entryvar(label) -width 6]
3633    grid $f3e1 -column 1 -row 4 -padx 2 -sticky nsw -pady 3
3634    set expgui(atomentry) $f3e1
3635
3636    set f3l8 [label $frame3.coords.l8 -text "Coordinates" -bg $expgui(bkgcolor1)]
3637    grid $f3l8 -column 2 -row 4 -padx 2 -sticky nsw -pady 3
3638    lappend expgui(atomlabels) $f3l8
3639    set f3l11 [label $frame3.coords.l11 -text "Occupancy" -bg $expgui(bkgcolor1)]
3640    grid $f3l11 -column 6 -row 4 -padx 2 -sticky nsw -pady 3
3641    lappend expgui(atomlabels) $f3l11
3642
3643    foreach var {x y z frac} col {3 4 5 7} {
3644        set entrybox($var) [entry $frame3.coords.e$var \
3645                -textvariable entryvar($var) -width 10]
3646        grid $entrybox($var) -column $col -row 4 -padx 2 -sticky nsw -pady 3
3647        lappend expgui(atomentry) $entrybox($var)
3648    }
3649
3650
3651    set f3f31 [frame $frame3.f3f31  -width 100 -borderwidth 0 -bg $expgui(bkgcolor1)]
3652    grid $f3f31 -column 0 -row 7 -columnspan 12
3653    set expgui(anisolabels) {}
3654    foreach lbl {13 14 15 16 17 18} txt {Uiso U22 U33 U12 U13 U23} {
3655        lappend expgui(anisolabels)  [\
3656                label $f3f31.l$lbl -text $txt -bg $expgui(bkgcolor1)
3657        ]
3658    }
3659    set expgui(anisoentry) {}
3660    foreach i {e13 e14 e15 e16 e17 e18} var {U11 U22 U33 U12 U13 U23} { 
3661        lappend expgui(anisoentry) [\
3662                entry $f3f31.$i -textvariable entryvar($var) \
3663                -width 10]
3664        set entrybox($var) $f3f31.$i
3665    }
3666   
3667    set col 0
3668    foreach item1 $expgui(anisolabels) item2 $expgui(anisoentry) {
3669        grid $item1 -column $col -row 0 -sticky nsw -pady 3
3670        incr col
3671        grid $item2 -column $col -row 0 -sticky nsw -pady 3
3672        incr col
3673    }
3674    # --------------------------- End Edit Box -------------------------
3675   
3676    #/\ /\ /\ /\ /\ /\ /\ END OF PHASE PANE CODE /\ /\ /\ /\ /\ /\ /\ /\ /
3677    # resize in case the pane needs more space
3678    ResizeNotebook
3679}
3680
3681# called to create a window for editing unit cell constants
3682proc EditCellConstants {} {
3683    global expgui entrybox
3684    set spg [phaseinfo $expgui(curPhase) spacegroup]
3685    set laueaxis [GetLaue $spg]
3686    set vary ""
3687    set equivL ""
3688    set equivA ""
3689    switch -exact $laueaxis {
3690        1bar {set vary "a b c alpha beta gamma"}
3691        2/ma {set vary "a b c alpha"}
3692        2/mb {set vary "a b c beta"}
3693        2/mc {set vary "a b c gamma"}
3694        mmm  {set vary "a b c"}
3695        4/m  -
3696        4/mmm {set vary "a c"; set equivL "a b"} 
3697        3barR     -
3698        "3bar mR" {
3699            set vary "a alpha"
3700            set equivL "a b c"
3701            set equivA "alpha beta gamma"
3702        }
3703        3bar    -
3704        3barm1  -
3705        3bar1m  -
3706        6/m     -
3707        6/mmm  {set vary "a c";set equivL "a b"}
3708        "m 3"  -
3709        m3m    {set vary a;set equivL "a b c"}
3710        default {
3711            MyMessageBox -parent . -title "Laue problem" \
3712                    -message "Error processing Laue code: $laueaxis\nError in space group \"$spg\"?\nUnable to edit cell. Fix or use EXPEDT." \
3713                    -icon warning -type OK -default ok \
3714                    -helplink "expguierr.html BadLaue"
3715        }
3716    }
3717    set row 0
3718    set w .cell
3719    toplevel $w -bg beige
3720    wm title $w "Edit Cell Parameters" 
3721#    bind $w <Key-F1> "MakeWWWHelp expgui3.html EditBackground"
3722    bind $w <Return> "set expgui(temp) 1; destroy $w"
3723    pack [label $w.l1 -bg yellow -anchor center -justify center \
3724            -text "Edit unit cell parameters for phase #$expgui(curPhase)" \
3725            ] -side top -expand yes -fill both
3726    pack [label $w.l2 -bg beige -justify left \
3727            -text "title: [phaseinfo $expgui(curPhase) name]\nSpace group: $spg\nLaue class: $laueaxis" \
3728            ] -side top -expand yes -fill both
3729    pack [frame $w.0 -bd 6 -relief groove  -bg beige \
3730            ] -side top -expand yes -fill both
3731    pack [frame $w.b -bg beige] -fill x -expand yes -side top
3732    grid [button $w.b.2 -text Continue -command "set expgui(temp) 1; destroy $w"] -row 0 -column 1
3733    grid [button $w.b.3 -text Cancel \
3734            -command "set expgui(temp) 0; destroy $w"] -row 0 -column 2
3735#    grid [button $w.b.help -text Help -bg yellow \
3736#           -command "MakeWWWHelp expgui3.html EditBackground"] \
3737#           -row 0 -column 4
3738
3739    global tmpvar
3740    trace variable tmpvar w TestCellEdit
3741    foreach ent {a b c alpha beta gamma} {
3742        set tmpvar($ent) [phaseinfo $expgui(curPhase) $ent]
3743    }
3744
3745    set frameLatt $w.0
3746    foreach col {2 4 6} var {a b c} lbl {a b c} {
3747        grid [label $frameLatt.l$var -text $lbl -bg beige] \
3748                -column $col -row $row -padx 5 -sticky e
3749        incr col
3750        if {[lsearch $equivL $var] == -1} {
3751            set v $var
3752        } else {
3753            set v [lindex $equivL 0]
3754        }
3755        if {[lsearch $vary $var] == -1} {
3756            grid [label $frameLatt.e$var -textvariable tmpvar($v) \
3757                    -width 10 -bg beige] \
3758                    -column $col -row $row -padx 5
3759        } else {
3760            grid [entry $frameLatt.e$var -textvariable tmpvar($v) \
3761                    -width 10] -column $col -row $row -padx 5
3762            set entrybox($var) $frameLatt.e$var 
3763        }
3764    }
3765    incr row
3766    foreach col {2 4 6} var {alpha beta gamma} lbl {a b g} {
3767        grid [label $frameLatt.l$var -text $lbl -bg beige] \
3768                -column $col -row $row -padx 5 -sticky e
3769        set font [$frameLatt.l$var cget -font]
3770        $frameLatt.l$var config -font "Symbol [lrange $font 1 end]"
3771
3772        incr col
3773        if {[lsearch $equivA $var] == -1} {
3774            set v $var
3775        } else {
3776            set v [lindex $equivA 0]
3777        }
3778        if {[lsearch $vary $var] == -1} {
3779            grid [label $frameLatt.e$var -textvariable tmpvar($v)\
3780                    -width 10 -bg beige] \
3781                    -column $col -row $row -padx 5
3782        } else {
3783            grid [entry $frameLatt.e$var -textvariable tmpvar($v) \
3784            -width 10] -column $col -row $row -padx 5
3785            set entrybox($var) $frameLatt.e$var 
3786        }
3787    }
3788    putontop $w
3789    tkwait window $w
3790    afterputontop
3791    global entryvar
3792    set change 0
3793    if {$expgui(temp)} {
3794        foreach var {a b c} {
3795            if {[lsearch $equivL $var] == -1} {
3796                set v $var
3797            } else {
3798                set v [lindex $equivL 0]
3799            }
3800            catch {
3801                expr [set val $tmpvar($v)]
3802                if {[phaseinfo $expgui(curPhase) $var] != $val} {
3803                    phaseinfo $expgui(curPhase) $var set $val
3804                    RecordMacroEntry "phaseinfo $expgui(curPhase) $var set $val" 0
3805                    set entryvar($var) $val
3806                    incr expgui(changed)                   
3807                    set change 1
3808                }
3809            }
3810        }
3811        foreach var {alpha beta gamma} {
3812            if {[lsearch $equivA $var] == -1} {
3813                set v $var
3814            } else {
3815                set v [lindex $equivA 0]
3816            }
3817            catch {
3818                expr [set val $tmpvar($v)]
3819                if {[phaseinfo $expgui(curPhase) $var] != $val} {
3820                    phaseinfo $expgui(curPhase) $var set $val
3821                    RecordMacroEntry "phaseinfo $expgui(curPhase) $var set $val" 0
3822                    set entryvar($var) $val
3823                    incr expgui(changed)                   
3824                    set change 1
3825                }
3826            }
3827        }
3828        RecordMacroEntry "incr expgui(changed)" 0
3829        if {$change} {
3830            # set the powpref warning (1 = suggested)
3831            if {$expgui(needpowpref) == 0} {set expgui(needpowpref) 1}
3832            append expgui(needpowpref_why) "\tCell parameters were changed\n"
3833        }
3834    }
3835    unset tmpvar
3836}
3837
3838# highlight errors in unit cell constants
3839proc TestCellEdit {var elem mode} {
3840    global tmpvar entrybox
3841    if {[catch {expr $tmpvar($elem)} errmsg]} {
3842        catch {$entrybox($elem) config -fg red}
3843    } else {
3844        catch {$entrybox($elem) config -fg black}
3845    }
3846}
3847
3848#-----------------------------------------------------------------------------
3849proc MakeHistPane {} {
3850    #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
3851    global expgui
3852   
3853    grid columnconfigure $expgui(histFrame) 0 -weight 1
3854    grid rowconfigure $expgui(histFrame) 1 -weight 1
3855    grid rowconfigure $expgui(histFrame) 2 -weight 1
3856    grid rowconfigure $expgui(histFrame) 3 -weight 1
3857
3858    grid [frame $expgui(histFrame).hs -class HistList] \
3859            -column 0 -row 0 -rowspan 10 -sticky nsew
3860    MakeHistBox $expgui(histFrame).hs
3861    bind $expgui(histFrame).hs.lbox <ButtonRelease-1>  {
3862        set expgui(curhist) [$expgui(histFrame).hs.lbox curselection]
3863        DisplayHistogram
3864    }
3865    bind $expgui(histFrame).hs.lbox <Button-3>  {
3866        if $expgui(globalmode) {
3867            $expgui(histFrame).hs.lbox selection set 0 end
3868            set expgui(curhist) [$expgui(histFrame).hs.lbox curselection]
3869            DisplayHistogram
3870        }
3871    }
3872   
3873    frame $expgui(histFrame).top -borderwidth 4 -relief groove
3874    grid [label $expgui(histFrame).top.txt] -row 0 -column 0
3875    foreach item {backBox diffBox absBox} num {2 3 4} title {Background "Diffractometer Constants" "Absorption/Reflectivity Correction"} {
3876        TitleFrame $expgui(histFrame).$item  \
3877            -borderwidth 4 -side left -relief groove -text $title
3878        set expgui($item) [$expgui(histFrame).$item getframe]
3879        grid $expgui(histFrame).$item -column 1 -row $num -sticky nsew
3880        grid rowconfigure $expgui(histFrame) $num -minsize 100
3881    }
3882    grid [frame $expgui(histFrame).bb] -column 1 -row 6
3883    if [file executable $expgui(exptool)] {
3884        button $expgui(histFrame).bb.newh -text "Add New\nHistogram" \
3885                -command MakeAddHistBox
3886        grid $expgui(histFrame).bb.newh -column 0 -row 1
3887    }
3888    button $expgui(histFrame).bb.excl \
3889            -text "Set Data Limits &\nExcluded Regions" -command excledit
3890    grid $expgui(histFrame).bb.excl -column 1 -row 1
3891
3892    button $expgui(histFrame).bb.use -text "Set Histogram\nUse Flags" \
3893            -command SetHistUseFlags
3894    grid $expgui(histFrame).bb.use -column 2 -row 1
3895
3896    # BACKGROUND information.
3897    # <<<<<<<<<<<<<<<<<<<<<<<<< BACKGROUND  <<<<<<<<<<<<<<<<<<<<<
3898    grid [frame $expgui(backBox).frm1 ] -row 0 -column 0  -columnspan 11
3899    grid [label $expgui(backBox).frm1.lBGType \
3900            -textvariable expgui(backtypelbl)] \
3901            -row 1 -column 0 -sticky nws  -padx 2 -pady 3
3902    grid [label $expgui(backBox).frm1.lBGTerms \
3903            -textvariable expgui(backtermlbl)] \
3904            -row 1 -column 1 -sticky nws  -padx 2 -pady 3
3905    grid [button $expgui(backBox).frm1.edit -textvariable expgui(bkglbl) \
3906            -command editbackground] \
3907            -row 1 -column 2 -columnspan 3 -sticky w -padx 2 -pady 3
3908    grid [frame $expgui(backBox).frm2 ] \
3909            -row 1 -column 0 -columnspan 11 -sticky e
3910    grid [label $expgui(backBox).frm2.lfBG -text "  Refine background" ] \
3911            -row 2 -column 1 -sticky news -padx 4 -pady 3
3912    grid [checkbutton $expgui(backBox).frm2.rfBG -text "" \
3913            -variable  entryvar(bref) ] \
3914            -row 2 -column 2 -sticky news -padx 4 -pady 3
3915    grid [label $expgui(backBox).frm2.lBGDamp -text Damping ] \
3916            -row 2 -column 3 -sticky w    -padx 2 -pady 3
3917    tk_optionMenu $expgui(backBox).frm2.om  entryvar(bdamp) 0 1 2 3 4 5 6 7 8 9
3918    grid $expgui(backBox).frm2.om \
3919            -row 2 -column 4 -sticky news -padx 4 -pady 3 -sticky e
3920    # Absorption information.
3921    set expgui(abstypelbl) ""
3922    grid [label $expgui(absBox).lbl1 \
3923              -textvariable expgui(abstypelbl)] \
3924            -row 1 -column 1 -columnspan 5 -sticky nws
3925    grid [label $expgui(absBox).rf1 -text "  Refine Abs./Refl." ] \
3926            -row 2 -column 1 -sticky news -padx 2 -pady 3
3927    grid [checkbutton $expgui(absBox).rf2 -text "" \
3928            -variable  entryvar(absref) ] \
3929            -row 2 -column 2 -sticky news -padx 4 -pady 3
3930    grid [label $expgui(absBox).d1 -text Damping ] \
3931            -row 2 -column 3 -sticky w    -padx 2 -pady 3
3932    tk_optionMenu $expgui(absBox).d2  entryvar(absdamp) 0 1 2 3 4 5 6 7 8 9
3933    grid $expgui(absBox).d2 \
3934        -row 2 -column 4 -sticky news -padx 4 -pady 3 -sticky e
3935    grid [button $expgui(absBox).edit -textvariable expgui(abslbl) \
3936              -command editabsorption] \
3937        -row 2 -column 5 -sticky nsw -padx 2 -pady 3
3938
3939    #^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^END OF HISTOGRAM PANE CODE ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
3940    # insert the histograms & resize in case the pane needs more space   
3941    sethistlist
3942    ResizeNotebook
3943}
3944###############################################################################
3945proc MakeScalingPane {} {
3946    #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
3947    global expgui entryvar entrybox
3948
3949    pack [frame $expgui(fracFrame).hs -class HistList] \
3950            -side left -expand y -fill both
3951    MakeHistBox $expgui(fracFrame).hs
3952    bind $expgui(fracFrame).hs.lbox <ButtonRelease-1> {
3953        set expgui(curhist) [$expgui(fracFrame).hs.lbox curselection]
3954        DisplayFrac
3955    }
3956    bind $expgui(fracFrame).hs.lbox <Button-3>  {
3957        if $expgui(globalmode) {
3958            $expgui(fracFrame).hs.lbox selection set 0 end
3959            set expgui(curhist) [$expgui(fracFrame).hs.lbox curselection]
3960            DisplayFrac
3961        }
3962    }
3963
3964    pack [frame $expgui(fracFrame).f1] -fill both -expand true
3965    # Create a large canvas area containing a frame for each phase in the data set.
3966    # The canvas and vertical scrollbar are inside a frame called f1
3967    TitleFrame $expgui(fracFrame).f1.scaleBox \
3968        -borderwidth 4 -text "Scale Factor"
3969    #       -borderwidth 4 -width 600 -height 100 -label "Scale Factor"
3970    grid $expgui(fracFrame).f1.scaleBox -column 0 -row 0 -sticky nsew -columnspan 2
3971    set expgui(scaleBox)  [$expgui(fracFrame).f1.scaleBox getframe]
3972    grid [label $expgui(scaleBox).histSFLabel -text Scale] \
3973        -row 1 -column 0 -sticky nws  -padx 2 -pady 3
3974    grid [entry $expgui(scaleBox).ent1 -textvariable entryvar(scale) -width 15] \
3975            -row 1 -column 1 -sticky ew -padx 4 -pady 3
3976    set entrybox(scale) $expgui(scaleBox).ent1
3977
3978    button $expgui(scaleBox).but1 -text "Set Globally" \
3979            -command "editglobalparm histinfo scale {Scale Factor}"
3980
3981    grid [label $expgui(scaleBox).histSFRLabel -text " Refine"] \
3982            -row 1 -column 2 -sticky nws  -padx 2 -pady 3
3983    grid [checkbutton $expgui(scaleBox).rf -variable entryvar(sref)] \
3984            -row 1 -column 3 -sticky news -padx 4 -pady 3
3985    grid [label $expgui(scaleBox).lD1 -text "Damping"] \
3986            -row 1 -column 4 -sticky w    -padx 2 -pady 3
3987    tk_optionMenu $expgui(scaleBox).om entryvar(sdamp) 0 1 2 3 4 5 6 7 8 9
3988    grid $expgui(scaleBox).om \
3989            -row 1 -column 5 -sticky news -padx 4 -pady 3
3990    grid columnconfigure $expgui(scaleBox) 6  -weight 1
3991   
3992    grid [TitleFrame $expgui(fracFrame).f1.phaseFrac -bd 4 \
3993              -text "Phase Fractions" -relief groove] \
3994        -sticky news -row 1 -column 0 -columnspan 2
3995    set PhaseFractBox [$expgui(fracFrame).f1.phaseFrac getframe]
3996    grid columnconfigure $expgui(fracFrame).f1 0 -weight 1
3997    grid rowconfigure $expgui(fracFrame).f1 1 -weight 1
3998   
3999    grid [set expgui(FracBox) [canvas $PhaseFractBox.fracBox \
4000            -scrollregion {0 0 5000 500} \
4001            -yscrollcommand "$PhaseFractBox.yscroll set" \
4002            -width 500 -height 350 -bg lightgrey]] \
4003            -sticky  news -row 1 -column 0
4004    grid [scrollbar $PhaseFractBox.yscroll \
4005            -command "$expgui(FracBox) yview" \
4006            -orient vertical] \
4007            -sticky ns -row 1 -column 1
4008    frame $expgui(FracBox).f -bd 0
4009    $expgui(FracBox) create window 0 0 -anchor nw  -window $expgui(FracBox).f
4010
4011    # the rest of the page is created in DisplayFrac
4012
4013    # insert the histograms & resize in case the pane needs more space
4014    sethistlist
4015    ResizeNotebook
4016    # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ END OF SCALING PANE CODE ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
4017}
4018###############################################################################
4019proc MakeProfilePane {} {
4020    global expgui
4021    # 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
4022    pack [frame $expgui(profFrame).hs -class HistList] \
4023            -side left -expand y -fill both
4024    MakeHistBox $expgui(profFrame).hs
4025    bind $expgui(profFrame).hs.lbox <ButtonRelease-1> {
4026        set expgui(curhist) [$expgui(profFrame).hs.lbox curselection]
4027        DisplayProfile
4028    }
4029    bind $expgui(profFrame).hs.lbox <Button-3>  {
4030        if $expgui(globalmode) {
4031            $expgui(profFrame).hs.lbox selection set 0 end
4032            set expgui(curhist) [$expgui(profFrame).hs.lbox curselection]
4033            DisplayProfile
4034        }
4035    }
4036
4037    # Create a large canvas area containing a frame for each phase in the data set.
4038    # The canvas and vertical scrollbar are inside a frame called f1
4039    pack [frame $expgui(profFrame).f1] -fill both -expand true
4040    grid [set expgui(ProfileBox) [canvas $expgui(profFrame).f1.profileBox \
4041            -scrollregion {0 0 5000 500} -width 500 -height 350 -bg lightgrey]] \
4042            -sticky  news -row 0 -column 0
4043    grid [scrollbar $expgui(profFrame).f1.yscroll -orient vertical] \
4044            -sticky ns -row 0 -column 1
4045   
4046    $expgui(ProfileBox) config -yscrollcommand "$expgui(profFrame).f1.yscroll set"
4047    $expgui(profFrame).f1.yscroll config -command { $expgui(ProfileBox) yview }
4048   
4049    grid columnconfigure $expgui(profFrame).f1 1 -weight 1
4050    grid rowconfigure $expgui(profFrame).f1 0 -weight 1
4051    frame $expgui(ProfileBox).f -bd 0
4052    $expgui(ProfileBox) create window 0 0 -anchor nw  -window $expgui(ProfileBox).f
4053   
4054    # insert the histograms & resize in case the pane needs more space
4055    sethistlist
4056    ResizeNotebook
4057    # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ END OF PROFILE PANE CODE ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
4058}
4059
4060##############################################################################
4061# 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
4062array set printopts {
4063    0 "Print the reciprocal metric tensor changes"
4064    1 "Print the correlation matrix"
4065    2 "Print the Least-Squares matrices and vectors"
4066    4 "Print the linear constraint matrices"
4067    5 "Print the applied  shifts and shift factors"
4068    6 "Print the reciprocal metric tensor Var-Covar terms"
4069    7 "Print all parameters for each cycle"
4070    8 "Print summary shift/esd data after last cycle"
4071    9 "Print zero/unit pole figure constraint terms"
4072    10 "Output parameter name, value & esd to file"
4073}
4074pack [frame $expgui(lsFrame).hs -class HistList] \
4075        -side left -expand y -fill both
4076MakeHistBox $expgui(lsFrame).hs
4077bind $expgui(lsFrame).hs.lbox <ButtonRelease-1> {
4078    set expgui(curhist) [$expgui(lsFrame).hs.lbox curselection]
4079    SetupExtractHist
4080}
4081bind $expgui(lsFrame).hs.lbox <Button-3>  {
4082    if $expgui(globalmode) {
4083        $expgui(lsFrame).hs.lbox selection set 0 end
4084        set expgui(curhist) [$expgui(lsFrame).hs.lbox curselection]
4085        SetupExtractHist
4086    }
4087}
4088
4089pack [frame $expgui(lsFrame).f1] -fill both -expand true
4090set row 0
4091grid [label $expgui(lsFrame).f1.his1 -pady 6 -text "Last History:"] -row $row -column 0
4092grid [label $expgui(lsFrame).f1.his2 -relief groove -bd 2 -pady 6 \
4093        -textvariable expgui(last_History)] \
4094        -row $row -column 1 -columnspan 5 -sticky w
4095incr row
4096grid [label $expgui(lsFrame).f1.tit1 -pady 6 -text "Title:"] -row $row -column 0
4097grid [entry $expgui(lsFrame).f1.tit2 \
4098        -textvariable entryvar(title) -width 48] \
4099        -row $row -column 1 -columnspan 5 -sticky w
4100set entrycmd(title) "expinfo title"
4101
4102incr row
4103grid rowconfigure $expgui(lsFrame).f1 $row -weight 1
4104incr row
4105grid [frame $expgui(lsFrame).f1.b -bd 4 -relief groove] \
4106        -row $row -column 0 -columnspan 2 -pady 3  -sticky s
4107grid [label $expgui(lsFrame).f1.b.lcyc -text "Number of Cycles"] -row 0 -column 0
4108grid [entry $expgui(lsFrame).f1.b.ecyc -width 3 \
4109        -textvariable entryvar(cycles)] -row 0 -column 1
4110set entrybox(cycles) $expgui(lsFrame).f1.b.ecyc
4111
4112grid [frame $expgui(lsFrame).f1.cv -bd 4 -relief groove] \
4113        -row $row -column 2 -sticky ew
4114grid [label $expgui(lsFrame).f1.cv.l -text "Convergence Criterion"] \
4115        -row 0 -column 0 -columnspan 2
4116grid [label $expgui(lsFrame).f1.cv.v -textvariable expgui(convlbl)] -row 1 -column 0
4117grid [scale $expgui(lsFrame).f1.cv.s -orient horizontal \
4118        -from -200 -to 200 -showvalue 0 -command SetConv -resolution 10 \
4119        -variable expgui(convg)] -row 1 -column 1
4120
4121incr row
4122grid [menubutton $expgui(lsFrame).f1.lprint -textvariable expgui(printopt) \
4123        -menu $expgui(lsFrame).f1.lprint.menu -bd 4 -relief raised \
4124        ] -row $row -column 0 -columnspan 2 
4125menu $expgui(lsFrame).f1.lprint.menu
4126foreach num [lsort -integer [array names printopts]] {
4127    $expgui(lsFrame).f1.lprint.menu add checkbutton \
4128        -label "$printopts($num) ([expr int(pow(2,$num))])"\
4129        -variable entryvar(printopt$num)
4130}
4131
4132grid [frame $expgui(lsFrame).f1.marq -bd 4 -relief groove] \
4133        -row $row -column 2 -sticky ew
4134grid [label $expgui(lsFrame).f1.marq.l -text "Marquardt Damping"] \
4135        -row 0 -column 0 -columnspan 2
4136grid [label $expgui(lsFrame).f1.marq.v -textvariable expgui(marq)] \
4137        -row 1 -column 0
4138grid [scale $expgui(lsFrame).f1.marq.s -orient horizontal \
4139        -from 1.0 -to 9.99 -showvalue 0 -command SetMarq -resolution 0.01 \
4140        -variable expgui(marq)] -row 1 -column 1
4141
4142incr row
4143grid [frame $expgui(lsFrame).f1.d -bd 4 -relief groove] \
4144        -row $row -column 2 -sticky ew
4145grid [label $expgui(lsFrame).f1.d.lmbw -text "LS matrix bandwidth"] -row 0 -column 0
4146grid [entry $expgui(lsFrame).f1.d.embw -width 4 \
4147        -textvariable entryvar(mbw)] -row 0 -column 1
4148set entrybox(mbw) $expgui(lsFrame).f1.d.embw
4149
4150incr row
4151grid rowconfigure $expgui(lsFrame).f1 $row -weight 1
4152
4153incr row
4154grid [TitleFrame $expgui(lsFrame).f1.a -bd 4 -relief groove \
4155          -text "Reflection Intensity Extraction" \
4156         ] -row $row -column 0 -columnspan 6
4157set expgui(FobsExtractFrame) [$expgui(lsFrame).f1.a getframe]
4158
4159grid [frame $expgui(FobsExtractFrame).c -bd 4 -relief groove] \
4160        -row 0 -column 8 -columnspan 3 -sticky ens
4161grid [label $expgui(FobsExtractFrame).c.fol -text "Extract Fobs"] \
4162        -row 0 -column 2
4163grid [checkbutton $expgui(FobsExtractFrame).c.foc \
4164        -variable entryvar(fobsextract)] -row 0 -column 3
4165
4166grid [frame $expgui(FobsExtractFrame).d -bd 4 -relief groove] \
4167        -row 0 -column 3 -columnspan 5 -sticky ens
4168grid [label $expgui(FobsExtractFrame).d.fol -text "LeBail damping"] \
4169        -row 0 -column 2
4170tk_optionMenu $expgui(FobsExtractFrame).d.d entryvar(LBdamp) \
4171        0 1 2 3 4 5 6 7 8 9
4172grid $expgui(FobsExtractFrame).d.d -row 0 -column 3
4173incr row
4174grid rowconfigure $expgui(lsFrame).f1 $row -weight 1
4175
4176
4177foreach num {1 2 3 4 5 6 7 8 9} {
4178    grid [label $expgui(FobsExtractFrame).l$num -text $num] -row 1 -column $num
4179    grid [radiobutton $expgui(FobsExtractFrame).cc$num \
4180            -command "HistExtractSet $num" \
4181            -variable expgui(Fextract$num) -value 0] \
4182            -row 2 -column $num
4183    grid [radiobutton $expgui(FobsExtractFrame).ca$num \
4184            -command "HistExtractSet $num" \
4185            -variable expgui(Fextract$num) -value 1] \
4186            -row 3 -column $num
4187    grid [radiobutton $expgui(FobsExtractFrame).cb$num \
4188            -command "HistExtractSet $num" \
4189            -variable expgui(Fextract$num) -value 2] \
4190            -row 4 -column $num
4191}
4192set expgui(ExtractSettingsRadiobuttons) $expgui(FobsExtractFrame).cc
4193lappend expgui(ExtractSettingsRadiobuttons) $expgui(FobsExtractFrame).ca
4194lappend expgui(ExtractSettingsRadiobuttons) $expgui(FobsExtractFrame).cb
4195
4196grid [label $expgui(FobsExtractFrame).t \
4197        -text "Extraction\nMethod" -anchor c] \
4198        -column 0 -row 0 -sticky n
4199grid [label $expgui(FobsExtractFrame).t0 -text "(Phase #)" -anchor c] \
4200        -column 10 -row 1 -sticky w
4201grid [label $expgui(FobsExtractFrame).t1 -text "Rietveld" -anchor c] -column 0 -row 2
4202grid [label $expgui(FobsExtractFrame).t2 -text "F(calc) Weighted" -anchor c] -column 0 -row 3
4203grid [label $expgui(FobsExtractFrame).t3 -text "Equally Weighted" -anchor c] -column 0 -row 4
4204grid [label $expgui(FobsExtractFrame).t2a -text "(Model biased)" -anchor c] -column 10 -row 3
4205grid [label $expgui(FobsExtractFrame).t3a -text "(Le Bail method)" -anchor c] -column 10 -row 4
4206
4207proc InitLSvars {} {
4208    global expgui
4209    set expgui(convg) [set expgui(convinit) [expinfo convg]]
4210    set expgui(convlbl) [format %5.2f [expr pow(10,$expgui(convg)/100.)]]
4211    set expgui(marq) [set expgui(marqinit) [expinfo marq]]
4212    set expgui(mbw) [set expgui(mbwinit) [expinfo mbw]]
4213}
4214proc SetConv {x} {
4215    global expgui
4216    if {$x != $expgui(convinit) && $expgui(changed) <= 0} {
4217        incr expgui(changed)
4218        RecordMacroEntry "incr expgui(changed)" 0
4219    }
4220    if {$expgui(changed)} {
4221        expinfo convg set $x
4222        RecordMacroEntry "expinfo convg set $x" 0
4223    }
4224    set expgui(convlbl) [format %5.2f [expr {pow(10,$x/100.)}]]
4225}
4226proc SetMarq {x} {
4227    global expgui
4228    if {$x != $expgui(marqinit) && $expgui(changed) <= 0} {
4229        incr expgui(changed)
4230        RecordMacroEntry "incr expgui(changed)" 0
4231    }
4232    if {$expgui(changed)} {
4233        expinfo marq set $x
4234        RecordMacroEntry "expinfo marq set $x" 0
4235    }
4236}
4237# ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ END OF LS PANE CODE ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
4238#-------------------------------------------------------------------------
4239#-------------------------------------------------------------------------
4240#vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv THE MENU BAR vvvvvvvvvvvvvvvvvvvvvv
4241#---- file menu button
4242menubutton $expgui(fm).file -text File -menu $expgui(fm).file.menu
4243menu $expgui(fm).file.menu
4244if $expgui(debug) {
4245    $expgui(fm).file.menu add command -label "Reset" -command "reset"
4246}
4247if {$expgui(shell)} {
4248    $expgui(fm).file.menu add command -label "Open" -command readnewexp
4249    $expgui(fm).file.menu add command -label "expnam" -command readnewexp
4250}
4251$expgui(fm).file.menu add command -label "Save" -underline 0 \
4252        -command savearchiveexp
4253foreach c {s S} {bind . <Alt-$c> [list savearchiveexp]}
4254$expgui(fm).file.menu add command -label "Save As" \
4255        -command "SaveAsFile"
4256$expgui(fm).file.menu add command -label "Reread .EXP file" \
4257        -command {rereadexp $expgui(expfile)}
4258
4259#---- help menu button
4260menubutton $expgui(fm).help -text Help -menu $expgui(fm).help.menu
4261menu $expgui(fm).help.menu
4262$expgui(fm).help.menu add command -command showhelp -underline 0 \
4263        -label "Help Summary"
4264$expgui(fm).help.menu add command -command MakeWWWHelp  \
4265        -label "Help on current pane"
4266$expgui(fm).help.menu add command -command "MakeWWWHelp menu" \
4267        -label "Help on menu"
4268if {$tcl_platform(platform) == "windows"} {
4269    $expgui(fm).help.menu add command -label "Open console" \
4270        -command {console show}
4271}
4272if {![catch {package require tkcon} errmsg]} {
4273    $expgui(fm).help.menu add command -label "Open tkcon console" \
4274        -command {tkcon show}
4275} elseif {[file exists [file join $expgui(scriptdir) tkcon tkcon.tcl]]} {
4276    $expgui(fm).help.menu add command -label "Open tkcon console" \
4277        -command {source [file join $expgui(scriptdir) tkcon tkcon.tcl]}
4278} else {
4279    $expgui(fm).help.menu add command -label "Turn on debug puts" \
4280        -command {set expgui(debug) 1}
4281}
4282# add update commands to menu
4283if {[file exists [file join  $expgui(gsasdir) .svn]]} {
4284    $expgui(fm).file.menu add command -command CheckAndDoUpdate -label "Update GSAS/EXPGUI"
4285} else {
4286    $expgui(fm).file.menu add command  -state disabled -label "Self-updating not installed"
4287}
4288foreach c {h H} {bind . <Alt-$c> [list showhelp]}
4289# define help actions
4290bind . <Key-F1> MakeWWWHelp
4291$expgui(fm).help.menu add command -label "About..." -command About
4292$expgui(fm).help.menu add command -label "Cite..." -command Cite
4293
4294#---- options menu button
4295menubutton $expgui(fm).option -text Options \
4296        -menu $expgui(fm).option.menu
4297menu $expgui(fm).option.menu
4298
4299if {$expgui(shell)} {
4300    $expgui(fm).option.menu add checkbutton  -label "Archive EXP" \
4301            -variable expgui(archive)
4302    $expgui(fm).option.menu add checkbutton  -label "Use DISAGL window" \
4303            -variable expgui(disaglSeparateBox)
4304    $expgui(fm).option.menu  add checkbutton -label "Autoload EXP" \
4305            -variable expgui(autoexpload)
4306    $expgui(fm).option.menu  add checkbutton -label "Prompt after GSAS run" \
4307            -variable expgui(execprompt)
4308    $expgui(fm).option.menu  add checkbutton -label "Iconify during GSAS" \
4309            -variable expgui(autoiconify)
4310    if {$tcl_platform(platform) == "windows" && \
4311            $tcl_platform(os) == "Windows 95"} {
4312        $expgui(fm).option.menu  add checkbutton -label "Autostart GRWND" \
4313                -variable expgui(autoGRWND)
4314    }
4315}
4316$expgui(fm).option.menu add cascade -menu  $expgui(fm).option.menu.asort \
4317        -label "Sort atoms by"
4318
4319set expgui(asorttype) number
4320menu $expgui(fm).option.menu.asort
4321foreach opt {number type mult x y z occupancy} {
4322    $expgui(fm).option.menu.asort add radiobutton -command {DisplayAllAtoms $expgui(curPhase)}\
4323            -label $opt -value $opt -variable expgui(asorttype) 
4324}
4325
4326$expgui(fm).option.menu add cascade -menu  $expgui(fm).option.menu.hsort \
4327        -label "Sort histograms by"
4328
4329set expgui(hsorttype) number
4330menu $expgui(fm).option.menu.hsort
4331$expgui(fm).option.menu.hsort add radiobutton -command sethistlist \
4332        -label number -value number -variable expgui(hsorttype) 
4333$expgui(fm).option.menu.hsort add radiobutton -command sethistlist \
4334        -label "Histogram type" -value type -variable expgui(hsorttype) 
4335$expgui(fm).option.menu.hsort add radiobutton -command sethistlist \
4336        -label "Bank #" -value bank -variable expgui(hsorttype) 
4337$expgui(fm).option.menu.hsort add radiobutton -command sethistlist \
4338        -label "Angle/Wavelength" -value angle -variable expgui(hsorttype) 
4339
4340#---- Global mode menu button
4341$expgui(fm).option.menu add cascade -menu $expgui(fm).option.menu.editmode \
4342        -label "Multiple hist. selection"
4343menu $expgui(fm).option.menu.editmode
4344$expgui(fm).option.menu.editmode add radiobutton  -label "Off" \
4345        -variable expgui(globalmode) -value 0 \
4346        -command sethistlist
4347$expgui(fm).option.menu.editmode add radiobutton  -label "All" \
4348        -variable expgui(globalmode) -value 6 \
4349        -command sethistlist
4350$expgui(fm).option.menu.editmode add radiobutton  -label "TOF" \
4351        -variable expgui(globalmode) -value 1 \
4352        -command sethistlist
4353$expgui(fm).option.menu.editmode add radiobutton  -label "CW Neutron" \
4354        -variable expgui(globalmode) -value 2  \
4355        -command sethistlist
4356$expgui(fm).option.menu.editmode add radiobutton  -label "Alpha12 Xray" \
4357        -variable expgui(globalmode) -value 3 \
4358        -command sethistlist
4359$expgui(fm).option.menu.editmode add radiobutton  -label "Monochromatic Xray" \
4360        -variable expgui(globalmode) -value 4 \
4361        -command sethistlist
4362$expgui(fm).option.menu.editmode add radiobutton  -label "Energy Disp Xray" \
4363        -variable expgui(globalmode) -value 5 \
4364        -command sethistlist
4365$expgui(fm).option.menu.editmode add separator
4366$expgui(fm).option.menu.editmode add checkbutton \
4367        -label "Group phases together" \
4368        -variable expgui(globalphasemode) \
4369        -command sethistlist
4370
4371set expgui(globalmode) 0
4372set expgui(globalphasemode) 1
4373
4374if {$tcl_platform(platform) == "unix"} {
4375    $expgui(fm).option.menu  add checkbutton -label "Override backspace" \
4376            -variable env(GSASBACKSPACE)
4377}
4378
4379$expgui(fm).option.menu add cascade -menu  $expgui(fm).option.menu.font \
4380        -label "Screen font"
4381menu $expgui(fm).option.menu.font
4382foreach f {10 11 12 13 14 16 18 20 22} {
4383    $expgui(fm).option.menu.font add radiobutton \
4384            -command {SetTkDefaultOptions $expgui(font); ResizeFont .; ResizeNotebook} \
4385        -label $f -value $f -variable expgui(font) -font "Helvetica -$f"
4386}
4387
4388$expgui(fm).option.menu  add checkbutton -label "Show EXPTOOL output" \
4389        -variable expgui(showexptool)
4390$expgui(fm).option.menu add command -label "Save Options" \
4391        -command "SaveOptions"
4392$expgui(fm).option.menu add command -label "Save Position" \
4393        -command "SavePosition"
4394pack $expgui(fm).file $expgui(fm).option -side left  -in $expgui(fm)
4395
4396if {$expgui(shell)} {
4397    foreach menu $expgui(menunames) {
4398        set m [string tolower $menu]
4399        pack [menubutton $expgui(fm).$m -text $menu \
4400                -menu $expgui(fm).$m.menu] -side left
4401        menu $expgui(fm).$m.menu
4402    }
4403}
4404pack $expgui(fm).help  -side right -in $expgui(fm)
4405
4406if {$expgui(shell)} {
4407    # add an export command to the last menu that gets filled in later
4408    $expgui(fm).$m.menu add  cascade -label "Coord Export" \
4409            -menu $expgui(fm).$m.menu.coordexp
4410    menu $expgui(fm).$m.menu.coordexp \
4411            -postcommand "BuildCoordExpMenu $expgui(fm).$m.menu.coordexp"
4412    $expgui(fm).$m.menu.coordexp add command -label "Building menu" \
4413            -state disabled
4414    $expgui(fm).$m.menu.coordexp add command -label "Please wait..." \
4415            -state disabled
4416
4417    $expgui(fm).$m.menu add  cascade -label "CIF Export" \
4418            -menu $expgui(fm).$m.menu.cifexp
4419    menu $expgui(fm).$m.menu.cifexp
4420    $expgui(fm).$m.menu.cifexp add command -label gsas2cif \
4421            -command "runGSASwEXP gsas2cif"
4422    $expgui(fm).$m.menu.cifexp add command -label FillTemplate \
4423            -command "exec $wishshell [file join $expgui(scriptdir) fillcif.tcl] \[file root \[file tail \$expgui(expfile)]]"
4424    $expgui(fm).$m.menu.cifexp add command -label CIFselect \
4425            -command {
4426        if {[info procs CIFselect] == ""} {
4427            source [file join $expgui(scriptdir) cifselect.tcl]
4428        }
4429        CIFselect $expgui(expfile)
4430    }
4431    # add the commands in expgui_menulist
4432    foreach menu [array names expgui_menulist ] {
4433        foreach cmd $expgui_menulist($menu) {
4434            set action {}
4435            set opt {}
4436            catch {set action [lindex $expgui_cmdlist($cmd) 0]}
4437            catch {set opt [lindex $expgui_cmdlist($cmd) 2]}
4438            if {$expgui(debug) && $action == ""} {puts "blank command for $cmd"}
4439            if {$action != "" && $action != "-"} {
4440                eval $expgui(fm).$menu.menu add command \
4441                        -label $cmd $opt -command [list [subst $action]]
4442                if {[lindex $opt 0] == "-underline"} {
4443                    catch {
4444                        set num [lindex $opt 1]
4445                        set key [string range $cmd $num $num]
4446                        bind . <Alt-[string tolower $key]> [subst $action]
4447                        bind . <Alt-[string toupper $key]> [subst $action]
4448                    }
4449                }
4450            }
4451        }
4452    }
4453}
4454
4455# Macro menu
4456$expgui(fm).macro.menu add checkbutton  -label "Record EXPGUI macro" \
4457    -variable expgui(RecordMacro)
4458$expgui(fm).macro.menu add command -label "Add comment to macro" \
4459    -command AddCommentMacroFile
4460$expgui(fm).macro.menu add command -label "Replay macro line-at-a-time" \
4461    -command {ReplayMacroFile 1}
4462$expgui(fm).macro.menu add command -label "Replay macro all at once" \
4463    -command {ReplayMacroFile 0}
4464$expgui(fm).macro.menu add checkbutton  -label "Show GSAS output in window" \
4465    -variable expgui(ShowGENLES)
4466bind . <Control-m> {set expgui(RecordMacro) [expr ! $expgui(RecordMacro)]}
4467set expgui(RecordMacro) 0
4468set expgui(MacroRunning) 0
4469set expgui(MacroStatus) "?"
4470set expgui(ShowGENLES) 1
4471trace variable expgui(RecordMacro) w SetRecordMacroOnOff
4472
4473# setup command help
4474foreach cmd [array names expgui_cmdlist] {
4475    set help {}
4476    catch {set help [lindex $expgui_cmdlist($cmd) 1]}
4477    if {$help == ""} {
4478        if {$expgui(debug)} {puts "no help for $cmd"}
4479    } else {
4480        # remove
4481        regsub -all \x09 $help " " help
4482        # preserve blank lines
4483        regsub -all \x0A\x0A $help "AAA1234567890AAA" help
4484        regsub -all \x0A $help " " help
4485        regsub -all "AAA1234567890AAA" $help \x0A\x0A help
4486        regsub -all " +" $help " " help
4487        set expgui_helplist($cmd) [string trim $help]
4488    }
4489}
4490if {$expgui(shell)} {
4491    # set up button bar
4492    foreach cmd $expgui(buttonlist) {
4493        set action {}
4494        catch {set action [lindex $expgui_cmdlist($cmd) 0]}
4495        if {$expgui(debug) && $action == ""} {puts "blank command for $cmd"}
4496        if {$action != ""} {
4497            pack [eval button .bar.$cmd -bg beige -activebackground yellow \
4498                    -padx 2m -pady 0 \
4499                    -text $cmd -command [list [subst $action]]] -side left
4500        }
4501    }
4502}
4503
4504if {$tcl_platform(os) == "Darwin"} {
4505#    $expgui(fm).file.menu add command -label "Create AppleScript" -command MakeAppleScript
4506    $expgui(fm).option.menu add checkbutton -label "Assign app to .EXP files" \
4507        -variable expgui(MacAssignApp)
4508}
4509$expgui(fm).file.menu add command -label "Exit"  -underline 1 -command catchQuit
4510foreach c {X x} {bind . <Alt-$c> [list catchQuit]}
4511#^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ END OF MENU DEFINITION ^^^^^^^^^^^^^^^^^^^
4512
4513# make the phase pane -- this must be done before setphases
4514# can be called (in loadexp)
4515MakePhasePane
4516
4517# handle indirect exits
4518wm protocol . WM_DELETE_WINDOW catchQuit
4519if {$tcl_platform(platform) != "windows"} {bind . <Control-c> catchQuit}
4520
4521set expgui(pagenow) ""
4522set expgui(curhist) {}
4523set expgui(selectedatomlist) {}
4524
4525loadexp $expgui(expfile)
4526
4527# reset the phase selection
4528set expgui(curPhase) {}
4529# select the first histogram in the list by default (if there are any)
4530if {[llength $expmap(histlistboxcontents)] > 0} {
4531    set expgui(curhist) 0
4532} else {
4533    set expgui(curhist) {}
4534}
4535
4536# execute any local commands for final initialization
4537eval $expgui(initstring)
4538
4539# resize the notebook to fit all the tabs and the largest page
4540ResizeNotebook
4541if {$expgui(resize)} {
4542    # this appears to be needed by OSX
4543    update
4544    #wm geom . [winfo reqwidth .]x[winfo reqheight .]
4545    wm geom . {}
4546}
4547# place the EXPGUI window
4548set xpos 50
4549catch {set xpos $expgui(xpos)}
4550set ypos 50
4551catch {set ypos $expgui(ypos)}
4552set poscntr "nsew"
4553catch {set poscntr $expgui(poscenter)}
4554LocateWindow "." $xpos $ypos $poscntr
4555update
4556RaisePage lsFrame
4557if {[CountHistory] > 200} {
4558    DeleteHistoryRecords "This .EXP file has [CountHistory] history records\nErasing most will speed EXPGUI"
4559}
Note: See TracBrowser for help on using the repository browser.