#!/usr/bin/perl -w
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#NAME
#  pdfjoin - Join PDF files into a single file 
#
#SYNOPSIS
#  pdfjoin [options] [file]..
#REQUIRES
#
#DESCRIPTION
# This program uses gs (ghostscript) to combine a list of PDF files into a
# single PDF file.  By default, it's 
#
#OPTIONS
# 
# -O<file>
#   Write the PDF output to <file>.  The default is standard output.
#
#EXAMPLES
#
#FILES
#
#BUGS
#
#SEE ALSO
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu>
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

$| = 1;
$exitstat = 0;
($P = $0) =~ s".*/"";
$V = $ENV{"V_$P"} || $ENV{"D_$P"} || 1;	# Verbose level.

$outfile = '-';		# Write to stdout by default
$infiles = '';		# List of PDF files to combine

foreach $arg (@ARGV) {
	print STDERR "$P: arg=\"$arg\n" if $V>1;
	if (($flg,$opt,$val) = ($arg =~ /^([-+])(\w)(.*)$/)) {
		print STDERR "$P: flg '$flg' opt '$opt' val 'val'\n" if $V>1;
		if ($opt eq 'O' ) {
			$outfile = $val;
			print STDERR "$P: outfile=\"$outfile\"\n" if $V>1;
		} else {
			print STDERR "$P: Option $flg$opt not recognized, ignored.\n" if $V;
		}
	} elsif (-f $arg) {
		print STDERR "$P: infile=\"$arg\"\n" if $V>1;
		$infiles .= "$arg ";
	} elsif (-f "$arg.pdf") {
		print STDERR "$P: infile=\"$arg.pdf\"\n" if $V>1;
		$infiles .= "$arg.pdf ";
	} else {
		print STDERR "$P: arg \"$arg\" not recognized, ignored.\n" if $V;
	}
}

$cmd = "gs -dSAFER -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=$outfile $infiles";
print STDERR "$P: cmd=\"$cmd\"\n" if $V>1;
$result = `$cmd`;
$exitstat = $?;
if ($result) {
	print $result;
} else {
	print STDERR "$P: No output produced.\n" if $V>1;
	$exitstat = 1 unless $exitstat;
}

print STDERR "$P: Exit with status $exitstat.\n" if $V>1 || $exitstat;
exit $exitstat;
