#! /usr/local/bin/perl -s
#
# Usage: refparse  -r=references_file
#
# Use this program to turn DOS / OS/2 Text reference list files from
# Excel into Bibtex database files.
#
# If there is no command-line switche, refparse looks for the file
# "references".  If the switch -r is used, it will use the file names
# specified with it.
#
# Should add the formatting rules and transfer procedure for the Excel
# file, here.
#

# The Beginning

print "Opening files for reading and writing.\n";
# Open file for reading
if ($r)
   { open(REFERENCE, $r) || die "Couldn't open references file!\n"; }
else
   { open(REFERENCE, "references") || die "Couldn't open references file!\n"; }

# Open file for writing
open(REFBIB, "> references.bib") || die "Couldn't open references.bib file!\n";

print "Translating references file -> references.bib.\n";
# Read references file
$ref=<REFERENCE>;
while($ref=<REFERENCE>) {
   chop($ref);
   &decode_ref($ref,);
}


# Decode references input and write Bibtex file
sub decode_ref {
   local($lref) = @_;
   $lref =~ s/"//g;
   @REF     = split(/\t/,$lref);
   $ID      = $REF[0];
   $year    = $REF[1];
   $authors = $REF[2];
   $title   = $REF[3];
   $pub     = $REF[4];
   $volume  = $REF[5];
   $number  = $REF[6];
   $pp      = $REF[7];
   $type    = $REF[8];

   $pp =~ s/-/--/;    # change - to -- in page ranges
   $authors = &arrange_auth($authors,*Shortref,*year);  # rearrange authors
   push(@Shrefid,$ID);

   print REFBIB "\@\U$type\E\{$ID,\n";
   print REFBIB "  author = \"$authors\",\n";
   print REFBIB "  title = \"$title\",\n";
   if ("\U$type" =~ /ARTICLE/)
     { print REFBIB "  journal = \"$pub\",\n"; }
   elsif ("\U$type" =~ /INPROCEEDINGS/)
     { print REFBIB "  booktitle = \"$pub\",\n"; }
   elsif ("\U$type" =~ /INCOLLECTION/)
     { print REFBIB "  booktitle = \"$pub\",\n";
       print REFBIB "  publisher = \"$number\",\n"; }
   elsif ("\U$type" =~ /PHDTHESIS/)
     { print REFBIB "  school = \"$pub\",\n"; }
   elsif ("\U$type" =~ /TECHREPORT/)
     { print REFBIB "  institution = \"$pub\",\n"; }
   else
     { print REFBIB "  journal = \"$pub\",\n"; }
   print REFBIB "  year = \"$year\",\n";
   print REFBIB "  volume = \"$volume\",\n";
   if ("\U$type" !~ /INCOLLECTION/)
     { print REFBIB "  number = \"$number\",\n"; }
   print REFBIB "  pages = \"$pp\"\}\n";
   print REFBIB "\n";
}


# Rearrange the authors' names
sub arrange_auth {
   local($authorlist) = $_[0];
   local(*Shortref) = $_[1];
   local(*year) = $_[2];

   @broken = split(/\,\s/,$authorlist);
   @main = split(/\s/,@broken[0]);
   foreach $name (0 .. $#broken) {
     @person = split(/\s/,$broken[$name]);
     $broken[$name] = $person[1].' '.$person[0];
   }
   push(@Shortref, $main[0]." ($year)");
   $authorlist = join(' and ',@broken);
}
