#!/bin/sh
#
# Generate gnuplot commands to plot a "table".  (see also [un]make-table).
# 
# With no flags, generates the commands to standard output
# if -x* or -g*, or -p* is given, runs gnuplot and produces output for
# X11, or GIF, or PostScript respectively (the latter two in files)
#
# Corey Satten, corey @ cac.washington.edu, 3/6/97
# http://staff.washington.edu/corey

TITLE=FILENAME

for i in $*; do
    case "$1" in
	-s*) SLEEP="$2"; shift;;	# sleep at end if piping to gnuplot
	-g*) GIF=1;;			# go direct to *.gif file
	-x*) X11=1;;			# plot directly to X11 display
	-p*) PS=1;;			# go direct to *.ps file
	-t*) TITLE="\"$2\""; shift;;	# plot title (else filename)
	*)   break;;
    esac
    shift
done

FILE="$1"

AWKPROG='
NR==1	{for (i=2; i<=NF; ++i) col[i] = $i}
NR >1	{row[NR-1] = $1; for (i=2; i<=NF; ++i) if ($i > maxy) maxy = $i}
END	{if (NR <= 30) Ntics = int((NR-2)/(int((NR-1)/10)+1))
	 else Ntics = 8
	 printf("set xtics (")
         for(i=0; i<=Ntics; ++i) {
	    x = int(1+i*(NR-2)/Ntics)
	    printf("%s \"%s\" %d", c, row[x], x)
	    c=","
	    }
        printf(")\n")
	printf("set xrange [1:%d]\n", NR-1)
	printf("set key outside\n")
	printf("set data style lines\n")
	printf("set grid\n")
	printf("set title \"%s\"\n", '"$TITLE"')
	cmd = "plot"
	for (i=2; i<=NF; ++i) {
	    printf("%s \"%s\" u 0:%d title \"%s\"", cmd,FILENAME,i,col[i])
	    cmd = ","
	    }
	printf("\n");
        }'

case "$GIF/$PS/$X11" in
   //)  awk "$AWKPROG" $FILE
	case "$SLEEP" in '');; *) sleep $SLEEP;; esac
	;;
  1//)  BASE=`echo $FILE | sed 's#.*/##; s#\.[^.]*$##'` # basename
	(echo "set term gif medium"
	 echo "set output \"$BASE.gif\""
	 awk "$AWKPROG" $FILE) | gnuplot3.6
	;;
  /1/)  BASE=`echo $FILE | sed 's#.*/##; s#\.[^.]*$##'` # basename
	(echo "set term postscript color"
	 echo "set output \"$BASE.ps\""
	 awk "$AWKPROG" $FILE) | gnuplot3.6
	;;
  //1)  (awk "$AWKPROG" $FILE) | gnuplot3.6 -persist
	;;
esac
