source: trunk/expgui @ 823

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

# on 2004/10/04 16:20:26, toby did:
Require BWidget (remove non-BWidget code)

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