#!/bin/bash
# runbib - creates bibliography files from SGML/XML, LaTeX  or RTF files
# Markus Hoenicka <markus@mhoenicka.de> 2001-05-10

# OPTIONS: -d (database) -h (invoke help), -S bibliography-style,
#          -t type (db31|db31x|db50x|teix|tei5x|bibtex|rtf)
# relies on these external programs: (open)jade (db31)
#                                    xsltproc (db31x,db50x,teix,tei5x)
#                                    textutils (bibtex)
# use the configuration file runbibrc to alter the settings

### start user-customizable section
# the commands used to extract the IDs from the document sources
myjade="/usr/bin/openjade"
myxsltproc="/usr/bin/xsltproc"

# the textutils commands
mysort=sort
myuniq=uniq

# some refdb commands
myrefdbib=refdbib
myrtfcitations=rtfcitations
myrefdbrtf=refdbrtf

# the SGML and XML declarations
sgmldecl="/usr/share/refdb/declarations/docbook.dcl"
xmldecl="/usr/share/refdb/declarations/xml.dcl"

### end user-customizable section

# default stylesheets. Override them in runbibrc
citlist="/usr/share/refdb/dsssl/citations.dsl"
makecss="/usr/share/refdb/dsssl/makecss.dsl"
citlistx="/usr/share/refdb/xsl/citations.xsl"
citlistxraw="/usr/share/refdb/xsl/citationsraw.xsl"
db2teix="/usr/share/refdb/xsl/bibdb2tei.xsl"
makecssx="/usr/share/refdb/xsl/makecss.xsl"
makecssxns="/usr/share/refdb/xsl/makecss-ns.xsl"
teihtml="/usr/share/refdb/xsl/tei-refdb-xsl/tei-html/tei-refdb-html.xsl"
teifo="/usr/share/refdb/xsl/tei-refdb-xsl/tei-fo/tei-refdb-fo.xsl"
tei5html="/usr/share/refdb/xsl/tei-refdb-xsl/tei-html/tei-refdb-html-ns.xsl"
tei5fo="/usr/share/refdb/xsl/tei-refdb-xsl/tei-fo/tei-refdb-fo-ns.xsl"
docbkhtml="/usr/share/refdb/xsl/docbk-refdb-xsl/docbk-html/docbk-refdb-html.xsl"
docbkxhtml="/usr/share/refdb/xsl/docbk-refdb-xsl/docbk-xhtml/docbk-refdb-xhtml.xsl"
docbkfo="/usr/share/refdb/xsl/docbk-refdb-xsl/docbk-fo/docbk-refdb-fo.xsl"
docbk5html="/usr/share/refdb/xsl/docbk-refdb-xsl/docbk-html/docbk-refdb-html-ns.xsl"
docbk5xhtml="/usr/share/refdb/xsl/docbk-refdb-xsl/docbk-xhtml/docbk-refdb-xhtml-ns.xsl"
docbk5fo="/usr/share/refdb/xsl/docbk-refdb-xsl/docbk-fo/docbk-refdb-fo-ns.xsl"

# some initialization
databaseopt=""
encodingopt=""
outformat=db31
username=""
useropt=""
passwd=""
passwdopt=""
portarg=""
skip_id=""
startnumber="1"
numopt=""
cssfile=""
raw="f"
myfo=""
myhtml=""
myxhtml=""

# this allows to include or ignore marked sections in the SGML file
jadeincludearg=""

# this allows to pass additional options to (open)jade
jadeargs=""

# this allows to pass additional options to xsltproc
xsltprocargs=""

# the server IP address is passed to refdbib
iparg=""

# functions
fixdoctype ()
{
# Arguments: $1: filename of a jade-generated xml file
#
# jade and openjade erroneously forget a space in the doctype line
# this problem is *only* fixed in OpenJade 1.3.1, but this function
# will not alter this version's correct output so it is safe to run it
# unconditionally
    sed 's/\(<?.*\)\"\"\(.*\)/\1\" \"\2/' < $1 > $1.$$

    if [ $? -ne 0 ]; then
        echo "error while post-processing id file"
        exit 1
    fi
	
    mv $1.$$ $1
}

manglexsl ()
{
# Arguments: $1: filename of the refdbd-created driver file
#            $2: string denoting the document type (see outformats.h)
#
# refdbd sends us a generic xsl stylesheet. We need to create
# one html stylesheet and one fo stylesheet by importing the proper
# refdb xsl stylesheets. DocBook gets an additional xhtml stylesheet
# we'll also create a CSS file for all (x)html output
    local basename=${1%.*}

    if [ $2 = "REFTEIX5" ] || [ $2 = "REFDOCBKX5" ]; then
	$myxsltproc $makecssxns $1 > $basename.css
    else
	$myxsltproc $makecssx $1 > $basename.css
    fi


# todo: test whether $cssfile is an url
    if [ -n "$cssfile" ] && [ "$cssfile" != "$basename.css" ]; then
	# custom css file
	if [ $2 = "REFTEIX" ]; then
	    if [ "X$myfo" != "X" ]; then
		teifo=$myfo
	    fi
	    if [ "X$myhtml" != "X" ]; then
		teihtml=$myhtml
	    fi
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$teihtml\"/>& ; s&<!-- REFDBBIBSTYLE -->.*<!-- /REFDBBIBSTYLE -->&& ; s&<!--CSSFILE/-->&<xsl:param name=\"html.stylesheet\">$cssfile</xsl:param>&' < $1 > $basename.html.xsl" | sh
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$teifo\"/>& ; s&<!--CSSFILE/-->&&' < $1 > $basename.fo.xsl" | sh
	elif [ $2 = "REFTEIX5" ]; then
	    if [ "X$myfo" != "X" ]; then
		tei5fo=$myfo
	    fi
	    if [ "X$myhtml" != "X" ]; then
		tei5html=$myhtml
	    fi
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$tei5html\"/>& ; s&<!-- REFDBBIBSTYLE -->.*<!-- /REFDBBIBSTYLE -->&& ; s&<!--CSSFILE/-->&<xsl:param name=\"html.stylesheet\">$cssfile</xsl:param>&' < $1 > $basename.html.xsl" | sh
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$tei5fo\"/>& ; s&<!--CSSFILE/-->&&' < $1 > $basename.fo.xsl" | sh
	elif [ $2 = "REFDOCBKX" ]; then
	    if [ "X$myfo" != "X" ]; then
		docbkfo=$myfo
	    fi
	    if [ "X$myhtml" != "X" ]; then
		docbkhtml=$myhtml
	    fi
	    if [ "X$myxhtml" != "X" ]; then
		docbkxhtml=$myxhtml
	    fi
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$docbkhtml\"/>& ; s&<!-- REFDBBIBSTYLE -->.*<!-- /REFDBBIBSTYLE -->&& ; s&<!--CSSFILE/-->&<xsl:param name=\"html.stylesheet\">$cssfile</xsl:param>&' < $1 > $basename.html.xsl" | sh
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$docbkxhtml\"/>& ; s&<!-- REFDBBIBSTYLE -->.*<!-- /REFDBBIBSTYLE -->&& ; s&<!--CSSFILE/-->&<xsl:param name=\"html.stylesheet\">$cssfile</xsl:param>&' < $1 > $basename.xhtml.xsl" | sh
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$docbkfo\"/>& ; s&<!--CSSFILE/-->&&' < $1 > $basename.fo.xsl" | sh
	elif [ $2 = "REFDOCBKX5" ]; then
	    if [ "X$myfo" != "X" ]; then
		docbk5fo=$myfo
	    fi
	    if [ "X$myhtml" != "X" ]; then
		docbk5html=$myhtml
	    fi
	    if [ "X$myxhtml" != "X" ]; then
		docbk5xhtml=$myxhtml
	    fi
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$docbk5html\"/>& ; s&<!-- REFDBBIBSTYLE -->.*<!-- /REFDBBIBSTYLE -->&& ; s&<!--CSSFILE/-->&<xsl:param name=\"html.stylesheet\">$cssfile</xsl:param>&' < $1 > $basename.html.xsl" | sh
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$docbk5xhtml\"/>& ; s&<!-- REFDBBIBSTYLE -->.*<!-- /REFDBBIBSTYLE -->&& ; s&<!--CSSFILE/-->&<xsl:param name=\"html.stylesheet\">$cssfile</xsl:param>&' < $1 > $basename.xhtml.xsl" | sh
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$docbk5fo\"/>& ; s&<!--CSSFILE/-->&&' < $1 > $basename.fo.xsl" | sh
	fi
    elif [ -s "$basename.css" ]; then
	# default css file
	if [ $2 = "REFTEIX" ]; then
	    if [ "X$myfo" != "X" ]; then
		teifo=$myfo
	    fi
	    if [ "X$myhtml" != "X" ]; then
		teihtml=$myhtml
	    fi
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$teihtml\"/>& ; s&<!-- REFDBBIBSTYLE -->.*<!-- /REFDBBIBSTYLE -->&& ; s&<!--CSSFILE/-->&<xsl:param name=\"html.stylesheet\">$basename.css</xsl:param>&' < $1 > $basename.html.xsl" | sh
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$teifo\"/>& ; s&<!--CSSFILE/-->&&' < $1 > $basename.fo.xsl" | sh
	elif [ $2 = "REFTEIX5" ]; then
	    if [ "X$myfo" != "X" ]; then
		tei5fo=$myfo
	    fi
	    if [ "X$myhtml" != "X" ]; then
		tei5html=$myhtml
	    fi
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$tei5html\"/>& ; s&<!-- REFDBBIBSTYLE -->.*<!-- /REFDBBIBSTYLE -->&& ; s&<!--CSSFILE/-->&<xsl:param name=\"html.stylesheet\">$basename.css</xsl:param>&' < $1 > $basename.html.xsl" | sh
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$tei5fo\"/>& ; s&<!--CSSFILE/-->&&' < $1 > $basename.fo.xsl" | sh
	elif [ $2 = "REFDOCBKX" ]; then
	    if [ "X$myfo" != "X" ]; then
		docbkfo=$myfo
	    fi
	    if [ "X$myhtml" != "X" ]; then
		docbkhtml=$myhtml
	    fi
	    if [ "X$myxhtml" != "X" ]; then
		docbkxhtml=$myxhtml
	    fi
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$docbkhtml\"/>& ; s&<!-- REFDBBIBSTYLE -->.*<!-- /REFDBBIBSTYLE -->&& ; s&<!--CSSFILE/-->&<xsl:param name=\"html.stylesheet\">$basename.css</xsl:param>&' < $1 > $basename.html.xsl" | sh
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$docbkxhtml\"/>& ; s&<!-- REFDBBIBSTYLE -->.*<!-- /REFDBBIBSTYLE -->&& ; s&<!--CSSFILE/-->&<xsl:param name=\"html.stylesheet\">$basename.css</xsl:param>&' < $1 > $basename.xhtml.xsl" | sh
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$docbkfo\"/>& ; s&<!--CSSFILE/-->&&' < $1 > $basename.fo.xsl" | sh
	elif [ $2 = "REFDOCBKX5" ]; then
	    if [ "X$myfo" != "X" ]; then
		docbk5fo=$myfo
	    fi
	    if [ "X$myhtml" != "X" ]; then
		docbk5html=$myhtml
	    fi
	    if [ "X$myxhtml" != "X" ]; then
		docbk5xhtml=$myxhtml
	    fi
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$docbk5html\"/>& ; s&<!-- REFDBBIBSTYLE -->.*<!-- /REFDBBIBSTYLE -->&& ; s&<!--CSSFILE/-->&<xsl:param name=\"html.stylesheet\">$basename.css</xsl:param>&' < $1 > $basename.html.xsl" | sh
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$docbk5xhtml\"/>& ; s&<!-- REFDBBIBSTYLE -->.*<!-- /REFDBBIBSTYLE -->&& ; s&<!--CSSFILE/-->&<xsl:param name=\"html.stylesheet\">$basename.css</xsl:param>&' < $1 > $basename.xhtml.xsl" | sh
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$docbk5fo\"/>& ; s&<!--CSSFILE/-->&&' < $1 > $basename.fo.xsl" | sh
	fi
    else
	# no css file
	if [ $2 = "REFTEIX" ]; then
	    if [ "X$myfo" != "X" ]; then
		teifo=$myfo
	    fi
	    if [ "X$myhtml" != "X" ]; then
		teihtml=$myhtml
	    fi
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$teihtml\"/>& ; s&<!-- REFDBBIBSTYLE -->.*<!-- /REFDBBIBSTYLE -->&& ; s&<!--CSSFILE/-->&&' < $1 > $basename.html.xsl" | sh
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$teifo\"/>& ; s&<!--CSSFILE/-->&&' < $1 > $basename.fo.xsl" | sh
	elif [ $2 = "REFTEIX5" ]; then
	    if [ "X$myfo" != "X" ]; then
		tei5fo=$myfo
	    fi
	    if [ "X$myhtml" != "X" ]; then
		tei5html=$myhtml
	    fi
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$tei5html\"/>& ; s&<!-- REFDBBIBSTYLE -->.*<!-- /REFDBBIBSTYLE -->&& ; s&<!--CSSFILE/-->&&' < $1 > $basename.html.xsl" | sh
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$tei5fo\"/>& ; s&<!--CSSFILE/-->&&' < $1 > $basename.fo.xsl" | sh
	elif [ $2 = "REFDOCBK" ]; then
	    if [ "X$myfo" != "X" ]; then
		docbkfo=$myfo
	    fi
	    if [ "X$myhtml" != "X" ]; then
		docbkhtml=$myhtml
	    fi
	    if [ "X$myxhtml" != "X" ]; then
		docbkxhtml=$myxhtml
	    fi
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$docbkhtml\"/>& ; s&<!-- REFDBBIBSTYLE -->.*<!-- /REFDBBIBSTYLE -->&& ; s&<!--CSSFILE/-->&&' < $1 > $basename.html.xsl" | sh
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$docbkxhtml\"/>& ; s&<!-- REFDBBIBSTYLE -->.*<!-- /REFDBBIBSTYLE -->&& ; s&<!--CSSFILE/-->&&' < $1 > $basename.xhtml.xsl" | sh
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$docbkfo\"/>& ; s&<!--CSSFILE/-->&&' < $1 > $basename.fo.xsl" | sh
	elif [ $2 = "REFDOCBKX5" ]; then
	    if [ "X$myfo" != "X" ]; then
		docbk5fo=$myfo
	    fi
	    if [ "X$myhtml" != "X" ]; then
		docbk5html=$myhtml
	    fi
	    if [ "X$myxhtml" != "X" ]; then
		docbk5xhtml=$myxhtml
	    fi
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$docbk5html\"/>& ; s&<!-- REFDBBIBSTYLE -->.*<!-- /REFDBBIBSTYLE -->&& ; s&<!--CSSFILE/-->&&' < $1 > $basename.html.xsl" | sh
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$docbk5xhtml\"/>& ; s&<!-- REFDBBIBSTYLE -->.*<!-- /REFDBBIBSTYLE -->&& ; s&<!--CSSFILE/-->&&' < $1 > $basename.xhtml.xsl" | sh
	    echo "sed 's&<!-- REFDBSTYLESHEET -->.*<!-- /REFDBSTYLESHEET -->&<xsl:import href=\"$docbk5fo\"/>& ; s&<!--CSSFILE/-->&&' < $1 > $basename.fo.xsl" | sh
	fi
    fi

    rm $1
}

mangledsssl ()
{
# refdb sends us a dsssl stylesheet. We need to create
# a CSS file for all (x)html output. We first send the driver file through
# a dsssl script to isolate the html section (otherwise we'd get another
# definition for each variable from the print section), then grep for the
# definitions, and convert them to css
    local basename=${1%.*}

    $myjade -t sgml -d $makecss $1 | grep "(define refdb-" | sed 's/(define refdb-text-indent \(.*\))/p.BIBLIOMIXED {text-indent: \1;}/ ;  s/(define refdb-start-indent \(.*\))/p.BIBLIOMIXED {margin-left: \1;}/ ; s/(define refdb-font-size \(.*\))/p.BIBLIOMIXED {font-size: \1;}/' > $basename.css

    if [ -n "$cssfile" ] && [ "$cssfile" != "$basename.css" ]; then
	    echo "sed 's&(define %stylesheet% #f)&(define %stylesheet% \"$cssfile\")&' < $1 > $basename.dsl$$" | sh
	    mv $basename.dsl$$ $basename.dsl
    elif [ -s "$basename.css" ]; then
	    echo "sed 's&(define %stylesheet% #f)&(define %stylesheet% \"$basename.css\")&' < $1 > $basename.dsl$$" | sh
	    mv $basename.dsl$$ $basename.dsl
    fi
}

# the path of the global configuration file
globalconfig="/etc/refdb/runbibrc"

# determine configuration files
if [ ! -r "$globalconfig" ] && [ -n "$REFDBLIB" ]; then
    globalconfig=$REFDBLIB/runbibrc
fi
userconfig=$HOME/.runbibrc

if [ -n "$globalconfig" ] && [ -r "$globalconfig" ]; then
    allconfigs=$globalconfig
fi

if [ -r "$userconfig" ]; then
    allconfigs=$allconfigs" "$userconfig
fi

# read the settings in the configure file(s)
for config in $allconfigs; do
    while read refdbvar refdbval; do
	if [ -n "$refdbvar" ]; then
	    if [ $refdbvar = jade_args ]; then
		jadeargs=$refdbval
	    fi
	    if [ $refdbvar = jade_includearg ]; then
		jadeincludearg=$jadeincludearg" -i "$refdbval
	    fi
	    if [ $refdbvar = outformat ]; then
		outformat=$refdbval
	    fi
	    if [ $refdbvar = xsltproc_args ]; then
		xsltprocargs=$refdbval
	    fi
	fi
    done < $config
done

# read the command line options
while getopts ":a:b:c:d:E:G:hi:I:j:N:p:rsS:t:u:w:" opt; do
  case $opt in
    a  ) myfo=$OPTARG;;
    b  ) myhtml=$OPTARG;;
    c  ) myxhtml=$OPTARG;;
    d  ) databaseopt="-d "$OPTARG;;
    E  ) encodingopt="-E "$OPTARG;;
    G  ) cssfile=$OPTARG;;
    h  ) echo "creates refdb bibliographies from SGML, XML, Latex, or RTF documents"
	 echo 'usage: runbib [-a fo-driver] [-b html-driver] [-c xhtml-driver] [-d database] [-E encoding] [-G cssfile] [-h] [-i server-ip] [-I name] [-j jade-args] [-N number] [r] [s] [-S style] [-t type] [-u username] [-w password] file1 [file2...]'
	 echo "Options: -a select custom fo driver file"
	 echo "         -b select custom html driver file"
	 echo "         -c select custom xhtml driver file"
	 echo "         -d select default database"
	 echo "         -E set output character encoding"
	 echo "         -G set the path or URL of a CSS file for (x)html output"
	 echo "         -h print this help and exit"
	 echo "         -i set server IP address"
	 echo "         -I set name of INCLUDE section in OpenJade"
	 echo "         -j additional command-line options for OpenJade"
	 echo "         -N set start of reference numbering"
	 echo "         -r create raw instead of cooked bibliography"
	 echo "         -s skip ID extraction (provide your own IDs)"
	 echo "         -S select bibliography style"
	 echo "         -t select output type (db31|db31x|db50x|teix|tei5x|bibtex|rtf)"
	 echo "         -u set username"
	 echo "         -w set password"
	 exit 0 ;;
    i  ) iparg=" -i "$OPTARG;;
    I  ) jadeincludearg=$jadeincludearg" -i "$OPTARG;;
    j  ) jadeargs=$OPTARG;;
    N  ) startnumber=$OPTARG;;
    p  ) portarg=" -p $OPTARG";;
    r  ) raw="t";;
    s  ) skip_id="t";;
    S  ) style=$OPTARG;;
    t  ) outformat=$OPTARG;;
    u  ) username=$OPTARG;;
    w  ) passwd=$OPTARG;;
    \? ) echo 'usage: runbib [-a fo-driver] [-b html-driver] [-c xhtml-driver] [-d database] [-E encoding] [-G cssfile] [-h] [-i server-ip] [-I name] [-j jade-args] [-N number] [-r] [s] [-S style] [-t type] [-u username] [-w password] file1 [file2...]'
	 echo 'type runbib -h to invoke help'
	 exit 1;;
  esac
done

# correct the index so the filename argument is always $1
shift $(($OPTIND - 1))

# check arguments
if [ $outformat != "db31" ] && [ $outformat != "bibtex" ] && 
    [ $outformat != "db31x" ] && [ $outformat != "teix" ] && 
    [ $outformat != "db50x" ] && [ $outformat != "tei5x" ] &&
    [ $outformat != "rtf" ]; then
    echo "invalid output type"
    exit 1
fi

if [ -n "$username" ]; then
    useropt=" -u $username"
fi

if [ -n "$passwd" ]; then
    passwdopt=" -w $passwd"
fi

if [ -n "$startnumber" ]; then
    numopt=" -N $startnumber"
fi

for filename in $*; do
    # extract the basename from the argument
    basename=${filename%.*}

### DocBook SGML
    if [ $outformat = "db31" ]; then
	# create a dummy bibliography file to get rid of the error msg
	if [ ! -f "$basename.bib.sgml" ]; then
	    touch $basename.bib.sgml
	fi

	if [ ! -n "$skip_id" ]; then
	    # first we run (open)jade with the citations.dsl stylesheet
            # to extract a list of citations from the source document

	    $myjade $jadeincludearg $jadeargs -t xml -d $citlist $sgmldecl $filename > $basename.id.xml
	    # this command will return an error if the bibliography does
	    # not exist yet. Therefore we can't test for an error condition
	    # here
	    #if [ $? -ne 0 ]; then
	        #exit 1
	    #fi

	    # due to a bug in both jade and openjade we need to doctor the
	    # doctype line to get a well-formed document
	    fixdoctype $basename.id.xml

	fi

	# then we run refdbib with the intermediate xml file to retrieve
	# the bibliography file and the style specification file
	
	$myrefdbib $databaseopt $encodingopt $useropt $passwdopt $numopt $portarg $iparg -S $style -D "." -t db31 $basename.id.xml > $basename.bib.sgml
	if [ $? -ne 0 ]; then
	    # move the output to error files so we can use the script
	    # in makefiles
	    mv $basename.bib.sgml $basename.bib.sgml.err
	    mv ${style%.}.dsl ${style%.}.dsl.err
	    exit 1
	fi

	# need to create the css file
	mangledsssl ${style%.}.dsl

### DocBook XML V4
    elif [ $outformat = "db31x" ]; then
	# create a dummy bibliography file to get rid of the error msg
	if [ ! -f "$basename.bib.xml" ]; then
	    touch $basename.bib.xml
	fi

	if [ ! -n "$skip_id" ]; then
	    # extract IDs with xsltproc
	    if [ $raw = "t" ]; then
		$myxsltproc --catalogs $citlistxraw $filename > $basename.id.xml
	    else
		$myxsltproc --catalogs $citlistx $filename > $basename.id.xml
	    fi
	fi

	if [ $raw = "t" ]; then
	    $myrefdbib $databaseopt $encodingopt $useropt $passwdopt $numopt $portarg $iparg -r -t db31x $basename.id.xml > $basename.bib.xml
	    if [ $? -ne 0 ]; then
	    # move the output to error files so we can use the script
	    # in makefiles
		mv $basename.bib.xml $basename.bib.xml.err
		exit 1
	    fi
	else # cooked bib including driver file
	    $myrefdbib $databaseopt $encodingopt $useropt $passwdopt $numopt $portarg $iparg -S $style -D "." -t db31x $basename.id.xml > $basename.bib.xml
	    if [ $? -ne 0 ]; then
	        # move the output to error files so we can use the script
	        # in makefiles
		mv $basename.bib.xml $basename.bib.xml.err
		mv ${style%.}.xsl ${style%.}.xsl.err
		exit 1
	    fi

	    # need to create three (html/xhtml/fo) xsl stylesheets
	    manglexsl ${style%.}.xsl "REFDOCBKX"
	fi

### DocBook XML V5
    elif [ $outformat = "db50x" ]; then
	# create a dummy bibliography file to get rid of the error msg
	if [ ! -f "$basename.bib.xml" ]; then
	    touch $basename.bib.xml
	fi

	if [ ! -n "$skip_id" ]; then
	    # extract IDs with xsltproc
	    if [ $raw = "t" ]; then
		$myxsltproc --catalogs $citlistxraw $filename > $basename.id.xml
	    else
		$myxsltproc --catalogs $citlistx $filename > $basename.id.xml
	    fi
	fi

	if [ $raw = "t" ]; then
	    $myrefdbib $databaseopt $encodingopt $useropt $passwdopt $numopt $portarg $iparg -r -n d -t db50x $basename.id.xml > $basename.bib.xml
	    if [ $? -ne 0 ]; then
	    # move the output to error files so we can use the script
	    # in makefiles
		mv $basename.bib.xml $basename.bib.xml.err
		exit 1
	    fi
	else # cooked bib including driver file
	    $myrefdbib $databaseopt $encodingopt $useropt $passwdopt $numopt $portarg $iparg -S $style -D "." -n d -t db50x $basename.id.xml > $basename.bib.xml
	    if [ $? -ne 0 ]; then
	        # move the output to error files so we can use the script
	        # in makefiles
		mv $basename.bib.xml $basename.bib.xml.err
		mv ${style%.}.xsl ${style%.}.xsl.err
		exit 1
	    fi

	    # need to create three (html/xhtml/fo) xsl stylesheets
	    manglexsl ${style%.}.xsl "REFDOCBKX5"
	fi

### TEI P4 XML
    elif [ $outformat = "teix" ]; then
	# same procedure as above, but for TEI P4 xml documents
	# create a dummy bibliography file to get rid of the error msg
	if [ ! -f "$basename.bib.xml" ]; then
	    touch $basename.bib.xml
	fi

	if [ ! -n "$skip_id" ]; then
	    # extract IDs with xsltproc
	    if [ $raw = "t" ]; then
		$myxsltproc --catalogs $citlistxraw $filename > $basename.id.xml
	    else
		$myxsltproc --catalogs $citlistx $filename > $basename.id.xml
	    fi
	fi

	if [ $raw = "t" ]; then
	    $myrefdbib $databaseopt $encodingopt $useropt $passwdopt $numopt $portarg $iparg -r -t teix $basename.id.xml > $basename.bib.xml
	    if [ $? -ne 0 ]; then
	        # move the output to error files so we can use the script
	        # in makefiles
		mv $basename.bib.xml $basename.bib.xml.err
		exit 1
	    fi

	    # the bibliography carries its own prolog, comment it out
#	    sed 's/\(<?xml.*\)/<!-- \1 -->/ ; s/\(<!DOCTYPE.*\)/<!-- \1 -->/' < $basename.bib.xml.$$ > $basename.bib.xml
#	    rm $basename.bib.xml.$$

	else # cooked bibliography including driver file
	    $myrefdbib $databaseopt $encodingopt $useropt $passwdopt $numopt $portarg $iparg -S $style -D "." -t teix $basename.id.xml > $basename.bib.xml
	    if [ $? -ne 0 ]; then
	        # move the output to error files so we can use the script
	        # in makefiles
		mv $basename.bib.xml $basename.bib.xml.err
		mv ${style%.}.xsl ${style%.}.xsl.err
		exit 1
	    fi

	    # the bibliography is in DocBook notation, transform to TEI
	    $myxsltproc --catalogs $db2teix $basename.bib.xml > $basename.bib.xml.$$
	    if [ $? -ne 0 ]; then
		mv $basename.bib.xml.$$ $basename.bib.xml.err
		mv ${style%.}.xsl ${style%.}.xsl.err
		exit 1
	    fi

	    # the bibliography carries its own prolog, comment it out
	    sed 's/\(<?xml.*\)/<!-- \1 -->/ ; s/\(<!DOCTYPE.*\)/<!-- \1 -->/' < $basename.bib.xml.$$ > $basename.bib.xml
	    rm $basename.bib.xml.$$

	    manglexsl ${style%.}.xsl "REFTEIX"
	fi

### TEI P5 XML
    elif [ $outformat = "tei5x" ]; then
	# same procedure as above, but for TEI P5 xml documents
	# create a dummy bibliography file to get rid of the error msg
	if [ ! -f "$basename.bib.xml" ]; then
	    touch $basename.bib.xml
	fi

	if [ ! -n "$skip_id" ]; then
	    # extract IDs with xsltproc
	    if [ $raw = "t" ]; then
		$myxsltproc --catalogs $citlistxraw $filename > $basename.id.xml
	    else
		$myxsltproc --catalogs $citlistx $filename > $basename.id.xml
	    fi
	fi

	if [ $raw = "t" ]; then
	    $myrefdbib $databaseopt $encodingopt $useropt $passwdopt $numopt $portarg $iparg -r -n tei -t tei5x $basename.id.xml > $basename.bib.xml
	    if [ $? -ne 0 ]; then
	        # move the output to error files so we can use the script
	        # in makefiles
		mv $basename.bib.xml $basename.bib.xml.err
		exit 1
	    fi

	else # cooked bibliography including driver file
	    $myrefdbib $databaseopt $encodingopt $useropt $passwdopt $numopt $portarg $iparg -S $style -D "." -n tei -t tei5x $basename.id.xml > $basename.bib.xml
	    if [ $? -ne 0 ]; then
	        # move the output to error files so we can use the script
	        # in makefiles
		mv $basename.bib.xml $basename.bib.xml.err
		mv ${style%.}.xsl ${style%.}.xsl.err
		exit 1
	    fi

	    manglexsl ${style%.}.xsl "REFTEIX5"
	fi

### BibTeX
    elif [ $outformat = "bibtex" ]; then
	if [ ! -r "$filename" ]; then
	    filename=$filename.aux
	    if [ ! -r "$filename" ]; then
		echo "cannot read input file"
		exit 1
            fi
        fi

	$mysort $filename | $myuniq | $myrefdbib $databaseopt $encodingopt $useropt $passwdopt $portarg $iparg -S $style -t bibtex > $basename.bib
	if [ $? -ne 0 ]; then
	    echo "No references retrieved from $filename"
	fi
### RTF
    else # RTF output
	if [ ! -n "$skip_id" ]; then
	    # extract IDs with rtfcitations
	    $myrtfcitations $filename > $basename.id.xml
	fi

	$myrefdbib $databaseopt $encodingopt $useropt $passwdopt $numopt $portarg $iparg -S $style -D "." -t rtf $basename.id.xml > $basename.bib.rtf
	if [ $? -ne 0 ]; then
	    # move the output to error files so we can use the script
	    # in makefiles
	    mv $basename.bib.xml $basename.bib.xml.err
	    mv ${style%.}.xsl ${style%.}.xsl.err
	    exit 1
	fi
    fi
done

exit 0
