#! /bin/tcsh -f
if ($#argv != 1) then
    echo "usage: bibTOxml.sh bibfile"
else
    #setting input file
    set infile = $1
    #setting bibclean output file
    set bibcleanout = $infile.clean
    #setting bibclean error-log file
    set bibcleanerr = $bibcleanout.errors
    #set bibcleanerrerr = $bibcleanerr.error
    #setting bibparse error-log file
    set bibparseerr = $infile.bibparse.errors
    #setting bibxml output file
    set bibxmlout = $infile.noconv.xml
    #setting utf conversion error-log file
    set converr = $infile.conv.errors
    #setting final output file
    set outfile = $infile.inter.xml
    #setting final file
    set finalfile = $infile.xml

    echo "Parsing file $infile..."

    #starting bibclean with some options
    echo "Starting bibclean..."
    ./bibclean -delete-empty-values -error-log $bibcleanerr $infile > $bibcleanout
    # starts error.pl

    set error = $bibcleanerr.error.html
    set warning = $bibcleanerr.warning.html

    (./error.pl $bibcleanerr > $warning ) > & $error

    echo "bibclean output file: $bibcleanout"

    echo "Starting Bibparse.."
    ./bibparse $bibcleanout > & $bibparseerr

    echo "Parsing finished!"

    echo "Starting bibxmlparse..."
    ./bibxmlparse $bibcleanout > $bibxmlout
    echo "bibxmlparse output file: $bibxmlout"
    # cleaning up the bibxmlparse output
    perl prep.pl < $bibxmlout > $bibxmlout.zwi
    echo "Converting Latex special characters..."
    # first convert iso8859-1 (Latin1) characters to Latex special characters 
    # then convert ("recode") Latex special characters to utf-8
    recode -d l1..ltex < $bibxmlout.zwi > $outfile.zwi
    recode -d ltex..utf8 < $outfile.zwi > $outfile.utf.zwi
    # a perl file for characters that recode does not handle properly
    perl ec.pl < $outfile.utf.zwi > $outfile.utf 

    echo "Conversion finished !" 
    echo "XSL Transformation..." 
    xsltproc i2bibtexml.xsl $outfile.utf > $infile.xml 
    echo "Transformation finished !" 
    
   # The next step is optional, see description of the "conv" programme
   # in bibTOxml.doc
    echo "Tidying up the resulting output..." 
    ./conv  < $infile.xml  > zwi
   # now rename this intermediary file and give it its true name
    mv zwi $infile.xml
    echo "output file:  $infile.xml"
    echo "Note that this file is UTF-8 encoded !"
endif
