#!/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

if (scalar(@ARGV) != 2 ) {

    print "$0: Convert all *.pdf files in a directory into one PDF file in the curent directory\n\n";
    print "usage $0 file.pdf directory_of_pdf_files/ \n" ;
    exit 1;
}


my $PDF2PS = '/usr/bin/pdf2ps';
my $GS = '/usr/bin/gs' ;
my (@filelist, $file);

my $PDFFILE = shift ;
my $PDFDIR = shift;

chomp($PDFDIR);

$PDFDIR = $PDFDIR . '/' if substr($PDFDIR, length($PDFDIR)-1) ne '/';

print "Combining all .pdf files in $PDFDIR to one file called $PDFFILE\n" ;

opendir(DIR, $PDFDIR) or die "Can't open directory $PDFDIR: $! \n" ;

while (defined($file = readdir(DIR))) {

    next if $file =~ /^\./ ;
    next if $file =~ /^\.\./ ;
    next if !($file =~ /\.pdf$/) ;

    $file = $PDFDIR . $file ;
    my $outfile = $file . ".ps";

    push(@filelist, $outfile) ;

    `$PDF2PS $file $outfile` ;
}

#convert ps files to a pdf file

my $listoffiles = join(" ", @filelist) ;
`$GS -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=$PDFFILE  -dBATCH $listoffiles` ;

# clean up after yourself

foreach $file (@filelist) {

    `rm $file` ;
}
