#!/igd/a4/software/perl/bin/perl -w


#
#      Bibtex everything and repair broken \path's and \url's
#
# Bibtex messages are also filtered.
# The following warning messages are discarded:
# o  Warning--empty publisher
# o  Warning--can't use both volume and number
# o  Repeated entry
#   
# source ~/.tex first!
#
# GZ, May 2000 (Gabriel.Zachmann@gmx.net)
#


# you can add your favorite main tex file name here
@default_main_files = ( "whole", "main", "root" );


#usey diagnostics;
use English;
use FileHandle;
STDOUT->autoflush(1);


#  tex variables set already?
if ( ! defined($ENV{"TEXDIR"}) )
{
	die "btx: environmnet variable TEXDIR not set!\nsource ~/.tex\n";
}


$maintex = shift;
if ( ! defined($maintex) )
{
	foreach $f ( @default_main_files )
	{
		if ( -e "$f.tex" )
		{
			$maintex = "$f";
			last;
		}
	}
}

if ( ! defined($maintex) )
{
	die "btx: no main tex file specified and none of the default ones found!\n";
	exit -1;
}

$maintex =~ s/\.tex$//o;
print "main tex file = $maintex.tex\n";


print "Running bibtex ...\n";

#  run bibtex, kill warnings "Repeated entry" ...

#`bibtex $maintex 1>&2`;
$duplicate=0;
open( PIPE, "bibtex $maintex 2>&1 |" )
	or die "btx: can't fork: $!";
while (<PIPE>)
{
	# switch filter on
	if ( m/^Repeated entry/o ) { $duplicate = 1; }
	# skip one-line warnings
	if ( m/^Warning--empty publisher/o ) { next; }
	if ( m/^Warning--can't use both volume and number/o ) { next; }
	# print, if not filtering right now
	print if ! $duplicate;
	# switch filter off (these lines will be filtered, too)
	if (  $duplicate && m/^I'm skipping whatever remains of this entry/o )
	{ $duplicate = 0; }
}


#  remove trailing % characters

open F, "$maintex.bbl"
	or die "btx: couldn't open bbl file $maintex.bbl: $!\n";

@f = <F>;
$f = join "", @f;
$f =~ s/\%\n//og;

close F;
open F, ">$maintex.bbl"
	or die "btx: couldn't open bbl file $maintex.bbl for output: $!\n";

print F $f;

close F;
close PIPE;


