#!/bin/sh

if [ $# -ne 2 ]; then
    echo "usage: texmathtoimg in_file.tex out_file.png|.pdf|.eps|.ps"
    exit 1
fi

in_tex=$1
out_img=$2

if [ ! -f "$in_tex" ]; then
    echo "usage: texmathtoimg in_file.tex out_file.png|.pdf|.eps|.ps"
    exit 1
fi

rm -f /tmp/texmathtoimg.*

echo '\documentclass[12pt]{article}' > /tmp/texmathtoimg.tex
echo '\pagestyle{empty}' >> /tmp/texmathtoimg.tex
echo '\begin{document}' >> /tmp/texmathtoimg.tex
cat "$in_tex" >> /tmp/texmathtoimg.tex
echo '\end{document}' >> /tmp/texmathtoimg.tex

(cd /tmp; latex --interaction batchmode texmathtoimg.tex)

if [ ! -f /tmp/texmathtoimg.dvi ]; then
    echo "$in_tex has TeX errors"
    rm -f /tmp/texmathtoimg.*
    exit 2
fi

dvips -E -o /tmp/texmathtoimg.eps /tmp/texmathtoimg.dvi

case "$out_img" in
*.png)	gs -q -dBATCH -dNOPAUSE -sDEVICE=png16m -r96 \
    		-dTextAlphaBits=4 -dGraphicsAlphaBits=4 -dEPSCrop \
		"-sOutputFile=$out_img" /tmp/texmathtoimg.eps ;;
*.pdf)	ps2pdf12 -dEPSCrop /tmp/texmathtoimg.eps "$out_img" ;;
*)	mv /tmp/texmathtoimg.eps "$out_img" ;;

esac

rm -f /tmp/texmathtoimg.*
