#! /home/cs/sans/Linux/expectk -f

# This is an interactive interface written for mplot Multiple Sans Spectra.
# Written by Satchi Sri under the supervision of Ron Ghosh 02/98
# Last modified on 30/06/98
# Filename searches for g0* not g* {Ron Sep 98]
# search now terminates on HELP or EXIT  [Ron Sep 98]
# new field for error bar settings [Ron Apr 99] 2.1
# filename searches for g[0-9]?????.??? [Ron Jun 00] 2.2
# correction to set values for A and B exponents [Ron Jul 00] 2.3
# correction suppress printer message [Ron Oct 2001] 2.4
# corrections for error bar choice  [Ron Jan 2010] 2.5

global putnum barc varname pform suff dir_name headprog env

catch { package require expect } resc1
catch { package require Expect } resc2
# don't know which spelling is available per se

set putnum 0
set barc 1
set varname 1

set version 2.5

set pform $tcl_platform(platform)
set suff ".exe"
set mplotpath mplot.exe
# assume windows version has path including exes (from prop)
set dir_name $env(SAS_DIR)
set headprog $dir_name/pchead.exe
if { $pform == "unix" } {
set suff ""
set headprog "head"
catch { exec $dir_name/monbug XMPL $version } reslt
set mplotpath $dir_name/mplot
}
set runspath "./"
set setxy 0

set selectbg green
set unselectbg #9900991B99FE
set selectfg black
set unselectfg white
set avairunsfg cyan
set selrunsfg black
set mal {}
set lafont "-*-*-bold-*-normal-*-10*"


proc bugs { bstr } {
set rbug "rtrace.exe"
set outt " >>bfile"
set trac " $rbug $bstr $outt "
eval exec $trac
 
}
proc blink { w option value1 value2 interval } {
	if { [winfo exists $w] ==1 } {
	   $w config $option $value1
	   after $interval [list blink $w $option $value2 $value1 $interval]
	} else {
		return
	}
}


proc plotselect { args } {
global  itnom items selectbg dop
	set count 0
	exp_send "r\r"
	expect "Run number...ext...divider : "
	foreach term $args {
	   set color [$term cget -bg ]
	   if { $color == $selectbg } {
		set list [split [lindex $items $count] ]
		expr [lindex $list 2] 
		#puts stdout [lindex $list 2]
		exp_send "[lindex $items $count]\r"	
		expect "Run number...ext...divider : " {
		} \
		"A maximum of 10 spectra have been read in." { }
	   } else { 
		
		}
	   incr count
	}
	exp_send "\r"
	expect "HELP or EXIT :"
	keepbound
	exp_send "p\r"
	expect "LEFT MOUSE OR TYPE SPACE FOR X,Y OR RETURN TO CONTINUE" {
		warning .warior } \
		"HELP or EXIT :" {
		}
	#expect "HELP or EXIT :"
	keepbound
#	exp_send "r\r"
#	expect "Run number...ext...divider : "
#	foreach item $items {
#		exp_send "$item\r"
#		expect "Run number...ext...divider : " { 
#		} \
#		       "A maximum of 10 spectra have been read in." { }
#	}
#	exp_send "\r"
#	expect "HELP or EXIT :"
		
}
proc checko { but value } {
global status
	if { $but == "ba1" && $value < 10 } {
		set status { Click on Selected data for sub selection }
	}
	if { $but == "ba1" && $value >= 10 } {
		set status {Maximum of 10 data is selected}
	}
	if { $but == "bs1" && $value == 0 } {
		set status { Click on Available data for primary selection }
	}
	if { $but == "bs1" && $value <= 10 && $value > 0 } {
		set status { Click on Click on Selected data for sub selection }
	}
}
proc fileselect {{default {}} {mustExist 1} } {
	global fileselect
	set fileselect(path) [file tail $default]
	set dir [file dirname $default]
	set fileselect(dir) {}
	set fileselect(done) 0
	set fileselect(mustexist) $mustExist
	fileselectList $dir
	return $fileselect(path)
}
proc fileselectList { dir {files {}} } {
	global fileselect items 
	set items {}
	set fileselect(dir) $dir
	update idletasks
	if { [string length $files] == 0 } {
	set files [glob -nocomplain $fileselect(dir)/g\[0\-9\]?????.???]
	}
	foreach f [lsort $files] {
		if ![file isdirectory $f] {
			lappend items [file tail $f]
			#puts stdout "$f"	
		}
	}
	ListSelect .p $items
	#pack .f -expand true -fill both	
}
proc ScrolledListbox2 { parent args } {
	#Create listbox attached to scrollbars , pass thru $args

	frame $parent
	eval {listbox $parent.list \
		-yscrollcommand [list $parent.sy set] } $args
	scrollbar $parent.sy -orient vertical \
		-command [list $parent.list yview]
	pack $parent.sy  -side right  -fill y
	eval {$parent.list see end}
	pack $parent.list -side left -fill both -expand true 
	return $parent.list 
}
proc warning { warn } {
	set donewarn {}
	
	toplevel $warn
	#wm title $warn "MESSAGE"
	#wm focusmodel $warn active
	wm overrideredirect $warn 1
	frame $warn.box -height 15 -width 100 -relief raised -borderwidth 3 
	message $warn.lab -text {Use left button to mark x, y  \
	use right button on picture to exit cursor position } -aspect 1000\
	 -relief flat -justify left -bg yellow -fg Black 
	#wm transient $warn $warn.lab
	pack $warn.lab -in $warn.box
	pack $warn.box
	update idletasks
	tkwait visibility $warn
	focus $warn
	grab $warn
	set timeout 2000000
	blink $warn.lab -bg yellow orange 600
	expect "HELP or EXIT :" {set donewarn 1} 
	grab release $warn 
	destroy $warn
	return
}
proc infor { mess con args  } {
	global warn lafont
	set warn .miow
	set donewarn {}
	toplevel $warn
	wm title $warn "MESSAGE"
	set k [wm geometry $warn] 
	wm geometry $warn +350+350
	#puts stdout $k
	wm overrideredirect $warn 1
	wm focusmodel $warn passive
	focus $warn
	tkwait visibility $warn
	grab $warn
	frame $warn.box -height 150 -width 100 -relief raised -borderwidth 3
	label $warn.lab -text $mess  \
	 -width 31 -height 3 -relief flat -fg blue
	pack $warn.lab -in $warn.box
	pack $warn.box
	focus $warn.lab
	if {$con == "no" } {
		set timeout 2
		expect "nothing"
		grab release $warn 
		destroy $warn
	} elseif {$con == "until" } {
		set timeout 20000
		expect $args
		grab release $warn 
		destroy $warn
	} else {return }
	
	#tkwait visibility $warn
}
proc testplot {} {
	global target xlow xupp ylow yupp curse 
	if { $target == "sel" } {
		plotselect .p.larun0 .p.larun1 .p.larun2 .p.larun3 .p.larun4 \
		   .p.larun5 .p.larun6 .p.larun7 .p.larun8 .p.larun9
		set donekid 1
	} else {
		exp_send "p\r"
		expect "HELP or EXIT :" 
	}
}
proc Options { kid } {
	global 	o b d curse plot varname c donekid coun init factorb dop lafont\
		xlow ylow xupp yupp target previous kidy factora rc opstatus \
		setxy barc 
	set donekid {}
#dblocate "init is $init barc is $barc varname is $varname "
	if { $init==0 } {
	set plot 1
	set curse d
	set factora 1.00
	set factorb 1.00
	set init 1
	}
#	set previous(curse) $curse
#	set previous(varname) $varname
#	set previous(xlow) $xlow
#	set previous(xupp) $xupp
#	set previous(ylow) $ylow
#	set previous(yupp) $yupp
#	set previous(factora) $factora
#	set previous(factorb) $factorb
	set kidy [toplevel $kid -takefocus 1]
	
#	set barc 2

	wm group $kid $d
	wm transient $kid $d
	#wm focusmodel $d active
	grab release $d
	focus $kidy
	grab $kidy
	frame $kid.scale -relief raised -borderwidth 3
	frame $kid.scaleup -relief ridge -borderwidth \
	 	3 
	frame $kid.xy -height 1500 -width 100
	frame $kid.low -height 150 -width 150 
	frame $kid.upp -height 15  -width 150 
	frame $kid.left -height 100  -width 160 
	frame $kid.top -height 90 -width 150 
	frame $kid.bot -height 300 -width 150 -relief ridge -borderwidth 3
	frame $kid.right -height 900 -width 150 
 	frame $kid.scales -height 30 -width 150 -relief ridge -borderwidth 3 
	frame $kid.other -height 120 -width 150 -relief ridge 
	frame $kid.bar -width 15  -relief ridge -borderwidth 3
	frame $kid.fac -relief ridge -bd 3
	frame $kid.facab -relief flat -bd 1 
	frame $kid.faca
	frame $kid.facb
	frame $kid.facset
	frame $kid.curseme -relief ridge -bd 3

	label $kid.lfac -text Factor -relief flat   -width 12 
	label $kid.lfaca -text A -relief flat   -width 3 
	label $kid.lfacb -text B -relief flat   -width 3 
	entry $kid.efaca   -width 4 -state disabled -textvariable factora 
	entry $kid.efacb   -width 4 -state disabled -textvariable factorb
	button $kid.bsetab -text {SET FACTOR A B} -state disabled -disabledforeground \
			lightgrey  -command {
		expr $factora
		expr $factorb
		exp_send "s\r"
	 	expect "Type RETURN or option number 1 - 13 :" 
		exp_send "$varname\r" 
		expect "Change these values ? (Y) :"
		exp_send "y\r"
		expect "Factor A  ....  Factor B :"
		exp_send "$factora $factorb\r"
		expect "HELP or EXIT :"
		testplot
		}
	
	label $kid.opstatus -textvariable opstatus -height 1 -fg blue \
		 -relief groove   -width 56
	set rp [frame $kid.plot -height 120 -width 500 -relief ridge \
		-borderwidth 3 ]
	wm title $kid "Options"
	set rt [ frame $kid.type -height 90 -width 150 -relief ridge \
 		-borderwidth 3 ]
	set c 1
	label $kid.lrt -text { Plotting Option Y vs X } -relief raised \
		 -height 2
	pack $kid.lrt -in $rt -side top -fill both
	foreach items { {I(Q) vs Q A-1} {Log(I) vs Q A-1} {Log(I) vs Log(Q) } \
	{Log(I) vs Q**2  A-2 } {CON/I vs Q**2 A-2 } {Log(IQ) vs Q**2 A-2 } \
 	{Log(IQ^2) vs Q**2 A-2 } {IQ**4 vs Q**4 A-4 } {I**A vs Q**B } \
	{IQ**A vs Q**B} {Log(IQ^A) vs Q**B} {Log(IQ^A) vs Log(Q**B)} {IQ**4 vs Q A-1 } } {
		radiobutton $rt.$c -variable varname -text $items \
			-value $c   -width 20  -anchor w -relief flat \
			-command { 
			if { $dop == 1 } {
			
			set dop 0
			exp_send "s\r"
	 		expect "Type RETURN or option number 1 - 13 :" 
			exp_send "$varname\r" 
			expect "HELP or EXIT :" {
				if { [getbound] == 0 } {  }
				set opstatus {}
				$kidy.facab config -relief flat
				$kidy.bsetab config -state disabled
$kidy.efaca config -state disabled
$kidy.efacb config -state disabled
				} \
 			       "Change these values ? (Y) :" { 
				set opstatus {Factors A&B may be modified }
					exp_send "\r" 
				expect "HELP or EXIT :"
				if { [getbound] == 0 } { set donekid 1 } 
				exp_send "s\r"
	 			expect "Type RETURN or option number 1 - 13 :"
				exp_send "$varname\r"
				expect -re "Factor A is ((.*),  factor B is (.*))\r\n"
				#puts stdout "xxxxxxx $expect_out(1,string) W "
				set factora $expect_out(2,string)
				set factorb $expect_out(3,string)
				$kidy.facab config -relief flat
				$kidy.bsetab config -state normal 
$kidy.efaca config -state normal
$kidy.efacb config -state normal
				exp_send "\r"
				expect "HELP or EXIT :"
				 } 
			testplot
			set dop 1
 			} }
		pack $rt.$c -side top -fill both                             
		incr c
	} 
	entry $kid.exl -textvariable xlow -relief sunken   -width 10
	entry $kid.exu -textvariable xupp -relief sunken   -width 10
	entry $kid.eyl -textvariable ylow -relief sunken   -width 10
	entry $kid.eyu -textvariable yupp -relief sunken   -width 10
	label $kid.ls -text {Scale} -relief flat 
	label $kid.lsx -text {X :} -relief flat 
	label $kid.lsy -text {Y :} -relief flat  
	label $kid.lsl -text {LowerLimit} -relief flat   
	label $kid.lsu -text {UpperLimit} -relief flat -padx 1 
	label $kid.lcurs -text { Cursor } -relief raised 
	label $kid.lplot -text { View } -relief raise 
	
	radiobutton $rp.sin -text {Single} -variable plot -anchor w -value 1  \
		-command { set plot 1 }
	radiobutton $rp.mul -text {Multiple} -variable plot -anchor w -value 2 \
		-command { set plot 2 }
  	button $kid.bsetup -text {Set X Y Limits} -width 13 -height 2 \
		-state disabled -disabledforeground lightgrey  -command {
		expr $xlow 
		expr $xupp 
		expr $ylow 
		expr $yupp 
		exp_send "x\r"
		expect "Type RETURN use values or give new values XMIN XMAX :"
		exp_send " $xlow $xupp\r"
		expect "HELP or EXIT :" 
		exp_send "y\r"
		expect "Type RETURN use values or give new values YMIN YMAX :"
		exp_send " $ylow $yupp\r"
		expect "HELP or EXIT :"
		testplot
		$kidy.bsetup config -state disabled 
		}  	 
	button $kid.bdef -text {Auto Scale}  -width 13 -height 2 -command {
		exp_send "x\r"
		expect -re "Spectra min. ((.*)max (.*))\r\n      Plot"
		set xlow $expect_out(2,string)
		set xupp $expect_out(3,string)
		#puts stdout "$xlow pp $xupp"
		exp_send " $xlow $xupp\r"
		#exp_send "\r"
		expect "HELP or EXIT :"
		exp_send "y\r"
		expect -re "Spectra min. ((.*)max  (.*))\r\n      Plot"
		set ylow $expect_out(2,string)
		set yupp $expect_out(3,string)
		exp_send " $ylow $yupp\r"
 		#exp_send "\r"
		expect "HELP or EXIT :"
		testplot
		}
	button $kid.ok -text Close   -width 8 -height 2 -command {\
		testplot
		
#dblocate " $barc  barc"
         	set donekid 1
	}
	button $kid.cancel -text Dismiss   -width 8 -height 2 -command {\
#his does not do anything since the commands are never resent  (Ron-2010)
		set donekid 1
	}
	label $kid.bar1 -text {Error bars}  -relief flat 
	radiobutton $kid.b0 -text {none} -variable barc -value 1 \
	-anchor w -command { exp_send "b\r"
 		   expect "curve only :"
		   exp_send "0\r"
		   expect "HELP or EXIT :" 
		   testplot }
#	$kid.b0 select
	radiobutton $kid.b1 -text { on last choice} -variable barc -value 2 \
	-anchor w -command { exp_send "b\r"
 		   expect "curve only :"
		   exp_send "L\r"
		   expect "HELP or EXIT :" 
		   testplot }
	radiobutton $kid.b2 -text {on all choices} -variable barc -value 3\
	-anchor w -command { exp_send "b\r"
 		   expect "curve only :"
		   exp_send "A\r"
		   expect "HELP or EXIT :"
		   testplot  }
	pack $kid.bar1 $kid.b0 $kid.b1 $kid.b2 -in $kid.bar -side top -expand 1 -fill both
	pack $kid.bsetab -in $kid.facset -expand 1 -fill both -padx 39 -pady 5
	pack $kid.lfaca $kid.efaca -in $kid.faca -side left -expand 1 -fill both
	pack $kid.lfacb $kid.efacb -in $kid.facb -side left -expand 1 -fill both
	pack $kid.faca $kid.facb -in $kid.facab -side left -expand 1 -fill both 
	pack $kid.lfac $kid.facab $kid.facset -in $kid.fac -side top -expand 1 \
		 -fill both -padx 2 -pady 2
	pack $kid.fac  -in $kid.other -side left -expand 1 -fill both
 	pack $kid.bsetup $kid.bdef -in $kid.scale -side left -expand 1 -pady 5 \
	-padx 10 -anchor n 
	pack $kid.ls $kid.lsx $kid.lsy -in $kid.xy -side top -expand 1 -pady 10
	pack $kid.lsl $kid.exl $kid.eyl -in $kid.low -side top -expand 1 \
		-pady 10
	pack $kid.lsu $kid.exu $kid.eyu -in $kid.upp -side top -expand 1 \
		-pady 10 -padx 12
	pack $kid.xy $kid.low $kid.upp  -in $kid.scaleup -side left \
		-pady 1 -anchor n -padx 5
	pack $kid.scaleup $kid.scale -in $kid.scales -side top -fill both \
	-expand 1 
	pack  $rt -in $kid.left -side top -expand 1 -fill both 
	pack $kid.lplot $rp.sin $rp.mul -in $kid.plot -side top \
		-fill both
	pack $kid.scales $kid.other $kid.bar -in $kid.right -expand 1 -side top \
		-fill both	
	pack $kid.left $kid.right -in $kid.top -side left -expand 1 -fill both
	pack $kid.ok  -in $kid.bot -side left -expand 1 -fill both \
		-pady 10 -padx 10
	pack $kid.opstatus $kid.top $kid.bot -side top -expand 1 -fill both

	bind $kid.bdef <ButtonPress-1> { focus $kidy.opstatus 
				set opstatus { }
	}
	bind $kid.exl <KeyPress> { set opstatus { Click on "Set x y" to lock \
		scale } 
		$kidy.bsetup config -state normal }
	bind $kid.exu <KeyPress> { set opstatus { Click on "Set x y" to lock \
		scale } 
		$kidy.bsetup config -state normal }
	bind $kid.eyl <KeyPress> { set opstatus { Click on "Set x y" to lock \
		scale } 
		$kidy.bsetup config -state normal }
	bind $kid.eyu <KeyPress> { set opstatus { Click on "Set x y" to lock \
		scale } 
		$kidy.bsetup config -state normal }
	bind $kid.bsetup <Button-1> { focus $kidy.opstatus
		set opstatus { }
		set setxy 1
		$d.bdef config -state normal
		 }
	bind $kid.bdef <Button-1> { focus $kidy.opstatus
#		set opstatus { }
		set setxy 0
		$d.bdef config -state disabled
		 }
	bind $kid.efaca <KeyPress> { set opstatus { Click on "Set A B" to lock \
		factor } }
	bind $kid.efacb <KeyPress> { set opstatus { Click on "Set A B" to lock \
		factor } }
	bind $kid.bsetab <Button-1> { focus $kidy.opstatus
		set opstatus { } }
        wm geometry $kid +10+10
 	tkwait variable donekid
	grab release $kidy 
	destroy $kidy
}
proc isselect { args } {
global color
	foreach term $args {
	set color [$term cget -bg ]
	if { $color == $selectbg } {
		return 1  
	   }  
	}
	return 0
}
proc Sel { term ent } {
global color unselectbg selectbg unselectfg selectfg selrunsfg items
	set color [$term cget -bg ]
	if { $color == $selectbg } {
		$term config -bg $unselectbg  
		$term config -selectbackground $unselectbg  
		$term config -selectforeground $selrunsfg
		$term config -fg $selrunsfg
		$ent config -bg $unselectbg 
		#$ent config -fg $unselectfg
		$ent config -fg $selrunsfg

	} else { 
		$term config -bg $selectbg
 		$term config -selectbackground $selectbg
		$term config -selectforeground $selectfg
		$term config -fg $selectfg
		$ent config -bg $selectbg
		$ent config -fg $selectfg
		}
	return term
}
proc del { dst args } {
global color items putnum itnom d factorlist selectbg setxy xlow ylow xupp yupp
	set count 0
	for {set n -1} {$n < 10} {incr n} { 
		global factor$n
		set factor$n {}
	}
	set n -1
	foreach term $args {
		incr n
		$term delete 0 end
		set color [$term cget -bg]
		set nio2 ".p.efac$n"
		.p.efac$n config -state disabled
		if { $color == $selectbg } {
			Sel $term $nio2
			$term config -bg #9900991B99FE
			
			set factor$n {}
			set items [lreplace $items $count $count]
			set itnom [lreplace $itnom $count $count]
			set factorlist [lreplace $factorlist $count $count]
		} else { 
			incr count
		}
	}
	set count 0
	$d.bRPlot config -state disabled
	$d.bRPost config -state disabled
	$d.bROption config -state disabled
	$d.bcursor config -state disabled
	$d.bclean config -state disabled
	$d.bdef config -state disabled
	set i 0
	foreach item $itnom {
		$d.bRPlot config -state normal
		$d.bRPost config -state normal
		$d.bROption config -state normal
		$d.bcursor config -state normal
		$d.bclean config -state normal
		$d.bdef config -state normal
		.p.efac$count config -state normal
		$dst$count insert 0 $item
		set factor$count [lindex $factorlist $count]
		incr count
	} 
	set putnum $count
	if {$items != {} } {
	  exp_send "r\r"
	  expect "Run number...ext...divider : "
	  foreach item $items {
		exp_send "$item\r"
		expect "Run number...ext...divider : "
	  }
	  exp_send "\r"	
	  expect "HELP or EXIT :"
	} else {
	exp_send "z\r"	
	  expect "HELP or EXIT :"
	}
	checko bs1 $putnum  
	$d.bRClear config -state disabled 
	$d.bRNext config -state disabled 
	set state [$d.bRPlot cget -state]
	if {$state == "normal" && $items != {} } {
		keepbound
	}
	
	if {$setxy == 1 && $items != {} } {
	shaffle
	keepbound
	}
	if {$setxy == 0 && $items != {}} {
	shaffle
	getbound
	}
	exp_send "p\r"	
	puts stdout "LLLL $setxy"
	 expect "HELP or EXIT :"
}
proc clear1 { args } {
global color items putnum itnom d factorlist selectbg
	set count 0
	for {set n -1} {$n < 10} {incr n} { 
		global factor$n
		set factor$n {}
	}
	set n -1
	foreach term $args {
		incr n
		$term delete 0 end
		set color [$term cget -bg]
		if { $color == $selectbg } {
			$term config -bg #9900991B99FE
			set nio2 ".p.efac$n"
			Sel $term $nio2
			set factor$n {}
		}
		
	}
	set putnum 0
	set items {}
	set itnom 0
	set factorlist {}
}
proc clear { args } {
global color items putnum itnom d factorlist selectbg
	set count 0
	for {set n -1} {$n < 10} {incr n} { 
		global factor$n
		set factor$n {}
	}
	set n -1
	foreach term $args {
		incr n
		$term delete 0 end
		if {[lindex $items $n] != {} } {
		$term config -bg $selectbg
		}
	}
			
}
proc activater { but1 but2 args } {
global select selectbg 
	set select 0
	foreach term $args {
		set color [$term cget -bg ]
	   	if { $color == $selectbg } {
			set select 1	
		}
	}
	if {$select == 1} { 
		$but1 config -state normal
		$but2 config -state normal

	} else { 
		$but1 config -state disabled
		$but2 config -state disabled
	}
}
proc namecompare {a b} {
	set alast [lindex [split $a .] 0]
	set blast [lindex [split $b .] 0 ]
	set res [string compare $alast $blast]
	if {$res != 0 } {
		return $res
	} else {
		return [string compare $a $b]
	}
}	
proc extcompare {a b} {
	set alast [lindex [split $a .] end]
	set blast [lindex [split $b .] end]
	set res [string compare $alast $blast]
	if {$res != 0 } {
		return $res
	} else {
		return [string compare $a $b]
	}
}
proc check {a b} {
	#puts stdout "aa $a"
	#puts stdout "bb $b"

	if {$b == "non" } {
		return 0 
	} else {
		return 1
	}
}	
proc updaterun {} {
global sou mess warn runspath s1 headprog env
	infor "Searching For New Data..." yes
	update idletasks
	#tkwait visibility $warn
#	set s2 [glob g\[0\-9\]?????.???]
        set s2 [glob {g[0-9][0-9][0-9][0-9][0-9][0-9].[0-9][0-9][0-9]} ]
	if { [string compare $s1 $s2] == 0} {
	grab release $warn 
	destroy $warn 
	return
	} 
	set s1 $s2
	$sou delete 0 end
	set n [lsort -command extcompare \
[glob {g[0-9][0-9][0-9][0-9][0-9][0-9].[0-9][0-9][0-9]} ] ]
#	set m "$headprog -1 $n > sri.dat"
	eval { exec $headprog } -1 $n >sri.dat
	set fileid [open sri.dat {RDONLY} ]
	if { [llength $n ] != 1} {
	while { [gets $fileid line] >= 0 } {
      		set name [string range $line 5 10]
      		set ext [string range $line 12 14]
      		gets $fileid line
      		set title [string range $line 0 19]
		gets $fileid line
		$sou see end
		$sou insert end "$name $ext $title"
		update idletasks
		}
	} else {
	        set datas [string range $n 1 6]
		set ext [string range $n 8 10]
		gets $fileid line
		set title [string range $line 0 19]
		$sou see end
		$sou insert end "$datas $ext $title"
		update idletasks
	}
	close $fileid  
	grab release $warn 
	destroy $warn 
}
proc ListSelect { parent choices } {
	global done items list dst putnum plotm_id spawn_id datas color we status unselectfg\
	dop select d win starter who runspath factorlist target warn mess lafont \
	curse runspath sou avairunsfg selrunsfg s1 headprog env
	set items {}
	set select {}
	set dop 1
	set done {}
	set nom {}
	set target {}
 	set d [toplevel $parent]
	#wm transient $d $warn
	#wm focusmodel $d active
	set dst $parent.picked.list
	set sou $parent.choices.list
	#wm minsize $parent 19 15	
	#wm focusmodel $warn passive
	wm geometry $parent +10+10
	#grab release $warn 
	#destroy $warn
	
	wm title $parent "xmplot version 2.5 sri/reg  March 2010"	
	frame $parent.first -height 300 -width 200 -relief groove -borderwidth 5 
	frame $parent.picked -width 200 -height 200
	frame $parent.sub2 -width 200 -height 20	
	frame $parent.ups -height 15 -width 100
	frame $parent.left -height 15 -width 100 
	frame $parent.butbot2 -height 300 -width 200 
	frame $parent.sub -relief ridge -borderwidth 3 -height 450 -width 400
	frame $parent.tophalf -height 15 -width 100 
        frame $parent.bottomhalf -height 15 -width 100 
	frame $parent.sub0 -relief ridge -borderwidth 3 -height 150 -width 100
	frame $parent.butbot1 -height 15 -width 100 
	frame $parent.butbot -height 15 -width 200 -relief ridge -borderwidth 0
	frame $parent.men
	set we [label $parent.larun -text {  Run  Ext  Title } -height 1 -relief groove \
		 -anchor w -pady 3   -width 15]
	button  $parent.bclean -text {Remove Selection} -width 14 -height 1 -state disabled \
		-disabledforeground lightgrey -command  { 
		clear $t0 $t1 $t2 $t3 $t4 $t5 $t6 $t7 $t8 $t9
		del $we $t0 $t1 $t2 $t3 $t4 $t5 $t6 $t7 $t8 $t9
		set setxy 0
		}
	button  $parent.bcursor -text {Cursor} -width 9 -height 1 -disabledforeground \
		lightgrey  -state disabled -command { 
		exp_send "c\r"
		expect "HELP or EXIT :" 
		exp_send "p\r"
		expect "LEFT MOUSE OR TYPE SPACE FOR X,Y OR RETURN TO CONTINUE" { warning .m }
		exp_send "d\r"
		expect "HELP or EXIT :" 
		} 
	button $parent.bRClear -text {Remove Sub Selection}   -width 18 -height 1 \
		-state disabled -relief raised -disabledforeground lightgrey -command { \
		 del $we $t0 $t1 $t2 $t3 $t4 $t5 $t6 $t7 $t8 $t9
		}
	button $parent.bROption -text {Options..} -width 9 -height 1 \
		-state disabled -disabledforeground lightgrey -relief raised -command { \
		Options .sun
		}
	button $parent.bRPost -text {Print Plot} -width 9 -height 2 \
		-state disabled -relief raised -disabledforeground lightgrey -command { \
		exp_send "w\r"
		expect -re "HELP or EXIT :"
		exp_send "f\r"
		expect -re " %PGPLOT,  Closing file (.*)\r\n "
		set printname $expect_out(1,string)
		#set com1 [exec ls]
		if [ catch { set lppp $env(SAS_PLOTTER) } resul ]  {
                  infor { no printer set in SAS_PLOTTER } no
                } else { 
#		set com1 [exec $com]
### printer message dummied out...
      	if  [catch { exec lp -d$lppp $printname >/dev/null } resul ] {}
		infor Printing.... no
		#puts stdout $com1
		}
                 }
	button $parent.bRPlot -text {Plot Selection} -width 14 \
		-state disabled -height 1 -relief raised -disabledforeground lightgrey -command {\
		set target "all"
		#getbound
		
		set factorlist {}
		foreach w "[$e0 get] [$e1 get] [$e2 get] [$e3 get] [$e4 get] \
		[$e5 get] [$e6 get] [$e7 get] [$e8 get] [$e9 get]" { 
			lappend factorlist $w
			 #puts stdout "iiiii $w"
		}
		set temp $items
		set items {}
		set i 0
		#puts stdout "factor [lindex $factorlist 0]" 
		foreach term $temp {
			lappend items [concat [lrange $term 0 1]  \
				[lindex $factorlist $i ] ]
	     		incr i
		}
		foreach term $factorlist {
		expr $term
		}
		set tmp1 [$d.bRNext cget -state]
		$d.bRPlot config -state disabled
		$d.bRNext config -state disabled
		shaffle
		if {$setxy == 1} {
		keepbound }
		if {$setxy == 0} {
		getbound }
		exp_send "p\r"
		expect "LEFT MOUSE OR TYPE SPACE FOR X,Y OR RETURN TO CONTINUE" {
				warning .warior } \
			"HELP or EXIT :" {
				}
		$d.bRPlot config -state normal
		$d.bRNext config -state $tmp1 
		}
	button $parent.bRNext -text {Plot Sub Selection} -width 18 \
		-state disabled -height 1 -relief raised -disabledforeground \
		lightgrey -command { 
		set factorlist {}
		foreach w "[$e0 get] [$e1 get] [$e2 get] [$e3 get] [$e4 get] \
		[$e5 get] [$e6 get] [$e7 get] [$e8 get] [$e9 get]" { 
			lappend factorlist $w
			 #puts stdout "iiiii $w"
		}
		set temp $items
		set items {}
		set i 0
		foreach term $temp {
			lappend items [concat [lrange $term 0 1] \
				[lindex $factorlist $i ] ]
			expr [lindex $factorlist $i ]
	     		incr i
		}
		$d.bRNext config -state disabled
		$d.bRPlot config -state disabled
		shaffle
		 set target "sel"
		plotselect $t0 $t1 $t2 $t3 $t4 $t5 $t6 $t7 $t8 $t9
		$d.bRNext config -state normal
		$d.bRPlot config -state normal
	}
	button $parent.bRScales -text { Scales } -width 9 -height 1 \
		-relief raised -disabledforeground lightgrey -command {
	}
	button $parent.exit -text { Exit } -width 9 -height 1 \
		-relief raised -disabledforeground lightgrey -command { 
		exp_send "e\r"
		expect "PGPLOT,  Closing file"
		set done 1
	}
	button $parent.bdef -text {Auto Scale} -width 9 -height 2 -state \
		disabled -disabledforeground lightgrey -command {
		exp_send "x\r"
		expect -re "Spectra min. ((.*)max (.*))\r\n      Plot"
		set xlow $expect_out(2,string)
		set xupp $expect_out(3,string)
		#puts stdout "$xlow pp $xupp"
		exp_send " $xlow $xupp\r"
		#exp_send "\r"
		expect "HELP or EXIT :"
		exp_send "y\r"
		expect -re "Spectra min. ((.*)max  (.*))\r\n      Plot"
		set ylow $expect_out(2,string)
		set yupp $expect_out(3,string)
		exp_send " $ylow $yupp\r"
 		#exp_send "\r"
		expect "HELP or EXIT :"
		testplot
		$d.bdef config -state disabled
		}
	label $parent.lstatus -textvariable status -height 1 -fg blue\
		 -relief groove   -width 56
	label $parent.lava -text { Available Data } -height 2 \
		 -relief groove   -width 28 
	button $parent.bupdate -text { Update Data } -height 2 \
		  -width 19 -relief raised -command { updaterun }
	button $parent.bhelp -text { Help } -height 1 \
		  -width 10 -relief raised -command { help }
	label $parent.lsel -text {Selected Data } -height 2 \
		-relief groove  -width 30
	label $parent.ldiv -text {Div} -height 2 \
		-relief groove   -width 4
	set status { Click on Available data for primary selection }	    
	#focus $win
	#grab $parent
	ScrolledListbox2 $parent.choices -width 31 -height 16  \
		-selectmode single -setgrid 0
	#$parent.choices see end
	$parent.choices.list see end
	for {set n 0} {$n < 10} {incr n} { 
	     global  t$n factor$n e$n
	    frame $parent.pick$n -width 200 -height 200
	    set dog t$n
	    set t$n [listbox $parent.larun$n -height 1 -relief groove -width 31 \
			-bg #9900991B99FE -selectbackground brown -fg $selrunsfg ]
	    set e$n [entry $parent.efac$n -relief sunken -state disabled -textvariable \
			factor$n   -width 5 -bg #9900991B99FE -fg $selrunsfg ] 
	   #puts stdout $e0   
 	    pack $parent.larun$n $parent.efac$n -in $parent.pick$n -side left \
		-expand true -fill both
	    pack $parent.pick$n -in $parent.picked -side top -expand true -fill both   
	}
        bind $parent.larun0 <ButtonRelease-1> \
		{ if { [lindex $items 0] != {} } { Sel $t0 $e0
		  activater $d.bRClear $d.bRNext $t0 $t1 $t2 $t3 $t4 $t5 $t6 $t7 $t8 $t9 
	 } }
	bind $parent.larun1 <ButtonRelease-1> \
		{ if { [lindex $items 1] != {} } { Sel $t1 $e1
		  activater $d.bRClear $d.bRNext $t0 $t1 $t2 $t3 $t4 $t5 $t6 $t7 $t8 $t9
	 } }
	bind $parent.larun2 <ButtonRelease-1> \
		{ if { [lindex $items 2] != {} } { Sel $t2 $e2
		  activater $d.bRClear $d.bRNext  $t0 $t1 $t2 $t3 $t4 $t5 $t6 $t7 $t8 $t9
	 } }
	bind $parent.larun3 <ButtonRelease-1> \
		{ if { [lindex $items 3] != {} } { Sel $t3 $e3
	  	activater $d.bRClear $d.bRNext  $t0 $t1 $t2 $t3 $t4 $t5 $t6 $t7 $t8 $t9
	} }
	bind $parent.larun4 <ButtonRelease-1> \
		{ if { [lindex $items 4] != {} } { Sel $t4 $e4
	  	activater $d.bRClear $d.bRNext  $t0 $t1 $t2 $t3 $t4 $t5 $t6 $t7 $t8 $t9
	} }
	bind $parent.larun5 <ButtonRelease-1> \
		{ if { [lindex $items 5] != {} } { Sel $t5 $e5
	  	activater $d.bRClear $d.bRNext  $t0 $t1 $t2 $t3 $t4 $t5 $t6 $t7 $t8 $t9
	} }
	bind $parent.larun6 <ButtonRelease-1> \
		{ if { [lindex $items 6] != {} } { Sel $t6 $e6
	  	activater $d.bRClear $d.bRNext  $t0 $t1 $t2 $t3 $t4 $t5 $t6 $t7 $t8 $t9
	}  }
	bind $parent.larun7 <ButtonRelease-1> \
		{ if { [lindex $items 7] != {} } { Sel $t7 $e7
	  	activater $d.bRClear $d.bRNext  $t0 $t1 $t2 $t3 $t4 $t5 $t6 $t7 $t8 $t9
	} }
	bind $parent.larun8 <ButtonRelease-1> \
		{ if { [lindex $items 8] != {} } {Sel $t8 $e8
	  	activater $d.bRClear $d.bRNext  $t0 $t1 $t2 $t3 $t4 $t5 $t6 $t7 $t8 $t9
	} }
	bind $parent.larun9 <ButtonRelease-1> \
		{ if { [lindex $items 9] != {} } { Sel $t9 $e9
	  	activater $d.bRClear $d.bRNext  $t0 $t1 $t2 $t3 $t4 $t5 $t6 $t7 $t8 $t9
	} }
	#set putnum $putnum
	pack  $parent.first -fill both -expand true 
	pack $parent.lstatus $parent.butbot2 $parent.butbot -in $parent.first -side top \
		 -expand 1 -fill both -padx 2 -pady 1
	pack $parent.bROption $parent.bcursor $parent.bRPost $parent.bdef \
		$parent.bhelp $parent.exit  -in $parent.butbot -side \
		left -expand 1 -fill both -padx 4 -pady 6  
	pack $parent.sub0 $parent.sub -in $parent.butbot2 -side left -expand 1 \
		 -fill both -padx 10 -pady 5
	pack $parent.ups $parent.tophalf $parent.bottomhalf -in $parent.sub \
		-side top -expand true -fill both -padx 10 -pady 5
	pack $parent.bclean $parent.bRClear -in $parent.bottomhalf \
		-side left -expand true -fill y
	pack $parent.bRPlot $parent.bRNext -in $parent.tophalf -side left \
		-fill y -expand true
	pack $parent.left $parent.picked -in $parent.ups -side top -expand \
		true -fill both 
	pack $parent.bupdate -in $parent.sub2 -expand 1 -fill y
	pack $parent.butbot1 $parent.sub2 -in $parent.sub0 \
		-side top -expand true -fill both -padx 10 -pady 5
	pack $parent.lsel $parent.ldiv -in $parent.left -side left -expand true -fill x 

	pack $parent.lava $parent.choices -in $parent.butbot1 -side top -expand true \
		-fill x 	
	bind $parent.choices.list <ButtonRelease-1> \
		  [ list ListSelectEnd %W %y $parent.larun  \
		  $parent.bRPlot  $parent.bRPost $parent.bROption \
		$parent.bclean $parent.bcursor $parent.bdef] 
 	set i 0
	grab release $warn 
	destroy $warn 
	tkwait visibility $d
	infor "Sorting data..." yes
	update idletasks
	set a1 {g[0-9][0-9][0-9][0-9][0-9][0-9].[0-9][0-9][0-9]*}
	#puts stdout $s1 
	set s1 [glob $a1] 
	#puts stdout $s1	
	set n [lsort -command extcompare $s1]
        eval {  exec $headprog  } -1 $n >sri.dat 
        set fileid [open sri.dat {RDONLY}]
	grab release $warn 
	destroy $warn 
	infor " Transfering data..." yes
	update idletasks
	if { [llength $n ] != 1} {
	while { [gets $fileid line] >= 0 } {
      		set datas [string range $line 5 10]
      		set ext [string range $line 12 14]
      		gets $fileid line
      		set title [string range $line 0 19]
      		gets $fileid line
		$parent.choices.list insert end "$datas $ext $title"
		$parent.choices.list see end
		#puts stdout "$datas $ext $title"
		update idletasks
	}
	} else {
	        set datas [string range $n 1 6]
		set ext [string range $n 8 10]
		gets $fileid line
		set title [string range $line 0 19]
		$parent.choices.list see end
		$parent.choices.list insert end "$datas $ext $title"
		update idletasks
	}
	close $fileid 
	grab release $warn 
	destroy $warn 

	tkwait variable done 
	destroy $parent
	return
	}
proc ListSelectEnd {src y dst args } {
global items putnum xlow xupp ylow yupp itnom dop mal setxy factorlist 
	checko ba1 $putnum  
	if { $dop == 1 } {
	  set dop 0
	  for {set m 0} {$m < 10} {incr m} {
	  	global factor$m .p.efac$m

		lappend factorlist 1
	  }
	  set factor$putnum 1 
	  foreach butt $args {
	  	$butt config -state normal
		puts stdout $butt
		if {$setxy == 0 && $butt == ".p.bdef"} {
		$butt config -state disabled
		}
	  }
	  if { $putnum < 10 } { 
	  .p.efac$putnum config -state normal
	  update idletasks
	  set i [$src nearest $y]
	  $dst$putnum insert 0 [$src get $i]
 	  lappend items [concat [lrange [$src get $i] 0 1]  \
		[lindex $factorlist $putnum ] ]
	  lappend itnom [$src get $i]
	  shaffle
	if {$setxy == 1} {
	  keepbound 
	} else {
	getbound
		}
	  incr putnum
	}
	set dop 1
	}  
}
proc keepbound {} {
global xlow xupp ylow yupp
		exp_send "x\r"
		expect "Type RETURN use values or give new values XMIN XMAX :"
		exp_send " $xlow $xupp\r" 
		expect "HELP or EXIT :"
		exp_send "y\r"
		expect "Type RETURN use values or give new values YMIN YMAX :"
 		exp_send " $ylow $yupp\r"
		expect "HELP or EXIT :"
}
proc getbound {} {
global  xlow xupp ylow yupp donekid done plotm_id spawn_id warn mplotpath
	exp_send "x\r"
	expect -re "Plot    min. ((.*)max (.*))\r" { } \
		"forrtl: error (73): floating divide by zero" {
		infor "Internal Error!! Please Wait..." yes
		set donekid 1
		unset plotm_id
		unset spawn_id
		spawn $mplotpath
		set plotm_id $spawn_id
		shaffle
		grab release $warn
		destroy $warn 
		return 0 
	}
	set xlow $expect_out(2,string)
	set xupp $expect_out(3,string)
	exp_send "\r"
	expect "HELP or EXIT : "
	exp_send "y\r"
	expect -re "Plot    min. ((.*)max (.*))\r"
	set ylow $expect_out(2,string)
	set yupp $expect_out(3,string)
 	exp_send "\r"
	expect "HELP or EXIT : "
	return 1  
}
proc shaffle {} {
global items putnum dop xlow ylow xupp yupp

	exp_send "r\r"
	expect "Run number...ext...divider : "
	exp_send "[lindex $items 0]\r"
	expect "Run number...ext...divider : "
	exp_send "\r"
	expect "HELP or EXIT :"
	set test [expr [llength $items] -2 ]
	set first $items 
	set coun 0
	exp_send "a\r" 
	expect "Run number...ext...divider : "
	foreach item  $items  {
		incr coun
		if { $coun == 10 } { 
			exp_send "$item\r"
			expect "HELP or EXIT :"
			set dop 1
		 	break
		} else {
			if { $coun != 1 } {
			 exp_send "$item\r"
			 expect "Run number...ext...divider :" 
			 } 
			}	
	}
	exp_send "\r"
	expect "HELP or EXIT :"
	#getbound
}
proc shaffle1 {} {
global items putnum dop

	exp_send "r\r"
	expect "Run number...ext...divider : "
	exp_send "[lindex $items 0]\r"
	expect "Run number...ext...divider : "
	exp_send "\r"
	expect "HELP or EXIT :"
	exp_send "a\r"
	expect "Run number...ext...divider : "
	set n 0
	set more $items
	foreach item  $items  {
		incr n
		if {$n != 1 } {
		   exp_send "$item\r"
		   expect "Run number...ext...divider :" 
		}
	}
	exp_send "\r"
	expect "HELP or EXIT :"
}
proc help {} {
	set helpdone {}
	set helps [toplevel .tophelp]
	grab $helps
	set frm [frame $helps.r]
	frame $helps.r2
	text $frm.page -setgrid true -wrap word   -width 42 -height 14 \
		-yscrollcommand "$frm.sy set" -state normal
	scrollbar $frm.sy -orient vert -command "$frm.page yview"
	button $helps.but -text Close -command { set helpdone 1}
	pack $frm.sy -side right -fill y -in $frm
	pack $frm.page -side left -fill both -expand true -in $frm
	pack $helps.but -fill both -expand true -in $helps.r2 
	$frm.page insert end " Under development!\n
	Please send comment to sri@ill.fr" 
	$frm.page config -state disabled 
	pack $frm $helps.r2 -side top -expand true -fill both
	tkwait variable helpdone
	grab release $helps
	destroy $helps
}


######################  dblocate     debug window

proc dblocate  W {
toplevel .dbl
frame .dbl.f
label .dbl.f.label -text " ... $W ..." -fg red
button .dbl.f.but -text "OK" -command {destroy .dbl }
pack .dbl.f.label  .dbl.f.but
pack .dbl.f
focus .dbl
grab set .dbl
tkwait window .dbl
}


wm withdraw . 
infor "Loading MPLOT..." yes
update idletasks
spawn $mplotpath
set plotm_id $spawn_id 
set init 0
set nom [fileselect $runspath ]
exit 0
#:EOF

