#!/bin/sh
#
# sgmlconv - convert SGML file to DVI, TXT, or HTML.
#
outputtype=dvi
VerboseMode=false
usage() {
    echo 'Usage: sgmlconv [-d] [-t] [-h] [--dvi]'
    echo '                [--txt] [--html] [--help]'
    echo '                {inputfile.sgml}'
    echo 'converts SGML file into DVI, text or HTML file (default DVI).'
    echo 'Options:'
    echo '   -d, --dvi   produce inputfile.dvi (DVI file)'
    echo '   -t, --txt   produce inputfile.txt (nroff file)'
    echo '   -h, --html  produce inputfile.html (HTML file)'
    echo '   --help      give this help'
    exit
}

# Parse args
# ----------
inputfiles=''
if [ $# -eq 0 ]; then usage; fi
while [ $# -gt 0 ]
do
	i="$1"
    case ".$i" in
		.-help|.--help)
			usage
			;;
        .-v|.--verbose|.-verbose) VerboseMode=true ;;
        .-d|.--dvi|.-dvi) outputtype=dvi ;;
        .-t|.--txt|.-txt) outputtype=txt ;;
        .-h|.--html|.-html) outputtype=html ;;
		.-*)	# other thus far unrecognized opts are ccoptions
            echo "*** sgmlconv warning: unrecognized option $i"
			;;
		# did not recognize option, append to $Mfiles
        .*)		# non-options are probably filenames
			inputfiles="$inputfiles $i"
            ;;
    esac
	shift
done

for i in $inputfiles
do
    outfile="`basename $i .sgml`.$outputtype"
	inputfile=`echo $i | sed 's/\.sgml//'`
    if [ "$VerboseMode" = 'true' ]; then echo "Producing $outfile .."; fi
    case ".$outputtype" in
       .dvi)
           format -Tlatex "$inputfile" | qtex -d >"$outfile"
           ;;
       .txt)
           format -Tnroff "$inputfile" | qroff >"$outfile"
           ;;
       .html)
            tmp1=tmp1$$.html
            tmp2=tmp2$$.html
           	format -Thtml "$inputfile" | prehtml >$tmp1
            fixref <$tmp1 >$tmp2
            cat <$tmp1 >>$tmp2
            cat $tmp2 | html2html "$inputfile" >"$outfile"
            rm $tmp1 $tmp2
            ;;
   esac
done
