#!/usr/bin/perl
#
#clean a latex file for camera-ready submission
#this is the second part of cleanlatex, it removes duplicate
#definitions and unused definitions 
#
#Jan Poland, March 8, 2006
#

@A=<STDIN>;

@B=@A;
@P=();
$found = 0;
while (@A>0 && !$found) {  
  if (@A[0]=~/^\\begin{document}/) {$found=1;} else {unshift(@P,shift(@A));}  
}
@Q=();
while (@P>0) {
  $s = shift(@P);
  if ($s=~/^\\newcommand/) {
    $r=$s;
    chomp($r);
    $r=~s/^\\newcommand{\\(\w+)}.*/\1/;
    $add=0;
    foreach $line(@B) {if (($line=~/\\$r[^a-zA-Z]/ || $line=~/\\$r$/) && !($line=~/^\\newcommand{\\$r}/)) {$add=1;}}
  } else {$add=2;}
  if ($add==1) {
    foreach $line(@Q) {if ($line=~/^\\newcommand{\\$r}/) {$add=0;}}
  }
  if ($add) {unshift(@Q,$s);} else {
    $cut=1;
    while ($cut) {
      $r=$s;
      chomp($r);
      if (@P==0 || chop($r) ne '%') {$cut=0;}
      if ($cut==1) {$s = shift(@P);}
    }  
  }
}
print @Q;
print @A;


