#!/bin/bash
#
# by Chih-Wei Huang
#                        27-31 July 1998
#                Updated 20 September 1998
#

PATH=.:$PATH
FUNCTIONS="`type -path bg5sgmlfunctions`"
if [ -z $FUNCTIONS ]; then
    echo "$0: include file not found!"
    exit 1
fi
. $FUNCTIONS

sgmloptions=""
TEX=0
DVI=0
PS=0
CLEAN=0
STOP=0

for opt in $options
do
    case $opt in
        --output=tex)
        TEX=1
        ;;

        --output=dvi)
        DVI=1
        ;;

        --output=ps)
        PS=1
        ;;

        --output=all)
        TEX=1; DVI=1; PS=1
        ;;

        --clean)
        CLEAN=1
        ;;

        --stop)
        STOP=1
        ;;

        --font*)
        FONT=`echo $opt | cut -d= -f2`
        ;;

        *)
        sgmloptions="$sgmloptions $opt"
        ;;
    esac
done

unalias chilatex
if [ "$DVI" = "1" -o "$PS" = "1" ]; then
    if [ -z "`type -path chilatex`" ]; then
        echo "chilatex not found! create .tex file only..."
        TEX=1; DVI=0; PS=0
    fi
else
    TEX=1
fi

TEXINPUTS="`kpsexpand \\\$TEXINPUTS`:/usr/lib/sgml-tools//"
export TEXINPUTS

function TeXHeader()
{
    head -1 $TMP/$1.tex > $1.tex
    cat << 'EOH' >> $1.tex
\let\labelold\label
\def\label{\protect\labelold}
\let\bfseriesold\bfseries
\def\bfseries{\protect\bfseriesold}
%\let\numberlineold\numberline
%\def\numberline{\protect\numberlineold}
EOH

    [ "$STOP" != "1" ] && echo '\nonstopmode' >> $1.tex
    [ ! -z $FONT ] && echo "\\$FONT" >> $1.tex
}

for src in $filelist
do
    checksrcfile $src
    [ $? = 0 ] && continue

    encodingbg5 $src

    pushd . > /dev/null
    cd $TMP
    sgml2latex --output=tex $sgmloptions $name.sgml
    popd > /dev/null

    if [ -e $TMP/$name.tex ]; then
        head -1 $TMP/$name.tex > $name.tex
        [ "$STOP" != "1" ] && echo '\nonstopmode' >> $name.tex
        # NOTE: ! -z is not the same as -n  !!  A bug ??
        [ ! -z $FONT ] && echo "\\$FONT" >> $name.tex
        tail +2 $TMP/$name.tex | $B2A -d >> $name.tex

        if [ "$DVI" = "1" -o "$PS" = "1" ]; then
            [ ! -e $name.toc ] && chilatex $name.tex
            chilatex $name.tex
#            if [ "$CLEAN" != "1" -a -x /usr/lib/texmf/bin/chitex/ctran ]; then
#                /usr/lib/texmf/bin/chitex/ctran $name.log > $name.log@
#                mv -f $name.log@ $name.log
#                [ -e tmp@ ] && rm -f tmp@
#            fi
            if [ -e $name.dvi -a "$PS" = "1" ]; then
                dvips -o $name.ps $name.dvi
            fi
        fi

        if [ "$CLEAN" = "1" ]; then
            rm -f $name.aux $name.log $name.toc
            [ "$TEX" = "0" -a -e $name.tex ] && rm -f $name.tex
            [ "$DVI" = "0" -a -e $name.dvi ] && rm -f $name.dvi
            [ "$PS" = "0" -a -e $name.ps ] && rm -f $name.ps
        fi
    fi
done

cleartmp

