#! /bin/sh

############################################################
# This shell script is a "front-end" to twobody which 
# expedites the analysis of the results from that code,
# including the generation of Postscript plots of the 
# particle position, d(energy), d(angular momentum) as a 
# function of time using gnuplot.
############################################################
P=`basename $0`

############################################################
# Set defaults 
############################################################
tmax=5.0
dt=0.05
tol=1.0d-6

############################################################
# Usage
############################################################
Usage() {
cat<<END
usage: $P <y0> [<tol>]

       Default tol: $tol

       y0 = 1.0 will produce circular orbit.

       To enable automatic previewing of Postscript files
       set GV environment variable to any non-blank
       value, e.g.
   
       setenv GV on
END
exit 1
}

############################################################
# Subroutine (fcn) to produce postscript version of 
# gnuplot plot of data stored in file $1.  Postscript 
# file will be called $1.ps.  If optional second argument
# is supplied, the resulting Postscript file will be 
# 'gv'ed.   
############################################################
gnuplot_it() {
gnuplot<<END
   set terminal postscript portrait
   set size square
   set xlabel "x"
   set ylabel "$1"
   set output "$1.ps"
   plot "$1"
   quit
END
if test "${2}undefined" != undefined; then
   if [ -f $1.ps ]; then
      (gv $1.ps) &
   else
       echo "gnuplot_it: $f.ps does not exist"
   fi
fi
}

############################################################
# Argument handling
############################################################
case $# in
1|2) y0=$1; tol=${2-$tol};;
*) Usage;;
esac

############################################################
# Build application, run it, and process the results.
############################################################
make -f Makefile twobody

tag="$y0"-"$tol"
ofile=out-$tag

twobody 0.0 $y0 1.0 0.0 $tmax $dt $tol > $ofile

nth 2 3 < $ofile > xcyc-$tag
nth 1 2 < $ofile > xc-$tag
nth 1 3 < $ofile > yc-$tag
nth 1 4 < $ofile > dEtot-$tag
nth 1 5 < $ofile > dJtot-$tag

for f in xcyc-$tag xc-$tag yc-$tag dEtot-$tag dJtot-$tag; do
   gnuplot_it $f $GV
   /bin/rm $f
done
/bin/ls -l *$tag*.ps

exit 0