#!/bin/sh

# Generate an Encapsulated Postscript file (eps) from the
# PLplot pstex driver generated files. 

if test $# = "0"; then
	echo -e "\n\
	Usage: pstex2eps <filename>\n\
	\n\
	Where <filename> is the name of the output file you specified\n\
	with the -o option in PLplot.\n\
	There must exist two files, the postscript file without text,\n\
	<filename>, and the latex file with the text, <filename_t>.\n\
	The output file will be named <filename.eps>.\n\
	\n\
	The Computer Modern Type 1 fonts will be included in the output\n\
	eps file. If you intent to use the plot figure in LaTeX, just\n\
	use a plain \include{<filename_t>} in your latex file.\n\
	\n\
	Warning: the ghostscript utility 'ps2epsi', used in this script,\n\
	can mis-calculate the postscript Bounding Box.\n"
	exit 1
fi

if test ! -e $1 -o ! -e $1_t; then
	echo "$1 or $1_t don't exist. Exiting."
	exit 1
fi

ifile=$1
ofile=`mktemp pstex2eps.XXXXXX`

cat > ${ofile}.tex <<EOF
\documentclass{article}
\usepackage{aecompl}
\usepackage{graphicx}
\begin{document}
\pagestyle{empty}
\rotatebox{0}{\scalebox{1.0}{\input{${ifile}_t}}}
\end{document}
EOF

latex ${ofile} > /dev/null \
&& dvips -Pcmz -o ${ofile}.ps $ofile 2> /dev/null \
&& ps2epsi ${ofile}.ps

sed  -e '/BeginPreview/,/EndPreview/d'  ${ofile}.epsi > ${ifile}.eps

rm ${ofile}*
