#!/usr/bin/perl

# Files used: 
#			bp.pl and the bp perl libraray
# $basename.aux    	source of citations
# $basename.bpk  	dictionary of key conversions; and the list of source
#			bibfiles 
# $basename.bib		output bib file

# 
# The file $basename.bpk contains two types of entries, each entry on
# a separate line.
# The first type of entry is of the form
#     bibinpfile [path and name of file]   (extension included)
# This specifies that entries should be searched for in the given file
# The second type of entry has the form
#     key1 key2
# key1 is the key that appears in the .aux file, while key2 is the key
# that appears in the input biblio files.
# Example .bpk file:
# 
# BS:pyond MR97j:60179
# bibinpfile /home/rdlyons/texstuff/mr.bib
# bibinpfile /home/rdlyons/texstuff/prep.bib



# Get path to library:
unshift(@INC, $ENV{'BPHOME'})  if defined $ENV{'BPHOME'};
require "bp.pl";

&bib'errors('print', 'exit');

@ARGV = &bib'stdargs(@ARGV);

# Get the base file name
$basename = shift @ARGV;
&dieusage  unless $basename;
$basename =~ s/\..*$//;



sub getcitations { # get keys 
  die "Could not find or open aux file $auxname\n" unless
  open(AUXIN,$basename . ".aux");

  %cits = ();
  while(<AUXIN>)
  {
	if(/\\citation\{(.*)\}/)  { $cits{$1} = $1 ;}
  }
}

sub getdict { # gets keys dictionary and list of source bib files
  if (open(DICT,$basename . ".bpk"))
  {
    while(<DICT>)
    {
	my($a,$b) = split;
	if($a eq "bibinpfile") { unshift(@bibfiles, $b);}
	elsif(defined($cits{$a}))  { $cits{$b} = $a;}
    }
  }
}


&getcitations;
&getdict;
die "No bib files specified" if -1 == $#bibfiles;

&bib'format("bibtex","bibtex"); # specifies input and output formats

$outfile = "$basename.bib" unless defined $outfile;
# check that if the file exists, we can write to it.
if (-e $outfile && !-w $outfile) {
  die "Cannot write to $outfile\n";
}
# check that we won't be overwriting any files.
if ($outfile ne '-') {
  foreach $file (@bibfiles) {
    next if $file eq '-';
    die "Will not overwrite input file $file\n" if $file eq $outfile;
  }
}

# open output file
&bib'open('>' . $outfile) || die "Could not open $outfile\n";


# Read the input bib files, and output those entries that are needed,
# with any required change of keys.
foreach $file (@bibfiles) {
  next unless &bib'open($file);
  while ($record = &bib'read($file) ) {
    	%entry = &bib'explode($record);
	if(defined $cits{$entry{'CITEKEY'}})
	{ 
		my($origkey) = $entry{'CITEKEY'};
		if(!($origkey eq $cits{$origkey})) { # need to change key
			$entry{'CITEKEY'} =  $cits{$origkey};
			if($origkey =~ /^MR.*:.*/ 
		   		# probably Math Reviews record number
				&& ! defined $entry{'MR'}) {
				$entry{'MR'} = $origkey; # keep the MR number
			}
			else { $entry{'OLDKEY'} = $origkey;}
		}
    		&bib'write($outfile, &bib'implode(%entry));
	}
    }
    &bib'close($file);
  }

&bib'close('>' . $outfile);




sub dieusage {
  my($prog) = substr($0,rindex($0,'/')+1);
 
  $str =<<"EOU";
Usage: $prog basefilename[.tex]
EOU
 
  die $str;
}


exit;

