#! /usr/bin/perl

# Program to substitute in bib file  author names for their codes.
# the codes are in the code file names (name\tcode)
# 

# (1) quit unless we have the correct number of command-line args
$num_args = $#ARGV + 1;
if ($num_args != 3) {
  print "\nUsage: name2code.pl codefile bibfile outfile\n";
  exit;
}

open(CODEF,$ARGV[0]) or die "Can't open code file: $!\n";

#Read bib file into array
open(BIBF,$ARGV[1]) or die "Can't open bib file$!\n";
my @biblines = <BIBF>;
close(BIBF);

# Main loop: get code, search whole array and change
while($authcode = <CODEF>)
  { ($code, $name) = split("\t",$authcode);
	  chop($name);
	  
	  for ($i = 0; $i < @biblines; $i++)
	     {$biblines[$i] =~ s/$name/$code/;}
	 }
	 
close(CODEF); 

#Write out file
open(OUTF, ">$ARGV[2]") or die "Can't open output file $!\n";
	  foreach $bibln (@biblines)
	    { print OUTF $bibln;}
close(OUTF)