#!/usr/dist/bin/perl

print "\nHandout Builder: makes 2x3 pdf handouts with interleaved note pages\n\n";

if($#ARGV != 0)
{
  print "\n\n";
  print "Usage: makehandout filename.tex";
  print "\n\n";
  exit(-1);
}

if(!-e "@ARGV[0]")
{
  print "ERROR: file @ARGV[0] does not exist\n\n";
  exit(-1);
}

$filename=`basename @ARGV[0] .tex`;
chomp($filename);
$texname="$filename.tex";
$pdfname="$filename.pdf";

$handoutbasename="$filename-Handout";
$handouttexname="$filename-Handout.tex";
$handoutpdfname="$filename-Handout.pdf";

#Apparently, its enough to have this file in your tex path
#system("cp home/grad/cbourke/.latex/NoteSlide.pdf .");

print "Making Beamer Presentation Handout With Notes.\n";
print "===================================================\n";
print "Running sed script on $texname...\t";

system("sed -e 's/documentclass{beamer}/documentclass[handout]{beamer}/g' $texname > $handouttexname");

print "DONE\n";

print "Making First LaTeX Run...\t\t";

# We run pdfLaTeX in nonstopmode, dumping any error messages
# into FirstTeX.output

$FirstRun = system("pdflatex --interaction nonstopmode $handouttexname > FirstTeX.output");

if($FirstRun != 0)
{
    print "\n\n";
    print "There was a Fatal pdfLaTeX Error:\n";
    print "--------------------------------------------------\n";
    system("cat FirstTeX.output"); #write out the log file to stdout
    print "--------------------------------------------------\n\n";
    #system("nedit $filename.bib &");
    #system("rm FirstTeX.output");
    exit(-1);
}
else
{
  print "DONE\n";
}

print "Making Second LaTeX Run...\t\t";
#system("pdflatex $texname > /dev/null");
print "DONE\n";

#print "Building Handouts...\n";
#system("buildpdf $handouttexname");

system("pdfnup --nup 1x1 --orient landscape --frame true --trim \"0cm 0cm 0cm 0cm\" --outfile temp.pdf $handoutpdfname");
system("pdfnup --nup 2x3 --paper letter --pages all --orient portrait --frame false --trim \"-1cm -1cm -1cm -1cm\" --outfile $handoutpdfname temp.pdf");
system("cleanlatex $filename");
#system("rm $handouttexname");



