#!/bin/sh
#
# Author:
#   Leif Kornstaedt <kornstae@ps.uni-sb.de>
#
# Contributor:
#   Tobias Mueller <tmueller@ps.uni-sb.de>
#
# Copyright:
#   Leif Kornstaedt, 1998
#
# Last change:
#   $Date$ by $Author$
#   $Revision$
#
# This file is part of Mozart, an implementation of Oz 3:
#   $MOZARTURL$
#
# See the file "LICENSE" or
#   $LICENSEURL$
# for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL
# WARRANTIES.
#

if [ $# -lt 3 ]
then
    echo usage: `basename $0` \<input file\> \<output dir\> \<int\> ... 1>&2
    exit 2
fi

infile=$1; shift
outdir=$1; shift

tmpdir=/tmp/ps2png.$$
trap 'rm -rf $tmpdir' 0 1 2 15
mkdir $tmpdir

cp $infile $tmpdir/x.tex
(
    cd $tmpdir

    latex x 1>&2 || exit 1
    dvips x.dvi -o x.ps 1>&2

    mkfifo moo

    gs -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r102 \
    -sDEVICE=pnmraw -sOutputFile=latex%d.ppm x.ps < moo |
    (
	i=0
	while [ $# -gt 0 ]; do
	    exit=no
	    while [ $exit ]; do
		read line
		case $line in
		*showpage*)
		    exit=""
		    ;;
		*)
		    echo $line 1>&2
		    ;;
		esac
	    done
	    i=`expr $i + 1`
	    pnmcrop < latex$i.ppm 2> /dev/null |
	    pnmtopng -transparent rgbi:1/1/1 2> /dev/null > latex$1.png  || exit 1
	    rm latex$i.ppm
	    echo Wrote latex$1.png 1>&2
	    echo
	    shift
	done
	echo quit
    ) > moo
) || exit 1

mv $tmpdir/latex*.png $outdir

exit 0
