#!/bin/sh

if [ $# -ne 3 ] ; then
	echo mk-xtrkcad-manual-html SRCDIR BINDIR OUTFILE
	echo SRCDIR contains .but files
	echo BINDIR contains .html files
	echo OUTFILE is the output .html file
	echo Open OUTFILE in Chrome and print as pdf
	echo from a directory which contains png.d
	exit 1
fi

SRCDIR=$1
BINDIR=$2
OUTFILE=$3
OUTDIR=`pwd`

if [ ! -d ${SRCDIR} ] ; then
	echo $SRCDIR does not exist
	exit 1
fi

if [ ! -f ${SRCDIR}/addm.but ] ; then
	echo $SRCDIR does not contain .but files
	exit 1
fi

if [ ! -d ${SRCDIR}/png.d ] ; then
	echo $SRCDIR does not contain png.d directory
	exit 1
fi

if [ ! -d ${BINDIR} ] ; then
	echo $BINDIR does not exist
	exit 1
fi

if [ ! -f ${BINDIR}/addM.html ] ; then
	echo $BINDIR does not contain .html files
	exit 1
fi


extract() {
	grep '^\\[ACHS]' $1 |\
	sed \
		-e 's/^\\[ACHS][0-9]*{//' \
		-e 's/}.*//' \
		-e '/^$/d' \
	       	-e 's/$/.html/' ;
}

cd $SRCDIR
# extract .html refs
FILES="\
contents.html \
`extract intro.but.in` \
`extract addm.but` \
`extract changem.but` \
`extract drawm.but` \
`extract editm.but` \
`extract filem.but` \
`extract helpm.but` \
`extract hotbar.but` \
`extract macrom.but` \
`extract managem.but` \
`extract optionm.but` \
`extract statusbar.but` \
`extract view_winm.but` \
`extract navigation.but` \
`extract appendix.but` \
`extract ${BINDIR}/../../help/messages.but` \
`extract upgrade.but` \
`extract warranty.but` \
IndexPage.html"

cd $OUTDIR
(
cd $BINDIR
# clean up html: remove nav line, fix case file names
cat $FILES |\
       	grep -v 'Previous.*Next' |\
	sed \
		-e 's/bSensor.png/bsensor.png/'\
		-e 's/bControl.png/bcontrol.png/'\
		-e 's/iconlink.PNG/iconlink.png/'\
       	) > ${OUTFILE}

echo "Combined .html files are in ${OUTFILE}" 
echo "Make sure ${OUTFILE} is in a directory which contains a link to"
echo "  $SRCDIR/png.d/"
echo "Open with Chrome and Print to File as a PDF"
echo "You should specify a custom scale of at least 150%"
