#!/bin/sh
#XER2PRINT_XSL_PATH=/var/xsl

INDEX=1

while [ -e /tmp/xer2print.$INDEX.tmp ] ; do
    INDEX=$INDEX+1
    done
    
LANG=$1
OUTPUT=$2
INPUT=$3
NAME=/tmp/xer2print.$INDEX.tmp

if [ ! $3 ] ; then
    INPUT=/dev/stdin
    fi


function fo(){
    xsltproc --stringparam lang $LANG  --stringparam margintop 10mm --stringparam marginbottom 10mm $XER2PRINT_XSL_PATH/forms/main.xsl $INPUT
}

function html(){
    xsltproc --stringparam lang $LANG  --stringparam margintop 0mm --stringparam marginbottom 0mm $XER2PRINT_XSL_PATH/forms/main.xsl $INPUT |
    xsltproc $XER2PRINT_XSL_PATH/forms/fo2html.xsl /dev/stdin
    }

function pdf() {
    xsltproc --stringparam lang $LANG  --stringparam margintop 10mm --stringparam marginbottom 10mm $XER2PRINT_XSL_PATH/forms/main.xsl $INPUT >$NAME.fo 
    cd /tmp
    pdfxmltex $NAME.fo >/dev/null
    pdfxmltex $NAME.fo >/dev/null
    cat $NAME.pdf
    rm $NAME.*
    }

function dvi() {
    xsltproc --stringparam lang $LANG  --stringparam margintop 10mm --stringparam marginbottom 10mm $XER2PRINT_XSL_PATH/forms/main.xsl $INPUT >$NAME.fo
    cd /tmp
cat <<-END> $NAME.tex
\\def\\xmlfile{$NAME.fo}
\\input xmltex.tex
END
    latex $NAME.tex >/dev/null
    latex $NAME.tex >/dev/null
#    xmltex $NAME.fo >/dev/null
    cat $NAME.dvi
    rm $NAME.*
    }

function ps(){
    xsltproc --stringparam lang $LANG  --stringparam margintop 10mm --stringparam marginbottom 10mm $XER2PRINT_XSL_PATH/forms/main.xsl $INPUT >$NAME.fo
    cd /tmp
cat <<-END> $NAME.tex
\\def\\xmlfile{$NAME.fo}
\\input xmltex.tex
END
    latex $NAME.tex >/dev/null
    latex $NAME.tex >/dev/null
#    xmltex $NAME.fo >/dev/null
    dvips -R -q -o /dev/stdout $NAME.dvi
    rm $NAME.*
    }

case "$OUTPUT" in
    fo)
	fo
	;;
    html)
	html
	;;
    pdf)
	pdf
	;;
    dvi)
	dvi
	;;

    ps)
	ps
	;;
    *)
	echo "Usage: process lang {fo|html|pdf|ps|dvi} [filename1] [filename2]"
esac
