#!/bin/csh
set pgm = $0; set pgm = $pgm:t
if ($#argv < 1) then
  error:
  more << "USAGE"
  USAGE:
	$pgm [<label> <data>]+ [options]

	<label>			label for curve  
	<data>			file of points to plot;
				if the file does not exist, then <data>
				is assumed to be a function defined in
				a -misc or -file command
	[-eps|-ps|-png|-pdf <name>]	plot to .eps,.ps,.png or .pdf file <name>.[eps|ps|png|pdf]
				tex file <name>.tex
				plot to screen if <name> is "_screen_"
				default is screen
	[-xlabel <xlab>]	label for x axis
	[-ylabel <ylab>]	label for y axis
	[-xlaboff [<xoff>][,<yoff>]]	offset for label for x axis
	[-ylaboff [<xoff>][,<yoff>]]	offset for label for y axis
	[-xrange [<x1>] : [<x2>]]	range for x axis
	[-yrange [<y1>] : [<y2>]]	range for y axis
	[-key <x> <y>]  	position key at <x,y>
	[-title <title>]	title for plot; underscores are blanked
	[-misc <whatever>]+	any gnuplot command(s) separated by ';'
	[-file <file>]		file containing gnuplot commands;
	[-file_first <file>]	file containing gnuplot commands;
				these commands will be done before -file
				and -misc commands
	[-size <xsize> <ysize>]	scale-factor for size of plot
			        note: use 0.713,0.713 for 9cm wide
	[-point <psize>]	point size for text on plot; default = 11
	[-rm_]			replace underscores with blanks in
				<label>, <xlab> and <ylab>
	[-big]			make 65in, two column figure
	[-[no]color]		make a [non-]color figure
	[-solid]		make all lines solid
	[-f]			force: overwrite files if they exist
	[-nocat]		don't print the plot script; default: cat the script to STDOUT

	Plots one or more curves from files containing <x, y> pairs.
	Default is to screen.
	The -misc commands followed by the -file are done just before
	any plot commands generated by the <label> <data> pairs.

	Underscores in <title> are replaced by blanks.

	Note: to put "<=" in a postscript file, use "{/Symbol \243}".
	Other symbols are given in file symbol_font_codes.ps.

 	Creates files:
		<name>.[eps|ps|png|pdf]
		<name>.tex
		tmp.tex
"USAGE"
  exit 1
endif

set command = ($0 "$*")

onintr cleanup

set ncurves = 0
set label = (1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1)
set data = ""
set misc = ""; 
set point = 11

set miscfile = $pgm.miscfile.$$.tmp

set xlaboff = ""
set ylaboff = ""

set color = ""

set solid = ""

set force = 0

# tex figure parameters
set col = "" 
set width = "\widtha"
set otype = ""

# get input switches
while  ("$1" != "")
  switch ("$1")
  case -eps:
  case -ps:
  case -png:
  case -pdf:
    if ($2 == "_screen_") break
    set name = $2:t; 
    if ("$1" == "-ps" || "$1" == "-eps") then
      set otype = "ps"
      if ("$1" == "-eps") then
        set ext = eps 
      else
        set ext = ps 
      endif
      set out = $2.$ext;
      set out2 = ""
    else if ("$1" == "-pdf") then
      set otype = "pdf"
      set out = $2.pdf;
      set out2 = ""
    else 
      set otype = "png"
      set out = $2.png;
      set out2 = "";
    endif
    shift
    breaksw
  case -key:
    set key = "set key ${2},${3}"; shift; shift; breaksw
  case -xlabel:
    set xlab = "$2"; shift; breaksw
  case -ylabel:
    set ylab = "$2"; shift; breaksw
  case -xlaboff:
    set xlaboff = $2; shift; breaksw
  case -ylaboff:
    set ylaboff = $2; shift; breaksw
  case -xrange:
    shift; 
    if ($1 != ":") then
      set xrange = "[$1 : $3]"; shift; shift;
    else 
      set xrange = "[ : $2]"; shift
    endif
    breaksw
  case -yrange:
    shift; 
    if ($1 != ":") then
      set yrange = "[$1 : $3]"; shift; shift;
    else 
      set yrange = "[ : $2]"; shift
    endif
    breaksw
  case -title:
    set title = `echo $2 | sed s/_/" "/g`; shift; breaksw
  case -misc:
    if !(-e $miscfile) touch $miscfile
    shift; echo "$1" >> $miscfile; breaksw
  case -file_first:
    set gnufile_first = "$2"; shift; breaksw
  case -file:
    set gnufile = "$2"; shift; breaksw
  case -size:
    set xsize = $2; shift; set ysize = $2; shift; breaksw
  case -point:
    shift; set point = $1; breaksw
  case -rm_:
    set rm_ = 1; breaksw
  case -big:
    set col = '*'; set width = "6.5in"; breaksw
  case -color:
    set color = "color"; breaksw
  case -nocolor:
    set color = ""; breaksw
  case -solid:
    set solid = "solid"; breaksw
  case -f
    set force = 1; breaksw
  case -nocat
    set nocat = 1; breaksw
  default:
    @ ncurves++
    if ($ncurves > $#label) then
      echo Too many curves specified | perl -n -e 'print stderr $_'
      exit 1
    endif
    set label[$ncurves] = "$1"
    set data = ($data $2)
    shift; breaksw
  endsw
  shift
#  echo $1
end

# set up the file which will receive the plot 
set gnuplot = $pgm.plotscript.$$.tmp
if ($?out) then
  if ((-e $out) && $force == 0) then
    echo "File $out already exists.  Overwrite? (n)" | perl -n -e 'print stderr $_'
    set ans = $<
    if (!($ans == "y" || $ans == "Y")) then
      exit
    endif
    rm $out
  endif
  echo 'Output will be to file(s)' $out $out2 | perl -n -e 'print stderr $_'
  if ("$otype" == "ps") then
    echo "set terminal postscript eps enhanced $color 'Helvetica' $point" > $gnuplot
  else if ("$otype" == "pdf") then
    echo "set terminal pdf enhanced $color font 'Helvetica' fontscale $point" > $gnuplot
  else
    #set psize = `echo $point | perl -n -e 'printf($_<20 ? "small" : ($_<30 ? "medium" : "large"))'`
    set fontscale = 1
    echo "set terminal png enhanced fontscale $fontscale font 'Helvetica'" > $gnuplot
  endif
  echo "set output '$out'" >> $gnuplot
else
  set terminal x11 enhanced nopersist
  echo Output will be to screen | perl -n -e 'print stderr $_'
  echo -n "" > $gnuplot
endif

# set up the file which will receive the latex figures (.tex file)
if ($?latex) then
  if ((-e $latex) && $force == 0) then
    echo "File $latex already exists.  Overwrite? (n)" | perl -n -e 'print stderr $_'
    set ans = $<
    if ($ans == "y" || $ans == "Y") then
      rm $latex
    else
      set latex = /dev/null
    endif
  endif
  echo -n "" >! $latex

# print the header for a latex document
  echo "\documentstyle[12pt,named]{article}" >! tmp.tex
  echo "\input{macros}" >> tmp.tex
  echo "\input{psfig}" >> tmp.tex
endif

if ($?title) then
  if ($?rm_) set title = `echo $title | sed s/_/" "/g`
  echo "set title '$title'" >> $gnuplot
endif
echo "set style data linespoints" >> $gnuplot
if ($?xlab) then
  if ($?rm_) set xlab = `echo $xlab | sed s/_/" "/g`
  echo "set xlabel '$xlab' $xlaboff" >> $gnuplot
endif
if ($?ylab) then
  if ($?rm_) set ylab = `echo $ylab | sed s/_/" "/g`
  echo "set ylabel '$ylab' $ylaboff" >> $gnuplot
endif
if ($?xrange) then 
  echo set xrange "$xrange" >> $gnuplot
endif
if ($?yrange) then
  echo set yrange "$yrange" >> $gnuplot
endif
if ($?key) then
  echo "$key" >> $gnuplot
endif
if ($?xsize) then
  echo set size $xsize,$ysize >> $gnuplot
endif
if ($?gnufile_first) then
  cat $gnufile_first >> $gnuplot
endif
if (-e $miscfile) cat $miscfile >> $gnuplot
if ($?gnufile) then
  cat $gnufile >> $gnuplot
endif

set plotcmd = plot
set comma = ""
set i=1
while ($i <= $ncurves)
# plot the points
  if ($?rm_) then 
    set curve_title = `echo $label[$i] | sed s/_/" "/g`
  else
    set curve_title = $label[$i]
  endif
  echo "curve ${i}: $curve_title" | perl -n -e 'print stderr $_'
  if (-e "$data[$i]") then
    set plotcmd = "$plotcmd$comma '$data[$i]' title '$curve_title'"
  else
    set plotcmd = "$plotcmd$comma $data[$i] title '$curve_title'"
  endif

  set comma = ","
  @ i++
end
if ($ncurves > 0) then
  echo $plotcmd >> $gnuplot
endif

if (!($?out)) then
  echo "pause 1e10 'Hit cntrl-C to exit: '" >> $gnuplot
else
  # make a latex file if required
  if ($?latex) then
    echo "\begin{figure$col}" >> $latex
    echo "\centerline{" >> $latex
    echo "  \psfig{figure=$out,width=$width}" >> $latex
    echo "}" >> $latex
    echo "\caption{$name}" >> $latex
    echo "\label{fig:$name}"  >> $latex
    echo "% $command" >> $latex
    echo "\end{figure$col}" >> $latex
    echo "\markfigure{\ref{fig:$name}}" >> $latex
  endif
endif

# end the latex document
if ($?latex) then
  echo  "\begin{document}" >> tmp.tex
  echo  "\input{$latex2}" >> tmp.tex
  echo  "\end{document}" >> tmp.tex
endif

# print the script if desired
if (!($?nocat)) then
  cat $gnuplot | perl -n -e 'print stderr $_'
endif

# execute the gnuplot script, capturing errors and printing them
gnuplot -bg white $gnuplot

cleanup:
rm $pgm.*.$$.tmp
