
proc init_GNUPLOT {} {
global wpp 
    set wpp -1
}


proc window_GNUPLOT {title {geometry 600x250}} {
global vp wpp 
# initialize the geometry if it hasn't been done already
    incr wpp
    if {![info exists vp($wpp)]} {set vp($wpp) [open |gnuplot w+]}
    puts $vp($wpp) "set title \"$title\""
    return $wpp
}

#
# plot_GNUPLOT  Plot data using the GNUplot package.
#
# This version expects 1D data in columns
#
# window - Identifies a window to display the plot
# axstyle - defines the type of axes to use
# args - a list of lists, each containing {filename format graphstyle legends}
#
proc plot_GNUPLOT {window axstyle args} {
    global vp

global script

    set script {plot}
    foreach graph $args {
	if {$script != {plot}} {set script "$script ,"}
	set infile [lindex $graph 0]
	set format [lindex $graph 1]
	set graphstyle [lindex $graph 2]
	set legends [lindex $graph 3]
	if {![file exists $infile]} {return 1}
	set d1 [get_dims $infile]
	set nsets [lindex $d1 1]
	case $format in {
	    {y xy} {
		set script "$script \"$infile\""
	    }
	    {xydx xydxdx xydydy} {
		set script "$script \"$infile\" with errorbars"
	    }
	    xy1y2... {
		for {set i 2} {$i <= $nsets} {incr i} {
		    set script "$script \"$infile\" using $i"
		    if {[set title [lindex $legends [expr $i - 2]]] == {}} { 
			set script "$script title \"Component [expr $i - 1]\""
		    } else {
			set script "$script title \"$title\""
		    }
		    if {$i < $nsets} {set script "$script ,"}
		}
		set legends {}
	    }
	    hdf {}
	    ncdf {}
	}
	case $graphstyle in {
	    curve {}
	    scatter {set script "$script with points"}
	}
	if {$legends != {}} {set script "$script title \"$legends\""}
    }
    puts $vp($window) "set data style lines"
    case $axstyle in {
	linear { puts $vp($window) "set nologscale xyz" }
	log-linear { puts $vp($window) "set logscale x" }
	linear-log { puts $vp($window) "set logscale y" }
	log-log	{ puts $vp($window) "set logscale xy" }
    }

    #
    # Plot the data
    puts $vp($window) $script
    flush $vp($window)
}


proc close_GNUPLOT {} {}
