#!/usr/bin/perl
#
# $Id: TexProcess.pl,v 1.2 2005/05/12 17:43:00 ashu Exp $
#
# Pre-process a TeX file and do:
#  a) strip out comments
#  b) process \input, \include, \includeonly and \bibliography statements
#
# finally produce a file which can be processed by latex. Useful for 
# camera-ready submissions to ACM.
#
# Limitation: does not do anything with the style or class files
#
# Author: Ashwin Bharambe  (ashu@cs.cmu.edu)  -- Copyright (c) 2005 

use strict;
use Getopt::Std;
use IO::File;
use vars qw();

getopts ("");

our $SEEN_BIB = 0;
our $ALLOWED_INCLUDES = undef;
our $ERROR = 0;
our $MAINFILE = shift @ARGV;
defined $MAINFILE or die "No file given to process!\n";

PreProcessFile ($MAINFILE);
exit ($ERROR);

sub PreProcessFile ($)
{
    my $file = shift;
    my $fh = new IO::File ("< $file");
	
    defined $fh or die "Can't open $file for reading: $!\n";

    my $str;
    while (<$fh>) {
	next if /^%/;          # fast path;
	
	chomp;
	
	$str = ProcessLine ($_);
	print "$str\n" if defined $str;
    }
    close $fh;    
}

sub ProcessLine ($)
{
    my $line = shift;

    # perform comment processing;
    $line =~ s/\\%/___percent___/g;
    $line =~ s/%.*//;
    $line =~ s/___percent___/\\%/g;

    # check for includeonly; include; input;
    if ($line =~ /\\input{([^}]+)}/) {
	my $file = `basename $1 .tex`;
	chomp $file;
	
	PreProcessFile ("$file.tex");
	return undef;
    }
    elsif ($line =~ /\\includeonly{([^}]+)}/) {
	$ALLOWED_INCLUDES = $1;
	return undef;
    }
    elsif ($line =~ /\\include{([^}]+)}/) {
	my $file = `basename $1 .tex`;
	chomp $file;

	if (defined $ALLOWED_INCLUDES && $ALLOWED_INCLUDES !~ /$file/) {
	    return undef;
	}

	# the semantics of include say only a warning is produced!
	if (!-f "$file.tex") {
	    print STDERR ">>> WARNING: include'd file ($file.tex) doesn't exist!\n";
	    $ERROR = 1;
	    return undef;
	}
	    
	PreProcessFile ("$file.tex");
	return undef;
    }
    elsif ($line =~ /\\bibliography{([^}]+)}/) {
	if (!$SEEN_BIB) {
	    my $file = `basename $MAINFILE .tex`;
	    chomp $file;
	    
	    return $line if !-f "$file.bbl";
	    PreProcessFile ("$file.bbl");
	}
	$SEEN_BIB = 1;
	return undef;
    }
    elsif ($line =~ /\\epsfig{figure=([^, ]+)/) {
	print STDERR "$1\n";
	return $line;
    }

    return $line;
}
