#! /bin/sh
LATEX=latex
DVIPS=dvips
GS=gs
RESOLUTION=100 # resolution in dpi
PNMCROP="pnmcrop -white"
PNMEXTRA=""
PNMMARGIN="pnmmargin -white 1"
PPMQUANT=""
#PPMTOEXT="pnmtopng -transparent '#ffffff'"
#EXT=png
PPMTOEXT="ppmtogif -transparent '#ffffff'"
EXT=gif
TODIR="."
RM="/bin/rm -f"


while true
do
    case $1 in
     -todir)
       shift
       TODIR="$1"
       mkdir -p ${TODIR} 2> /dev/null || :
       ;;
     -gif)
	PPMTOEXT="ppmtogif -transparent '#ffffff'"
        EXT=gif
        ;;
     -png)
        PPMTOEXT="pnmtopng -transparent '#ffffff'"
        EXT=png
        ;;
     -pnm)
        PPMTOEXT=cat
        EXT=pnm
        ;;  
     -quant)
        shift
        PPMQUANT="ppmquant $1 |"
        ;;
    -extra)
        shift
        PNMEXTRA="$1 |"
        ;;
    -mag)
        shift
	RESOLUTION="$( expr '(' "$1" '*' 72 '+' 999 ')' '/' 1000)"
        ;;
    -res)
        shift
        RESOLUTION="$1"
        ;;
    *)
        break
        ;;
    esac
    shift
done
echo "RESOLUTION: $RESOLUTION"
#always quantize for gifs (ppmtogif ouputs non valid files when colors >= 256)
if [ "$EXT" = "gif" -a -z "$PPMQUANT" ]
then
  PPMQUANT="ppmquant 255 |"
fi

case $1 in
  '')
   BASE=image
   ;;
  *)
   BASE=$1
  ;;
esac
NAME=${BASE}.image

trap "${RM} ${NAME}.dvi ${NAME}.log ${NAME}.aux head.tmp body.tmp ; exit 2" 1 2 3 8 10 13 15

DVIPSOPTS="-j -z -Z -Ppdf -D $RESOLUTION"
GSOPTS="-q  -dNOPAUSE -dBATCH -DNOPROMPT -sDEVICE=ppmraw \
	-r$RESOLUTION -dTextAlphaBits=2"

test -f  ${NAME}.tex ||\
{ echo "Failure: no ${NAME}.tex file!" 2>&1 ; exit 2 ; }
${LATEX} ${NAME}.tex
${DVIPS} ${DVIPSOPTS} -o - ${NAME}.dvi |\
${GS} ${GSOPTS} -sOutputFile="|\
    ${PNMCROP} | ${PNMEXTRA} \
    ${PNMMARGIN} | ${PPMQUANT} \
    ${PPMTOEXT} > ${TODIR}/${BASE}%03d.${EXT}" -
${RM} ${NAME}.dvi ${NAME}.log ${NAME}.aux  head.tmp body.tmp
