#! /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 2>/dev/null |"
        ;;
    -extra)
        shift
        PNMEXTRA="$1 |"
        ;;
    -mag)
        shift
	RESOLUTION="$( expr '(' "$1" '*' 72 '+' 999 ')' '/' 1000)"
        ;;
    -res)
        shift
        RESOLUTION="$1"
        ;;
    -t)
        shift
        TPAPER="-t $1"
        ;;
     -pdflatex|-pdf)
         LATEX=pdflatex
         DVIPS=cat
       ;;
    *)
        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 2>/dev/null |"
fi

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

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

DVIPSOPTS="-Z $TPAPER"
GSOPTS="-q -dNOPAUSE -dBATCH -DNOPROMPT -sDEVICE=ppmraw \
	-r$RESOLUTION -dAutoRotatePages=/None \
        -dTextAlphaBits=4 -dGraphicsAlphaBits=4"
if [ "${TODIR}" = "." ]
then
  FINAL=${BASE}%03d.${EXT}
else
  FINAL=${TODIR}/${BASE}%03d.${EXT}
fi
test -f  ${NAME}.tex ||\
{ echo "Failure: no ${NAME}.tex file!" 2>&1 ; exit 2 ; }
${LATEX} ${NAME}.tex
NAMEDIR=`dirname ${NAME}`
if [ "${LATEX}" = "pdflatex" ]
then
  if [ ${NAMEDIR} != "." ]
  then
    mv `basename ${NAME}.pdf` ${NAME}.pdf
  fi
  cat ${NAME}.pdf
else
 if [ ${NAMEDIR} != "." ]
  then
    mv `basename ${NAME}.dvi` ${NAME}.dvi
  fi
  ${DVIPS} ${DVIPSOPTS} -o - ${NAME}.dvi
fi |\
${GS} ${GSOPTS} -sOutputFile="|\
    ${PNMCROP} | ${PNMEXTRA} \
    ${PNMMARGIN} | ${PPMQUANT} \
    ${PPMTOEXT} 2>/dev/null > ${FINAL}" -
${RM} ${NAME}.dvi ${NAME}.pdf   head.tmp body.tmp
${RM} `basename ${NAME}.log` `basename ${NAME}.aux`