#!/bin/bash
# Based on original from Eric Bischoff <eric@caldera.de>

# Modified by Tammy Fox <tfox@redhat.com> for Red Hat Documentation

# Support for Asian Languages by Paul Gampe <pgampe@redhat.com>

JADETEX="jadetex"

CJK="no"
if [ $LANG = "ja_JP" -o $LANG = "zh_TW" \
  -o $LANG = "zh_CN" -o $LANG = "ko_KR" ]; then
	echo "Enabling Asian Language Support via jadetex-cjk"
	JADETEX="jadetex-cjk"
	CJK="yes"
fi

# Convert to TeX
$SGML_JADE -t tex -o ${SGML_FILE_NAME}.tex $SGML_ARGUMENTS
if [ $? -ne 0 ]
then exit 1
fi

# Convert from TeX to DVI
$JADETEX ${SGML_FILE_NAME}.tex >${SGML_FILE_NAME}.out
if [ $? -ne 0 -a $CJK != "yes" ]
then
  cat ${SGML_FILE_NAME}.out
  rm ${SGML_FILE_NAME}.out
  rm ${SGML_FILE_NAME}.tex
  exit 2
fi
rm ${SGML_FILE_NAME}.out

# If there are unresolved references, re-run jadetex, twice 
INDEX_CNT=0
INDEX_MAX=5
while egrep '^LaTeX Warning: There were undefined references.$' ${SGML_FILE_NAME}.log >/dev/null 2>&1
do
    if [ $INDEX_CNT -gt $INDEX_MAX ] ; then
       echo "Could not resolve undefined references after $INDEX_MAX tries"
       exit 1
    fi;
    echo "$INDEX_CNT: re-running $JADETEX to resolve undefined references"
    $JADETEX ${SGML_FILE_NAME}.tex >/dev/null
    INDEX_CNT=`expr $INDEX_CNT + 1`
done
#Keep log file - tfox
#rm ${SGML_FILE_NAME}.log
rm ${SGML_FILE_NAME}.aux
rm ${SGML_FILE_NAME}.tex

if [ "$CJK" = "no" ]; then
	# Convert from DVI to PostScript
	echo -n Converting to PS...
	dvips -T 5.49in,8.26in -q ${SGML_FILE_NAME}.dvi -o ${SGML_FILE_NAME}.ps
	if [ $? -ne 0 ]
	then
	  rm ${SGML_FILE_NAME}.dvi
	  exit 3
	fi
	rm ${SGML_FILE_NAME}.dvi
	echo Done!

	# Convert from PS to PDF
	echo -n Converting to PDF...
	gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sPAPERSIZE=a5 -sOutputFile=${SGML_FILE_NAME}.pdf ${SGML_FILE_NAME}.ps
	rm ${SGML_FILE_NAME}.ps
else
	dvipdfm -p a5 ${SGML_FILE_NAME}.dvi > /dev/null
fi

echo Done!

exit 0
