
proc init_XGRAPH {} {
    global vp wpp
    set wpp -1
}


proc window_XGRAPH {title {geometry 600x250}} {
    global vp wpp 
# initialize the geometry if it hasn't been done already
    incr wpp
    set vp(title$wpp) $title
    return $wpp
}


#
# Plot 1 dimensional data from a file
#
# This version expects columnar data
#
proc plot_XGRAPH {window axstyle args} {
    global vp XGRAPH
    case $axstyle in {
        linear { set graphtype " -graphtype xy" }
        log-linear { set graphtype " -graphtype logx" }
        linear-log { set graphtype " -graphtype logy" }
    }
    set xgflags "-p /opt/local/bin/xgrdefault.par -autoscale xy $graphtype"
    lappend xgflags -pexec "title \"$vp(title$window)\""
    set gset -1
    foreach graph $args {
	set infile [lindex $graph 0]
	set format [lindex $graph 1]
	set graphstyle [lindex $graph 2]
	set legends [lindex $graph 3]
	incr gset
	if {![file exists $infile]} {return 1}
	set d1 [get_dims $infile]
	set nsets [lindex $d1 1]
	case $format in {
	    y {
		set format xy
	    }
	    xy {      }
	    {xydx xydxdx} { set format "$format -p /opt/local/bin/error.par" }
	    xydydy {
		set format "$format -p /opt/local/bin/error.par"
		exec awk {{print $1, $2, $4-$2, $2-$3}} $infile >$infile.tmp
		set infile $infile.tmp
	    }
	    xy1y2... {
#		set format {nxy -p LIB_PATH/nxy.par}
		set format nxy
	    }
	    hdf {}
	    ncdf {}
	}
	case $graphstyle in {
	    scatter {
		lappend xgflags -pexec "s$gset symbol 4"
		lappend xgflags -pexec "s$gset symbol fill 1"
		lappend xgflags -pexec "s$gset linestyle 0"
	    }
	}
	set xgflags "$xgflags -$format $infile"
	if {$legends != {}} {lappend xgflags -pexec "legend string $gset \"$legends\""}
    }
#		set xgflags "$xgflags -pexec s$gset symbol fill 1'"
#		set xgflags "$xgflags -pexec 's$gset linestyle 0'"

# Plot the data
#  open XGRAPH as a standalone process, save the PID in array vp.
    catch {set vp(old) $vp($window)}
    set vp($window) [eval exec $XGRAPH $xgflags [list -name $vp(title$window)] &]
    catch {exec kill $vp(old)}
}


proc close_XGRAPH {} {
	global vp
	if [info exists vp] {
	    foreach pid [array names vp] {catch {exec kill $vp($pid)}}
	}
}


#
# sqrt  Return an approximation of the square root of y
#
proc sqrt {y} {
    set x [expr $y * 1.189]
    for {set i 0} {$i < 5} {incr i} {
	set x [expr ($x + $y / $x) * 0.5]
    }
    return $x
}
