#!/opt/local/bin/perl

# auxtobib takes the name of a main .aux file (as generated by LaTeX)
# as argument.  It extracts all the citations contained in the aux
# file, recursively descending into included aux files (as generated
# by the LaTeX \include directive), and uses this list to extract a
# BibTeX file containing only the cited references, including the
# needed string abbreviations and crossreferences. The names of the
# BibTeX files are taken from the main aux file, and are searched in 
# exactly the same way as done by bibtex.
#
# Needs bib2bib (see http://www.lri.fr/~filliatr/bibtex2html)
# and kpsewhich (comes with the kpathsea library).
#
# Ralf Treinen <treinen@debian.org>.
# Published under the Gnu General Public Licence, version 2.

# process arguments
if ( $#ARGV != 0 ) {&errorexit("Usage: aux2bib <aux-file>");}
$mainauxfile = $ARGV[0];

sub errorexit {
    print STDERR "aux2bib: @_[0]\n";
    exit;
}

# process the aux files
sub dofile {
	local($filename, $handle) = @_;
	$handle++;
	open($handle,$filename) || &errorexit("Cannot open file $filename");
	while (<$handle>){
		if (/\\\@input\{(.*)\}/) {
			&dofile($1,$handle);
			next;
		}
		if (/\\citation\{(.*)\}/) {
		        foreach $subkey (split(/,/,$1)) {
				$keys{$subkey} = 0;
			}
			next;
		}
		if (/\\bibdata\{(.*)\}/) {
			@bibfiles = split(/,/,$1);
		}
	}
	close $handle;
}
&dofile($mainauxfile,'handle00');

# build the expression for the search condition
$condfile="/tmp/aux2bib$$";
open(COND,"> $condfile") || &errorexit("Cannot open temp file $condfile");
foreach $key (keys %keys){
	print COND "\$key=\"$key\" or ";
}
print COND "1=2\n";
close COND;

# get the string of path names of the bib files
$bibfilesbib = "";
foreach $bibfile (@bibfiles) {
    $bibfilesbib .= "$bibfile.bib "
}

$bibfilestring = "";
open(CMD,"kpsewhich $bibfilesbib|");
while (<CMD>){
    chop;
    $bibfilestring .= "$_ ";
}
close(CMD);

# call bib2bib
open(CMD,"bib2bib -c \"`cat $condfile`\" $bibfilestring|");
while (<CMD>){print;}
close(CMD);

# cleanup
unlink($condfile);
