#!/bin/sh
#
#       bib2tex - output list of references given a BibTeX
#                       database file as a LaTeX source file
#
#       Written by Jonathan Bowen, November 1987.
#

PATH=/bin:/usr/bin:/usr/ucb
PROGNAME=`basename $0`
DEBUG=false
STYLE=plain
NAMEDFILES=false
ALPHABETICAL=false

while expr X"$1" : X'-' > /dev/null
do
    case "$1" in
    -a) : sort into alphabetical order
        ALPHABETICAL=true
        ;;
    -d)
        DEBUG=true
        ;;
    -n) : output to named files
        NAMEDFILES=true
        ;;
    -s) : bib style name
        if [ "$2" != "" ]
        then
            STYLE=$2
            shift
        else
            echo "$PROGNAME: no bibliography style name given" 1>&2
            exit 1
        fi
        ;;
    -u|-U)
        echo "Usage: $PROGNAME [ options ] file [ ... ]
Output list of citations from a BibTeX database in LaTeX source
format.
-a      alphabetical ordering           (default=$ALPHABETICAL)
-d      enable debugging                (default=$DEBUG)
-n      output to named files (*.tex)   (default=$NAMEDFILES)
-s name bibliography style name         (default=\"$STYLE\")
-u      display usage information" 1>&2
        exit 0
        ;;
    -*)
        echo "$PROGNAME: invalid option $1 (try -u)" 1>&2
        exit 0
        ;;
    esac
    shift
done

# If no files given, give usage.
if [ -z "$*" ]
then
        echo "Usage: $PROGNAME [ options ] file [ ... ]" 1>&2
        exit 0
fi

# Process each input file
for FILE in $*
do
        BASENAME=`basename "$FILE" .bib`

# Check file is there.
    if [ -r "$FILE.bib" -a -f "$FILE.bib" ]
    then
        $DEBUG && echo "Reading <$FILE.bib>" 1>&2
        INFILE="$FILE.bib"
    elif [ -r "$FILE" -a -f "$FILE" ]
    then
        $DEBUG && echo "Reading <$FILE>" 1>&2
        INFILE="$FILE"
    else
        echo "$PROGNAME: Can't read $FILE" 1>&2
        INFILE=""
    fi

# If file exists, process it.
    if [ "$INFILE" ]
    then

# Expand and split trailing spaces
        expand $INFILE | sed 's/ *$//' |

# Get names
        sed -n '/^@.*{.*,$/s/^@.*{\(.*\),$/\\nocite{\1}/p' |

# Optionally sort into alphabetical dictionary order
        if $ALPHABETICAL
        then
                sort -d
        else
                cat
        fi |

# Add header and footer
{
        echo "
\\documentstyle[11pt]{article}

\\begin{document}

"
        cat
#       echo "
# \\newpage
# \\setcounter{page}{1}
# "
        echo "
\\bibliography{$FILE}
\\bibliographystyle{$STYLE}

\\end{document}

"
} |

# Check for named files
        if $NAMEDFILES
        then
                cat > "$BASENAME.tex"
        else
                cat
        fi

    fi

done

exit 0
