#!/usr/bin/env bash

# This script allows the user to run the bhl2xxx functions without
# needing to start emacs.
 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.

# This program is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.

# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the Free
# Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307 USA

function usage
{
    echo "Usage:  bhl2xxx [-l lisp_directory] [-f in_file] [-o out_file] (html|latex|sgml|txt)"
    echo
    echo "The lisp_directory is the path to the location of the bhl.el file."
    echo "It defaults to the present working directory."
    echo
    echo "bhl2xxx will read from stdin if no in_file is specified, and write"
    echo "to stdout if no out_file is specified."
}


# Run the actual emacs conversion of the BHL input.
function convert
{
    /usr/bin/env emacs \
	--batch \
	--load=$lispdir/bhl.el \
	--execute="(bhl2xxx-batch-wrapper \"$infile\" '$lang)"
}


# clean up, saving the input to the input.bhl.dead file.
function cleanup
{
    if [ -e $msgfile ]; then
	mv $msgfile input.bhl.dead
    fi
    exit
}

# process the command line arguments
lispdir=$(pwd)		       
while getopts ":f:l:o:" opt
do
  case $opt in
      f  ) infile=$OPTARG;;
      l  ) lispdir=$OPTARG;;
      o  ) outfile=$OPTARG;;
      \? ) usage
           exit 1;;
  esac
done
shift $(($OPTIND - 1))
lang=$1


# Trap some common signals (CTRL-C type stuff) and clean up...
trap cleanup INT TERM


# For dreadfully obscure reasons, emacs cannot easily read stdin into
# a buffer.  Therefore, if the input is coming from stdin, create a
# temporary input file, if needed and read that in.
if [ -z $infile ]; then
    msgfile="/tmp/bhlinput$$"   # $$ -> process id:  helps make a unique name
    cat > $msgfile
    infile=$msgfile
fi


# do the conversion
if [ -z $outfile ]; then	# if sending to stdout
    (convert) 2> /dev/null
else
    touch $outfile
    (convert) > $outfile 2> "$outfile.log"
fi


# do normal cleanup
if [ -e $msgfile ]; then
    rm -f $msgfile
fi
