#!/usr/bin/env bash
#
# $Id: browser,v 1.16 2004/06/21 08:25:57 kleing Exp $
# Author: Markus Wenzel, TU Muenchen
#
# DESCRIPTION: Isabelle graph browser


PRG="$(basename "$0")"

function usage()
{
  echo
  echo "Usage: $PRG [OPTIONS] [GRAPHFILE]"
  echo
  echo "  Options are:"
  echo "    -d           delete file after use"
  echo "    -o FILE      output to FILE (ps, eps, pdf)"
  echo
  exit 1
}

function fail()
{
  echo "$1" >&2
  exit 2
}


## process command line

# options

DELETE=""
OUTFILE=""

while getopts "do:" OPT
do
  case "$OPT" in
    d)
      DELETE=true
      ;;
    o)
      OUTFILE="$OPTARG"
      ;;
    \?)
      usage
      ;;
  esac
done

shift $(($OPTIND - 1))


# args

GRAPHFILE=""
[ "$#" -gt 0 ] && { GRAPHFILE="$1"; shift; }
[ "$#" -ne 0 ] && usage


## main

export CLASSPATH="$ISABELLE_HOME/lib/browser/GraphBrowser.jar"
if [ -z "$GRAPHFILE" ]; then
  cd "$ISABELLE_BROWSER_INFO"
  exec java GraphBrowser.GraphBrowser
else
  PDF=""
  case "$OUTFILE" in
    *.pdf)
      OUTFILE="${OUTFILE%%.pdf}.eps"
      PDF=true
      ;;
  esac

  if [ -z "$OUTFILE" ]; then
    java GraphBrowser.GraphBrowser "$GRAPHFILE"
  else
    java GraphBrowser.Console "$GRAPHFILE" "$OUTFILE"
  fi
  RC="$?"

  if [ -n "$PDF" ]; then
    "$ISABELLE_EPSTOPDF" "$OUTFILE" || fail "Failed to produce pdf output"
  fi

  [ -n "$DELETE" ] && rm -f "$GRAPHFILE"
fi

exit "$RC"
