#! /bin/sh 
#
# sgml2txt
# Greg Hankins, 27 August 1995
#
# Based on the original 'format' and 'qroff' scripts by Tom Gordon 
# and Alexander Horz.
# 
# This will fail if you give it an option, but no source file. 
#

# Don't make any changes here, it is all done by install!
LINUXDOCBIN=linuxdocbin
LINUXDOCLIB=linuxdoclib

TABS="-8"		      # expand replaces tabs with 8 spaces
CHECK="no"		      # don't just check SGML syntax
CHAR="nroff"		      # use ASCII (nroff) character set 

usage () {
echo "  Usage: sgml2txt [-c] [-t <n>] <filename> ";
echo "	-c	   check syntax only";
echo "  -l         use latin1 character set (default ASCII)";
echo "	-t <n>	   tabstops each <n>th col (default 8)";
echo "	<filename> SGML source file, .sgml extension is optional";
echo 
echo "  Output will appear in <filename>.txt"
exit 1 
}

# check argc
if [ $# = 0 ]
then
	usage
fi

# do they need help?
case "$1" in
	"-h" | "--help" | "-help") usage
	exit 1
esac

# getopt
for i in $*
do
        case $i in
	      -c)	CHECK="yes"; shift;;
	      -t) 	TABS="-"$2; shift; shift;;
	      -l)	CHAR="latin1"; shift;;
              --)       shift;
			break;;
        esac
done

# SGML_PATH for sgmls - must be exported
SGML_PATH=$LINUXDOCLIB/dtd/%N.dtd:$LINUXDOCLIB/dtd/%P.dtd:$LINUXDOCLIB/rep/$CHAR/%N
export SGML_PATH

# check to see if there is a source file
FILE=$1
if [ -f $FILE.sgml ] 
then
	SGMLFILE=$FILE.sgml
elif [ ! -f $FILE ] 
then
	echo "sgml2txt: can't find $FILE or $FILE.sgml" >&2
	exit 1
else
	SGMLFILE=$FILE
fi
TXTFILE=`basename $SGMLFILE .sgml`.txt

# do we want to just check the file?
if [ $CHECK = "yes" ]
then
	$LINUXDOCBIN/sgmls -s $SGMLFILE > /dev/null
	if [ $? = 1 ] 
	then 
		exit 1
	else
		exit 0
	fi
fi

echo "Making $TXTFILE from $SGMLFILE."
# format
$LINUXDOCBIN/sgmls $SGMLFILE > /tmp/sgml2txt$$tmp
if [ $? = 1 ]
then
        echo "SGML parsing error, no formatting done..."
        exit 1
fi

# if there are no SGML parse errors, continue...
case $CHAR in
	latin1) cat /tmp/sgml2txt$$tmp | sed -f $LINUXDOCLIB/latin1.sed | \
		$LINUXDOCBIN/sgmlsasp $LINUXDOCLIB/rep/latin1/mapping | \
		expand $TABS | sed -f $LINUXDOCLIB/preroff.sed | \
		groff -T latin1 -t -mgs > $TXTFILE;;
	*)	cat /tmp/sgml2txt$$tmp | $LINUXDOCBIN/sgmlsasp \
		$LINUXDOCLIB/rep/nroff/mapping | expand $TABS | \
		sed -f $LINUXDOCLIB/preroff.sed | groff -T ascii -t -mgs \
		> $TXTFILE;;
esac

rm -f /tmp/sgml2txt$$tmp
exit 0
