#! /bin/sh 
#
# sgml2lyx
#

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

AWK="gawk"
CHAR="groff"
TABS="-8"		      # expand replaces tabs with 8 spaces
STYLE=                        # Use standard Linuxdoc-SGML style

trap "CleanUp" 0 1 2 3 9 15

usage () {
echo "  Usage: sgml2lyx [-l] [-style <s>] [-t <n>] <filename> ";
echo "  -l         use latin1 character set (default ASCII)";
echo "  -style <s> use rtf/<s>mapping backend in addition to default";
echo "             rtf/mapping";
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>.lyx"
exit 1 
}

CleanUp() {
    rm -f /tmp/sgml2lyx$$tmp
}

# 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
              -style)   style=$2; shift; 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/lyx/%N
export SGML_PATH

if [ -f $LINUXDOCLIB/dtd/${style}.dcl ]; then
        SGMLDECL=$LINUXDOCLIB/dtd/${style}.dcl
elif [ -f $LINUXDOCLIB/dtd/sgml.dcl ]; then
        SGMLDECL=$LINUXDOCLIB/dtd/sgml.dcl
# else just use sgmls's defaults
fi

if [ "$style" != "" ]; then
        STYLE=$LINUXDOCLIB/rep/lyx/${style}mapping;
fi

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

echo "Making $LYXFILE from $SGMLFILE."
# format
case $CHAR in
        latin1) cat $SGMLDECL $SGMLFILE | awk '{ print $0 " " }' | \
		sed -f $LINUXDOCLIB/latin1.sed | \
		$LINUXDOCBIN/sgmls $DASHI > /tmp/sgml2lyx$$tmp;;
        *)      cat $SGMLDECL $SGMLFILE | awk '{ print $0 " " }' | \
        	$LINUXDOCBIN/sgmls $DASHI > /tmp/sgml2lyx$$tmp;;
esac
if [ $? = 1 ]
then
        echo "SGML parsing error, no formatting done..."
        exit 1
fi

# if there are no SGML parse errors, continue...
cat /tmp/sgml2lyx$$tmp | $LINUXDOCBIN/sgmlsasp $STYLE \
$LINUXDOCLIB/rep/lyx/mapping | $AWK -f $LINUXDOCLIB/prelyx.awk | \
sed -f $LINUXDOCLIB/prelyx.sed | \
$AWK -f $LINUXDOCLIB/purifylyx.awk | \
$AWK -f $LINUXDOCLIB/postlyx.awk | \
$AWK -f $LINUXDOCLIB/purifylyx.awk | expand $TABS > $LYXFILE

exit 0
