#!/home/cs/sans/expectk -f
global button 
########################################################################
##ver 1.4, june 1996, a threshold added for montior counts, if, after
##dividing by preset result is less than 10e-3, then set to 1.
##
#########################################################################
##ver 1.5, june 1996, added a help button, which uses html.tk.
##ver 1.6 March 1998 use pdqpg
##ver 1.7 July 1998  add reset/mod history when no sample bgd
##ver 1.8 January 2003 modify list box removing error entries in history
##
##

# dialog.tcl --
#
# This file defines the procedure tk_dialog, which creates a dialog
# box containing a bitmap, a message, and one or more buttons.
#
# $Header: /user6/ouster/wish/library/RCS/dialog.tcl,v 1.4 93/08/16 16:59:52 ouster Exp $ SPRITE (Berkeley)
#
# Copyright (c) 1992-1993 The Regents of the University of California.
# All rights reserved.
#
# Permission is hereby granted, without written agreement and without
# license or royalty fees, to use, copy, modify, and distribute this
# software and its documentation for any purpose, provided that the
# above copyright notice and the following two paragraphs appear in
# all copies of this software.
#
# IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
# DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
# OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
# CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
# ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
# PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
#

#
# tk_dialog:
#
# This procedure displays a dialog box, waits for a button in the dialog
# to be invoked, then returns the index of the selected button.
#
# Arguments:
# w -		Window to use for dialog top-level.
# title -	Title to display in dialog's decorative frame.
# text -	Message to display in dialog.
# bitmap -	Bitmap to display in dialog (empty string means none).
# default -	Index of button that is to display the default ring
#		(-1 means none).
# args -	One or more strings to display in buttons across the
#		bottom of the dialog box.

proc tk_dialog {w title text bitmap default args} {
    global tk_priv

    # 1. Create the top-level window and divide it into top
    # and bottom parts.

    catch {destroy $w}
    toplevel $w -class Dialog
    wm title $w $title
    wm iconname $w Dialog
    frame $w.top -relief raised -bd 1
    pack $w.top -side top -fill both
    frame $w.bot -relief raised -bd 1
    pack $w.bot -side bottom -fill both

    # 2. Fill the top part with bitmap and message.

    message $w.msg -width 3i -text $text \
	    -font -Adobe-Times-Medium-R-Normal-*-180-*
    pack $w.msg -in $w.top -side right -expand 1 -fill both -padx 5m -pady 5m
    if {$bitmap != ""} {
	label $w.bitmap -bitmap $bitmap
	pack $w.bitmap -in $w.top -side left -padx 5m -pady 5m
    }

    # 3. Create a row of buttons at the bottom of the dialog.

    set i 0
    foreach but $args {
	button $w.button$i -text $but -command "set tk_priv(button) $i"
	if {$i == $default} {
	    frame $w.default -relief sunken -bd 1
	    raise $w.button$i $w.default
	    pack $w.default -in $w.bot -side left -expand 1 -padx 3m -pady 2m
	    pack $w.button$i -in $w.default -padx 2m -pady 2m \
		    -ipadx 2m -ipady 1m
	    bind $w <Return> "$w.button$i flash; set tk_priv(button) $i"
	} else {
	    pack $w.button$i -in $w.bot -side left -expand 1 \
		    -padx 3m -pady 3m -ipadx 2m -ipady 1m
	}
	incr i
    }

    # 4. Withdraw the window, then update all the geometry information
    # so we know how big it wants to be, then center the window in the
    # display and de-iconify it.

    wm withdraw $w
    update idletasks
    set x [expr [winfo screenwidth $w]/2 - [winfo reqwidth $w]/2 \
	    - [winfo vrootx [winfo parent $w]]]
    set y [expr [winfo screenheight $w]/2 - [winfo reqheight $w]/2 \
	    - [winfo vrooty [winfo parent $w]]]
    wm geom $w +$x+$y
    wm deiconify $w

    # 5. Set a grab and claim the focus too.

    set oldFocus [focus]
    grab $w
    focus $w

    # 6. Wait for the user to respond, then restore the focus and
    # return the index of the selected button.

    tkwait variable tk_priv(button)
    destroy $w
    focus $oldFocus
    return $tk_priv(button)
}
# -----------------------------------------------------------------------
#------------------------------------------------------------------------
# execute loguse for useage logging
#------------------------------------------------------------------------
set parin 0
set version 1.8
exec monbug XPOL $version

wm title . "Xpolly v$version"
#------------------------------------------------------------------------
# create the frames for GUI layout
#------------------------------------------------------------------------

frame .cadmium
frame .par -height 1c -width 16c
frame .top 
frame .a
frame .b
frame .c
frame .cc
frame .d
frame .bot 
frame .d1 -bd 2 -relief ridge
frame .d2 
frame .bot2
frame .par.f1
frame .par.f2
frame .par.f3
frame .par.f4
frame .par.f5
frame .par.f6
pack .par.f1 .par.f2 .par.f3 .par.f4 .par.f5 .par.f6 -side left -in .par -expand 1 -fill both

#------------------------------------------------------------------------
# pointer information
#------------------------------------------------------------------------

# 0 cadmium runs  1 van runs  2 van runs used  3 van back       4 van back used 
# 5  A1           6 A3        7 Background     8 Sample used    9 A2
#10 cross section 11 header  12 Sample used
#------------------------------------------------------------------------
# pointerarray aids program flow, and type array aids pointer ident.
#------------------------------------------------------------------------

set pointerarray(0) 1; set typearray(0) "Cadmium Runs"
set pointerarray(1) 7; set typearray(1) "Vanadium Sample Runs"
set pointerarray(2) 3; set typearray(2) "Vanadium Sample Runs"
set pointerarray(3) 6; set typearray(3) "Vanadium Background"
set pointerarray(4) 5; set typearray(4) "Vanadium Background"
set pointerarray(5) 6; set typearray(5) "Set Parameters"
set pointerarray(6) 7; set typearray(6) "Set Parameters"
set pointerarray(7) 12; set typearray(7) "Sample-Background Runs"
set pointerarray(8) 9; set typearray(8) "Sample Runs"
set pointerarray(9) 10; set typearray(9) "Set Parameters"
set pointerarray(10) 11; set typearray(10) "Set Parameters"
set pointerarray(11) 12; set typearray(11) "Header Information"
set pointerarray(12) 7; set typearray(12) "Sample Runs" 

#------------------------------------------------------------------------
#calls par when extra parameters are requested from spolly
#and is called with the current value of pointer, enabling 
#the correct sequence of parameters to be send to the program.
#------------------------------------------------------------------------

proc par {value} {

foreach widget {.done .add .preview .run\
.ext .pre} {
$widget configure -state disabled
}

#------------------------------------------------------------------------
# create the parameter entry widgets, labels adnd select reqd. ones
#------------------------------------------------------------------------

entry .par.1 -width 6 -textvariable var1
entry .par.2 -width 6 -textvariable var2
entry .par.3 -width 6 -textvariable var3
entry .par.4 -width 6 -textvariable var4
entry .par.5 -width 20 -textvariable var5
set var1 1
set var2 1
set var3 1
set var4 0
label .par.1l
label .par.2l
label .par.3l
label .par.4l
label .par.5l
#------------------------------------------------------------------------
# value gives program location, and boxes packed according to value
#------------------------------------------------------------------------


# after restarting
if {$value ==0} {
foreach widget {.done .add .preview .run\
.ext .pre} {
$widget configure -state normal
}
}



if {$value ==5} {
.par.1l configure -text "Vanadium Abs.(A1)"
.par.2l configure -text "Total Cross Section Vanadium (A3)"
pack .par.1l .par.1 -in .par.f1
pack .par.2l .par.2 -in .par.f2
}
if {$value ==6} {
.par.2l configure -text "Vanadium Xsection (A3)"
pack .par.2l .par.2 -in .par.f2
}
if {$value ==9} {
.par.1l configure -text "Sample Abs.(A2)"
.par.2l configure -text "Total Xsection (A4)"
.par.3l configure -text "Conc."
.par.4l configure -text "Flat Bkgd. (A5)"
.par.5l configure -text "New Title"
pack .par.1l .par.1 -in .par.f1
pack .par.2l .par.2 -in .par.f2
pack .par.3l .par.3 -in .par.f3
pack .par.4l .par.4 -in .par.f4
pack .par.5l .par.5 -in .par.f5 
}
if {$value ==10} {
.par.2l configure -text "Total Xsection (A4)"
.par.3l configure -text "Conc."
.par.4l configure -text "Flat Bkgd. (A5)"
.par.5l configure -text "New Title"
pack .par.2l .par.2 -in .par.f2
pack .par.3l .par.3 -in .par.f3
pack .par.4l .par.4 -in .par.f4
pack .par.5l .par.5 -in .par.f5 
}
if {$value != 0} focus .par.1
#------------------------------------------------------------------------
# button to send parameters, saved result and kill extra widgets
#------------------------------------------------------------------------

button .par.apply -text APPLY -command {

if {$pointer ==5} {exp_send "$var1 \r"; expect "*spol*"
.runs insert end "Vanadium Abs. Background Corr.(A1)  $var1 "; set pointer 6}
if {$pointer ==6} {exp_send "$var2 \r"; expect "*spol*"
 .runs insert end "Total Vanadium Cross section (A3)  $var2"}
if {$pointer ==9} {exp_send "$var1 \r"; expect "*spol*"
 .runs insert end "Sample Abs Background corr.  (A2)   $var1"
set pointer 10}
if {$pointer ==10} {exp_send "$var2 $var3 $var4 \r"; expect "*spol*"
 set titleinfo $expect_out(buffer)
 exp_send "$var5 \r"; expect "*spol*"
set titleinfo [lindex [split $titleinfo \n] 1]

#insert entries into the log
 .runs insert end "Total Cross-section (A4)            $var2"
 .runs insert end "Concentration                       $var3"
 .runs insert end "Flat Background (A5)                $var4"
 .runs insert end $titleinfo
 .runs insert end "New Title                           $var5"
 set pointer 11
 set runsaved [string trim [lindex $expect_out(buffer) [expr 5+[llength $var5]]]]
 set extsaved [string trim [lindex $expect_out(buffer) [expr 7+[llength $var5]]]]

 while {[string length $runsaved] <6} {set runsaved 0$runsaved}
 while {[string length $extsaved] <3} {set extsaved 0$extsaved}
  set cadrun $runsaved
 set cadext $extsaved

.runs insert end "                              ==========="
 .runs insert end "Output saved as               g$runsaved.$extsaved" 
 .runs insert end "- - - - - - - - - - - - - - - - - - - - -"
 .slctr.list insert end [exec pdqtitle g$runsaved.$extsaved]
.runs see [.runs size]
spawn pdqpg $runsaved $extsaved

set spawn_id $spollyid

 }
destroy .par
frame .par -height 1c -width 16c
pack .par
frame .par.f1
frame .par.f2
frame .par.f3
frame .par.f4
frame .par.f5
frame .par.f6
pack .par.f1 .par.f2 .par.f3 .par.f4 .par.f5 .par.f6 -side left -in .par 
foreach widget {.done .add .preview .run\
.ext .pre} {
$widget configure -state normal
}
set pointer $pointerarray($pointer)
set instype $typearray($pointer)
}
pack .par.apply -in .par.f6
}
#------------------------------------------------------------------------
#end of the procedure.
#------------------------------------------------------------------------



pack .d1 .d2 -in .d
set pointer 0
set used 0
pack .top .bot .bot2 -in .cadmium -fill both
pack .a .b .c .cc .d  -side left -in .bot 
label .label -textvariable  instype
label .label2 -textvariable instype -width 25
set instype $typearray($pointer)
pack .label -in .top 
label .runl -text Run
label .extl -text Ext
label .prel -text Preset
entry .run -width 7 -textvariable cadrun
entry .ext -width 5 -textvariable cadext
entry .pre -width 9 -textvariable cadpre
label .inf1 -text "        " 

set cadpre {}
pack .runl .run -in .a -expand 1 -fill both 
pack .extl .ext -in .b -expand 1 -fill both
pack .prel .pre -in .c -expand 1 -fill both
pack .inf1  -in .cc -expand 1 -fill both
label .history -text History
listbox .runs -height 15 -width 60 -font -adobe-courier-medium-r-normal--12-120-75-75-m-70-iso8859-1\
-yscrollcommand ".scroll set" -relief flat
scrollbar .scroll -command ".runs yview"
button .preview -text PREVIEW -underline 3 -command {
 while {[string length $cadrun] <6} {set cadrun 0$cadrun}
 while {[string length $cadext] <3} {set cadext 0$cadext}
spawn pdqpg $cadrun $cadext

set spawn_id $spollyid
}
button .done -text "NEXT SET" -underline 0 -command {
exp_send "\r"
expect "*spol*"
set parin 0
set cadrun {}
set cadext {}
set cadpre {}
if {$pointer ==7} {
if {$used ==1} {
.runs insert end "End of sample bkgd. set"
}}
set pointer $pointerarray($pointer)
set instype $typearray($pointer)
if {$pointer ==7} {set used 0}
if {$pointer ==8} {
if {$used ==0} {
.runs insert end "!! no sample-background run set !!"
}}
if {$pointer ==9} {
if {$used ==0} {set pointer $pointerarray($pointer)
set instype $typearray($pointer)

}}
if {$pointer ==5 } {
set parin 1
par $pointer
}
if {$pointer ==6 } {
set parin 1
par $pointer
}
if {$pointer ==9 } {
set parin 1
par $pointer
}
if {$pointer ==10 } {
set parin 1
par $pointer
}

set var1 1
set var2 1
set var3 1
set var4 0
}

set var1 1
set var2 1
set var3 1
set var4 0

button .add -text ADD -underline 0 -command {
	 set presetok [scan $cadpre %f cadpre]
if {$presetok == 0} {
tk_dialog .dialog {Bad Value} {The Preset field contains non-numeric data} \
error 0 {OK} 
} else {
if {$cadrun > 0} {
exp_send "$cadrun $cadext \r"
expect "*NOT ALLOWED*" {.runs insert end "Invalid fields defined  ";exp_send "\r"} \
	"*No data found*" {.runs insert end "No data found                  $cadrun "}  \
	"*spol*" {

if {$pointer ==12} {
if {$used ==0} {
.runs insert end "! no sample-background runs !"
}}

.runs insert end "Run added with Preset $cadpre      $cadrun.$cadext as $instype "
	if {$pointer == 1} {set pointer 2}
	 if {$pointer ==3} {set pointer 4}
	 if {$pointer ==12} {
set pointer 8
puts  "position 12/8"}
# this is sample background for setting  "used"
	 if {$pointer ==7} {set used 1}
	 exp_send " $cadpre \r"
	 expect "*spol*" }}
focus .run
set .cadrun {}
set .cadext {}
set .cadpre {}
.runs see [.runs size]
}
}
button .help -text HELP!! -command {
exec html.tk $env(SAS_DIR)/xpollyhelp/xpolly.htm &
}
button .restart -text RESTART -underline 0 -command {
if { $parin ==1} {exp_send "\r" }
exp_send -- "-1\r"
expect eof




set lisfile [lindex $expect_out(buffer) 4]

#write history file, xpolly.his 
#from the history listbox
set history [.runs get 0 [.runs size]]
set indx 0
set fileid [open "xpolly.his" a]
set date [exec date]
puts $fileid "-----------------------------------------------------------------------"
puts $fileid "Xpolly tk S.Fayers v$version New Entry Created on $date"
puts $fileid "-----------------------------------------------------------------------"
while {$indx < [llength $history]} {
puts $fileid [lindex $history $indx]
incr indx
}
puts $fileid "** Full listing in file $lisfile **"
puts $fileid "-- restarting --"
flush $fileid
close $fileid

set pointer 0
set used 0

spawn $env(SAS_DIR)/spolly
expect "*spol*"
# output, none, screen or printer listing
exp_send "2\r"
expect "*spol*"
# monitor prescaler (default 100000 in spolly is used)
exp_send "\r"
expect "*spol*"
set spollyid $spawn_id



.runs delete 0 [.runs size]

.runs insert end "----------------  restarting  -----------------------"
.runs see [.runs size]
set pointer 0
set used 0
set cadrun {}
set cadext {}
set cadpre {}
set instype $typearray($pointer)
}


button .exit -text EXIT -underline 1 -command {
if { $parin ==1} {exp_send "\r" }
exp_send -- "-1\r"
expect eof
set lisfile [lindex $expect_out(buffer) 4]

#write history file, xpolly.his 
#from the history listbox
set history [.runs get 0 [.runs size]]
set indx 0
set fileid [open "xpolly.his" a]
set date [exec date]
puts $fileid "-----------------------------------------------------------------------"
puts $fileid "Xpolly tk S.Fayers v$version New Entry Created on $date"
puts $fileid "-----------------------------------------------------------------------"
while {$indx < [llength $history]} {
puts $fileid [lindex $history $indx]
incr indx
}
puts $fileid "** Full listing in file $lisfile **"
puts $fileid "-- END --"
flush $fileid
close $fileid
exit
}


pack .history -in .d1 -side top
pack .runs -in .d1 -side left -expand 1 -fill x
pack .scroll -in .d1 -side right -fill y
pack .label2 .preview .add .done .help .restart .exit -side left -in .d2 -expand 1 -fill both
bind .run <Tab> { focus .ext}
bind .ext <Tab> { focus .pre}

bind . <Alt-n> {.done invoke}
bind . <Alt-v> {.preview invoke}
bind . <Alt-a> {.add invoke}
bind . <Alt-x> {.exit invoke}
pack .cadmium .par
spawn $env(SAS_DIR)/spolly
expect "*spol*"
# output, none, screen or printer listing
exp_send "2\r"
expect "*spol*"
# monitor prescaler (default 100000 in spolly is used)
exp_send "\r"
expect "*spol*"
set spollyid $spawn_id

focus .run
toplevel .slctr
frame .slctr.top
frame .slctr.bot
pack .slctr.top .slctr.bot
label .slctr.l1 -text "Control Double Left button to only place in entry fields"
label .slctr.l2 -text "Double Left button to Add run with Default Preset"
button .slctr.l3 -text "Preview Selected Run" -underline 3 -command {
set cadrun [string trim [string range [.slctr.list get active] 5 10]]
set cadext [string trim [string range [.slctr.list get active] 16 18]]
set cadpre [string trim [string range [.slctr.list get active] 25 33]]
set cadpre [expr $cadpre /100000.0]
# if monitor is < 10e-3, set to 1.
if {$cadpre < 0.001} {set cadpre 1}
 while {[string length $cadrun] <6} {set cadrun 0$cadrun}
 while {[string length $cadext] <3} {set cadext 0$cadext}
.preview invoke}
wm title .slctr "Xpolly v1 - Run Selector"
listbox .slctr.list -height 20 -width 60 -font \
-adobe-courier-medium-r-normal--17-*-*-*-*-*-* -yscrollcommand ".slctr.scroll set"
scrollbar .slctr.scroll -command ".slctr.list yview"
pack .slctr.list -side left -in .slctr.bot -expand 1 -fill x
pack .slctr.scroll -side right -in .slctr.bot -expand 1 -fill y
pack .slctr.l1 .slctr.l2 .slctr.l3 -in .slctr.top -anchor w
set list [eval exec pdqtitle [glob g\[0\-9\]?????.???]]
set list [lsort [split $list \n]]
set indx 0
# skip lines for unsuccessfully read RGIOs (no titles)
while {$indx < [llength $list]} {
if {[string first "Title:" [lindex $list $indx]] == -1} {
incr indx
} else {
.slctr.list insert end [lindex $list $indx] 
incr indx
}
}
bind .slctr.list <Double-Button-1> {
set cadrun [string trim [string range [.slctr.list get active] 5 10]]
set cadext [string trim [string range [.slctr.list get active] 16 18]]
set cadpre [string trim [string range [.slctr.list get active] 25 33]]
set cadpre [expr $cadpre /100000.0]
# if monitor is < 10e-3, set to 1.
if {$cadpre < 0.001} {set cadpre 1}
 while {[string length $cadrun] <6} {set cadrun 0$cadrun}
 while {[string length $cadext] <3} {set cadext 0$cadext}
.add invoke
}
bind .slctr.list <Control-Double-Button-1> {
set cadrun [string trim [string range [.slctr.list get active] 5 10]]
set cadext [string trim [string range [.slctr.list get active] 16 18]]
set cadpre [string trim [string range [.slctr.list get active] 25 33]]
set cadpre [expr $cadpre /100000.0]
# if monitor is < 10e-3, set to 1.
if {$cadpre < 0.001} {set cadpre 1}
 while {[string length $cadrun] <6} {set cadrun 0$cadrun}
 while {[string length $cadext] <3} {set cadext 0$cadext}
focus .pre
}
bind .slctr <Alt-v> {.slctr.l3 invoke}
