#!/usr/pkg/bin/bash
#
#  Eukleides version 1.5.4
#  Copyright (c) Christian Obrecht 2004-2010
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

usage() {
cat <<- USAGE
Usage is: euktoeps [<option> ...] <input_file>
-i, --include=<string>		Include LaTeX directives in preamble.
-l, --locale[=<lang>]		Use localized keywords (possibly disabled).
-#, --interactive=<string>	Modify interactive variables.
-d, --data=<data_file>		Use specific data.
-v, --version			Print version number and exit.
-h, --help			Print this help and exit.
USAGE
exit $1
}

args=$(/usr/pkg/bin/getopt -o i:l::#:d:vh --long include:,locale::,interactive:,data:,version,help \
       -n 'Euktoeps' -- "$@")

if [ $? -ne 0 ]
then
  usage 1
fi

eval set -- "$args"

batchmode=-b

while true
do
  case "$1" in
    -h|--help)		usage 0 ;;
    -v|--version)	echo "Euktoeps version 1.5.4"
			echo "Copyright (c) Christian Obrecht 2004-2010"
			exit 0 ;;
    -i|--include)	include=$2
			shift 2 ;;
    -l|--local)		case "$2" in
				"") lang=-l; shift 2 ;;
				*)  lang=-l$2 ; shift 2 ;;
			esac ;;
    -#|--interactive)	interactive=-#$2
			shift 2 ;;
    -d|--data)		batchmode=-b$2;
    			shift 2 ;;
    --)			shift
    			break ;;
    *)			echo "Internal error. Exiting."  > /dev/stderr
    			exit 1 ;;
  esac
done

if [ ! $1 ]
then
  usage 1
fi

if [ ! -e $1 ]
then
  echo "Unable to find file '$1'. Exiting." > /dev/stderr
  exit 1
fi

base=$(expr $1 : '\(.*\)\.euk' '|' $1)
tex=$base.tex

cat > $tex <<- SOURCE
\documentclass{article}
$include
\usepackage{pstricks,pst-eps}
\nofiles
\pagestyle{empty}
\begin{document}
\TeXtoEPS
SOURCE

euktopst -o $lang $interactive $batchmode $1 >> $tex &&
if [ $? -ne 0 ]
then
  rm -f $tex
  exit 1
fi

cat >> $tex <<- SOURCE
\endTeXtoEPS
\end{document}
SOURCE

latex -interaction=nonstopmode $tex > /dev/null
if [ $? -ne 0 ]
then
  echo "LaTeX error: please check '$base.log'." > /dev/stderr
  rm -f $base.dvi
  exit 1
fi

dvips -q -E -o $base.eps $base.dvi
rm -f $base.{tex,log,dvi}
