#! /bin/bash
lname=$1
name=${1%.*}
echo "name $name lname $lname"
if test $lname = $name ; then
  # look first for a .jog then a .g then give up
  if test -f $name.jog ; then
    lname=$name.jog
  elif test -f $name.g ; then
    lname=$name.g
  else
    echo "no $1.jog or $1.g file"
    exit 1
  fi
fi
echo "name $name lname $lname"
suf=${lname##*.}
echo "suf  $suf"
# now the suf is known and name is completed with suffix .g or .jog
if test $suf = "jog" ; then
  echo "is a jog file"
  prog="/usr/local/jog07/src/jog"
elif test $suf = "g" ; then
  echo "is a ProG file"
  prog="/usr/local/prog/prog2004"
  if ! test -f $prog; then
    echo "ProG is not installed on your system"
    exit 1
  fi
else
  echo "Don't know what kind of file"
  exit 1
fi
if test -f $lname ; then
  echo "Make an eps of $lname with $prog"
else
  echo file "$lname not found"
  exit 1
fi
# may be "ge foo/bar/g1.jog"
# ensures that g1.eps is located in the same directory
# as the source file...
rep=${lname%/*}
if [ -d ${rep} ]
then
  cd ${rep}
fi
if $prog < ${lname} > ${name}.ps ; then
  # Fit BB to drawing
  echo "gs -q -dNOPAUSE -sDEVICE=bbox -- ${name}.ps 2> _BB"
  gs -q -dNOPAUSE -sDEVICE=bbox -- ${name}.ps 2> _BB
# retrieves the bounding box from file _BB
# add a 10 pt white margin
  BB=$(awk '!/Hi/{print($1 " " $2-10 " " $3-10 " " $4+10 " " $5+10)}' _BB)
# insert bounding box comment where it belongs and remove the showpage
  awk -vBB="$BB"  '{
    if ( /%%Bou/ ){
        printf("%s\n",BB)
    } else if ( /showpage/ ) {
        print "% showpage"
    } else {
        print($0)
    }
  }' ${name}.ps > ${name}.eps
  rm _BB
  rm ${name}.ps
  #gv ${name}.eps
else
  @echo "This command failed:"
  @echo "$prog < ${lname} > ${name}.ps"
  exit 1
fi

# Now find if gv is running or not on the same image
# if not start gv (should be in follow mode...)
# TODO make sure gv exist fold back on something else...
if ps -o args -C gv | grep ${name}.eps ; then
  echo "gv already running on this file in watch mode"
else
  gv --safer --quiet --watch ${name}.eps
fi
