#!/bin/sh
n=`grep -l "%%Creator: Mathematica-PSRender" * 2> /dev/null | wc | awk '{print $1}'`
if [ $n -eq 0 ]
then
	echo
	echo "Cannot find an EPS file created by Mathematica."
	exit 0
fi

#####################################################################

echo
echo "Convert from EPS to single-page PostScript:"
echo
grep -l "%%Creator: Mathematica-PSRender" *  2> /dev/null   | cat -n
echo
echo "Selection [1-$n]:  \c"
read selection

#####################################################################

if [ "$selection" = "" ]
then
	selection=1
fi
if [ $selection -lt 1 ]
then
	selection=1
fi
if [ $selection -gt $n ]
then
	selection=1
fi

fn=`grep -l "%%Creator: Mathematica-PSRender" *  2> /dev/null   | head -$selection | tail -1`
bb=`grep BoundingBox $fn | head -1 | sed 's/^.*: //'`
x0=`echo $bb | awk '{print $1}'`
y0=`echo $bb | awk '{print $2}'`
x1=`echo $bb | awk '{print $3}'`
y1=`echo $bb | awk '{print $4}'`
w=`expr $x1 - $x0`
h=`expr $y1 - $y0`

echo "Would you prefer Portrait or Landscape orientation? [pl]:  \c"
read resp
case $resp in
[lL]*) rot=90 ;;
*) rot=0;;
esac
if [ $rot -eq 0 ]
then
	xsc=`echo 'x' | awk "{print (540.0/$w)}"`
	ysc=`echo 'x' | awk "{print (720.0/$h)}"`
else
	xsc=`echo 'x' | awk "{print (720.0/$w)}"`
	ysc=`echo 'x' | awk "{print (540.0/$h)}"`
fi


echo "   -- Scaling factor $xsc uses full page width*, and"
echo "   -- Scaling factor $ysc uses full page height*"
echo "	  (*leaving 0.5 inch margin on page):"
echo "Choose overall size scaling factor [1.0]:  \c"
read resp
if [ "$resp" = "" ]
then
	scale=1.0
else
	scale=$resp
fi

##########################################################################

if [ $rot -eq 0 ]
then
  llx=`echo 'x' | awk "{print int(305-$w * $scale * 0.5)}"`
  lly=`echo 'x' | awk "{print int(395-$h * $scale * 0.5)}"`
  urx=`echo 'x' | awk "{print int(306.9+$w * $scale * 0.5)}"`
  ury=`echo 'x' | awk "{print int(396.9+$h * $scale * 0.5)}"`
else
  llx=`echo 'x' | awk "{print int(305-$h * $scale * 0.5)}"`
  lly=`echo 'x' | awk "{print int(395-$w * $scale * 0.5)}"`
  urx=`echo 'x' | awk "{print int(306.9+$h * $scale * 0.5)}"`
  ury=`echo 'x' | awk "{print int(396.9+$w * $scale * 0.5)}"`
fi

newfile=${fn}.fixed
rm -f $newfile
cat > $newfile << EOH
%!PS-Adobe-2 EPSF-2
%%BoundingBox: $llx $lly $urx $ury
306 396 translate
$rot rotate
$scale dup scale
-144 -144 translate

EOH
tail +5 $fn >> $newfile
/bin/ls -l $fn $newfile
