#!/usr/bin/perl -w
use strict;
# n21pdf.pl: A quick and dirty little program to convert multiple PDFs
# to one PDF requires pdf2ps and Ghostscript
# written by Faber Fedor (faber@linuxnj.com) 2003-05-27
# Tweaked by Ben Okopnik 05-27-2003

die "Usage: ", $0 =~ /([^\/]+)$/, " <outfile.pdf> <directory_of_pdf_files>\n"
        unless @ARGV == 2;

my ( $PDFFILE, $PDFDIR ) = @ARGV;

my $filelist;
my ( $GS, $PDF2PS ) = ("/usr/bin/gs", "/usr/bin/pdf2ps");
my $GS_ARGS = " -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=$PDFFILE -dBATCH ";

print "Combining all .pdf files in $PDFDIR into $PDFFILE\n" ;

for ( <$PDFDIR/*pdf> ){
        system "$PDF2PS", "$_", "$_.ps"
                and die "$_ to $_.ps: PDF-PS conversion problem!\n";
        $filelist .= " $_.ps";
}

my $cmd_string = $GS . $GS_ARGS . $filelist ;
#convert ps files to a pdf file
system $cmd_string
        and die "Problem combining files!\n";

# clean up after yourself
unlink or die "$_: $!\n" for split ' ', $filelist

