#!/bin/sh

if [ "$1" = "" ]; then
  echo -e 'Usage: mptogif1.sh FILE [DPI [-noantialias]]\n'
  exit 1
fi

if [ "$2" = "" ]; then
  DPI=300
else
  DPI=$2
fi

DIR=$PWD
TMP=`echo $1 | awk 'BEGIN{FS=".";} {print $1}'`
FILE=$DIR/$TMP
EPS=$FILE.eps
GIF=$FILE.png
GIF_=$DIR/icons/$TMP".png"

cd /tmp
cp $FILE.mp mptogif.$$.mp
echo "\\hsize=15.85cm\\vsize=13.48cm\\input epsf\\nopagenumbers\\leavevmode\\noindent\\epsfbox{mptogif.$$.1}\\vfill\\end" > mptogif.$$.tex
for file in $DIR/mbmac.mp $DIR/mbmac.tex; do
  ln -sf $file
done

echo "prologues:=1;" > prologues.mp
mpost mptogif.$$.mp
cp mptogif.$$.1 $FILE.2

echo "prologues:=0;" > prologues.mp
mpost mptogif.$$.mp
cp mptogif.$$.1 $FILE.1

csplain mptogif.$$.tex
dvips -T 15cm,16cm -o mptogif.$$.ps mptogif.$$.dvi
psfixbb -o $EPS mptogif.$$.ps
gs -q -dSAFER -sPAPERSIZE=a5 -sDEVICE=ppmraw -sOutputFile=- -dNOPAUSE -r"$DPI"x"$DPI" $EPS quit.ps | pnmcrop > mptogif.$$.pnm
if [ "$3" != "-noantialias" ]; then
  pnmscale 0.5 < mptogif.$$.pnm | ppmquant 256 | pnmtopng > $GIF
  pnmscale 0.125 < mptogif.$$.pnm | ppmquant 256 | pnmtopng > $GIF_
else
  ppmquant 256 < mptogif.$$.pnm | pnmtopng > $GIF
fi

rm mptogif.$$.*
rm mbmac.mp mbmac.tex
cd $DIR

