Index: /trunk/Geo_Viewer.tcl
===================================================================
--- /trunk/Geo_Viewer.tcl	(revision 1165)
+++ /trunk/Geo_Viewer.tcl	(revision 1166)
@@ -47,4 +47,5 @@
      array set ::geo_bonds ""
      set ::geo_alist ""
+     set ::geo_filterval 5.00
 }
 
@@ -60,7 +61,11 @@
    set angle_total -1
 
+   set ::geo_phase_list {}
+   catch {unset ::geo_angles}
+   catch {unset ::geo_bonds}
    array set ::geo_bonds ""
    array set ::geo_angles ""
    array set ::geo_angle_keys ""
+
 
    while {[gets $fh line] >= 0} {
@@ -143,4 +148,10 @@
     Geo_Read $root.disagl
     donewait
+    if {[llength  $::geo_phase_list] == 0} {
+	MyMessageBox -parent . -title "DISAGL Problem" \
+	    -message "No output found in DISAGL output. Is something wrong with DISAGL settings or this .EXP file?" \
+	    -icon error
+	return
+    }
      set mcb .maincontrolbox
      catch {toplevel $mcb}
@@ -175,8 +186,13 @@
      eval tk_optionMenu $sc.phase ::geo_entryvar(phase) $::geo_phase_list
      label $sc.atom1 -text "Atom Type"
+     label $sc.filterlab -text "Dmax Filter"
+     entry $sc.filterval -textvariable ::geo_filterval
+          $sc.filterval config -width 6
      #button $sc.engage -text "Print Info" -command Geo_Fill_Display
      grid $sc.phlabel -row 0 -column 0
-     grid $sc.phase  -row 0 -column 1
-     grid $sc.atom1 -column 0 -row 1
+     grid $sc.phase   -row 0 -column 1
+     grid $sc.atom1   -row 1 -column 0
+     grid $sc.filterlab   -row 2 -column 0
+     grid $sc.filterval -row 2 -column 1
 
      label $as.atom -text "Choose Atom(s)"
@@ -270,5 +286,5 @@
      label $top.toplabel1 -text "Atom 2" -width 8
      label $top.toplabel2 -text "symm" -width 8
-     label $top.toplabel3 -text "Distance" -width 8
+     label $top.toplabel3 -text "Distance" -width 10
      label $top.toplabel4 -text "Angle"
 #     grid $top.toplabel0 -column 0 -row 0
@@ -293,45 +309,59 @@
              set symlist {}
              incr rownum
+             if {[string trim $::geo_filterval] == ""} {set ::geo_filterval 5.00}
              foreach j $slist {
-                 lappend keylist [lindex $j 10]
-                 lappend atmlist [lindex $j 6]
-                 lappend symlist [lindex $j 9]
-                 label $::geo_side.atom1${bondnum} -text [lindex $j 5] -width 8
-                 label $::geo_main.atom2${bondnum} -text [lindex $j 6] -width 8
-                 label $::geo_main.atom2symm${bondnum} -text [lindex $j 9] -width 8
-                 label $::geo_main.bonddist${bondnum} -text [lindex $j 7] -width 8
-
-                 grid $::geo_side.atom1${bondnum} -row $rownum -column 0
-                 grid $::geo_main.atom2${bondnum} -row $rownum -column 0
-                 grid $::geo_main.atom2symm${bondnum} -row $rownum -column 1
-                 grid $::geo_main.bonddist${bondnum} -row $rownum -column 2
-
-                 set key [lindex $j 10]
-                 set atom [lindex $j 1]
-                 set phase [lindex $j 0]
-
-
-                 foreach k $keylist {
-
-                 if {$key != $k} {
-                    if {[array name ::geo_angles "$phase,$key,$atom,$k"] != ""} {
-                    label $::geo_main.$counter -text [lindex $::geo_angles($phase,$key,$atom,$k) 7]
-                    grid $::geo_main.$counter -row $rownum -column $colnum -padx 5
-                    incr colnum
-                    incr counter
-                    } elseif {[array name ::geo_angles "$phase,$k,$atom,$key"] != ""} {
-                    label $::geo_main.$counter -text [lindex $::geo_angles($phase,$k,$atom,$key) 7]
-                    grid $::geo_main.$counter -row $rownum -column $colnum -padx 5
-
-                    incr colnum
-                    incr counter
+                 if {[lindex $j 7] <= $::geo_filterval} {
+                    lappend keylist [lindex $j 10]
+                    lappend atmlist [lindex $j 6]
+                    lappend symlist [lindex $j 9]
+                    label $::geo_side.atom1${bondnum} -text [lindex $j 5] -width 8
+                    label $::geo_main.atom2${bondnum} -text [lindex $j 6] -width 8
+                    label $::geo_main.atom2symm${bondnum} -text [lindex $j 9] -width 8
+                    set bonddist [lindex $j 7]
+                    set bondesd  [lindex $j 8]
+                    set bondentry [formatSU $bonddist $bondesd]
+                    label $::geo_main.bonddist${bondnum} -text $bondentry -width 10
+
+                    grid $::geo_side.atom1${bondnum} -row $rownum -column 0
+                    grid $::geo_main.atom2${bondnum} -row $rownum -column 0
+                    grid $::geo_main.atom2symm${bondnum} -row $rownum -column 1
+                    grid $::geo_main.bonddist${bondnum} -row $rownum -column 2
+
+                    set key [lindex $j 10]
+                    set atom [lindex $j 1]
+                    set phase [lindex $j 0]
+
+
+                    foreach k $keylist {
+
+                            if {$key != $k} {
+                            # search for atom 1 - central atom - atom 2 angle.
+                            if {[array name ::geo_angles "$phase,$key,$atom,$k"] != ""} {
+                               set ang  [lindex $::geo_angles($phase,$key,$atom,$k) 7]
+                               set angesd [lindex $::geo_angles($phase,$key,$atom,$k) 8]
+                               set angentry [formatSU $ang $angesd]
+                               label $::geo_main.$counter -text $angentry
+#                               label $::geo_main.$counter -text [lindex $::geo_angles($phase,$key,$atom,$k) 7]
+                               grid $::geo_main.$counter -row $rownum -column $colnum -padx 5
+                               incr colnum
+                               incr counter
+                               # search for atom 2 - central atom - atom 1 angle.
+                            } elseif {[array name ::geo_angles "$phase,$k,$atom,$key"] != ""} {
+                               set ang  [lindex $::geo_angles($phase,$k,$atom,$key) 7]
+                               set angesd [lindex $::geo_angles($phase,$k,$atom,$key) 8]
+                               set angentry [formatSU $ang $angesd]
+                               label $::geo_main.$counter -text $angentry
+#                              label $::geo_main.$counter -text [lindex $::geo_angles($phase,$k,$atom,$key) 7]
+                              grid $::geo_main.$counter -row $rownum -column $colnum -padx 5
+
+                              incr colnum
+                              incr counter
+                            }
+                            }
                     }
-
-                 }
-                 }
                  incr bondnum
-                incr rownum
+                 incr rownum
                  set colnum 3
-
+             }
              }
                   set colnum 3
Index: /trunk/addcmds.tcl
===================================================================
--- /trunk/addcmds.tcl	(revision 1165)
+++ /trunk/addcmds.tcl	(revision 1166)
@@ -709,10 +709,10 @@
     # mode must be t-max or 2theta, at least for now
     if {$newhist(LimitMode) != 1} return
-    # is a instrument parameter file loaded? If not, try again later
-    if {[string trim $newhist(instfile)] == ""} return
     # get data bank number, test if valid
     set num $newhist(banknum)
     if {[catch {expr $num}]} {return}
     if {$newhist(insttype) == "TOF"} {
+        # is a instrument parameter file loaded? If not, try again later
+        if {[string trim $newhist(instfile)] == ""} return
 	set newhist(2tLimit) [expr {$newhist(tmin$num) / 10.}]
 	# at Ashfia's request, override the bank header # with the 
@@ -740,5 +740,5 @@
 	set inp [
 	tk_getOpenFile -parent $np -initialfile $newhist(instfile) -filetypes {
-	    {"Inst files" .INS*} {"Inst files" .ins*} 
+	    {"Inst files" .INS*} {"Inst files" .ins*}
 	    {"Inst files" .PRM}  {"Inst files" .prm} 
 	    {"All files" *}
@@ -937,6 +937,14 @@
     puts $fp "H"
     if {$tcl_platform(platform) == "windows"} {
-	puts $fp [file attributes $rawfile -shortname]
-	puts $fp [file attributes $instfile -shortname]
+        if {[string length $rawfile] > 50} {
+            puts $fp [file attributes $rawfile -shortname]
+        } else {
+            puts $fp $rawfile
+        }
+        if {[string length $instfile] > 50} {            
+            puts $fp [file attributes $instfile -shortname]
+        } else {
+            puts $fp $instfile
+        }
     } else {
 	puts $fp $rawfile
@@ -1637,5 +1645,5 @@
 	grid $top.scroll -sticky ns -column 4 -row 2
     } else {
-	grid forget $top.scroll 
+	grid forget $top.scroll
     }
     update
@@ -1949,4 +1957,39 @@
     }
 
+    # allow fixing of atom coordinates
+    if {[lindex $expmap(phasetype) [expr {$p - 1}]] != 4} {
+	grid [TitleFrame $w.10 -bd 6 -relief groove \
+		-text "Fix Atom$suffix Coordinates"] \
+		-row 9 -column 0 -columnspan 10 -sticky news
+	set fix [$w.10 getframe]
+        Fix_Initialize $numberList
+
+        label $fix.xlab -text "  x  " -width 8
+        label $fix.ylab -text "  y  " -width 8
+        label $fix.zlab -text "  z  " -width 8
+        grid $fix.xlab -row 2 -column 0
+        grid $fix.ylab -row 2 -column 1
+        grid $fix.zlab -row 2 -column 2
+
+
+        button $fix.x -text "$::fix_state_X" -width 8 \
+               -command "Fix_Atoms $phase [list $numberList] X $fix.x;
+               Fix_Write
+               DisplayAllAtoms $phase"
+
+        button $fix.y -text "$::fix_state_Y" -width 8 \
+		-command "Fix_Atoms $phase [list $numberList] Y $fix.y
+                Fix_Write
+                DisplayAllAtoms $phase"
+        button $fix.z -text "$::fix_state_Z" -width 8 \
+		-command "Fix_Atoms $phase [list $numberList] Z $fix.z
+                Fix_Write
+                DisplayAllAtoms $phase"
+        grid $fix.x -row 3 -column 0
+        grid $fix.y -row 3 -column 1
+        grid $fix.z -row 3 -column 2
+    }
+    #xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+
     grid rowconfigure $w 11 -minsize 5
     grid [frame $w.b] -row 12 -column 0 -columnspan 10 -sticky ew
@@ -1966,4 +2009,101 @@
     if {[llength $expgui(selectedatomlist)] != 0} editRecord
 }
+
+#xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx x
+
+proc Fix_Initialize {numberList} {
+     set phaselist $::expmap(phaselist)
+     catch {unset ::fix_param}
+     foreach i $phaselist {
+             set ::fix_list(X,$i) ""
+             set ::fix_list(Y,$i) ""
+             set ::fix_list(Z,$i) ""
+
+             set temp [atom_constraint_read $i]
+             foreach j $temp {
+                     set atomnum [string trim [string range $j 2 3]]
+                     set param [string trim [string range $j 4 6]]
+                     set ::fix_param($i,$atomnum,$param) 1
+                     if {$param == "X"} {lappend ::fix_list(X,$i) $atomnum}
+                     if {$param == "Y"} {lappend ::fix_list(Y,$i) $atomnum}
+                     if {$param == "Z"} {lappend ::fix_list(Z,$i) $atomnum}
+             }
+     }
+    set ::fix_state_X [Fix_State $i $numberList X]
+    set ::fix_state_Y [Fix_State $i $numberList Y]
+    set ::fix_state_Z [Fix_State $i $numberList Z]
+}
+
+proc Fix_State {phase numberList coord} {
+     set status_fixed "-1"
+     set status_unfixed "-1"
+     #puts "$coord before: $status_fixed $status_unfixed"
+     foreach i $numberList {
+	 set temp [info exists ::fix_param($phase,$i,$coord)]
+	 #puts "::fix_param($phase,$i,$coord) is variable present?: $temp"
+	 if {$temp != 0} {set status_fixed 1}
+	 if {$temp == 0} {set status_unfixed 1}
+     }
+     #puts "$coord after $status_fixed $status_unfixed"
+     if {$status_fixed == 1 && $status_unfixed != 1} {return "fixed"}
+     if {$status_fixed == 1 && $status_unfixed == 1} {return "mixed"}
+     if {$status_fixed != 1 && $status_unfixed == 1} {return "unfixed"}
+}
+
+proc Fix_Write {} {
+      incr ::expgui(changed)
+      #puts "Prepare to write [array names ::fix_Param]"
+      foreach j [array names ::fix_param] {
+             regexp {[0-9]+} $j  temp_phase
+             regexp {,[0-9]+} $j ans
+             set temp_atom [string range $ans 1 end]
+             regexp {[a-zA-Z]+} $j temp_param
+             if {$temp_param == "U"} {regexp {[a-zA-Z]+[0-9]+} $j temp_param}
+             set temp_entry [format "%1s %+2s%-4s" $temp_phase $temp_atom $temp_param]
+             lappend fix_list($temp_phase) $temp_entry
+     }
+     set phaselist $::expmap(phaselist)
+     foreach i $phaselist {
+             catch {atom_constraint_write $i $fix_list($i)}
+             catch  {RecordMacroEntry "catch {atom_constraint_write $i $fix_list($i)}" 0}
+             #puts $fix_list($i)
+     }
+}
+
+proc Fix_Atoms {phase numberList coord but} {
+#     puts "before  ::fix_state_$coord [set ::fix_state_$coord]"
+     #puts " before operationi: $::fix_list($coord,$phase)"
+     switch [set ::fix_state_$coord] {
+     "unfixed" {$but config -text "fixed"
+               set ::fix_state_$coord "fixed"
+               }
+     "fixed"   {$but config -text "unfixed"
+               set ::fix_state_$coord "unfixed"
+               }
+     "mixed"   {$but config -text "unfixed"
+               set ::fix_state_$coord "unfixed"
+               }
+     }
+     if {[set ::fix_state_$coord] == "fixed"} {
+        #puts "fixing atom number $numberList"
+        foreach i $numberList {
+                lappend ::fix_list($coord,$phase) $i
+                set ::fix_list($coord,$phase) [lsort -uniq -integer $::fix_list($coord,$phase)]
+                set ::fix_param($phase,$i,$coord) 1
+        }
+     }
+     if {[set ::fix_state_$coord] == "unfixed"} {
+        #puts "unfixing atoms $numberList"
+        foreach i $numberList {
+           set temp [lsearch $::fix_list($coord,$phase) $i]
+           if {$temp != -1} {
+              set ::fix_list($coord,$phase) [lreplace $::fix_list($coord,$phase) $temp $temp]
+              catch {unset ::fix_param($phase,$i,$coord)}
+           }
+        }
+     }
+     #puts "after operation: $::fix_list($coord,$phase)"
+}
+
 
 # transform the coordinates
Index: /trunk/disagledit.tcl
===================================================================
--- /trunk/disagledit.tcl	(revision 1165)
+++ /trunk/disagledit.tcl	(revision 1166)
@@ -1,290 +1,290 @@
 proc DA_Initialize {} {
-catch {unset ::da_ddrad}
-catch {unset ::da_darad}
-catch {unset ::da_drad}
-catch {unset ::da_arad}
-catch {unset ::da_acon}
-catch {unset ::da_dcon}
+    catch {unset ::da_ddrad}
+    catch {unset ::da_darad}
+    catch {unset ::da_drad}
+    catch {unset ::da_arad}
+    catch {unset ::da_acon}
+    catch {unset ::da_dcon}
     set ::da_quit 1
-set ::da_phase $::expmap(phaselist)
-foreach j $::da_phase {
+    set ::da_phase $::expmap(phaselist)
+    foreach j $::da_phase {
         set ::da_dcon($j) [phaseinfo $j DistCalc]
         set b [regexp -all {[0-9]} $::da_dcon($j)]
         if {$b > 0} {
-           set ::da_dval($j) $::da_dcon($j)]
-           } else {
-             set ::da_dval$j ""
+	    set ::da_dval($j) $::da_dcon($j)]
+    } else {
+	set ::da_dval$j ""
+    }
+
+    set ::da_acon($j) [phaseinfo $j AngCalc]
+    set c [regexp -all {[0-9]} $::da_acon($j)]
+    if {$c > 0} {set ::da_aval$j $::da_acon($j)
+    } else {
+	set ::da_aval$j ""}
+
+}
+
+}
+
+proc DA_Read {} {
+
+    set ::da_list [AtmTypList]
+    set da_angrad [DefAtmTypInfo angrad]
+    set da_distrad [DefAtmTypInfo distrad]
+
+    #Build search arrays
+    #::da_darad array contains default angle search radii
+    #::da_ddrad array contains default distance search radii
+    #::da_arad array contains current angle search radii
+    #::da_drad array contains current distance search radii
+
+    foreach j $da_angrad {
+	set ::da_darad([lindex $j 0]) [lindex $j 1]
+    }
+    foreach k $da_distrad {
+	set ::da_ddrad([lindex $k 0]) [lindex $k 1]
+    }
+    foreach i $::da_list {
+	set ::da_drad($i) [AtmTypInfo distrad $i]
+	set ::da_arad($i) [AtmTypInfo angrad $i]
+    }
+}
+
+#**************** Build Disagl Control Panel ****************************
+
+proc DA_Control_Panel {"launchdisagl 0"} {
+    DA_Initialize
+    DA_Read
+    destroy .disaglcon
+    set dcb .disaglcon
+    catch {toplevel $dcb}
+    eval destroy [winfo children $dcb]
+
+    #construct phase control box in phasecon frame
+    set phasecon $dcb.phasecon
+    frame $phasecon -bd 2 -relief groove
+    grid $phasecon -column 0 -row 0
+
+    label $phasecon.lbl1 -text "Bond Search \n Method"
+    label $phasecon.lbl2 -text "Angle Search \n Method"
+    grid  $phasecon.lbl1 -column 1 -row 0
+    grid  $phasecon.lbl2 -column 2 -row 0
+
+
+    foreach i $::da_phase {
+	label  $phasecon.phase$i -text "Phase $i" -width 8
+	set tacon [regexp {[0-9]+.[0-9]+} $::da_acon($i)]
+	set tdcon [regexp {[0-9]+.[0-9]+} $::da_dcon($i)]
+	if {$tacon} {set alist {none radii $::da_acon($i)}
+	} else {set alist {none radii {fixed search range}}}
+	if {$tdcon} {set dlist {none radii $::da_dcon($i)}
+	} else {set dlist {none radii {fixed search range}}}
+
+	#            set list  {none radii {fixed search range}}
+	#if {[set ::da_dval$i] != ""} {lappend list [set ::da_dval$i]}
+	eval tk_optionMenu $phasecon.dist$i ::da_dcon($i) $dlist
+	$phasecon.dist$i config -width 10
+	eval tk_optionMenu $phasecon.ang$i  ::da_acon($i) $alist
+	$phasecon.ang$i config -width 10
+	grid   $phasecon.phase$i -row $i -column 0 -padx 10
+	grid   $phasecon.dist$i  -row $i -column 1 -padx 10
+	grid   $phasecon.ang$i   -row $i -column 2 -padx 10
+    }
+
+    trace var ::da_dcon w DA_Controls
+    trace var ::da_acon w DA_Controls
+
+
+    #save box
+    set dasave $dcb.dasave
+    frame $dasave -bd 2 -relief groove
+    grid $dasave -column 0 -row 2
+
+    if {$launchdisagl} {
+	wm title $dcb "DISAGL Control Panel"
+	grab release $dcb
+	checkbutton $dasave.option -text "DISAGL output in separate window" \
+	    -variable ::expgui(disaglSeparateBox)
+	grid $dasave.option -row 0 -column 0
+	button $dasave.sexit -text "Save and run DISAGL" -command DA_Save -bg LightGreen
+	grid $dasave.sexit -row 1 -column 0
+    } else {
+	wm title $dcb "Distance Search Parameters"
+	grab release $dcb
+	button $dasave.sexit -text "Save and Exit" -command DA_Save -bg LightGreen
+	grid $dasave.sexit -row 0 -column 0
+    }
+    button $dasave.quit -text "Cancel" -command "destroy $dcb"
+    grid $dasave.quit -row 2 -column 0
+
+
+    #construct control box
+
+
+    set dacon $dcb.dacon
+    frame $dacon -bd 2 -relief groove
+    grid $dacon -column 1 -row 2
+
+    button $dacon.default -text "Restore to Default Radii" -command {
+	foreach i $::da_list {
+	    set ::da_drad($i) $::da_ddrad([lindex [split $i {+-}] 0])
+	    set ::da_arad($i) $::da_darad([lindex [split $i {+-}] 0])
+	}
+    }
+    grid $dacon.default -row 3 -column 0 -columnspan 3
+
+    label $dacon.dradcon -text "Increment All Bond Search Radii (0.10 A)"
+    label $dacon.aradcon -text "Increment All Angle Search Radii (0.10 A)"
+    button $dacon.dradup -text "\u2191" -command DA_Inc_Drad
+    button $dacon.draddn -text "\u2193" -command DA_Dec_Drad
+    button $dacon.aradup -text "\u2191" -command DA_Inc_Arad
+    button $dacon.araddn -text "\u2193" -command DA_Dec_Arad
+    grid $dacon.dradcon -column 0 -row 0 -pady 5
+    grid $dacon.dradup  -column 1 -row 0 -padx 5
+    grid $dacon.draddn  -column 2 -row 0 -padx 5
+    grid $dacon.aradcon -column 0 -row 1 -pady 5
+    grid $dacon.aradup  -column 1 -row 1 -padx 5
+    grid $dacon.araddn  -column 2 -row 1 -padx 5
+
+    #     button $dacon.radcon -text "Radii Editor" -command {DA_Radii_Box .disaglcon}
+    #     grid $dacon.radcon -row 1 -column 0
+
+    DA_Radii_Box .disaglcon
+    putontop  .disaglcon
+    tkwait window .disaglcon
+    afterputontop
+    return $::da_quit
+
+}
+
+proc DA_Controls {var phase junk } {
+    if {[set ${var}($phase)] == "none"} {
+        if {$var == "::da_acon"} {
+	    set ::da_dcon($phase) "none"
+	    #puts 1
+        } else {
+	    set ::da_acon($phase) "none"
+	    #puts 2
         }
-
-        set ::da_acon($j) [phaseinfo $j AngCalc]
-        set c [regexp -all {[0-9]} $::da_acon($j)]
-        if {$c > 0} {set ::da_aval$j $::da_acon($j)
+    }
+    if {[set ${var}($phase)] != "none" && ($::da_dcon($phase) == "none" || $::da_acon($phase) == "none")} {
+        if {$var == "::da_acon"} {
+	    set ::da_dcon($phase) "radii"
         } else {
-          set ::da_aval$j ""}
-
-}
-
-}
-
-proc DA_Read {} {
-
-   set ::da_list [AtmTypList]
-   set da_angrad [DefAtmTypInfo angrad]
-   set da_distrad [DefAtmTypInfo distrad]
-
-   #Build search arrays
-   #::da_darad array contains default angle search radii
-   #::da_ddrad array contains default distance search radii
-   #::da_arad array contains current angle search radii
-   #::da_drad array contains current distance search radii
-
-   foreach j $da_angrad {
-       set ::da_darad([lindex $j 0]) [lindex $j 1]
-   }
-   foreach k $da_distrad {
-       set ::da_ddrad([lindex $k 0]) [lindex $k 1]
-   }
-   foreach i $::da_list {
-           set ::da_drad($i) [AtmTypInfo distrad $i]
-           set ::da_arad($i) [AtmTypInfo angrad $i]
-   }
-}
-
-#**************** Build Disagl Control Panel ****************************
-
-proc DA_Control_Panel {"launchdisagl 0"} {
-     DA_Initialize
-     DA_Read
-     destroy .disaglcon
-     set dcb .disaglcon
-     catch {toplevel $dcb}
-     eval destroy [winfo children $dcb]
-
-     #construct phase control box in phasecon frame
-     set phasecon $dcb.phasecon
-     frame $phasecon -bd 2 -relief groove
-     grid $phasecon -column 0 -row 0
-
-     label $phasecon.lbl1 -text "Bond Search \n Method"
-     label $phasecon.lbl2 -text "Angle Search \n Method"
-     grid  $phasecon.lbl1 -column 1 -row 0
-     grid  $phasecon.lbl2 -column 2 -row 0
-
-
-     foreach i $::da_phase {
-             label  $phasecon.phase$i -text "Phase $i" -width 8
-             set tacon [regexp {[0-9]+.[0-9]+} $::da_acon($i)]
-             set tdcon [regexp {[0-9]+.[0-9]+} $::da_dcon($i)]
-             if {$tacon} {set alist {none radii $::da_acon($i)}
-                } else {set alist {none radii {fixed search range}}}
-             if {$tdcon} {set dlist {none radii $::da_dcon($i)}
-                } else {set dlist {none radii {fixed search range}}}
-
-#            set list  {none radii {fixed search range}}
-             #if {[set ::da_dval$i] != ""} {lappend list [set ::da_dval$i]}
-             eval tk_optionMenu $phasecon.dist$i ::da_dcon($i) $dlist
-                  $phasecon.dist$i config -width 10
-             eval tk_optionMenu $phasecon.ang$i  ::da_acon($i) $alist
-                  $phasecon.ang$i config -width 10
-             grid   $phasecon.phase$i -row $i -column 0 -padx 10
-             grid   $phasecon.dist$i  -row $i -column 1 -padx 10
-             grid   $phasecon.ang$i   -row $i -column 2 -padx 10
-     }
-
-     trace var ::da_dcon w DA_Controls
-     trace var ::da_acon w DA_Controls
-
-
-     #save box
-     set dasave $dcb.dasave
-     frame $dasave -bd 2 -relief groove
-     grid $dasave -column 0 -row 2
-
-     if {$launchdisagl} {
-       wm title $dcb "DISAGL Control Panel"
-       grab release $dcb
-       checkbutton $dasave.option -text "DISAGL output in separate window" \
-                   -variable ::expgui(disaglSeparateBox)
-       grid $dasave.option -row 0 -column 0
-       button $dasave.sexit -text "Save and run DISAGL" -command DA_Save -bg LightGreen
-       grid $dasave.sexit -row 1 -column 0
-     } else {
-       wm title $dcb "Distance Search Parameters"
-       grab release $dcb
-       button $dasave.sexit -text "Save and Exit" -command DA_Save -bg LightGreen
-       grid $dasave.sexit -row 0 -column 0
-     }
-     button $dasave.quit -text "Cancel" -command "destroy $dcb"
-     grid $dasave.quit -row 2 -column 0
-
-
-     #construct control box
-
-
-     set dacon $dcb.dacon
-     frame $dacon -bd 2 -relief groove
-     grid $dacon -column 1 -row 2
-
-     button $dacon.default -text "Restore to Default Radii" -command {
-            foreach i $::da_list {
-                    set ::da_drad($i) $::da_ddrad([lindex [split $i {+-}] 0])
-                    set ::da_arad($i) $::da_darad([lindex [split $i {+-}] 0])
-            }
-     }
-     grid $dacon.default -row 3 -column 0 -columnspan 3
-
-     label $dacon.dradcon -text "Increment All Bond Search Radii (0.10 A)"
-     label $dacon.aradcon -text "Increment All Angle Search Radii (0.10 A)"
-     button $dacon.dradup -text "\u2191" -command DA_Inc_Drad
-     button $dacon.draddn -text "\u2193" -command DA_Dec_Drad
-     button $dacon.aradup -text "\u2191" -command DA_Inc_Arad
-     button $dacon.araddn -text "\u2193" -command DA_Dec_Arad
-     grid $dacon.dradcon -column 0 -row 0 -pady 5
-     grid $dacon.dradup  -column 1 -row 0 -padx 5
-     grid $dacon.draddn  -column 2 -row 0 -padx 5
-     grid $dacon.aradcon -column 0 -row 1 -pady 5
-     grid $dacon.aradup  -column 1 -row 1 -padx 5
-     grid $dacon.araddn  -column 2 -row 1 -padx 5
-
-#     button $dacon.radcon -text "Radii Editor" -command {DA_Radii_Box .disaglcon}
-#     grid $dacon.radcon -row 1 -column 0
-
-DA_Radii_Box .disaglcon
-             putontop  .disaglcon
-             tkwait window .disaglcon
-             afterputontop
-             return $::da_quit
-
-}
-
-proc DA_Controls {var phase junk } {
-     if {[set ${var}($phase)] == "none"} {
-        if {$var == "::da_acon"} {
-           set ::da_dcon($phase) "none"
-           puts 1
-        } else {
-           set ::da_acon($phase) "none"
-           puts 2
+	    set ::da_acon($phase) "radii"
         }
-     }
-     if {[set ${var}($phase)] != "none" && ($::da_dcon($phase) == "none" || $::da_acon($phase) == "none")} {
-        if {$var == "::da_acon"} {
-           set ::da_dcon($phase) "radii"
-        } else {
-           set ::da_acon($phase) "radii"
-        }
-     }
-
-
-#     if {[set ${var}($phase)] == "fixed search range"} {}
-      if {[set ${var}($phase)] != "none" && [set ${var}($phase)] != "radii" } {
-           catch {destroy .disaglcon.top}
-           set dedit .disaglcon.top
-           toplevel $dedit
-           bind $dedit <Return> "destroy $dedit"
-#           frame $dedit -bd 2 -relief groove
-#           pack $dedit -side top
-           set temp [regexp {[0-9]+.[0-9]+} [set ${var}($phase)]]
-           if {$temp == 0} {set ${var}($phase) 0.00}
-           if {$var == "::da_acon"} {
-              label $dedit.lbl1    -text "set angle fixed search range \n for phase $phase in angstroms"
-#              set ::da_acon($phase) 0
-              entry  $dedit.entry1 -textvariable ::da_acon($phase) -takefocus 1 
-                     $dedit.entry1 selection range 0 end
-              grid $dedit.lbl1 -column 0 -row 0
-              grid $dedit.entry1 -column 0 -row 1
-              focus $dedit.entry1
-           }
-           if {$var == "::da_dcon"} {
- #             set ::da_dcon($phase) 0
-              label $dedit.lbl1    -text "set bond fixed search range \n for phase $phase in angstroms"
-              entry  $dedit.entry1 -textvariable ::da_dcon($phase) -takefocus 1
-                     $dedit.entry1 selection range 0 end
-              grid $dedit.lbl1 -column 0 -row 0
-              grid $dedit.entry1 -column 0 -row 1
-              focus $dedit.entry1
-           }
-           button $dedit.quit -text "Set" -command "destroy $dedit"
-           grid $dedit.quit -column 0 -row 2
-           putontop $dedit
-           tkwait window $dedit
-           afterputontop
-     }
-
-
-
-
-#     puts "phase = $phase"
-#     puts "var = $var"
-#     puts "new value = [set ${var}($phase)]"
+    }
+
+
+    #     if {[set ${var}($phase)] == "fixed search range"} {}
+    if {[set ${var}($phase)] != "none" && [set ${var}($phase)] != "radii" } {
+	catch {destroy .disaglcon.top}
+	set dedit .disaglcon.top
+	toplevel $dedit
+	bind $dedit <Return> "destroy $dedit"
+	#           frame $dedit -bd 2 -relief groove
+	#           pack $dedit -side top
+	set temp [regexp {[0-9]+.[0-9]+} [set ${var}($phase)]]
+	if {$temp == 0} {set ${var}($phase) 0.00}
+	if {$var == "::da_acon"} {
+	    label $dedit.lbl1    -text "set angle fixed search range \n for phase $phase in angstroms"
+	    #              set ::da_acon($phase) 0
+	    entry  $dedit.entry1 -textvariable ::da_acon($phase) -takefocus 1 
+	    $dedit.entry1 selection range 0 end
+	    grid $dedit.lbl1 -column 0 -row 0
+	    grid $dedit.entry1 -column 0 -row 1
+	    focus $dedit.entry1
+	}
+	if {$var == "::da_dcon"} {
+	    #             set ::da_dcon($phase) 0
+	    label $dedit.lbl1    -text "set bond fixed search range \n for phase $phase in angstroms"
+	    entry  $dedit.entry1 -textvariable ::da_dcon($phase) -takefocus 1
+	    $dedit.entry1 selection range 0 end
+	    grid $dedit.lbl1 -column 0 -row 0
+	    grid $dedit.entry1 -column 0 -row 1
+	    focus $dedit.entry1
+	}
+	button $dedit.quit -text "Set" -command "destroy $dedit"
+	grid $dedit.quit -column 0 -row 2
+	putontop $dedit
+	tkwait window $dedit
+	afterputontop
+    }
+
+
+
+
+    #     puts "phase = $phase"
+    #     puts "var = $var"
+    #     puts "new value = [set ${var}($phase)]"
 }
 
 proc DA_Radii_Box {dcb args} {
-     #construct radii control box
-     catch {destory $dcb.radcon}
-     catch {destory $dcb.discon}
-     set radcon $dcb.radcon
-     frame $radcon -bd 2 -relief groove
-     grid $radcon -column 1 -row 0 -rowspan 2
-
-     label $radcon.lbl1 -text "Atom/Ion"
-     label $radcon.lbl2 -text "Bond \n Search Radii"
-     label $radcon.lbl3 -text "Angle \n Search Radii"
-     grid $radcon.lbl1 -row 0 -column 0
-     grid $radcon.lbl2 -row 0 -column 1
-     grid $radcon.lbl3 -row 0 -column 2
-     set count 1
-     foreach j [array names ::da_drad] {
-             label $radcon.atom$j -text "$j" -width 5
-             entry $radcon.drad$j -textvariable ::da_drad($j) -width 6 -takefocus 1
-             entry $radcon.arad$j -textvariable ::da_arad($j) -width 6 -takefocus 1
-             grid  $radcon.atom$j -row $count -column 0
-             grid  $radcon.drad$j -row $count -column 1
-             grid  $radcon.arad$j -row $count -column 2
-             incr count
-     }
+    #construct radii control box
+    catch {destory $dcb.radcon}
+    catch {destory $dcb.discon}
+    set radcon $dcb.radcon
+    frame $radcon -bd 2 -relief groove
+    grid $radcon -column 1 -row 0 -rowspan 2
+
+    label $radcon.lbl1 -text "Atom/Ion"
+    label $radcon.lbl2 -text "Bond \n Search Radii"
+    label $radcon.lbl3 -text "Angle \n Search Radii"
+    grid $radcon.lbl1 -row 0 -column 0
+    grid $radcon.lbl2 -row 0 -column 1
+    grid $radcon.lbl3 -row 0 -column 2
+    set count 1
+    foreach j [array names ::da_drad] {
+	label $radcon.atom$j -text "$j" -width 5
+	entry $radcon.drad$j -textvariable ::da_drad($j) -width 6 -takefocus 1
+	entry $radcon.arad$j -textvariable ::da_arad($j) -width 6 -takefocus 1
+	grid  $radcon.atom$j -row $count -column 0
+	grid  $radcon.drad$j -row $count -column 1
+	grid  $radcon.arad$j -row $count -column 2
+	incr count
+    }
 }
 
 
 proc DA_Inc_Drad {args} {
-        foreach j [array names ::da_drad] {
-                set ::da_drad($j) [format %.1f [expr $::da_drad($j) + 0.1]]
-        }
+    foreach j [array names ::da_drad] {
+	set ::da_drad($j) [format %.1f [expr $::da_drad($j) + 0.1]]
+    }
 }
 
 proc DA_Dec_Drad {args} {
-        foreach j [array names ::da_drad] {
-                set ::da_drad($j) [format %.1f [expr $::da_drad($j) - 0.1]]
-        }
+    foreach j [array names ::da_drad] {
+	set ::da_drad($j) [format %.1f [expr $::da_drad($j) - 0.1]]
+    }
 }
 proc DA_Inc_Arad {args} {
-        foreach j [array names ::da_arad] {
-                set ::da_arad($j) [format %.1f [expr $::da_arad($j) + 0.1]]
-        }
+    foreach j [array names ::da_arad] {
+	set ::da_arad($j) [format %.1f [expr $::da_arad($j) + 0.1]]
+    }
 }
 proc DA_Dec_Arad {args} {
-        foreach j [array names ::da_drad] {
-                set ::da_arad($j) [format %.1f [expr $::da_arad($j) - 0.1]]
-        }
+    foreach j [array names ::da_drad] {
+	set ::da_arad($j) [format %.1f [expr $::da_arad($j) - 0.1]]
+    }
 }
 
 proc DA_Save {args} {
-     foreach i $::da_list {
-           if {$::da_drad($i) >= 0 && $::da_drad($i) <= 10000} {
-              AtmTypInfo distrad $i set $::da_drad($i)
-           }
-           puts 1
-           if {$::da_arad($i) >= 0 && $::da_arad($i) <= 10000} {
-              AtmTypInfo angrad $i set $::da_arad($i)
-           }
-
-     }
-     foreach j $::da_phase {
+    foreach i $::da_list {
+	if {$::da_drad($i) >= 0 && $::da_drad($i) <= 10000} {
+	    AtmTypInfo distrad $i set $::da_drad($i)
+	}
+	puts 1
+	if {$::da_arad($i) >= 0 && $::da_arad($i) <= 10000} {
+	    AtmTypInfo angrad $i set $::da_arad($i)
+	}
+
+    }
+    foreach j $::da_phase {
         phaseinfo $j DistCalc set $::da_dcon($j)
         phaseinfo $j AngCalc set $::da_acon($j)
-     }
-     # indicate a change to the .EXP file
-     incr ::expgui(changed)
-     set ::da_quit 0
-     destroy .disaglcon
-}
+    }
+    # indicate a change to the .EXP file
+    incr ::expgui(changed)
+    set ::da_quit 0
+    destroy .disaglcon
+}
Index: /trunk/distrest.tcl
===================================================================
--- /trunk/distrest.tcl	(revision 1165)
+++ /trunk/distrest.tcl	(revision 1166)
@@ -37,4 +37,5 @@
 
 proc DisplayDistanceRestraints {args} {
+    #puts DisplayDistanceRestraints
     global expcons
     eval destroy [winfo children $expcons(distmaster)]
@@ -51,9 +52,9 @@
 	-sticky nsew
     grid [frame $phasebox -bd 2 -relief groove] -column 0 -row 0 \
-         -sticky new -columnspan 2
+	-sticky new -columnspan 2
 
 
     grid [frame $editorbox -bd 2 -relief groove] -column 0 -row 2 \
-         -sticky sew -columnspan 2
+	-sticky sew -columnspan 2
 
 
@@ -64,10 +65,10 @@
     # Pick Phase to be Evaluated **********************************************
     label $phasebox.phlabel -text Phase
-#    set ::sr_phaselist $::expmap(phaselist)
+    #    set ::sr_phaselist $::expmap(phaselist)
 
     eval tk_optionMenu $phasebox.phase ::sr_entryvar(softphase) $::expmap(phaselist)
-#    eval tk_optionMenu $phasebox.phase ::sr_entryvar(softphase) $::sr_phaselist
-#   trace variable ::sr_entryvar(softphase) w DisplayDistanceRestraints
-#   bind $phasebox.phase <ButtonRelease> {DisplayDistanceRestraints}
+    #    eval tk_optionMenu $phasebox.phase ::sr_entryvar(softphase) $::sr_phaselist
+    #   trace variable ::sr_entryvar(softphase) w DisplayDistanceRestraints
+    #   bind $phasebox.phase <ButtonRelease> {DisplayDistanceRestraints}
 
     grid $phasebox.phlabel -column 0 -row 0
@@ -78,10 +79,11 @@
     grid [label $leftfr.lweight -text "Restraint Weight"] -column 0 -row 1 -sticky sw -pady 10
     grid [entry $leftfr.weight -width 8 -textvariable entryvar(distrestweight)] -column 1 -row 1 -sticky sw \
-         -padx 5 -pady 10
+	-padx 5 -pady 10
     set ::entrycmd(distrestweight) "SoftConst weight"
     set ::entrycmd(trace) 0
     set ::entryvar(distrestweight) [SoftConst weight]
+    RecordMacroEntry "set ::entryvar(distrestweight) [SoftConst weight]" 0
     set ::entrycmd(trace) 1
-
+    incr ::expgui(changed)
 
     #Run Disagl Commands *****************************************************
@@ -95,9 +97,9 @@
     grid [button $editorbox.edit -text "Activate Restraint \n Editor" -command SR_TEST] -column 0 -row 4 \
 	-columnspan 2 -pady 5
-        $editorbox.edit config -bg LightGreen -bd 6
+    $editorbox.edit config -bg LightGreen -bd 6
 
     grid [button $editorbox.search -text "Edit Search Distance \n Parameters" -command DA_Control_Panel] -column 0 -row 3 \
         -columnspan 2
-        $editorbox.edit config -bd 4
+    $editorbox.edit config -bd 4
 
 
@@ -114,5 +116,5 @@
 
     label  $top.rlabel1 -text "Restraint" -width 9 -anchor center
-    label  $top.rlabel2 -text "esd"       -width 9 -anchor center
+    label  $top.rlabel2 -text "Tolerance" -width 9 -anchor center
 
     grid $top.alabel1 -column 1 -row 2 -padx 3
@@ -139,5 +141,5 @@
     SR_Show_RestraintsOnly $main $rightfr
     foreach item [trace vinfo ::sr_entryvar(softphase)] {
-    eval trace vdelete ::sr_entryvar(softphase) $item
+	eval trace vdelete ::sr_entryvar(softphase) $item
     }
 
@@ -148,4 +150,5 @@
     SR_Fill_Display  $main
     ResizeScrollTable $rightfr
+    #puts $rightfr
 }
 
@@ -336,10 +339,10 @@
 
     label  $sr_top.rlabel1 -text "Restraint"
-    label  $sr_top.rlabel2 -text "esd"
+    label  $sr_top.rlabel2 -text "Tolerance"
     grid $sr_top.rlabel1 -column 4 -row 2 -padx 20
     grid $sr_top.rlabel2 -column 5 -row 2 -padx 20
 
 
-    button $sr_top.rcon1   -text "Check All" -width 10 -command "
+    button $sr_top.rcon1   -text "Check\nAll" -width 4 -command "
 	set ::sr_checkall 1;
 	SR_Set_All_Check_Buttons;
@@ -348,5 +351,5 @@
     "
 
-    button $sr_top.rcon2   -text "Clear All" -width 10 -command "
+    button $sr_top.rcon2   -text "Clear\nAll" -width 4 -command "
 	set ::sr_checkall 0;
 	SR_Set_All_Check_Buttons;
@@ -396,8 +399,8 @@
 				label $main.rdistance$i -text [lindex $rprint 8] -justify center -anchor center
 				entry $main.restraint$i -width 8 -textvariable ::sr_restraintdist([lindex $rprint 13]) -takefocus 1
-				      $main.restraint$i selection range 0 end
+				$main.restraint$i selection range 0 end
                                 bind  $main.restraint$i <KeyRelease> {SR_Validate_Soft %W distance}
 				entry $main.restesd$i -width 8 -textvariable ::sr_restraintesd([lindex $rprint 13]) -takefocus 1
-				      $main.restesd$i selection range 0 end
+				$main.restesd$i selection range 0 end
 				bind  $main.restesd$i <KeyRelease> {SR_Validate_Soft %W esd}
 				checkbutton $main.sr_crestraint$i -variable ::sr_crestraint([lindex $rprint 13])
@@ -458,5 +461,5 @@
 	# valid value
         $win config -fg black
-        $::srcb3.rbutton3 config -bg LightGreen -text "Save Restraints to EXP File"
+        $::srcb3.rbutton3 config -bg LightGreen -text "Save Changes"
         set ::sr_error 0
     }
@@ -515,29 +518,29 @@
 	set sr_write ""
 	set new_list ""
-#	set len [llength $::sr_bond_list]
+	#	set len [llength $::sr_bond_list]
 	set ::sr_key_list ""
         foreach temp $::sr_bond_list  {
-puts $temp
-#	for {set i 0} {$i <= [expr $len-1]} {incr i} {}
-#	    set temp [lindex $::sr_bond_list $i]
-
-           catch {
-            if {[string trim $::sr_restraintdist([lindex $temp 13])] != ""} {
-		set softrest "[lindex $temp 0] [lindex $temp 1] \
+	    #	for {set i 0} {$i <= [expr $len-1]} {incr i} {}
+	    #	    set temp [lindex $::sr_bond_list $i]
+
+	    if {[catch {
+		if {[string trim $::sr_restraintdist([lindex $temp 13])] != ""} {
+		    set softrest "[lindex $temp 0] [lindex $temp 1] \
                                 [lindex $temp 2] [lindex $temp 3] [lindex $temp 4] \
                                 [lindex $temp 5] [lindex $temp 6] [lindex $temp 7]\
                                 $::sr_restraintdist([lindex $temp 13])\
                                 $::sr_restraintesd([lindex $temp 13])"
-		lappend sr_write $softrest
-puts $softrest
-		lappend new_list $temp
-	    }
-	    }
+		    lappend sr_write $softrest
+		    #lappend new_list $temp
+		}
+	    } errmsg]} {puts "error: $errmsg"}
         }
-#
+	#
 	#puts $sr_write
 	# put the entire restraint list back into the .EXP file
+	#puts "SoftConst restraintlist set $sr_write"
 	SoftConst restraintlist set $sr_write
-	set ::sr_bond_list $new_list
+        RecordMacroEntry "SoftConst restraintlist set $sr_write" 0
+	#set ::sr_bond_list $new_list
 	# indicate a change to the .EXP file
 	incr ::expgui(changed)
@@ -623,5 +626,5 @@
     label $srcb1.dmaxlabel    -text "Dmax"
     label $srcb2.restlabel    -text "Restraint Value" -width 16 -anchor w
-    label $srcb2.restlabelesd -text "esd"
+    label $srcb2.restlabelesd -text "Tolerance"
 
     eval tk_optionMenu $srcb1.atom1 ::sr_entryvar(softatom1) "[lsort [array names ::sr_lookuplist1${::sr_entryvar(softphase)}]] all"
@@ -630,11 +633,11 @@
 
     entry  $srcb1.sr_dminvalue -width 8 -textvariable ::sr_dminvalue        -takefocus 1
-           $srcb1.sr_dminvalue selection range 0 end
+    $srcb1.sr_dminvalue selection range 0 end
     entry  $srcb1.sr_dmaxvalue -width 8 -textvariable ::sr_dmaxvalue        -takefocus 1
-           $srcb1.sr_dmaxvalue selection range 0 end
+    $srcb1.sr_dmaxvalue selection range 0 end
     entry  $srcb2.sr_rvalue    -width 8 -textvariable ::sr_rvalue           -takefocus 1
-           $srcb2.sr_rvalue selection range 0 end
+    $srcb2.sr_rvalue selection range 0 end
     entry  $srcb2.sr_resd      -width 8 -textvariable ::sr_resd             -takefocus 1
-           $srcb2.sr_resd selection range 0 end
+    $srcb2.sr_resd selection range 0 end
 
     bind  $srcb1.sr_dminvalue <KeyRelease> {SR_Validate_Soft %W dmin}
@@ -644,15 +647,19 @@
 
     button $srcb1.recalc   -text "Filter" -bd 6 -command {SR_Display}
-    button $srcb2.rbutton1 -text "check update" -command {SR_Update_Restraints}
-    button $srcb2.rbutton2 -text "check delete" -command {SR_Delete_Restraints}
-    button $::srcb3.rbutton3 -text "Save Restraints to EXP File" -bd 6 -bg LightGreen -command {SR_Write_Restraints}
-    button $::srcb3.rbutton4 -text "Cancel" -command {destroy .mainrestraintbox
+    button $srcb2.rbutton1 -text "Set checked" -command {SR_Update_Restraints}
+    button $srcb2.rbutton2 -text "Delete checked" -command {SR_Delete_Restraints}
+    button $::srcb3.rbutton3 -text "Save changes" -bd 6 -bg LightGreen -command {SR_Write_Restraints}
+    button $::srcb3.rbutton4 -text "Cancel" -command {
+	destroy .mainrestraintbox
 	afterputontop
 	SR_Rest_Only
-	DisplayDistanceRestraints}
-    wm protocol .mainrestraintbox WM_DELETE_WINDOW {destroy .mainrestraintbox
+	DisplayDistanceRestraints
+    }
+    wm protocol .mainrestraintbox WM_DELETE_WINDOW {
+	destroy .mainrestraintbox
 	afterputontop
 	SR_Rest_Only
-	DisplayDistanceRestraints}
+	DisplayDistanceRestraints
+    }
 
     grid $srcb1.atomlabel1   -column 1 -row 0
@@ -725,6 +732,6 @@
     set ::sr_distance_button 1
     set ::sr_entryvar(choicenum) 0
-#    set ::sr_entryvar(softphase) "1"
-#    set ::sr_phaselist $::expmap(phaselist)
+    #    set ::sr_entryvar(softphase) "1"
+    #    set ::sr_phaselist $::expmap(phaselist)
     set ::sr_entryvar(softatom1) "all"
     set ::sr_entryvar(softatom2) "all"
Index: /trunk/doc/excledt.html
===================================================================
--- /trunk/doc/excledt.html	(revision 1165)
+++ /trunk/doc/excledt.html	(revision 1166)
@@ -283,7 +283,4 @@
 </TH></TR></TABLE>
 
-<P><font size=-1><A HREF="MAILTO:crystal@NIST.gov?subject=WWW page <?=$PHP_SELF?>">Comments, corrections or questions: crystal@NIST.gov</A></font><BR>
-<font size=-1><? lastmod(); ?> </font>
-<br>$Revision$ $Date$
 </blockquote>
 </body>
Index: /trunk/doc/expgui.html
===================================================================
--- /trunk/doc/expgui.html	(revision 1165)
+++ /trunk/doc/expgui.html	(revision 1166)
@@ -16,5 +16,5 @@
 EXPGUI<BR>
 A Graphical User Interface for 
-<A Href="http://www.ncnr.nist.gov/programs/crystallography/software/gsas.html">
+<A Href="https://subversion.xor.aps.anl.gov/trac/EXPGUI/wiki/GSASIntro">
 GSAS</A>
 <HR noshade width="75%" size="2" align="center">
@@ -34,7 +34,6 @@
 <P><P>
 EXPGUI is a graphical interface for the 
-Los Alamos
-<A Href="http://www.ncnr.nist.gov/programs/crystallography/software/gsas.html">
-GSAS</A> package. 
+<A Href="https://subversion.xor.aps.anl.gov/trac/EXPGUI/wiki/GSASIntro">GSAS</A>
+package, developed at Los Alamos and maintained now at Argonne. 
 EXPGUI does two things: 
 it can be used to directly modify the GSAS 
@@ -60,7 +59,8 @@
 <TH><A Href="expgui4.html">Scaling info</A></TH>
 <TH><A Href="expgui5.html">Profile terms</A></TH>
-<TH><A Href="expgui6.html">Constraints</A></TH>
+<TH><A Href="expgui6.html">Constraints & Restraints</A></TH>
 </TR>
 <TR>
+<TH><A Href="expgui6A.html">Rigid Bodies</A></TH>
 <TH><A Href="expgui7.html">Preferred Orientation</A></TH>
 <TH><A Href="expguic.html">Menus</A></TH>
@@ -117,5 +117,6 @@
 A.C. Larson and R.B. Von Dreele, "General Structure Analysis System (GSAS)", 
 Los Alamos National Laboratory Report LAUR 86-748 (2000).
-<A HREF="http://www.ccp14.ac.uk/ccp/ccp14/ftp-mirror/gsas/public/gsas/manual/GSASManual.pdf">
+<A
+  HREF="https://subversion.xor.aps.anl.gov/EXPGUI/gsas/all/GSAS%20Manual.pdf">
 [link to PDF copy of manual]
 </A>
@@ -154,4 +155,28 @@
 are used. The File/Save operation is done automatically before any GSAS
 programs, such as GENLES or EXPEDT, are run.
+<P>
+<A name="badexp">
+The GSAS refinement program, GENLES, will sometimes "blow up", where the
+  program changes varied parameters to values very far from their
+  correct values. This occurs when parameters are highly correlated,
+  are refining to values that are not allowed, or some of the refined parameters have
+  very little impact on the quality of the fit. When this happens,
+  invalid values are written to the GSAS experiment file that contain
+  either asterisks (****) or the string "NAN" (not a number). Such
+  files cannot be used for additional GENLES runs.
+  <P>
+  When EXPGUI reads a .EXP file it scans it for evidence of a previous
+  failure of a GENLES refinement and warns if a problem is
+  noted. Please note that this scan is not perfect and occasionally
+  you may be warned in cases where the file is fine (if possible,
+  please send such .EXP file to Brian Toby so this scan can be improved.)
+  When such a "bad" .EXP file is located, one can "revert" to an
+  archived copy of a previous experiment file (with suffix .Oxx). This
+  can be done with the Revert menu item in the File menu. Note that
+clicking on a file in the file selection window causes it to be
+scanned and shows the status of that refinement. Also note that
+usually the last good archived file has settings that will produce the same bad
+refinement, so it is necessary to either revert further back, or to
+change the refinement options before running GENLES. 
 <P>
 
@@ -475,11 +500,12 @@
 
 The INSTEDIT utility is used to edit or create an instrument parameter file.
-At this time it can only be used to edit files for 
-constant-wavelength data. The utility can be started from the "Edit File"
-button in the 
+The utility can be started from the "Edit File" button in the 
 <A HREF="expgui3.html#AddHist">"Add New Histogram"</A> dialog, or from the 
-the "instedit" option in the Powder menu. In the latter case, the user
-is given the chance to select an input file. If no file is selected,
-a new, empty, file is created. An example INSTEDIT window appears below.
+the "instedit" option in the Powder menu. Alternately, to create a new
+  instrument parameter file, choose Powder menu option "New InstParm
+  file". (It is also possible 
+  to create a new file using the standard instedit by selecting
+  "Cancel" when asked for an input file.)
+An example INSTEDIT window appears below.
 <P>
 <img SRC="instedit1.gif" align=RIGHT alt="EXPGUI Screen snapshot">
@@ -593,8 +619,6 @@
 records can slow the GSAS programs 
 (this is less of a problem on faster computers). For these reasons, it may be 
-a good idea to prune the older history records from the file. If more than 100
-history records are found in an experiment file, EXPGUI suggests that the
-older history entries be deleted. Alternately the File/EraseHistory command
-can be used to invoke the this option.
+a good idea to prune the older history records from the file.
+The File/EraseHistory command can be used to invoke the this option.
 <P>
 On the dialog the number of history records to be retained is specified. 
@@ -681,26 +705,16 @@
 <A name=tcltk>
 <H2>
-<A Href="http://www.ncnr.nist.gov/programs/crystallography/software/tclpkgs.html">
+<A Href="http://www.tcl.tk">
 Tcl/Tk</A></H2>
 The 
-<A Href="http://www.ncnr.nist.gov/programs/crystallography/software/tclpkgs.html">
+<A Href="http://www.tcl.tk">
 Tcl/Tk program</A> is a platform-independent scripting language that is
 used to implement most of EXPGUI. This software is available for free
-and must be loaded in order to use EXPGUI. See the 
-installation notes for 
-<A HREF="expgui_Win_readme.html">Windows</A>,
-and for
-<A HREF="expgui_Unix_readme.html">UNIX</A> for information on how to do this.
+and must be loaded in order to use EXPGUI. A somewhat out of date
+version of Tcl/Tk (8.4) is distributed with EXPGUI (ncnrpack.exe, etc.) but
+more recent versions can be used, but note that the BLT package (see
+below) is needed for all features of EXPGUI.
 While learning Tcl/Tk is a great thing to do, it is not a requirement
 for using or installing EXPGUI.
-
-<A name=winexec>
-<H3>
-WINEXEC</H3>
-<UL>
-The WINEXEC package is needed under Windows-95 and its offspring 
-(-98 and -ME). See the <A HREF="expgui_Win_readme.html">Windows installation 
-notes</A> for more details.
-</UL>
 
 <A name=blt>
@@ -715,9 +729,5 @@
 If this is the case, a message, 
 "BLT Setup Error: could not access a Blt_ routine...", will be displayed.
-This is most common in UNIX and is discussed further in the 
-<A HREF="expgui_Unix_readme.html">UNIX installation notes</A>. Also see 
-<A HREF="http://www.ncnr.nist.gov/programs/crystallography/software/tclpkgs.html">
-http://www.ncnr.nist.gov/programs/crystallography/software/tclpkgs.html
-</A> for more information on installation of BLT.
+Use of the ncnrpack file distributed with EXPGUI usually avoids this problem.
 </UL>
 
@@ -727,8 +737,8 @@
 <UL>
 The
-<A HREF="www.hume.com">Hume 
+<A HREF="http://www.hume.com">Hume 
 </A>
 Linear Algebra Tcl Package, 
-<A HREF="www.hume.com">
+<A HREF="http://www.hume.com/la/la.html">
 La</A>, 
 is used by the BKGEDIT
@@ -739,10 +749,13 @@
 should not happen, since the package is included with the EXPGUI files.
 So if get this error you probably have an incomplete installation.
-Note that the La package requires Tcl/Tk version 8.1 or higher, so that if 
-you are using an older version of Tcl/Tk, you will need to upgrade.
-See the installation instructions for
-<A HREF="expgui_Win_readme.html">Windows</A>,
-and for
-<A HREF="expgui_Unix_readme.html">UNIX</A> for more information on Tcl/Tk.
+</UL>
+
+<A name=winexec>
+<H3>
+WINEXEC</H3>
+<UL>
+The WINEXEC package was needed under Windows-95 and its offspring 
+(-98 and -ME). It was found in older versions of EXPGUI, but is no
+  longer included.
 </UL>
 
@@ -750,10 +763,12 @@
 Acknowledgments</H2>
 Praise to Larson and 
-Von Dreele for GSAS, <A HREF="http://www.scriptics.com/">Ousterhout</A>
+Von Dreele for GSAS, <A HREF="http://home.pacbell.net/ouster/">John Ousterhout</A>
 for Tcl/Tk, 
-Przemek Klosowski</A>
+Przemek Klosowski
 for convincing me to learn Tcl/Tk 
-and Jonathan Wasserman for helping get this project started.
-Thanks also to 
+and Jonathan Wasserman for helping me get this project started.
+Thanks also to
+Charles Lake of Indiana University of PA for working on many recent additions to EXPGUI, including the
+bond-distance restraints module and the (soon to come) rigid body editor;
 Pamela Whitfield of the NRC (Canada) for writing large 
 sections of the 
@@ -763,5 +778,5 @@
 code and to John Cowgill for the "Export to GRACE" code.
 <P>
-<A Href="http://www.ncnr.nist.gov/programs/crystallography/software/gsas.html">
+<A Href="https://subversion.xor.aps.anl.gov/trac/EXPGUI/wiki/GSASIntro">
 GSAS</A>
 is written by Allen C. Larson and Robert B. Von Dreele while at 
@@ -770,6 +785,5 @@
 <A HREF="MAILTO:vondreele@anl.gov">vondreele@anl.gov</A>
 EXPGUI was written by Brian H. Toby while at the NIST Center for Neutron Research,
-<A HREF="MAILTO:Brian.Toby@ANL.GOV">Brian.Toby@ANL.GOV</A> 
-with help from Jonathan Wasserman.
+<A HREF="MAILTO:Brian.Toby@ANL.GOV">Brian.Toby@ANL.GOV</A>.
 
 <P><hr><blockquote>
@@ -786,5 +800,5 @@
 software.
 
-<P>The author of EXPGUI is a U.S. Government employee which means that
+<P>EXPGUI was written by a U.S. Government employee, which means that
 EXPGUI is not subject to copyright. Have fun with it. Modify it. Please write 
 new sections and make them available to the rest of the world. 
@@ -793,6 +807,5 @@
 expressed or implied, or assumes any liability or responsibility 
 for the use of this information or the software described
-here. Brand names cited herein are used for
-identification purposes and do not constitute an endorsement by NIST.
+here.
 </blockquote>
 
Index: /trunk/doc/expgui0.html
===================================================================
--- /trunk/doc/expgui0.html	(revision 1165)
+++ /trunk/doc/expgui0.html	(revision 1166)
@@ -44,8 +44,5 @@
 </TH></TR></TABLE>
 
-<P><font size=-1><A HREF="MAILTO:crystal@NIST.gov?subject=WWW page <?=$PHP_SELF?>">Comments, corrections or questions: crystal@NIST.gov</A></font><BR>
-<font size=-1><? lastmod(); ?> </font>
-<br>$Revision$ $Date$
-</blockquote>
+/blockquote>
 </body>
 </html>
Index: /trunk/doc/expgui1.html
===================================================================
--- /trunk/doc/expgui1.html	(revision 1165)
+++ /trunk/doc/expgui1.html	(revision 1166)
@@ -186,7 +186,4 @@
 </TH></TR></TABLE>
 
-<P><font size=-1><A HREF="MAILTO:crystal@NIST.gov?subject=WWW page <?=$PHP_SELF?>">Comments, corrections or questions: crystal@NIST.gov</A></font><BR>
-<font size=-1><? lastmod(); ?> </font>
-<br>$Revision$ $Date$
 </blockquote>
 </body>
Index: /trunk/doc/expgui2.html
===================================================================
--- /trunk/doc/expgui2.html	(revision 1165)
+++ /trunk/doc/expgui2.html	(revision 1166)
@@ -80,23 +80,31 @@
 <P>
 <a name="xform"></a>
-<h4>A.2.2 Transform Coordinates</h4> 
-<DL><DL>
-<img SRC="2a.gif" align=RIGHT alt="EXPGUI Screen snapshot">
-If one or more atoms have been selected
-<A href="expgui.html#mouseactions">(see Mouse Actions)</A>, it is possible
-to make changes to those atoms by pressing the "Xform atom(s)" button. 
-This raises the window shown to the right.
-Note that no changes are actually made, until the 
-"Transform Coordinates", "Set Occupancies",... buttons are pressed.
-<P>
-This window can be used 
-to transform the coordinates coordinates of the selected atoms, 
-globally set occupancy or Uiso (Uequiv) 
-values for the selected atoms, or erase the selected atoms. by pressing the 
-It is also possible to transform the selected atoms
-from isotropic to anisotropic, or the reverse. 
-<P>
-<IMG SRC="new.gif" alt="New!">
-The "Xform Origin 1 to Origin 2" button is only available for those 
+<h4>A.2.2 Modify Atom</h4> 
+<DL><DL>
+<img SRC="2a.jpg" align=RIGHT alt="EXPGUI Screen snapshot">
+The "Modify Atom" button ("Modify Atoms" when multiple atoms are
+  selected) provides access to additional options that can
+  transform or modify the selected atom(s) from the phase panel  
+<A href="expgui.html#mouseactions">(see Mouse Actions</A> for
+  information on selecting atoms); this opens the menu window shown to
+  the right.
+Note that changes are made to the coordinates when the buttons on this
+  window (such as 
+"Transform Coordinates", "Set Occupancies",...) are pressed.
+<P><B>Modify Coordinates:</B>
+  This is used 
+to transform the coordinates coordinates of the selected atoms using a
+set of  transformation relationships.
+  
+<P><B>Reset Multiplicities:</B>
+ When atom positions are edited in EXPGUI, they may be moved off from
+  or onto special positions in the cell, changing the site
+  multiplicity -- but this will not be reflected in the phase
+  display. When atoms are subsequently refined, GENLES will update the
+  multiplcities. Pressing the  "Reset Multiplicities" button cases
+  this to be done right away (I think this may not work if there are no
+  histograms present). 
+
+<P><B>Xform Origin 1 to Origin 2:</B> This button is only available for those 
 orthorhombic, tetragonal and cubic space groups that are listed in the
 International Tables with two origin settings. (These space groups have 
@@ -106,5 +114,51 @@
 of symmetry. GSAS only uses the origin 2 settings.)
 If coordinates have been entered in the origin 1 setting, they may be 
-transformed to the origin 2 setting using this button.
+transformed to the origin 2 setting using this button. It is important
+  to select all atoms in the asymmetric unit before using this button.
+
+  <P><B>Modify Occupancies:</B>
+ This allows the occupancy to be set for one or more atoms. It is
+  most convenient for when many atoms will have their occupancy
+  changed at one time.
+
+<P><B>Modify Displacement Parameters:</B>
+  This allows one to set Uiso (or Uequiv) values for the selected
+  atoms (<B>Set U</B>). To change the flag that determines if the
+  selected atom(s) are represented as Isotropic or Anisotropic, press
+  the <B>Set Isotropic</B> or <B>Set Anisotropic</B> buttons.
+
+<P><B>Erase Atoms:</B>
+  The "Erase Atoms" removes the selected atoms from the phase. I
+  usually set the occupancy to 0. instead. 
+  
+<P><B>Fix Atom Coordinates:</B>
+When an atom is refined in GSAS, only the coordinates that are not
+defined by site symmetry are refined. However, in some space groups,
+it is necessary to not refine additional coordinates. The most common
+example are polar space groups (P1, P2, P2<sub>1</sub>, C2,  P4, P4<sub>1</sub>, P
+4<sub>2</sub>, P4<sub>3</sub>, I4, I4<sub>1</sub>, P3, P3<sub>1</sub>, P3<sub>2</sub>, R3, P6, P6<sub>1</sub>, P6<sub>5</sub>, P6<sub>2</sub>, P6<sub>4</sub> and
+P6<sub>3</sub> - from
+<a href="http://www.ruppweb.org/Xray/comp/space_instr.htm"> Bernard Rupp's
+web site, http://www.ruppweb.org/Xray/comp/space_instr.htm</A>) where
+one or more coordinates of the origin are not defined by symmetry. In
+these space groups an appropriate number of coordinates must be fixed
+to define the origin. As an example, in P1, one x, one y and one z
+coordinate must not be refined; in space group P2<sub>1</sub>, the
+2<sub>1</sub> screw axis defines the origin at (0,0,z) so one z
+coordinate cannot be varied.
+
+Occasionally, while symmetry may allow
+atom coordinates to be varied, a crystallographer may choose to
+simplify or constrain the representation to fix the atom in a
+particular location and not refine with all allowed degrees of freedom.
+
+<IMG SRC="new.gif" alt="New!">
+ The "Fix Atom Coordinates" buttons allows a flag to be set (or
+cleared) for an atom
+to prevent refinement of selected coordinates, even when the X
+refinement flag is set. Note the addition of an "F" for the x and z
+coordinates of the first atom as shown in the phase panel, above. This
+indicates that x & z have been fixed. When the atom position is
+varied, only y will be optimized. 
 
 <br clear=all>
@@ -248,7 +302,4 @@
 </TH></TR></TABLE>
 
-<P><font size=-1><A HREF="MAILTO:crystal@NIST.gov?subject=WWW page <?=$PHP_SELF?>">Comments, corrections or questions: crystal@NIST.gov</A></font><BR>
-<font size=-1><? lastmod(); ?> </font>
-<br>$Revision$ $Date$
 </blockquote>
 </body>
Index: /trunk/doc/expgui3.html
===================================================================
--- /trunk/doc/expgui3.html	(revision 1165)
+++ /trunk/doc/expgui3.html	(revision 1166)
@@ -31,8 +31,8 @@
 <HR noshade width="75%" size="2" align="center">
 </h1></center>
-<h3>A.3 Histogram panel</h3> 
-<DL><DL>
-The histogram panel is used to edit background
-and diffractometer constants for a histogram, as well as 
+<h3>A.3 Powder panel</h3> 
+<DL><DL>
+The Powder (was histogram) panel is used to edit background
+and diffractometer constants for powder histogram(s), as well as 
 set damping and refinement flags for these parameters.
 <P>
@@ -288,7 +288,4 @@
 </TH></TR></TABLE>
 
-<P><font size=-1><A HREF="MAILTO:crystal@NIST.gov?subject=WWW page <?=$PHP_SELF?>">Comments, corrections or questions: crystal@NIST.gov</A></font><BR>
-<font size=-1><? lastmod(); ?> </font>
-<br>$Revision$ $Date$
 </blockquote>
 </body>
Index: /trunk/doc/expgui4.html
===================================================================
--- /trunk/doc/expgui4.html	(revision 1165)
+++ /trunk/doc/expgui4.html	(revision 1166)
@@ -60,7 +60,4 @@
 </TH></TR></TABLE>
 
-<P><font size=-1><A HREF="MAILTO:crystal@NIST.gov?subject=WWW page <?=$PHP_SELF?>">Comments, corrections or questions: crystal@NIST.gov</A></font><BR>
-<font size=-1><? lastmod(); ?> </font>
-<br>$Revision$ $Date$
 </blockquote>
 </body>
Index: /trunk/doc/expgui5.html
===================================================================
--- /trunk/doc/expgui5.html	(revision 1165)
+++ /trunk/doc/expgui5.html	(revision 1166)
@@ -118,7 +118,4 @@
 </TH></TR></TABLE>
 
-<P><font size=-1><A HREF="MAILTO:crystal@NIST.gov?subject=WWW page <?=$PHP_SELF?>">Comments, corrections or questions: crystal@NIST.gov</A></font><BR>
-<font size=-1><? lastmod(); ?> </font>
-<br>$Revision$ $Date$
 </blockquote>
 </body>
Index: /trunk/doc/expgui6.html
===================================================================
--- /trunk/doc/expgui6.html	(revision 1165)
+++ /trunk/doc/expgui6.html	(revision 1166)
@@ -22,5 +22,5 @@
 <TABLE BORDER BGCOLOR="#FFFF40" ALIGN=RIGHT>
 <TR><TH><A  Href="expgui.html">EXPGUI top</A> 
-</TH><TH><A Href="expgui7.html">Next page</A>
+</TH><TH><A Href="expgui6A.html">Next page</A>
 </TH><TH><A Href="expgui5.html">Previous page</A>
 </TH></TR></TABLE><BR CLEAR=ALL>
@@ -32,5 +32,5 @@
 </h1></center>
 
-<h3>A.6 Constraints panel</h3>
+<h3>A.6 Re/Constraints panel</h3>
 <DL><DL>
 GSAS offers two types of restraints that can be included in a model. 
@@ -41,7 +41,9 @@
 by grouping parameters so that a single shift (possibly scaled) is 
 applied to each parameter in the group.
-The constraints panel is used to set these "hard constraints."
+The Re/Constraints panel is used to set these "hard constraints" or in
+  the case of bond distances, "restraints".
 At this time the only constraints that can be set in EXPGUI are on atomic
-and profile profile (others can be set in EXPEDT).
+and profile profile (others can be set in EXPEDT). EXPEDT offers many
+  other types of restraints as well.
 <P>
 Note that these constraints are only applied to shifts, but not to the
@@ -212,14 +214,66 @@
 usually make sense and EXPGUI does not allow it.
 </DL></DL>
+<a name="DistanceRestraints"></a>
+<H4>Distance Restraints</H4>
+<DL><DL>
+  When the distance restraints tab is first selected, the active
+  distance restraints for the selected phase are shown. The <B>Atom 1</B> and
+  <B>Atom 2</B> buttons can be used to sort this list.
+  <P>
+  The <B>Restraint Weight</B> parameter is very important. As this
+  determines how strongly the distance restraints will be used in the
+  refinement relative to the diffraction data. This value is sometimes
+  set as high as 500,000 in the initial stages of a fit, but should be
+  lowered as much as is possible in the final stages of the fit, as
+  needed to obtain chemically plausible interatomic distances. For
+  some refinements, a value of 0.0 is possible for the Restraint
+  Weight in the final stages. This removes any restraint effect.
+
+  To see how restraints are affecting the refinement, one can look at
+  the ratio of the "Sum(w*d**2)" (shown in the .LST file) for the
+  diffraction histograms vs. the restraint histogram.
+<P>
+  The <B>Active Restraints Editor</B> can be used to select distances
+  to be restrained or edit the restraints. If there are too many
+  distances shown, the options at the top of the window can be used to
+  select a distance range, or specific atoms to include. Likewise,
+  only restrained or unrestrained distances can be selected. The
+  changes are applied when the <B>Filter</B> button is pressed.
+<P>
+  The bottom section of the window shows individual interatomic
+  distances. A <B>Restraint</B> and <B>Tolerance</B> value is needed to restrain
+  that distance. The quantity minimized is
+<blockquote>
+<blockquote>
+ "Restraint Weight" * SUM{  [ (Distance - Restraint) / Tolerance ]**2 } 
+</blockquote>
+</blockquote>
+thus the "Tolerance" provides individual weighting for each
+  restraint.
+<P>
+  To set a large number of restraints at the same time, select the
+  check button next to the distance(s), or use the <B>Check
+  All</B>. Then use the section above to enter a global
+  <B>Restraint</B> and <B>Tolerance</B> value. These values are set
+  when the <B>Set Checked</B> button is used.  The <B>Delete
+  Checked</B> button removes restraints from all selected distances.
+<P>
+The entered restraint information will be used onlt when the <B>Save
+  Changes</B> button is pressed. The <B>Cancel</B> button will reverse
+  any changes made while the window is open. Closing the window has
+  the same effect as "Cancel."
+  <P>
+  Note that the interatomic distances that are shown are determined by
+  the parameters to program DISAGL. These are controlled with the
+  <B>Edit Search Distance Parameters</B> button. 
+
+</DL></DL>
 <hr>
 <TABLE BORDER BGCOLOR="#FFFF40" ALIGN=RIGHT>
 <TR><TH><A  Href="expgui.html">EXPGUI top</A> 
-</TH><TH><A Href="expgui7.html">Next page</A>
+</TH><TH><A Href="expgui6A.html">Next page</A>
 </TH><TH><A Href="expgui5.html">Previous page</A>
 </TH></TR></TABLE>
 
-<P><font size=-1><A HREF="MAILTO:crystal@NIST.gov?subject=WWW page <?=$PHP_SELF?>">Comments, corrections or questions: crystal@NIST.gov</A></font><BR>
-<font size=-1><? lastmod(); ?> </font>
-<br>$Revision$ $Date$
 </blockquote>
 </body>
Index: /trunk/doc/expgui6A.html
===================================================================
--- /trunk/doc/expgui6A.html	(revision 1166)
+++ /trunk/doc/expgui6A.html	(revision 1166)
@@ -0,0 +1,359 @@
+<html>
+<head>
+   <title>EXPGUI</title>
+   <meta name="keywords" content="crystallography, Rietveld, diffraction,
+   GSAS, EXPGUI">
+</HEAD>
+<style>
+A:link {text-decoration:none}
+A:vlink {text-decoration:none}
+</style>
+
+<BODY BGCOLOR="#FFFFFF"
+      topmargin="0" leftmargin="0" marginwidth="0" marginheight="0" 
+      text="#000000" link="#0033ff" vlink="#0033ff" alink="#0033ff">
+
+<? 
+   include("/var/www/include/navigation.inc");
+   include("/var/www/include/utility.inc"); 
+?>
+<blockquote><font face="arial, helvetica, sans-serif">
+
+<TABLE BORDER BGCOLOR="#FFFF40" ALIGN=RIGHT>
+<TR><TH><A  Href="expgui.html">EXPGUI top</A> 
+</TH><TH><A Href="expgui7.html">Next page</A>
+</TH><TH><A Href="expgui6.html">Previous page</A>
+</TH></TR></TABLE><BR CLEAR=ALL>
+
+<center><h1>
+<HR noshade width="75%" size="2" align="center">
+EXPGUI, part 7
+<HR noshade width="75%" size="2" align="center">
+</h1></center>
+
+<h3>A.7 Rigid Body Introduction</h3>
+<DL><DL>
+GSAS Rigid bodies are another way to constrain relative atomic
+  positions. In a rigid body fit,
+a group of atoms are constrained so that they rotate and/or translate as a unit.
+GSAS allows quite complex rigid bodies, with up to 9 scaling parameters and
+when multiple rigid bodies are used with grouped parameters even more complex
+constraints can be developed. The EXPGUI rigid body interface allows access to
+most of the GSAS features and offers some setup features not in GSAS, but
+expert users may need to use EXPEDT for some very complex constraint models.
+<P>
+ Use of a rigid body reduces
+the number of parameters refined, prevents deviations from chemical
+reasonableness and generally helps obtain a more stable refinement. This can be especially important in the
+early stages of refinement. Rigid
+bodies are commonly used to constrain rigid moieties such phenyl or cyclopentadienyl rings but, they can be generated for much
+more complicated structures. Rigid bodies in GSAS are always
+represented by a set of Cartesian coordinates describing the relative positions
+of the atoms to be constrained. More complex frameworks can be constructed
+using multiple sets of Cartesian coordinates with variable multipliers, for
+more complex constraints. Even more sophisticated refinements are possible when
+multiple rigid bodies are constrained to share an origin or positioning (Euler)
+angles.
+<P>
+ Once created, the
+rigid body framework is applied as a constraint by mapping it onto atoms in a
+phase. The same rigid body framework can be mapped multiple times into one or
+more phases.
+  Once mapped, the set
+of atoms will refine as a single body with 3 parameters describing the
+translation of the rigid body origin (generally the centroid of mass of the
+atomic grouping but, this is optional) and 3 parameters describing the rotation
+of the body about the origin (Euler Angles). TLS terms (translation, libration,
+screw) can be used to model cooperative thermal motion about the rigid
+body. The EXPGUI rigid body routines
+will allow the user to readily generate the rigid body framework (called matrices
+in EXPGUI terminology) and map the rigid body to sets of atoms already present
+in the GSAS EXP file. 
+
+The EXPGUI Rigid Body Panel allows for the
+creation or viewing of rigid bodies.
+A rough outline of the procedure to generate and refine with a rigid body
+is as follows:
+
+<OL>
+<LI>Define the framework of the rigid
+body with a set of Cartesian coordinates representing the relative atomic
+positions. This can be done by
+manual input, loading the coordinates from an ASCII file,
+converting Z-matrix coordinates to Cartesian or generating Cartesian coordinates
+from fractional coordinates in an existing molecular fragment in the GSAS EXP
+file.
+<LI>
+ The rigid body
+framework must be mapped upon the crystal structure.
+This requires that the atoms in the
+phase be sequential and must match the order of atoms in the rigid body
+framework. 
+  To change the sequential
+order in the rigid body, the Edit Matrix routine may be used to reorder the
+rigid body coordinates.
+ In the
+mapping procedure, this number of the first atom in the phase to match the
+rigid body is designated (since the mapping then follows) and both the Euler angles
+and rigid body origin are specified; EXPGUI can help determine values
+  for these. 
+  This can be repeated to map the rigid
+body framework to other parts of the structure.
+<LI>
+ Once the rigid body framework
+is mapped to the crystal structure, the refinement flags for the Euler angles
+and Origin can be set. This will turn on the 'X' refinement flags for the
+included atoms in the Phase Panel. It is important that these match the state
+of the rigid body refinement flags or GENLES will crash.
+</OL>  
+</DL></DL>
+<H3>A.7.a Main Rigid Body Panel</H3>
+<DL><DL>
+The main panel for rigid bodies presents a interface where bodies can
+  be initially defined. When bodies have been defined, a tab appears
+  for each defined body, where these bodies can be used or
+  edited. This main panel is shown below and subsequent sections
+  describe how bodies are initially defined. 
+  <BR><img src="rb001.jpg" alt="RB start panel">
+ <BR>
+  Rigid bodies are created
+from one or more sets of Cartesian coordinates multiplied by a scale factor and
+then summed to create Cartesian coordinates in Angstroms. This can be expressed
+as a linear algebra expression,
+<P><DL><DL>
+ XYZ = M1*XYZ1 + M2*XYZ2 + ...
+</DL></DL>
+<P> 
+Where XYZ, XYZ1, ...are 3 by N matrices (3 columns by N atoms) and M1,
+M2,...
+are scalars. Therefore in EXPGUI terminology, each set of Cartesian
+coordinates is called a "Matrix." The
+sum of these scaled matrices describes the rigid body framework that is to be
+mapped upon the atoms of the crystal structure. Most commonly, however, only
+one matrix is used and M1=1. In this case the matrix is simply a set of Cartesian
+coordinates in Angstroms, which can be input by multiple methods.
+As a reminder, note that the rigid body
+framework will be mapped to consecutive atoms in the EXP file must be so the Cartesian
+coordinates of the rigid body MUST be listed in a corresponding order.
+<P>
+If the ordering of the Cartesian
+coordinates of the rigid body, as input, is incorrect, they may be rearranged
+with the Edit Matrix panel invoked
+from the Rigid Body Type panel.
+<P>
+Advanced refinements
+may take advantage of the GSAS feature of multiple matrices, each with its own
+matrix multiplier. This can result is some very advanced refinements such as
+independently refining the C-C and C-H bond distances in a hydrocarbon
+ring.
+<P>
+The "Create Rigid Body" tab offers several ways to create a rigid
+body:
+<UL><LI>Manual rigid body definition
+  <LI>Cartesian coordinates from ASCII text file
+  <LI>Cartesian coordinates from a Z-matrix
+  <LI>Compute Cartesian coordinates from EXP file (fractional coordinates)
+  </UL>
+  
+ <H4>A.7.a1 Manual rigid body definition</H4>
+<DL>
+  The manual definition window allows input of coordinates and
+  multipier(s) by typing values into boxes. Number of matrices
+  determines the number of multipliers and sets of coordinates that
+  are added. Number of Cartesian sites is the number of atoms in the
+  rigid body. The "Save Rigid Body" button creates a new rigid body
+  with the specified input. The "Export Cartesian Coordinates..."
+  writes an ASCII file with the current input.
+  <BR><img src="rb002.jpg" alt="Manual RB creation window">
+</DL>
+ <H4>A.7.a2 Cartesian coordinates from ASCII text file</H4>
+<DL>
+Cartesian coordinates
+can be read from any ASCII file containing Cartesian coordinates in a standard
+tabular format.
+  This routine allows
+the user to determine which columns (separated by a delimiter) represents the X,
+Y and Z coordinates.
+ The user also
+has the option to ignore any row or column that contains irrelevant
+information.
+  Once the Cartesian
+coordinates are isolated, and the "Continue" button is pressed,
+  the user continues to the "Create Rigid Body" window (see above).
+  <BR><img src="rb003.jpg" alt="ASCII RB input window">
+</DL>
+
+  <H4>A.7.a3 Cartesian coordinates from a Z-matrix</H4>
+<DL>
+Cartesian coordinates
+can also be calculated from a Z-matrix in an appropriate ASCII format.
+ The conversion routine will allow dummy
+atoms to be identified and ignored in the conversion process.
+ Upon pressing the "Continue" button, the Z-matrix
+is converted to Cartesian coordinates and the user progresses to the
+  "Create Rigid Body" window (see above).
+ <BR><img src="rb004.jpg" alt="Z-matrix RB input window">
+</DL>
+  <H4>A.7.a4 Compute Cartesian coordinates from EXP file (fractional coordinates)</H4>
+<DL>
+  Cartesian coordinates
+can also be determined from atoms in the EXP file.
+  In order to generate Cartesian
+coordinates, the number of sites in the rigid body framework must be specified
+as well as the starting atom (remember rigid bodies are mapped consecutively).
+  Once the number of atoms in the body is
+set, the "Choose Start Atom" button is pressed. This creates buttons for
+all possible choices for the first atom to define the body. Once the starting
+atom is selected by pressing one of these button(s), the atoms to be used to
+define the rigid body framework have been determined. The user must than select
+which atoms will be used to define the origin (the origin will be at the
+centroid of the atoms chosen) and must define the axes that will be used to
+generate the x-axis and the xy plane.
+The Cartesian coordinates can then be generated.
+Either the defined body can be determined and mapped (with the "Save and Map
+Rigid Body" button), or the Cartesian coordinates can exported to an
+ASCII text file (with the "Export Cartesian Coordinates"
+button).
+  <BR><img src="rb005.jpg" alt="Fraction Coords RB input window">
+</DL>
+
+</DL></DL>
+<H3>A.7.b Rigid Body Panel</H3>
+<DL><DL>
+ As each rigid body is
+defined, a "Rigid Body Type N" panel will be created.<span
+style="mso-spacerun:yes">&nbsp; 
+  This panel will show how the rigid body
+is mapped, and will allow the user to map / unmap the
+rigid body on to the crystal structure, view the rigid body (this
+  assumes the
+ <A HREF="http://www.lwfinger.net/drawxtl/">DRAWxtl</A> program is installed on their computer), edit the
+rigid body, set refinement flags, or delete the rigid body.
+  <BR><img src="rb006.jpg" alt="RB edit panel">
+
+  <H4>A.7.b1 Plot Rigid Body</H4>
+<DL>
+  <A HREF="http://www.lwfinger.net/drawxtl/">DRAWxtl</A>
+  is a very useful viewing program that
+EXPGUI can invoke, if installed. It
+allows for the viewing of the rigid body to ensure it is correct before mapping
+and matches the ordering of the atoms in the EXP file. The plot below
+  was obtained from the "Plot Rigid Body" button.
+  <BR><img src="rb007.png" alt="DRAWxtl screen">
+</DL>
+
+ <H4>A.7.b2 Map Rigid Body</H4>
+<DL>
+The rigid body must be mapped to the
+crystal structure to define the constraint. This is done by pressing
+  the "Map Rigid Body" button, which raises the window below. 
+  <BR><img src="rb008.png" alt="Map RB"><BR> 
+  In order to map the rigid body the user
+will need to specify the phase and the sequence number of the first atom in the
+.EXP file to be included.
+  This will
+be the atom assigned to the first set of coordinates in the rigid
+  body.
+ Each succeeding atom will be assigned
+the consecutive set of coordinates.
+The origin and Euler angles for the rigid body placement must be
+determined; this can be done by fitting to the atoms in the
+.EXP file using the &quot;Fit rigid body to phase&quot; button. A
+  table of RMS (~ A distances) between the mapped rigid body placement
+  and the initial atom placements -- this describes the quality of the fit.
+ If the fit is poor, it is
+likely that the ordering of Cartesian coordinates is incorrect, resulting in high
+RMS values. If this occurs, the ordering of the Cartesian coordinates must be
+modified with the Edit Matrix routine.
+  <BR><img src="rb010.png" alt=""><BR>
+ <img src="rb009.png" alt="" ALIGN="RIGHT">
+ The fit can be visually examined with
+the &quot;Plot rigid body &amp; phase&quot; button with results as
+  show to the right. 
+  The rigid body is shown in
+red and the .EXP file coordinates are shown in green. Note that it is often
+easier to understand what is being plotted, when bonds are drawn. The input in
+the "Bonds" box specifies ranges of distances where 0.9-1.1, 1.3-1.6 draws bonds
+between atoms spaced 0.9 to 1.1 A (typical C-H bonds) and 1.3 to 1.6 A (typical
+organic molecule bonds). You may wish to specify different
+  ranges where other types of bonding are present. One can also change
+  the display from the DRAWxtl menus.
+<BR Clear="all">
+  </DL>
+ <H4>A.7.b3 Edit Rigid Body</H4>
+  <DL>
+
+Pressing the "Edit Matrix" button on the "Rigid Body Type N" panel
+    provides an interface that will allow the Cartesian coordinates to be modified by
+sorting, swapping, adding or deleting matrix elements.
+   It will also allow for setting the refinement flag for Matrix
+Multipliers.
+  <BR><img src="rb011.jpg" alt=""><BR>
+ <img src="rb012.png" alt="" ALIGN="RIGHT">
+   Note that repeating the previous
+mapping, after reordering
+of the Cartesian coordinates, the following fit of a cyclopentadienyl
+ligand is accomplished and the RMS differences in the
+fitting procedure are small.
+    Below
+shows the correct fit.
+  <BR><img src="rb013.png" alt=""><BR>
+  <BR><img src="rb014.png" alt=""><BR>
+</DL>
+
+</DL></DL>
+<H3>A.7.c Setting Rigid Body Refinement Flags</H3>
+<DL><DL>
+ The "Refinement Flags" button opens a window that allows the
+user to set flags to refine various parameters.
+Parameters can be set up to refine as
+free variables or constrained variables.
+The TLS (translation, librations, screw) terms describe the rigid body
+thermal motions and are normally off.
+They should only be turned on if the user has a strong understanding of
+the relationships between the TLS terms.
+Note: if an Origin or Euler angle
+flag is enabled, the appropriate atom X refinement flag on the phase panel will
+be set.
+  GENLES will have errors if
+rigid body parameters are refined, but not the positions of the corresponding
+atoms.
+
+ Note that in EXPEDT,
+rigid body parameters can be grouped by assigning them the same variable
+number. The same feature is possible via a graphical interface by "tagging" (pressing
+the appropriate button for) items to vary and then using the following buttons:
+<UL><LI>
+ "Set Free Variables" - will assign each tagged parameter as
+an unconstrained variable by providing a unique variable number.
+
+ <LI>Do Not Refine Variables - will turn off the refinement flag
+for all tagged parameters.
+
+ <LI>Set Constrained variables - will constrain all tagged parameters
+and assign a single variable for refinement.
+ <LI>Clear All Variables - will clear all refinement flags.
+
+<LI>Assign Variables and Save - will assign variable numbers to each
+unique parameter to be refined and close the Refinement Flag window.
+  <BR><img src="rb015.png" alt=""><BR>
+  <BR><img src="rb016.png" alt=""><BR>
+
+The above Phase Panel shows the 'X'
+refinement flags active allowing the rigid body refinement to
+  commence.
+ These flags were set automatically when
+the rigid body position parameter were set to be refined. If these flags are
+turned off, it is likely that GENLES will crash. 
+
+  </DL></DL>
+<hr>
+<TABLE BORDER BGCOLOR="#FFFF40" ALIGN=RIGHT>
+<TR><TH><A  Href="expgui.html">EXPGUI top</A> 
+</TH><TH><A Href="expgui7.html">Next page</A>
+</TH><TH><A Href="expgui6.html">Previous page</A>
+</TH></TR></TABLE>
+
+</blockquote>
+</body>
+</html>
Index: /trunk/doc/expgui7.html
===================================================================
--- /trunk/doc/expgui7.html	(revision 1165)
+++ /trunk/doc/expgui7.html	(revision 1166)
@@ -23,14 +23,14 @@
 <TR><TH><A  Href="expgui.html">EXPGUI top</A> 
 </TH><TH><A Href="expguic.html">Next page (Menus)</A>
-</TH><TH><A Href="expgui6.html">Previous page</A>
+</TH><TH><A Href="expgui6A.html">Previous page</A>
 </TH></TR></TABLE><BR CLEAR=ALL>
 
 <center><h1>
 <HR noshade width="75%" size="2" align="center">
-EXPGUI, part 7
+EXPGUI, part 8
 <HR noshade width="75%" size="2" align="center">
 </h1></center>
 
-<h3>A.7 Preferential Orientation Panel</h3></a>
+<h3>A.8 Preferential Orientation Panel</h3></a>
 <DL><DL>
 The Preferential Orientation Panel is used to control parameters related
@@ -43,5 +43,5 @@
 </DL></DL>
 <a name="MD"></a>
-<h4>A.7.a March-Dollase</H4>
+<h4>A.8.a March-Dollase</H4>
 <DL><DL>
 In this model one or more axes are designated
@@ -67,5 +67,5 @@
 </DL></DL>
 <a name="ODF"></a>
-<H4>A.7.b Spherical harmonic</H4>
+<H4>A.8.b Spherical harmonic</H4>
 <DL><DL>
 The spherical harmonic formulation, also referred to as an "orientation
@@ -98,10 +98,7 @@
 <TR><TH><A  Href="expgui.html">EXPGUI top</A> 
 </TH><TH><A Href="expguic.html">Next page (Menus)</A>
-</TH><TH><A Href="expgui6.html">Previous page</A>
+</TH><TH><A Href="expgui6A.html">Previous page</A>
 </TH></TR></TABLE>
 
-<P><font size=-1><A HREF="MAILTO:crystal@NIST.gov?subject=WWW page <?=$PHP_SELF?>">Comments, corrections or questions: crystal@NIST.gov</A></font><BR>
-<font size=-1><? lastmod(); ?> </font>
-<br>$Revision$ $Date$
 </blockquote>
 </body>
Index: /trunk/doc/expgui_intro.html
===================================================================
--- /trunk/doc/expgui_intro.html	(revision 1165)
+++ /trunk/doc/expgui_intro.html	(revision 1166)
@@ -70,12 +70,12 @@
 Customization notes</A>
 <LI>
-<A HREF="tutorial3/index.html">
+<A HREF="https://subversion.xor.aps.anl.gov/EXPGUI/tutorials/tutorial3/index.html">
 A well-annotated CW neutron tutorial (Alumina).</A>
 <B><I>A very good place to start!</I></B>
 <LI>
-<A HREF="tutorial1/index.html">
+<A HREF="https://subversion.xor.aps.anl.gov/EXPGUI/tutorials/tutorial1/index.html">
 A TOF Tutorial Example (Nickel)</A>
 <LI>
-<A HREF="tutorial2/index.html">
+<A HREF="https://subversion.xor.aps.anl.gov/EXPGUI/tutorials/tutorial2/index.html">
 A CW Neutron Tutorial Example (Garnet)</A>
 </UL>
@@ -164,5 +164,5 @@
 <p><br><B>Who is to blame for EXPGUI?</B>
 <blockquote>The initial version of the GUI part of EXPGUI was created by
-Jonathan Wasserman (thanks Jon!) <a href="http://www.ncnr.nist.gov/staff/toby/">Brian
+Jonathan Wasserman (thanks Jon!) Brian
 Toby</a> is irresponsible for the rest.</blockquote>
 
@@ -170,6 +170,5 @@
 <blockquote>Gee, you want to add some features... Great! You have all the
 EXPGUI sources and
-<A Href="http://www.ncnr.nist.gov/programs/crystallography/software/tclpkgs.html">Tcl/Tk</A>
-is free. Oh, you want me to do it. Well, please 
+Tcl/Tk is free. Oh, you want me to do it. Well, please 
 ask and I will try. In particular, I am looking for good ideas on 
 how to design GUI's for different aspects of experiment editing, 
@@ -177,7 +176,8 @@
 
 <p><br><B>Mailing List</B>
-<blockquote>If you would like to get news about EXPGUI, please send 
-<a href="mailto:brian.toby@anl.gov?subject=EXPGUI Mailing List">Brian.Toby@ANL.GOV</a> e-mail. The mailing list is not active at present, but 
-I hope to use it again to provide 
+<blockquote>If you would like to get news about EXPGUI, please 
+<a href="http://www.aps.anl.gov/mailman/listinfo/expgui">see this
+link</a>.
+The mailing list is used only to provide 
 information about updates and bug fixes. 
 </blockquote>
Index: /trunk/doc/expguic.html
===================================================================
--- /trunk/doc/expguic.html	(revision 1165)
+++ /trunk/doc/expguic.html	(revision 1166)
@@ -49,6 +49,6 @@
 	experiment file from scratch.
 <DT>expnam<DD>
-Equivalent to Open, included since this is the command used in other 
-GSAS shells to select GSAS experiments.
+Equivalent to Open (included for historical reasons.)
+
 <DT>Save<DD>Saves modifications to the current experiment file to disk (shortcut Alt-S).
 <DT>Save As<DD>Saves modifications to the current experiment file to disk
@@ -60,7 +60,11 @@
   offers the program user the option to update these files. The update
   will fail if the user does not have permission to change the EXPGUI
-  or GSAS files. In this case, a system administrator may be needed. 
+  or GSAS files. In this case, a system administrator may be needed.
+  <DT>revert<DD>Used to load an <a href="#archive">archived</A>
+    (backup) version of the current .EXP file. 
 <DT>EraseHistory<DD>Deletes old history records to speed reading of the .EXP file.
-<DT>convert<DD>Convert a standard ASCII file to the direct access format used by GSAS (and for UNIX, the reverse)
+<DT>convert<DD>Convert a standard ASCII file to the direct access
+  format used by GSAS (and for UNIX, the reverse) -- this is not
+  likely to be needed, as GSAS now does most conversions automatically.
 <DT>exit<DD>Exit EXPGUI (shortcut Alt-X or ^C)
 </DL>
@@ -99,10 +103,10 @@
 revised .EXP file, which means that you reject the last set of changes.
 This is useful if 
-GENLES blows up or you have done something wrong. The advantage 
-of turning "autoload EXP" on is
+GENLES blows up or you have done something wrong. The reason to  
+turning "autoload EXP" on is
 that there is one less thing to do when running GSAS programs.
 Note that it is still possible to reverse changes, if 
-<a href="#archive">archive files</A>, but this may require more effort.
-
+<a href="#archive">archive files</A>, but this may require more
+  effort. See the File/revert menu entry.
 <a name="execprompt"></a>
 <DT>Prompt after GSAS run<DD>
@@ -121,5 +125,6 @@
 screen cluttered with EXPGUI when it can't be used, 
 but this is an option so that the mode can be turned off by those people
-who find this behavior annoying.
+who find this behavior annoying. It appears this option causes
+  problems on Windows 7. 
 
 <a name="AutostartGRWND"></a>
@@ -225,5 +230,4 @@
 <DT>rawplot<DD>Plot powder data
 <DT>fitspec<DD>Fit a TOF vanadium scattering spectrum
-<DT>tofnorm<DD>Normalize a TOF spectrum
 <DT><a HREF="liveplot.html#bkgedit">bkgedit</a>
 <DD>Invokes the <a HREF="liveplot.html#bkgedit">BKGEDIT</a> program
@@ -233,4 +237,13 @@
 to set the upper and lower limits for a histogram, as well as
 edit excluded regions.
+<DT>seqgsas<DD>Invokes the sequential GSAS refinement program to run
+  GENLES on a set of very similar data files.
+<DT>mustrplot<DD>Plot microstrain results
+<DT><a HREF="expgui.html#INSTEDIT">instedit</A><DD>Invokes the <a HREF="expgui.html#INSTEDIT">instedit</A>
+  to edit an instrument parameter file.
+<DT>New InstParm file<DD>Creates a new instrument parameter file using
+  <a HREF="expgui.html#INSTEDIT">instedit</A>.
+
+
 </DL>
 <img SRC="m3.gif"  BORDER=3 alt="EXPGUI Screen snapshot">
@@ -238,5 +251,5 @@
 
 <a name="4"></a>
-<h3>C.4 Single Crystal Menu</h3>
+<h3>C.4 Xtal (Single Crystal) Menu</h3>
 <BLOCKQUOTE>
 This menu contains links to GSAS programs used for 
@@ -268,4 +281,6 @@
 <DT>fourier<DD>Generate Fourier map
 <DT>forsrh<DD>Search Fourier map for peaks
+<DT>gsas2map<DD>Exports a Fourier map in formats used by other
+  programs (for example Fox and DRAWxtl).
 <DT><a HREF="liveplot.html#liveplot">liveplot</a>
 <DD>Invokes the <a HREF="liveplot.html#liveplot">LIVEPLOT</a> program
@@ -274,4 +289,9 @@
 <DT>vrstplot<DD>Create a VRML 3-D file for viewing with 3rd party software
 <DT>widplt<DD>Displays the FWHM as a function of Q, 2Theta,... for UVWXY values input or read from an EXP file
+<DT><a HREF="expgui.html#ABSPLT">absplt</A>
+<DD>The <a HREF="expgui.html#ABSPLT">absplt</A> program displays the
+  absorption/reflectivity correction curve for values used in a histogram.
+<DT>mustrplot<DD>Plot microstrain results
+<DT>seqplot<DD>Plot results from seqgsas
 </DL>
 <img SRC="m5.gif"  BORDER=3 alt="EXPGUI Screen snapshot">
@@ -287,4 +307,6 @@
 <DT>bijcalc<DD>Thermal parameter analysis
 <DT>disagl<DD>Distance/angle calculations
+<DT>disaglviewer<DD>Display results from distance/angle calculations
+  in a graphical browser.
 <DT>reflist<DD>List reflection data
 <DT>geometry<DD>Molecular geometry calculations
@@ -297,4 +319,5 @@
 <DT>ramafit<DD>Fits torsion angle distributions, particularly in peptide
 chains, for use in restraints.
+<DT>seqplot<DD>Plot results from seqgsas
 </DL>
 <img SRC="m6.gif"  BORDER=3 alt="EXPGUI Screen snapshot">
@@ -307,7 +330,11 @@
 <DL>
 <DT>cllchg<DD>Transform unit cell
-<DT>fprime<DD>Compute f, f', f'' and mu/rho for an element for a range of x-ray wavelengths
+<DT>composition<DD>Computes the chemical composition of a unit cell
+accounting for site multiplicies and occupancies
 <DT>rducll<DD>Unit cell reduction
 <DT>spcgroup<DD>Space group symbol interpreter
+<DT>seqgsas<DD>Invokes the sequential GSAS refinement program to run
+  GENLES on a set of very similar data files.
+<DT>seqplot<DD>Plot results from seqgsas
 <DT>unimol<DD>Unique molecule assembler
 </DL>
@@ -315,34 +342,6 @@
 </BLOCKQUOTE>
 
-<a name="8"></a>
-<h3>C.8 Import/Export Menu</h3>
-<BLOCKQUOTE>
-This menu contains utilities for importing information into GSAS and
-exporting.
-<DL>
-<DT>exp2xtl<DD>Prepare a .XTL format file of atomic positions. This
-file is used in MSI software such as Cerius and InsightII.
-<DT>gsas2cif<DD>Prepare IUCr crystallographic information (CIF) file
-<DT>hklsort<DD>Prepare HKL tables
-<DT>pubtable<DD>Prepare atom parameter tables
-<DT>convert<DD>Convert a standard ASCII file to the direct access format used by GSAS (and for UNIX, the reverse)
-<DT>cad4rd<DD>Prepare CAD4 single crystal data
-<DT>dbwscnv<DD>Convert a powder diffraction data file from DBWS format
-<DT>x17bcnv<DD>Convert an energy dispersive diffractogram data file from NSLS X17b
-<DT>p3r3data<DD>Prepare Siemens/Brucker P3R3 single crystal data
-<DT>sxtldata<DD>Prepare generic single crystal data
-<DT>gsas2pdb<DD>
-Import (using GSAS2PDB & EXPEDT) and export coordinates (for 
-macromolecular phases) to/from Protein Data Base files
-<DT>ref2asc<DD>
-Exports a GSAS reflection file to ASCII for use in non-GSAS programs
-<DT>ref2bin<DD>
-Imports an ASCII reflection file to the GSAS binary format
-</DL>
-<img SRC="m8.gif"  BORDER=3 alt="EXPGUI Screen snapshot">
-</BLOCKQUOTE>
-
 <a name="9"></a>
-<h3>C.9 Macro Menu
+<h3>C.8 Macro Menu
 <IMG SRC="new.gif" HEIGHT=13 WIDTH=36 alt="New!">
 </h3>
@@ -402,4 +401,77 @@
 </DL>
 </BLOCKQUOTE>
+
+<a name="8"></a>
+<h3>C.9 Import/Export Menu</h3>
+<BLOCKQUOTE>
+This menu contains utilities for importing information into GSAS and
+exporting it to other programs.
+<DL>
+<DT>Coord Export<DD>This provides a series of routines that are used
+to write coordinates and possibly other information to files:<P>
+<DL>
+<DT>gsas2cif<DD>Prepares IUCr crystallographic information (CIF) file
+that documents the current refinement. The CIF contains the
+coordinates for all phases as well as the observed and computed
+diffraction patterns. The templates used by GSAS2CIF can be customized
+to provide a detailed description of the experimental measurements and
+results for use in documenting analysis for publication or
+deposition. 
+<DT>coords-only CIF<DD>For export of intermediate results to another
+program, CIF can be a useful exchange format. This routine provides a
+CIF with the current coordinates from one phase and not much else.
+<DT>export to DRAWxtl<DD>This writes a .STR file used in the DRAWxtl
+program and optionally launches DRAWxtl. 
+<DT>export to SHELX<DD>This writes coordinates for a selected phase in
+the .INS format used by SHELX and several other programs.
+<DT>export to PLATON<DD>This writes coordinates for a selected phase in
+the .SPF format used by PLATON
+<DT>export test format<DD>This demonstrates how a coordinate export
+routine can be added to EXPGUI. See the <A
+HREF="expgui_cfg.html#export">documentation on this</A> for further
+information. 
+<DT>export to FOX<DD>This prepares a XML file with coordinates for use
+in the FOX program
+<DT>MSI .xtl<DD>Prepare a .XTL format file of atomic positions. This
+file is used in older Accelrys software such as Cerius and
+Insight-II. It may no longer be of value.
+</DL>
+
+<DT>CIF Export<DD>This provides a series of routines that are used
+to prepare CIF files:<P>
+<DL>
+<DT>gsas2cif<DD>Prepares IUCr crystallographic information (CIF) file
+that documents the current refinement. The CIF contains the
+coordinates for all phases as well as the observed and computed
+diffraction patterns. The templates used by GSAS2CIF can be customized
+to provide a detailed description of the experimental measurements and
+results for use in documenting analysis for publication or
+deposition.
+<DT>FillTemplate<DD>Used to edit the CIF template files used in GSAS2CIF
+<DT>CIFselect<DD>Used to select interatomic distances and angles to be
+included in the CIF created by GSAS2CIF.
+</DL>
+
+<DT>hklsort<DD>Prepare HKL tables
+<DT>pubtable<DD>Prepare atom parameter tables
+<DT>convert<DD>Convert a standard ASCII file to the direct access format used by GSAS (and for UNIX, the reverse)
+<DT>cad4rd<DD>Prepare CAD4 single crystal data
+<DT>dbwscnv<DD>Convert a powder diffraction data file from DBWS format
+<DT>x17bcnv<DD>Convert an energy dispersive diffractogram data file from NSLS X17b
+<DT>p3r3data<DD>Prepare Siemens/Brucker P3R3 single crystal data
+<DT>sxtldata<DD>Prepare generic single crystal data
+<DT>gsas2pdb<DD>
+Import (using GSAS2PDB & EXPEDT) and export coordinates (for 
+macromolecular phases) to/from Protein Data Base files
+<DT>ref2asc<DD>
+Exports a GSAS reflection file to ASCII for use in non-GSAS programs
+<DT>ref2bin<DD>
+Imports an ASCII reflection file to the GSAS binary format
+<DT>gsas2map<DD>Exports a Fourier map in formats used by other
+  programs (for example Fox and DRAWxtl).
+</DL>
+<img SRC="m8.gif"  BORDER=3 alt="EXPGUI Screen snapshot">
+</BLOCKQUOTE>
+
 <hr>
 <TABLE BORDER BGCOLOR="#FFFF40" ALIGN=RIGHT>
Index: /trunk/doc/gsas2cif.html
===================================================================
--- /trunk/doc/gsas2cif.html	(revision 1165)
+++ /trunk/doc/gsas2cif.html	(revision 1166)
@@ -33,6 +33,5 @@
 <BR>
 to export
-<A Href="http://www.ncnr.nist.gov/programs/crystallography/software/gsas.html">
-GSAS</A>
+<A Href="https://subversion.xor.aps.anl.gov/trac/EXPGUI/wiki/GSASIntro">GSAS</A>
 results
 <HR noshade width="75%" size="2" align="center">
@@ -575,7 +574,4 @@
 </BLOCKQUOTE>
 
-<P><font size=-1><A HREF="MAILTO:crystal@NIST.gov?subject=WWW page <?=$PHP_SELF?>">Comments, corrections or questions: crystal@NIST.gov</A></font><BR>
-<font size=-1><? lastmod(); ?></font>
-$Revision$ $Date$
 </font>
 </BLOCKQUOTE>
Index: /trunk/doc/liveplot.html
===================================================================
--- /trunk/doc/liveplot.html	(revision 1165)
+++ /trunk/doc/liveplot.html	(revision 1166)
@@ -40,10 +40,7 @@
 <P>
 Both LIVEPLOT and BKGEDIT get the current diffraction information 
-by running the GSAS TCLDUMP program, if installed, or
-the GSAS HSTDUMP otherwise. The TCLDUMP program has been optimized for use 
-with LIVEPLOT and allows LIVEPLOT to offer a number of extra 
-options that are not available when HSTDUMP is used. Since TCLDUMP has been 
-included in GSAS since April of 2000, the following documentation assumes 
-that TCLDUMP is installed.
+by running the GSAS TCLDUMP program. (In GSAS/EXPGUI before 2001, the
+GSAS HSTDUMP program was used, which was less powerful. This code has
+not been removed, but will not be used if TCLDUMP is present.)
 
 <a name="liveplot"></a>
@@ -54,5 +51,12 @@
 Some of the features available in LIVEPLOT are:
 <UL>
-<LI>The plot is updated automatically after each refinement run
+<LI><IMG SRC="new.gif" alt="New!"> 
+Regions of the plot can be magnified to show more detail, for example
+  in regions at high Q. 
+<LI><IMG SRC="new.gif" alt="New!"> 
+Plots can be <a href="#export">exported to obtain publication-quality
+graphics </a> -- <B><I>now on all platforms</I></B>.
+<LI><IMG SRC="new.gif" alt="New!"> Intensity can be displayed as I/sigma(I)
+ <LI>The plot is updated automatically after each refinement run
 <LI>The plot can be "zoomed-in", by clicking on the corners of the 
 area to be magnified and "zoomed-out" using the 
@@ -61,6 +65,6 @@
 The units used for plotting histograms can be selected. Choices are: 
 native units (2Theta/TOF/KeV); d-space (A) or Q (A<sup>-1</sup>)
-<LI>
-The background (fixed plus fitted) can be plotted or can be subtracted. 
+ <LI>
+  The background (fixed plus fitted) can be plotted or can be subtracted. 
 <LI>
 Reflection tickmarks can be displayed in a variety of formats 
@@ -73,10 +77,7 @@
 <LI>
 The cumulative chi<sup>2</sup> function or 
-<IMG SRC="new.gif" alt="New!"> (obs-calc)/sigma can be plotted.
+ (obs-calc)/sigma can be plotted.
 <LI>
 The cursor position can be displayed
-<LI>
-Plots can be <a href="#export">exported to obtain publication-quality
-graphics.</a>
 </UL>
 
@@ -285,5 +286,4 @@
 <P>
 <a name="zoomshift"></a>
-<IMG SRC="new.gif" alt="New!">
 To shift the zoom region around, 
 the right and left arrow keys can be used to shift the 
@@ -363,18 +363,61 @@
 <br clear=all>
 <P>
+<a name="magnification"></a>
+<B>Plot Magnification</B>
+Sections of the plot can be magnified through use of options in the
+Magnification menu or by using control-1 through control-9. 
+<img SRC="magreg.png" align=RIGHT alt="LIVEPLOT Screen snapshot">
+<UL>
+<LI>The Magnification/Add region menu item requests a location in the
+  pattern (2Theta/TOF/KeV/d-space/Q) and a multiplier. Data where the
+  scan variable (2Theta...) is of that value or higher, up to the
+  next region or end of the pattern are multiplied by that factor. The
+  factor, must be >0.
+<LI>Magnification/Edit regions brings up a menu (see below) where the previously
+ defined regions can be changed. The region boundaries can be moved
+  and the multiplier values can be changed. If a multiplier is set to
+  zero (or negative) that region is removed.
+<LI>Magnification/Clear deletes all previously defined regions
+<LI>Pressing control plus a positive digit (1,2,3,...9) also adds a
+  magnification region. The digit determines the magnification
+  multiplier. Data where the
+  scan variable (2Theta...) from the mouse position up to the
+  next region or end of the pattern are multiplied by that factor.
+<img SRC="editreg.png" align=RIGHT alt="LIVEPLOT menu">
+</UL>
+ <br clear=all>
+<P>
 <a name="export"></a>
 <B>Export plot options</B>
 <UL><LI>
-The plot can be exported to 
+<IMG SRC="new.gif" alt="New!"> 
+The LIVEPLOT program can export plots to to a <I>high quality</I> PDF
+  file for presentations or publications using <A
+  HREF="http://www.gnuplot.info/">gnuplot</A>.
+  The PDF will match what is is shown on fairly
+  closely with respect to colors, <A href="#plotfont">font sizes</a>
+  and <a href="#zoom">zoom</a>. The new <A href="#magnification">plot magnification</a> to show detail in
+  the fit and for publication increase the 
+  <A href="#plotfont">plot font</a> so that the figure size can be
+  reduced to the standard Rietveld postage stamp, required by so many
+  Journals -- allowing the text to be discerned, even if the problems in the
+  fit cannot.
+  <P>Starting August
+  2011, windows and Mac versions of gnuplot are included with the GSAS
+  binaries; gnuplot is easily
+  installed on Linux with standard tools such as yum (Redhat),
+  apt-get (ubuntu) or zypper (openSuse). 
+
+<P><LI>  The plot can be exported to 
 <A HREF="http://plasma-gate.weizmann.ac.il/Grace/">Grace</A>, WYSIWYG 2D plotting tool for X-Windows
-that produces publication-quality graphics. Many UNIX users know 
-this program under a previous name, xmgr.
-The export is implemented 
-by producing an ASCII file with instructions that 
-creates a plot with similar formatting to what appears on the 
-screen in LIVEPLOT/BKGEDIT. However, the output quality from 
-Grace is much higher quality. Further, Grace
-can be used to enhanced and annotate the plot further.
-<LI>
+that produces publication-quality graphics that appear very similar to
+  what is seen in LIVEPLOT/BKGEDIT. Further, Grace
+  can be used to enhance the plot, for example by editing captions,
+  figure display options and even annotate the plot.
+  Grace runs well on Linux and Mac computers; Many UNIX users know 
+  this program under a previous name, xmgr.
+  For Windows,
+  installation of <A HREF="http://cygwin.com/">Cygwin</A> is required.
+  <P><LI>
 For use in many other graphics programs, LIVEPLOT will produce a 
 "comma separated variable" data file with the data displayed on the screen. 
@@ -382,7 +425,10 @@
 set line styles and scaling, etc., but this does provide an option for 
 generating high-quality graphics for presentations and publications.
-<LI>LIVEPLOT will produce PostScript versions of the plot on the screen,
+<P><LI>LIVEPLOT will produce PostScript versions of the plot on the screen,
 but the quality is rather low (this is a limitation of the BLT graphics
 package).
+  <P><LI>LIVEPLOT/BKGFIT can also be used to prepare input for FOX (Free
+  Objects for Xtallography). 
+  
 </UL>
 
@@ -408,4 +454,7 @@
 <DT><a href="#zoomshift">arrow keys</A>
 <DD>Moves zoom region around in plot
+<DT><a href="#mag">Control+1, 2,...</a>
+<DD>Defines a <a href="#magnification">magnification region</A> at the
+  cursor location.
 </DL>
 
@@ -438,6 +487,14 @@
 <DT>Export Plot
 <DD>This offers options for exporting the plot in multiple formats.
-I am hoping to add more export formats eventually.
-<DL><DL>
+<DL><DL>
+<DT>to PDF
+ <IMG SRC="new.gif" alt="New!"> 
+<DD>Creates a <I>high quality</I> PDF file that may be useful for
+  presentations or publications. Note that you may wish to use
+  <A href="#magnification">plot magnification</a> to show detail in
+  the fit and for publication increase the 
+  <A href="#plotfont">plot font</a> so that the figure size can be
+  reduced.
+
 <DT>to PostScript
 <DD>Creates a <I>low quality</I> PostScript file containing the LIVEPLOT 
@@ -446,5 +503,6 @@
 On Windows, a program such ghostview may be needed to translate the 
 PostScript to a format that can be viewed or printed.
-<A name="grace">
+
+  <A name="grace">
 <DT>to Grace
 <IMG SRC="note.gif" alt="Note!">
@@ -454,4 +512,12 @@
 After the plot is exported, it can be further 
 enhanced and annotated in grace.
+
+<DT>to .csv file
+  <DD>Creates a "comma separated variable" file. This contains all the
+  diffraction data shown in the plot. It can be used to produce a plot
+  in some other graphics program. 
+  <DT>Fox XML
+  <DD>The Fox program provides structure solution capabilities. This
+  option can be used to write data in the XML format that Fox uses. 
 </DL></DL>
 <DT>Quit
@@ -505,5 +571,8 @@
 <DT>Y units
 <DD>The intensity values can be normalized by the incident spectrum
-(for energy dispersive methods).
+(for energy dispersive methods) or
+  <IMG SRC="new.gif" alt="New!"> can be displayed as a ratio with the
+  experimental uncertainty [I<sub>obs</sub>/sigma(I<sub>obs</sub>),
+  I<sub>calc</sub>/sigma(I<sub>obs</sub>) and their difference].
 </DL></DL>
 <br clear=all>
@@ -535,5 +604,12 @@
 <DT>Set screen font
 <DD>This option is used to control the font used for menus, graphics and 
-other aspects of windows. 
+other aspects of windows. This value can be saved as a default value. 
+<A name="plotfont">
+  <DT>Set plot font
+<DD>This option is used to change the font used in the plot
+  window. This has a similar effect to changing the screen font, but
+  can be changed over a wider range and only affects the
+  graph. Changing the font size either way will change the font used
+  in the exported .PDF.
 <DT>Raise on update
 <DD>This causes the plot to be placed on top of other windows, if partially
@@ -650,19 +726,11 @@
 <P>
 <hr><H2>Interfacing External Programs</H2>
-<IMG SRC="new.gif" alt="New!">
 <B>Combining LIVEPLOT with CMPR & LOGIC</B>
 If you have the 
-<A HREF="http://www.ncnr.nist.gov/programs/crystallography/software/cmpr">
-CMPR/LOGIC</A>
-programs installed on your computer, you can use superimpose on the 
+<A HREF="https://subversion.xor.aps.anl.gov/trac/CMPR">CMPR</A>
+program installed on your computer, you can use superimpose on the 
 GSAS results the peaks for an arbitrary unit cell.
-If you have an old version of the 
-<A HREF="http://www.icdd.com/products/overview.htm">
-ICDD-JCPDS PDF-2 powder diffraction database</a>, 
-(when distributed as an AIDS*83 format flat file)
-you can also superimpose entries from this database on the 
-GSAS results displayed in LIVEPLOT. 
-<P>
-When the CMPR/LOGIC program is installed in the same location
+<P>
+When the CMPR program is installed in the same location
 as the GSAS package (<i>e.g.</i> 
 <font face="courier">/home/gsas</font> & 
@@ -692,13 +760,8 @@
 software is located. The
 "Display a cell" option produces a window similar to the
-<A href="http://www.ncnr.nist.gov/xtal/software/cmpr/doc/cmprdoc.html#editcell">
+<A href="https://subversion.xor.aps.anl.gov/CMPR/trunk/doc/cmprdoc.html#editcell">
 Edit Cell feature in CMPR</A>
 where allowed reflection positions are displayed for a set of unit cell 
 parameters and optionally a space group or extinction conditions.
-The "Plot ICDD Entry" provides a window similar to the 
-<A href="http://www.ncnr.nist.gov/xtal/software/cmpr/doc/cmprdoc.html#editcell">
-LOGIC interface in CMPR</A>
-where ICDD searches may be conducted. From the resulting list of matches,
-selected entries may be displayed.
 <P>
 Note that these routines display peak positions in units of 2Theta, Q or
@@ -718,8 +781,4 @@
 </TH></TR></TABLE>
 
-<P><font size=-1><A HREF="MAILTO:crystal@NIST.gov?subject=WWW page <?=$PHP_SELF?>">Comments, corrections or questions: crystal@NIST.gov</A></font><BR>
-<font size=-1><? lastmod(); ?> </font>
-<br>
-$Revision$ $Date$
 </blockquote>
 </body>
Index: /trunk/doc/revlog.html
===================================================================
--- /trunk/doc/revlog.html	(revision 1165)
+++ /trunk/doc/revlog.html	(revision 1166)
@@ -32,9 +32,16 @@
     </h1></center>
     <P>
-    This page describes all revisions logged for changes to the EXPGUI source
+    This page has been superceeded by the Trac registry, see
+    <A HREF="https://subversion.xor.aps.anl.gov/trac/EXPGUI/timeline">
+    https://subversion.xor.aps.anl.gov/trac/EXPGUI/timeline</A>.
+    <HR><HR>
+    Below is information on older revisions logged for changes to the EXPGUI source
     files, sorted by date. 
-    See the <A HREF="wishlist.html">EXPGUI Wish List</A> for a more 
-    descriptive listing.
-
+    See the
+    <A HREF="https://subversion.xor.aps.anl.gov/trac/EXPGUI/report">
+    View Tickets</A> section of the Trac site for active and closed
+    projects. There is some older information on the 
+    <A HREF="wishlist.html">EXPGUI Wish List</A>.
+    
 <h2>since 1-Jun-2009</h2><DL><DL>
 </DL></DL>
@@ -1633,8 +1640,5 @@
     </TH><TH><A Href="wishlist.html">Past and Planned<BR>Updates</A>  
     </TH></TR></TABLE>
-    <P><font size=-1><A HREF="MAILTO:crystal@NIST.gov?subject=WWW page <?=$PHP_SELF?>">Comments, corrections or questions: crystal@NIST.gov</A></font><BR>
-    <font size=-1><? lastmod(); ?> </font>
-    <br>
-    </blockquote>
+   </blockquote>
 
 Created Fri Jul 03 20:35:34 CDT 2009
Index: /trunk/doc/win_old_notes.html
===================================================================
--- /trunk/doc/win_old_notes.html	(revision 1165)
+++ /trunk/doc/win_old_notes.html	(revision 1166)
@@ -43,5 +43,5 @@
 Nonetheless, please report problems, including improvements on 
 these instructions to
-<A HREF="mailto:brian.toby@nist.gov">Brian Toby</A>.
+<A HREF="mailto:brian.toby@anl.gov">Brian Toby</A>.
 Otherwise, Windows-specific issues are unlikely to be addressed or repaired.
 </EM>
@@ -57,6 +57,6 @@
 <P>
 <LI>Get 
-<A Href="http://www.ncnr.nist.gov/programs/crystallography/software/gsas.html">
-GSAS</A> from one of the following sites:
+<A Href="https://subversion.xor.aps.anl.gov/trac/EXPGUI/wiki/GSASIntro">GSAS</A>
+from one of the following sites:
 <DL><P>
 <DT>UK<DD>
@@ -296,5 +296,5 @@
 <A HREF="MAILTO:vondreele@anl.gov">vondreele@anl.gov</A>
 <P>EXPGUI is written by Brian H. Toby of the NIST Center for Neutron Research,
-<A HREF="MAILTO:Brian.Toby@NIST.GOV">Brian.Toby@NIST.GOV</A> 
+<A HREF="MAILTO:Brian.Toby@ANL.GOV">Brian.Toby@ANL.GOV</A> 
 with help from Jonathan Wasserman.
 
@@ -325,8 +325,4 @@
 </TH></TR></TABLE>
 
-<P><font size=-1><A HREF="MAILTO:crystal@NIST.gov?subject=WWW page <?=$PHP_SELF?>">Comments, corrections or questions: crystal@NIST.gov</A></font><BR>
-<font size=-1><? lastmod(); ?> </font>
-<br>
-$Revision$ $Date$
 </blockquote>
 </body>
Index: /trunk/doc/wishlist.html
===================================================================
--- /trunk/doc/wishlist.html	(revision 1165)
+++ /trunk/doc/wishlist.html	(revision 1166)
@@ -31,4 +31,20 @@
 <HR noshade width="75%" size="2" align="center">
 </h1></center>
+<I><blockquote><blockquote>
+Information on desired (and completed) development tasks for EXPGUI
+are now captured as "Tickets" in the
+    <A HREF="https://subversion.xor.aps.anl.gov/trac/EXPGUI/">
+EXPGUI Trac system</A>. In particular, see the
+    <A HREF="https://subversion.xor.aps.anl.gov/trac/EXPGUI/timeline">
+    timeline of changes</A> and the 
+   <A HREF="https://subversion.xor.aps.anl.gov/trac/EXPGUI/report">
+    reports on Tickets</A>. Any other information on this page is no
+longer being updated -- though there are still some good ideas for
+development here.
+</blockquote></blockquote></I>
+<P>
+<hr><hr>
+
+
 <P>
 This page describes recent features added to EXPGUI or that are being 
Index: /trunk/expgui
===================================================================
--- /trunk/expgui	(revision 1165)
+++ /trunk/expgui	(revision 1166)
@@ -327,4 +327,6 @@
 	    file copy -force $expgui(expfile) $expnam.EXP
 	    set expgui(expfile) $expnam.EXP
+	    wm title . "EXPGUI interface to GSAS: [file tail $expgui(expfile)]"
+	    set expgui(titleunchanged) 1
 	} else {
 	    MyMessageBox -parent . -title "File not found" \
@@ -334,5 +336,5 @@
 	}
     } else {
-	SetEXPfile $expgui(expfile)
+	set expgui(expfile) [SetEXPfile $expgui(expfile)]
     }
 }
@@ -349,5 +351,5 @@
     # I am not sure it is still needed.
     update
-    SetEXPfile [getExpFileName ""]
+    set expgui(expfile) [SetEXPfile [getExpFileName ""]]
     set expgui(resize) 1
 }
@@ -361,72 +363,15 @@
 proc loadexp {expfile} {
     global expgui expmap entryvar entrycmd tcl_platform
-    set prevexp $expgui(expfile)
-    # is this a compressed archive file? 
-    if {[string match {*.O[0-9A-F][0-9A-F]} $expfile]} {
-	set expnam [file rootname $expfile]
-	set ans [MyMessageBox -parent . -title "Load Archived File" \
-		-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?" \
-		-icon question -type "{Use New Name} {Continue with current}" \
-		-default {Use New Name} \
-		-helplink "expguierr.html LoadArchived"
-	]
-	# archive the current .EXP file
-	if {$ans != "use new name" && [file exists $expfile]} {
-	    # get the last archived version
-	    set lastf [lindex [lsort [glob -nocomplain $expnam.{O\[0-9A-F\]\[0-9A-F\]}]] end]
-	    if {$lastf == ""} {
-		set num 01
-	    } else {
-		regexp {.*\.O([0-9A-F][0-9A-F])$} $lastf a num
-		scan $num %x num
-		if {$num >= 255} {
-		    set num FF
-		} else {
-		    set num [string toupper [format %.2x [incr num]]]
-		}
-	    }
-	    catch {
-		set newfile $expnam.O$num
-		file rename -force $expnam.EXP $newfile
-		set fp [open $expnam.LST a+]
-		puts $fp "\n----------------------------------------------"
-		puts $fp "     Regressing to archive file [file tail $expfile]"
-		puts $fp "     but first archiving [file tail $expnam.EXP] as [file tail $newfile]"
-		puts $fp "----------------------------------------------\n"
-		close $fp
-	    }
-	    file copy -force $expfile $expnam.EXP
-	    set expfile $expnam.EXP
-	}
-	if {$ans == "use new name"} {
-	    set newexpfile [getExpFileName new]
-	    if {$newexpfile == ""} return 
-	    file copy -force $expfile $newexpfile
-	    catch {cd [string trim [file dirname $expgui(expfile)]]}
-	    set expfile [file tail $newexpfile]
-	    set expgui(needpowpref) 2
-	    set expgui(needpowpref_why) "\tA new .EXP file was created\n" 
-	    SetEXPfile $newexpfile
-	} else {
-	    SetEXPfile $expfile
-	}
-	if {$expgui(expfile) == ""} {
-	    set expgui(expfile) $prevexp
-	    return
-	}
-    }
-
+    set expfile [SetEXPfile $expfile]
+    if {$expfile == ""} {
+	return
+    }
     # change the icon and assign an app to this .EXP file
     if {$tcl_platform(os) == "Darwin" && $expgui(MacAssignApp)} {
 	MacSetResourceFork $expfile
     }
-
-    SetEXPfile $expfile
-    if {$expgui(expfile) == ""} {
-	set expgui(expfile) $prevexp
-	return
-    }
     # read in the .EXP file
     set fmt [expload $expfile]
+    set expgui(expfile) $expfile
     # if the file was not in the correct format, force a rewrite before use
     if {$fmt < 0} {
@@ -453,5 +398,5 @@
     set expgui(last_History) [string range [string trim [lindex [exphistory last] 1]] 0 50 ]
     # set the window/icon title
-    wm title . "EXPGUI interface to GSAS: $expfile"
+    wm title . "EXPGUI interface to GSAS: [file tail $expgui(expfile)]"
     set expgui(titleunchanged) 1
     wm iconname . [file tail $expfile]
@@ -462,4 +407,9 @@
     # start checking for external changes
     afterawhile
+    # check if the file seems corrupt
+    set warnings [ScanEXPforError]
+    if {$warnings != ""} {
+	ExplainEXPerror . $warnings $expfile
+    }
 }
 
@@ -547,13 +497,8 @@
     global expgui
     global tcl_platform
-    set prevexp $expgui(expfile) 
-    set newexpfile [getExpFileName new]
-    if {$newexpfile == ""} return 
-    SetEXPfile $newexpfile 1
-    if {$expgui(expfile) == ""} {
-	set expgui(expfile) $prevexp
-	return
-    }
+    set newexpfile [SetEXPfile [getExpFileName new] 1]
+    if {$newexpfile == ""} return
     expwrite $newexpfile
+    set expgui(expfile) $newexpfile
     # change the icon and assign an app to this .EXP file
     if {$tcl_platform(os) == "Darwin" && $expgui(MacAssignApp)} {
@@ -574,5 +519,5 @@
 
 # called to read a different .EXP file
-proc readnewexp {} {
+proc readnewexp {"mode 0"} {
     global expgui expmap
     if $expgui(changed) {
@@ -586,17 +531,17 @@
 	}
     }
-    set prevexp $expgui(expfile) 
-    set newexpfile [getExpFileName old]
-    if {$newexpfile == ""} return 
-    SetEXPfile $newexpfile
-    if {$expgui(expfile) == ""} {
-	set expgui(expfile) $prevexp
-	return
-    }
-
-    # switch to the 1st page
-    RaisePage lsFrame
+    if {$mode == 0} {
+	set newexpfile [getExpFileName old]
+    } else {
+	set newexpfile [RevertExpFile]
+    }
+    if {$newexpfile == ""} return
+
     set expgui(globalmode) 0
-    loadexp $expgui(expfile)
+    loadexp $newexpfile
+
+    # switch to the appropriate 1st page
+    #StageTabUse
+    SetStartPanel
 
     # reset the phase selection
@@ -609,7 +554,7 @@
 	set expgui(curhist) {}
     }
-    if {[CountHistory] > 100} {
-	DeleteHistoryRecords "This .EXP file has [CountHistory] history records\nErasing most will speed EXPGUI"
-    }
+#    if {[CountHistory] > 100} {
+#	DeleteHistoryRecords "This .EXP file has [CountHistory] history records\nErasing most will speed EXPGUI"
+#    }
 }
 
@@ -1058,5 +1003,5 @@
 
     set crsPhase {}
-    $expgui(atomxform) config -text "Xform Atoms" -state disabled
+    $expgui(atomxform) config -text "Modify Atoms" -state disabled
     foreach n $expmap(phaselist) type $expmap(phasetype) {
 	if {$n == $num} {
@@ -1099,9 +1044,13 @@
 	DisplayRefFlags 0 0
 	$expgui(atomlistbox) delete 0 end
+	$expgui(AddAtomBut)  config -state disabled
 	return
     }
 
     # don't reload the last displayed phase
-    if {$expgui(curPhase) == $crsPhase} return
+    if {$expgui(curPhase) == $crsPhase} {
+       DisplayAllAtoms $crsPhase
+       return
+    }
 
     ##########################################################
@@ -1127,4 +1076,5 @@
     DisplayRefFlags 0 0
     $expgui(EditingAtoms) config -text ""
+    $expgui(AddAtomBut)  config -state normal
 
     DisplayAllAtoms $crsPhase
@@ -1308,5 +1258,5 @@
 	    } else {
 		append refflag " [mmatominfo $phase $atom ${type}damp] "
-	    }   
+	    }
 	}
 	set line [format \
@@ -1323,5 +1273,5 @@
 		[mmatominfo $phase $atom z] \
 		[mmatominfo $phase $atom frac] \
-		[mmatominfo $phase $atom Uiso] 
+		[mmatominfo $phase $atom Uiso]
 	]
     } elseif {[atominfo $phase $atom temptype] == "A"} {
@@ -1337,14 +1287,15 @@
 	set maxline A
 	# aniso
-	set line [format "%3d %-6s %-6s %8s %10.6f%10.6f%10.6f%4d%9.4f" \
+        set fmt "%3d %-6s %-6s %8s %s%s%s%4d%9.4f"
+	set line [format $fmt \
 		$atom \
 		[atominfo $phase $atom label] \
 		[atominfo $phase $atom type] \
 		$refflag \
-		[atominfo $phase $atom x] \
-		[atominfo $phase $atom y] \
-		[atominfo $phase $atom z] \
+		[ShowFixAtom $phase $atom x] \
+		[ShowFixAtom $phase $atom y] \
+		[ShowFixAtom $phase $atom z] \
 		[atominfo $phase $atom mult] \
-		[atominfo $phase $atom frac] 
+		[atominfo $phase $atom frac]
 	]
 	append line [format "  %9.5f%9.5f%9.5f%9.5f%9.5f%9.5f" \
@@ -1354,5 +1305,5 @@
 		[atominfo $phase $atom U12] \
 		[atominfo $phase $atom U23] \
-		[atominfo $phase $atom U13] 
+		[atominfo $phase $atom U13]
 	]
     } else {
@@ -1362,21 +1313,33 @@
 	    } else {
 		append refflag " [atominfo $phase $atom ${type}damp] "
-	    }   
-	}
-	set line [format \
-		"%3d %-6s %-6s %8s %10.6f%10.6f%10.6f%4d%9.4f  %9.5f" \
+	    }
+	}
+	#set fmt "%3d %-6s %-6s %8s %10.6f%10.6f%10.6f%4d%9.4f  %9.5f"
+	set fmt "%3d %-6s %-6s %8s %s%s%s%4d%9.4f  %9.5f"
+	set line [format $fmt \
 		$atom \
 		[atominfo $phase $atom label] \
 		[atominfo $phase $atom type] \
 		$refflag \
-		[atominfo $phase $atom x] \
-		[atominfo $phase $atom y] \
-		[atominfo $phase $atom z] \
+		[ShowFixAtom $phase $atom x] \
+		[ShowFixAtom $phase $atom y] \
+		[ShowFixAtom $phase $atom z] \
 		[atominfo $phase $atom mult] \
 		[atominfo $phase $atom frac] \
-		[atominfo $phase $atom Uiso] 
+		[atominfo $phase $atom Uiso]
 	]
     }
     return $line
+}
+
+# format a coordinate from a non-mm phase as 10 chars; mark fixed coordinates differently
+proc ShowFixAtom {phase atom var} {
+  # is this fixed?
+  set param [string toupper $var]
+  if {[array name ::fix_param "$phase,$atom,$param"] != ""} {
+    return [format "%9.5fF" [atominfo $phase $atom $var]]
+  } else {
+    return [format "%10.6f" [atominfo $phase $atom $var]]
+  }
 }
 
@@ -1442,5 +1405,5 @@
     DisplayRefFlags $atomnum $p
     $expgui(EditingAtoms) config -text "Editing atom #$atomnum -- [atominfo $p $atomnum label]"
-    $expgui(atomxform) config -text "Xform Atom" -state normal
+    $expgui(atomxform) config -text "Modify Atom" -state normal
 }
 
@@ -1467,5 +1430,5 @@
     # this needs to track by phase
     DisplayRefFlags $numberList $p
-    $expgui(atomxform) config -text "Xform Atoms" -state normal
+    $expgui(atomxform) config -text "Modify Atoms" -state normal
 }
 
@@ -1849,4 +1812,5 @@
 	set expgui(backtermlbl) ""
 	set expgui(backtypelbl) ""
+        set expgui(abstypelbl) "" 
 	foreach var {bref bdamp absref absdamp} {
 	    set entrycmd($var) ""
@@ -1865,5 +1829,5 @@
 	set expgui(backtermlbl) ""
 	set expgui(backtypelbl) ""
-	set expgui(abstypelbl) ""
+        set expgui(abstypelbl) "" 
 	foreach var {bref bdamp absref absdamp} {
 	    set entrycmd($var) "histinfo [list $histlist] $var"
@@ -3349,5 +3313,5 @@
 	    {SelectOnePhase $expgui(curPhase)} \
 	    0  expgui2.html ""}
-    {histFrame    Histogram \
+    {histFrame    Powder \
 	    MakeHistPane \
 	    DisplayHistogram \
@@ -3365,4 +3329,8 @@
 	    DisplayConstraintsPane \
 	    0  expgui6.html ""}
+    {rbFrame   "Rigid Body" \
+	    "source  [file join $expgui(scriptdir) rigid.tcl]; MakeRBPane" \
+	    DisplayRB \
+	    1  expguiRB.html ""}
     {orientFrame  "MD Pref Orient" \
 	    MakeOrientPane \
@@ -3374,4 +3342,15 @@
 	    0  expgui7.html ODF}
 }
+
+# future expansion: single crystal panel goes here -- if present
+catch {
+   source  [file join $expgui(scriptdir) single.tcl]
+   set expgui(notebookpagelist) [linsert $expgui(notebookpagelist) 3 \
+       {singFrame   Single \
+       "MakeSinglePane" \
+       DisplaySingle \
+       1  expguiSing.html ""}]
+} err
+
 
 pack [NoteBook .n -bd 2] -expand yes -fill both
@@ -3396,7 +3375,10 @@
     }
 }
+
+set expgui(startpanel) 2
 # procedure to disable tabs when phases or histograms are not defined
 proc StageTabUse {args} {
     global expgui
+    set expgui(startpanel) 2
     # reset everything
     foreach item [lrange $::expgui(notebookpagelist) 0 end] {
@@ -3423,4 +3405,5 @@
 	    .n itemconfigure $frm -state disabled
 	}
+	set expgui(startpanel) 0
 	return
     }
@@ -3441,4 +3424,5 @@
 	    .n itemconfigure $frm -state disabled
 	}
+	set expgui(startpanel) 0
 	return
     }
@@ -3450,4 +3434,5 @@
 	    .n itemconfigure $frm -state disabled
 	}
+	set expgui(startpanel) 1
 	return
     }
@@ -3463,4 +3448,15 @@
     .n see $nextpage
     .n raise $nextpage
+}
+
+proc SetStartPanel {} {
+    global expgui
+    if {$expgui(startpanel) == 0} {
+	RaisePage phaseFrame
+    } elseif {$expgui(startpanel) == 1} {
+	RaisePage histFrame
+    } else {
+	RaisePage lsFrame
+    }
 }
 
@@ -4307,6 +4303,13 @@
     $expgui(fm).option.menu  add checkbutton -label "Prompt after GSAS run" \
 	    -variable expgui(execprompt)
-    $expgui(fm).option.menu  add checkbutton -label "Iconify during GSAS" \
+    if {$tcl_platform(platform) == "windows" && \
+	    $tcl_platform(osVersion) == 6.1} {
+        set expgui(autoiconify) 0
+        $expgui(fm).option.menu  add checkbutton -label "Iconify during GSAS" \
+	    -variable expgui(autoiconify) -state disabled
+    } else {
+        $expgui(fm).option.menu  add checkbutton -label "Iconify during GSAS" \
 	    -variable expgui(autoiconify)
+    }
     if {$tcl_platform(platform) == "windows" && \
 	    $tcl_platform(os) == "Windows 95"} {
@@ -4453,4 +4456,5 @@
     }
 }
+$expgui(fm).powder.menu add command -label "New InstParm file" -command {EditInstFile (new)}
 
 # Macro menu
@@ -4555,6 +4559,6 @@
 LocateWindow "." $xpos $ypos $poscntr
 update
-RaisePage lsFrame
-if {[CountHistory] > 200} {
-    DeleteHistoryRecords "This .EXP file has [CountHistory] history records\nErasing most will speed EXPGUI"
-}
+SetStartPanel
+#if {[CountHistory] > 200} {
+#    DeleteHistoryRecords "This .EXP file has [CountHistory] history records\nErasing most will speed EXPGUI"
+#}
Index: /trunk/gnuplot.tcl
===================================================================
--- /trunk/gnuplot.tcl	(revision 1166)
+++ /trunk/gnuplot.tcl	(revision 1166)
@@ -0,0 +1,244 @@
+proc Graph2CSV {graph_name csvname  {initialComment 1}} {
+    if { [catch {set fp [open $csvname w]}] } {
+	if { [file isfile $csvname] } {
+	    MyMessageBox -parent . -title "Cannot write to file" \
+		-message  "Write access to $csvname is denied.  File may be opened by another program, or directory may be write protected.  Try closing programs, or changing your current working directory" \
+	    -type OK -default ok
+	} else {
+	    MyMessageBox -parent . -title "No write access" \
+		-message "This directory does not have write access, you much change your current working directory" \
+		-type OK -default ok
+	}
+	return 1
+    }
+    set commas {}
+    set element_list [$graph_name element show] 
+
+    set heading "" 
+    set num 0
+    catch {unset data_list}
+    set max 0
+    foreach element_name $element_list {
+        set element_cmd "$graph_name element cget $element_name"
+        # get xy data for this element
+        set data_list($num) [eval $element_cmd -data]
+        #if there is no data, skip this set
+        set pts [llength $data_list($num)]
+        if {$pts > $max} {set max $pts}
+        if {[llength $data_list($num)] == 0} continue
+        incr num
+	if {$heading != ""} {append heading ","}
+	append heading  [$graph_name axis cget x -title]
+	append heading ","
+	append heading $element_name
+    }
+    #For Gnuplot exports, the column labels need to be commented out
+    if {$initialComment} {
+	puts $fp "#$heading"
+    } else {
+	puts $fp $heading
+    }
+    for {set i 0} {$i < $max} {incr i 2} {
+        set line ""
+        for {set n 0} {$n < $num} {incr n} {
+        # get xy data for this element
+            foreach {x y} [lrange $data_list($n) $i [expr {$i + 1}]] {}
+            append line "$x,$y,"
+        }
+        puts $fp $line
+    }
+    close $fp
+    return 0
+}
+
+proc Graph2Gnuplot {graph_name gplotname psname csvname "legendplace 1"} {
+    if {[Graph2CSV $graph_name $csvname]} {return 1}
+    if { [catch {set gplotfp [open $gplotname w]}] } {
+	MyMessageBox -parent . -title "Cannot write to file" \
+	    -message  "Write access to $gplotname is denied.  File may be opened by another program, or directory may be write protected.  Try closing programs, or changing your current working directory" \
+	    -type OK -default ok
+	return 1
+    }
+    puts $gplotfp "set datafile separator \",\"\n"
+    puts $gplotfp "set terminal postscript"
+    puts $gplotfp "set output \"$psname\""
+    
+    # use the title font size throughout
+    set fontsize [lindex [$graph_name cget -font] 1]
+    if {$fontsize != ""} {
+        if {$fontsize < 0} {
+            set fontsize ",[expr {-$fontsize}] "
+        } else {
+            set fontsize ",$fontsize "
+        }
+    }
+
+    if {$::tcl_platform(platform) != "windows"} { 
+	set font "\"Helvetica$fontsize\""
+    } else { 
+	set font "font \"Arial$fontsize\"" 
+    }
+    puts $gplotfp "set term postscript landscape color solid $font size 10.5in,7.5in enhanced\n"
+    puts $gplotfp "set xtics border out \nset ytics border out"
+    puts $gplotfp "set mxtics 5\nset mytics 5\n"
+    
+    #turns out that an opaque key is brand new in the gnuplot dev version 4.5.  This is what Windows ships with, but for now, unix systems will have to do without.  Too bad
+    if {$::tcl_platform(platform) == "windows"} { puts $gplotfp "set key opaque" }
+    if {$legendplace == 0 } { puts $gplotfp "set key out" }
+    if {[$graph_name legend cget -hide]} {puts $gplotfp "set key off\n" }
+
+    set title [$graph_name cget -title]
+    if { $title != "" } {
+	regsub -all "\"" $title "\\\"" thetitle
+	puts $gplotfp "set title \"$thetitle\""
+    }
+	
+    set xlab [$graph_name axis cget x -title]
+    if {[string match -nocase $xlab "2theta"]} {set xlab "2{/Symbol q}"}
+    puts $gplotfp "\nset xlabel \"$xlab\""
+    puts $gplotfp "set ylabel \"[$graph_name axis cget y -title]\""
+	
+    puts $gplotfp "\nset origin -0.05,0.025"
+
+    foreach {xmin xmax} [$graph_name xaxis limits] {}
+    foreach {ymin ymax} [$graph_name yaxis limits] {}
+    puts $gplotfp "set xrange \[ ${xmin}:${xmax} \]"
+	
+    set yoff [expr ($ymax-$ymin)*0.02]
+    set yminauto [expr $ymin-$yoff]
+    set ymaxauto [expr $ymax+$yoff]
+	
+    set line "set yrange \[";
+    if {[$graph_name yaxis cget -min] == "" } { 
+	append line "$yminauto:" 
+    } else { 
+	append line "$ymin:" 
+    }
+    if {[$graph_name yaxis cget -max] == "" } { 
+	append line "$ymaxauto\]\n" 
+    } else { 
+	append line "$ymax\]\n" 
+    }	
+    puts $gplotfp $line
+
+    puts $gplotfp "set style line 1 lt 1 lw 2" 
+    # it would be nice to control this for each figure
+    puts $gplotfp "set pointsize 1.75" 
+
+    set plotline "plot "
+    set i 0
+    set element_list [$graph_name element show]
+
+    set heading "" 
+    foreach element_name $element_list {
+        set element_cmd "$graph_name element cget $element_name"
+        #if there is no data, skip this set
+        if {[llength [eval $element_cmd -data]] == 0} continue
+        if {$plotline != "plot "} { append plotline "\\\n   , " }
+
+	# get line info from plot -- not currently used
+	set lw [eval $element_cmd -linewidth]
+	set symbol  [eval $element_cmd -symbol]
+	set size  [eval $element_cmd -pixels]
+	set dash  [eval $element_cmd -dashes]
+	#puts "$element_name $symbol"
+	if {$lw >= 1 && $symbol == "none"} {
+	    append plotline "\"$csvname\" using [expr 2*$i+1]:[expr 2*$i+2] with lines ls 1 lc rgbcolor "
+	} elseif {$lw >= 1 && $symbol != "none"}  {
+	    # don't know how to control symbol type or size line by line
+	    append plotline "\"$csvname\" using [expr 2*$i+1]:[expr 2*$i+2] with linespoints ls 1 lc rgbcolor "
+	} else {
+	    append plotline "\"$csvname\" using [expr 2*$i+1]:[expr 2*$i+2] with points ls 1 lc rgbcolor "	}
+	# get color
+	set linecolor [eval $element_cmd -color]
+	# convert 16 bit color to 3x8 bit digit RGB value
+	set str "#"
+	foreach rgb [winfo rgb . $linecolor] {
+	    append str [format "%02X" [expr {$rgb / 256}]]
+	}
+	append plotline {"} $str {"}
+
+	append plotline " title \""
+	set plotlbl [eval $element_cmd -label]
+	#if {$plotlbl == ""} {set plotlbl $element_name}
+	regsub -all "\"" [string trim $plotlbl] "\\\"" thetitle
+	append plotline $thetitle;
+	append plotline "\""
+	incr i
+    }
+
+    # loop over markers
+    foreach mrk [$graph_name marker names] {
+	set type [$graph_name marker type $mrk]
+	if {$type == "TextMarker"} {
+	    set txt [$graph_name marker cget $mrk -text]
+	    set angle [$graph_name marker cget $mrk -rotate]
+	    set coords [$graph_name marker cget $mrk -coords]
+	    set justify [$graph_name marker cget $mrk -justify]
+	    set anchor [$graph_name marker cget $mrk -anchor]
+	    set color [$graph_name marker cget $mrk -foreground]
+	    # convert 16 bit color to 3x8 bit digit RGB value
+	    set str "#"
+	    foreach rgb [winfo rgb . $color] {
+		append str [format "%02X" [expr {$rgb / 256}]]
+	    }
+	    # deal with text placement -- anchor/justify not quite mapped
+	    set place "left"
+	    if {$anchor == "center"} {
+                set place "center"
+            } elseif {[string first "w" $anchor]} {
+                set place "right"
+            }
+
+	    # text rotation
+	    set rot {}
+	    if {$angle != 0.0 && $angle != ""} {
+		set rot "rotate by $angle" 
+	    }
+	    # text location
+	    foreach val $coords var {x1 y1} \
+		min [list $xmin $ymin] max [list $xmax $ymax] {
+		    if {$val == "+Inf"} {
+			set $var $max
+		    } elseif {$val == "-Inf"} {
+			set $var $min
+		    } else {
+			set $var $val
+		    }
+		}
+            if {$x1 < $xmin || $x1 > $xmax} {continue}
+	    # replace newlines
+	    regsub -all "\n" $txt {\n} txt
+	    puts $gplotfp "set label \"$txt\" at first $x1,$y1 tc rgbcolor \"$str\" $place $rot" 
+	} elseif {$type == "LineMarker"} {
+	    set coords [$graph_name marker cget $mrk -coords]
+	    #set lw [$graph_name marker cget $mrk -linewidth]
+	    #set dashes [$graph_name marker cget $mrk -dashes]
+	    set linecolor [$graph_name marker cget $mrk -outline]
+	    # convert 16 bit color to 3x8 bit digit RGB value
+	    set str "#"
+	    foreach rgb [winfo rgb . $linecolor] {
+		append str [format "%02X" [expr {$rgb / 256}]]
+	    }
+	    foreach val $coords var {x1 y1 x2 y2} \
+		min [list $xmin $ymin $xmin $ymin] max [list $xmax $ymax $xmax $ymax] {
+		    if {$val == "+Inf"} {
+			set $var $max
+		    } elseif {$val == "-Inf"} {
+			set $var $min
+		    } else {
+			set $var $val
+		    }
+		}
+            if {$x1 < $xmin || $x2 > $xmax} {continue}
+	    puts $gplotfp "set arrow from first $x1,$y1 to first $x2,$y2 nohead lc rgbcolor \"$str\"" 
+	} else {
+	    puts "unable to process marker $mrk of type $type"
+	}
+    }
+    # last item, do plot command
+    puts $gplotfp $plotline
+    close $gplotfp
+    return 0
+}
+set gnuplotexport "loaded"
Index: /trunk/graceexport.tcl
===================================================================
--- /trunk/graceexport.tcl	(revision 1165)
+++ /trunk/graceexport.tcl	(revision 1166)
@@ -241,8 +241,8 @@
 		set center 10
 	    } elseif {[string range $just 0 0] == "e"} {
-		# is this correct?
+		# is this correct? 
+		set center 1
+	    } else {
 		set center 0
-	    } else {
-		set center 1
 	    }
 	    set color_data 1
Index: /trunk/gsascmds.tcl
===================================================================
--- /trunk/gsascmds.tcl	(revision 1165)
+++ /trunk/gsascmds.tcl	(revision 1166)
@@ -464,4 +464,56 @@
     afterputontop
     return $makenew(result)
+}
+
+# format numbers & errors in crystallographic notation
+proc formatSU {num err} {
+    # errors less or equal to t are expressed as 2 digits
+    set T 19
+    set lnT [expr { log10($T) }]  
+    # error is zero
+    if {$err == 0} {
+	# is this an integer?
+	if {int($num) == $num} {
+	    return [format %d [expr int($num)]]
+	}
+	# allow six sig figs with a zero error (except for 0.0)
+	set dec [expr int(5.999999-log10( abs($num) ))]
+	if {$dec < -2 || $dec > 9} {
+	    return [format %.5E $num]
+	} elseif {$dec <= 0} {
+	    return [format %d [expr int($num)]]
+	} else {
+	    return [format %.${dec}f $num]
+	}
+    } else {
+	#set sigfigs [expr log10( abs(10) / abs(.012/$T) ) + 1]
+	# should the number be expressed in scientific notation?
+	if {$err > $T || abs($num) < 0.0001} {
+	    # get the exponent
+	    set exp [lindex [split [format %E $num] E] end]
+	    # strip leading zeros
+	    regsub {([-\+])0+} $exp {\1} exp
+	    # number of decimals in exponetial notation
+	    set dec [expr int($lnT - log10( abs($err) ) + $exp)]
+	    # should the error be displayed?
+	    if {$err < 0} {
+		return [format "%.${dec}E" $num]
+	    } else {
+		# scale the error into a decimal number
+		set serr [expr int(0.5 + $err * pow(10,$dec-$exp))]
+		return [format "%.${dec}E(%d)" $num $serr]
+	    }
+	} else {
+	    # number of digits
+	    set dec [expr int($lnT - log10( abs($err) ))]
+	    # should the error be displayed?
+	    if {$err < 0} {
+		return [format "%.${dec}f" $num]
+	    } else {
+		set serr [expr int(0.5 + $err * pow(10,$dec))]
+		return [format "%.${dec}f(%d)" $num $serr]
+	    }
+	}
+    }
 }
 
@@ -974,10 +1026,10 @@
 	    }
 	}
-	# so sorry, have to use Internet Explorer
+	# so sorry, have to use Safari, even if not default
 	set url [file nativename $url]; # replace ~/ if present
 	if {[file pathtype $url] == "relative"} {
 	    set url [file join [pwd] $url]
 	}
-	exec osascript -e "tell application \"Internet Explorer\"\rGetURL \"file://$url\"\rend tell"
+	exec osascript -e "tell application \"Safari\" to open location \"file://$url\""
     } elseif {$tcl_platform(platform) == "unix"} {
 	set browserlist {}
@@ -1959,5 +2011,4 @@
 proc SetEXPfile {expfile "newOK 0"} {
     global expgui tcl_platform
-    set expgui(expfile) {}
     if {[string trim $expfile] == ""} return
 
@@ -2015,12 +2066,16 @@
     # force exp files to be upper case, set to force save if name changes
     set origexp $expname
-    if {$expname != [string toupper $expfile]} {
-	set expname [string toupper [file tail $expfile]]
-	if {$tcl_platform(platform) != "windows"} {set expgui(changed) 1}
-    }
-    if {[file extension $expname] != ".EXP"} {
+    if {$expname != [file tail $expfile] && $tcl_platform(platform) != "windows"} {
+	set expgui(changed) 1
+    }
+    #puts $expgui(expfile)
+    if {[string match {.O[0-9A-F][0-9A-F]} [file extension $expname]]} {
+	set expname [ArchiveChoice $expname]
+	set dirname ""
+	if {$expname == ""} return
+    } elseif {[file extension $expname] != ".EXP"} {
 	append expname ".EXP"
     }
-    if {$dirname == "."} {
+    if {$dirname == "." || $dirname == ""} {
 	set newexpfile $expname
     } else {
@@ -2081,21 +2136,78 @@
 	if {[string tolower $ans] == "create"} {
 	    # you've been warned this .EXP does not exist!
-	    # create an "empty" exp file
-	    createexp $newexpfile \
-		[getstring "title for experiment $expname" 60 0]
-	    if {! [file exists [file join $dirname $expname]]} {
-		update
-		MyMessageBox -parent . -title "File Creation Error" \
-		    -message "Experiment file name \"$expname\" was not created -- This is unexpected, please try a different name" \
-		    -icon warning -type Continue -default continue
-		set expgui(resize) 1
-		return
-	    }
+	    if [CreateMTexpfile $newexpfile] return
 	} else {
 	    return
 	}
     }
-    set expgui(expfile) $newexpfile
-    catch {cd [string trim [file dirname $expgui(expfile)]]}
+    catch {cd [string trim [file dirname $newexpfile]]}
+    return $newexpfile
+}
+
+proc ArchiveChoice {expfile} {
+    set expnam [file rootname $expfile]
+    set ans [MyMessageBox -parent . -title "Load Archived File" \
+	-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?" \
+	-icon question -type "{Use New Name} {Continue with current}" \
+	-default {Use New Name} \
+	-helplink "expguierr.html LoadArchived"
+    ]
+    # archive the current .EXP file
+    if {$ans != "use new name" && [file exists $expfile]} {
+	# get the last archived version
+	set lastf [lindex [lsort [glob -nocomplain $expnam.{O\[0-9A-F\]\[0-9A-F\]}]] end]
+	if {$lastf == ""} {
+	    set num 01
+	} else {
+	    regexp {.*\.O([0-9A-F][0-9A-F])$} $lastf a num
+	    scan $num %x num
+	    if {$num >= 255} {
+		set num FF
+	    } else {
+		set num [string toupper [format %.2x [incr num]]]
+	    }
+	}
+	catch {
+	    set newfile $expnam.O$num
+	    file rename -force $expnam.EXP $newfile
+	    set fp [open $expnam.LST a+]
+	    puts $fp "\n----------------------------------------------"
+	    puts $fp "     Regressing to archive file [file tail $expfile]"
+	    puts $fp "     but first archiving [file tail $expnam.EXP] as [file tail $newfile]"
+	    puts $fp "----------------------------------------------\n"
+	    close $fp
+	}
+	file copy -force $expfile $expnam.EXP
+	set expfile $expnam.EXP
+    }
+    if {$ans == "use new name"} {
+	set newexpfile [getExpFileName new]
+	if {$newexpfile == ""} {
+	    set expgui(FileMenuEXPNAM) ""
+	    return 
+	}
+	file copy -force $expfile $newexpfile
+	set expgui(needpowpref) 2
+	set expgui(needpowpref_why) "\tA new .EXP file was created\n" 
+	return $newexpfile
+    } else {
+	return $expfile
+    }
+}
+
+# create an "empty" exp file
+proc CreateMTexpfile {newexpfile} {
+    set expname [file tail $newexpfile]
+    createexp $newexpfile \
+	[getstring "title for experiment $expname" 60 0]
+    if {! [file exists $newexpfile]} {
+	update
+	MyMessageBox -parent . -title "File Creation Error" \
+	    -message "Experiment file name \"$expname\" was not created -- This is unexpected, please try a different name" \
+	    -icon warning -type Continue -default continue
+	set ::expgui(resize) 1
+	return 1
+    }
+    return 0
 }
 
@@ -2129,5 +2241,5 @@
 		-side top -fill both -expand yes -pady 5
     } elseif {$mode != "new"} {
-	# for initial read, don't access archived files
+	# for initial read, don't offer access to archived files
 	pack [frame $expgui(FileInfoBox) -bd 4 -relief groove \
 		-class SmallFont] \
@@ -2158,29 +2270,10 @@
     afterputontop
     if {$expgui(FileMenuEXPNAM) == ""} return
-    # is there a space in the EXP name?
-#    if {[string first " " [file tail $expgui(FileMenuEXPNAM)]] != -1} {
-#	update
-#	MyMessageBox -parent . -title "File Name Error" \
-#	    -message "File name \"$expgui(FileMenuEXPNAM)\" is invalid -- EXPGUI can#not process experiment files with spaces in the name" \
-#	    -icon warning -type Continue -default continue
-#		-helplink "expguierr.html OpenErr"
-#	return
-#    }
-#    if {[string first " " $expgui(FileMenuDir)] != -1} {
-#	set warn 1
-#	catch {set warn $expgui(warnonexpdirspace)}
-#	if $warn {
-#	    update
-#	    MyMessageBox -parent . -title "Good luck..." \
-#		-message "You are using a directory with a space in the name ($expgui(FileMenuDir)) -- You may encounter bugs in EXPGUI. Please e-mail them to Brian.Toby@ANL.gov so they can be fixed." \
-#		-icon warning -type Continue -default continue
-#	    #		-helplink "expguierr.html OpenErr"
-#	    set expgui(warnonexpdirspace) 0
-#	}
-#    }
+    #puts "end getexp $expgui(expfile)"
     return [file join $expgui(FileMenuDir) $expgui(FileMenuEXPNAM)]
 }
 
 # validation routine
+# called from getExpFileName, either from Read button or from SelectExpFil (see expfilebox)
 proc valid_exp_file {frm mode} {
     global expgui tcl_platform
@@ -2208,22 +2301,14 @@
 	return
     }
-    # append a .EXP if not present
-    if {[file extension $expgui(FileMenuEXPNAM)] == ""} {
+    set ext [string toupper [file extension $expgui(FileMenuEXPNAM)]]
+    if {$ext == ""} {
+	# append a .EXP if not present
 	append expgui(FileMenuEXPNAM) ".EXP"
-    }
-    # is there a space in the name?
-#    if {[string first " " $expgui(FileMenuEXPNAM)] != -1} {
-#	MyMessageBox -parent . -title "File Name Error" \
-#		-message "File name $expgui(FileMenuEXPNAM) is invalid -- EXPGUI cannot process experiment files with spaces in the name" \
-#		-icon warning -type Continue -default continue
-#		-helplink "expguierr.html OpenErr"
-#	return
-#    }
-    # check for archive files
-    if {[string match {*.O[0-9A-F][0-9A-F]} $expgui(FileMenuEXPNAM)] && \
+    } elseif {[string match {*.O[0-9A-F][0-9A-F]} $ext] && \
 	    $mode == "old" && [file exists $expgui(FileMenuEXPNAM)]} {
+	# check for archive files
 	destroy .file
 	return
-    } elseif {[string toupper [file extension $expgui(FileMenuEXPNAM)]] != ".EXP"} {
+    } elseif {$ext != ".EXP"} {
 	# check for files that end in something other than .EXP .exp or .Exp...
 	MyMessageBox -parent . -title "File Open Error" \
@@ -2258,5 +2343,8 @@
 		-helplink "expguierr.html OpenErr"
 	]
-	if {[string tolower $ans] == "create"} {destroy .file}
+	if {[string tolower $ans] == "create"} {
+	    if [CreateMTexpfile $file] return
+	    destroy .file
+	}
 	return
     }
@@ -2417,5 +2505,71 @@
 	    - [winfo height $box.top] - [winfo height $box.scroll]-25]
 }
-
+proc RevertExpFile {} {
+    global expgui tcl_platform
+    set frm .file
+    catch {destroy $frm}
+    toplevel $frm
+    wm title $frm "Experiment file"
+    bind $frm <Key-F1> "MakeWWWHelp expguierr.html open"
+    pack [frame [set frmA $frm.1] -bd 2 -relief groove] -padx 3 -pady 3 -side left
+    pack [frame [set frmC $frm.3] ] -padx 3 -pady 3 -side left \
+	    -fill y -expand yes
+    pack [button $frmC.help -text Help -bg yellow \
+	    -command "MakeWWWHelp expguierr.html open"] \
+	    -side top -anchor e
+    set expgui(filesort) 0
+    set expgui(includearchived) 1
+    set expgui(FileInfoBox) $frmC.info
+    pack [label $frmC.ar -text "(Showing Archived Files Only)"] -side top -pady 10
+    pack [frame $expgui(FileInfoBox) -bd 4 -relief groove \
+	      -class SmallFont] \
+	-side top -fill both -expand yes -pady 5
+
+    pack [button $frmC.b -text Read \
+	    -command "valid_exp_file $frmA old"] -side bottom
+    pack [button $frmC.q -text Cancel \
+	    -command "set expgui(FileMenuEXPNAM) {}; destroy $frm"] -side bottom
+    bind $frm <Return> "$frmC.b invoke"
+
+    pack [label $frmA.0 -text "Select an archived experiment file to read"] \
+		-side top -anchor center
+    set bx $frmA 
+    pack [frame $bx.top] -side top 
+    #pack [label $bx.top.a -text "Directory" ] -side left 
+    set expgui(FileDirButtonMenu) [tk_optionMenu $bx.top.d expgui(FileMenuDir) [pwd] ]
+    #pack $bx.top.d -side left
+    #set expgui(FileMenuDir) [pwd]
+    # the icon below is from tk8.0/tkfbox.tcl
+    pack [frame $bx.a -width 200 -height 75] -side top -expand yes -fill both
+    listbox $bx.a.files -relief raised -bd 2 \
+	    -yscrollcommand "sync2boxesY $bx.a.files $bx.a.dates $bx.a.scroll" \
+	    -height 15 -width 0 -exportselection 0 
+    listbox $bx.a.dates -relief raised -bd 2 \
+	    -yscrollcommand "sync2boxesY $bx.a.dates $bx.a.files $bx.a.scroll" \
+	    -height 15 -width 0 -takefocus 0 -exportselection 0 
+    scrollbar $bx.a.scroll -command "move2boxesY \" $bx.a.files $bx.a.dates \" "
+    ChooseExpFil $bx 1
+    if {[llength [$bx.a.files get 0 end]] == 0} {
+	destroy $frm
+	MyMessageBox -parent . -title "No Archives" \
+	    -message "Sorry no archived versions of $::expgui(expfile) are present" \
+		    -icon warning -type ok -default ok
+	return
+    }
+    bind $bx.a.files <ButtonRelease-1> "ReleaseExpFil $bx"
+    bind $bx.a.dates <ButtonRelease-1> "ReleaseExpFil $bx"
+    bind $bx.a.files <Double-1> "SelectExpFil $bx old"
+    bind $bx.a.dates <Double-1> "SelectExpFil $bx old"
+    pack $bx.a.scroll -side left -fill y 
+    pack $bx.a.files $bx.a.dates -side left -fill both -expand yes
+    pack [entry $bx.c -textvariable expgui(FileMenuEXPNAM)] -side top
+    # force the window to stay on top
+    putontop $frm
+    focus $frmC.b
+    tkwait window $frm
+    afterputontop
+    if {$expgui(FileMenuEXPNAM) == ""} return
+    return [file join $expgui(FileMenuDir) $expgui(FileMenuEXPNAM)]
+}
 
 # support routine for SetHistUseFlags
@@ -2542,4 +2696,145 @@
     return
 }
+
+proc ScanEXPforError {"ns {}"} {
+    # record types to ignore
+    set ignorelist {DESCR HSTRY PNAM HNAM "REFN STATS"}
+    set warn {}
+    set badkeylist {}
+    # scan file for warnings
+    foreach key [array names ${ns}::exparray] {
+	if {[string first "***" [set ${ns}::exparray($key)]] != -1 || 
+	    [string first "#IN" [set ${ns}::exparray($key)]] != -1 ||
+	    [string first "nan" [set ${ns}::exparray($key)]] != -1 ||
+	    [string first "NAN" [set ${ns}::exparray($key)]] != -1 
+	} {
+	    #puts [set ${ns}::exparray($key)]
+	    set OK 0
+	    foreach i $ignorelist {
+		if {[string first $i $key] != -1} {
+		    set OK 1
+		    break
+		}
+	    }
+	    # ignore atom name section of Atom records
+	    if {(! $OK) && [string match  "CRS*AT*A" $key]} {
+		foreach str [list [string range [set ${ns}::exparray($key)] 0 49] 
+			     [string range [set ${ns}::exparray($key)] 58 end]] {
+		    if {[string first "***" $str] || 
+			[string first "#INF" $str] || 
+			[string first "nan" $str] || 
+			[string first "NAN" $str]} {
+			append warn "  Record \"$key\": [set ${ns}::exparray($key)]\n"
+			lappend badkeylist $key
+			break
+		    }
+		}
+		continue
+	    }
+	    if {! $OK} {
+		append warn "  Record \"$key\": [set ${ns}::exparray($key)]\n"
+		lappend badkeylist $key
+	    }
+	}
+    }
+    if {$warn == ""} return
+    set hint ""
+    set unknown ""
+    foreach key $badkeylist {
+	if {[string match  "CRS*AT*" $key]} {
+	    if {[string first "atomic parameter" $hint] == -1} {
+		append hint "\t* An atomic parameter (coordinate, occupancy or U) appears out of range\n"
+	    }
+	} elseif {[string match  "CRS*ABC*" $key] || 
+		  [string match  "CRS*ANGLES*" $key] || 
+		  [string match  "CRS*CELVOL*" $key]} {
+	    if {[string first "cell parameter" $hint] == -1} {
+		append hint "\t* A unit cell parameter appears out of range\n"
+	    }
+	} elseif {[string match  "CRS*ODF*" $key]} {
+	    if {[string first "spherical harmonic" $hint] == -1} {
+		append hint "\t* A spherical harmonic (ODF) parameter appears out of range\n"
+	    }
+	} elseif {[string match  "HST*ICONS" $key]} {
+	    if {[string first "diffractometer constant" $hint] == -1} {
+		append hint "\t* A diffractometer constant (wave, DIFC,...) appears out of range\n"
+	    }
+	} elseif {[string match  "HST*TRNGE" $key]} {
+	    if {[string first "histogram data range" $hint] == -1} {
+		append hint "\t* A histogram data range value appears out of range\n"
+	    }
+	} elseif {[string match "*GNLS  RUN*" $key] || 
+		  [string match "*GNLS SHFTS" $key] ||
+		  [string match "HST*RPOWD" $key] ||
+		  [string match " REFN RPOWD " $key] ||
+		  [string match " REFN GDNFT " $key]
+	      } {
+	    if {[string first "refinement statistics" $hint] == -1} {
+		append hint "\t* The refinement statistics imply the last refinement diverged\n"
+	    }
+	} else {
+	    lappend unknown $key
+	}
+    }
+    if {$unknown != ""} {
+	append hint "\t* The following less common problem record(s) appear out of range:\n\t\t"
+	foreach key $unknown {
+	    append hint "\"" [string trim $key] "\" "
+	}
+    }
+    return "Likely error(s) noted:\n$hint\nDetails of problem(s):\n$warn"
+}
+
+proc ExplainEXPerror {parent message file} {
+    if {$parent == "."} {
+	set w .experr
+    } else {
+	set w $parent.experr
+    }
+    catch {destroy $w}
+    toplevel $w -class Dialog
+    wm title $w "Corrupt .EXP file"
+    wm iconname $w Dialog
+    wm protocol $w WM_DELETE_WINDOW { }
+    # Make the message box transient if the parent is viewable.
+    if {[winfo viewable [winfo toplevel $parent]] } {
+        wm transient $w $parent
+    } 
+    frame $w.bot
+    pack $w.bot -side bottom -fill both
+    frame $w.top
+    pack $w.top -side top -fill both -expand 1
+    frame $w.msg
+    pack $w.msg -in $w.top -side right -expand 1 -fill both -padx 3m -pady 3m
+    set txt {Likely errors were noted when reading this file}
+    append txt " ([file tail $file]). "
+    append txt "These problems probably\narose from the last refinement, "
+    append txt "based on settings applied in the previous saved file.\n"
+    append txt "It is probably not possible to continue with this file.\n"
+    append txt "You likely need to revert at least two archived versions back."
+    grid [label $w.msg.s -text $txt -justify left] -row 0 -column 0 -sticky nws
+    grid [button $w.msg.1 -text Help -bg yellow \
+	      -command "MakeWWWHelp expgui.html badexp"] -row 0 -column 1 -columnspan 2 -sticky ne
+    bind $w <Key-F1> "MakeWWWHelp expgui.html badexp"
+    set filelist [lsort -dictionary -decreasing \
+		      [glob -nocomplain \
+			   [file root $file.O* ]]]
+    grid [text  $w.msg.t -font {Times 12} \
+	      -height 10 -width 90 -relief flat -wrap word \
+	      -yscrollcommand "$w.msg.rscr set" \
+	     ] -row 1 -column 0  -columnspan 2 -sticky news
+    grid [scrollbar $w.msg.rscr  -command "$w.msg.t yview" \
+	     ] -row 1 -column 2 -sticky ns
+    # give extra space to the text box
+    grid columnconfigure $w.msg 0 -weight 1
+    grid rowconfigure $w.msg 1 -weight 1
+    $w.msg.t insert end $message
+    button $w.ok -command [list destroy $w] -text OK -default active
+    pack $w.ok -in $w.bot -side left -expand 1 -padx 3m -pady 2m
+    putontop $w
+    tkwait window $w
+    afterputontop
+}
+
 proc UpdateInfoBox {} {
     global expgui
@@ -2548,8 +2843,21 @@
     set file [file join [set expgui(FileMenuDir)] $expgui(FileMenuEXPNAM)]
     if [file isdirectory $file] return
-    if [file exists $file] {
+    if [file exists $file] {	
 	pack [label $expgui(FileInfoBox).1 -text $expgui(FileMenuEXPNAM)] \
 		-side top
 	catch {
+	    # load the EXP file into a namespace & scan for errors
+	    expload $file scan
+	    set warnings [ScanEXPforError scan]
+	    if {$warnings != ""} {
+		pack [frame $expgui(FileInfoBox).1a -bg yellow -padx 4 -pady 4] -side top
+		pack [label $expgui(FileInfoBox).1a.err -justify left \
+			  -text "WARNING: Likely corrupt" -bg yellow] \
+		    -side left -anchor w -fill both
+		pack [button $expgui(FileInfoBox).1a.show \
+			  -text "More..." -padx 0 \
+			  -command "ExplainEXPerror $expgui(FileInfoBox) [list $warnings] $file"\
+			 ] -side right -anchor w
+	    }
 	    set fp [open $file r]
 	    global testline
@@ -2562,4 +2870,6 @@
 		    -text "last GENLES run:\n  $last\n  total cycles: $cycles"] \
 		-side top -anchor w
+	    set chi2 ?
+	    set vars ?
 	    regexp {REFN GDNFT.*= *([0-9]*\.[0-9]*) +for *([0-9]+) variables} \
 		    $testline a chi2 vars
@@ -2600,5 +2910,5 @@
 		    -text $lbl] \
 		    -side top -anchor w	    
-	}
+	} err
     }
 }
@@ -2634,5 +2944,5 @@
 # fill the files & dates & Directory selection box with current directory,
 # also called when box is created to fill it
-proc ChooseExpFil {frm} {
+proc ChooseExpFil {frm "archiveonly 0"} {
     global expgui
     set files $frm.a.files
@@ -2641,18 +2951,24 @@
     $files delete 0 end
     $dates delete 0 end
-    $files insert end {<Parent>}
-    $dates insert end {(Directory)}
-    set filelist [glob -nocomplain \
-	    [file join [set expgui(FileMenuDir)] *] ]
-    foreach file [lsort -dictionary $filelist] {
-	if {[file isdirectory $file]} {
-	    $files insert end [file tail $file]
-	    $dates insert end {(Directory)}
-	}
+    if {$archiveonly == 0} {
+	$files insert end {<Parent>}
+	$dates insert end {(Directory)}
+	set filelist [glob -nocomplain \
+			  [file join [set expgui(FileMenuDir)] *] ]
+	foreach file [lsort -dictionary $filelist] {
+	    if {[file isdirectory $file]} {
+		$files insert end [file tail $file]
+		$dates insert end {(Directory)}
+	    }
+	}
+    } else {	
+	set filelist [glob -nocomplain \
+			  [file root $expgui(expfile)].O* ]
     }
     set pairlist {}
     foreach file [lsort -dictionary $filelist] {
 	if {![file isdirectory $file]  && \
-		[string toupper [file extension $file]] == ".EXP"} {
+		[string toupper [file extension $file]] == ".EXP" \
+		&& $archiveonly == 0} {
 	    set modified [file mtime $file]
 	    lappend pairlist [list $file $modified]
@@ -2704,4 +3020,6 @@
 	if {$expgui(expfile) == [file join $expgui(FileMenuDir) $file]} {
 	    $files selection set $i
+	    set expgui(FileMenuEXPNAM) $file
+	    UpdateInfoBox
 	}
     }
@@ -3398,4 +3716,5 @@
     global expgui
     if {$expgui(MacroChanged)} {
+
 	set ans [MyMessageBox -parent $txt -title "Save macro file?" \
 		     -message "Macro file has been changed, do you want to save it?" \
Index: /trunk/gsasmenu.tcl
===================================================================
--- /trunk/gsasmenu.tcl	(revision 1165)
+++ /trunk/gsasmenu.tcl	(revision 1166)
@@ -9,4 +9,5 @@
 array set expgui_menulist {
     file {
+	revert
 	EraseHistory
 	convert
@@ -25,7 +26,7 @@
 	bkgedit
 	excledt
-	instedit
 	seqgsas
 	mustrplot
+	instedit
     }
     xtal {
@@ -57,5 +58,4 @@
 	cllchg
 	composition
-	fprime
 	hklgen
 	rducll
@@ -158,4 +158,8 @@
     }
 
+    revert {{readnewexp archive} {
+    	Select an old version of the current GSAS file}
+    }
+
     {archive EXP} {- {
 	Toggles archiving of .EXP files. When on, files are 
@@ -304,8 +308,4 @@
     fitspec	{{runGSASprog $cmd} {
 	Fit a TOF vanadium scattering spectrum}
-    }
-
-    fprime	{{runGSASprog $cmd} {
-	Compute f, f', f'' and mu/rho for an element for a range of x-ray wavelengths}
     }
 
@@ -363,4 +363,7 @@
     instedit	{{EditInstFile} {
 	Edit an instrument parameter file}
+    }
+    {New InstParm file}	{- {
+	Create a new instrument parameter file}
     }
 
Index: /trunk/instedit.tcl
===================================================================
--- /trunk/instedit.tcl	(revision 1165)
+++ /trunk/instedit.tcl	(revision 1166)
@@ -78,37 +78,45 @@
     # loop over banks
     set msg {}
-    for {set i 1} {$i <= $instdat(lastbank)} {incr i} {
-	instbankinfo rad $i set $instdat(rad$i) 
-	instbankinfo head $i set $instdat(head$i) 
-	if {[string trim $instdat(name$i)] == ""} {
-	    append msg "\n  The instrument name may not be blank"
-	}
-	instbankinfo name $i set $instdat(name$i)
-	set l {}
-	foreach var {difc difa zero pola ipola kratio} {
-	    lappend l $instdat(${var}$i)
-	}
-	if {[instbankinfo icons $i set $l] != 1} {
-	    append msg "\n  There is an error in values for:\n    the wavelength, zero or polarization"
-	}
-	# loop over the profile terms
-
-	for {set j 1} {$j <= $instparms(proftypes${i})} {incr j} {
-	    set l {}
-	    for {set k 1} {$k <= $instparms(profterms${i}_$j)} {incr k} {
-		lappend l $instdat(prof${i}_${j}_$k)
-	    }
-	    if {[instprofinfo $i $j set [list \
-		    $instdat(proftype${i}_$j) $instdat(profcut${i}_$j) $l]\
-		    ] != 1} {
-		append msg "\n  There is an error in the values for profile set $j."
-	    }
-	}
-	if {$msg != ""} {
-	    MyMessageBox -parent . -title "No save" \
+    if {[catch {
+        for {set i 1} {$i <= $instdat(lastbank)} {incr i} {
+            instbankinfo rad $i set $instdat(rad$i) 
+            instbankinfo head $i set $instdat(head$i) 
+            if {[string trim $instdat(name$i)] == ""} {
+                append msg "\n  The instrument name may not be blank"
+            }
+            instbankinfo name $i set $instdat(name$i)
+            set l {}
+            foreach var {difc difa zero pola ipola kratio} {
+                lappend l $instdat(${var}$i)
+            }
+            if {[instbankinfo icons $i set $l] != 1} {
+                append msg "\n  There is an error in values for:\n    the wavelength, zero or polarization"
+            }
+            # loop over the profile terms
+            
+            for {set j 1} {$j <= $instparms(proftypes${i})} {incr j} {
+                set l {}
+                for {set k 1} {$k <= $instparms(profterms${i}_$j)} {incr k} {
+                    lappend l $instdat(prof${i}_${j}_$k)
+                }
+                if {[instprofinfo $i $j set [list \
+                                                 $instdat(proftype${i}_$j) $instdat(profcut${i}_$j) $l]\
+                        ] != 1} {
+                    append msg "\n  There is an error in the values for profile set $j."
+                }
+            }
+            if {$msg != ""} {
+                MyMessageBox -parent . -title "No save" \
 		    -message "Error in input for bank $i:$msg" -icon warning \
 		    -type Sorry -default sorry
-	    return
-	}
+                return
+            }
+        }
+    } errmsg]} {
+        if {$errmsg == ""} return
+        MyMessageBox -parent . -title "No save" \
+            -message "Error in input (did you define data type, profile type, etc?):\n$errmsg" -icon warning \
+            -type Sorry -default sorry
+        return
     }
     if {$filename == ""} {
@@ -150,4 +158,6 @@
 proc instShowBank {box} {
     global instdat instparms
+    set instparms(profileframe) {}
+
     set topfr $box.a
     if {$instparms(bank) == 0} return
@@ -159,5 +169,4 @@
     }
     if {$instparms(banklabel) == ""} {
-	puts starting
 	return
     }
@@ -562,5 +571,4 @@
 proc AddInstProfile {box b} {
     global instparms instdat
-    set frame $instparms(profileframe)
     incr instparms(proftypes${b})
     instShowBank $box
@@ -759,4 +767,6 @@
 		-parent $instparms(top) -defaultextension .ins \
 		-filetypes {{"Instrument parameters file" ".ins .inst .prm"} {All *.*}}]
+    } elseif {$filename == "(new)"} {
+	set instparms(filename) ""
     } else {
 	set instparms(filename) $filename
Index: /trunk/liveplot
===================================================================
--- /trunk/liveplot	(revision 1165)
+++ /trunk/liveplot	(revision 1166)
@@ -14,5 +14,5 @@
 # process command line arguments
 set exitstat 0
-set expnam [lindex $argv 0]
+set expnam [file root [lindex $argv 0]]
 if {$expnam == ""} {catch {puts "error -- no experiment name"}; set exitstat 1}
 if $exitstat {
@@ -20,5 +20,8 @@
     exit
 }
-
+# work in .EXP directory (in case files will be exported).
+catch {
+    cd [file dirname $expnam]
+}
 # get name of script
 set expgui(script) [info script]
@@ -42,4 +45,5 @@
     set graph(legend) [lindex $argv 2]
 }
+set plot_title "(None)"
 
 set graph(backsub) 0
@@ -79,5 +83,5 @@
 set expgui(fadetime) 10
 set expgui(hklbox) 1
-set expgui(autotick) 0
+set expgui(autotick) 1
 set expgui(phaselabel) 0
 set expgui(pixelregion) 5
@@ -174,4 +178,7 @@
 source [file join $expgui(scriptdir) readexp.tcl]
 source [file join $expgui(scriptdir) opts.tcl]
+#----------------------------------------------------------------
+# use EXPGUI directory for packages
+lappend auto_path $expgui(scriptdir)
 
 if {$program == "bkgedit"}  {
@@ -357,18 +364,5 @@
 	catch {$vec variable $vec}
     }
-    set maxdiff  [set diffvec(max)]
-    set cmin [set calcvec(min)]
-    set omin [set obsvec(min)]
-    set cmax [set calcvec(max)]
-    set omax [set obsvec(max)]
-    set expgui(min) [expr {$omin < $cmin ? $omin : $cmin}]
-    set expgui(max) [expr {$omax > $cmax ? $omax : $cmax}]
-    set ymin1 [expr {$cmin - 1.1*$maxdiff}]
-    set ymin2 [expr {$omin - 1.1*$maxdiff}]
-    if {$ymin1 < $ymin2} {
-	diffvec set [diffvec + $ymin1]
-    } {
-	diffvec set [diffvec + $ymin2]
-    }
+    ApplyMag
     plotdata
 }
@@ -441,9 +435,10 @@
 	wifdvec set $sumlist
 	wifdvec set [wifdvec / [wifdvec length]]
-    }
-    if {$graph(OmCoS)} {
+    } elseif {$graph(OmCoS)} {
 	wifdvec set $WGT
 	wifdvec expr sqrt(wifdvec)
 	wifdvec set [wifdvec * diffvec]
+    } else {
+	wifdvec length 0
     }
     if $graph(backsub) {
@@ -451,20 +446,25 @@
 	calcvec set [calcvec - bckvec]
     }
-    global obsvec calcvec diffvec 
-    set maxdiff  [set diffvec(max)]
-    set cmin [set calcvec(min)]
-    set omin [set obsvec(min)]
-    set cmax [set calcvec(max)]
-    set omax [set obsvec(max)]
-    set expgui(min) [expr {$omin < $cmin ? $omin : $cmin}]
-    set expgui(max) [expr {$omax > $cmax ? $omax : $cmax}]
-    set ymin1 [expr {$cmin - 1.1*$maxdiff}]
-    set ymin2 [expr {$omin - 1.1*$maxdiff}]
-    if {$ymin1 < $ymin2} {
-	diffvec set [diffvec + $ymin1]
-    } {
-	diffvec set [diffvec + $ymin2]
-    }
-    
+    ApplyMag
+    plotdata
+}
+
+proc SetTitle {} {
+    set bx .title
+    toplevel $bx
+    wm title $bx "Edit plot title"
+    wm iconname $bx "Edit plot title"
+    grid [label $bx.txt -text "Enter plot title below"] -row 1 -column 1
+    grid [entry $bx.title -width 70] -row 2 -column 1
+    grid [frame $bx.a] -row 3 -column 1
+    grid [button $bx.a.save -text "Save" \
+              -command "set plot_title \"\[$bx.title get\]\"; destroy $bx" \
+             ] -row 1 -column 1
+    grid [button $bx.a.quit -text "Quit" \
+              -command "destroy $bx" \
+             ] -row 1 -column 2
+    putontop $bx
+    tkwait window $bx
+    afterputontop
     plotdata
 }
@@ -572,4 +572,26 @@
     global expnam hst peakinfo xunits yunits cycle reflns modtime
     global lasthst graph expgui box
+    global obsvec calcvec diffvec 
+
+    if {$graph(yunits) == 2} {
+        set yunits {Intensity/sigma(I)}
+	wifdvec set $::weightlist
+	wifdvec expr sqrt(wifdvec)
+        obsvec set [obsvec * wifdvec]
+        calcvec set [calcvec * wifdvec]
+        bckvec set {}
+        diffvec set [obsvec - calcvec]
+	wifdvec set {}
+        $box element config 1 -label {} -line 0 -hide 1
+    } else {
+        $box element config 1 -label bckgr -line 1 -hide 0
+    }
+
+    set cmin [set calcvec(min)]
+    set omin [set obsvec(min)]
+    set cmax [set calcvec(max)]
+    set omax [set obsvec(max)]
+    set expgui(min) [expr {$omin < $cmin ? $omin : $cmin}]
+    set expgui(max) [expr {$omax > $cmax ? $omax : $cmax}]
 
     foreach p $::expmap(phaselist) {
@@ -592,5 +614,9 @@
 	return
     }
-    $box config -title "$expnam cycle $cycle Hist $hst"
+    if {$::plot_title == "(None)"} {
+        $box config -title "$expnam cycle $cycle Hist $hst"
+    } else {
+        $box config -title $::plot_title
+    }
     $box xaxis config -title $xunits
     $box yaxis config -title $yunits
@@ -622,37 +648,41 @@
     calcvec notify now
     bckvec notify now
-    diffvec notify now
     wifdvec notify now
     # now deal with peaks
-    for {set i 1} {$i < 10} {incr i} {
-	if {$expgui(autotick)} {
-	    set div [expr {( $expgui(max) - $expgui(min) )/40.}]
-	    set ymin [expr {$expgui(min) - ($i+1) * $div}]
-	    set ymax [expr {$expgui(min) - $i * $div}]
-	} else {
-	    set ymin $peakinfo(min$i)
-	    set ymax $peakinfo(max$i)
-	}
-	set j 0
-	if [set peakinfo(flag$i)] {
-	    foreach X $reflns($i) {
-		incr j
-		catch {
-		    $box marker create line -name peaks${i}_$j 
-		}
-		$box marker config peaks${i}_$j  -under 1 \
-			-coords "$X $ymin $X $ymax" 
-		catch {
-		    $box marker config peaks${i}_$j \
-			    $graph(MarkerColorOpt) [list $peakinfo(color$i)]
-		    if {$peakinfo(dashes$i) && ! $expgui(autotick)} {
-			$box marker config peaks${i}_$j -dashes "5 5"
-		    }
-		}
+    #for {set i 1} {$i < 10} {incr i} 
+    set k 0
+    set cmin $expgui(min)
+    foreach i $::expmap(phaselist) {
+	if {[set peakinfo(flag$i)]} {
+            incr k
+            if {$expgui(autotick)} {
+                set div [expr {( $expgui(max) - $expgui(min) )/40.}]
+                set ymin [expr {$expgui(min) - ($k+1) * $div}]
+                set ymax [expr {$expgui(min) - $k * $div}]
+                if {$cmin > $ymin} {set cmin $ymin}
+            } else {
+                set ymin $peakinfo(min$i)
+                set ymax $peakinfo(max$i)
+            }
+            set j 0
+            foreach X $reflns($i) {
+                incr j
+                catch {
+                    $box marker create line -name peaks${i}_$j 
+                }
+                $box marker config peaks${i}_$j  -under 1 \
+                    -coords "$X $ymin $X $ymax" 
+                catch {
+                    $box marker config peaks${i}_$j \
+                        $graph(MarkerColorOpt) [list $peakinfo(color$i)]
+                    if {$peakinfo(dashes$i) && ! $expgui(autotick)} {
+                        $box marker config peaks${i}_$j -dashes "5 5"
+                    }
+                }
 	    }
 	    catch {$box element create phase$i}
 	    catch {
 		$box element config phase$i -color $peakinfo(color$i) \
-			-label $graph(label$i)
+                    -label $graph(label$i)
 	    }
 	} else {
@@ -661,4 +691,13 @@
 	}
     }
+    # offset the difference pattern
+    set maxdiff  [set diffvec(max)]
+    if {$expgui(autotick)} {
+	diffvec set [diffvec + [expr {$cmin - $maxdiff}]]
+    } else {
+	diffvec set [diffvec + [expr {$cmin - 1.1*$maxdiff}]]
+    }
+    diffvec notify now
+
     # force an update of the plot as BLT may not
     $box config -title [$box cget -title]
@@ -1122,4 +1161,7 @@
 	eval $box y2axis config $graph(ElementHideOption) 
 	$box element config 0 -label ""
+        # clear the vector
+        wifdvec set {}
+        wifdvec notify now
     }
 }
@@ -2046,4 +2088,45 @@
 setlegend $box $graph(legend)
 
+set ps2pdfcmd {}
+set gnuplotpath {}
+# find gnuplot
+if {$::tcl_platform(platform) == "windows"} {
+    set gnuplotpath [file join $::expgui(gsasexe) "gnuplot/gnuplot.exe"]
+    if {![file exists $gnuplotpath]} {
+        set gnuplotpath [auto_execok gnuplot.exe]
+    }
+} else {
+    set ::env(PATH) "${::expgui(gsasexe)}:${::env(PATH)}"
+    auto_reset
+    set gnuplotpath [auto_execok gnuplot]
+}
+# find postscript conversion routine
+if {$::tcl_platform(platform) == "windows"} {
+    set gspath [file join $::expgui(gsasexe) "gs/bin/gswin32c.exe"]
+    if {![file exists $gspath]} {
+        set gspath [auto_execok gswin32c.exe]
+    }
+    if {[file exists $gspath]} {
+        set ps2pdfcmd "$gspath -q -P- -dSAFER -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=\$pdfoutname -c save pop -f \$psoutname"
+    }
+} else {
+    # look for ghostscript
+    set gspath [auto_execok gs]
+    if {[file exists $gspath]} {
+        set ps2pdfcmd "$gspath -q -P- -dSAFER -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=\$pdfoutname -c save pop -f \$psoutname"
+    } else {
+        set gspath [auto_execok pstopdf]; # this is on Mac only
+        if {[file exists $gspath]} {
+            set ps2pdfcmd "$gspath \$psoutname -o \$pdfoutname"
+        }
+    }
+}
+set gnuplotexport {}
+catch {
+    source [file join $expgui(scriptdir) gnuplot.tcl]
+}
+
+#======================================================================
+# make menus
 frame .a -bd 3 -relief groove
 pack [menubutton .a.file -text File -underline 0 -menu .a.file.menu] -side left
@@ -2054,4 +2137,6 @@
 .a.file.menu add command -label "Update Plot" \
 	-command {set cycle [getcycle];readdata .g}
+.a.file.menu add command -label "Set Plot Title" \
+	-command SetTitle
 .a.file.menu add cascade -label "Export plot" -menu .a.file.menu.export
 menu .a.file.menu.export
@@ -2062,4 +2147,14 @@
     .a.file.menu.export add command -label "to Grace" -command exportgrace
 }
+if {$gnuplotpath == {}} {
+    .a.file.menu.export add cascade -label "gnuplot program not found"
+} elseif {$gnuplotexport == ""} {
+    .a.file.menu.export add cascade -label "file gnuplot.tcl not found"
+} elseif {$ps2pdfcmd == ""} {
+    .a.file.menu.export add cascade -label "gs or pstopdf program not found"
+} else {
+    .a.file.menu.export add command -label "to PDF" -command ExportPDF
+}
+
 .a.file.menu add command -label Quit -command "destroy ."
 .a.file.menu.export add command -label "as .csv file" \
@@ -2089,6 +2184,300 @@
 .a.options.menu.tick add separator
 
+pack [menubutton .a.mag -text Magnification -underline 0 -menu .a.mag.menu] \
+	-side left
+menu .a.mag.menu
+set maglist {}
+set mag0 1.0
+# display magnification routines
+proc ShowMag {} {
+    global blt_version tcl_platform peakinfo expgui
+    set bx .opt
+    catch {destroy $bx}
+    toplevel $bx
+    putontop $bx
+    wm iconname $bx "Mag Regs"
+    wm title $bx "Plot Magnification Regions"
+    pack [label $bx.0 -text "Magnification Regions:"] -side top
+    if {[llength $::maglist] == 0} {
+	set lbl "None"
+    } else {
+	set lbl ""
+	set xm $::xvec(min)
+	set ym $::mag0
+	set ::maglist [lsort -real -index 0 $::maglist]
+	foreach pair $::maglist {
+	    foreach {xh ymh} $pair {}
+	    append lbl "\tfrom $xm to $xh: times $ym\n"
+	    set xm $xh
+	    set ym $ymh
+	}
+	set xh $::xvec(max)
+	append lbl "\tfrom $xm to $xh: times $ym"
+    }
+    pack [label $bx.1 -text $lbl -justify left] -side top
+    pack [button $bx.2 -text "Close" -command "destroy $bx"] -side top
+    tkwait window $bx
+    afterputontop
+}
+
+# edit magnification regions
+proc EditMag {} {
+    set ::multrow 1
+    set bx .opt
+    catch {destroy $bx}
+    toplevel $bx
+    putontop $bx
+    wm iconname $bx "Mag Regs"
+    wm title $bx "Edit Magnification Regions"
+    pack [label $bx.0 -text "Vertical Magnification Regions:"] -side top
+    if {[llength $::maglist] == 0} {
+	set lbl "None"
+	pack [label $bx.1 -text $lbl -justify left] -side top
+	pack [button $bx.2 -text "Close" -command "destroy $bx"] -side top
+	tkwait window $bx
+	afterputontop
+	return
+    } else {
+	pack [frame $bx.1] -side top
+	set ::maglist [lsort -real -index 0 $::maglist]
+	set row 0
+	foreach pair $::maglist {
+	    foreach {xh ymh} $pair {}
+	    set row1 [expr {$row + 1}]
+	    set ::xmag($row1) $xh
+	    set ::mag($row1) $ymh
+	    if {$row == 0} {
+		grid [label $bx.1.a$row -text "From "] -column 1 -row $row
+		grid [label $bx.1.b$row -text $::xvec(min)] -column 2 -row $row
+		grid [label $bx.1.c$row -text " to "] -column 3 -row $row
+		grid [entry $bx.1.d$row -textvariable xmag(1) -width 6] -column 4 -row $row
+		grid [label $bx.1.e$row -text " times "] -column 5 -row $row
+		grid [entry $bx.1.f$row -textvariable mag0 -width 4] -column 6 -row $row
+	    } else {
+		grid [label $bx.1.a$row -text "From "] -column 1 -row $row
+		grid [entry $bx.1.b$row -textvariable xmag($row) -width 6] -column 2 -row $row
+		grid [label $bx.1.c$row -text " to "] -column 3 -row $row
+		grid [entry $bx.1.d$row -textvariable xmag($row1) -width 6] -column 4 -row $row
+		grid [label $bx.1.e$row -text " times "] -column 5 -row $row
+		grid [entry $bx.1.f$row -textvariable mag($row) -width 4] -column 6 -row $row
+	    }
+	    incr row
+	}
+	grid [label $bx.1.a$row -text "From "] -column 1 -row $row
+	grid [entry $bx.1.b$row -textvariable xmag($row) -width 6] -column 2 -row $row
+	grid [label $bx.1.c$row -text " to "] -column 3 -row $row
+	grid [label $bx.1.d$row -text $::xvec(max)] -column 4 -row $row
+	grid [label $bx.1.e$row -text " times "] -column 5 -row $row
+	grid [entry $bx.1.f$row -textvariable mag($row) -width 4] -column 6 -row $row
+	set ::multrow $row
+    }
+    pack [label $bx.l -text "\nSet the multiplier to zero to delete a region"] -side top
+    pack [frame $bx.2] -side top
+    pack [button $bx.2.a -text "Edit" -command "destroy $bx"] -side left
+    pack [button $bx.2.b -text "Cancel" -command "set multrow 0; destroy $bx"] -side left
+    tkwait window $bx
+    afterputontop
+    if {$::multrow == 0} return
+    set newmaglist {}
+    set xp $::xvec(min)
+    for {set i 1} {$i <= $::multrow} {incr i} {
+	if {$::mag($i) > 0} {
+	    lappend newmaglist [list $::xmag($i) $::mag($i)]
+	}
+	set xp $::xmag($i)
+    }
+    set ::maglist $newmaglist
+    readdata .g
+}
+
+# show a menu to add a magnification region
+proc AddMag {} {
+    set bx .opt
+    catch {destroy $bx}
+    toplevel $bx
+    putontop $bx
+    wm iconname $bx "Add Regs"
+    wm title $bx "Add Plot Magnification Region"
+    pack [frame $bx.0] -side top
+    pack [label $bx.0.a -text "Magnify from "] -side left
+    pack [entry $bx.0.b -textvariable xmin -width 6] -side left
+    pack [label $bx.0.c -text " to next region. Multiply by "] -side left
+    pack [entry $bx.0.d -textvariable mult -width 4] -side left
+    pack [frame $bx.2] -side top
+    pack [button $bx.2.a -text "Add" -command "destroy $bx"] -side left
+    pack [button $bx.2.b -text "Cancel" -command "set mult {}; destroy $bx"] -side left
+    if {[catch {expr $::mult}]} {set ::mult 1.0}
+    if {$::mult <= 0} {set ::mult 1.0}
+    tkwait window $bx
+    afterputontop
+    catch {
+	if {$::xmin < $::xvec(min)} {set ::xmin $::xvec(min)} 
+	if {$::xmin > $::xvec(max)} {set ::xmin $::xvec(max)} 
+	if {$::mult > 0} {
+	    lappend ::maglist [list $::xmin $::mult]
+	    readdata .g
+	} else {
+	    MyMessageBox -parent . -title "Invalid" \
+		-message "Invalid input, try again" \
+		-icon error -type Continue -default continue
+	}
+    }
+}
+proc AddCursorMag {p m} {
+    set x [.g xaxis invtransform $p]
+    if {$x < $::xvec(min) || $x > $::xvec(max) } {
+	bell
+	return
+    }
+    lappend ::maglist [list $x $m]
+    readdata .g
+}
+
+# scale the data with magnification regions
+proc ApplyMag {} {
+    foreach mrk [.g marker names mag*] {
+	.g marker delete $mrk
+    }
+    if {[llength $::maglist] == 0} return
+    global xvec
+    vector create ymult([xvec length])
+    set xl $xvec(min)
+    set ym $::mag0
+    set i 0
+    set ::maglist [lsort -real -index 0 $::maglist]
+    foreach pair $::maglist {
+	foreach {xh ymh} $pair {}
+	set xr [xvec search $xl $xh]
+	#puts "$xl $xh [lindex $xr 0]:[lindex $xr end] $ym"
+	if {[lindex $xr 0] != [lindex $xr end]} {
+	    set ymult([lindex $xr 0]:[lindex $xr end]) $ym
+	    if {$xl != $xvec(min)} {
+		.g marker create line -coords "$xl -Inf $xl Inf" -name mag[incr i]
+	    }
+	    .g marker create text -coords "$xl Inf" -name mag[incr i] -text "x$ym" -anchor w
+	}
+	set xl $xh
+	set ym $ymh
+    }
+    set xh $xvec(max)
+    set xr [xvec search $xl $xh]
+    set ymult([lindex $xr 0]:[lindex $xr end]) $ym
+    #puts "$xl $xh [lindex $xr 0]:[lindex $xr end] $ym"
+    .g marker create line -coords "$xl -Inf $xl Inf" -name mag[incr i]
+    .g marker create text -coords "$xl Inf" -name mag[incr i] -text "x$ym" -anchor w
+    foreach vec {obsvec calcvec bckvec diffvec} {
+	global $vec
+	$vec expr {$vec * ymult}
+    }
+}
+
+# create a PDF using GNUPLOT & GhostScript
+proc ExportPDF {} {
+    set msg {}
+    if {$::gnuplotpath == {}} {
+        append msg "\n\tThe gnuplot program was not found"
+    } 
+    if {$::gnuplotexport == ""} {
+        append msg "\n\tfile gnuplot.tcl not found in $::expgui(scriptdir)"
+    } 
+    if {$::ps2pdfcmd == ""} {
+        append msg "\n\tNo PDF conversion routine (ghostscript or pstopdf on Mac was found"
+    }
+    if {$msg != ""} {
+        MyMessageBox -parent . -title "Gnuplot/GS Error" \
+		-message $msg \
+		-icon error -type OK -default OK
+        return 0
+    }
+
+    set pdfoutname [tk_getSaveFile -title "Select output file" -parent . \
+                        -defaultextension ".pdf" \
+                        -initialdir [pwd] \
+                        -initialfile "[file rootname $::expnam].pdf"]
+    if { $pdfoutname == "" } { return }
+    cd [file dirname $pdfoutname]
+    set pdfoutname [regsub -all " " [file tail $pdfoutname] "_"]
+    set rootname [file root $pdfoutname]
+    set csvoutname "$rootname.csv"
+    set gplotname "$rootname.gplot"
+    set psoutname "$rootname.ps"
+    foreach filename [list $pdfoutname $csvoutname $gplotname $psoutname] {
+        catch {file -force delete $filename}
+    }
+    waitmsg "running gnuplot, Please wait"
+    Graph2Gnuplot .g $gplotname $psoutname $csvoutname
+    if {![file exists $gplotname]} {
+        set msg "\n  Output file for gnuplot not created! ($gplotname)"
+    }
+    if {![file exists $csvoutname]} {
+        append msg "\n   Output file for gnuplot not created! ($csvoutname)"
+    }
+    if {$msg == ""} {
+        if {[catch { exec $::gnuplotpath $gplotname } err]} {
+	    if {[string first "Warning" $err] == -1} {
+		append msg "Error in running gnuplot: $err"
+	    }
+        }
+        if {![file exists $psoutname]} {
+            append msg "\n   Output file from gnuplot not created! ($psoutname)"
+        }
+    }
+    if {$msg == ""} {
+        if {[catch { eval exec [subst $::ps2pdfcmd]} err]} {
+            append msg "Error in PDF conversion: $err"
+        }
+        if {![file exists $pdfoutname]} {
+            append msg "\n   PDF file not created! ($pdfoutname)"
+        }
+    }
+    donewaitmsg
+    if {$msg == ""} {
+        # clean up
+        foreach filename [list $csvoutname $gplotname $psoutname] {
+            catch {file -force delete $filename}
+        }
+        MyMessageBox -parent . -title "PDF created" \
+            -message "Success: PDF file created ($pdfoutname)" \
+            -type OK -default OK
+        return 1
+    } else {
+        # something failed
+        MyMessageBox -parent . -title "Gnuplot/GS Error" \
+		-message "Error: $msg" \
+		-icon error -type OK -default OK
+        return 0
+    }
+}
+
+# resize graph font only
+proc ResizeGraphFont {graph font} {
+    foreach w {legend xaxis yaxis xaxis yaxis \
+                   x2axis y2axis x2axis y2axis} \
+        o {-font -tickfont -tickfont -titlefont -titlefont \
+               -tickfont -tickfont -titlefont -titlefont} {
+                   catch {
+                       $graph $w configure $o $font
+                   }
+               }
+    catch {
+        set curfont [$graph cget -font]
+        if {[string tolower [lindex $curfont 0]] == "symbol"} {
+            $graph configure -font "Symbol [lrange $font 1 end]"
+        } else {
+            $graph configure -font $font
+        }
+    }
+}
+
 if {$program == "liveplot"} {
+    .a.mag.menu add command -label "Add region" -command "AddMag"
+    .a.mag.menu add command -label "Edit Regions" -command "EditMag"
+    .a.mag.menu add separator
+    .a.mag.menu add command -label "Clear" \
+	-command "set maglist {}; readdata .g"
     .a.options.menu add command -label "Obs symbol" -command getsymopts
+    foreach i {1 2 3 4 5 6 7 8 9} {
+	bind . <Control-Key-$i> "AddCursorMag %x $i"
+    }
 } else {
     .a.options.menu add cascade -label "Symbol Type" -menu .a.options.menu.sym
@@ -2131,4 +2520,7 @@
 	    -variable graph(yunits) -value 1 \
 	    -command {set cycle [getcycle];readdata .g}
+    .a.options.menu.yunits add radiobutton -label "I/Sigma(I)" \
+	    -variable graph(yunits) -value 2 \
+	    -command {set cycle [getcycle];readdata .g}
     .a.options.menu add command -label "HKL labeling" -command setlblopts
     .a.options.menu add checkbutton -label "Subtract background" \
@@ -2155,4 +2547,12 @@
 }
 if {$program == "liveplot"} {
+    .a.options.menu add cascade -menu  .a.options.menu.gfont \
+	-label "Graph font"
+    menu .a.options.menu.gfont
+    foreach f {12 14 16 18 20 22 24 26 28 32 36 40} {
+        .a.options.menu.gfont add radiobutton \
+            -command "ResizeGraphFont .g \[list Helvetica -$f\]" \
+            -label $f -font "Helvetica -$f"
+    }
     .a.options.menu add checkbutton -label "Raise on update" \
 	    -variable graph(autoraise)
@@ -2314,5 +2714,10 @@
 expload $expnam.EXP
 mapexp
-
+if {$expgui(autotick)} {
+    foreach i $::expmap(phaselist) {
+        set peakinfo(flag$i) 1
+    }
+}
+        
 # fill the histogram menu
 if {[llength $expmap(powderlist)] > 15} {
Index: /trunk/rb.tcl
===================================================================
--- /trunk/rb.tcl	(revision 1166)
+++ /trunk/rb.tcl	(revision 1166)
@@ -0,0 +1,1162 @@
+#============================================================================
+# Rigid body utility routines
+#============================================================================
+# RigidBodyGetVarNums: Returns a list of the variable numbers in use
+#       for rigid body variable parameters.
+# RigidBodyAtomNums: returns a list of atom numbers that are mapped to
+#       rigid bodies in a selected phase
+# RigidStartAtoms: returns a list of atoms that are allowed for creation of RB
+# ExtractRigidBody: Use the GSAS geometry program to cartesian coordinates &
+#       setting info for a RB from fractional coordinates for atoms in a phase
+# RunRecalcRBCoords: updates the coordinates in all phases after changes have
+#       been made to rigid parameters.
+# CalcBody: Convert ortho to fractional coordinates using RB parameters
+# FitBody: Optimize the origin and Euler angles to match a rigid body to a
+#       set of fractional coordinates
+# zmat2coord: convert a z-matrix to a set of cartesian coordinates
+# RB2cart: convert the representation used for rigid bodies into 
+#       cartesian coordinates
+# PlotRBtype: plot a rigid body with DRAWxtl
+# PlotRBcoords: plot orthogonal coordinates with DRAWxtl
+# DRAWxtlPlotRBFit: plot a set of fraction coordinates superimposed 
+#       on a structure read from a phase with DRAWxtl
+#============================================================================
+#============================================================================
+# RigidBodyGetVarNums: Returns a list of the variable numbers used already
+# for rigid body variable parameters
+proc RigidBodyGetVarNums {} {
+    set varlist {}
+    foreach type [RigidBodyList] {
+	set typelist [lindex [ReadRigidBody $type] 1]
+	foreach item $typelist {
+	    lappend varlist [lindex $item 2]
+	}
+	foreach phase $::expmap(phaselist) {
+	    foreach i [RigidBodyMappingList $phase $type] {
+		set items [ReadRigidBodyMapping $phase $type $i]
+		set varlist [concat $varlist [lindex $items 3]]
+		if {[llength [lindex $items 6]] > 0} {
+		    set varlist [concat $varlist [lindex $items 6]]
+		}
+	    }
+	}
+    }
+    return [lsort -integer -unique $varlist]
+}
+
+# RigidBodyAtomNums: Returns a list of the atoms mapped to rigid bodies in 
+# phase $phase
+proc RigidBodyAtomNums {phase} {
+    if {[lsearch $::expmap(phaselist) $phase] == -1} {return ""}
+    set allatoms $::expmap(atomlist_$phase)
+    # get matching atoms coordinate range
+    set mappedlist {}
+    foreach type [RigidBodyList] {
+	foreach i [RigidBodyMappingList $phase $type] {
+	    # get the number of atoms in this type of body
+	    set natoms [llength [lindex [lindex [lindex [ReadRigidBody $type] 1] 0] 3]]
+	    set natom1 [expr {$natoms - 1}]
+	    set items [ReadRigidBodyMapping $phase $type $i]
+	    set firstatom [lindex $items 0]
+	    set firstind [lsearch $allatoms $firstatom]
+	    set mappedlist [concat $mappedlist \
+				[lrange \
+				     [lrange $allatoms $firstind end] \
+				     0 $natom1] \
+			       ]
+	}
+    }
+    return [lsort -integer $mappedlist]
+}
+
+# RigidStartAtoms: Find allowed starting atoms for a rigid body in a phase
+# Input: 
+#   phase is the phase number
+#   natoms is the number of atoms in the RB to be mapped
+# Returns a list of valid "start" atoms.
+# Example: if the atom numbers in the phase are {2 4 5 6 7 8} and no rigid bodies
+# are mapped, then a 4-atom body can be mapped starting with atom 2, 4 or 5 only,
+# so {2 4 5} is returned
+# If atoms 2-6 were already mapped, then this routine would return an empty
+# list, as it is not possible to map the body.
+proc RigidStartAtoms {phase natoms} {
+    if {[lsearch $::expmap(phaselist) $phase] == -1} {return ""}
+    set allatoms $::expmap(atomlist_$phase)
+    set usedatoms [RigidBodyAtomNums $phase]
+    set startatomlist {}
+    for {set i 0} {$i < [llength $allatoms]} {incr i} {
+	set al [lrange $allatoms $i [expr {$i+$natoms-1}]]
+	if {[llength $al] < $natoms} break
+	set ok 1
+	foreach atom $al {
+	    if {[lsearch $usedatoms $atom] != -1} {
+		set ok 0
+		break
+	    }
+	}
+	if $ok {lappend startatomlist [lindex $al 0]}
+    }
+    return $startatomlist
+}
+
+# ExtractRigidBody: Use the GSAS geometry program to compute a set of cartesian coordinates for a 
+# set of atoms in a .EXP file and provide the origin shift and Euler angles needed to 
+# place the cartesian system into the crystal coordinates. Used for setting up a rigid body.
+# Returns a nested list of lists:
+#   element 0: a list of the origin location {x y z} in fraction coordinates
+#   element 1: a list of three rotation angles in form {a1 a2 a3}
+#              where a1, a2 and a3 are rotations around the cartesian x, y and z axes
+#   element 2: a list of $natom cartesian coordinate triples {{x1 y1 z1} {x2 y2 z2}...}
+# arguments:
+    # phase: phase #
+    # natom: number of atoms in group
+    # firstatom: sequence # in phase (may be > than number of the atom)
+    # originlist: atoms to define origin (where 1 is first atom in group; <= natom)
+    # vector1: list of 3 values with X, Y or Z, atom #a and #b (number as in origin)  (for example {X 1 3})
+    # vector2: list of 3 values with X, Y or Z, atom #a and #b (number as in origin)
+    # note that vector2 must define a different axis than vector1 
+    # also and vector1 and vector2 cannot use the same atom pair
+proc ExtractRigidBody {phase natom firstatom originlist vector1 vector2} {
+    global expgui
+    set fp [open "geom.inp" "w"]
+    puts $fp "N"
+    if {[llength ::expmap(phaselist)] > 1} {
+       # select phase
+       puts $fp "N"
+       puts $fp $phase
+       puts $fp "N"
+    }
+    puts $fp "R"
+    puts $fp "$natom"
+    puts $fp "$firstatom"
+    puts $fp [llength $originlist]
+    foreach i $originlist {
+	puts $fp $i
+    }
+    foreach i [concat $vector1 $vector2] {
+	puts $fp $i
+    }
+    puts $fp "0"
+    puts $fp "X"
+    close $fp
+    #puts "[file join $expgui(gsasexe) geometry] $expgui(expfile) < geom.inp > geom.out"
+    catch {
+	exec [file join $expgui(gsasexe) geometry] $expgui(expfile) < geom.inp > geom.out
+    } err
+    #puts $err
+    file delete geom.inp
+    set fp [open geom.out r]
+    set origin {}
+    set Euler {}
+    set coordlist {}
+    while {[gets $fp line] >= 0} {
+	if {[string first "Cell coordinates of origin" $line] != -1} {
+	    set origin [lrange [string range $line [string first "are" $line] end] 1 3]
+            #puts "origin in rb = $origin"
+	}
+	if {[string first "Rotation angles" $line] != -1} {
+	    set Euler {}
+	    foreach i [lrange [split $line "="] 1 3] {
+		lappend Euler [lindex $i 0]
+	    }
+	    #puts $line
+	    #puts $Euler
+	}
+	if {[string first "Atom   Orthon" $line] != -1} {
+	    set coordlist {}
+	    for {set i 1} {$i <= $natom} {incr i} {
+		gets $fp line
+		set coord {}
+		lappend coord [string trim [string range $line 9 15]]
+		lappend coord [string trim [string range $line 16 22]]
+		lappend coord [string trim [string range $line 23 29]]
+		lappend coord [string trim [string range $line 0 8]]
+		#puts $line
+		#puts $coord
+		lappend coordlist $coord
+	    }
+	    #puts $coordlist
+	}
+    }
+    #file delete geom.out
+    if {[llength $origin] == 0 || [llength $Euler] == 0 || [llength $coordlist] == 0} {
+       puts "Error: run of GEOMETRY failed"
+    }
+    return [list $origin $Euler $coordlist]
+}
+
+# RunRecalcRBCoords: updates the coordinates in a .EXP file after a rigid 
+# body has been changed, mapped or the setting info is changed
+proc RunRecalcRBCoords { } {
+    global expgui tcl_platform
+    set input [open resetmult.inp w]
+    puts $input "Y"
+    puts $input "l b"
+    puts $input "n"
+    puts $input "x x x"
+    puts $input "x"
+    close $input
+    # Save the current exp file
+    savearchiveexp
+    # disable the file changed monitor
+    set expgui(expModifiedLast) 0
+    set expnam [file root [file tail $expgui(expfile)]]
+    set err [catch {
+	if {$tcl_platform(platform) == "windows"} {
+	    exec [file join $expgui(gsasexe) expedt.exe] $expnam < resetmult.inp >& resetmult.out
+	} else {
+	    exec [file join $expgui(gsasexe) expedt] $expnam < resetmult.inp >& resetmult.out
+	}
+    } errmsg]
+    loadexp $expgui(expfile)
+    set fp [open resetmult.out r]
+    set out [read $fp]
+    close $fp
+    set expgui(exptoolout) $out
+    catch {file delete resetmult.inp resetmult.out}
+    if {$err} {
+	return $errmsg
+    } else {
+	return ""
+    }
+}
+
+
+# compute a rotation matrix for orthogonal coordinates (based on MAKMATD in GSAS)
+# rotate angle degrees around axis (1, 2 or 3) for (x, y, or z)
+# returns a list that can be used as a matrix in the La package
+proc RotMatrix {axis angle} {
+    set ang [expr {$angle * acos(0) / 90.}]
+    set mat "1 0 0 0 1 0 0 0 1"
+    if {$axis == 1}  {
+	set i1 1
+	set i2 2
+    } elseif {$axis == 2}  {
+	set i1 2
+	set i2 0
+    } else {
+	set i1 0
+	set i2 1
+    }
+    proc imat {i1 i2} {return [expr {(3*$i2) + $i1}]}
+    foreach item {
+	{$i1 $i1 [expr {cos($ang)}]}
+	{$i2 $i2 [expr {cos($ang)}]}
+	{$i1 $i2 [expr {-sin($ang)}]}
+	{$i2 $i1 [expr {sin($ang)}]}
+    } {
+	foreach {c r val} [subst $item] {}
+	set mat [lreplace $mat [imat $c $r] [imat $c $r] $val]	
+    }
+    return "2 3 3 $mat"
+}
+
+# compute the derivative of the rotation matrix with respect to the angle, see RotMatrix
+# (based on MAKMATD in GSAS)
+# returns a list that can be used as a matrix in the La package
+proc DerivRotMatrix {axis angle} {
+    set ang [expr {$angle * acos(0) / 90.}]
+    set mat "0 0 0 0 0 0 0 0 0"
+    if {$axis == 1}  {
+	set i1 1
+	set i2 2
+    } elseif {$axis == 2}  {
+	set i1 2
+	set i2 0
+    } else {
+	set i1 0
+	set i2 1
+    }
+    proc imat {i1 i2} {return [expr {(3*$i2) + $i1}]}
+    foreach item {
+	{$i1 $i1 [expr {-sin($ang) * acos(0) / 90.}]}
+	{$i2 $i2 [expr {-sin($ang) * acos(0) / 90.}]}
+	{$i1 $i2 [expr {-cos($ang) * acos(0) / 90.}]}
+	{$i2 $i1 [expr {cos($ang) * acos(0) / 90.}]}
+    } {
+	foreach {c r val} [subst $item] {}
+	set mat [lreplace $mat [imat $c $r] [imat $c $r] $val]	
+    }
+    return "2 3 3 $mat"
+}
+
+# compute an orthogonalization matrix from cell parameters (based on AMATRX in GSAS)
+# returns a list that can be used as a matrix in the La package
+proc OrthoMatrix {a b c alpha beta gamma} {
+    set CA [expr {cos($alpha * acos(0) / 90.)}]
+    set CB [expr {cos($beta * acos(0) / 90.)}]
+    set CG [expr {cos($gamma * acos(0) / 90.)}]
+    set SA [expr {sin($alpha * acos(0) / 90.)}]
+    set SB [expr {sin($beta * acos(0) / 90.)}]
+    set SC [expr {sin($gamma * acos(0) / 90.)}]
+    set CASTAR [expr { ($CB*$CG-$CA)/($SB*$SC) }]    ;#! cos(Alpha*)
+    set CBSTAR [expr { ($CA*$CG-$CB)/($SA*$SC) }]    ;#! cos(Beta*)
+    set CCSTAR [expr { ($CA*$CB-$CG)/($SA*$SB) }]    ;#! cos(Gamma*)
+    set SASTAR [expr { sqrt(1.0-($CASTAR*$CASTAR*2)) }]    ;#! sin(Alpha*)
+    set SBSTAR [expr { sqrt(1.0-($CBSTAR*$CBSTAR*2)) }]    ;#! sin(Beta*)
+    set SCSTAR [expr { sqrt(1.0-($CCSTAR*$CCSTAR*2)) }]    ;#! sin(Gamma*)
+
+    set A  "2 3 3      $a 0 0    0 $b 0    0 0 $c"
+    set A1 "2 3 3     1.0 0 0    $CG [expr {$SASTAR*$SC}] [expr {-$CASTAR*$SC}]    $CB 0.0 $SB"
+    #!This matrix is
+    #!   (1.0      0.0            0.0             )
+    #!   (cos(G)  sin(A*)*sin(G) -cos(A*)*sin(G)  )
+    #!   (cos(B)   0.0            sin(B)          )
+    return [La::transpose [La::mmult $A $A1]]
+}
+
+# compute the transformation matrix that converts a rigid body coordinates into fractional 
+# coordinates
+# arguments: 
+#   rotations: a list of axes and angles to rotate: { {axis1 angle1} {axis2 angle2} ...} 
+#              where axis1,... can be 1, 2 or 3 corresponding to the cartesian X, Y or Z axes
+#   cellprms: a list with "a b c alpha beta gamma" in Angstroms and degrees
+# returns a list that can be used as a matrix in the La package
+proc CalcXformMatrix {rotations cellprms} {
+    set prod {}
+    foreach item $rotations {
+	#puts $item
+	set mat [eval RotMatrix $item]
+	if {$prod == ""} {
+	    set prod $mat
+	} else {
+	    set prod [La::mmult $prod $mat]
+	}
+    }
+    #puts "--- rotation product ---"
+    #puts [La::show $prod]
+
+    set ortho [eval OrthoMatrix $cellprms]
+    #puts "--- ortho ---"
+    #puts [La::show $ortho]
+    set deortho [La::msolve $ortho [La::mident 3] ]
+    #puts "--- deortho ---"
+    #puts [La::show $deortho]
+    #puts "--- xform ---"
+    set xform [La::mmult $deortho $prod]
+    return $xform
+}
+
+# transforms a triplet of orthogonal coordinates into fractional ones using 
+# arguments: 
+#    xform: a transformation matrix from CalcXformMatrix
+#    origin: a list of fraction coordinates {x y z} describing the location of the 
+#            origin of the orthogonal coordinates in the crystal system
+#    ortho: a triplet of othogonal coordinates
+# returns a triplet of fractional coordinates
+proc Ortho2Xtal {xform origin ortho} {
+    set ocv "2 3 0 $ortho"
+    set frac [La::mmult $xform $ocv]
+    #puts [La::show [La::transpose $frac]]
+    #puts $frac
+    set frac [La::madd $frac "[lrange $frac 0 2] $origin"]
+    #puts [La::show [La::transpose $frac]]
+    return $frac
+}
+
+# compute the derivative of the transformation matrix (see CalcXformMatrix) 
+# with respect to every rotation in the $rotations list
+# arguments: 
+#   rotations: a list of axes and angles to rotate: { {axis1 angle1} {axis2 angle2} ...} 
+#              where axis1,... can be 1, 2 or 3 corresponding to the cartesian X, Y or Z axes
+#   cellprms: a list with "a b c alpha beta gamma" in Angstroms and degrees
+# returns a list of matrices where each matrix is a list that can be used as a 
+# matrix in the La package
+proc CalcDerivMatrix {rotations cellprms} {
+    set ortho [eval OrthoMatrix $cellprms]
+    set deortho [La::msolve $ortho [La::mident 3] ]
+    set derivlist {}
+
+    foreach item $rotations {
+	#puts $item
+	set mat [eval DerivRotMatrix $item]
+	#puts $item
+	#puts [La::show $mat]
+	set xform [La::mmult $deortho $mat]
+	lappend derivlist $xform
+    }
+    return $derivlist
+}
+
+# CalcBody: Calculate fractional coordinates using rigid body setting parameters
+# arguments: 
+#  Euler: a list of axes and angles to rotate: { {axis1 angle1} {axis2 angle2} ...} 
+#              where axis1,... can be 1, 2 or 3 corresponding to the cartesian X, Y or Z axes
+#  cell: a list with "a b c alpha beta gamma" in Angstroms and degrees
+#  ortholist: list containing triplets with orthogonal coordinates 
+#  origin: a list of fraction coordinates {x y z} describing the location of the 
+#            origin of the orthogonal coordinates in the crystal system
+#     note that the length of ortholist, useflag and fraclist should be the same
+# Returns a list with the computed fractional coordinates for all atoms
+proc CalcBody {Euler cell ortholist origin} {
+    set xform [CalcXformMatrix $Euler $cell]
+    set i 0
+    set sumdvs 0
+    set fracout {}
+    set rmsout {}
+    foreach oc $ortholist {
+	set frac [lrange [Ortho2Xtal $xform $origin $oc] 3 end]
+	lappend fracout $frac
+    }
+    return $fracout
+}
+
+
+# fit a rigid body's origin 
+# arguments: 
+#  Euler: a list of axes and angles to rotate: { {axis1 angle1} {axis2 angle2} ...} 
+#              where axis1,... can be 1, 2 or 3 corresponding to the cartesian X, Y or Z axes
+#  cell: a list with "a b c alpha beta gamma" in Angstroms and degrees
+#  ortholist: list containing triplets with orthogonal coordinates 
+#  useflag: list of flags to indicate if an atom should be used (1) or ignored (0)
+#  fraclist: list containing triplets with fractional coordinates  
+#  origin: a list of fraction coordinates {x y z} describing the location of the 
+#            origin of the orthogonal coordinates in the crystal system
+#     note that the length of ortholist, useflag and fraclist should be the same
+# Returns a list with the following elements
+#   0: a list with three new origin values
+#   1: the root-mean square difference between the fraclist coordinates and those computed 
+#      using the input values for those atoms where $use is one (in Angstroms)
+#   2: the computed fractional coordinates for all atoms
+#   3: individual rms values for all atoms (in Angstroms)
+# note that items 1-3 are computed with the imput origin, not the revised one
+proc FitBodyOrigin {Euler cell ortholist useflag fraclist origin} {
+puts $fraclist
+    set xform [CalcXformMatrix $Euler $cell]
+    #puts "entering FitBodyOrigin"
+    foreach var {x y z} {set sum($var) 0.0}
+    set i 0
+    set sumdvs 0
+    set fracout {}
+    set rmsout {}
+    foreach oc $ortholist use $useflag coord $fraclist {
+        #puts "ortho: $oc"
+	set frac [lrange [Ortho2Xtal $xform $origin $oc] 3 end]
+	lappend fracout $frac
+	if {$use} {incr i}
+	set dvs 0
+	foreach var {x y z} v1 $frac v2 $coord abc [lrange $cell 0 2] {
+	    #puts "v2 = $v2"
+	    #puts "v1 = $v1"
+	    #puts "abc = $abc"
+	    set dv [expr {($v2 - $v1)*$abc}]
+	    set dvs [expr {$dvs + $dv*$dv}]
+	    set sumdvs [expr {$sumdvs + $dv*$dv}]
+	    if {$use} {set sum($var) [expr {$sum($var) + $dv/$abc}]}
+	    #puts "round and round"
+	}
+	lappend rmsout [expr {sqrt($dvs)}]
+    }
+    set rms 0
+    if {$i > 1} {set rms [expr {sqrt($sumdvs)/$i}]}
+    set neworig {}
+    foreach var {x y z} o $origin {
+	lappend neworig [expr {$o + ($sum($var)/$i)}]
+    }
+    return [list $neworig $rms $fracout $rmsout]
+}
+
+# fit a rigid body's Euler angles using least-squares
+# arguments: 
+#  Euler: a list of axes and angles to rotate: { {axis1 angle1} {axis2 angle2} ...} 
+#              where axis1,... can be 1, 2 or 3 corresponding to the cartesian X, Y or Z axes
+#  cell: a list with "a b c alpha beta gamma" in Angstroms and degrees
+#  ortholist: list containing triplets with orthogonal coordinates 
+#  useflag: list of flags to indicate if an atom should be used (1) or ignored (0)
+#  fraclist: list containing triplets with fractional coordinates  
+#  origin: a list of fraction coordinates {x y z} describing the location of the 
+#            origin of the orthogonal coordinates in the crystal system
+#     note that the length of ortholist, useflag and fraclist should be the same
+# Returns a list of new Euler angles 
+proc FitBodyRot {Euler cell ortholist useflag fraclist origin} {
+    set xform [CalcXformMatrix $Euler  $cell]
+    set derivlist [CalcDerivMatrix $Euler  $cell]
+    set A "2 [expr 3*[llength $ortholist]] 3"
+    foreach oc $ortholist use $useflag coord $fraclist {
+	if {! $use} continue
+	foreach deriv $derivlist {
+	    foreach xyz [lrange [Ortho2Xtal $deriv "0 0 0" $oc] 3 end] {
+		lappend A $xyz
+	    }
+	}
+    }
+    #puts "A: [La::show $A]"
+    set y "2 [expr 3*[llength $ortholist]] 1"
+    foreach oc $ortholist use $useflag coord $fraclist {
+	if {! $use} continue
+	set frac [lrange [Ortho2Xtal $xform $origin $oc] 3 end]
+	foreach xyz $coord XYZ $frac {
+	    lappend y [expr {$XYZ - $xyz}]
+	}
+    }
+
+    set AtA [La::mmult [La::transpose $A] $A]
+    set Aty [La::mmult [La::transpose $A] $y]
+    
+    set l {}
+    #set shifts {}
+    foreach delta [lrange [La::msolve $AtA $Aty] 3 end] item $Euler {
+	#lappend shifts $delta
+	lappend l "[lindex $item 0] [expr {$delta + [lindex $item 1]}]"
+    }
+    #puts "shifts = $shifts"
+    return $l
+}
+
+# FitBody: fit a rigid body's Origin and Euler angles
+# arguments: 
+#  Euler: a list of axes and angles to rotate: { {axis1 angle1} {axis2 angle2} ...} 
+#              where axis1,... can be 1, 2 or 3 corresponding to the cartesian X, Y or Z axes
+#  cell: a list with "a b c alpha beta gamma" in Angstroms and degrees
+#  ortholist: list containing triplets with orthogonal coordinates 
+#  useflag: list of flags to indicate if an atom should be used (1) or ignored (0)
+#  fraclist: list containing triplets with fractional coordinates  
+#  origin: a list of fraction coordinates {x y z} describing the location of the 
+#            origin of the orthogonal coordinates in the crystal system
+#     note that the length of ortholist, useflag and fraclist should be the same
+# Returns a list containing 
+#   new origin
+#   new Euler angles
+#   total rms 
+#   fractional coordinates
+#   rms deviation in fractional coordinates of new Euler angles 
+proc FitBody {Euler cell ortholist useflag fraclist origin "ncycle 5"} {
+    #puts "start origin = $origin"
+    foreach {
+	origin 
+	startrms 
+	fracout 
+	rmsout } [FitBodyOrigin $Euler $cell $ortholist $useflag $fraclist $origin] {}
+    #puts "start rms = $startrms"
+    set rmsprev $startrms
+    #puts "new origin = $origin"
+    for {set i 0} {$i < $ncycle} {incr i} {
+	set Eulerprev $Euler
+	set Euler [FitBodyRot $Euler $cell $ortholist $useflag $fraclist $origin]
+	#puts "New Euler $Euler"
+	#puts "after fit" 
+	foreach {
+	    origin 
+	    rms 
+	    fracout 
+	    rmsout } [FitBodyOrigin $Euler $cell $ortholist $useflag $fraclist $origin] {}
+	if {$rms > (1.1 * $rmsprev) + 0.01} {
+	    #puts "rms = $rms, new origin = $origin"
+	    set rmsprev $rms
+	}
+    } 
+    #proc FitBodyOrigin {Euler cell ortholist useflag fraclist origin} 
+    #return "$neworig $rms $fracout $rmsout"
+    set fmt  {"%8.5f %8.5f %8.5f     %8.5f %8.5f %8.5f   %6.3f"}
+    #foreach fracin $fraclist fraccalc $fracout rmsi $rmsout {
+	#puts "[eval format $fmt $fracin $fraccalc $rmsi]"
+    #}
+    return [list $origin $Euler $rms $fracout $rmsout]
+}
+
+# zmat2coord: convert a z-matrix to a set of cartesian coordinates
+#   a z-matrix is also known as "internal coordinates" or "torsion space"
+#   (see Journal of Computational Chemistry, Vol 26, #10, p. 1063â1068, 2005 or
+#    http://www.cmbi.ru.nl/molden/zmat/zmat.html)
+# INPUT:
+#   atmlist is a list of ascii lines where each line contains
+#     lbl c1 distance c2 angle c3 torsion
+#   where each atom is computed from the previous where the new atom is: 
+#     distance $distance from atom $c1 (angstrom)
+#     angle $angle from $c1--$c2 (degrees)
+#     torsion $torsion from $c1--$c2--$c3 (degrees)
+# OUTPUT:
+#  zmat2coord returns a list of atom labels and cartesian coordinates, 
+#  with 4 items in each element (label, x, y, z)
+# this routine was tested against results from Babel via the web interface at 
+# http://www.shodor.org/chemviz/zmatrices/babel.html and sample input at 
+# http://iopenshell.usc.edu/howto/zmatrix/
+proc zmat2coord {atmlist} { 
+    set torad [expr {acos(0)/90.}]
+    set i 0
+    foreach line $atmlist {
+	incr i
+	foreach {lbl c1 dist c2 angle c3 torsion} $line {} 
+	if {$i == 1} {
+	    set atm(1) [list $lbl 0 0 0] ; # 1st atom is at origin
+	} elseif {$i == 2} {
+	    set dist1 $dist
+	    set atm(2) [list $lbl $dist1 0 0] ; # 2nd atom is along x-axis
+	} elseif {$i == 3} {
+	    # 3rd atom can be bonded to the 1st or 2nd
+	    if {$c1 == 1} {
+		set atm(3) [list $lbl \
+				[expr {$dist * cos($torad * $angle)}] \
+				[expr {$dist * sin($torad * $angle)}] \
+				0]
+	    } else {
+		set atm(3) [list $lbl \
+				[expr {$dist1 - $dist * cos($torad * $angle)}] \
+				[expr {$dist * sin($torad * $angle)}] \
+				0]
+	    }
+	} else {
+	    set atm($i) [concat $lbl \
+			     [ahcat "atm" $c1 $dist $c2 $angle $c3 $torsion]]
+	}
+    }
+    set coordlist {}
+    foreach key [lsort -integer [array names atm]] {
+	lappend coordlist $atm($key)
+    }
+    return $coordlist
+}
+# Compute the length of a vector
+proc vlen {a} {
+    set sum 0.0
+    foreach ai $a {
+	set sum [expr {$sum + $ai*$ai}]
+    }
+    return [expr sqrt($sum)]
+}
+# compute vector (a + z * b) and optionally normalize to length d
+proc vadd {a b d z} {
+    set c {}
+    foreach ai $a bi $b {
+        lappend c [expr {$bi + $z * $ai}]
+    }
+    set v [vlen $c]
+    if {$d != 0} {
+	set r {}
+	foreach ci $c {
+	    lappend r [expr {$d * $ci / $v}]
+	}
+	return [list $v $r]
+    }
+    return [list $v $c]
+}
+# normalize a vector
+proc vnrm {x} {
+    set v [vlen $x]
+    if {abs($v) < 1e-8} {return [list 0 0 0]}
+    set y {}
+    foreach xi $x {
+	lappend y [expr {$xi / $v}]
+    }
+    return $y
+}
+# compute the coordinates for an atom that is bonded:
+#   distance $dist from atom $nc
+#   angle $bondang from $nc--$nb
+#   torsion $torsang from $nc--$nb--$na
+#   coordinates are found in array $atmarr in the calling routine
+# based on a Fortran routine provided by Peter Zavalij (Thanks Peter!)
+proc ahcat {atmarr nc dist nb bondang na torsang} {
+    upvar 1 $atmarr atm
+    set xa [lrange $atm($na) 1 3]
+    set xb [lrange $atm($nb) 1 3]
+    set xc [lrange $atm($nc) 1 3]
+    set torad [expr {acos(0)/90.}]
+    # x = unit Vector A-B
+    foreach {x1 x2 x3} [lindex [vadd $xb $xa 1. -1.] 1] {}
+    # y = unit Vector C-B
+    set y [lindex [vadd $xb $xc 1. -1.] 1]
+    foreach {y1 y2 y3} $y {}
+    set z1 [expr {$x2*$y3 - $x3*$y2}]
+    set z2 [expr {$x3*$y1 - $x1*$y3}]
+    set z3 [expr {$x1*$y2 - $x2*$y1}]
+    set z [vnrm [list $z1 $z2 $z3]]
+    set q1 [expr {$y2*$z3 - $y3*$z2}]
+    set q2 [expr {$y3*$z1 - $y1*$z3}]
+    set q3 [expr {$y1*$z2 - $y2*$z1}]
+    set q [vnrm [list $q1 $q2 $q3]]
+    set th [expr {$bondang * $torad}]
+    set ph [expr {-1. * $torsang * $torad}]
+    set cth [expr {cos($th)}]
+    set sth [expr {sin($th)}]
+    set cph [expr {cos($ph)}]
+    set sph [expr {sin($ph)}]
+    set xh {}
+    foreach xci $xc xi $q zi $z yi $y {
+	lappend xh [expr {
+			  $xci +
+			  $dist*($sth*($cph*$xi + $sph*$zi)-$cth*$yi)
+		      }]
+    }
+    return $xh
+}
+ 
+# RB2cart: convert the rigid body representation reported as the 2nd element 
+# in ReadRigidBody into cartesian coordinates
+#   rblist: a list containing an element for each scaling factor
+# in each element there are four items: 
+#    a multiplier value for the rigid body coordinates
+#    a damping value (0-9) for the refinement of the multiplier (not used)
+#    a variable number if the multiplier will be refined (not used)
+#    a list of cartesian coordinates coordinates 
+# each cartesian coordinate contains 4 items: x,y,z and a label
+# returns a list of coordinate triplets
+proc RB2cart {rblist} {
+    foreach item $rblist {
+	foreach {mult damp ref coords} $item {}
+	set i 0
+	foreach xyz $coords {
+	    foreach {x y z} [lrange $xyz 0 2] {}
+	    foreach val [lrange $xyz 0 2] var {X Y Z} {
+		if {[array names $var $i] == ""} {
+		    set ${var}($i) [expr {$mult * $val}]
+		} else {
+		    set ${var}($i) [expr {[set ${var}($i)] + $mult * $val}]
+		}
+	    }
+	    incr i
+	}
+    }
+    set out ""
+    foreach i [lsort -integer [array names X]] {
+	lappend out [list $X($i) $Y($i) $Z($i)]
+    }
+    return $out
+}
+
+# get the name of the DRAWxtl application, if installed
+proc GetDRAWxtlApp {} {
+    # is DRAWxtl installed?
+    set app {}
+    if {![catch {set fp [open [file join $::env(HOME) .drawxtlrc] r]}]} {
+	# line 12 is name of executable
+	set i 0
+	while {$i < 12} {
+	    incr i
+	    gets $fp appname
+	}
+	close $fp
+	set app [auto_execok $appname]
+    }
+    if {$app != ""} {
+	return $appname
+    }
+    return ""
+}
+
+# DRAWxtlPlotOrtho: plot orthogonal coordinates in DRAWxtl
+# input:
+#  filename: file name for the .str file to create
+#  title: string for title in .str file
+#  coords: cartesian coordinates
+#  bondlist: list of bonds to draw as min, max length (A) and 
+#      an optional color; for example: {{1.4 1.6} {1.2 1.3 Red}}
+proc DRAWxtlPlotOrtho {filename title coords bondlist} {
+    foreach {xmin ymin zmin} {"" "" ""} {}
+    foreach {xmax ymax zmax} {"" "" ""} {}
+    foreach xyz $coords {
+	foreach {x y z} $xyz {}
+	foreach s {x y z} {
+	    foreach t {min max} {
+		if {[set ${s}${t}] == ""} {set ${s}${t} [set $s]}
+	    } 
+	    if {[set ${s}min] > [set $s]} {set ${s}min [set $s]}
+	    if {[set ${s}max] < [set $s]} {set ${s}max [set $s]}
+	}
+    }
+    #puts "$xmin $xmax $ymin $ymax $zmin $zmax"
+    set max $xmin
+    foreach val "$xmin $xmax $ymin $ymax $zmin $zmax" {
+	if {$max < abs($val)} {set max $val}
+    }
+    set scale [expr {4.*$max}]
+    set a 10.
+    lappend range [expr -0.01+($xmin/$scale)] [expr 0.01+($xmax/$scale)] \
+	[expr -0.01+($ymin/$scale)] [expr 0.01+($ymax/$scale)] \
+	[expr -0.01+($zmin/$scale)] [expr 0.01+($zmax/$scale)]
+    set fp [open $filename w]
+    puts $fp "title $title"
+    puts $fp "box  0.000 Black"
+    puts $fp "background White"
+    #puts $fp "nolabels"
+    puts $fp "cell $a $a $a 90 90 90"
+    puts $fp "spgr P 1"
+    puts $fp "pack $range"
+    set i 0
+    foreach xyz $coords {
+	foreach {x y z} $xyz {}
+	incr i
+	puts $fp "atom c $i [expr {$x/$scale}] [expr {$y/$scale}] [expr {$z/$scale}]"
+	puts $fp "labeltext [expr {0.02 + $x/$scale}] [expr {0.01 + $y/$scale}] [expr {0.01 + $z/$scale}] $i"
+    }
+    puts $fp "sphere c  [expr 0.100*($a/$scale)] Red"
+    puts $fp "finish   0.70   0.30   0.08   0.01"
+    foreach bondpair $bondlist {
+	foreach {b1 b2 color} $bondpair {}
+	if {$color == ""} {set color Red}
+	puts $fp "bond c c [expr {0.01*$a/$scale}] [expr {$b1*$a/$scale}] [expr {$b2*$a/$scale}] $color"
+    }
+    puts $fp "frame"
+    set range {}
+    lappend range -0.01 [expr 0.01+(0.1*$a/$scale)] \
+	-0.01 [expr 0.01+(0.1*$a/$scale)] \
+	-0.01 [expr 0.01+(0.1*$a/$scale)]
+    puts $fp "cell $a $a $a 90 90 90"
+    puts $fp "spgr P 1"
+    puts $fp "pack $range"
+    puts $fp "atom o 1 0 0 0"
+    puts $fp "atom o 2 [expr {0.1*$a/$scale}] 0 0"
+    puts $fp "atom o 3 0 [expr {0.1*$a/$scale}] 0"
+    puts $fp "atom o 4 0 0 [expr {0.1*$a/$scale}]"
+    puts $fp "bond o o [expr {0.01*$a/$scale}] [expr {-0.1 + $a/$scale}] [expr {0.1 + $a/$scale}] Black"
+    puts $fp "labelscale 0.5"
+    puts $fp "labeltext [expr {0.11*$a/$scale}] 0 0 x"
+    puts $fp "labeltext 0 [expr {0.11*$a/$scale}] 0 y"
+    puts $fp "labeltext 0 0 [expr {0.11*$a/$scale}] z"
+    puts $fp "sphere o [expr {0.02*$a/$scale}] Blue"
+    puts $fp "origin   .0 .0 .0"
+    puts $fp "end"
+    close $fp
+}
+
+# PlotRBtype: plot a rigid body in DRAWxtl
+# input:
+#  rbtype: # of rigid body
+#  bondlist: list of bonds to draw as min, max length (A) and 
+#      an optional color; for example: {{1.4 1.6} {1.2 1.3 Red}}
+#  file: file name for the .str file to create
+proc PlotRBtype {rbtype "bondlist {}" "file {}"} {
+    set app [GetDRAWxtlApp]
+    if {$app == ""} {
+	MyMessageBox -parent . -title "No DRAWxtl" \
+		-message "Sorry, DRAWxtl is not installed" \
+		-icon warning
+	return
+    }
+    if {$::tcl_platform(platform) == "windows" && $file == ""} {
+	set file [file join [pwd] rbplot.str]
+    } else {
+	set file "/tmp/rbplot.str"
+    }
+    set coords [RB2cart [lindex [ReadRigidBody $rbtype] 1]]
+    DRAWxtlPlotOrtho $file "" $coords $bondlist
+    if {$app != ""} {exec $app $file &}
+}
+
+# PlotRBcoords: plot orthogonal coordinates in DRAWxtl
+# input:
+#  coords: cartesian coordinates
+#  bondlist: list of bonds to draw as min, max length (A) and 
+#      an optional color; for example: {{1.4 1.6} {1.2 1.3 Red}}
+#  file: file name for the .str file to create
+proc PlotRBcoords {coords "bondlist {}" "file {}"} {
+    set app [GetDRAWxtlApp]
+    if {$app == ""} {
+	MyMessageBox -parent . -title "No DRAWxtl" \
+		-message "Sorry, DRAWxtl is not installed" \
+		-icon warning
+	return
+    }
+    if {$::tcl_platform(platform) == "windows" && $file == ""} {
+	set file [file join [pwd] rbplot.str]
+    } else {
+	set file "/tmp/rbplot.str"
+    }
+    DRAWxtlPlotOrtho $file "" $coords $bondlist
+    if {$app != ""} {exec $app $file &}
+}
+
+# DRAWxtlPlotRBFit: plot a set of fraction coordinates superimposed 
+# on a structure read from a phase
+# input:
+#  RBcoords: fractional coordinates for rigid body
+#  phase:# of phase to plot
+#  firstatom: seq # of 1st atom in structure to be mapped to rigid body
+#  allatoms: 0 to plot only atoms in phase that are in the rigid body, 
+#      otherwise plot all atoms
+#  bondlist: list of bonds to draw for the phase as min, max length (A) and 
+#      an optional color; for example: {{1.4 1.6} {1.2 1.3 Red}}
+#  rbbondlist: list of bonds to draw for the phase as min, max length (A) and 
+#      an optional color; for example: {{1.4 1.6} {1.2 1.3 Red}}
+#  file: optional file name for the .str file to create
+proc DRAWxtlPlotRBFit {RBcoords phase firstatom "allatoms 0" \
+			   "bondlist {}" "rbbondlist {}" "file {}"} {
+    set natom [llength $RBcoords]
+    set app [GetDRAWxtlApp]
+    if {$app == ""} {
+	MyMessageBox -parent . -title "No DRAWxtl" \
+		-message "Sorry, DRAWxtl is not installed" \
+		-icon warning
+	return
+    }
+    if {$::tcl_platform(platform) == "windows" && $file == ""} {
+	set file [file join [pwd] rbplot.str]
+    } else {
+	set file "/tmp/rbfit.str"
+    }
+
+    # get rigid body coordinate range
+    foreach {xmin ymin zmin} {"" "" ""} {}
+    foreach {xmax ymax zmax} {"" "" ""} {}
+    foreach xyz $RBcoords {
+	foreach {x y z} $xyz {}
+	foreach s {x y z} {
+	    foreach t {min max} {
+		if {[set ${s}${t}] == ""} {set ${s}${t} [set $s]}
+	    } 
+	    if {[set ${s}min] > [set $s]} {set ${s}min [set $s]}
+	    if {[set ${s}max] < [set $s]} {set ${s}max [set $s]}
+	}
+    }
+    set rbrange {}
+    foreach val [list [expr -0.01+$xmin] [expr 0.01+$xmax] \
+		     [expr -0.01+$ymin] [expr 0.01+$ymax] \
+		     [expr -0.01+$zmin] [expr 0.01+$zmax] ] {
+	append rbrange [format " %8.4f" $val]
+    }
+    set rbcenter [list [expr {($xmin+$xmax)/2}] \
+		      [expr {($ymin+$ymax)/2}] \
+		      [expr {($zmin+$zmax)/2}] ]
+    # get matching atoms coordinate range
+    set firstind [lsearch $::expmap(atomlist_$phase) $firstatom]
+    set matchedatomlist [lrange \
+		      [lrange $::expmap(atomlist_$phase) $firstind end] \
+		      0 [expr {$natom-1}]]
+    foreach atom $matchedatomlist {
+	foreach s {x y z} {
+	    set $s [atominfo $phase $atom $s]
+	    foreach t {min max} {
+		if {[set ${s}${t}] == ""} {set ${s}${t} [set $s]}
+	    } 
+	    if {[set ${s}min] > [set $s]} {set ${s}min [set $s]}
+	    if {[set ${s}max] < [set $s]} {set ${s}max [set $s]}
+	}
+    }
+    # expand to cover at least one unit cell
+    foreach var {xmin ymin zmin} { 
+	if {[set $var] > 0.0} {set $var 0.0}
+    }
+    foreach var {xmax ymax zmax} { 
+	if {[set $var] < 1.} {set $var 1.}
+    }
+    set range {}
+    foreach val [list [expr -0.01+$xmin] [expr 0.01+$xmax] \
+		     [expr -0.01+$ymin] [expr 0.01+$ymax] \
+		     [expr -0.01+$zmin] [expr 0.01+$zmax]] {
+	append range [format " %8.4f" $val]
+    }
+
+    set fp [open $file w]
+    puts $fp "title structure/rigid-body fit plot"
+    # plot the structure
+    puts -nonewline $fp "cell"
+    foreach p {a b c alpha beta gamma} {
+	puts -nonewline $fp " [phaseinfo $phase $p]"
+    }
+    puts $fp ""
+    puts $fp "spgp [phaseinfo $phase spacegroup]"
+    puts $fp "pack $range"
+    if {$allatoms != 0} {
+	set atoms $::expmap(atomlist_$phase)
+    } else {
+	set firstind [lsearch $::expmap(atomlist_$phase) $firstatom]
+	set atoms [lrange \
+		       [lrange $::expmap(atomlist_$phase) $firstind end] \
+		       0 [expr {$natom-1}]]
+    }
+
+    # set origin at center of rigid body
+    puts $fp "origin  $rbcenter"
+    # now loop over atoms
+    foreach atom $atoms {
+	set type [atominfo $phase $atom type]
+	set typelist($type) 1
+	set xyz ""
+	foreach v {x y z} {
+	    append xyz "[atominfo $phase $atom $v] "
+	}
+	puts $fp "atom $type $atom $xyz"
+	if {[lsearch $matchedatomlist $atom] != -1} {
+	    puts $fp "labeltext $xyz $atom"
+	}
+		
+	set uiso [atominfo $phase $atom Uiso]
+	# are there anisotropic atoms? If so convert them to Uequiv
+	if {[atominfo $phase $atom temptype] == "A"} {
+	    puts -nonewline $fp "Uij [atominfo $phase $atom type] $atom "
+	    foreach v {U11 U22 U33 U12 U13 U23} {
+		puts -nonewline $fp "[atominfo $phase $atom $v] "
+	    }
+	    puts $fp ""
+	}
+    }
+
+    foreach type [array names typelist] color {Green Blue Magenta Cyan} {
+	if {$type == ""} break
+	puts $fp "sphere $type 0.1 $color"
+    }
+    foreach type [array names typelist] color1 {Green Blue Magenta Cyan} {
+	foreach bondpair $bondlist {
+	    foreach {b1 b2 color} $bondpair {}
+	    if {$color == ""} {set color $color1}
+	    puts $fp "bond $type $type 0.02 $b1 $b2 $color"
+	}
+	foreach type1 [array names typelist] {
+	    if {$type1 == $type} break
+	    foreach bondpair $bondlist {
+		foreach {b1 b2 color} $bondpair {}
+		if {$color == ""} {set color $color1}
+		puts $fp "bond $type $type1 0.02 $b1 $b2 $color"
+	    }
+	}
+    }
+    # plot the rigid body
+    puts $fp "frame"
+    puts -nonewline $fp "cell"
+    foreach p {a b c alpha beta gamma} {
+	puts -nonewline $fp " [phaseinfo $phase $p]"
+    }
+    puts $fp ""
+    puts $fp "background White"
+    #puts $fp "nolabels"
+    puts $fp "labelscale 0.5"
+    puts $fp "spgr P 1"
+    puts $fp "pack $rbrange"
+    set i 0
+    foreach xyz $RBcoords {
+	foreach {x y z} $xyz {}
+	incr i
+	puts $fp "atom c $i $x $y $z"
+	puts $fp "labeltext $x $y $z r$i"
+    }
+    foreach bondpair $rbbondlist {
+	foreach {b1 b2 color} $bondpair {}
+	if {$color == ""} {set color Red}
+	puts $fp "bond c c 0.02 $b1 $b2 $color"
+    }
+
+    puts $fp "sphere c 0.05 Red"
+    puts $fp "finish   0.70   0.30   0.08   0.01"
+    puts $fp "end"
+
+    #puts $fp "bond o o [expr {0.01*$a/$scale}] [expr {-0.1 + $a/$scale}] [expr {0.1 + $a/$scale}] Black"
+    close $fp
+    MyMessageBox -parent . -title "Info" \
+		-message "Note that the phase is drawn in green, blue, cyan & magenta and the rigid body in red."
+    if {$app != ""} {exec $app $file &}
+}
+
+
+#AddRigidBody {1} { {{0 0 0 xe} {1 1 1 o} {2 2 2 si+4}} }
+#puts [GetRB 1 6 8 "1 2" "X 1 2" "Y 1 3"]
+#puts [GetRB 1 4 8 "1" "X 1 2" "Z 3 4"]
+#MapRigidBody 1 1 7 ".11 .22 .33" "11 12 13"
+
+
+#AddRigidBody {1} { {
+#    {1 1 1 o} {-1 1 1 o} {1 -1 1 o} {-1 -1 1 o} 
+#    {1 1 -1 o} {-1 1 -1 o} {1 -1 -1 o} {-1 -1 -1 o} 
+#} }
+#set n [MapRigidBody 1 1 1 ".2 .3 .4" "13 17 19"]
+#puts "body $n created"
+#incr expgui(changed)
+#RunRecalcRBCoords
+#puts "press Enter to continue"
+#gets stdin line
+#MapRigidBody 1 1 $n ".5 .5 .5" "0 0 0"
+#incr expgui(changed)
+#RunRecalcRBCoords
+
+#puts "Test FitBody"
+set fraclist {
+    { 0.5483305238484277 0.4887545024531055 0.6167996784631056 }
+    { 0.1036801409356145 0.5954016321779562 0.5129448102437683 }
+    { 0.26404665760133855 0.09455414439078394 0.612655365147539 }
+    { -0.18060372531147473 0.20120127411563465 0.5088004969282018 }
+    { 0.5806037253114747 0.3987987258843653 0.2911995030717982 }
+    { 0.13595334239866147 0.5054458556092161 0.18734463485246095 }
+    { 0.2963198590643855 0.004598367822043814 0.2870551897562318 }
+    { -0.1483305238484277 0.1112454975468945 0.1832003215368945 }
+}
+set ortholist {
+    {1 1 1} 
+    {-1 1 1}
+    {      1.000000   -1.000000    1.000000}
+    {     -1.000000   -1.000000    1.000000}
+    {      1.000000    1.000000   -1.000000}
+    {     -1.000000    1.000000   -1.000000}
+    {      1.000000   -1.000000   -1.000000}
+    {     -1.000000   -1.000000   -1.000000} 
+}
+# test code, generates DRAWxtl imput file from orthogonal coordinate list
+# with bonds of ~2, 2.8 and 3.4 A
+#DRAWxtlPlotOrtho test4.str "test file" $ortholist {{1.9 2.1} {3.4 3.5 Blue} {2.8 2.83 Green} }
+
+# test code, plots rigid body type #2 with bonds drawn at ~1.3 & 2 A
+#PlotRBtype 2 {{1.9 2.1} {1.28 1.32}}
+
+# test code, plots rigid body coords in ortholist with bonds @  ~2, 2.8 and 3.4 A
+#PlotRBcoords $ortholist {{1.9 2.1} {3.4 3.5 Blue} {2.8 2.83 Green} }
+
+
+set useflag {1 1 1 1 1 1 1 1}
+set cell {4.  5.  6.  95.  100.  105.}
+#set origin ".20 .30 .40"
+set origin ".0 .0 .0"
+#set Euler  {{1 13} {2 17} {3 19}}
+#set Euler  {{1 0} {2 180} {3 0}}
+set Euler  {{1 0} {2 0} {3 0}}
+
+#puts [La::show $xform]
+#puts "out: [FitBody $Euler $cell $ortholist $useflag $fraclist $origin 30]"
+
+
+# test zmat2coord
+set atmlist {
+    {C1 0 0.0 0 0.0 0 0.0}
+    {O2 1 1.20 0 0.0 0 0.0}
+    {H3 1 1.10 2 120.0 0 0.0}
+    {C4 1 1.50 2 120.0 3 180.0}
+    {H5 4 1.10 1 110.0 2 0.00}
+    {H6 4 1.10 1 110.0 2 120.0}
+    {H7 4 1.10 1 110.0 2 -120.0}
+}
+#  C        0.00000        0.00000        0.00000
+#  O        1.20000        0.00000        0.00000
+#  H       -0.55000        0.95263        0.00000
+#  C       -0.75000       -1.29904       -0.00000
+#  H       -0.04293       -2.14169       -0.00000
+#  H       -1.38570       -1.36644        0.89518
+#  H       -1.38570       -1.36644       -0.89518
+# set coordlist [zmat2coord $atmlist]
+ set i 0
+# puts "\nZmatrix in"
+# foreach line $atmlist {
+#     incr i
+#     puts "$i) $line"
+# }
+# puts "Cartesian out"
+# foreach line $coordlist {
+#     puts [eval format "%-4s%10.5f%10.5f%10.5f" $line]
+# }
+
+# AddRigidBody {1 0.75} { 
+#     {
+# 	{1 1 1 c} 
+# 	{-1 1 1 c}
+# 	{      1.000000   -1.000000    1.000000 c}
+# 	{     -1.000000   -1.000000    1.000000 c}
+# 	{      1.000000    1.000000   -1.000000 c}
+# 	{     -1.000000    1.000000   -1.000000 c}
+# 	{      1.000000   -1.000000   -1.000000 c}
+# 	{     -1.000000   -1.000000   -1.000000 c} 
+# 	{1 1 1 h} 
+# 	{1 -1 -1 h} 
+# 	{-1 1 -1 h} 
+# 	{-1 -1 1 h} 
+#     } {
+# 	{0 0 0 c }
+# 	{0 0 0 c}
+# 	{0 0 0 c}
+# 	{0 0 0 c}
+# 	{0 0 0 c}
+# 	{0 0 0 c}
+# 	{0 0 0 c}
+# 	{0 0 0 c}
+# 	{1 1 1 h} 
+# 	{1 -1 -1 h} 
+# 	{-1 1 -1 h} 
+# 	{-1 -1 1 h} 
+#     }
+# }
+# MapRigidBody 2 2 1 {0 0 0} {10 15 20}
Index: /trunk/rbimport_cartesian.tcl
===================================================================
--- /trunk/rbimport_cartesian.tcl	(revision 1166)
+++ /trunk/rbimport_cartesian.tcl	(revision 1166)
@@ -0,0 +1,166 @@
+
+     set ::rb_loader(cartesian) RB_Cartesian_Load
+     set ::rb_descriptor(cartesian) "Cartesian coordinates from text file"
+
+
+   proc RB_Cartesian_Load {args} {
+
+     destroy .cartesian
+     toplevel .cartesian
+     set cart .cartesian
+
+
+     pack [frame $cart.con -bd 2 -relief groove] -side top
+     pack [frame $cart.display -bd 2 -relief groove] -side top -expand 1 -fill both
+     pack [frame $cart.save -bd 2 -relief groove] -side bottom
+     wm title $cart "Load rigid body information from cartesian coordinate file"
+     wm geometry $cart 600x600+10+10
+     set ::rb_file_load ""
+     set ::rb_cartfile ""
+     set filelist ""
+     set files [glob -nocomplain [file join $::expgui(scriptdir) *.cart]]
+     foreach file $files {
+            lappend ::rb_cartfile [lindex [string map {"/" " "} $file] end]
+     }
+ #    puts $::rb_cartfile
+     set ::rb_file_load [lindex $::rb_cartfile 0]
+ #    grid [label $cart.con.lbl -text "Choose Z-Matrix file to load"] -row 1 -column 0
+ #    eval tk_optionMenu $cart.con.file ::rb_file_load $::rb_cartfile
+ #    grid $cart.con.file -row 1 -column 1
+
+     grid [button $cart.con.but -text "Load Coordinates from File" -width 22 -command "RB_cart $cart.display"] -row 2 -column 1
+     grid [button $cart.save.but2 -text "Save Cartesian \n Coordinates" -width 15 -command "RB_cart_Build"] -row 2 -column 1 -padx 5
+     $cart.save.but2 config -state disable
+     grid [button $cart.save.but3 -text "Abort" -width 15 -command "destroy .cartesian"] -row 2 -column 3 -padx 5 -sticky ns
+}
+
+proc RB_cart {location args} {
+     catch {unset array ::tline}
+     set ::rb_file_load [tk_getOpenFile -parent .cartesian -filetypes {
+      	    {"Cartesian input" .cart} {"All files" *}}]
+     if {[string trim $::rb_file_load] == ""} return
+     set fh [open $::rb_file_load r]
+     set ::rb_linenum 0
+     while {[gets $fh line] >= 0} {
+           set line [string trim $line]
+           if {$line == ""} continue
+#           puts "blankcheck = $blankcheck\ntemp = $temp"
+#           set temp [string trim $line " "]
+#           if {$blankcheck != "0" && $blankcheck != "-1"}
+#           if {$blankcheck != ""} {
+              incr ::rb_linenum
+              set ::tline($::rb_linenum) [string map {, " "} $line]
+              puts "::tline($::rb_linenum) = $::tline($::rb_linenum) "
+#           }
+
+
+     }
+     RB_cart_Display $location
+     .cartesian.save.but2 config -state normal
+
+}
+
+ proc RB_cart_Display {location args} {
+
+     eval destroy [winfo children $location]
+     foreach {top main side lbl} [MakeScrollTable $location] {}
+     set col [llength $::tline(1)]
+     grid [label $top.col -justify center -text "Ignore \n line"] -row 0 -column 0
+     set ::rb_cart_col(1) "label"
+     set ::rb_cart_col(2) "X"
+     set ::rb_cart_col(3) "Y"
+     set ::rb_cart_col(4) "Z"
+
+
+
+     set ::rb_colnum 0
+     for {set linenum 1} {$linenum <= $::rb_linenum} {incr linenum} {
+         for {set colnum 0} {$colnum <= [expr [llength $::tline($linenum)] -1]} {incr colnum} {
+             grid [label $main.cart$::rb_colnum -text [lindex $::tline($linenum) $colnum] -width 8] -padx 5 -row $linenum -column [expr $colnum + 1]
+             set ::rb_dummy_atom($linenum) 0
+             grid [checkbutton $main.d$::rb_colnum -variable ::rb_dummy_atom($linenum)]  -row $linenum -column 0
+             incr ::rb_colnum
+         }
+     }
+
+       for {set z 1} {$z <= $::rb_colnum} {incr z} {
+         if {$z > 4} {set ::rb_cart_col($z) "Ignore"}
+
+
+         set menu [tk_optionMenu $top.$z ::rb_cart_col($z) atom X Y Z Ignore]
+             $menu entryconfig 1 -command "RB_cart_restraint $z"
+             $menu entryconfig 2 -command "RB_cart_restraint $z"
+             $menu entryconfig 3 -command "RB_cart_restraint $z"
+         grid $top.$z -row 0 -column $z
+         $top.$z config -width 8
+
+     }
+
+     ResizeScrollTable $location
+}
+
+proc RB_cart_restraint {col args} {
+
+     set fixcoord $::rb_cart_col($col)
+          puts "column $col coordinate changed to $fixcoord"
+     for {set z 1} {$z <= $::rb_colnum} {incr z} {
+         if {$z != $col} {
+            if {$::rb_cart_col($z) == $fixcoord} {puts "col $z needs to be changed"}
+            if {$::rb_cart_col($z) == $fixcoord} {set ::rb_cart_col($z) "Ignore"}
+         }
+     }
+}
+
+
+proc RB_cart_Build {} {
+
+     set bodytyp [expr [llength [RigidBodyList]] + 1]
+     set ::rb_num 1
+     set ::rb_matrix_num($bodytyp) 1
+     set sitenum $::rb_linenum
+     set temp $::rb_linenum
+     set colnum [llength $::tline(1)]
+
+     for {set z 1} {$z <= $::rb_colnum} {incr z} {
+        if {$::rb_cart_col($z) == "x" || $::rb_cart_col($z) == "X"} {set ::rb_x_coord [expr $z - 1]}
+        if {$::rb_cart_col($z) == "y" || $::rb_cart_col($z) == "Y"} {set ::rb_y_coord [expr $z - 1]}
+        if {$::rb_cart_col($z) == "z" || $::rb_cart_col($z) == "Z"} {set ::rb_z_coord [expr $z - 1]}
+     }
+   #  puts "x = $::rb_x_coord"
+   #  puts "y = $::rb_y_coord"
+   #  puts "z = $::rb_z_coord"
+
+     set x 1
+
+     catch {array unset ::rb_x $bodytyp,1,*}
+     catch {array unset ::rb_y $bodytyp,1,*}
+     catch {array unset ::rb_z $bodytyp,1,*}
+
+
+     for {set coordnum 1} {$coordnum <= $sitenum} {incr coordnum} {
+         if {$::rb_dummy_atom($coordnum) != 1} {
+  #                puts $::tline($coordnum)
+                  set ::rb_x($bodytyp,1,$x) [lindex $::tline($coordnum) $::rb_x_coord]
+                  set ::rb_y($bodytyp,1,$x) [lindex $::tline($coordnum) $::rb_y_coord]
+                  set ::rb_z($bodytyp,1,$x) [lindex $::tline($coordnum) $::rb_z_coord]
+  #                puts "line = $::tline($coordnum)"
+  #                puts "coors = $::rb_x($bodytyp,1,$coordnum) $::rb_y($bodytyp,1,$coordnum) $::rb_z($bodytyp,1,$coordnum)"
+                  incr x
+         } else {
+         set temp [expr $temp -1]
+         }
+
+     }
+
+     set ::rb_coord_num($bodytyp,1) $temp
+
+
+    #$::rb_notebook raise [$::rb_notebook page 0]
+    # set pane [$::rb_notebook getframe rb_body0]
+    # set con2 $pane.con2
+
+     #RB_Create_Cart $bodytyp $con2
+     destroy .cartesian
+     NewBodyTypeWindow
+}
+
Index: /trunk/rbimport_fixfrag.tcl
===================================================================
--- /trunk/rbimport_fixfrag.tcl	(revision 1166)
+++ /trunk/rbimport_fixfrag.tcl	(revision 1166)
@@ -0,0 +1,4 @@
+
+     set ::rb_loader(fixfrag) RB_Fixfrag_Load
+     set ::rb_descriptor(fixfrag) "Compute Coordinates from EXP File"
+
Index: /trunk/rbimport_zmatrix.tcl
===================================================================
--- /trunk/rbimport_zmatrix.tcl	(revision 1166)
+++ /trunk/rbimport_zmatrix.tcl	(revision 1166)
@@ -0,0 +1,178 @@
+
+     set ::rb_loader(zmatrix) RB_Zmat_Load
+     set ::rb_descriptor(zmatrix) "Cartesian Coordinates generated by Z-Matrix"
+
+proc RB_Zmat_Load {args} {
+
+     destroy .zmatrix
+     toplevel .zmatrix
+     set zmat .zmatrix
+
+     pack [frame $zmat.con -bd 2 -relief groove] -side top
+     pack [frame $zmat.display -bd 2 -relief groove] -side top -expand 1 -fill both
+     pack [frame $zmat.save -bd 2 -relief groove] -side bottom
+     wm title $zmat "Load rigid body information from Z-Matrix"
+     wm geometry $zmat 600x600+10+10
+     set ::rb_file_load ""
+     set ::rb_zmatfile ""
+     set filelist ""
+     set files [glob -nocomplain [file join $::expgui(scriptdir) *.zmat]]
+     foreach file $files {
+            lappend ::rb_zmatfile [lindex [string map {"/" " "} $file] end]
+     }
+     puts $::rb_zmatfile
+     set ::rb_file_load [lindex $::rb_zmatfile 0]
+ #    grid [label $zmat.con.lbl -text "Choose Z-Matrix file to load"] -row 1 -column 0
+ #    eval tk_optionMenu $zmat.con.file ::rb_file_load $::rb_zmatfile
+ #    grid $zmat.con.file -row 1 -column 1
+
+     grid [button $zmat.con.but -text "Load Z-Matrix" -width 22 -command "RB_Zmat $zmat.display"] -row 2 -column 1
+     grid [button $zmat.save.but2 -text "Convert to Cartesian \n Coordnates" -width 17 -command "RB_Zmat_Convert"] -row 2 -column 1 -padx 5
+          $zmat.save.but2 config -state disable
+     grid [button $zmat.save.but3 -text "Abort" -width 17 -command "destroy .zmatrix"] -row 2 -column 2 -padx 5 -sticky ns
+
+}
+
+proc RB_Zmat {location args} {
+     set ::rb_file_load [tk_getOpenFile -parent .zmatrix -filetypes {
+      	    {"Z-matrix input" .zmat} {"All files" *}
+ }]
+ if {[string trim $::rb_file_load] == ""} return
+     set fh [open $::rb_file_load r]
+     set ::rb_linenum 1
+     while {[eof $fh] != 1} {
+           set temp [gets $fh line]
+           set ::tline($::rb_linenum) $line
+           puts "$::rb_linenum line = $::tline($::rb_linenum)"
+           incr ::rb_linenum
+     }
+     RB_Zmat_Display $location
+     .zmatrix.save.but2 config -state normal
+ }
+
+ proc RB_Zmat_Display {location args} {
+     eval destroy [winfo children $location]
+     foreach {top main side lbl} [MakeScrollTable $location] {}
+
+     grid [label $main.dlbl -text "Dummy Atom"] -row 0 -column 0
+      for {set z 1} {$z <= [expr $::rb_linenum - 1]} {incr z} {
+          switch -exact $z {
+                 1       {set ::zlabel($z) [lindex $::tline($z) 0]
+                          set ::zc1($z)    0
+                          set ::zdist($z)  0
+                          set ::zc2($z)    0
+                          set ::zangle($z) 0
+                          set ::zc3($z)    0
+                          set ::ztors($z)  0
+                          if {$::zlabel($z) == "X"} {set ::rb_dummy_atom($z) 1
+                             } else {
+                             set ::rb_dummy_atom($z) 0}
+                          grid [checkbutton $main.d$z -variable ::rb_dummy_atom($z)]  -row $z -column 0
+                          grid [entry $main.zlabel$z -width 3 -textvariable ::zlabel($z)] -row $z -column 1
+                          }
+                 2        {set ::zlabel($z) [lindex $::tline($z) 0]
+                          set ::zc1($z)    [lindex $::tline($z) 1]
+                          set ::zdist($z)  [lindex $::tline($z) 2]
+                          set ::zc2($z)    0
+                          set ::zangle($z) 0
+                          set ::zc3($z)    0
+                          set ::ztors($z)  0
+                         if {$::zlabel($z) == "X"} {set ::rb_dummy_atom($z) 1
+                             } else {
+                             set ::rb_dummy_atom($z) 0}
+                          grid [checkbutton $main.d$z -variable ::rb_dummy_atom($z)]  -row $z -column 0
+                          grid [entry $main.zlabel$z -width 3 -textvariable ::zlabel($z)] -row $z -column 1
+                          grid [entry $main.zc1$z    -width 3 -textvariable ::zc1($z)] -row $z    -column 2
+                          grid [entry $main.zdist$z  -width 6 -textvariable ::zdist($z)] -row $z  -column 3
+                          }
+                 3        {set ::zlabel($z)  [lindex $::tline($z) 0]
+                          set ::zc1($z)      [lindex $::tline($z) 1]
+                          set ::zdist($z)    [lindex $::tline($z) 2]
+                          set ::zc2($z)      [lindex $::tline($z) 3]
+                          set ::zangle($z)   [lindex $::tline($z) 4]
+                          set ::zc3($z)      0
+                          set ::ztors($z)    0
+                          if {$::zlabel($z) == "X"} {set ::rb_dummy_atom($z) 1
+                             } else {
+                             set ::rb_dummy_atom($z) 0}
+                          grid [checkbutton $main.d$z -variable ::rb_dummy_atom($z)]  -row $z -column 0
+                          grid [entry $main.zlabel$z -width 3 -textvariable ::zlabel($z)] -row $z -column 1
+                          grid [entry $main.zc1$z    -width 3 -textvariable ::zc1($z)]    -row $z -column 2
+                          grid [entry $main.zdist$z  -width 6 -textvariable ::zdist($z)]  -row $z -column 3
+                          grid [entry $main.zc2$z    -width 3 -textvariable ::zc2($z)]    -row $z -column 4
+                          grid [entry $main.zangle$z -width 8 -textvariable ::zangle($z)] -row $z -column 5
+                          }
+                 default {set ::zlabel($z)   [lindex $::tline($z) 0]
+                          set ::zc1($z)      [lindex $::tline($z) 1]
+                          set ::zdist($z)    [lindex $::tline($z) 2]
+                          set ::zc2($z)      [lindex $::tline($z) 3]
+                          set ::zangle($z)   [lindex $::tline($z) 4]
+                          set ::zc3($z)      [lindex $::tline($z) 5]
+                          set ::ztors($z)    [lindex $::tline($z) 6]
+                          if {$::zlabel($z) == "X"} {set ::rb_dummy_atom($z) 1
+                             } else {
+                             set ::rb_dummy_atom($z) 0}
+                          grid [checkbutton $main.d$z -variable ::rb_dummy_atom($z)]  -row $z -column 0
+                          grid [entry $main.zlabel$z -width 3 -textvariable ::zlabel($z)] -row $z -column 1
+                          grid [entry $main.zc1$z    -width 3 -textvariable ::zc1($z)]    -row $z -column 2
+                          grid [entry $main.zdist$z  -width 6 -textvariable ::zdist($z)]  -row $z -column 3
+                          grid [entry $main.zc2$z    -width 3 -textvariable ::zc2($z)]    -row $z -column 4
+                          grid [entry $main.zangle$z -width 8 -textvariable ::zangle($z)] -row $z -column 5
+                          grid [entry $main.zc3$z    -width 3 -textvariable ::zc3($z)]    -row $z -column 6
+                          grid [entry $main.ztors$z  -width 6 -textvariable ::ztors($z)]  -row $z -column 7
+                          }
+          }
+          ResizeScrollTable $location               
+          
+      }
+}
+proc RB_Zmat_Convert {args} {
+     set bodytyp [RB_New_RBnum]
+     puts "bodytyp = $bodytyp"
+#     set bodytyp [expr [llength [RigidBodyList]] + 1]
+     set atomlist ""
+     for {set z 1} {$z <= [expr $::rb_linenum - 1]} {incr z} {
+         set temp ""
+         set temp "$::zlabel($z) $::zc1($z) $::zdist($z) $::zc2($z) $::zangle($z) $::zc3($z) $::ztors($z)"
+         lappend atomlist $temp
+     }
+     puts $atomlist
+     set precoordlist [zmat2coord $atomlist]
+
+     #remove dummy atoms before transfer to Create Rigid Body procedure
+     set coordnum 1
+     set sitenum 0
+     set coordlist ""
+     foreach coord $precoordlist {
+             if {$::rb_dummy_atom($coordnum) != 1} {lappend coordlist $coord; incr sitenum}
+             incr coordnum
+     }
+
+     set ::rb_num 1
+     set ::rb_matrix_num($bodytyp) 1
+     set ::rb_coord_num($bodytyp,1) $sitenum
+     set coordnum 0
+
+     catch {array unset ::rb_x $bodytyp,1,*}
+     catch {array unset ::rb_y $bodytyp,1,*}
+     catch {array unset ::rb_z $bodytyp,1,*}
+
+     foreach coord $coordlist {
+             incr coordnum
+             set ::rb_x($bodytyp,1,$coordnum) [lindex $coord 1]
+             set ::rb_y($bodytyp,1,$coordnum) [lindex $coord 2]
+             set ::rb_z($bodytyp,1,$coordnum) [lindex $coord 3]
+     }
+     destroy .cartesian
+     NewBodyTypeWindow
+
+
+#     $::rb_notebook raise [$::rb_notebook page 0]
+#     set pane [$::rb_notebook getframe rb_body0]
+#     set con2 $pane.con2
+
+#     RB_Create_Cart $bodytyp $con2
+     destroy .zmatrix
+
+}
+
Index: /trunk/readexp.tcl
===================================================================
--- /trunk/readexp.tcl	(revision 1165)
+++ /trunk/readexp.tcl	(revision 1166)
@@ -9,8 +9,10 @@
 # returns 1 if the file is 80 char/line + cr/lf
 # returns 2 if the file is sequential but not fixed-record length
-proc expload {expfile} {
-    global exparray tcl_platform
-    # $expfile is the path to the data file. 
-
+proc expload {expfile "ns {}"} {
+    # expfile is the path to the data file. 
+    # ns is the namespace to place the output array (default is global)
+    if {$ns != ""} {
+	namespace eval $ns {}
+    }
     if [catch {set fil [open "$expfile" r]}] {
 	tk_dialog .expFileErrorMsg "File Open Error" \
@@ -27,5 +29,5 @@
     }
     catch {
-	unset exparray
+	unset ${ns}::exparray
     }
     if {$len > 160} {
@@ -39,5 +41,5 @@
 	    incr i2 80
 	    set key [string range $nline 0 11]
-	    set exparray($key) [string range $nline 12 end]
+	    set ${ns}::exparray($key) [string range $nline 12 end]
 	}
     } else {
@@ -45,5 +47,5 @@
 	while {$len > 0} {
 	    set key [string range $line 0 11]
-	    set exparray($key) [string range $line 12 79]
+	    set ${ns}::exparray($key) [string range $line 12 79]
 	    if {$len != 81 || [string range $line end end] != "\r"} {set fmt 2}
 	    set len [gets $fil line]
@@ -187,4 +189,6 @@
 	}
     }
+    # load the constrained parameters
+    atom_constraint_load
     set expgui(mapstat) 1
 }
@@ -294,4 +298,5 @@
 	    set digits 1
 	}
+	if {$digits <= 0} {set digits 1}
 	if {$digits + $sign >= $length} {
 	    # the number is much too big -- use exponential notation
@@ -307,5 +312,5 @@
 	    set decimal [expr {$length - $digits - $sign - 1}]
 	    set tmp [format "%#.${decimal}f" $value]
-	} elseif {abs($value) < pow(10,2-$decimal) && $length > 6} {
+	} elseif {abs($value) < pow(10,2-$decimal) && $length > 6 && $value != 0} {
 	    # for small values, switch to exponential notation (2-$decimal -> three sig figs.)
 	    set decimal [expr {$length - 6 - $sign}]
@@ -1388,5 +1393,6 @@
 #     absdamp -- damping for absorption refinement (*)
 #     absref -- refinement damping for absorption refinement (*)
-#     proftbl -- returns number of profile table termns
+#     proftbl -- returns number of profile table terms
+#     anomff -- returns a list of elements, f' and f"
 #   parameters transferred from the instrument parameter file:
 #     ITYP    -- returns the contents of the ITYP record
@@ -1977,4 +1983,44 @@
 		return $val
 	    }
+	    anomff-get {
+                set l {}
+                foreach i {1 2 3 4 5 6 7 8 9} {
+                    if {![existsexp "${key}FFANS$i"]} continue
+                    set line [readexp "${key}FFANS$i"]
+                    set elem [string trim [string range $line 2 9]]
+                    set fp [string trim [string range $line 10 19]]
+                    set fpp [string trim [string range $line 20 29]]
+                    lappend l [list $elem $fp $fpp]
+                }
+                return $l
+            }
+	    anomff-set {
+                # match up input against elements in list. 
+                # change elements included, return any elements that are 
+                # not found.
+                set errorlist {}
+                foreach triplet $value {
+                    foreach {e fp fpp} $triplet {}                
+                    foreach i {1 2 3 4 5 6 7 8 9} {
+                        if {![existsexp "${key}FFANS$i"]} continue
+                        # note that the element name is not used or validated
+                        set elem [string trim [string range \
+                                                   [readexp "${key}FFANS$i"] 2 9]]
+                        if {[string match -nocase $e $elem]} { 
+                            if ![validreal fp 10 3] {return 0}
+                            setexp "${key}FFANS$i" $fp 11 10
+                            if ![validreal fpp 10 3] {return 0}
+                            setexp "${key}FFANS$i" $fpp 21 10
+                            set e {}
+                            break
+                        }
+                    }
+                    if {$e != ""} {
+                        # oops, no match
+                        lappend errorlist $e
+                    }
+                }
+                if {$errorlist != ""} {return [list 0 $errorlist]}
+            }
 	    default {
 		set msg "Unsupported histinfo access: parm=$parm action=$action"
@@ -2173,4 +2219,59 @@
     return 1
 }
+
+#  read fixed constraints
+
+proc atom_constraint_read {phase} {
+    set fix_list ""
+    foreach k {1 2 3 4 5 6 7 8 9} {
+	set key [format "LEQV HOLD%1d%2d" $phase $k]
+	set line [readexp $key]
+	foreach j {2 10 18 26 34 42 50 58} {
+	    set fix_param [string range $line $j [expr $j+7]]
+	    if {[string trim $fix_param] == ""} {return $fix_list}
+	    lappend fix_list $fix_param
+	}
+    }
+}
+
+# load all atom constraints into global array fix_param
+proc atom_constraint_load { } {
+    catch {unset ::fix_param}
+    foreach i $::expmap(phaselist) {
+	set temp [atom_constraint_read $i]
+	foreach j $temp {
+	    set atomnum [string trim [string range $j 2 3]]
+	    set param [string trim [string range $j 4 6]]
+	    set ::fix_param($i,$atomnum,$param) 1    
+	}
+    }
+}
+
+proc atom_constraint_write {phase fix_list} {
+    foreach key [array names ::exparray "LEQV HOLD$phase*"] {
+	delexp $key
+    }
+    set k 0
+    set j 1
+    set line ""
+    foreach fix $fix_list {
+	incr k
+	append line $fix
+	if {$k == 8} {
+	    set key [format "LEQV HOLD%1d%2d" $phase $j]
+	    makeexprec $key
+	    setexp $key $line 3 [expr ($k * 8) + 2]
+	    set k 0
+	    incr j
+	    set line ""
+	}
+    }
+    if {$line != ""} {
+        set key [format "LEQV HOLD%1d%2d" $phase $j]
+        makeexprec $key
+        setexp $key $line 3 [expr ($k * 8) + 2]
+    }   
+}
+
 
 #  get a logical constraint
@@ -3099,5 +3200,4 @@
 	}
     }
-    if {$HST == ""} {return "1"}
     if {$HST <=9} {
 	set key "HST  $HST"
@@ -3119,5 +3219,5 @@
 	    makeexprec $key
 	}
-	setexp $key "RSN" [expr 3 + 5*(($HST-1) % 12)] 5
+	setexp $key "RSN " [expr 3 + 5*(($HST-1) % 12)] 5
 	# create other HST  xx recs
 	if {$HST <=9} {
@@ -3130,4 +3230,8 @@
 	makeexprec "$key FACTR"
 	makeexprec "$key NBNDS"
+	mapexp
+    } elseif {$HST == ""} {
+	if $::expgui(debug) {puts "no restraints"}
+	return "1"
     }
 
@@ -3449,2 +3553,705 @@
     }
 }
+#============================================================================
+# rigid body EXP editing routines (to move into readexp.tcl)
+# RigidBodyList -- returns a list of the defined rigid body types
+# SetRigidBodyVar -- set variables and damping for rigid body type multipliers
+# ReadRigidBody  -- # of times a body is mapped, scaling factors, var #s & coordinates
+# RigidBodyMappingList - return a list instances where a RB is mapped in phase
+# RigidBodyEnableTLS -- Enable or Disable TLS use for a rigid body mapping
+# RigidBodySetTLS  -- change the TLS values for a rigid body mapping
+# RigidBodySetDamp -- change the damping values for a rigid body mapping
+# RigidBodyVary    -- set refinement variable numbers for a rigid body mapping
+# RigidBodyTLSVary -- set TLS refinement variable nums for a rigid body mapping
+# AddRigidBody -- defines a new rigid body type
+# DeleteRigidBody -- remove a rigid body definition
+# ReplaceRigidBody -- replaces a previous rigid body type
+# ReadRigidBodyMapping  -- get parameters for a rigid body mapping
+# MapRigidBody -- map a rigid body type into a phase
+# EditRigidBodyMapping -- change the parameters in a rigid body mapping
+# UnMapRigidBody --remove a rigid body constraint by removing a RB "instance"
+#----- note that these older routines should not be used ------
+# RigidBodyCount -- returns the number of defined rigid bodies (body types)
+#    use RigidBodyList instead
+# RigidBodyMappingCount -- # of times a rigid body is mapped in phase
+#    use RigidBodyMappingList instead
+#============================================================================
+# returns the number of defined rigid bodies 
+proc RigidBodyCount {} {
+    set n [string trim [readexp "RGBD  NRBDS"]]
+    if {$n == ""} {
+	set n 0
+    }
+    return $n
+}
+
+# returns a list of the defined rigid body types 
+proc RigidBodyList {} {
+    set n [string trim [readexp "RGBD  NRBDS"]]
+    if {$n == ""} {
+	set n 0
+    }
+    set rblist {}
+    foreach rbnum {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15} {
+	set value $rbnum
+	validint value 2
+	set key "RGBD${value}"
+	if {[existsexp "$key NATR "]} {
+	    lappend rblist $rbnum
+	}
+	if {[llength $rblist] == $n} break
+    }
+    return $rblist
+}
+
+# ReadRigidBody provides all information associated with a rigid body type
+#  rbnum is the rigid body type number
+# it returns two items: 
+#   the number of times the rigid body is mapped
+#   a list containing an element for each scaling factor in rigid body #rbnum.
+# in each element there are four items: 
+#    a multiplier value for the rigid body coordinates
+#    a damping value (0-9) for the refinement of the multiplier
+#    a variable number if the multiplier will be refined
+#    a list of cartesian coordinates coordinates 
+# each cartesian coordinate contains 4 items: x,y,z and a label
+#  note that the label is present only when the RB is created in EXPGUI and is
+#  not used in GSAS.
+proc ReadRigidBody {rbnum} {
+    if {[lsearch [RigidBodyList] $rbnum] == -1} {
+	return ""
+    }
+    set value $rbnum
+    validint value 2
+    set key "RGBD${value}"
+    set n [string trim [string range [readexp "$key NATR"] 0 4]]
+    set used [string trim [string range [readexp "$key NBDS"] 0 4]]
+    set nmult [string trim [string range [readexp "$key NSMP"] 0 4]]
+    set out {}
+    for {set i 1} {$i <= $nmult} {incr i} {
+	set line [readexp "${key}${i}PARM"]
+	set mult [string trim [string range $line 0 9]]
+	set var [string trim [string range $line 10 14]]
+	set damp [string trim [string range $line 15 19]]
+	set coordlist {}
+	for {set j 1} {$j <= $n} {incr j} {
+	    set value $j
+	    validint value 3
+	    set line [readexp "${key}${i}SC$value"]
+	    set x [string trim [string range $line 0 9]]
+	    set y [string trim [string range $line 10 19]]
+	    set z [string trim [string range $line 20 29]]
+	    set lbl [string trim [string range $line 30 39]]
+	    lappend coordlist [list $x $y $z $lbl]
+	}
+	lappend out [list $mult $damp $var $coordlist]
+    }
+    return [list $used $out]
+}
+
+# SetRigidBodyVar
+#   rbnum is the rigid body type number
+#   varnumlist is a list of variable numbers
+#      note that if this list is shorter than the number of actual multipliers
+#      for the body, the unspecified variable will not be changed
+#   damplist   is a list of damping values (0-9)
+#      note that if the damplist is shorter than the number of actual multipliers
+#      the unspecified values are not changed
+#  SetRigidBodVar 2 {1 2 3} {}
+#       will vary the (first 3) translations in body #3 and will not change the
+#       damping values
+#  SetRigidBodVar 3 {} {0 0 0}
+#       will not change variable settings but will change the (first 3) damping values
+#  SetRigidBodVar 4 {11 11} {8 8}
+#      changes both variable numbers and damping at the same time
+# Nothing is returned
+proc SetRigidBodyVar {rbnum varnumlist damplist} {
+    if {[lsearch [RigidBodyList] $rbnum] == -1} {
+	return ""
+    }
+    set value $rbnum
+    validint value 2
+    set key "RGBD${value}"
+    set nmult [string trim [string range [readexp "$key NSMP"] 0 4]]
+    for {set i 1} {$i <= $nmult} {incr i} {
+	set j $i
+	incr j -1
+	set var [lindex $varnumlist $j]
+	if {$var != ""} {
+	    validint var 5
+	    setexp "${key}${i}PARM" $var 11 15
+	}
+	set damp [lindex $damplist $j]
+	if {$damp != ""} {
+	    if {$damp > 9} {set damp 9}
+	    if {$damp < 0} {set damp 0}
+	    validint damp 5
+	}
+	setexp "${key}${i}PARM" $damp 16 20
+    }
+}
+
+
+# return the number of times rigid body $bodytyp is mapped in phase $phase
+proc RigidBodyMappingCount {phase bodytyp} {
+    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1]"
+    if {! [existsexp "$key  NBDS"]} {return 0}
+    set n [string trim [readexp "$key  NBDS"]]
+    if {$n == ""} {
+	set n 0
+    }
+    return $n
+}
+# return a list of the instances where rigid body $bodytyp is mapped in phase $phase
+proc RigidBodyMappingList {phase bodytyp} {
+    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1]"
+    if {! [existsexp "$key  NBDS"]} {return {}}
+    set n [string trim [readexp "$key  NBDS"]]
+    if {$n == ""} {
+	set n 0
+    }
+    set rblist {}
+    foreach rbnum {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15} {
+	set value $rbnum
+	validint value 2
+	set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $rbnum 1]"
+	if {[existsexp "$key  NDA"]} {
+	    lappend rblist $rbnum
+	}
+	if {[llength $rblist] == $n} break
+    }
+    return $rblist
+}
+
+
+
+# reads rigid body mapping parameters for phase ($phase), body type # ($bodytyp) and instance # ($num)
+# returns a list of items (most lists) as follows:
+#   1) sequence # of first atom in body
+#   2) origin of body in fractional coordinates (3 elements)
+#   3) Euler angles as 6 pairs of numbers (see below)
+#   4) variable numbers for the 9 position variables (origin followed by rotations)
+#   5) damping vals for the 9 position variables (origin followed by rotations)
+#   6) the TLS values, in order below (empty list if TLS is not in use)
+#   7) the variable numbers for each TLS values, in order below (or empty)
+#   8) three damping values for the T, L and S terms.
+# returns an empty list if no such body exists.
+#
+# Euler angles are a list of axes and angles to rotate: 
+#   { {axis1 angle1} {axis2 angle2} ...} 
+# where axis1,... can be 1, 2 or 3 corresponding to the cartesian X, Y or Z axes
+#
+# The 20 TLS terms are ordered:
+#    T11, T22, T33, T12, T13, T23
+#    L11, L22, L33, L12, L13, L23
+#    S12, S13, S21, S23, S31, S32, SAA, SBB
+#
+proc ReadRigidBodyMapping {phase bodytyp num} {
+    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $num] == -1} {
+	return ""
+    }
+    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $num 1]"
+    set first [string trim [string range [readexp "$key  NDA"] 0 4]]
+    set line [readexp "$key BDFL"]
+    set varlist {}
+    set damplist {}
+    foreach i {0 1 2 3 4 5 6 7 8} {
+	lappend varlist [string trim [string range $line [expr {5*$i}] [expr {4 + 5*$i}] ]]
+	lappend damplist [string trim [string range $line [expr {45 + $i}] [expr {45 + $i}] ]]
+    }
+    set TLSdamplist {}
+    foreach i {54 55 56} {
+	lappend TLSdamplist [string trim [string range $line $i $i ]]
+    }
+    set line [readexp "${key} BDLC"]
+    set x [string trim [string range $line 0 9]]
+    set y [string trim [string range $line 10 19]]
+    set z [string trim [string range $line 20 29]]
+    set origin [list $x $y $z]
+    set line [readexp "${key} BDOR"]
+    set rotations {}
+    foreach i {0 10 20 30 40 50} {
+	set angle [string trim [string range $line $i [expr {$i+7}]]]
+	set axis [string trim [string range $line [expr {$i+8}] [expr {$i+9}]]]
+	lappend rotations [list $angle $axis]
+    }
+    set TLS [string trim [string range [readexp "${key} LSTF"] 0 4]]
+    set tlsvars {}
+    set tlsvals {}
+    if {$TLS != 0} {
+	set line [readexp "${key}TLSF1"]
+	for {set j 0} {$j < 20} {incr j} {
+            set var [string trim [string range $line [expr {3*$j}] [expr {3*$j+2}]]]
+            if {$var == ""} {set var 0}
+	    lappend tlsvars $var
+	}
+	for {set j 0} {$j < 20} {incr j} {
+	    set i 0
+	    if {$j == 0} {
+		set i 1
+	    } elseif {$j == 8} {
+		set i 2
+	    } elseif {$j == 16} {
+		set i 3
+	    }
+	    if {$i != 0} {
+		set line [readexp "${key}TLSP$i"]
+		set i 0
+		set j1 0
+		set j2 7
+	    } else {
+		incr j1 8
+		incr j2 8
+	    }
+            set val [string trim [string range $line $j1 $j2]]
+            if {$val == ""} {set val 0}
+	    lappend tlsvals $val
+	}
+    }
+    return [list $first $origin $rotations $varlist $damplist $tlsvals $tlsvars $TLSdamplist]
+}
+
+# Control TLS representation for phase, body # and instance number of a Rigid body mapping 
+#   for mapping with phase ($phase), body type # ($bodytyp) and instance # ($num)
+# Enable TLS use if TLS is non-zero (true). Disable if zero
+proc RigidBodyEnableTLS {phase bodytyp num TLS} {
+    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $num] == -1} {
+	return ""
+    }
+    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $num 1]"
+    if {$TLS} {
+	setexp "${key} LSTF" [format "%5d" 1] 1 5
+	if {![existsexp "${key}TLSF1"]} {makeexprec "${key}TLSF1"}
+	if {![existsexp "${key}TLSP1"]} {
+	    makeexprec "${key}TLSP1"
+	    set str {}
+	    foreach v {.01 .01 .01 0 0 0 0 0} d {4 4 4 4 4 4 2 2} {
+		validreal v 8 $d
+		append str $v
+	    }
+	    setexp "${key}TLSP1" $str 1 64
+	}
+	if {![existsexp "${key}TLSP2"]} {
+	    makeexprec "${key}TLSP2"
+	    set str {}
+	    set v 0
+	    foreach d {2 2 2 2 4 4 4 4} {
+		validreal v 8 $d
+		append str $v
+	    }
+	    setexp "${key}TLSP2" $str 1 64
+	}
+	if {![existsexp "${key}TLSP3"]} {
+	    makeexprec "${key}TLSP3"
+	    set str {}
+	    set v 0
+	    foreach d {4 4 4 4} {
+		validreal v 8 $d
+		append str $v
+	    }
+	    setexp "${key}TLSP3" $str 1 64
+	}
+    } else {
+	setexp "${key} LSTF" [format "%5d" 0] 1 5
+    }
+    return 1
+}
+
+# Control the TLS values for Rigid body mapping for mapping with
+#    phase ($phase), body type # ($bodytyp) and instance # ($num)
+# set the 20 TLS values to the values in TLSvals
+# There must be exactly 20 TLS terms, which are ordered:
+#    T11, T22, T33, T12, T13, T23
+#    L11, L22, L33, L12, L13, L23
+#    S12, S13, S21, S23, S31, S32, SAA, SBB
+proc RigidBodySetTLS {phase bodytyp num TLSvals} {
+    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $num] == -1} {
+	return ""
+    }
+    if {[llength $TLSvals] != 20} {return ""}
+    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $num 1]"
+    set TLS [string trim [string range [readexp "${key} LSTF"] 0 4]]
+    if {$TLS == 0} {return ""}
+    if {![existsexp "${key}TLSF1"]} {makeexprec "${key}TLSF1"}
+    foreach n {1 2 3} {
+	if {![existsexp "${key}TLSP$n"]} {makeexprec "${key}TLSP$n"}
+    }
+    set str {}
+    set n 1
+    set i 0
+    foreach v $TLSvals d {4 4 4 4 4 4 2 2 2 2 2 2 4 4 4 4 4 4 4 4} {
+	incr i
+	validreal v 8 $d
+	append str $v
+	if {$i == 8} {
+	    set i 0
+	    setexp "${key}TLSP$n" $str 1 64
+	    incr n
+	    set str {}
+	}
+    }
+    setexp "${key}TLSP$n" $str 1 64
+    return 1
+}
+
+# set damping values for a Rigid body mapping
+#   for mapping with phase ($phase), body type # ($bodytyp) and instance # ($num)
+# there must be 9 damping values in RBdamp for the 9 position variables (origin followed by rotations)
+# Use of TLSdamp is optional, but to be used, TLS representation must be enabled and there must be
+# three damping terms (for all T terms; for all L terms and for all S terms)
+proc RigidBodySetDamp {phase bodytyp num RBdamp "TLSdamp {}"} {
+    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $num] == -1} {
+	return ""
+    }
+    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $num 1]"
+    if {[llength $RBdamp] != 9} {return ""}
+    set str {}
+    foreach v $RBdamp {
+	if {[validint v 1] != 1} {set v " "}
+	append str $v
+    }
+    setexp "$key BDFL" $str 46 9
+    set TLS [string trim [string range [readexp "${key} LSTF"] 0 4]]
+    if {$TLS != 0 &&  [llength $TLSdamp] == 3} {
+	set str {}
+	foreach v $TLSdamp {
+	if {[validint v 1] != 1} {set v " "}
+	    append str $v
+	}
+	setexp "$key BDFL" $str 55 3
+    }
+    return 1
+}
+
+# set refinement variable numbers for a Rigid body mapping
+#   for mapping with phase ($phase), body type # ($bodytyp) and instance # ($num)
+# there must be 9 variable values in RBvar for the 9 position variables (origin followed by rotations)
+# note that the variable values should be unique integers 
+proc RigidBodyVary {phase bodytyp num RBvar} {
+    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $num] == -1} {
+	return ""
+    }
+    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $num 1]"
+    if {[llength $RBvar] != 9} {return ""}
+    set str {}
+    foreach v $RBvar {
+	if {[validint v 5] != 1} {set v " "}
+	append str $v
+    }
+    setexp "$key BDFL" $str 1 45    
+}
+
+# set TLS refinement variable numbers for a Rigid body mapping
+#   for mapping with phase ($phase), body type # ($bodytyp) and instance # ($num)
+# there must be 20 variable values in TLSvar for the 20 parameters:
+#    T11, T22, T33, T12, T13, T23
+#    L11, L22, L33, L12, L13, L23
+#    S12, S13, S21, S23, S31, S32, SAA, SBB
+# note that the variable values should be unique integers 
+proc RigidBodyTLSVary {phase bodytyp num TLSvar} {
+    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $num] == -1} {
+	return ""
+    }
+    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $num 1]"
+    if {[llength $TLSvar] != 20} {return ""}
+    set TLS [string trim [string range [readexp "${key} LSTF"] 0 4]]
+    if {$TLS == 0} {return ""}
+    set str {}
+    foreach v $TLSvar {
+	if {[validint v 3] != 1} {set v " "}
+	append str $v
+    }
+    setexp "${key}TLSF1" $str 1 60
+
+# AddRigidBody: add a new rigid body definition into the .EXP file
+# arguments are:
+#   multlist: defines a list of multipliers for each set of coordinates. In the
+#             simplest case this will be {1}
+#   coordlist: a nested list of coordinates such as { { {0 0 0} {.1 .1 .1} {.2 .2 .2} } }
+# note that when the length of multlist > 1 then coordlist must have the same length.
+# for input where
+#     multlist = {s1 s2} and
+#     coordlist = { { {0 0 0} {1 1 0} {.0 .0 .0} ...}
+#                     {0 0 0} {1 1 0} {2 1 2} ...}
+#                 }
+# the cartesian coordinates are defined from the input as
+#    atom 1 = s1 * (0,0,0) + s2*(0,0,0) [ = (0,0,0)]
+#    atom 2 = s1 * (1,1,0) + s2*(1,1,0) [ = (s1+s2) * (1,1,0)]
+#    atom 3 = s1 * (0,0,0) + s2*(2,1,2) [ = s2 * (2,1,2)]
+#    ...
+# Returns the number of the rigid body that has been created
+proc AddRigidBody {multlist coordlist} {
+    # find the first unused body #
+    foreach rbnum {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} {
+	set value $rbnum
+	validint value 2
+	set key "RGBD${value}"
+	if {! [existsexp "$key NATR "]} {break}
+    }
+    # did we go too far?
+    if {$rbnum == 16} {return ""}
+    # increment the RB counter
+    set n [string trim [readexp "RGBD  NRBDS"]]
+    if {$n == ""} {
+	makeexprec "RGBD  NRBDS"
+	set n 0
+    }
+    incr n
+    validint n 5
+    setexp "RGBD  NRBDS" $n 1 5
+    SetRigidBody $rbnum $multlist $coordlist
+    return $rbnum
+}
+
+# DeleteRigidBody: remove a rigid body definition from the .EXP file
+# The body may not be mapped. I am not sure if GSAS allows more than 9 bodies,
+# but if it does, the simplifed approach used here will fail, so this
+# is not allowed.
+# Input:
+#   Rigid body number
+# Returns:
+#   1 on success
+#   -1 if the body number is 11 or greater
+#   -2 if the body is mapped
+#   -3 if the body is not defined
+proc DeleteRigidBody {rbnum} {
+    # can't delete bodies with numbers higher than 10, since the key prefix
+    # (RGBD11... will overlap with rigid body instance records, which would be
+    # deleted below
+    if {$rbnum > 10} {
+	return -1
+    }
+    set value $rbnum
+    validint value 2
+    set key "RGBD${value}"
+    if {![existsexp "$key NATR "]} {
+	return -2
+    }
+    # make sure the body is not mapped
+    if {[string trim [string range [readexp "$key NBDS"] 0 4]] != 0} {
+	return -3
+    }
+    # delete the records starting with "RGBD x" or "RGBD10"
+    foreach key [array names ::exparray "${key}*"] {
+	#puts $key
+	delexp $key
+    }
+    # decrement the RB counter
+    set n [string trim [readexp "RGBD  NRBDS"]]
+    if {$n == ""} {
+	set n 0
+    }
+    incr n -1
+    validint n 5
+    if {$n > 0} {
+	setexp "RGBD  NRBDS" $n 1 5
+    } else {
+	delexp "RGBD  NRBDS"
+    }
+    return 1
+}
+
+# ReplaceRigidBody: replace all the information for rigid body #rbnum
+# Works the sames as AddRigidBody (see above) except that the rigid body is replaced rather
+# than added.
+# Note that count of the # of times the body is used is preserved
+proc ReplaceRigidBody {rbnum multlist coordlist {varlist ""} {damplist ""}} {
+    set value $rbnum
+    validint value 2
+    set key "RGBD${value}"
+    set line [readexp "$key NBDS"]
+    foreach key [array names ::exparray "${key}*"] {
+	#puts $key
+	delexp $key
+    }
+    SetRigidBody $rbnum $multlist $coordlist $varlist $damplist
+    setexp "$key NBDS" $line 1 68
+}
+
+# Edit the parameters for rigid body #rbnum
+# (normally called from ReplaceRigidBody or AddRigidBody)
+proc SetRigidBody {rbnum multlist coordlist {varlist ""} {damplist ""}} {
+    set value $rbnum
+    validint value 2
+    set key "RGBD${value}"
+    # number of atoms
+    set value [llength [lindex $coordlist 0]]
+    validint value 5
+    makeexprec "$key NATR"
+    setexp "$key NATR" $value 1 5
+    # number of times used
+    set value 0
+    validint value 5
+    makeexprec "$key NBDS"
+    setexp "$key NBDS" $value 1 5
+    # number of coordinate matrices
+    set value [llength $multlist]
+    validint value 5
+    makeexprec "$key NSMP"
+    setexp "$key NSMP" $value 1 5
+    set i 0
+    foreach mult $multlist coords $coordlist {
+        set var [lindex $varlist $i]
+        if {$var == ""} {set var 0}
+        set damp [lindex $damplist $i]
+        if {$damp == ""} {set damp 0}
+	incr i
+        makeexprec "${key}${i}PARM"
+	setexp "${key}${i}PARM" [format "%10.5f%5d%5d" $mult $var $damp] 1 20
+	set j 0
+	foreach item $coords {
+	    #puts $item
+	    incr j
+	    set value $j
+	    validint value 3
+	    makeexprec "${key}${i}SC$value"
+	    if {[llength $item] == 4} {
+		setexp "${key}${i}SC$value" [eval format "%10.6f%10.6f%10.6f%10s" $item] 1 40
+	    } elseif {[llength $item] == 3} {
+		setexp "${key}${i}SC$value" [eval format "%10.6f%10.6f%10.6f" $item] 1 30
+	    } else {
+		return -code 3 "Invalid number of coordinates"
+	    }
+	}
+    }
+}
+
+# convert a decimal to the GSAS hex encoding with a field $digits long.
+proc ToHex {num digits} {
+    return [string toupper [format "%${digits}x" $num]]
+}
+
+# convert a GSAS hex encoding to a decimal integer
+proc FromHex {hex} {
+    return [scan $hex "%x"]
+}
+
+# MapRigidBody: define an "instance" of a rigid body: meaning that the coordinates 
+# (and optionally U values) for a set of atoms will be generated from the rigid body
+# arguments:
+#   phase: phase number (1-9)
+#   bodytyp: number of rigid body (1-15) as returned from AddRigidBody
+#   firstatom: sequence number of the first atom in phase (note that atoms may 
+#              not be numbered sequentially)
+#   position: list of three fractional coordinates for the origin of the rigid body coordinates
+#   angles: list of 3 angles to rotate the rigid body coordinates around x, y, z of the 
+#           cartesian system before the body is translated to position. 
+# returns the instance # (number of times body $bodytyp has been used in phase $phase)
+proc MapRigidBody {phase bodytyp firstatom position angles} {
+    # find the first unused body # for this phase & type
+    foreach rbnum {1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16} {
+	set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $rbnum 1]"
+	if {! [existsexp "$key  NDA"]} {break}
+    }
+    # did we go too far?
+    if {$rbnum == 16} {return ""}
+    # increment number of mapped bodies of this type overall
+    set value $bodytyp
+    validint value 2
+    set key "RGBD${value}"
+    set used [string trim [string range [readexp "$key NBDS"] 0 4]]
+    incr used
+    set value $used
+    validint value 5
+    setexp "$key NBDS" $value 1 5
+    # increment number of mapped bodies of this type in this phase
+    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1]"
+    if {[existsexp "$key  NBDS"]} {
+	set used [string trim [string range [readexp "$key  NBDS"] 0 4]]
+    } else {
+	makeexprec "$key  NBDS"
+	set used 0
+    }
+    incr used
+    set value $used
+    validint value 5
+    setexp "$key  NBDS" $value 1 5
+    # now write the mapping parameters
+    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $rbnum 1]"
+    set value $firstatom
+    validint value 5
+    makeexprec "$key  NDA"
+    setexp "$key  NDA" $value 1 5
+    set l1 {}
+    set l2 {}
+    for {set i 0} {$i < 9} {incr i} {
+	append l1 [format %5d 0]
+	append l2 [format %1d 0]
+    }
+    makeexprec "$key BDFL"
+    setexp "$key BDFL" $l1$l2 1 54
+    makeexprec "${key} BDLC"
+    setexp "${key} BDLC" [eval format "%10.6f%10.6f%10.6f" $position] 1 30
+    makeexprec "${key} BDOR"
+    set l1 {}
+    foreach val "$angles 0 0 0" dir "1 2 3 1 1 1" {
+	append l1 [format "%8.2f%2d" $val $dir]
+    }
+    setexp "${key} BDOR" $l1 1 60
+    makeexprec "${key} LSTF"
+    setexp "${key} LSTF" [format "%5d" 0] 1 5
+    return $rbnum
+}
+
+# EditRigidBodyMapping: edit parameters that define an "instance" of a rigid body (see MapRigidBody)
+# arguments:
+#   phase: phase number (1-9)
+#   bodytyp: number of rigid body (1-15) as returned from AddRigidBody
+#   bodynum: instance number, as returned by MapRigidBody
+#   position: list of three fractional coordinates for the origin of the rigid body coordinates
+#   angles: list of 3 angles to rotate the rigid body coordinates around x, y, z of the 
+#           cartesian system before the body is translated to position. 
+# 
+proc EditRigidBodyMapping {phase bodytyp bodynum position angles} {
+    # number of bodies of this type in this phase
+    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $bodynum 1]"
+    setexp "${key} BDLC" [eval format "%10.6f%10.6f%10.6f" $position] 1 30
+    set l1 {}
+    foreach val "$angles 0 0 0" dir "1 2 3 1 1 1" {
+	append l1 [format "%8.2f%2d" $val $dir]
+    }
+    setexp "${key} BDOR" $l1 1 60
+}
+
+# UnMapRigidBody: remove a rigid body constraint by removing a RB "instance"
+# (undoes MapRigidBody)
+# arguments:
+#   phase: phase number (1-9)
+#   bodytyp: number of rigid body (1-15) as returned from AddRigidBody
+#   bodynum: instance number, as returned by MapRigidBody
+proc UnMapRigidBody {phase bodytyp mapnum} {
+    if {[lsearch [RigidBodyMappingList $phase $bodytyp] $mapnum] == -1} {
+	return ""
+    }
+    # decrement number of mapped bodies of this type overall
+    set value $bodytyp
+    validint value 2
+    set key "RGBD${value}"
+    set used [string trim [string range [readexp "$key NBDS"] 0 4]]
+    incr used -1
+    set value $used
+    validint value 5
+    setexp "$key NBDS" $value 1 5
+    # decrement number of mapped bodies of this type in this phase
+    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1]"
+    if {[existsexp "$key  NBDS"]} {
+	set used [string trim [string range [readexp "$key  NBDS"] 0 4]]
+    } else {
+	set used 0
+    }
+    incr used -1
+    set value $used
+    validint value 5
+    if {$used > 0} {
+	setexp "$key  NBDS" $value 1 5
+    } else {
+	delexp "$key  NBDS"
+    }
+    # now delete the mapping parameter records
+    set key "RGBD[ToHex $phase 1][ToHex $bodytyp 1][ToHex $mapnum 1]"
+    foreach key [array names ::exparray "${key}*"] {
+	delexp $key
+    }
+    return $used
+}
+
Index: /trunk/rigid.tcl
===================================================================
--- /trunk/rigid.tcl	(revision 1166)
+++ /trunk/rigid.tcl	(revision 1166)
@@ -0,0 +1,2215 @@
+# Procedure list:
+# RB_Import_Data_Type {args}            determines types of input available for rigid body creation panel.
+# RB_Load_RBdata {args}                 parses variables from ReadRigidBody
+# RB_Load_Mapdata {phase bodnum mapnum} parses variables from ReadRigidBodyMapping
+# RB_Control_Panel {panelnum args}      builds notebook for rigid bodies
+# RB_Create {args}                      builds rigid body create panel
+# RB_Create_Cart {bodnum location args} creates cartesian coordinate frame in nbt window. (nbt = new body type)
+# RB_Create_save {bodnum args}          builds rigid body from nbt window
+# RB_Delete_Body {bodnum location args} panel queries user confirm rigid body deletion
+# RB_Delete_Body_Confirm {bodnum location args} deletes and unmaps rigid body with UnMapRigidBody and DeleteRigidBody
+# RB_Populate {rb_notebook bodnum args} populates notebook pages with rigid body information
+# RB_Map_New {bodnum args}              adds new map for bodnum
+# RB_VarNums                            determines (add) or removes (sub ##) rigid body variable numbers.
+# RB_View_RMS {address args}            prints RMS data from Fit Rigid Body on mapping panel
+# RB_Choose_Atom {bodnum args}          finds possible first atom for rigid body mapping
+# RB_FitBody2Coords {bodnum menu}          fits rigid body to coordinates.
+# RB_PlotStrBody {bodnum menu}             plots rigid body onto structure
+# RB_Write_Map {args}                   writes mapping information with MapRigidBody
+# RB_Atom_List {phase atomnum address bodnum args} returns a list of atoms in rigid body
+# proc RB_ProcessPhase {bodnum args}    activate / deactivate buttons on rigid body mapping panel
+# RB_Unmap {bodnum args}                writes panel for unmapping rigid body
+# RB_unmap_delete {panel bodnum args}   unmaps rigid body
+# RB_Edit_Matrix {bodnum args}          build edit matrix panel
+# RB_Sort_Inc {bodnum dir args}         sort routine for edit matrix panel (dir = inc or dec)
+# RB_String_Reverse {string args}       reverses the order or elements in a string
+# RB_Matrix_Update {bodnum args}        updates the information in the edit matrix panel
+# proc RB_View_Parameters {phase x y args} not used at this time.
+# proc GetImportFormats {}              locates the file formats for rigid body creation panel not used at this time
+# MakeRBPane {}                         called to initialize pane in notebook
+# NewBodyTypeWindow                      build new rigid body save panel
+# RB_Fixfrag_Load {args}                build panel for generating rigid bodies from exp file
+# RB_FixFragSaveCoord {args}            build rigid body from information on rigid bodies from exp panel
+# RB_FixStartAtom {phase gdisplay gcon2 args}
+# RB_Atom_Fixlist {phase gdisplay}
+# RB_Atom_Origin_Set {args}
+# RB_Geom_Save {args}
+# RB_Refine_Con {args}                  sets matrix to set refinement constrols
+# RB_Variable_Clear {}
+# RB_Con_But_Proc {addresses change args}
+# RB_Con_Button {address args}
+# RB_Var_Gen {varcount args}
+# RB_Var_Assign {args}                   assigns variable numbers to refinement parameters
+# RB_Ref_FlagEnable {phasenum bodnum mapnum var val args}
+# RB_Var_Save {args}
+# RB_TLS_Onoff {phasenum main bodnum mapnum}
+# RB_Load_Vars {phasenum bodnum mapnum args}
+# RB_VarSet {varin mulvarlist args}
+# RB_New_RBnum {args}
+# RB_CartesianTextFile {bodnum args}
+
+
+
+# Important Global variable list:
+#          ::rbtypelist                               variable that contains RB file format types.
+#          ::rb_map(bodnum)                           number of times rigid body is mapped.
+#          ::rb_matrix_num(bodnum)                    number of matrices in rigid body.
+#          ::rb_mult(bodnum,matrixnum)                multiplier for matrix.
+#          ::rb_damp(bodnum,matrixnum)                damping factor for matrix multiplier.
+#          ::rb_var(bodnum,matrixnum)                 variable id for matrix multiplier.
+#          ::rb_coord_num(bodnum,matrixnum)           number of coordinates associated with matrix.
+#          ::rb_coord(bodnum,matrixnum,coord)         coordinate list
+#          ::rb_x(bodnum,matrixnum,coordnum)          x coordinate
+#          ::rb_y(bodnum,matrixnum,coordnum)          y coordinate
+#          ::rb_z(bodnum,matrixnum,coordnum)          z coordinate
+#          ::rb_lbl(bodnum,matrixnum,coordnum)        label for coordinate triplet
+#          ::rb_map_beginning(phase,bodnum,mapnum)    first atom in list
+#          ::rb_map_origin(phase,bodnum,mapnum)       origin of rigid body
+#          ::rb_map_euler(phase,bodnum,mapnum)        euler angles of rigid body
+#          ::rb_map_positions(phase,bodnum,mapnum)    positions
+#          ::rb_map_damping(phase,bodnum,mapnum)      damping
+#          ::rb_map_tls(phase,bodnum,mapnum)          tls
+#          ::rb_map_tls_var(phase,bodnum,mapnum)      tls variable id number
+#          ::rb_map_tls_damp(phase,bodnum,mapnum)     tls damping factor
+#          ::rb_notebook                              contains address of rigid body notebook
+#          ::rb_firstatom                             contains first atom on active rigid body.  Must be gobal for variable has trace.
+#$         ::rb_phase                                 phase for active map
+
+# debug code to load test files when run as an independent script
+if {[array name expgui shell] == ""} {
+    lappend auto_path c:/gsas/expgui
+    package require Tk
+    package require BWidget
+    set expgui(debug) 1
+    #package require La
+    #namespace import La::*
+    source c:/gsas/sandboxexpgui/readexp.tcl
+    source c:/gsas/sandboxexpgui/gsascmds.tcl
+    # test code (package already loaded in expgui)
+    lappend auto_path [file dirname [info script]]
+    package require La
+    source C:/gsas/sandboxexpgui/rb.tcl
+#    puts beforeread
+    expload c:/crystals/expgui/rigid/rb6norb.exp
+    mapexp
+#    puts after
+} else {
+    source [file join $expgui(scriptdir) rb.tcl]
+}
+
+# Procedure to determine possible RB file formats available
+
+proc RB_Import_Data_Type {args} {
+    global expgui tcl_platform
+    # only needs to be done once
+    set ::rbtypelist ""
+
+    set files [glob -nocomplain [file join $expgui(scriptdir) rbimport_*.tcl]]
+    foreach filetype $files {
+          set temp [lindex [string map {_ " "} $filetype] 1]
+          lappend ::rbtypelist $temp
+    }
+    if {$::rbtypelist == ""} {lappend ::rbtypelist "no rigid body file types available"}
+    foreach filetype $::rbtypelist {
+            source $::expgui(scriptdir)/rbimport_$filetype
+    }
+    return $::rbtypelist
+}
+
+#global variables generated by RB_Load
+#
+#
+#          ::rb_map(bodnum)                   number of times rigid body is mapped.
+#          ::rb_matrix_num(bodnum)            number of matrices in rigid body.
+#          ::rb_mult(bodnum,matrixnum)        multiplier for matrix.
+#          ::rb_damp(bodnum,matrixnum)        damping factor for matrix.
+#          ::rb_var(bodnum,matrixnum)         variable for matrix.
+#          ::rb_coord_num(bodnum,matrixnum)   number of coordinates associated with matrix.
+#          ::rb_coord(bodnum,matrixnum,coord) coordinates
+#          ::rb_x(bodnum,matrixnum,coordnum)  x coordinate
+#          ::rb_y(bodnum,matrixnum,coordnum)  y coordinate
+#          ::rb_z(bodnum,matrixnum,coordnum   z coordinate
+#          ::rb_lbl(bodnum,matrixnum,coordnum label for coordinate triplet
+
+proc RB_Load_RBdata {args} {
+    catch {unset ::rb}
+    #Loop over the rigid body types in EXP file
+    foreach bodnum [RigidBodyList] {
+             set rb($bodnum) [ReadRigidBody $bodnum]
+             #Set the number of times rigid body is mapped.
+             set ::rb_map($bodnum) [lindex $rb($bodnum) 0]
+             #define the matrices
+             set rb_mat [lindex $rb($bodnum) 1]
+             set ::rb_matrix_num($bodnum) [llength $rb_mat]
+             for {set matrixnum 1} {$matrixnum <= $::rb_matrix_num($bodnum)} {incr matrixnum} {
+                 set temp [lindex $rb_mat [expr $matrixnum - 1]]
+                 set ::rb_mult($bodnum,$matrixnum) [lindex $temp 0]
+                 set ::rb_damp($bodnum,$matrixnum) [lindex $temp 1]
+                 set ::rb_var($bodnum,$matrixnum)  [lindex $temp 2]
+                 if {$::rb_var($bodnum,$matrixnum) == 0} {
+                    set ::rb_varcheck($bodnum,$matrixnum) 0
+                 } else {
+                    set ::rb_varcheck($bodnum,$matrixnum) 1
+                 }
+#                 puts "in RB_Load_RBdata ::rb_damp = $::rb_damp($bodnum,$matrixnum)"
+                 set coords [lindex $temp 3]
+                 set ::rb_coord_num($bodnum,$matrixnum) [llength $coords]
+                 #load all coordniate information for matrix matrixnum
+                 for {set coordnum 0} {$coordnum < $::rb_coord_num($bodnum,$matrixnum)} {incr coordnum} {
+                     set ::rb_coord($bodnum,$matrixnum,$coordnum) [lindex $coords $coordnum]
+                     set ::rb_x($bodnum,$matrixnum,$coordnum) [lindex $::rb_coord($bodnum,$matrixnum,$coordnum) 0]
+                     set ::rb_y($bodnum,$matrixnum,$coordnum) [lindex $::rb_coord($bodnum,$matrixnum,$coordnum) 0]
+                     set ::rb_z($bodnum,$matrixnum,$coordnum) [lindex $::rb_coord($bodnum,$matrixnum,$coordnum) 0]
+                     set ::rb_lbl($bodnum,$matrixnum,$coordnum) [lindex $::rb_coord($bodnum,$matrixnum,$coordnum) 0]
+#                    restore values                     
+                     set ::rb_matrix_num_temp($bodnum) $::rb_matrix_num($bodnum)
+                     set ::rb_coord_num_temp($bodnum,1) $::rb_coord_num($bodnum,1)
+                     set ::rb_coord_temp($bodnum,$matrixnum,$coordnum) $::rb_coord($bodnum,$matrixnum,$coordnum)
+
+                 }
+             }
+     }
+}
+
+############################################
+#           ::rb_map_beginning(phase,bodnum,mapnum)   first atom in list
+#           ::rb_map_origin(phase,bodnum,mapnum)      origin of rigid body
+#           ::rb_map_euler(phase,bodnum,mapnum)       euler angles of rigid body
+#           ::rb_map_positions(phase,bodnum,mapnum)   positions
+#           ::rb_map_damping(phase,bodnum,mapnum)     damping
+#           ::rb_map_tls(phase,bodnum,mapnum)         tls
+#           ::rb_map_tls_var(phase,bodnum,mapnum)
+#           ::rb_map_tls_damp(phase,bodnum,mapnum)
+proc RB_Load_Mapdata {phase bodnum mapnum} {
+     set rb_map [ReadRigidBodyMapping $phase $bodnum $mapnum]
+     set ::rb_map_beginning($phase,$bodnum,$mapnum) [lindex $rb_map 0]
+     set ::rb_map_origin($phase,$bodnum,$mapnum) [lindex $rb_map 1]
+     set ::rb_map_euler($phase,$bodnum,$mapnum) [lindex $rb_map 2]
+     set ::rb_map_positionvars($phase,$bodnum,$mapnum) [lindex $rb_map 3]
+     set ::rb_map_damping($phase,$bodnum,$mapnum) [lindex $rb_map 4]
+     set ::rb_map_tls($phase,$bodnum,$mapnum) [lindex $rb_map 5]
+     set ::rb_map_tls_var($phase,$bodnum,$mapnum) [lindex $rb_map 6]
+     set ::rb_map_tls_damp($phase,$bodnum,$mapnum) [lindex $rb_map 7]
+}
+
+#############################################
+#   rcb     .a               initial rigid body control panel.
+#   panelnum                 the notebook panel to be accessed.
+#::rb_notebook              the notebook containing all rigid body panels.
+
+proc RB_Control_Panel {panelnum args} {
+     #set rcb .a
+     #destroy $rcb
+     #catch {toplevel $rcb} err
+     set rcb $::expgui(rbFrame)
+     eval destroy [winfo children $rcb]
+     #wm title $rcb "Rigid Body Control Panel"
+     #wm geometry $rcb 700x600+10+10
+     set rb_nb $rcb.nb
+
+     # Enable NoteBook from BWidget package
+
+     set ::rb_notebook [NoteBook $rb_nb -side bottom]
+     # loop over rigid body types, create notebook pages
+     set pagelist {}
+
+     # add create rigid body page and populate page
+     $::rb_notebook insert 0 rb_body0 -text "Create Rigid Body" \
+     -raisecmd "RB_Create"
+     lappend pagelist rb_body0
+
+
+     foreach bodnum [RigidBodyList] {
+         $::rb_notebook insert $bodnum rb_body$bodnum -text "Rigid Body Type $bodnum"  \
+         -raisecmd "RB_Populate $::rb_notebook $bodnum"
+	lappend pagelist rb_body$bodnum
+     }
+
+    # grid notebook
+    grid $::rb_notebook -sticky news -column 0 -row 1 -columnspan 2
+    grid columnconfig $rcb 1 -weight 1
+    grid rowconfig    $rcb 1 -weight 1
+    $::rb_notebook raise [lindex $pagelist $panelnum]
+}
+
+############################################
+# Procedure to create new rigid body
+
+proc RB_Create {args} {
+     RB_Import_Data_Type
+     $::rb_notebook raise [$::rb_notebook page 0]
+     #sets the new rigidbody number
+     set bodnum [expr [llength [RigidBodyList]] + 1]
+     #sets the phase list
+     set phase $::expmap(phaselist)
+     set pane [$::rb_notebook getframe rb_body0]
+     eval destroy [winfo children $pane]
+     set con0 $pane.con0
+     #set con1 $pane.con1
+     #set con2 $pane.con2
+     #set con3 $pane.con3
+
+     #initialize matrix number, multiplier and number of coordinates
+     set ::rb_matrix_num($bodnum) 1
+     set ::rb_mult($bodnum,1) 1.000
+
+     if {[info vars ::rb_coord_num($bodnum,1)] == ""} {set ::rb_coord_num($bodnum,1) 1}
+
+     #set check variables to see if number of matricies or coordinates incremented.
+     set ::rb_mat_num_check 0
+     set ::rb_atom_num_check 0
+
+     #building rigid body creation frames
+     pack [frame $con0 -bd 2 -relief groove] -side top -pady 10
+
+     set ::rb_loader(manual) NewBodyTypeWindow
+     set ::rb_descriptor(manual) "Manual Input"
+
+
+     set filedescriptors ""
+     set filearray [array names ::rb_descriptor]
+     foreach file $filearray {
+             lappend filedescriptors $::rb_descriptor($file)
+     }
+
+     set filecount 0
+     set ::rb_file_loader "Choose Method"
+     grid [label $con0.lbl -text "How are rigid body coordinates \n to be entered?"] -row 0 -column 0 -sticky ns
+     set menu [eval tk_optionMenu $con0.filematrix ::rb_file_loader $filedescriptors]
+         foreach file $filearray {
+                 $menu entryconfig $filecount -command "eval $::rb_loader($file)"
+                 incr filecount
+         }
+     $con0.filematrix configure -width 50
+     grid $con0.filematrix -row 0 -column 1
+
+}
+
+############################################################
+#procedure to create tables of cartesian coordinates
+
+proc RB_Create_Cart {bodnum location args} {
+     if {$::rb_matrix_num($bodnum) == $::rb_mat_num_check && $::rb_coord_num($bodnum,1) == $::rb_atom_num_check} {return}
+     if {[catch {expr $::rb_matrix_num($bodnum)}] == 1 || [catch {expr $::rb_coord_num($bodnum,1)}] == 1} {return}
+     if {$::rb_matrix_num($bodnum) != int($::rb_matrix_num($bodnum)) || $::rb_coord_num($bodnum,1) != int($::rb_coord_num($bodnum,1)) } {return}
+     eval destroy [winfo children $location]
+     foreach {top main side lbl} [MakeScrollTable $location] {}
+     set ::rb_atom_num_check $::rb_coord_num($bodnum,1)
+     set ::rb_mat_num_check $::rb_matrix_num($bodnum)
+     set col 0
+     grid [label $top.multilbl -text "Matrix Multiplier"] -row 1 -column 0
+#     grid [label $top.damplbl -text "Damping Factor"] -row 2 -column 0
+     for {set matrixnum 1} {$matrixnum <= $::rb_matrix_num($bodnum)} {incr matrixnum} {
+          grid [label $top.matlbl$matrixnum -text "Matrix $matrixnum"] -row 0 -column [expr $col + 2]
+          grid [entry $top.multi$matrixnum -textvariable ::rb_mult($bodnum,$matrixnum) -width 7 -takefocus 1] -row 1 -column [expr $col +2]
+#          puts "in RB_Create_Cart damp = $::rb_damp($bodnum,$matrixnum)"
+
+#          set dampfactors "0 1 2 3 4 5 6 7 8 9"
+#          eval tk_optionMenu $top.damp$matrixnum ::rb_damp($bodnum,$matrixnum) $dampfactors
+#          grid $top.damp$matrixnum -row 2 -column [expr $col +2]
+#          $top.damp$matrixnum config -width 4
+
+
+#          grid [entry $top.damp$matrixnum -textvariable ::rb_damp($bodnum,$matrixnum) -width 7 -takefocus 1] -row 2 -column  [expr $col +2]
+
+
+          if {$::rb_mult($bodnum,$matrixnum) == ""} {set ::rb_mult($bodnum,$matrixnum) 1.000}
+#          if {$::rb_damp($bodnum,$matrixnum) == ""} {set ::rb_damp($bodnum,$matrixnum) 0}
+
+          grid [label $main.x$matrixnum -text "X"] -row 0 -column [expr $col + 1]
+          grid [label $main.y$matrixnum -text "Y"] -row 0 -column [expr $col + 2]
+          grid [label $main.z$matrixnum -text "Z"] -row 0 -column [expr $col + 3]
+          grid [label $main.b$matrixnum -text "    "] -row 0 -column [expr $col +4]
+          incr col 4
+     }
+
+     for {set coordnum 0} {$coordnum <= [expr $::rb_coord_num($bodnum,1) - 1]} {incr coordnum} {
+          grid [label $main.lbl$coordnum -text "Site [expr $coordnum + 1]"] -row [expr $coordnum+10] -column 0
+          set col 0
+          for {set matrixnum 1} {$matrixnum <= $::rb_matrix_num($bodnum)} {incr matrixnum} {
+              grid [entry $main.x($matrixnum,$coordnum) -textvariable ::rb_x($bodnum,$matrixnum,$coordnum) -width 8 -takefocus 1] -row [expr $coordnum+10] -column [expr $col + 1]
+              if {$::rb_x($bodnum,$matrixnum,$coordnum) == ""} {set ::rb_x($bodnum,$matrixnum,$coordnum) 0}
+              grid [entry $main.y($matrixnum,$coordnum) -textvariable ::rb_y($bodnum,$matrixnum,$coordnum) -width 8 -takefocus 1] -row [expr $coordnum+10] -column [expr $col + 2]
+              if {$::rb_y($bodnum,$matrixnum,$coordnum) == ""} {set ::rb_y($bodnum,$matrixnum,$coordnum) 0}
+              grid [entry $main.z($matrixnum,$coordnum) -textvariable ::rb_z($bodnum,$matrixnum,$coordnum) -width 8 -takefocus 1] -row [expr $coordnum+10] -column [expr $col + 3]
+              if {$::rb_z($bodnum,$matrixnum,$coordnum) == ""} {set ::rb_z($bodnum,$matrixnum,$coordnum) 0}
+              grid [label $main.b($matrixnum,$coordnum) -text "    "] -row [expr $coordnum+10]  -column [expr $col +4]
+              incr col 4
+          }
+          ResizeScrollTable $location
+     }
+}
+########################################################
+# Procedure to save new rigid body to EXP file.
+
+proc RB_Create_Save {bodnum args} {
+     set temp_mat ""
+     set temp_car ""
+     set temp_mat_group ""
+     set temp_car_group ""
+     set total ""
+#     puts $::::rb_coord_num($bodnum,1)
+     for {set matrixnum 1} {$matrixnum <= $::rb_matrix_num($bodnum)} {incr matrixnum} {
+         lappend temp_mat $::rb_mult($bodnum,$matrixnum)
+     }
+
+     for {set matrixnum 1} {$matrixnum <= $::rb_matrix_num($bodnum)} {incr matrixnum} {
+         for {set coordnum 0} {$coordnum < $::rb_coord_num($bodnum,1)} {incr coordnum} {
+                  set temp_cart_triplet "$::rb_x($bodnum,$matrixnum,$coordnum) $::rb_y($bodnum,$matrixnum,$coordnum) $::rb_z($bodnum,$matrixnum,$coordnum)"
+                  lappend temp $temp_cart_triplet
+         }
+         lappend temp_car $temp
+     }
+#     puts "sites: $::rb_coord_num($bodnum,1)"
+#     puts "matrix multiplier:  $temp_mat"
+#     puts "cartesian coords:   $temp_car"
+     AddRigidBody $temp_mat $temp_car
+     RecordMacroEntry "AddRigidBody $temp_mat $temp_car" 0
+
+     incr ::expgui(changed)
+     destroy .nbt
+     RB_Load_RBdata
+     RB_Control_Panel $bodnum
+}
+
+###################################################
+# Procedures to delete rigid bodies
+
+proc RB_Delete_Body {bodnum location args} {
+     destroy $location.delete
+     set really $location.delete
+     toplevel $really
+     putontop $really
+     wm title $really "Delete Rigid Body"
+     grid [label $really.lbl -text "Confirm \n Is rigid body $bodnum to be deleted?"] -row 0 -column 0 -columnspan 2 -pady 15
+     grid [button $really.save -text "Delete" -bg red -command "RB_Delete_Body_Confirm $bodnum $location.delete"] \
+          -row 1 -column 0 -padx 5 -pady 5
+     grid [button $really.abort -text "Abort" -bg green -command "RB_Populate $::rb_notebook $bodnum; \
+     $::rb_notebook raise rb_body$bodnum"] -row 1 -column 1 \
+          -padx 5 -pady 5
+}
+
+proc RB_Delete_Body_Confirm {bodnum location args} {
+
+ #   unmap all instances of the rigid body
+     foreach phase $::expmap(phaselist) {
+             foreach mapnum [RigidBodyMappingList $phase $bodnum] {
+                     UnMapRigidBody $phase $bodnum $mapnum
+                     RecordMacroEntry "UnMapRigidBody $phase $bodnum $mapnum" 0
+             }
+     }
+#    puts "delete rigid body number $bodnum"
+     DeleteRigidBody $bodnum
+     RecordMacroEntry "DeleteRigidBody $bodnum" 0
+#    puts "destroy location $location"
+     destroy $location
+#    increment expgui
+     incr ::expgui(changed)
+     RB_Load_RBdata
+     RB_Control_Panel 0
+}
+
+############################################################
+# Procedure to populate notebook pages
+
+proc RB_Populate {rb_notebook bodnum args} {
+     RB_Load_RBdata
+     set ::rb_panel $bodnum
+     set phaselist $::expmap(phaselist)
+     # set notebook frame
+     set pane [$rb_notebook getframe rb_body$bodnum]
+     eval destroy [winfo children $pane]
+     set con $pane.con
+     grid [frame $con -bd 2 -relief groove] -row 0 -column 1 -pady 10
+
+     #Rigid body mapping control panel along with matrix multipliers and damping factor labels
+     grid [label  $con.rb_num -text "Rigid Body Type $bodnum"] -row 0 -column 0 -padx 5 -pady 5
+     grid [button $con.rb_newmap -text "Map Body $bodnum" -command "RB_Map_New $bodnum" -width 18] -row 0 -column 1 -padx 5 -pady 5
+     grid [button $con.rb_unmap -text "Unmap Body $bodnum" -command "RB_Unmap $bodnum" -width 18] -row 0 -column 2 -padx 5 -pady 5
+     button $con.rb_delete -text "Delete Body $bodnum" -command "RB_Delete_Body $bodnum $con.rb_delete" -width 18
+     grid   $con.rb_delete -row 4 -column 2 -padx 5 -pady 5
+
+     grid [label $con.rb_mlbl1 -text "Matrix"] -row 1 -column 0
+     grid [label $con.rb_mlbl2 -text "Multiplier"] -row 2 -column 0
+     grid [label $con.rb_mlbl3 -text "Damping Factor"] -row 3 -column 0
+     grid [button $con.plot -text "Plot Rigid Body" -command "PlotRBtype $bodnum" -width 18] -row 4 -column 0
+
+     set matrixnum 0
+     for {set mnum 1} {$mnum <= $::rb_matrix_num($bodnum)} {incr mnum} {
+        incr matrixnum
+        grid [label $con.rb_mm$mnum   -text "$mnum"]                -row 1 -column $matrixnum
+        grid [label $con.rb_mult$mnum -text "$::rb_mult($bodnum,$mnum)"] -row 2 -column $matrixnum
+        grid [label $con.rb_damp$mnum -text "$::rb_damp($bodnum,$mnum)"] -row 3 -column $matrixnum
+     }
+
+     button $con.rb_vmatrix -text "Edit Matrix" -command "RB_Edit_Matrix $bodnum" -width 18
+     grid   $con.rb_vmatrix -row 4 -column 1 -padx 5 -pady 5
+     grid [button $con.refine -text "Refinement \n Flags" -command "RB_Refine_Con" -width 18 ] -row 5 -column 1
+
+     # create header for mapping data
+     foreach {top main side lbl} [MakeScrollTable $pane] {}
+     grid [label $main.rb_origin -text "Origin"] -row 0 -column 3 -columnspan 3
+     grid [label $main.rb_euler -text "Euler Angles"] -row 0 -column 6 -columnspan 3
+     grid [label $main.rb_site -text "Sites"] -row 0 -column 10 -columnspan 3
+     grid [label $main.rb_ref -text "Phase"] -row 1 -column 2
+     grid [label $main.rb_map -text "Map"] -row 1 -column 1
+     grid [label $main.rb_x   -text "x"] -row 1 -column 3
+     grid [label $main.rb_y   -text "y"] -row 1 -column 4
+     grid [label $main.rb_z   -text "z"] -row 1 -column 5
+     grid [label $main.rb_euler_x -text "x"] -row 1 -column 6
+     grid [label $main.rb_euler_y -text "y"] -row 1 -column 7
+     grid [label $main.rb_euler_z -text "z"] -row 1 -column 8
+     set col 11
+     for {set coordnum 1} {$coordnum <= $::rb_coord_num($bodnum,1)} {incr coordnum} {
+        label $main.rb_site$coordnum -text "$coordnum"
+        grid $main.rb_site$coordnum -row 1 -column $col -padx 5
+        incr col
+     }
+
+     # populate mapping data table
+     set row 2
+     foreach phase $phaselist {
+             incr row
+	     foreach mapnum [RigidBodyMappingList $phase $bodnum] {
+                      set row [expr $row + $mapnum]
+                      RB_Load_Mapdata $phase $bodnum $mapnum
+                      grid [label $main.rb_map$phase$mapnum -text "$mapnum"] -row $row -column 1
+                      grid [label $main.rb_cb$phase$mapnum -text $phase] -row $row -column 2
+                      set origin $::rb_map_origin($phase,$bodnum,$mapnum)
+
+                      grid [label $main.rb_x$phase$mapnum   -text "[format %1.3f [lindex $origin 0]]"] -row $row -column 3 -padx 5
+                      grid [label $main.rb_y$phase$mapnum   -text "[format %1.3f [lindex $origin 1]]"] -row $row -column 4 -padx 5
+                      grid [label $main.rb_z$phase$mapnum   -text "[format %1.3f [lindex $origin 2]]"] -row $row -column 5 -padx 5
+                      set euler $::rb_map_euler($phase,$bodnum,$mapnum)
+                      for {set j 0} {$j < 3} {incr j} {
+                                  set euler1 [lindex $euler $j]
+                                  set angle  [lindex $euler1 0]
+                                  set axis   [lindex $euler1 1]
+                                  label $main.rb_euler_$phase$mapnum$axis -text "[format %1.2f $angle]"
+                      }
+
+                      grid [label $main.rb_tls$phase$mapnum -text "     "] -row $row -column 9
+                      set q 1
+                      grid $main.rb_euler_$phase$mapnum$q -row $row -column 6  -padx 5
+                      set q 2
+                      grid $main.rb_euler_$phase$mapnum$q -row $row -column 7 -padx 5
+                      set q 3
+                      grid $main.rb_euler_$phase$mapnum$q -row $row -column 8 -padx 5
+                      set col 11
+                      set atomnum $::rb_map_beginning($phase,$bodnum,$mapnum)
+                      for {set coordnum 1} {$coordnum <=$::rb_coord_num($bodnum,1)} {incr coordnum} {
+                          set atom [atominfo $phase $atomnum label]
+                          grid [label $main.rb_site$phase$mapnum$coordnum -text "$atom"] -row $row -column $col -padx 5
+                          incr atomnum
+                          incr col
+                      }
+             }
+     incr row
+     }
+     ResizeScrollTable $pane
+}
+
+proc DisplayRB {} {     ;# called each time the panel is raised
+    eval destroy [winfo children $::expgui(rbFrame)]
+     RB_Load_RBdata
+     RB_Control_Panel 0
+    #label $::expgui(rbFrame).l -text "RB Parameters"
+    #grid $::expgui(rbFrame).l -column 1 -row 1
+    ResizeNotebook
+}
+
+proc MakeRBPane {} {     ;# called to create the panel intially
+#    label $::expgui(rbFrame).l -text "RB Parameters"
+#    grid $::expgui(rbFrame).l -column 1 -row 1
+#    ResizeNotebook
+}
+
+#######################################################################
+# New Mapping Event
+# not updated
+
+proc RB_Map_New {bodnum args} {
+    catch {unset ::rb_firstatom}
+    set ::rb_firstatom ""
+    set ::body_type $bodnum
+    catch {destroy .newmap}
+    set nm .newmap
+    toplevel $nm
+    putontop $nm
+    wm title $nm "Map Rigid Body #$bodnum"
+
+    foreach item [trace vinfo ::rb_phase] {
+            eval trace vdelete ::rb_phase $item
+    }
+
+    set ::rb_phase [lindex $::expmap(phaselist) 0]
+    set nmap [expr $::rb_map($bodnum) + 1]
+    eval tk_optionMenu $nm.pinput ::rb_phase $::expmap(phaselist)
+    grid [label $nm.phase -text "Phase: "] -row 3 -column 1
+    grid [label $nm.f_atom -text "Choose first atom Number"] -row 4 -column 1
+    grid [label $nm.origin -text "input origin in fractional coordinates: "] -row 6 -column 1
+    grid [label $nm.euler -text "input Euler angles: "] -row 7 -column 1
+    grid [entry $nm.finputm -textvariable ::rb_firstatom -width 8 -takefocus 1] -row 4 -column 2
+
+    foreach item [trace vinfo ::rb_firstatom] {
+            eval trace vdelete ::rb_firstatom $item
+    }
+    trace variable ::rb_firstatom w "RB_Atom_List \$::rb_phase \$::rb_firstatom $nm $bodnum"
+
+    grid [button $nm.finput -text "list allowed" -command "RB_Choose_Atom $bodnum"] -row 4 -column 3
+    grid [label $nm.o1l -text "x"] -row 5 -column 2
+    grid [label $nm.o2l -text "y"] -row 5 -column 3
+    grid [label $nm.o3l -text "z"] -row 5 -column 4
+
+    set ::origin1 0
+    set ::origin2 0
+    set ::origin3 0
+    set ::euler1 0
+    set ::euler2 0
+    set ::euler3 0
+
+    grid [entry $nm.o1 -width 8 -textvariable ::origin1 -takefocus 1] -row 6 -column 2
+    grid [entry $nm.o2 -width 8 -textvariable ::origin2 -takefocus 1] -row 6 -column 3
+    grid [entry $nm.o3 -width 8 -textvariable ::origin3 -takefocus 1] -row 6 -column 4
+    grid [entry $nm.e1 -width 8 -textvariable ::euler1 -takefocus 1] -row 7 -column 2
+    grid [entry $nm.e2 -width 8 -textvariable ::euler2 -takefocus 1] -row 7 -column 3
+    grid [entry $nm.e3 -width 8 -textvariable ::euler3 -takefocus 1] -row 7 -column 4
+
+    grid $nm.pinput -row 3 -column 3
+
+    grid [frame $nm.p] -row 8 -column 1 -columnspan 4 -sticky e
+    grid [button $nm.p.fit -text "Fit rigid body to phase" -command "RB_FitBody2Coords $bodnum $nm; RB_View_RMS $nm"] -row 0 -column 1
+    grid [button $nm.p.plot -text "Plot rigid body & phase" -command "RB_PlotStrBody $bodnum $nm"] -row 1 -column 1
+    grid [label $nm.p.l -text "Bonds: "] -row 1 -column 2
+    grid [entry $nm.p.e] -row 1 -column 3
+    $nm.p.e delete 0 end
+    $nm.p.e insert 0 "0.9-1.1, 1.3-1.6"
+
+    grid [frame $nm.l] -row 9 -column 2 -columnspan 3
+    grid [button $nm.l.s -text "map update" -width 12 -command {RB_Write_Map}] -column 1 -row 1
+    grid [button $nm.l.q -text "Abort" -width 6 -command "destroy $nm"] -column 2  -row 1
+
+    foreach item [trace vinfo ::rb_phase] {
+            eval trace vdelete ::rb_phase $item
+    }
+    trace variable ::rb_phase w "RB_ProcessPhase $bodnum"
+}
+
+proc RB_View_RMS {address args} {
+     set addrms $address.rms
+     catch {destroy $addrms}
+     grid [frame $addrms -bd 2] -row 5 -column 8 -columnspan 99 -rowspan 99
+     set row 1
+
+     grid [label $addrms.atomlbl -text "   atom"] -row 0 -column 0
+     grid [label $addrms.rmslbl -text "\t rms"] -row 0 -column 1
+     foreach i $::rb_atom_rms {
+             set atom [lindex $i 0]
+             set temp [lindex $i 1]
+             set rms [format %.3f $temp]
+             set id [string tolower $atom]
+             grid [label $addrms.$id$row -text "   $atom"] -row $row -column 0
+             grid [label $addrms.rms$id$row -text "\t $rms"] -row $row -column 1
+             incr row
+     }
+}
+
+###########################################################
+# Procedure for choosing first atom during mapping event.
+# not updated
+
+proc RB_Choose_Atom {bodnum args} {
+    set phase $::rb_phase
+    # get the number of atoms in this type of body
+    set natoms [llength [lindex [lindex [lindex [ReadRigidBody $bodnum] 1] 0] 3]]
+    set atomlist [RigidStartAtoms $::rb_phase $natoms]
+    if {[llength $atomlist] == 0} {
+	RB_ProcessPhase $bodnum
+	return
+    }
+     catch {destroy .chooseatom}
+     set ca .chooseatom
+     toplevel $ca
+     wm title $ca "Choose Atom"
+#     puts $atomlist
+     foreach {top main side lbl} [MakeScrollTable $ca] {}
+     set row 0
+     set column 0
+     foreach atom $atomlist {
+        set label "[atominfo $phase $atom label] \($atom\)"
+        button $main.$atom -text $label -command "set ::rb_firstatom $atom; destroy $ca"
+        incr row
+        if {$row > 5} {
+           set row 1
+           incr column
+        }
+      grid $main.$atom -row $row -column $column -padx 5 -pady 5
+      }
+      ResizeScrollTable $ca
+      putontop $ca
+      tkwait window $ca
+      afterputontop
+      raise .newmap
+}
+
+##########################################################
+##########################################################
+
+proc RB_FitBody2Coords {bodnum menu} {
+    set warn ""
+    foreach i {1 2 3} lbl {x y z} {
+	if {[string trim [set ::euler$i]] == ""} {
+	    set ::euler$i 0.0
+	}
+	if {[string trim [set ::origin$i]] == ""} {
+	    set ::origin$i .0
+	}
+	if {[catch {expr [set ::euler$i]}]} {
+	    append warn "\tError in Euler angle around $lbl\n"
+	}
+	if {[catch {expr [set ::origin$i]}]} {
+	    append warn "\tError in origin $lbl\n"
+	}
+    }
+    if {[catch {expr $::rb_firstatom}]} {
+	append warn "\tError in 1st atom number\n"
+    }
+    if {$warn != ""} {
+	MyMessageBox -parent $menu -title "Input error" \
+		-message "Invalid input:\n$warn" -icon warning
+	return
+    }
+    set Euler [list "1 $::euler1" "2 $::euler2" "3 $::euler3"]
+    set origin "$::origin1 $::origin2 $::origin3"
+    set phase $::rb_phase
+    set cell {}
+    foreach p {a b c alpha beta gamma} {
+	lappend cell [phaseinfo $phase $p]
+    }
+    set coords [RB2cart [lindex [ReadRigidBody $bodnum] 1]]
+    set natom [llength $coords]
+    set firstind [lsearch $::expmap(atomlist_$phase) $::rb_firstatom]
+    set atoms [lrange \
+		   [lrange $::expmap(atomlist_$phase) $firstind end] \
+		   0 [expr {$natom-1}]]
+    # now loop over atoms
+    set frcoords {}
+    foreach atom $atoms {
+	set xyz {}
+	foreach v {x y z} {
+	    lappend xyz [atominfo $phase $atom $v]
+	}
+	lappend frcoords $xyz
+    }
+    # it would be nice to have checkboxes for each atom, but for now use em all
+    set useflags {}
+    foreach i $coords {lappend useflags 1}
+#    puts "frcoords $frcoords"
+#    puts "coords $coords"
+    # do the fit
+    foreach {neworigin newEuler rmsdev newfrac rmsbyatom} \
+	[FitBody $Euler $cell $coords $useflags $frcoords $origin] {}
+    foreach i {1 2 3} val $neworigin pair $newEuler {
+	set ::origin$i $val
+	set ::euler$i [lindex $pair 1]
+    }
+    # show deviations
+
+    set ::rb_atom_rms ""
+    foreach atom $atoms rms $rmsbyatom {
+#	puts "[atominfo $phase $atom label]\t$rms"
+	lappend ::rb_atom_rms "[atominfo $phase $atom label] $rms"
+    }
+    #puts "CalcBody $Euler $cell $coords $origin"
+    #puts $coords
+    #puts $frcoords
+    #DRAWxtlPlotRBFit $frcoords $phase $::rb_firstatom 0 $bondlist $bondlist
+ }
+
+proc RB_PlotStrBody {bodnum menu} {
+    set warn ""
+    foreach i {1 2 3} lbl {x y z} {
+	if {[catch {expr [set ::euler$i]}]} {
+	    append warn "\tError in Euler angle around $lbl\n"
+	}
+	if {[catch {expr [set ::origin$i]}]} {
+	    append warn "\tError in origin $lbl\n"
+	}
+    }
+    if {[catch {expr $::rb_firstatom}]} {
+	append warn "\tError in 1st atom number\n"
+    }
+    if {$warn != ""} {
+	MyMessageBox -parent $menu -title "Input error" \
+		-message "Invalid input:\n$warn" -icon warning
+	return
+    }
+    # translate bond list
+    set bl [$menu.p.e get]
+    regsub -all "," $bl " " bl
+    set bondlist {}
+    set warn ""
+    foreach b $bl {
+	if {[llength [split $b "-"]] == 2} {
+	    lappend bondlist [split $b "-"]
+	} else {
+	    set warn "error parsing bond list"
+	}
+    }
+    if {$warn != ""} {
+	MyMessageBox -parent . -title "Input warning" \
+		-message "Invalid bond input" -icon warning
+    }
+     set Euler [list "1 $::euler1" "2 $::euler2" "3 $::euler3"]
+     set origin "$::origin1 $::origin2 $::origin3"
+     set phase $::rb_phase
+     set cell {}
+     foreach p {a b c alpha beta gamma} {
+	lappend cell [phaseinfo $phase $p]
+    }
+    set coords [RB2cart [lindex [ReadRigidBody $bodnum] 1]]
+    set frcoords [CalcBody $Euler $cell $coords $origin]
+    #puts "CalcBody $Euler $cell $coords $origin"
+    #puts $coords
+    #puts $frcoords
+    DRAWxtlPlotRBFit $frcoords $phase $::rb_firstatom 0 $bondlist $bondlist
+ }
+#
+
+proc RB_Write_Map {args} {
+   if {$::rb_firstatom == ""} {
+      MyMessageBox -title "warning" -message "The first atom for the rigid body must be choosen to update mapping"
+      return
+   }
+   set origin "$::origin1 $::origin2 $::origin3"
+   set euler "$::euler1 $::euler2 $::euler3"
+#   puts "phase = $::rb_phase"
+#   puts "bodnum = $::body_type"
+#   puts "firstatom = $::rb_firstatom"
+#   puts "position = $origin"
+#   puts "Euler = $euler"
+   MapRigidBody $::rb_phase $::body_type $::rb_firstatom $origin $euler
+   RecordMacroEntry "MapRigidBody $::rb_phase $::body_type $::rb_firstatom $origin $euler" 0
+   incr ::rb_map($::body_type)
+   incr ::expgui(changed)
+   set curpage [$::rb_notebook raise]
+   $::rb_notebook raise [$::rb_notebook page end]
+   $::rb_notebook raise $curpage
+   destroy .newmap
+   RunRecalcRBCoords
+   incr ::expgui(changed)
+   RB_Populate $::rb_notebook $::body_type
+   $::rb_notebook raise rb_body$::body_type
+}
+
+proc RB_Atom_List {phase atomnum address bodnum args} {
+     foreach w [winfo children $address] {
+             if {[string first ".atom" $w] != -1} {destroy $w}
+     }
+     set col 8
+    if {$atomnum == ""} return
+    grid [label $address.atomlbl -text "Atoms Mapped to Rigid Body"] -row 3 -column 8 -columnspan 99
+    # get the number of atoms in this type of body
+    set natoms [llength [lindex [lindex [lindex [ReadRigidBody $bodnum] 1] 0] 3]]
+    set atoms [RigidStartAtoms $phase $natoms]
+    if {[lsearch $atoms $atomnum] == -1} {
+         grid [label $address.atomerr -text "(invalid 1st atom)"] -row 4 -column $col
+	return
+    }
+    set atoms [lrange $::expmap(atomlist_$phase) \
+		   [lsearch $::expmap(atomlist_$phase) $atomnum] end]
+    foreach j [lrange $atoms 0 [expr {$natoms - 1}]] {
+	set atom [atominfo $phase $j label]
+	grid [label $address.atom$phase$bodnum$j -text $atom] -row 4 -column $col
+	incr col
+     }
+}
+
+proc RB_ProcessPhase {bodnum args} {
+    if {$::rb_phase == ""} {
+	set atoms {}
+    } else {
+	# get the number of atoms in this type of body
+	set natoms [llength [lindex [lindex [lindex [ReadRigidBody $bodnum] 1] 0] 3]]
+
+	set atoms [RigidStartAtoms $::rb_phase $natoms]
+    }
+    set nm .newmap
+    if {[llength $atoms] == 0} {
+	foreach w "$nm.finputm $nm.p.plot $nm.p.fit $nm.p.e $nm.l.s" {
+	    $w config -state disabled
+	}
+	$nm.finput config -text "None allowed" -state disabled
+    } else {
+	foreach w "$nm.finputm $nm.p.plot $nm.p.fit $nm.p.e $nm.l.s" {
+	    $w config -state normal
+	}
+	$nm.finput config -text "Show allowed" -state normal
+    }
+}
+
+proc RB_Unmap {bodnum args} {
+    catch {unset ::rb_firstatom}
+    set ::rb_firstatom ""
+    set ::body_type $bodnum
+    catch {destroy .unmap}
+    set um .unmap
+    toplevel $um
+    putontop $um
+    wm title $um "Map Rigid Body #$bodnum"
+    set ::phase 1
+    set umap $::rb_map($bodnum)
+#    eval tk_optionMenu $um.pinput ::rb_phase $::expmap(phaselist)
+#    grid [label $um.phase -text "Phase: "] -row 3 -column 1
+#    grid $um.pinput -row 3 -column 2
+
+    set mapnumber $::rb_map($bodnum)
+    set unpane $um.pane
+    foreach {top main side lbl} [MakeScrollTable $um] {}
+    grid [label $main.cb -text "unmap"] -row 1 -column 0 -padx 5
+    grid [label $main.map -text "map"] -row 1 -column 1 -padx 5
+    grid [label $main.ph -text "Phase"] -row 1 -column 2 -padx 5
+    set matrixnum $::rb_matrix_num($bodnum)
+    for {set coordnum 1} {$coordnum <= $::rb_coord_num($bodnum,$matrixnum)} {incr coordnum} {
+        label $main.rb_site$coordnum -text "Site $coordnum"
+        grid $main.rb_site$coordnum -row 1 -column [expr 2 + $coordnum]
+    }
+    set row 2
+    foreach phase $::expmap(phaselist) {
+        incr row
+	foreach coordnum [RigidBodyMappingList $phase $bodnum] {
+                set row [expr $row + $coordnum]
+                RB_Load_Mapdata $phase $bodnum $coordnum
+                checkbutton $main.unmap$phase$coordnum -variable ::rb_unmap($phase,$bodnum,$coordnum)
+                grid $main.unmap$phase$coordnum -row $row -column 0
+                grid [label $main.rb_map$phase$coordnum -text "$coordnum"] -row $row -column 1
+                grid [label $main.rb_cb$phase$coordnum -text $phase] -row $row -column 2
+                      set atomnum $::rb_map_beginning($phase,$bodnum,$coordnum)
+                      set col 3
+                      for {set j 1} {$j <=$::rb_coord_num($bodnum,$matrixnum)} {incr j} {
+                          set atom [atominfo $phase $atomnum label]
+                          grid [label $main.rb_site$phase$coordnum$j -text "$atom"] -row $row -column $col
+                          incr atomnum
+                          incr col
+                      }
+             }
+     incr row
+     }
+     ResizeScrollTable $um
+
+     grid [frame $um.update -bd 2 -relief groove] -row 0 -column 1 -pady 10
+     button $um.update.con -text "Update Rigid Body Mapping" -command "RB_unmap_delete $um $bodnum"
+     button $um.update.abort -text "Abort" -command "destroy $um"
+     grid $um.update.con -row 0 -column 0 -padx 5 -pady 5
+     grid $um.update.abort -row 0 -column 1
+     incr ::expgui(changed)
+
+}
+
+proc RB_unmap_delete {panel bodnum args} {
+#     puts $panel
+     foreach phase $::expmap(phaselist) {
+        foreach mapnum [RigidBodyMappingList $phase $bodnum] {
+                if {$::rb_unmap($phase,$bodnum,$mapnum) == 1} {
+                   UnMapRigidBody $phase $bodnum $mapnum
+                   RecordMacroEntry "MapRigidBody $::rb_phase $::body_type $::rb_firstatom $origin $euler" 0
+                }
+        }
+        incr ::expgui(changed)
+        destroy $panel
+        set curpage [$::rb_notebook raise]
+        RB_Populate $::rb_notebook $bodnum
+        $::rb_notebook raise rb_body$bodnum
+     }
+}
+
+proc RB_Create_from_Edit {args} {
+     set bodnum [RB_New_RBnum]
+     RB_Create_Save $bodnum
+}
+
+
+
+proc RB_Edit_Matrix {bodnum args} {
+#     puts "Bodnum = $bodnum"
+     catch {destroy .viewmatrix}
+     set em .viewmatrix
+     toplevel $em
+     putontop $em
+     wm title $em "Edit Matrices for Rigid Body $bodnum"
+
+     set vm $em.entry
+     set um $em.update
+     set sm $em.sort
+     grid [frame $vm -bd 2 -relief groove] -row 0 -column 0 -columnspan 2
+     grid [frame $sm -bd 2 -relief groove] -row 1 -column 0 -columnspan 2 -pady 10
+     grid [frame $um -bd 2 -relief groove] -row 2 -column 0 -columnspan 2
+
+#    Editor Options
+     grid [label $sm.title -text "Matrix Editor Control Panel"] -row 0 -column 0 -columnspan 4
+     grid [label $sm.sort -width 21 -text "Move Checked Elements"] -row 1 -column 0
+     grid [button $sm.inc -text "\u2191" -command "RB_Sort_Inc $bodnum inc"] -row 1 -column 1 -padx 5
+     grid [button $sm.dec -text "\u2193" -command "RB_Sort_Inc $bodnum dec"] -row 1 -column 2 -padx 5
+     grid [button $sm.swap -width 21 -text "Swap Checked Elements" -command "RB_Sort_Swap $bodnum"] -row 2 -column 0 -columnspan 3
+     grid [button $sm.delete -width 21 -text "Delete Checked Elements" -command "RB_Delete_Element $bodnum"] -row 3 -column 0 -columnspan 3
+     grid [button $sm.add   -width 21 -text "Add New Matrix Elements" -command "RB_Add_Element $bodnum"] -row 4 -column 0 -columnspan 3
+     grid [button $sm.addmatrix -width 21 -text "Add New Matrix" -command "RB_Add_New_Matrix $bodnum"] -row 5 -column 0 -columnspan 3
+
+#    Save Options
+     grid [button $um.update -width 24 -text "Update Matrix Info" -bg green -command "RB_Matrix_Update $bodnum"] -row 3 -column 0 -padx 5
+     grid [button $um.new -width 24 -text "New Rigid Body Type" -command "RB_Create_from_Edit"] -row 0 -column 1 -padx 5
+ #    grid [button $um.sort -text "Sort Matrix Info" -command "RB_Cart_Sort $bodnum"] -row 0 -column 1
+
+     grid [button $um.print -width 24 -text "Save Cartesian \n Coordinates to File" -command "RB_CartesianTextFile $bodnum"] -row 2 -column 1 -pady 5
+     grid [button $um.restore -width 24 -text "Restore Original Matrix" -command "RB_Restore_Matrix $bodnum"] -row 3 -column 1 -padx 5
+     grid [button $um.abort -text "Abort" -width 24 -command "RB_Edit_Matrix_Abort $bodnum $em"] -row 3 -column 2 -padx 5
+
+     grid [label $vm.lblmm -text "Matrix Multiplier"] -row 3 -column 2
+     grid [label $vm.lbldamp -text "Damping Factor"] -row 4 -column 2
+     grid [label $vm.lblvar -text "Refine Multiplier"] -row 5 -column 2
+
+     set w 1
+     grid [label $vm.site -text "sort"] -row 6 -column 0 -columnspan 2
+
+
+     for {set coordnum 0} {$coordnum < $::rb_coord_num($bodnum,$w)} {incr coordnum} {
+         grid [checkbutton $vm.sort$coordnum -variable ::rb_sort($coordnum)] -row [expr $coordnum + 7] -column 1
+         grid [label $vm.lbls$coordnum -text "Site [expr $coordnum + 1]"] -row [expr $coordnum + 7] -column 2
+     }
+     set col 3
+     for {set matrixnum 1} {$matrixnum <= $::rb_matrix_num($bodnum)} {incr matrixnum} {
+         grid [label $vm.lblm$matrixnum -text "Matrix #$matrixnum"] -row 2 -column [expr $col +1]
+         grid [entry $vm.mult$matrixnum -textvariable ::rb_mult($bodnum,$matrixnum) -width 8 -takefocus 1] -row 3 -column [expr $col + 1]
+         set dampfactors "0 1 2 3 4 5 6 7 8 9"
+         eval tk_optionMenu $vm.damp$matrixnum ::rb_damp($bodnum,$matrixnum) $dampfactors
+         grid $vm.damp$matrixnum -row 4 -column [expr $col + 1]
+         $vm.damp$matrixnum config -width 4
+#         grid [entry $vm.damp$matrixnum -textvariable ::rb_damp($bodnum,$matrixnum) -width 8 -takefocus 1 -state normal] -row 4 -column [expr $col + 1]
+         grid [checkbutton $vm.var$matrixnum -variable ::rb_varcheck($bodnum,$matrixnum) -text $::rb_var($bodnum,$matrixnum) \
+              -state normal -command "RB_MMultRef $bodnum $matrixnum"] -row 5 -column [expr $col +1]
+
+         grid [label $vm.x$matrixnum -text "X"] -row 6 -column [expr $col]
+         grid [label $vm.y$matrixnum -text "Y"] -row 6 -column [expr $col + 1]
+         grid [label $vm.z$matrixnum -text "Z"] -row 6 -column [expr $col + 2]
+         for {set coordnum 0} {$coordnum < $::rb_coord_num($bodnum,$w)} {incr coordnum} {
+#             puts $::rb_coord($bodnum,$i,$j)
+
+              set ::rb_x($bodnum,$matrixnum,$coordnum) [lindex $::rb_coord($bodnum,$matrixnum,$coordnum) 0]
+              set ::rb_y($bodnum,$matrixnum,$coordnum) [lindex $::rb_coord($bodnum,$matrixnum,$coordnum) 1]
+              set ::rb_z($bodnum,$matrixnum,$coordnum) [lindex $::rb_coord($bodnum,$matrixnum,$coordnum) 2]
+              set ::rb_lbl($bodnum,$matrixnum,$coordnum) [lindex $::rb_coord($bodnum,$matrixnum,$coordnum) 3]
+
+
+             grid [entry $vm.lblcx$matrixnum$coordnum -textvariable ::rb_x($bodnum,$matrixnum,$coordnum) -width 8 -takefocus 1] -row [expr $coordnum+7] -column [expr $col]
+             grid [entry $vm.lblcy$matrixnum$coordnum -textvariable ::rb_y($bodnum,$matrixnum,$coordnum) -width 8 -takefocus 1] -row [expr $coordnum+7] -column [expr $col + 1]
+             grid [entry $vm.lblcz$matrixnum$coordnum -textvariable ::rb_z($bodnum,$matrixnum,$coordnum) -width 8 -takefocus 1] -row [expr $coordnum+7] -column [expr $col + 2]
+             grid [label $vm.lblcb$matrixnum$coordnum -text "    "] -row [expr  $coordnum+6] -column [expr $col + 3]
+         }
+     incr col 4
+     }
+}
+
+proc RB_Restore_Matrix {bodnum} {
+     set ::rb_matrix_num($bodnum) $::rb_matrix_num_temp($bodnum)
+     set ::rb_coord_num($bodnum,1) $::rb_coord_num_temp($bodnum,1)
+         for {set coordnum 0} {$coordnum < $::rb_coord_num($bodnum,1)} {incr coordnum} {
+             for {set matrixnum 1} {$matrixnum <= $::rb_matrix_num($bodnum)} {incr matrixnum} {
+                 set ::rb_coord($bodnum,$matrixnum,$coordnum) $::rb_coord_temp($bodnum,$matrixnum,$coordnum)
+
+             }
+     }
+RB_Edit_Matrix $bodnum
+}
+
+proc RB_Add_New_Matrix {bodnum} {
+     incr ::rb_matrix_num($bodnum)
+     set matrixnum $::rb_matrix_num($bodnum)
+     set ::rb_var($bodnum,$matrixnum) 0
+     set ::rb_mult($bodnum,$matrixnum) 1.000
+     for {set coordnum 0} {$coordnum < $::rb_coord_num($bodnum,1)} {incr coordnum} {
+         set ::rb_coord($bodnum,$matrixnum,$::rb_coord_num($bodnum,1) ""
+         lappend ::rb_coord($bodnum,$matrixnum,$coordnum) 0 0 0 lbl
+     }
+     RB_Edit_Matrix $bodnum
+
+
+}
+
+
+
+proc RB_Edit_Matrix_Abort {bodnum location} {
+#    reset matrix
+#     set ::rb_coord_num($bodnum,1) $::rb_coord_num_temp($bodnum,1)
+#     for {set matrixnum 1} {$matrixnum <= $::rb_matrix_num($bodnum)} {incr matrixnum} {
+#         for {set coordnum 0} {$coordnum < $::rb_coord_num_temp($bodnum,1)} {incr coordnum} {
+#             set ::rb_coord($bodnum,$matrixnum,$coordnum) $::rb_coord_temp($bodnum,$matrixnum,$coordnum)
+#         }
+#     }
+     destroy $location
+}
+
+proc RB_Add_Element {bodnum} {
+     incr ::rb_coord_num($bodnum,1)
+     for {set matrixnum 1} {$matrixnum <= $::rb_matrix_num($bodnum)} {incr matrixnum} {
+         set ::rb_coord($bodnum,$matrixnum,$::rb_coord_num($bodnum,1) ""
+         lappend ::rb_coord($bodnum,$matrixnum,[expr $::rb_coord_num($bodnum,1)- 1]) 0 0 0 lbl
+         puts $::rb_coord($bodnum,$matrixnum,[expr $::rb_coord_num($bodnum,1) - 1])
+     }
+     RB_Edit_Matrix $bodnum
+}
+
+proc RB_Delete_Element {bodnum} {
+
+     set newcoord 0
+     set deletedrecords 0
+
+     for {set coordnum 0} {$coordnum < $::rb_coord_num($bodnum,1)} {incr coordnum} {
+           for {set matrixnum 1} {$matrixnum <= $::rb_matrix_num($bodnum)} {incr matrixnum} {
+
+               if {$::rb_sort($coordnum) != 1} {
+                  set xtemp $::rb_x($bodnum,$matrixnum,$coordnum)
+                  set ytemp $::rb_y($bodnum,$matrixnum,$coordnum)
+                  set ztemp $::rb_z($bodnum,$matrixnum,$coordnum)
+                  set lbltemp [lindex $::rb_coord($bodnum,$matrixnum,$coordnum) 3]
+
+
+                  set ::rb_x($bodnum,$matrixnum,$newcoord) $xtemp
+                  set ::rb_y($bodnum,$matrixnum,$newcoord) $ytemp
+                  set ::rb_z($bodnum,$matrixnum,$newcoord) $ztemp
+                  puts "array element = $::rb_coord($bodnum,$matrixnum,$coordnum)"
+                  set ::rb_coord($bodnum,$matrixnum,$newcoord) ""
+                  puts "xyztemp = $xtemp $ytemp $ztemp $lbltemp"
+                  lappend ::rb_coord($bodnum,$matrixnum,$newcoord) $xtemp $ytemp $ztemp $lbltemp
+                  puts "goofy output = $::rb_coord($bodnum,$matrixnum,$newcoord)"
+                  incr newcoord
+               } else {
+                  incr deletedrecords
+               }
+           }
+     }
+     for {set coordnum 0} {$coordnum < $::rb_coord_num($bodnum,1)} {incr coordnum} {
+         set ::rb_sort($coordnum) 0
+     }
+     set tempcoord [expr $::rb_coord_num($bodnum,1) - $deletedrecords]
+     set ::rb_coord_num($bodnum,1) $tempcoord
+     RB_Edit_Matrix $bodnum
+}
+
+
+
+proc RB_VarNums {toggle {var ""} args} {
+#    initalize rigid body variable list if not already initialized
+#    toggle can be:
+#           add      This returns the smallest unused variable number
+#           sub ##   This removes variable ## from the varlist.
+
+     if {[info vars ::rb_varlist] == ""} {
+        set ::rb_varlist ""
+     }
+     if {$::rb_varlist == ""} {
+          set ::rb_varlist [RigidBodyGetVarNums]
+     }
+
+     if {$toggle == "add"} {
+          set count 1
+          while {[lsearch $::rb_varlist $count] > 0} {
+               incr count
+          }
+          lappend ::rb_varlist $count
+#          puts $::rb_varlist
+          return $count
+     }
+     if {$toggle == "sub"} {
+          set temp ""
+          foreach v $::rb_varlist {
+                  if {$v != $var} {
+                     lappend temp $v
+                  }
+          }
+          set ::rb_varlist $temp
+#          puts $::rb_varlist
+          return 0
+      }
+}
+
+proc RB_MMultRef {bodnum matrixnum args} {
+#    procedure sets or unsets the variable number for the matrix multiplier
+#     puts "boing:"
+     if {$::rb_varcheck($bodnum,$matrixnum) == "0"} {
+        set ::rb_var($bodnum,$matrixnum) [RB_VarNums sub $::rb_var($bodnum,$matrixnum)]
+     } else {
+        set ::rb_var($bodnum,$matrixnum) [RB_VarNums add]
+     }
+     destroy .viewmatrix
+     RB_Edit_Matrix $bodnum
+}
+
+proc RB_Sort_Swap {bodnum args} {
+     set count 0
+     set rb_swap_list ""
+     for {set coordnum 0} {$coordnum < $::rb_coord_num($bodnum,1)} {incr coordnum} {
+         if {$::rb_sort($coordnum) == 1} {
+            incr count
+            lappend rb_swap_list $coordnum
+         }
+     }
+     if {$count != 2} {
+#        puts "wrong number of arguments, swap failed"
+        bell
+        return
+     }
+#     puts "swap happens"
+#     puts $rb_swap_list
+     for {set i 1} {$i <= $::rb_matrix_num($bodnum)} {incr i} {
+         set coord1 [lindex $rb_swap_list 0]
+         set coord2 [lindex $rb_swap_list 1]
+         set x1dum $::rb_x($bodnum,$i,$coord1)
+         set y1dum $::rb_y($bodnum,$i,$coord1)
+         set z1dum $::rb_z($bodnum,$i,$coord1)
+         set ::rb_x($bodnum,$i,$coord1) $::rb_x($bodnum,$i,$coord2)
+         set ::rb_y($bodnum,$i,$coord1) $::rb_y($bodnum,$i,$coord2)
+         set ::rb_z($bodnum,$i,$coord1) $::rb_z($bodnum,$i,$coord2)
+         set ::rb_x($bodnum,$i,$coord2) $x1dum
+         set ::rb_y($bodnum,$i,$coord2) $y1dum
+         set ::rb_z($bodnum,$i,$coord2) $z1dum
+     }
+
+}
+
+proc RB_Sort_Inc {bodnum dir args} {
+     set sortlist ""
+     for {set count 0} {$count < $::rb_coord_num($bodnum,1)} {incr count} {
+         if {$::rb_sort($count) == 1} {
+            lappend sortlist $count
+         }
+     }
+#     puts $sortlist
+
+     foreach check $sortlist {
+             set checkup [expr $check - 1]
+             set checkdwn [expr $check + 1]
+             if {$checkup < 0} {
+                if {$dir == "inc"} {
+                   bell
+                   return
+                }
+             }
+             if {$checkdwn >= $::rb_coord_num($bodnum,1)} {
+                if {$dir == "dec"} {
+                   bell
+                   return
+                }
+             }
+     }
+     if {$dir == "dec"} {set sortlist [RB_String_Reverse $sortlist]}
+
+     for {set i 1} {$i <= $::rb_matrix_num($bodnum)} {incr i} {
+         foreach sort $sortlist {
+             if {$dir == "inc"} {set line1 [expr $sort - 1]}
+             if {$dir == "dec"} {set line1 [expr $sort + 1]}
+             set x1dum $::rb_x($bodnum,$i,$line1)
+             set y1dum $::rb_y($bodnum,$i,$line1)
+             set z1dum $::rb_z($bodnum,$i,$line1)
+             set ::rb_x($bodnum,$i,$line1) $::rb_x($bodnum,$i,$sort)
+             set ::rb_y($bodnum,$i,$line1) $::rb_y($bodnum,$i,$sort)
+             set ::rb_z($bodnum,$i,$line1) $::rb_z($bodnum,$i,$sort)
+             set ::rb_x($bodnum,$i,$sort) $x1dum
+             set ::rb_y($bodnum,$i,$sort) $y1dum
+             set ::rb_z($bodnum,$i,$sort) $z1dum
+
+             set ::rb_sort($sort) 0
+             if {$dir == "inc"} {set ::rb_sort([expr $sort - 1]) 1}
+             if {$dir == "dec"} {
+                foreach relabel $sortlist {
+                    set ::rb_sort([expr $relabel +1]) 1
+                }
+             }
+        }
+     }
+
+}
+
+proc RB_String_Reverse {string args} {
+#    puts "$string"
+    set rstring ""
+    set len [expr [llength $string] - 1]
+    while {$len > -1} {
+        lappend rstring [lindex $string $len]
+        incr len -1
+    }
+#    puts "contents of rstring = $rstring"
+    return $rstring
+}
+
+proc RB_Matrix_Update {bodnum args} {
+     set temp_mat ""
+     set temp_damp ""
+     set temp_var ""
+     set temp_car ""
+     set temp_mat_group ""
+     set temp_car_group ""
+     set total ""
+
+     for {set matrixnum 1} {$matrixnum <= $::rb_matrix_num($bodnum)} {incr matrixnum} {
+         set temp ""
+         lappend temp_mat $::rb_mult($bodnum,$matrixnum)
+         lappend temp_var $::rb_var($bodnum,$matrixnum)
+         lappend temp_damp $::rb_damp($bodnum,$matrixnum)
+#         puts "temp_damp = $::rb_damp($bodnum,$matrixnum)"
+         for {set atomnum 0} {$atomnum < $::::rb_coord_num($bodnum,1)} {incr atomnum} {
+             set temp_cart_triplet "$::rb_x($bodnum,$matrixnum,$atomnum) $::rb_y($bodnum,$matrixnum,$atomnum) $::rb_z($bodnum,$matrixnum,$atomnum)"
+             lappend temp $temp_cart_triplet
+         }
+         lappend temp_car $temp
+     }
+
+#     puts "Matrix Update Info = $bodnum $temp_mat $temp_car"
+#     puts "Matrix damping = $temp_damp"
+#     puts "Matrix vars = $temp_var"
+     SetRigidBodyVar $bodnum $temp_var $temp_damp
+     RecordMacroEntry "SetRigidBodyVar $bodnum $temp_var $temp_damp" 0
+     ReplaceRigidBody $bodnum $temp_mat $temp_car $temp_var $temp_damp
+     RecordMacroEntry "SetRigidBodyVar $bodnum $temp_var $temp_damp" 0
+     #SetRigidBodyVar $bodnum $temp_var $temp_damp
+     incr ::expgui(changed)
+     RB_Load_RBdata
+     RB_Control_Panel $bodnum
+     destroy .viewmatrix
+
+}
+
+
+proc GetImportFormats {} {
+    global expgui tcl_platform
+    # only needs to be done once
+    if [catch {set expgui(importFormatList)}] {
+	set filelist [glob -nocomplain [file join $expgui(scriptdir) import_*.tcl]]
+	foreach file $filelist {
+	    set description ""
+	    source $file
+	    if {$description != ""} {
+		lappend expgui(importFormatList) $description
+		if {$tcl_platform(platform) == "unix"} {
+		    set extensions "[string tolower $extensions] [string toupper $extensions]"
+		}
+		set expgui(extensions_$description) $extensions
+		set expgui(proc_$description) $procname
+	    }
+	}
+    }
+}
+
+proc NewBodyTypeWindow {} {
+     destroy .nbt
+     toplevel .nbt
+     putontop .nbt
+     set con1 .nbt.1
+     set con2 .nbt.2
+     set con3 .nbt.3
+
+     set bodnum [RB_New_RBnum]
+#     set bodnum [expr [llength [RigidBodyList]] + 1]
+     pack [frame $con1 -bd 2 -relief groove] -side top -pady 10
+     pack [frame $con2 -bd 2 -relief groove] -side top -expand 1 -fill both
+     pack [frame $con3 -bd 2 -relief groove] -side top
+     grid [label $con1.lbl -text "New Rigid Body Type $bodnum"] -row 0 -column 0
+     grid [label $con1.mat -text "Number of Matricies Describing Rigid Body"] -row 1 -column 0
+
+
+
+     spinbox $con1.matnum -from 1 -to 10 -textvariable ::rb_matrix_num($bodnum) -width 5 -command "RB_Create_Cart $bodnum $con2"
+     grid $con1.matnum -row 1 -column 1 -padx 10
+     grid [label $con1.atoms -text "Number of Cartesian Sites"] -row 2 -column 0
+     spinbox $con1.atomsnum -from 3 -to 1000 -textvariable ::rb_coord_num($bodnum,1) -width 5 -command "RB_Create_Cart $bodnum $con2"
+     grid $con1.atomsnum -row 2 -column 1 -padx 10
+
+
+     grid [button $con3.save -text "Save \n Rigid Body" -command "RB_Create_Save $bodnum"] -row 0 -column 2 -padx 5 -pady 5
+     grid [button $con3.print -text "Save Cartesian \n Coordinates to File" -command "RB_CartesianTextFile $bodnum"] -row 0 -column 3 -padx 5
+#     $con3.print configure -status disable
+     grid [button $con3.abort -text "Abort \n Rigid Body" -command "destroy .nbt; RB_Control_Panel end"] -row 0 -column 4 -padx 5 -pady 5
+
+     RB_Create_Cart $bodnum $con2
+
+     bind $con1.atomsnum <Leave> "RB_Create_Cart $bodnum $con2"
+     bind $con1.atomsnum <Return> "RB_Create_Cart $bodnum $con2"
+     bind $con1.matnum <Leave> "RB_Create_Cart $bodnum $con2"
+     bind $con1.matnum <Return> "RB_Create_Cart $bodnum $con2"
+}
+
+proc RB_Fixfrag_Load {args} {
+     destroy .geometry
+     toplevel .geometry
+     putontop .geometry
+     set geo .geometry
+
+
+     pack [frame $geo.con -bd 2 -relief groove] -side top
+     pack [frame $geo.display -bd 2 -relief groove] -side top -expand 1 -fill both
+     pack [frame $geo.con2 -bd 2 -relief groove] -side bottom
+#     pack [frame $geo.save -bd 2 -relief groove] -side bottom
+
+     wm title $geo "Fix Molecular Fragment from EXP File"
+     wm geometry $geo 800x400+10+10
+
+     set phase 1
+     set gcon $geo.con
+     set gcon2 $geo.con2
+     set gdisplay $geo.display
+     set ::gcon_atoms 3
+
+     eval tk_optionMenu $geo.con.phaseinput ::rb_phase $::expmap(phaselist)
+     grid [label $gcon.phaselbl -text "Input Phase"] -row 0 -column 0
+     grid $gcon.phaseinput -row 0 -column 1
+     set ::gcon_atoms_total $::expmap(atomlist_$phase)
+     grid [label $gcon.atomlbl -text "Number of atoms in fragment: "] -row 1 -column 0
+     spinbox $gcon.atom -from 3 -to [lrange $::expmap(atomlist_$phase) end end] -textvariable ::gcon_atoms -width 5
+     grid $gcon.atom -row 1 -column 1 -padx 5
+     grid [button $gcon.atomchoice -text "Choose Start Atom" -command "RB_FixStartAtom $phase $gdisplay $gcon2"] -row 1 -column 2
+     grid [button $gcon2.save -text "Save and Map \n Rigid Body" -width 15 -command "RB_Geom_Save"] -row 0 -column 0 -padx 5
+          $gcon2.save config -state disable
+     grid [button $gcon2.savec -text "Save Cartesian \n Coordinates" -width 15 -command "RB_FixFragSaveCoord"] -row 0 -column 1 -padx 5
+          $gcon2.savec config -state disable
+     grid [button $gcon2.abort -text "Abort" -width 15 -command "destroy .geometry"] -row 0 -column 2 -sticky ns -padx 5
+
+}
+
+proc RB_FixFragSaveCoord {args} {
+# number of atoms in rigid body  ::gcon_atoms
+# first atom in rigid body       ::gcon_start
+# origin list                    ::gcon_origin_list
+
+     set vector1list "X"
+     set vector2list "Y"
+
+     lappend vector1list [expr $::geom_x1 - [expr $::gcon_start -1]]
+     lappend vector1list [expr $::geom_x2 - [expr $::gcon_start -1]]
+     lappend vector2list [expr $::geom_y1 - [expr $::gcon_start -1]]
+     lappend vector2list [expr $::geom_y2 - [expr $::gcon_start -1]]
+
+     set ::gcon_origin_list ""
+     foreach item $::rb_atom_range {
+                if {$::rb_atom_origin_set($item) == 1} {
+                set temp [expr $item - [expr $::gcon_start - 1]]
+                   lappend ::gcon_origin_list $temp
+                }
+        }
+
+        set temp1 [ExtractRigidBody $::rb_phase $::gcon_atoms $::gcon_start $::gcon_origin_list $vector1list $vector2list]
+        if {[lindex $temp1 0] == {} || [lindex $temp1 1] == {} || [lindex $temp1 2] == {}} {
+   }
+
+   set coordlist ""
+   lappend coordlist [lindex $temp1 2]
+#   puts $coordlist
+
+   set bodnum [RB_New_RBnum]
+#   puts "body number = $bodnum"
+   set coordnum 0
+#   set ::rb_damp($bodnum,1) 0
+   set ::rb_coord_num($bodnum,1) $::gcon_atoms
+
+   catch {array unset ::rb_x $bodnum,1,*}
+   catch {array unset ::rb_y $bodnum,1,*}
+   catch {array unset ::rb_z $bodnum,1,*}
+
+
+   foreach coord $coordlist {
+
+           set ::rb_x($bodnum,1,$coordnum) [lindex $coord 1]
+           set ::rb_y($bodnum,1,$coordnum) [lindex $coord 2]
+           set ::rb_z($bodnum,1,$coordnum) [lindex $coord 3]
+           incr coordnum
+   }
+
+
+   NewBodyTypeWindow
+   destroy .geometry
+#   RB_Control_Panel 0
+
+
+}
+
+proc RB_FixStartAtom {phase gdisplay gcon2 args} {
+     set ::gcon_start ""
+     set possible_start [RigidStartAtoms $phase $::gcon_atoms]
+
+     if {$possible_start == ""} {
+        set ::gdisplay $gdisplay
+        #grid [label $ca.stop -text "Warning, action failed due to lack of unmapped atoms."] -row 0 -column 0
+        #grid [button $ca.cont -text "continue" -command "destroy $ca"] -row 1 -column 0
+        MyMessageBox -parent $gdisplay \
+          -message "There are not enough atoms in this phase that are not already mapped to a rigid body to use."
+        return
+     }
+
+     catch {destroy .chooseatom}
+     set ca .chooseatom
+     toplevel $ca
+     wm title $ca "Choose Atom"
+
+#     puts $atomlist
+     foreach {top main side lbl} [MakeScrollTable $ca] {}
+
+     set row 0
+     set column 0
+     foreach atom $possible_start {
+        set label "[atominfo $phase $atom label] \($atom\)"
+        button $main.$atom -text $label -command "set ::gcon_start $atom; destroy $ca"
+
+        incr row
+        if {$row > 5} {
+           set row 1
+           incr column
+        }
+      grid $main.$atom -row $row -column $column -padx 5 -pady 5
+      }
+      ResizeScrollTable $ca
+      putontop $ca
+      tkwait window $ca
+      afterputontop
+      $gcon2.save config -state normal
+      $gcon2.savec config -state normal
+      RB_Atom_Fixlist $phase $gdisplay
+}
+
+proc RB_Atom_Fixlist {phase gdisplay} {
+#     set ::gcon_start ""
+     set start_loc [lsearch $::expmap(atomlist_$phase) $::gcon_start]
+     set ::rb_atom_range [lrange $::expmap(atomlist_$phase) $start_loc [expr $start_loc + $::gcon_atoms - 1]]
+#     puts "location = $start_loc  range = $::rb_atom_range"
+     set rownum 1
+     set colnum 1
+
+     eval destroy [winfo children $gdisplay]
+     grid [frame $gdisplay.lbl -bd 2 -relief groove] -row 0 -column 0
+     grid [frame $gdisplay.atoms -bd 2 -relief groove] -row 1 -column 0
+     grid [frame $gdisplay.param -bd 2 -relief groove] -row 1 -column 1
+
+     grid [label $gdisplay.lbl.state -text "Select atoms to define centroid for origin"] -row 0 -column 0
+  #   grid [button $gdisplay.lbl.set -text "Set Origin" -command "RB_Atom_Origin_Set"] -row 3 -column 0
+
+     foreach {top main side lbl} [MakeScrollTable $gdisplay.atoms] {}
+     eval destroy [winfo children $main]
+     foreach atom $::rb_atom_range {
+
+
+             if {[expr $colnum % 4] == 0} {incr rownum; set colnum 1}
+             set atomid [atominfo $phase $atom  label]
+#             puts $atomid
+             set ::rb_atom_origin_set($atom) 1
+             grid [checkbutton $main.$atom -text "$atomid" -variable ::rb_atom_origin_set($atom)] -row $rownum -column $colnum
+             incr colnum
+
+             }
+      ResizeScrollTable $gdisplay.atoms
+
+
+  set paramlist $gdisplay.param
+# [atominfo $phase $::rb_atom_range label]
+  grid [label $paramlist.lbl -text "Define Axes"] -row 0 -column 0 -columnspan 2
+  grid [label $paramlist.lbl1 -text "Atom 1"] -row 1 -column 0
+  grid [label $paramlist.lbl2 -text "Atom 2"] -row 1 -column 1
+  grid [label $paramlist.lblx -text "Choose two atoms to define vector for x-axis: "] -row 2 -column 0 -pady 10 -columnspan 2
+  grid [label $paramlist.lbly -text "Choose two atoms to define second vector defining xy plane: "] -row 4 -column 0 -pady 10 -columnspan 2
+
+  set atom_info_list ""
+  set atom_list ""
+  foreach atom $::rb_atom_range {
+          lappend atom_info_list $atom
+          lappend atom_info_list [atominfo $phase $atom label]
+          lappend atom_list [atominfo $phase $atom label]
+  }
+
+#                  puts $atom_info_list
+       set ::rb_param_x1 [lindex $atom_list 0]
+       set ::rb_param_x2 [lindex $atom_list 1]
+       set ::rb_param_y1 [lindex $atom_list 0]
+       set ::rb_param_y2 [lindex $atom_list 2]
+       set ::geom_x1     [lindex $::rb_atom_range 0]
+       set ::geom_x2     [lindex $::rb_atom_range 1]
+       set ::geom_y1     [lindex $::rb_atom_range 0]
+       set ::geom_y2     [lindex $::rb_atom_range 2]
+
+       set menu [eval tk_optionMenu $paramlist.x1 ::rb_param_x1 $atom_list]
+           foreach item $atom {
+              set max [llength $atom]
+              for {set count 0} {$count <= [expr $max - 1]} {incr count} {
+                 $menu entryconfig $count -command "set ::geom_x1 [lindex $atom_info_list [expr $count*2]]"
+              }
+       }
+
+       set menu [eval tk_optionMenu $paramlist.x2 ::rb_param_x2 $atom_list]
+           foreach item $atom {
+              set max [llength $atom]
+              for {set count 0} {$count <= [expr $max - 1]} {incr count} {
+                 $menu entryconfig $count -command "set ::geom_x2 [lindex $atom_info_list [expr $count*2]]"
+              }
+       }
+
+       set menu [eval tk_optionMenu $paramlist.y1 ::rb_param_y1 $atom_list]
+           foreach item $atom {
+              set max [llength $atom]
+              for {set count 0} {$count <= [expr $max - 1]} {incr count} {
+                 $menu entryconfig $count -command "set ::geom_y1 [lindex $atom_info_list [expr $count*2]]"
+              }
+       }
+
+       set menu [eval tk_optionMenu $paramlist.y2 ::rb_param_y2 $atom_list]
+           foreach item $atom {
+              set max [llength $atom]
+              for {set count 0} {$count <= [expr $max - 1]} {incr count} {
+                 $menu entryconfig $count -command "set ::geom_y2 [lindex $atom_info_list [expr $count*2]]"
+              }
+       }
+
+
+       grid $paramlist.x1 -row 3 -column 0
+       grid $paramlist.x2 -row 3 -column 1
+       grid $paramlist.y1 -row 5 -column 0
+       grid $paramlist.y2 -row 5 -column 1
+
+
+         $paramlist.x1 config -width 4
+         $paramlist.x2 config -width 4
+         $paramlist.y1 config -width 4
+         $paramlist.y2 config -width 4
+
+  }
+
+
+proc RB_Atom_Origin_Set {args} {
+        set ::rb_origin_list ""
+        foreach item $::rb_atom_range {
+                if {$::rb_atom_origin_set($item) == 1} {
+                   lappend ::rb_origin_list $item
+                }
+        }
+#        puts "Origin list = $::rb_origin_list"
+}
+
+proc RB_Geom_Save {args} {
+# number of atoms in rigid body  ::gcon_atoms
+# first atom in rigid body       ::gcon_start
+# origin list                    ::gcon_origin_list
+
+     set vector1list "X"
+     set vector2list "Y"
+
+     lappend vector1list [expr $::geom_x1 - [expr $::gcon_start -1]]
+     lappend vector1list [expr $::geom_x2 - [expr $::gcon_start -1]]
+     lappend vector2list [expr $::geom_y1 - [expr $::gcon_start -1]]
+     lappend vector2list [expr $::geom_y2 - [expr $::gcon_start -1]]
+
+     set ::gcon_origin_list ""
+     foreach item $::rb_atom_range {
+                if {$::rb_atom_origin_set($item) == 1} {
+                set temp [expr $item - [expr $::gcon_start - 1]]
+                   lappend ::gcon_origin_list $temp
+                }
+        }
+#        puts "Origin list = $::gcon_origin_list"
+#        puts "vector 1 list = $vector1list"
+#        puts "vector 2 list = $vector2list"
+#        puts "number atoms = $::gcon_atoms"
+#        puts "start atom  = $::gcon_start"
+
+        set temp1 [ExtractRigidBody $::rb_phase $::gcon_atoms $::gcon_start $::gcon_origin_list $vector1list $vector2list]
+        if {[lindex $temp1 0] == {} || [lindex $temp1 1] == {} || [lindex $temp1 2] == {}} {
+           #   puts "Geometry Crashed"
+        }
+        #puts "string 1 = [lindex $temp1 0]"
+        #puts "string 2 = [lindex $temp1 1]"
+        #puts "string 3 = [lindex $temp1 2]"
+
+        set cartesian ""
+        lappend cartesian [lindex $temp1 2]
+        #puts "Cartesian = $cartesian"
+
+        set bodnum [AddRigidBody 1 $cartesian]
+        # set ::rb_damp($bodnum,1) 0
+        set ::rb_coord_num($bodnum,1) $::gcon_atoms
+
+        MapRigidBody $::rb_phase $bodnum $::gcon_start [lindex $temp1 0] [lindex $temp1 1]
+        RecordMacroEntry "MapRigidBody $::rb_phase $bodnum $::gcon_start [lindex $temp1 0] [lindex $temp1 1]" 0
+        destroy .geometry
+        RB_Control_Panel 0
+}
+
+proc RB_Refine_Con {args} {
+     catch {destroy .refcon}
+     set con .refcon
+     toplevel $con
+     wm title $con "Rigid Body Refinement Controls"
+     wm geometry $con 1150x600+10+10
+     set ::rb_var_list ""
+     set ::rb_var_list_tls ""
+     set ::varnum 1
+     set ::rb_var_name "var$::varnum"
+#     putontop $con
+      grid [frame $con.info -bd 2 -relief groove] -row 1 -column 0 -sticky news
+      grid columnconfig $con 0 -weight 1
+      grid [frame $con.con -bd 2 -relief groove] -row 0 -column 0
+      grid [frame $con.terminate -bd 2 -relief groove] -row 2 -column 0
+
+      #bandaid fix:  load all mapping data
+      foreach phase $::expmap(phaselist) {
+              foreach bodnum [RigidBodyList] {
+                      foreach mapnum [RigidBodyMappingList $phase $bodnum] {
+                              RB_Load_Mapdata $phase $bodnum $mapnum
+                      }
+              }
+      }
+
+      #grid rowconfig $con 0 -weight 1
+
+     foreach {top main side lbl} [MakeScrollTable $con.info] {}
+             grid [label $top.rb -text "Body"] -row 1 -column 1 -padx 3
+             grid [label $top.phase -text "Ph"] -row 1 -column 2 -padx 3
+             grid [label $top.mapnum -text "Map"] -row 1 -column 3 -padx 3
+             grid [label $top.x -text "X"] -row 1 -column 4 -padx 3
+             grid [label $top.y -text "Y"] -row 1 -column 5 -padx 3
+             grid [label $top.z -text "Z"] -row 1 -column 6 -padx 3
+             grid [label $top.b1 -text "   "] -row 1 -column 7 -padx 3
+             grid [label $top.e1 -text "E1"] -row 1 -column 8 -padx 3
+             grid [label $top.e2 -text "E2"] -row 1 -column 9 -padx 3
+             grid [label $top.e3 -text "E3"] -row 1 -column 10 -padx 3
+             grid [label $top.tlscon1 -text "on/off"] -row 1 -column 11 -padx 3
+#             grid [label $top.b2 -text "   "] -row 1 -column 11 -padx 3
+             grid [label $top.t11 -text "T11"] -row 1 -column 12 -padx 3
+             grid [label $top.t22 -text "T22"] -row 1 -column 13 -padx 3
+             grid [label $top.t33 -text "T33"] -row 1 -column 14 -padx 3
+             grid [label $top.t12 -text "T12"] -row 1 -column 15 -padx 3
+             grid [label $top.t13 -text "T13"] -row 1 -column 16 -padx 3
+             grid [label $top.t23 -text "T23"] -row 1 -column 17 -padx 3
+             grid [label $top.b3 -text "   "] -row 1 -column 18 -padx 3
+             grid [label $top.l11 -text "L11"] -row 1 -column 19 -padx 3
+             grid [label $top.l22 -text "L22"] -row 1 -column 20 -padx 3
+             grid [label $top.l33 -text "L33"] -row 1 -column 21 -padx 3
+             grid [label $top.l12 -text "L12"] -row 1 -column 22 -padx 3
+             grid [label $top.l13 -text "L13"] -row 1 -column 23 -padx 3
+             grid [label $top.l23 -text "L23"] -row 1 -column 24 -padx 3
+             grid [label $top.zb4 -text "   "] -row 1 -column 25 -padx 3
+             grid [label $top.s12 -text "S12"] -row 1 -column 26 -padx 3
+             grid [label $top.s13 -text "S13"] -row 1 -column 27 -padx 3
+             grid [label $top.s21 -text "S21"] -row 1 -column 28 -padx 3
+             grid [label $top.s23 -text "S23"] -row 1 -column 29 -padx 3
+             grid [label $top.s31 -text "S31"] -row 1 -column 30 -padx 3
+             grid [label $top.s32 -text "S32"] -row 1 -column 31 -padx 3
+             grid [label $top.saa -text "SAA"] -row 1 -column 32 -padx 3
+             grid [label $top.sbb -text "SBB"] -row 1 -column 33 -padx 3
+
+             grid [label $top.refcoord -text "Origin"] -row 0 -column 4 -padx 5 -columnspan 3
+             grid [label $top.refeuler -text "Euler Angles"] -row 0 -column 8 -padx 5 -columnspan 3
+             grid [label $top.tlscon2 -text "TLS"] -row 0 -column 11
+             grid [label $top.tls -text "TLS"] -row 0 -column 12 -padx 5 -columnspan 6
+#             grid [label $top.atoms -text "Atoms in Mapping"] -row 0 -column 6 -padx 5 -columnspan 10
+
+             #Determine number of rigid bodies and rigid body mappings
+             set rb_num [RigidBodyList]
+             set row 1
+             foreach phasenum $::expmap(phaselist) {
+                 foreach bodnum $rb_num {
+                     set rb_map_num($phasenum,$bodnum) [RigidBodyMappingList $phasenum $bodnum]
+
+                  foreach mapnum $rb_map_num($phasenum,$bodnum) {
+#                         puts "mapnum = $mapnum"
+#                         grid [checkbutton $main.check($phasenum,$bodnum,$mapnum)] -row $row -column 0
+                         grid [label $main.body($phasenum,$bodnum,$mapnum) -text $bodnum] -row $row -column 1
+                         grid [label $main.phase($phasenum,$bodnum,$mapnum) -text $phasenum] -row $row -column 2
+                         grid [label $main.map($phasenum,$bodnum,$mapnum) -text $mapnum] -row $row -column 3
+                         RB_Load_Vars $phasenum $bodnum $mapnum
+#                         puts "the checkbutton variable is $::rb_var($phasenum,$bodnum,$mapnum,tls)"
+
+#                         puts $main
+                         grid [button $main.cfefx($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.cfefx($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,x) -width 5] -row $row -column 4
+                         grid [button $main.cfefy($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.cfefy($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,y) -width 5]  -row $row -column 5
+                         grid [button $main.cfefz($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.cfefz($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,z) -width 5] -row $row -column 6
+                         grid [label $main.b1($phasenum,$bodnum,$mapnum) -text "   "] -row $row -column 7
+
+                         grid [button $main.eref1($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.eref1($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,e1) -width 5] -row $row -column 8
+                         grid [button $main.eref2($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.eref2($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,e2) -width 5] -row $row -column 9
+                         grid [button $main.eref3($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.eref3($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,e3) -width 5] -row $row -column 10
+#                         grid [label $main.b2($phasenum,$bodnum,$mapnum) -text "   "] -row $row -column 11
+
+                         grid [checkbutton $main.tlscon($phasenum,$bodnum,$mapnum) -variable ::rb_var($phasenum,$bodnum,$mapnum,tls) -command "RB_TLS_Onoff $phasenum $main $bodnum $mapnum" -width 5] -row $row -column 11
+
+
+                         grid [button $main.t11ref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.t11ref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,t11) -width 5] -row $row -column 12
+                         grid [button $main.t22ref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.t22ref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,t22) -width 5] -row $row -column 13
+                         grid [button $main.t33ref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.t33ref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,t33) -width 5] -row $row -column 14
+                         grid [button $main.t12ref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.t12ref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,t12) -width 5] -row $row -column 15
+                         grid [button $main.t13ref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.t13ref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,t13) -width 5] -row $row -column 16
+                         grid [button $main.t23ref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.t23ref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,t23) -width 5] -row $row -column 17
+                         grid [label $main.b3($phasenum,$bodnum,$mapnum) -text "   "] -row $row -column 18
+
+                         grid [button $main.l11ref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.l11ref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,l11) -width 5] -row $row -column 19
+                         grid [button $main.l22ref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.l22ref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,l22) -width 5] -row $row -column 20
+                         grid [button $main.l33ref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.l33ref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,l33) -width 5] -row $row -column 21
+                         grid [button $main.l12ref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.l12ref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,l12) -width 5] -row $row -column 22
+                         grid [button $main.l13ref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.l13ref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,l13) -width 5] -row $row -column 23
+                         grid [button $main.l23ref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.l23ref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,l23) -width 5] -row $row -column 24
+                         grid [label $main.b4($phasenum,$bodnum,$mapnum) -text "   "] -row $row -column 25
+
+                         grid [button $main.s12ref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.s12ref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,s12) -width 5] -row $row -column 26
+                         grid [button $main.s13ref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.s13ref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,s13) -width 5] -row $row -column 27
+                         grid [button $main.s21ref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.s21ref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,s21) -width 5] -row $row -column 28
+                         grid [button $main.s23ref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.s23ref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,s23) -width 5] -row $row -column 29
+                         grid [button $main.s31ref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.s31ref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,s31) -width 5] -row $row -column 30
+                         grid [button $main.s32ref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.s32ref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,s32) -width 5] -row $row -column 31
+                         grid [button $main.saaref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.saaref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,saa) -width 5] -row $row -column 32
+                         grid [button $main.sbbref($phasenum,$bodnum,$mapnum) -command "RB_Con_Button $main.sbbref($phasenum,$bodnum,$mapnum)" -textvariable ::rb_var($phasenum,$bodnum,$mapnum,sbb) -width 5] -row $row -column 33
+
+                         RB_TLS_Onoff $phasenum $main $bodnum $mapnum
+
+
+#                         set col 4
+                         set atomnum $::rb_map_beginning($phasenum,$bodnum,$mapnum)
+#                         puts "first atom = $atomnum"
+#                         set atomlist "atoms in rigid body #$bodnum:    "
+                         set atomlist "atoms in rigid body:    "
+                         for {set j 1} {$j <=$::rb_coord_num($bodnum,1)} {incr j} {
+                             set atom [atominfo $phasenum $atomnum label]
+                             lappend atomlist $atom
+#                            grid [label $main.rb_site$phasenum$mapnum$j -text "$atom"] -row [expr $row +1] -column $col -padx 5
+                             incr atomnum
+#                             incr col
+                        }
+                        grid [label $main.rb_site$phasenum$bodnum$mapnum -text "$atomlist"] -row [expr $row + 1] -column 4 -padx 5 -columnspan 999 -sticky w
+                        incr row 2
+                     }
+                 }
+             }
+             ResizeScrollTable $con.info
+             set ::rbaddresses [winfo children .refcon.info.can.f]
+
+             set ::rb_var_name "var$::varnum"
+             set free "free"
+             set const ""
+
+             grid [label $con.con.lbl -text "Set Variables Selected Below"] -row 1 -column 1
+             grid [button $con.con.free -width 22 -text "Set Free Variable" -command {RB_Con_But_Proc $::rbaddresses free}] -row 2 -column 1
+             grid [button $con.con.const -width 22 -text "Do Not Refine Variables" -command {RB_Con_But_Proc $::rbaddresses ""}] -row 3 -column 1
+             grid [button $con.con.var -width 22 -text "Set Constrained Variables" -command {RB_Con_But_Proc $::rbaddresses $::rb_var_name; incr ::varnum; set ::rb_var_name "var$::varnum"}] -row 4 -column 1
+             grid [entry $con.con.vare -textvariable ::rb_var_name -width 5] -row 4 -column 2
+             grid [button $con.con.clear -width 22 -text "Clear All Variables" -command {RB_Variable_Clear}] -row 5 -column 1
+
+             grid [label $con.terminate.originlabel -text "Origin Damping Factor "] -row 5 -column 1
+             eval tk_optionMenu $con.terminate.origindamp ::rb_damp_origin 0 1 2 3 4 5 6 7 8 9
+             grid $con.terminate.origindamp -row 5 -column 2
+             $con.terminate.origindamp config -width 4 -state disable
+
+             grid [label $con.terminate.anglelabel -text "Angle Damping Factor "] -row 6 -column 1
+             eval tk_optionMenu $con.terminate.angledamp ::rb_damp_angle 0 1 2 3 4 5 6 7 8 9
+             grid $con.terminate.angledamp -row 6 -column 2
+             $con.terminate.angledamp config -width 4 -state disable
+
+             grid [button $con.terminate.save -width 22 -text "Assign Variables and Save" -command RB_Var_Assign] -row 7 -column 1 -columnspan 2
+             grid [button $con.terminate.abort -width 22 -text "Abort" -command  {destroy .refcon}] -row 8 -column 1 -columnspan 2
+
+}
+
+proc RB_Variable_Clear {} {
+     foreach var $::rb_var_list {
+             set $var ""
+     }
+     foreach var $::rb_var_list_tls {
+             set $var ""
+     }
+
+}
+
+proc RB_Con_But_Proc {addresses change args} {
+#     puts "$addresses $change"
+     foreach address $addresses {
+             set a [eval $address cget -bg]
+             if {$a == "yellow"} {
+                set var [eval $address cget -textvariable]
+                set $var $change
+                $address config -relief raised -bg lightgray
+              }
+     }
+}
+
+#procedure to turn buttons on (sunken yellow) and off (lightgray raised).
+proc RB_Con_Button {address args} {
+     set a [eval $address cget -relief]
+     if {$a == "raised"} {
+        $address config -relief sunken -bg yellow
+     }
+     if {$a == "sunken"} {
+        $address config -relief raised
+        $address config -bg lightgray
+     }
+}
+
+
+
+#procedure to determine next available variable number for GSAS
+proc RB_Var_Gen {varcount args} {
+     while {[lsearch $::rb_varlist $varcount] != -1} {incr varcount}
+     lappend ::rb_varlist $varcount
+     return $varcount
+}
+
+#procedure to assign variable names to relationships
+proc RB_Var_Assign {args} {
+     set ::rb_varlist [RigidBodyGetVarNums]
+     set varcount 1
+     set varlist ""
+     catch {array unset rb_var_temp}
+     foreach var $::rb_var_list {
+            if {[set $var] == ""} {
+               set $var 0
+            } elseif {[set $var] == "free"} {
+                     set $var [RB_Var_Gen $varcount]
+                     set varcount [set $var]
+            } else {
+#                     puts [lsearch $varlist [set $var]]
+                     if {[lsearch $varlist [set $var]] == -1} {
+                        lappend varlist [set $var]
+#                        puts $varlist
+                        set rb_variable([set $var]) [RB_Var_Gen $varcount]
+                        set $var $rb_variable([set $var])
+
+                     } else {
+                        set $var $rb_variable([set $var])
+                     }
+             }
+     }
+
+          foreach var $::rb_var_list_tls {
+            if {[set $var] == ""} {
+               set $var 0
+            } elseif {[set $var] == "free"} {
+                     set $var [RB_Var_Gen $varcount]
+                     set varcount [set $var]
+            } else {
+#                     puts [lsearch $varlist [set $var]]
+                     if {[lsearch $varlist [set $var]] == -1} {
+                        lappend varlist [set $var]
+#                        puts $varlist
+                        set rb_variable([set $var]) [RB_Var_Gen $varcount]
+                        set $var $rb_variable([set $var])
+
+                     } else {
+                        set $var $rb_variable([set $var])
+                     }
+             }
+     }
+
+     RB_Var_Save
+     incr ::expgui(changed)
+     destroy .refcon
+}
+
+#procedure for enabling refinement flags
+proc RB_Ref_FlagEnable {phasenum bodnum mapnum var val args} {
+          set atomlist ""
+          set atomnum $::rb_map_beginning($phasenum,$bodnum,$mapnum)
+          for {set j 1} {$j <=$::rb_coord_num($bodnum,1)} {incr j} {
+               lappend atomlist $atomnum
+               incr atomnum
+          }
+          atominfo $phasenum $atomlist $var set $val
+
+ }
+
+
+
+
+#procedure to send variable numbers to EXP file.
+proc RB_Var_Save {args} {
+
+     #Determine number of rigid bodies and rigid body mappings
+     set rb_num [RigidBodyList]
+     foreach phasenum $::expmap(phaselist) {
+          foreach bodnum $rb_num {
+               set rb_map_num($phasenum,$bodnum) [RigidBodyMappingList $phasenum $bodnum]
+               foreach mapnum $rb_map_num($phasenum,$bodnum) {
+                       set refcoordflag 0
+                       set reftlsflag 0
+                       set rb_list "$::rb_var($phasenum,$bodnum,$mapnum,x) \
+                           $::rb_var($phasenum,$bodnum,$mapnum,y) $::rb_var($phasenum,$bodnum,$mapnum,z) \
+                           $::rb_var($phasenum,$bodnum,$mapnum,e1) $::rb_var($phasenum,$bodnum,$mapnum,e2) \
+                           $::rb_var($phasenum,$bodnum,$mapnum,e3) 0 0 0"
+                       RigidBodyVary $phasenum $bodnum $mapnum $rb_list
+                       RecordMacroEntry "incr expgui(changed); RigidBodyVary $phasenum $bodnum $mapnum [list $rb_list]" 0
+                       foreach test $rb_list {
+                            if {$test != 0} {
+                               set refcoordflag 1
+                            }
+                       }
+                          RB_Ref_FlagEnable $phasenum $bodnum $mapnum xref $refcoordflag
+
+                       if {$::rb_var($phasenum,$bodnum,$mapnum,tls) == 1} {
+                           set rb_tls "$::rb_var($phasenum,$bodnum,$mapnum,t11) $::rb_var($phasenum,$bodnum,$mapnum,t22) \
+                               $::rb_var($phasenum,$bodnum,$mapnum,t33) $::rb_var($phasenum,$bodnum,$mapnum,t12) \
+                               $::rb_var($phasenum,$bodnum,$mapnum,t13) $::rb_var($phasenum,$bodnum,$mapnum,t23) \
+                               $::rb_var($phasenum,$bodnum,$mapnum,l11) $::rb_var($phasenum,$bodnum,$mapnum,l22) \
+                               $::rb_var($phasenum,$bodnum,$mapnum,l33) $::rb_var($phasenum,$bodnum,$mapnum,l12) \
+                               $::rb_var($phasenum,$bodnum,$mapnum,l13) $::rb_var($phasenum,$bodnum,$mapnum,l23) \
+                               $::rb_var($phasenum,$bodnum,$mapnum,s12) $::rb_var($phasenum,$bodnum,$mapnum,s13) \
+                               $::rb_var($phasenum,$bodnum,$mapnum,s21) $::rb_var($phasenum,$bodnum,$mapnum,s23) \
+                               $::rb_var($phasenum,$bodnum,$mapnum,s31) $::rb_var($phasenum,$bodnum,$mapnum,s32) \
+                               $::rb_var($phasenum,$bodnum,$mapnum,saa) $::rb_var($phasenum,$bodnum,$mapnum,sbb)"
+#                           puts "TLS param save for $rb_tls"
+                           RigidBodyTLSVary $phasenum $bodnum $mapnum $rb_tls
+                           RecordMacroEntry "RigidBodyTLSVary $phasenum $bodnum $mapnum [list $rb_tls]" 0
+                           foreach test $rb_tls {
+                            if {$test != 0} {
+                               set reftlsflag 1
+                            }
+                       }
+                          RB_Ref_FlagEnable $phasenum $bodnum $mapnum uref $reftlsflag
+                       }
+                       incr ::expgui(changed)
+                       #RecordMacroEntry "incr expgui(changed)" 0
+
+               }
+          }
+#     puts "phasenumber is $phasenum"
+     DisplayAllAtoms $phasenum
+#need to track body number from button on notebook page.  Below is a temporary fix
+      RB_Control_Panel $::rb_panel
+#     RB_Populate $::rb_notebook 1
+     }
+}
+
+# procedure to turn tls buttons on or off
+proc RB_TLS_Onoff {phasenum main bodnum mapnum} {
+
+      lappend tlsparam $main.t11ref($phasenum,$bodnum,$mapnum) $main.t22ref($phasenum,$bodnum,$mapnum) $main.t33ref($phasenum,$bodnum,$mapnum) \
+              $main.t12ref($phasenum,$bodnum,$mapnum) $main.t13ref($phasenum,$bodnum,$mapnum) $main.t23ref($phasenum,$bodnum,$mapnum) \
+              $main.l11ref($phasenum,$bodnum,$mapnum) $main.l22ref($phasenum,$bodnum,$mapnum) $main.l33ref($phasenum,$bodnum,$mapnum) \
+              $main.l12ref($phasenum,$bodnum,$mapnum) $main.l13ref($phasenum,$bodnum,$mapnum) $main.l23ref($phasenum,$bodnum,$mapnum) \
+              $main.s12ref($phasenum,$bodnum,$mapnum) $main.s13ref($phasenum,$bodnum,$mapnum) $main.s21ref($phasenum,$bodnum,$mapnum) \
+              $main.s23ref($phasenum,$bodnum,$mapnum) $main.s31ref($phasenum,$bodnum,$mapnum) $main.s32ref($phasenum,$bodnum,$mapnum) \
+              $main.saaref($phasenum,$bodnum,$mapnum) $main.sbbref($phasenum,$bodnum,$mapnum)
+#      puts $tlsparam
+              if {$::rb_var($phasenum,$bodnum,$mapnum,tls) == 0} {
+                        RigidBodyEnableTLS $phasenum $bodnum $mapnum 0
+                        foreach x $tlsparam {
+                                $x config -state disable -relief sunken
+                        }
+              } else {
+                        RigidBodyEnableTLS $phasenum $bodnum $mapnum 1
+                        foreach x $tlsparam {
+                                $x config -state normal -relief raised
+                        }
+              }
+}
+
+
+proc RB_Load_Vars {phasenum bodnum mapnum args} {
+     foreach var $::rb_map_positionvars($phasenum,$bodnum,$mapnum) {
+             catch {unset temp($var)}
+     }
+
+     foreach var $::rb_map_positionvars($phasenum,$bodnum,$mapnum) {
+             if {[info exists temp($var)] == "0"} {
+                set temp($var) $var
+                } else {
+                  lappend mulvarlist $var
+             }
+     }
+
+     foreach var $::rb_map_tls_var($phasenum,$bodnum,$mapnum) {
+             if {[info exists temp($var)] == "0"} {
+                set temp($var) $var
+             } else {
+                lappend mulvarlist $var
+             }
+     }
+
+     set ::rb_var($phasenum,$bodnum,$mapnum,x) [RB_VarSet [lindex $::rb_map_positionvars($phasenum,$bodnum,$mapnum) 0] $mulvarlist]
+     set ::rb_var($phasenum,$bodnum,$mapnum,y) [RB_VarSet [lindex $::rb_map_positionvars($phasenum,$bodnum,$mapnum) 1] $mulvarlist]
+     set ::rb_var($phasenum,$bodnum,$mapnum,z) [RB_VarSet [lindex $::rb_map_positionvars($phasenum,$bodnum,$mapnum) 2] $mulvarlist]
+
+     lappend ::rb_var_list ::rb_var($phasenum,$bodnum,$mapnum,x) ::rb_var($phasenum,$bodnum,$mapnum,y) ::rb_var($phasenum,$bodnum,$mapnum,z)
+
+     set ::rb_var($phasenum,$bodnum,$mapnum,e1) [RB_VarSet [lindex $::rb_map_positionvars($phasenum,$bodnum,$mapnum) 3] $mulvarlist]
+     set ::rb_var($phasenum,$bodnum,$mapnum,e2) [RB_VarSet [lindex $::rb_map_positionvars($phasenum,$bodnum,$mapnum) 4] $mulvarlist]
+     set ::rb_var($phasenum,$bodnum,$mapnum,e3) [RB_VarSet [lindex $::rb_map_positionvars($phasenum,$bodnum,$mapnum) 5] $mulvarlist]
+
+     lappend ::rb_var_list ::rb_var($phasenum,$bodnum,$mapnum,e1) ::rb_var($phasenum,$bodnum,$mapnum,e2) ::rb_var($phasenum,$bodnum,$mapnum,e3)
+
+     if {$::rb_map_tls_var($phasenum,$bodnum,$mapnum) != ""} {
+
+
+          set ::rb_var($phasenum,$bodnum,$mapnum,t11) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 0] $mulvarlist]
+          set ::rb_var($phasenum,$bodnum,$mapnum,t22) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 1] $mulvarlist]
+          set ::rb_var($phasenum,$bodnum,$mapnum,t33) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 2] $mulvarlist]
+          set ::rb_var($phasenum,$bodnum,$mapnum,t12) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 3] $mulvarlist]
+          set ::rb_var($phasenum,$bodnum,$mapnum,t13) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 4] $mulvarlist]
+          set ::rb_var($phasenum,$bodnum,$mapnum,t23) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 5] $mulvarlist]
+
+          lappend ::rb_var_list_tls ::rb_var($phasenum,$bodnum,$mapnum,t11) ::rb_var($phasenum,$bodnum,$mapnum,t22) ::rb_var($phasenum,$bodnum,$mapnum,t33)
+          lappend ::rb_var_list_tls ::rb_var($phasenum,$bodnum,$mapnum,t12) ::rb_var($phasenum,$bodnum,$mapnum,t13) ::rb_var($phasenum,$bodnum,$mapnum,t23)
+
+          set ::rb_var($phasenum,$bodnum,$mapnum,l11) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 6] $mulvarlist]
+          set ::rb_var($phasenum,$bodnum,$mapnum,l22) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 7] $mulvarlist]
+          set ::rb_var($phasenum,$bodnum,$mapnum,l33) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 8] $mulvarlist]
+          set ::rb_var($phasenum,$bodnum,$mapnum,l12) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 9] $mulvarlist]
+          set ::rb_var($phasenum,$bodnum,$mapnum,l13) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 10] $mulvarlist]
+          set ::rb_var($phasenum,$bodnum,$mapnum,l23) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 11] $mulvarlist]
+
+          lappend ::rb_var_list_tls ::rb_var($phasenum,$bodnum,$mapnum,l11) ::rb_var($phasenum,$bodnum,$mapnum,l22) ::rb_var($phasenum,$bodnum,$mapnum,l33)
+          lappend ::rb_var_list_tls ::rb_var($phasenum,$bodnum,$mapnum,l12) ::rb_var($phasenum,$bodnum,$mapnum,l13) ::rb_var($phasenum,$bodnum,$mapnum,l23)
+
+          set ::rb_var($phasenum,$bodnum,$mapnum,s12) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 12] $mulvarlist]
+          set ::rb_var($phasenum,$bodnum,$mapnum,s13) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 13] $mulvarlist]
+          set ::rb_var($phasenum,$bodnum,$mapnum,s21) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 14] $mulvarlist]
+          set ::rb_var($phasenum,$bodnum,$mapnum,s23) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 15] $mulvarlist]
+          set ::rb_var($phasenum,$bodnum,$mapnum,s31) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 16] $mulvarlist]
+          set ::rb_var($phasenum,$bodnum,$mapnum,s32) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 17] $mulvarlist]
+          set ::rb_var($phasenum,$bodnum,$mapnum,saa) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 18] $mulvarlist]
+          set ::rb_var($phasenum,$bodnum,$mapnum,sbb) [RB_VarSet [lindex $::rb_map_tls_var($phasenum,$bodnum,$mapnum) 19] $mulvarlist]
+
+          lappend ::rb_var_list_tls ::rb_var($phasenum,$bodnum,$mapnum,s12) ::rb_var($phasenum,$bodnum,$mapnum,s13) ::rb_var($phasenum,$bodnum,$mapnum,s21)
+          lappend ::rb_var_list_tls ::rb_var($phasenum,$bodnum,$mapnum,s23) ::rb_var($phasenum,$bodnum,$mapnum,s31) ::rb_var($phasenum,$bodnum,$mapnum,s32)
+          lappend ::rb_var_list_tls ::rb_var($phasenum,$bodnum,$mapnum,saa) ::rb_var($phasenum,$bodnum,$mapnum,sbb)
+
+          set ::rb_var($phasenum,$bodnum,$mapnum,tls) 1
+
+     } else {
+          set ::rb_var($phasenum,$bodnum,$mapnum,t11) ""
+          set ::rb_var($phasenum,$bodnum,$mapnum,t22) ""
+          set ::rb_var($phasenum,$bodnum,$mapnum,t33) ""
+          set ::rb_var($phasenum,$bodnum,$mapnum,t12) ""
+          set ::rb_var($phasenum,$bodnum,$mapnum,t13) ""
+          set ::rb_var($phasenum,$bodnum,$mapnum,t23) ""
+
+          lappend ::rb_var_list_tls ::rb_var($phasenum,$bodnum,$mapnum,t11) ::rb_var($phasenum,$bodnum,$mapnum,t22) ::rb_var($phasenum,$bodnum,$mapnum,t33)
+          lappend ::rb_var_list_tls ::rb_var($phasenum,$bodnum,$mapnum,t12) ::rb_var($phasenum,$bodnum,$mapnum,t13) ::rb_var($phasenum,$bodnum,$mapnum,t23)
+
+          set ::rb_var($phasenum,$bodnum,$mapnum,l11) ""
+          set ::rb_var($phasenum,$bodnum,$mapnum,l22) ""
+          set ::rb_var($phasenum,$bodnum,$mapnum,l33) ""
+          set ::rb_var($phasenum,$bodnum,$mapnum,l12) ""
+          set ::rb_var($phasenum,$bodnum,$mapnum,l13) ""
+          set ::rb_var($phasenum,$bodnum,$mapnum,l23) ""
+
+          lappend ::rb_var_list_tls ::rb_var($phasenum,$bodnum,$mapnum,l11) ::rb_var($phasenum,$bodnum,$mapnum,l22) ::rb_var($phasenum,$bodnum,$mapnum,l33)
+          lappend ::rb_var_list_tls ::rb_var($phasenum,$bodnum,$mapnum,l12) ::rb_var($phasenum,$bodnum,$mapnum,l13) ::rb_var($phasenum,$bodnum,$mapnum,l23)
+
+          set ::rb_var($phasenum,$bodnum,$mapnum,s12) ""
+          set ::rb_var($phasenum,$bodnum,$mapnum,s13) ""
+          set ::rb_var($phasenum,$bodnum,$mapnum,s21) ""
+          set ::rb_var($phasenum,$bodnum,$mapnum,s23) ""
+          set ::rb_var($phasenum,$bodnum,$mapnum,s31) ""
+          set ::rb_var($phasenum,$bodnum,$mapnum,s32) ""
+          set ::rb_var($phasenum,$bodnum,$mapnum,saa) ""
+          set ::rb_var($phasenum,$bodnum,$mapnum,sbb) ""
+
+          lappend ::rb_var_list_tls ::rb_var($phasenum,$bodnum,$mapnum,s12) ::rb_var($phasenum,$bodnum,$mapnum,s13) ::rb_var($phasenum,$bodnum,$mapnum,s21)
+          lappend ::rb_var_list_tls ::rb_var($phasenum,$bodnum,$mapnum,s23) ::rb_var($phasenum,$bodnum,$mapnum,s31) ::rb_var($phasenum,$bodnum,$mapnum,s32)
+          lappend ::rb_var_list_tls ::rb_var($phasenum,$bodnum,$mapnum,saa) ::rb_var($phasenum,$bodnum,$mapnum,sbb)
+
+          set ::rb_var($phasenum,$bodnum,$mapnum,tls) 0
+     }
+
+}
+
+proc RB_VarSet {varin mulvarlist args} {
+     if {$varin == 0} {set varout ""
+        } else {
+          set temp [lsearch $mulvarlist $varin]
+          if {$temp == "-1"} {set varout "free"
+                 } else {
+                   set varout var$varin
+              }
+     }
+     return $varout
+}
+
+#returns next unused rigid body number
+proc RB_New_RBnum {args} {
+
+     set temp [RigidBodyList]
+     for {set count 1} {[lsearch $temp $count] != -1} {incr count} {
+     }
+     return $count
+}
+
+proc RB_CartesianTextFile {bodnum args} {
+    if {$::rb_matrix_num($bodnum) > 1} {
+       MyMessageBox -message "Multiple matrices present, cannot save coordinates to file"
+       return
+    }
+    set rb_file_write [tk_getSaveFile -filetypes {{"Cartesian output" .cart} {"All files" *}}]
+    set fh [open $rb_file_write w]
+    set coordnummax $::rb_coord_num($bodnum,1)
+    for {set coord 0} {$coord < $coordnummax} {incr coord} {
+        set line [list $::rb_x($bodnum,1,$coord) $::rb_y($bodnum,1,$coord) $::rb_z($bodnum,1,$coord)]
+#        puts $line
+#        puts $fh $line
+    }
+    close $fh
+}
+
+############################################################################################
+proc RB_View_Parameters {phase x y args} {
+   set euler     $::rb_map_euler($phase,$x,$y)
+   set positions $::rb_map_positions($phase,$x,$y)
+   set damping   $::rb_map_damping($phase,$x,$y)
+   catch {destroy .viewparam}
+   set vp .viewparam
+   toplevel $vp
+   wm title $vp "Refinement Options"
+   frame $vp.con -bd 2 -relief groove
+   frame $vp.spa -bd 2 -relief groove
+   frame $vp.refflag -bd 2 -relief groove
+   grid $vp.con -row 0 -column 0
+
+   grid $vp.spa -row 2 -column 0
+   grid $vp.refflag -row 1 -column 0
+
+   set con $vp.con
+   label $con.lbl -text "Refine: "
+   button $con.tog -text "off"
+   grid $con.lbl -row 0 -column 0
+   grid $con.tog -row 0 -column 1
+
+   grid [label $vp.spa.lbl1 -text "Supplemental Position Angles"] row 0 -column 0 -columnspan 3
+   set ::e_angle1$y [lindex [lindex $euler 3] 0]
+
+   set ::e_angle2$y [lindex [lindex $euler 4] 0]
+   set ::e_angle3$y [lindex [lindex $euler 5] 0]
+   grid [label $vp.spa.angle1l -text "Sup. Angle 1"] -row 1 -column 0
+   grid [label $vp.spa.angle2l -text "Sup. Angle 2"] -row 2 -column 0
+   grid [label $vp.spa.angle3l -text "Sup. Angle 3"] -row 3 -column 0
+   grid [entry $vp.spa.angle1 -textvariable ::e_angle1$y] -row 1 -column 1
+   grid [entry $vp.spa.angle2 -textvariable ::e_angle2$y] -row 2 -column 1
+   grid [entry $vp.spa.angle3 -textvariable ::e_angle3$y] -row 3 -column 1
+
+   set e_axis1 [lindex [lindex $euler 3] 1]
+   set e_axis2 [lindex [lindex $euler 4] 1]
+   set e_axis3 [lindex [lindex $euler 5] 1]
+
+   grid [label $vp.refflag.lbl1 -text "Refinement Flags"] -row 0 -column 0 -columnspan 3
+   grid [label $vp.refflag.x_axis -text "X-axis"] -row 1 -column 0
+   grid [label $vp.refflag.y_axis -text "Y-axis"] -row 1 -column 1
+   grid [label $vp.refflag.z_axis -text "Z-axis"] -row 1 -column 2
+   grid [label $vp.refflag.euler1 -text "Euler Angle 1"] -row 3 -column 0
+   grid [label $vp.refflag.euler2 -text "Euler Angle 2"] -row 3 -column 1
+   grid [label $vp.refflag.euler3 -text "Euler Angle 3"] -row 3 -column 2
+   grid [label $vp.refflag.sup1 -text "Sup. Angle 1"] -row 5 -column 0
+   grid [label $vp.refflag.sup2 -text "Sup. Angle 2"] -row 5 -column 1
+   grid [label $vp.refflag.sup3 -text "Sup. Angle 3"] -row 5 -column 2
+
+   for {set j 0} {$j < 9} {incr j} {
+       label $vp.refflag.$j -text [lindex $positions $j]
+   }
+   grid $vp.refflag.0 -row 2 -column 0
+   grid $vp.refflag.1 -row 2 -column 1
+   grid $vp.refflag.2 -row 2 -column 2
+   grid $vp.refflag.3 -row 4 -column 0
+   grid $vp.refflag.4 -row 4 -column 1
+   grid $vp.refflag.5 -row 4 -column 2
+   grid $vp.refflag.6 -row 6 -column 0
+   grid $vp.refflag.7 -row 6 -column 1
+   grid $vp.refflag.8 -row 6 -column 2
+
+}
+
Index: unk/single.tcl
===================================================================
--- /trunk/single.tcl	(revision 1165)
+++ 	(revision )
@@ -1,10 +1,0 @@
-# file for overall single crystal panel
-proc MakeSinglePane {} {     ;# called to create the panel intially
-    label $::expgui(singFrame).l -text "Single Crystal Parameters"
-    grid $::expgui(singFrame).l -column 1 -row 1
-    ResizeNotebook
-}
-
-proc DisplaySingle {} {     ;# called each time the panel is raised
-
-}
Index: /trunk/widplt
===================================================================
--- /trunk/widplt	(revision 1165)
+++ /trunk/widplt	(revision 1166)
@@ -11,4 +11,5 @@
 package require Tk
 bind all <Control-KeyPress-c> {destroy .}
+
 set expnam [lindex $argv 0]
 if {$expnam != ""} {
@@ -442,6 +443,14 @@
     global UVWP XY wave lblarr WidSetList WidDisplay ttrange 
     global ABS absSetList AbsDisplay
+    if {$program == "absplt"} {
+	$top yaxis config -title {Abs. Corr.} 
+    } else {
+	$top yaxis config -title {FWHM} 
+    }
     if {$graph(plotunits) == "d"} {
 	$top xaxis configure -title "d (A)"
+    } elseif {$graph(plotunits) == "deltad"} {
+	$top xaxis configure -title "d (A)"
+	$top yaxis configure -title "delta-d/d"
     } elseif {$graph(plotunits) == "q"} {
 	$top xaxis configure -title "Q (A-1)"
@@ -450,9 +459,4 @@
     } else {
 	$top xaxis configure -title "2Theta @ $graph(equivwave)"
-    }
-    if {$program == "absplt"} {
-	$top yaxis config -title {Abs. Corr.} 
-    } else {
-	$top yaxis config -title {FWHM} 
     }
     $top yaxis configure -min 0 
@@ -492,4 +496,6 @@
 		if {$graph(plotunits) == "d"} {
 		    set ttlist [tod $ttlist $item]
+		} elseif {$graph(plotunits) == "deltad"} {
+		    set ttlist [tod $ttlist $item]
 		} elseif {$graph(plotunits) == "q"} {
 		    set ttlist [toQ $ttlist $item]
@@ -530,4 +536,15 @@
 					[eval LFWHM $tt $XY($item)]]
 				lappend lfwhmlist $lfwhm
+			    }
+			} elseif {$graph(plotunits) == "deltad"} {
+			    set d [tt2d $wave($item) $tt ]
+			    lappend ttlist $d
+			    set gfwhm [deltad $wave($item) $tt \
+				    [eval FWHM $tt $UVWP($item)]]
+			    lappend fwhmlist [expr {$gfwhm/$d}]
+			    if $lflag {
+				set lfwhm [deltad $wave($item) $tt \
+					[eval LFWHM $tt $XY($item)]]
+				lappend lfwhmlist [expr {$lfwhm/$d}]
 			    }
 			} elseif {$graph(plotunits) == "q"} {
@@ -982,4 +999,63 @@
 }
 
+proc BLTmanualZoom {} {
+    global graph box
+    catch {toplevel .zoom}
+    eval destroy [grid slaves .zoom]
+    raise .zoom
+    wm title .zoom {Manual Scaling}
+    grid [label .zoom.l1 -text minimum] -row 1 -column 2 
+    grid [label .zoom.l2 -text maximum] -row 1 -column 3 
+    grid [label .zoom.l3 -text x] -row 2 -column 1 
+    grid [label .zoom.l4 -text y] -row 3 -column 1 
+    grid [entry .zoom.xmin -textvariable graph(xmin) -width 10] -row 2 -column 2 
+    grid [entry .zoom.xmax -textvariable graph(xmax) -width 10] -row 2 -column 3 
+    grid [entry .zoom.ymin -textvariable graph(ymin) -width 10] -row 3 -column 2 
+    grid [entry .zoom.ymax -textvariable graph(ymax) -width 10] -row 3 -column 3 
+    grid [frame .zoom.b] -row 4 -column 1 -columnspan 3
+    grid [button .zoom.b.1 -text "Set Scaling" \
+	     -command "SetManualZoom set"]  -row 4 -column 1 -columnspan 2
+    grid [button .zoom.b.2 -text Reset \
+	    -command "SetManualZoom clear"] -row 4 -column 3
+    grid [button .zoom.b.3 -text Close -command "destroy .zoom"] -row 4 -column 4 
+    grid rowconfigure .zoom 1 -weight 1 -pad 5
+    grid rowconfigure .zoom 2 -weight 1 -pad 5
+    grid rowconfigure .zoom 3 -weight 1 -pad 5
+    grid rowconfigure .zoom 4 -weight 0 -pad 5
+    grid columnconfigure .zoom 1 -weight 1 -pad 20
+    grid columnconfigure .zoom 1 -weight 1 
+    grid columnconfigure .zoom 3 -weight 1 -pad 10
+    foreach item {min min max max} \
+	    format {3   2   3   2} \
+	    axis   {x   y   x   y} {
+	set val [$box ${axis}axis cget -${item}]
+	set graph(${axis}${item}) {(auto)}
+	catch {set graph(${axis}${item}) [format %.${format}f $val]}
+    }
+    bind .zoom <Return> "SetManualZoom set"
+}
+
+proc SetManualZoom {mode} {
+    global graph box
+    if {$mode == "clear"} {
+	foreach item {xmin ymin xmax ymax} {
+	    set graph($item) {(auto)}
+	}
+    }
+    foreach item {xmin ymin xmax ymax} {
+	if {[catch {expr $graph($item)}]} {
+	    set $item ""
+	} else {
+	    set $item $graph($item)
+	}
+    }
+    # reset the zoomstack
+    catch {Blt_ZoomStack $box}
+    catch {$box xaxis config -min $xmin -max $xmax}
+    catch {$box yaxis config -min $ymin -max $ymax}
+    #global program
+    #if {$program == "bkgedit"} {bkgEditMode ""}
+}
+
 #-------------------------------------------------------------------------
 # export current plot to Grace
@@ -1242,4 +1318,7 @@
 	-variable graph(plotunits) \
 	-command "plotdata $box"
+.a.options.menu add radiobutton -label "delta-d/d" -value deltad \
+	-variable graph(plotunits) \
+	-command "plotdata $box"
 .a.options.menu add checkbutton -label "Include legend" \
 	-variable graph(legend) \
@@ -1274,5 +1353,8 @@
 #----------------------------------------------------------------
 
-    trace variable newmenu(opt) w setoptmsg
+trace variable newmenu(opt) w setoptmsg
+
+bind . <Key-z> {BLTmanualZoom}
+bind . <Key-Z> {BLTmanualZoom}
 
 proc setoptmsg {args} {
