#!/usr/bin/perl
#-*- perl -*-
#
# file:         pdfmerge
# created:      pasha may 9 2008
# modified:     pasha jul 2 2020
# modification: added --version option
#

use strict;
use warnings;
use Getopt::Long;
use PDF::API2;

$SIG{__WARN__} = sub { die ($_[0]); };  # die on warnings

sub _error ($);

my $method;
GetOptions 
  (
   'method=s' => \$method,

   'version' => sub
   {
	 print (STDERR 'PDF::API2 version ' . $PDF::API2::VERSION . "\n");
	 exit (0);
   },

   'help' => sub
   {
     print STDERR <<EOF
Usage:   
pdfmerge --method=<pdfapi2,pdfpages> <input> [... <input>] <output>
pdfmerge --help|--version
where:
--method  specifies whether to use perl with PDF::API2 (version ${PDF::API2::VERSION}) or LaTeX
          with pdfpages
<input>   input pdf file(s)
<output>  output pdf file
--version prints version of PDF::API2 and quites

Example: 
pdfmerge --method=pdfapi2 part1.pdf part2.pdf whole.pdf
Merges part1.pdf and part2.pdf into whole.pdf .
EOF
       ;
     exit (0);
   },
  );


_error ('--method option is mandatory') if (! defined ($method));

my $n = scalar (@ARGV);
# all arguments, except the last one, supposed to be input pdf files, 
# the last one is output pdf file

my $i;
for ($method)
  {
    /^pdfapi2$/ && do
      {
		my ($inputpdf, $j);
		my $outputpdf = PDF::API2->new;
		my $pages_counter = 0;
		for ($i = 0; $i < $n-1; $i++)
		  {
			$inputpdf = PDF::API2->open ($ARGV[$i]);
			for ($j=1; $j <= $inputpdf->pages; $j++)
			  {
				print (STDERR "processing page $j from " . $ARGV[$i] . " ...\n");
				$pages_counter++;
				$outputpdf->importpage ($inputpdf, $j, $pages_counter);
			  }
			$inputpdf->end();
		  }
		$outputpdf->saveas ($ARGV[$n-1]);
		$outputpdf->end();
		
		last;
	  };

    /^pdfpages$/ && do
      {
		(my $output = $ARGV[$n-1]) =~ s/\.pdf$//;

		# older pdflatex'es may not honor -jobname option when being piped;
		# at least this ok for pdflatex from texlive-2008
		open (IN, "|pdflatex -jobname=$output") || die();
		print IN <<"EOF"
\\documentclass{article}
\\usepackage{pdfpages}
\\begin{document}
EOF
		  ;
		for ($i = 0; $i < $n-1; $i++)
		  {
			print (IN '\includepdf[pages=-]{' . $ARGV[$i] . "}\n");
		  }
		print (IN "\\end{document}\n");
		close (IN);
		last;
      };
	
    _error ('--method option should take one of two values: pdfapi2 or pdfpages');
  }

exit (0);


sub _error ($)
  {
    print (STDERR 'ERROR: ' . $_[0] . "\n");
    exit (-1);
  }

__END__
