#!/bin/bash

#####################################
##### LATEST VERSION: at ~/REF/BIBTOOL-TST
#####################################

#####################################
# Author: christos faloutsos
# Date: Dec. 2011
#
# $Author: christos $
# $Date: 2012/01/01 03:06:41 $
# $Revision: 1.6 $
#####################################

# expects two (or more) bibtex files
#     double-checks they are OK
#     and merges them (dup-elimination) 
# into $OUTBIB

VERSION=1.6

echo "%    "
echo "%    ------------starting (v. $VERSION) -------------"

OUTBIB=all.bib
OUTTMP=__tmp    # very subtle: it holds the intermediate result, 
                # so that 
		#      $0 *.bib 
		# will NOT get in an infinite loop


# the work-horse!
BIBTOOLCMD="bibtool -d  -- preserve.key.case=on -- check.double.delete=on -s "

narg=$#

if [ $# -eq 0 ]
then
    echo "USAGE: $0 bibtex-file-name1 [bibtex-file-name2 ... ]    - exiting"
    exit
fi

# parsing the command-line files, and error checking

END=$narg
for ((j=1;j<=END;j++)); do
    new[$j]=$1
    shorthand=$1

    echo "%     FYI fname $j = ${new[$j]}"
    if [ ! -f $shorthand ]
    then
         echo "ERROR: can not find file '$shorthand' - exiting"
         exit
    fi
    if [ ${shorthand} != ${shorthand%.bib}.bib ]
    then
        echo "ERROR: '$shorthand' should have a '.bib' suffix - exiting"
        exit
    fi

    shift # to move to the next command-line argument - long story...
done

# creating 'clean' versions of input files
# ie., it passes all input files through bibtool, in case
# they have bibtex syntax errors

SUFFIX="_cleaned.bib"
\rm -f *${SUFFIX} 
for ((j=1;j<=END;j++)); do
    tmp=${new[$j]}
    echo "%    FYI: $0 working on $tmp  - cleaning it up"
    # bibtool -d -r $RFILE -s ${tmp} > ${tmp%.bib}${SUFFIX}
    $BIBTOOLCMD ${tmp} > ${tmp%.bib}${SUFFIX}
done

# echo "%    FYI: preemptively, removing $OUTBIB and $OUTTMP"
\rm -f $OUTBIB 
\rm -f $OUTTMP

# merge everything to a temp file
# bibtool -d -r $RFILE -s *${SUFFIX}  > $OUTBIB
$BIBTOOLCMD *${SUFFIX}  > $OUTTMP
mv $OUTTMP $OUTBIB
\rm -f $OUTTMP

echo "%    FYI: DONE with merging - cleaning up temp files "
\rm -f *${SUFFIX}
echo "%    FYI: removed temp files - all done "
echo "%            "
echo "%            **** output in $OUTBIB **** "
