%
%    \iffalse
%
% pdfpages.dtx Copyright (C) 2001-2003 Andreas MATTHIAS
%
%<*package>
%% This program may be distributed and/or modified under the
%% conditions of the LaTeX Project Public License, either version 1.2
%% of this license or (at your option) any later version.
%% The latest version of this license is in
%%   http://www.latex-project.org/lppl.txt
%% and version 1.2 or later is part of all distributions of LaTeX 
%% version 1999/12/01 or later.
%%
%</package>
%% Please send error reports and suggestions for improvements to
%%   Andreas MATTHIAS <amat@kabsi.at>.
%%
%
%<*!package>
% ===================================================================
%  @LaTeX-package-file{
%    author         = {Andreas MATTHIAS},
%    version        = "0.3e",
%    date           = "2004-01-31",
%    filename       = "pdfpages.sty",
%    address        = "",
%    telephone      = "",
%    email          = "amat@kabsi.at",
%    codetable      = "ISO/ASCII",
%    keywords       = "pdfLaTeX, PDF, include, insert, page",
%    dependences    = "ifthen, graphicx, eso-pic",
%    supported      = "yes",
%    docstring      = "Package for inserting pages of external
%                      PDF documents. (Requiring pdfLaTeX.)"
%  }
% ===================================================================
%</!package>
%
%<*dtx>
           \ProvidesFile{pdfpages.dtx}
%</dtx>
%<package>\NeedsTeXFormat{LaTeX2e}
%<package>\ProvidesPackage{pdfpages}
%<pppdftexdef>\ProvidesFile{pppdftex.def}
%<ppvtexdef>\ProvidesFile{ppvtex.def}
%<driver>\ProvidesFile{pdfpages.drv}
%<*!example1&!example2&!example3>
%    \fi
%
%    \ProvidesFile{pdfpages.dtx}
   [2004/01/31 v0.3e
%
%    \iffalse
%</!example1&!example2&!example3>
%<*none>
%    \fi
]
%    \iffalse
%</none>
%
%<package>    Insert pages of external PDF documents (AM)]
%<pppdftexdef>    Pdfpages driver for pdfTeX (AM)]
%<ppvtexdef>    Pdfpages driver for VTeX (AM)]
%
%<package>\def\AM@version{0.3e}
%
%    \fi
%
%    \GetFileInfo{pdfpages.dtx}
%
%    \CheckSum{3495}
%
% \CharacterTable
%  {Upper-case    \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
%   Lower-case    \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
%   Digits        \0\1\2\3\4\5\6\7\8\9
%   Exclamation   \!     Double quote  \"     Hash (number) \#
%   Dollar        \$     Percent       \%     Ampersand     \&
%   Acute accent  \'     Left paren    \(     Right paren   \)
%   Asterisk      \*     Plus          \+     Comma         \,
%   Minus         \-     Point         \.     Solidus       \/
%   Colon         \:     Semicolon     \;     Less than     \<
%   Equals        \=     Greater than  \>     Question mark \?
%   Commercial at \@     Left bracket  \[     Backslash     \\
%   Right bracket \]     Circumflex    \^     Underscore    \_
%   Grave accent  \`     Left brace    \{     Vertical bar  \|
%   Right brace   \}     Tilde         \~}
%
%
%    \iffalse
%<*driver>
\documentclass{ltxdoc}
\usepackage{array}
\OnlyDescription
\begin{document}
  \DocInput{pdfpages.dtx}
\end{document}
%</driver>
%    \fi
%
%   \newcommand*{\versionlist}{%
%     \setlength{\topsep}{0pt}%
%     \setlength{\itemsep}{0pt}%
%     \setlength{\leftmargin}{20pt}%
%     \setlength{\parsep}{0pt}}
%   \newcommand{\marginstyle}
%     {\raggedleft\itshape\small}
%
%    \def\pdfTeX{pdf\kern.04em\TeX}
%    \def\pdfLaTeX{pdf\kern.06em\LaTeX}
%    \def\VTeX{V\kern-.05em\TeX}
%    \def\PDF{{\small PDF}}
%
%    \title{The \textsf{pdfpages} Package\thanks{This file
%           has version number \fileversion, last revised \filedate.}}
%    \author{Andreas MATTHIAS\\ \texttt{amat@kabsi.at}} 
%
%
%    \date{\filedate}
%
%    \maketitle
%
%    \begin{abstract}
%       \noindent
%       This package makes it easy to insert pages of external
%       PDF documents. It supports \pdfLaTeX\ and \VTeX\, but
%       does \textit{not} work with \LaTeX.
%    \end{abstract}
%
%    \tableofcontents
%
%
%    \section{Introduction}
%    Creating \PDF\ documents, it is sometimes useful to insert
%    pages of other, external \PDF\ documents. This can be done
%    with the |\includegraphics| command from the
%    \texttt{graphics} package. But a simple
%    |\includegraphics{doc.pdf}| normally produces
%    `|Overfull \hbox|' and `|Overfull \vbox|' warnings,
%    because the size of the inserted pages does not match the
%    print space.
%    
%    The |pdfpages| package makes it easy to insert 
%    pages of external \PDF\ documents without worrying about
%    the print space. Here are some features of the
%    |pdfpages| package: Several logical pages can be arranged
%    onto each sheet of paper and the layout can be changed
%    individually. A lot of hypertext operations are supported,
%    like links to the inserted pages, links to the original
%    \PDF\ document, threads, etc.
%  
%    \section{Usage}
%    \subsection{Package Options}
%
%    \begin{minipage}{\linewidth}
%    |\usepackage[|\meta{options}|]{pdfpages}|
%
%    \begin{quote}
%      \meta{option} -- 
%         \begin{minipage}[t]{.8\linewidth}
%            \setlength\leftmargini{3.5em}
%            \begin{description}
%               \setlength\itemsep{0pt}
%               \item[|final|:] Inserts pages. This is the default.
%               \item[|draft|:] Does not insert pages, but prints a box
%                               and the filename instead.
%               \item[|enable-survey|:] Activates survey functionalities.
%                               (\emph{experimental, subject to change})
%            \end{description}
%         \end{minipage}
%    \end{quote}
%    \end{minipage}
%    
%    
%    \subsection{Commands}
%    
%    \DescribeMacro{\includepdf}
%    Inserts pages of an external \PDF\ document.
%    
%    \medskip\noindent
%    \begin{minipage}{\linewidth}
%    |\includepdf[|\meta{key=val}|]{|\meta{filename}|}|
%    
%    \begin{quote}
%    \begin{tabular}{@{}l@{\,--~}>{\raggedright}p{.8\linewidth}}
%        \meta{key=val}   & A comma separated list of options
%                   using the \meta{key}=\meta{value} syntax.
%                   \tabularnewline[.25\baselineskip]
%        \meta{filename} & Filename of the \PDF\ document. (The
%                   filename \emph{must not} contain any blanks!)
%    \end{tabular}
%    \end{quote}
%    \end{minipage}\bigskip
%
%    
%    \noindent
%    The following list describes all possible options of
%    |\includepdf|. All options are using the \meta{key=value} syntax.
%    
%    \newcommand*{\df}[1]{(Default: \mbox{|#1|})}
%
%    \setlength{\leftmargini}{\parindent}
%    \begin{itemize}
%
%
%    \item Main options:
%
%      \begin{description}
%      \makeatletter\@beginparpenalty=10000\makeatother
%        \item[pages] Selects pages to insert. The argument is a comma
%                     separated list, containing page numbers 
%                     (|pages={3,5,6,8}|), ranges of page numbers 
%                     (|pages={4-9}|) or any combination.
%                     To insert empty pages use |{}|.
%                     \par
%                     E.g.: |pages={3,{},8-11,15}| will insert
%                     page 3, an empty page, and pages 8, 9, 10, 11,
%                     and 15.
%                     \par
%                     Page ranges are specified by the following syntax:
%                     \meta{m}|-|\meta{n}. This selects all pages from
%                     \meta{m} to \meta{n}. Omitting \meta{m} defaults
%                     to the first page; omitting \meta{n} defaults to
%                     the last page of the document. Another way to 
%                     select the last page of the document, is to use the
%                     keyword |last|. (This is only permitted in a
%                     page range.)
%                     \par
%                     E.g.: |pages=-| will insert \emph{all} pages
%                     of the document, and |pages=last-1| will insert
%                     all pages in revers order.
%                     \par\df{pages=1}
%        \item[nup]   Puts multiple logical pages onto each sheet
%                     of paper. The syntax of this option is: 
%                     |nup=|\meta{xnup}|x|\meta{ynup}. Where
%                     \meta{xnup} and \meta{ynup} specify the number of
%                     logical pages in horizontal and vertical direction,
%                     which are arranged on each sheet of paper.
%                     \df{nup=1x1}
%        \item[landscape] Specifies the format of the sheet of paper,
%                     which is rotated by 90~degrees. This does
%                     \emph{not} affect the logical pages, which
%                     will \emph{not} be rotated by the `landscape'
%                     option. To rotate the logical pages use the
%                     `angle' option (e.g.~`angle=90').
%                     Either `true' or `false' (or no value, which
%                     is equivalent to `true'). \df{landscape=false}
%      \end{description}
%
%
%    \item Layout options:
%
%      \begin{description}
%      \makeatletter\@beginparpenalty=10000\makeatother
%        \item[delta] Puts some horizontal and vertical space between the
%                     logical pages. The argument should be two dimensions,
%                     separated by space. See Chapter~\ref{sec:layout} and
%                     Figure~\ref{fig:layout}. \df{delta=0 0}.
%        \item[offset] Displaces the origin of the inserted pages.
%                     The argument should be two dimensions, separated
%                     by space. In `oneside' documents positive values
%                     shift the pages to the \emph{right} and to the
%                     \emph{top} margin, respectively, whereas in `twoside'
%                     documents positive values shift the pages to the
%                     \emph{outer} and to the \emph{top} margin,
%                     respectively. See Chapter~\ref{sec:layout} and 
%                     Figure~\ref{fig:layout}. \df{offset=0 0}
%        \item[frame] Puts a frame around each logical page. The frame is
%                     made of lines of thickness |\fboxrule|. Either `true'
%                     or `false' (or no value, which is equivalent to `true').
%                     \df{frame=false}
%        \item[column] Pdfpages normally uses `row-major' layout, where 
%                     successive pages are placed in rows along the paper.
%                     The |column| option changes the output into a
%                     `column-major' layout, where successive pages are 
%                     arranged in columns down the paper.
%                     Either `true' or `false' (or no value, which
%                     is equivalent to `true'). \df{column=false}
%        \item[columnstrict] By default the last page is not set in a
%                     strict `column-major' layout, if the logical
%                     pages do not fill up the whole page. The
%                     |columnstrict| option forces a strict
%                     `column-major' layout for the last page.
%                     Either `true' or `false' (or no value, which
%                     is equivalent to `true'). \df{columnstrict=false}
%                     \par\hskip15pt
%                     \begin{minipage}[b]{110pt}
%                       \centering
%                       \begin{tabular}{|c|c|c|}\hline
%                       1 & 4 & \phantom{6}\\\hline
%                       2 & 5 &\\\hline
%                       3 &&\\\hline
%                       \end{tabular}\smallskip\par
%                       |columnstrict=true|
%                     \end{minipage}
%                     \hskip15pt
%                     \begin{minipage}[b]{110pt}
%                       \centering
%                       \begin{tabular}{|c|c|c|}\hline
%                       1 & 3 & 5\\\hline
%                       2 & 4 & \\\hline
%                       &&\\\hline
%                       \end{tabular}\smallskip\par
%                       |columnstrict=false|
%                     \end{minipage}
%        \item[openright] This option puts an empty page before the
%                      first logical page. In combination with |nup=2x1|,
%                      |nup=2x2|, etc., this means that the first page
%                      is on the right side. The same effect can be
%                      achieved with the |pages| option, if an empty page
%                      is inserted in front of the first page.
%                      Either `true' or `false' (or no value, which
%                      is equivalent to `true'). \df{openright=false}
%        \item[pagecommand] Declares \LaTeX\ commands, which are executed
%                      on each sheet of paper.
%                      \df{pagecommand=\{\bslash thispagestyle\{empty\}\}}
%        \item[turn] By default pages in landscape format are displayed 
%                     in landscape orientation (if the \PDF\ viewer supports
%                     this). With \texttt{turn=false} this can be prohibited.
%                     Either `true' or `false' (or no value, which
%                     is equivalent to `true'). \df{turn=true}
%        \item[noautoscale] By default pages are scaled automatically.
%                     This can be suppressed with the 
%                     \texttt{noautoscale} option.
%                     In combination with the \texttt{scale} option
%                     (from graphicx) the user has full control over
%                     the scaling process.
%                     Either `true' or `false' (or no value, which
%                     is equivalent to `true'). \df{noautoscale=false}
%        \item[fitpaper] Adjusts the paper size to the one of the
%                     inserted document.
%                     Either `true' or `false' (or no value, which
%                     is equivalent to `true'). \df{fitpaper=false}
%        \item[reflect] Reflects included pages.
%        \item[signature] Creates booklets by rearranging
%                     pages into signatures and setting
%                     |nup=1x2| or |nup=2x1|, respectively. This option
%                     takes one argument specifying the size of the
%                     signature, which should be a multiply of 4.\par
%                     An example for documents in portrait orientation:\par
%                     |\includepdf[pages=-, signature=8,|\\
%                     \hspace*{6em} |landscape]{portrait-doc.pdf}|\par
%                     An example for documents in landscape orientation:\par
%                     |\includepdf[pages=-, signature=8]{landscape-doc.pdf}|
%       \item[picturecommand] Declares picture commands which are executed
%                      on every page within a picture environment with the
%                      base point at the lower left corner of the page.
%                      (The base point does not change if the page is
%                      rotated, e.g.~by the |landscape| option.)
%                      \df{picturecommand=\{\}}
%       \item[picturecommand*] Like |picturecommand|, but with the restriction
%                      that |picturecommand*| executes its picture commands
%                      only on the very first page.
%                      \df{picturecommand*=\{\}}
%        \item[pagetemplate] By default the first inserted page will be
%                     used as a template. This means that all further
%                     pages are scaled to match within the contour of this
%                     first page. This option allows to declare another
%                     page to be used as a template; which is only useful
%                     if a \PDF\ document contains different page sizes
%                     or page orientations. The argument should
%                     be a page number.
%                     \df{pagetemplate=\meta{first inserted page}}
%        \item[rotateoversize] This option allows to rotate oversized
%                     pages. E.g.\ pages in landscape orientation are
%                     oversized relatively to their portrait counterpart,
%                     because they do not match within the contour of
%                     a portrait page without rotating them. By default
%                     oversized pages are scale and are \emph{not} rotated.
%                     Either `true' or `false' (or no value, which
%                     is equivalent to `true'). \df{rotateoversize=false}
%         \item[doublepages] Inserts every page twice. This is useful for
%                     2-up printing, if one wants to cut the stack of paper
%                     afterwards to get two copies.
%                     Either `true' or `false' (or no value, which
%                     is equivalent to `true'). \df{doublepages=false}
%        \item[doublepagestwist] Whereas with |doublepages| the cutting
%                     edge is once on the inner side and ones on the outer
%                     side, |doublepagestwist| turns the pages such, that
%                     the cutting edge is always on the inner side.
%                     Either `true' or `false' (or no value, which is
%                     equivalent to `true'). \df{doublepagestwist=false}
%         \item[doublepagestwistodd] Turns the pages such, that the 
%                     cutting edge is always on the outer side.
%                     Either `true' or `false' (or no value, which is
%                     equivalent to `true'). \df{doublepagestwistodd=false}
%         \item[doublepagestwist*] Like |doublepagestwist| but for
%                     double side printing.
%                     Either `true' or `false' (or no value, which is
%                     equivalent to `true'). \df{doublepagestwist*=false}
%         \item[doublepagestwistodd*] Like |doublepagestwistodd| but for
%                     double side printing
%                     Either `true' or `false' (or no value, which is
%                     equivalent to `true'). \df{doublepagestwistodd*=false}
%      \end{description}
%
%
%    \item Hypertext options:
%
%      \begin{description}
%        \makeatletter\@beginparpenalty=10000\makeatother
%        \item[link] Inserted pages become a target
%                    of a hyperlink. The name of the link is 
%                    `\texttt{\meta{filename}.\meta{page number}}'.
%                    The filename extension of \meta{filename} 
%                    \emph{must not} be stripped.
%                    Either `true' or `false' (or no value, which
%                    is equivalent to `true').
%                    \df{link=false}
%        \item[linkname] Changes the default linkname created by the option 
%                        \texttt{link}. Instead of \meta{filename} the
%                        value of this option is used. E.g.~\texttt{
%                        linkname=mylink} produces the linknames
%                        `\texttt{mylink.\meta{page number}}'.
%        \item[thread] Combines inserted pages to an article thread.
%                     Either `true' or `false' (or no value, which
%                     is equivalent to `true'). \df{thread=false}
%        \item[threadname] Several threads are distinguished by their 
%                          threadnames. By default the threadname is equal
%                          to the filename (plus filename extension), but it
%                          can be changed with this option. This is useful if 
%                          the same file is inserted twice or more times and
%                          should not be combined to one single thread.
%                          Or the other way round if pages from different
%                          documents should be combined to one single thread.
%                          \df{threadname=\meta{filename.ext}}
%        \item[linktodoc] Lets the inserted pages be hyperlinks to the
%                         document from which they were extracted.
%                         Note that the \PDF-Viewer will not find the
%                         file, if \meta{filename} has not filename
%                         extension (.pdf).
%                         Either `true' or `false' (or no value, which
%                         is equivalent to `true'). \df{linktodoc=false}
%      \end{description}
%
%
%    \item Additional hypertext options:
%
%      \begin{description}
%        \makeatletter\@beginparpenalty=10000\makeatother
%        \item[linkfit] Specifies the way the viewer displays a linked page.
%                       This option changes the default behavior of the
%                       option \texttt{link}.
%                       Possible values are: \texttt{fitb}, \texttt{fith},
%                       \texttt{fitv}, \texttt{fitr}, 
%                       \texttt{xyz zoom \meta{integer}}, etc.
%                       These are destinations (|\pdfdest|) like they are
%                       described in \cite{pdftex}.
%                       Pdfpages adds one additional destination named
%                       |region|, which scales a page such that it fits
%                       exactly into the window of the \PDF\ viewer.
%                       \df{linkfit=fit}
%        \item[linktodocfit] By default the option \texttt{linktodoc} opens
%                            the page in `Fit in Window' view.
%                            Another view can be specified with this option.
%                            Possible values are the legal \PDF\ tokens:
%                            \texttt{/FitH} \meta{top}, \texttt{/FitV}
%                            \meta{left}, etc.
%                            (See \cite{PDFRef} for more details.)
%                            \df{linktodocfit=/Fit}
%        \item[newwindow] By default option |linktodoc| opens a new
%                         window. This can be changed with option |newwindow|.
%                         Either `true' or `false' (or no value, which
%                         is equivalent to `true'). \df{newwindow=true}
%        \item[linkfilename] Sets the name (with path) of the file to be
%                            linked to by the option \texttt{linktodoc}.
%                            You will hardly ever need this option.
%                            \df{linkfilename=\meta{filename.ext}}
%      \end{description}
%
%
%    \item Experimental options: (Syntax may change in future versions!)
%
%      \begin{description}
%        \makeatletter\@beginparpenalty=10000\makeatother
%
%        \item[addtotoc] Adds an entry to the table of contents. This
%                     option requires five arguments, separated by commas:
%
%                     \texttt{addtotoc=\{\meta{page number},^^A
%                     \meta{section},\meta{level},\meta{heading},^^A
%                     \meta{label}\}}
%
%                     \begingroup
%                     \renewcommand*\descriptionlabel[1]{\hspace\labelsep
%                                     \normalfont #1}
%                     \begin{description}
%                       \item[\meta{page number}:] Page number of the
%                          inserted page.
%                       \item[\meta{section}:] \LaTeX\ sectioning name
%                          -- e.g., section, subsection, \ldots
%                       \item[\meta{level}:] Number, denoting depth of
%                          section -- e.g., section=1, subsection=2,
%                          \ldots
%                       \item[\meta{heading}:] Title inserted in the 
%                          table of contents.
%                       \item[\meta{label}:] Name of the label. This label
%                          can be referred to with |\ref| and |\pageref|.
%                      \end{description}
%                      \endgroup
%
%                      Note: The order of the five arguments must not
%                      be mixed. Otherwise you will get very strange
%                      error messages.
%
%                      The |addtotoc| option
%                      accepts multiple sets of the above mentioned five
%                      arguments, all separated by commas. The sets must
%                      be sorted such that the \meta{page number}s are in 
%                      ascending order. (Strictly speaking they must have
%                      the same order as the page numbers specified by
%                      the |pages| option.)
%
%                      The proper recursive definition of the |addtotoc|
%                      option is:
%
%                     \texttt{addtotoc=}\{\meta{toc-list}\}
%
%                     \meta{toc-list} $\rightarrow$ \meta{page number},^^A
%                     \meta{section},\meta{level},\meta{heading},^^A
%                     \meta{label}[,\meta{toc-list}]
%
%
%        \item[addtolist] Adds an entry to the list of figures, the
%                      list of tables, or any other list
%                      (e.g.~from \emph{float.sty}). This option
%                      requires four arguments, separated by commas:
%
%                      \texttt{addtolist=\{\meta{page number},^^A
%                      \meta{type},\meta{heading},\meta{label}\}}
%
%                     \begingroup
%                     \renewcommand*\descriptionlabel[1]{\hspace\labelsep
%                                     \normalfont #1}
%                     \begin{description}
%                       \item[\meta{page number}:] Page number of the
%                          inserted page.
%                       \item[\meta{type}:] Name of a floating
%                          environment. (\texttt{figure},
%                          \texttt{table}, etc.)
%                       \item[\meta{heading}:] Title inserted into LoF,
%                          LoT, etc.
%                       \item[\meta{label}:] Name of the label. This label
%                          can be referred to with |\ref| and |\pageref|.
%                      \end{description}
%                      \endgroup
%
%                      Like \texttt{addtotoc}, \texttt{addtolist} accepts
%                      multiple sets of the above mentioned four arguments,
%                      all separated by commas. The proper recursive 
%                      definition is:
%
%                      \texttt{addtolist=}\{\meta{lof-list}\}
%
%                      \meta{lof-list} $\rightarrow$ \meta{page number},^^A
%                      \meta{type},\meta{heading},\meta{label}^^A
%                      [,\meta{lof-list}]
%
%
%        \item[survey] Creates a survey of those pages of the document, which
%                      are marked with |\AddToSurvey|. (|\AddToSurvey| is
%                      a simple command with no arguments. It just writes out
%                      labels to the |.aux| file.)
%                      This option may be used when preparing slides to
%                      create a survey of only `finished' pages -- if
%                      pages are build up incrementally.
%
%                      To use this option a special sequence of production
%                      steps must be obeyed. Here is a small example:
%
%\begin{verbatim}
%  --- slides.tex ---
%  \documentclass{article}
%  \usepackage[draft,enable-survey]{pdfpages}
%  \begin{document}
%    ... some text ...
%    \AddToSurvey
%    ... some text ...
%    \includepdf[survey,nup=2x2]{slides-tmp.pdf}
%  \end{document}
%\end{verbatim}
%
%                      This is the outline of a document, called |slides.tex|.
%                      Run it through \pdfLaTeX\ several times until all
%                      cross-references are solved. (\LaTeX\ will produce a
%                      warning, if cross-references are not solved, yet.)
%                      Now copy the file |slides.pdf| to |slides-tmp.pdf|
%                      and rename |draft| (package option of pdfpages) to
%                      |final|. The next and final run through \pdfLaTeX\
%                      will actually insert the desired pages, whereas the
%                      former runs with |draft| did just insert blank pages.
%                      The inserted pages are hyperlink to the orignial
%                      pages.
%
%                      Experienced users would certainly call
%\begingroup
%\setlength\topsep{0pt}
%\begin{verbatim}
%  pdflatex '\PassOptionsToPackage{final}{pdfpages} \input{slides}'
%\end{verbatim}
%\endgroup
%                      instead of exchanging |draft| for |final|.
%
%                      Either `true' or `false' (or no value, which
%                      is equivalent to `true'). \df{survey=false}
%
%
%        \item[survey-nolink] Same as option |survey| except that the
%                      inserted pages do not become hyperlinks.
%                      This option may be used to create an external survey.
%                      To continue the example above (|slides.tex|), it
%                      is now possible to create handouts of the `finished'
%                      slides as an external document.
%
%\begin{verbatim}
%  \documentclass{article}
%  \usepackage{xr}
%  \externaldocument{slides}
%  \usepackage[enable-survey]{pdfpages}
%  \begin{document}
%    \includepdf[survey-nolink, nup=1x2]{slides.pdf}
%  \end{document}
%\end{verbatim}
%
%                      Either `true' or `false' (or no value, which
%                      is equivalent to `true'). \df{survey-nolink=false}
%
%
%        \item[xr-prefix] Adjusts a prefix to the labels |\includepdf| is
%                      looking for. The name of the prefix must be the
%                      same as the name of the optional argument of
%                      |\externaldocument|.
%                      \df{xr-prefix=\{\}}
%
%                      
%      \end{description}
%
%    \end{itemize}
% 
%
%    \begin{figure}
%      \centering\input{pic.tex}
%      \caption{Layout}
%      \label{fig:layout}
%    \end{figure}
%
%
%    \noindent
%    Internally the command |\includepdf| 
%    makes use of the |\includegraphics| command from the |graphicx| 
%    (actually |graphics|) package. Hence it is possible to use
%    all the options of |\includegraphics|, too.
%    Options which are not interpreted by |\includepdf| 
%    are passed directly to |\includegraphics|.
%
%    Especially the `trim' and `clip' options of |\includegraphics|
%    are quite useful, if only parts of a page should be inserted.
%    (Maybe to cut off the header and footer of the inserted pages.)
%    Just use the `trim' and `clip' options as if they were options
%    of |\inlcudepdf|. They will be passed to |\includegraphics|
%    internally.
%    
%
%    \begin{samepage}
%    \bigskip\noindent
%    \DescribeMacro{\includepdfmerge}
%    Inserts pages of several external \PDF\ documents.
%
%    \medskip\noindent
%    |\includepdfmerge[|\meta{key=val}|]{|\meta{file-page-list}|}|
%
%    \begin{quote}
%    \begin{tabular}{@{}l@{\,--~}>{\raggedright}p{.73\linewidth}}
%        \meta{key=val}   & A comma separated list of options
%                   using the \meta{key}=\meta{value} syntax.
%                   \tabularnewline
%        \meta{file-page-list} & \meta{filename}[\textbf{,}^^A
%                   \meta{page spec}]^^A
%                   [\textbf{,}\meta{file-page-list}]\\
%                   A comma separated list of filenames and 
%                   optional \meta{page spec} specifiers.
%                   A \meta{page spec} can be everything the
%                   option |pages| accepts. Leading and trailing
%                   spaces of items in the list is stripped.
%
%    \end{tabular}
%    \end{quote}
%    \end{samepage}
%
%    The |\includepdfmerge| command uses the same options as 
%    |\includepdf| with
%    one exception. The option |pages| has no meaning for 
%    |\includepdfmerge|. Instead the \meta{page spec} specifier
%    is used to specify which pages should be inserted.
%    The \meta{page spec} specifier accepts the same values as 
%    the |pages| option. If no \meta{page spec} specifier is given,
%    only the first page will be inserted.
%
%    \paragraph{Examples:}
%    To create a kind of summary of three \PDF\ documents, it might
%    be nice to insert just the first page of each document and
%    to provide links to the original documents:
%
%    \begin{quote}
%    |\includepdfmerge[nup=1x3, landscape, linktodoc]|\\
%    |                {doc1.pdf, doc2.pdf, doc3.pdf}|
%    \end{quote}
%
%    \noindent
%    But sometimes the title page of a document is not the first page.
%    So it would be more pleasant to insert the title page of
%    each document than the first page. This can be done with
%    the \meta{page spec} specifier. The following example inserts
%    the second page of \textit{doc1.pdf} and the third page of 
%    \textit{doc2.pdf} and \textit{doc3.pdf}:
%
%    \begin{quote}
%    |\includepdfmerge[nup=1x3, landscape, linktodoc]|\\
%    |                {doc1.pdf, 2, doc2.pdf, 3, doc3.pdf, 3}|
%    \end{quote}
%
%    \noindent
%    Here is an example of more complex \meta{page spec}
%    specifiers:
%
%    \begin{quote}
%    |\includepdfmerge[nup=1x3, landscape, linktodoc]|\\
%    |                {doc1.pdf, 1-3,|\\
%    |                 doc2.pdf, 3, 5, 9,|\\
%    |                 doc3.pdf, 3-5, 7}|
%    \end{quote}
%
%
%
%    \bigskip\noindent
%    \DescribeMacro{\includepdfset}
%    If you need the same options for |\includepdf| all the time, it is
%    possible to define global options with |\includepdfset|. The
%    argument of |\includepdfset| is a comma separated list of options,
%    using the \meta{key}=\meta{value} syntax.
%    These options are processed each time |\includepdf| is called.
%    Local options (passed as an optional argument directly to |\includepdf|)
%    are overwriting global options:
%    \begin{quote}
%       |\includepdfset{|\meta{global options}|}|\\
%       |\includepdf[|\meta{local options}|]{pdf-file}|
%    \end{quote}
%    Only options specific to this package can be made global by
%    |\includepdfset|. Options of the graphicx package are not
%    concerned.
%
%    \bigskip\noindent
%    \DescribeMacro{\threadinfodict}
%    When using the option |thread| to create an article thread, it
%    may be useful to create a thread information dictionary, too,
%    which contains informations about the thread, such as its title,
%    author, and creation date. The macro |\threadinfodict| is used
%    to set these informations. It can be redefined and may contain
%    entries of a thread information dictionary in low-level \PDF\
%    commands.
%    (See \cite{PDFRef} for more information.)
%    
%    \smallskip
%    |\renewcommand*{\threadinfodict}|\\\hspace*{\parindent}
%    |  {/Title (My first thread) /Author (That's me!)}|
%    
%    
%
%    \subsection{The Layout}\label{sec:layout}
%    
%    The default layout can be changed by the options |delta|
%    and |offset|. Figure~\ref{fig:layout} shows the
%    meaning of these options.
%    
%    The inserted logical pages are being centered on the
%    sheet of paper by default. To displace them use the |offset|
%     option, which argument should be two dimensions. E.g.~
%    |offset=10mm 14mm| means that the logical pages are displaced
%    by 10\,mm in horizontal direction and by 14\,mm in vertical
%    direction.
%    In `oneside' documents positive values shift the pages to
%    the \emph{right} and to the \emph{top} margin, respectively,
%    whereas in `twoside' documents positive values shift the pages
%    to the \emph{outer} and to the \emph{top} margin, respectively.
%    
%    By default logical pages are being arranged side by side.
%    To put some space between them, use the |delta| option,
%    whose argument should be two dimensions.
%    Figure~\ref{fig:layout} shows the meaning of |delta|.
%    
%    The layout options |delta| and |offset|
%    \textit{always} refer to a sheet of paper in portrait
%    orientation. No matter whether you have set the 
%    |landscape| option to |true|, or not.
%    
%    If you are confused about horizontal\,(|x|)
%    and vertical\,(|y|) directions, just set the option
%    |turn=false|. Now your \PDF\ viewer shows the pages in
%    the \textit{same} orientation as in Figure~\ref{fig:layout}.
%    And the options |delta| and |offset| have
%    the \textit{same} meaning as in Figure~\ref{fig:layout}.
%    Regardless of any other options.
%
%
%    \subsection{Pitfalls}
%
%    \begin{description}
%      \item[pagecolor]
%           When setting the background color with |\pagecolor|
%           (a command from \textit{color.sty}), the first 
%           |\pagecolor| \emph{must} precede |\usepackage{pdfpages}|. 
%           \begin{quote}
%             |\usepackage{color}|\\
%             |\pagecolor{white}|\\
%             |\usepackage{pdfpages}|
%           \end{quote}
%           The color is nonrelevant, it can be changed afterwards
%           by using |\pagecolor| again. Just the order (first
%           |\pagecolor| before |\usepackage{pdfpages}|) is
%           important. -- This is not needed when using \VTeX.
%    \end{description}
%
%
%
%    \section{Required Packages}
%
%    The |pdfpages| package requires the following packages:
%
%    \begin{description}
%      \item[eso-pic]
%            \texttt{CTAN:macros/latex/contrib/eso-pic/}
%      \item[everyshi]
%            \texttt{CTAN:macros/latex/contrib/ms/}
%      \item[graphicx, ifthen, calc]
%            These packages belong to the standard \LaTeX\
%            distribution.
%    \end{description}
%
%    \noindent
%    Furthermore it requires a recent version of:
%    \begin{description}
%      \item[pdftex.def]
%            \texttt{ http://www.tug.org/applications/pdftex/}
%    \end{description}
%
%    \noindent
%    Since pdf\TeX, Version 3.14159-1.00a-pretest-20010806,
%    \PDF\ import has improved a lot. This
%    results in much smaller file sizes, faster processing and the
%    intuitively correct treatment of landscape pages.
%    The latest version of pdf\TeX\ can be found at:
%    \texttt{ftp://ftp.muni.cz/pub/tex/local/cstug/thanh/pdftex}.
%
%
%
%    \section{Acknowledgment}
%    I would like to thank \textsc{Rolf Niepraschk} and
%    \textsc{Heiko Oberdiek} for their useful
%    hints and suggestions. As well as \textsc{Ross Moore},
%    who encouraged me to implement the hypertext features.
%
%
%    \StopEventually{
%    \begin{thebibliography}{1}
%    \bibitem{pdftex}
%      H\`an Th\^e\llap{\raise 0.5ex\hbox{\'{}}} Th\`anh,
%      Sebastian Rahtz, Hans Hagen,
%      \textit{The \pdfTeX\ user manual},
%      http://www.tug.org/applications/pdftex/pdftex-s.pdf
%    \bibitem{PDFRef} \textit{PDF Reference}, Third Edition, Version 1.4,
%      Adobe Systems Incorporated,\\
%      http://partners.adobe.com/asn/tech/pdf/specifications.jsp
%    \end{thebibliography}
%    }
%
%
%    \iffalse
%<*package>
%    \fi
%    \section{Implementation}
%
%    \subsection{Package Options}
%    \begin{macrocode}
\newif\ifAM@pkg@draft \AM@pkg@draftfalse
\newif\ifAM@pkg@survey \AM@pkg@surveyfalse
\DeclareOption{draft}{\AM@pkg@drafttrue}
\DeclareOption{final}{\AM@pkg@draftfalse}
\DeclareOption{enable-survey}{\AM@pkg@surveytrue}
\DeclareOption{disable-survey}{\AM@pkg@surveyfalse}
\ProcessOptions  
%    \end{macrocode}
%    \subsection{Required Packages and Version Checking}
%
%    |\AM@ifdriverlater| checks that the driver loaded is more recent
%    than the given date. See |\@ifpackagelater| from the standard
%    \LaTeX\ kernel.
%    \begin{macrocode}
\def\AM@ifdriverlater{\@ifl@ter{def}}
%    \end{macrocode}
%    Check for using \pdfTeX\ of \VTeX. 
%    -- Note: 
%    If \texttt{graphics.sty} is loaded before this package,
%    \texttt{pdfoutput} may be undefined, even if \pdfLaTeX\
%    is used, because some \texttt{graphic.cfg} undefine
%    \texttt{pdfoutput} (\verb|\let\pdfoutput\@undefined|),
%    if the document contains the line \verb|\pdfoutput=0|.
%    \begin{macrocode}
\def\AM@driver{pdftex}
\begingroup
\@ifundefined{pdfoutput}{%
  \@ifundefined{OpMode}{%
     \PackageError{pdfpages}
            {You are using neither pdfTeX nor VTeX.\MessageBreak
             Package pdfpages does not work with other\MessageBreak
             TeX implementations}
            {Please, change to pdfTeX or VTeX to use this
             package!}%
     \aftergroup\endinput
  }{\gdef\AM@driver{vtex}}%
}{}
\endgroup
%    \end{macrocode}
%    Required Packages.
%    \begin{macrocode}
\RequirePackage{ifthen, graphicx, calc, eso-pic}
\input{pp\AM@driver.def}
\ifx\AM@endinput\relax\endinput\fi
\ifAM@pkg@survey
  \let\AM@setanchor\AM@anchor@special
  \RequirePackage{count1to}%
  \AddToShipoutPicture{\AM@setanchor}%
\fi
%    \end{macrocode}
%    Checking for new versions of \texttt{eso-pic.sty}.
%    \begin{macrocode}
\@ifpackagelater{eso-pic}{2001/07/20}
  {\def\AM@AddToShipoutPicture{\AddToShipoutPicture*}%
   \def\AM@ClearShipoutPicture{\relax}}
  {\def\AM@AddToShipoutPicture{\AddToShipoutPicture}%
   \def\AM@ClearShipoutPicture{\ClearShipoutPicture}}
%    \end{macrocode}
%    \subsection{Booleans}
%    \begin{macrocode}
\newif\ifAM@openright\AM@openrightfalse
\newif\ifAM@frame\AM@framefalse
\newif\ifAM@landscape\AM@landscapefalse
\newif\ifAM@turn\AM@turntrue
\newif\ifAM@thread\AM@threadfalse
\newif\ifAM@link\AM@linkfalse
\newif\ifAM@linktodoc\AM@linktodocfalse
\newif\ifAM@survey\AM@surveyfalse
\newif\ifAM@surveynolink\AM@surveynolinkfalse
\newif\ifAM@output\AM@outputtrue
\newif\ifAM@column\AM@columnfalse
\newif\ifAM@columnstrict\AM@columnstrictfalse
\newif\ifAM@noautoscale\AM@noautoscalefalse
\newif\ifAM@fitpaper\AM@fitpaperfalse
\newif\ifAM@doublepages\AM@doublepagesfalse
\newif\ifAM@doublepagestwist\AM@doublepagestwistfalse
\newif\ifAM@doublepagestwistx\AM@doublepagestwistxfalse
\newif\ifAM@doublepagestmp\AM@doublepagestmpfalse
\newif\ifAM@doublepagestmpi\AM@doublepagestmpifalse
\newif\ifAM@linkfilename\AM@linkfilenamefalse
\newif\ifAM@signature\AM@signaturefalse
\newif\ifAM@sigrotate\AM@sigrotatefalse
\newif\ifAM@newwindow\AM@newwindowtrue
\newif\ifAM@rescale\AM@rescalefalse
\newif\ifAM@rotateoversize\AM@rotateoversizefalse
\newif\ifAM@firstpage\AM@firstpagefalse
\newif\ifAM@reflect\AM@reflectfalse
\newif\ifAM@reflectall\AM@reflectallfalse
%    \end{macrocode}
%    \subsection{Commands}
%    Declare macro names and define default values.
%    \begin{macrocode}
\newcommand*{\AM@pagestemp}{1}
\newcommand*{\AM@pagecommand}{\thispagestyle{empty}}
\newcommand*{\AM@lscape@rot}{0}
\newcommand*{\AM@threadname}{}\newcommand*{\AM@linkname}{}
\newcommand*{\AM@linkname@option}{}
\newcommand*{\AM@linkfit}{fit}\newcommand*{\AM@linktodocfit}{/Fit}
\newcommand*{\threadinfodict}{}
\newcommand*{\AM@toclist}{}\newcommand*{\AM@loflist}{}
\newcommand*{\AM@signature}{}
\newcommand*{\AM@ARBug@hook}{}
\newcommand*{\AM@xrprefix}{}
\newcommand*{\AM@picturecommand}{}\newcommand*{\AM@picturecommandstar}{}


\newsavebox{\AM@pagebox}

%    \end{macrocode}
%    \macro{\AM@setlscape}
%    |\AM@setlscape| is defined in the driver files but may be
%    redefined here, if `pdflscape.sty' is loaded.
%    This package is necessary, if landscape pages are produced
%    \textit{and} `thumbpdf.sty' is used.
%    \begin{macrocode}
\newif\ifAM@thumbpdf
\newif\ifAM@pdflscape
\AtBeginDocument{%
  \@ifpackageloaded{thumbpdf}{\AM@thumbpdftrue}{\AM@thumbpdffalse}%
  \@ifpackageloaded{pdflscape}{\AM@pdflscapetrue}{\AM@pdflscapefalse}%
  \ifAM@thumbpdf
    \ifAM@pdflscape
      \def\AM@setlscape{\PLS@Rotate{90}}%
    \else 
      \PackageWarningNoLine{pdfpages}{%
        You are using `thumbpdf.sty' but not\MessageBreak
        `pdflscape.sty'.\MessageBreak
        Please, insert `pdflscape.sty' in  your document\MessageBreak
        to get a pleasant PDF document with thumbs}%
    \fi
  \fi
}
%    \end{macrocode}
%    \macro{\AM@checkinteger}
%    Check, if |#1| is a positive integer.
%    \begin{macrocode}
\newif\ifAM@integer
\newcommand{\AM@checkinteger}{}
\def\AM@checkinteger#1{%
  \ifcat _\ifnum9<1#1_\else A\fi
    \AM@integertrue
  \else
    \AM@integerfalse
  \fi
}
%    \end{macrocode}
%    \macro{\AM@findfile}
%    Find file and set |\AM@currentdocname|.
%    \begin{macrocode}
\newcommand*{\AM@findfile@i}[2]{%
  \let\AM@currentdocname\relax
  \IfFileExists{#1.#2}{\edef\AM@currentdocname{#1.#2}}{%
     \IfFileExists{#1}{\edef\AM@currentdocname{#1}}{%
       \ifx\Ginput@path\@undefined\else
         \expandafter\@tfor\expandafter\AM@dir\expandafter
                   :\expandafter=\Ginput@path\do{%
           \IfFileExists{\AM@dir#1.#2}{%
             \ifx\AM@currentdocname\relax
               \edef\AM@currentdocname{\AM@dir#1.#2}%
             \fi
           }{%
             \IfFileExists{\AM@dir#1}{%
               \ifx\AM@currentdocname\relax
                 \edef\AM@currentdocname{\AM@dir#1}%
               \fi
             }%
           }%
         }% \@tfor
       \fi
     }%
   }%
}
\newcommand*{\AM@findfile@ii}[1]{%
  \ifx\AM@currentdocname\relax
    \PackageError{pdfpages}{Cannot find file `#1'}{}%
  \fi
}
%    \end{macrocode}
%    \macro{\includepdfset}
%    This command sets global options for |\includepdf|
%    and |\includepdfmerge|.
%    \begin{macrocode}
\newcommand*{\includepdfset}[1]{%
  \AM@split@options{pdfpages}{#1}%
  \edef\AM@temp{{pdfpages}{\the\@temptokena}}%
  \expandafter\setkeys\AM@temp
}
%    \end{macrocode}
%    \macro{\includepdf}
%    This command inserts any pages of an external 
%    \PDF\ document.
%    \begin{macrocode}
\newcommand*{\includepdf}[2][]{%
  \begingroup
  \let\AM@threadname\relax
  \AM@split@options{pdfpages}{#1}%
  \edef\AM@temp{{pdfpages}{\the\@temptokena}}%
  \expandafter\setkeys\AM@temp
%    \end{macrocode}
%    \begin{macrocode}
  \ifthenelse{\boolean{AM@pkg@draft} \and \boolean{AM@survey}}{%
    \let\AM@currentdocname\relax
    \renewcommand\includegraphics[2][]{Survey in draft-mode}%
    \def\AM@pagecount{0}%
  }{%
    \AM@findfile{#2}%
    \if\AM@threadname\relax
      \def\AM@threadname{\AM@currentdocname}%
    \fi
  }%
%    \end{macrocode}
%    Gather all pdfpages' labels form the |aux| file and store
%    the page numbers in |\AM@pagestemp|. If there are no labels
%    reset |\AM@pagestemp|.
%    \begin{macrocode}
  \ifAM@survey
    \def\AM@pagestemp{}%
    \@tempcnta=0
    \def\foo{%
      \@ifundefined{r@\AM@xrprefix pdfpages@page\the\@tempcnta}%
         {\let\foo\relax}
         {\expandafter\ifx\expandafter\\\AM@pagestemp\\
             \edef\AM@pagestemp{%
                \AM@pageref{\AM@xrprefix pdfpages@page\the\@tempcnta}}%
          \else
            \edef\AM@pagestemp{\AM@pagestemp,%
               \AM@pageref{\AM@xrprefix pdfpages@page\the\@tempcnta}}%
          \fi
          \advance\@tempcnta 1\relax
         }%
      \foo
    }%
    \foo
    \expandafter\ifx\expandafter\\\AM@pagestemp\\
      \def\AM@pagestemp{1}%
    \fi
  \fi
%    \end{macrocode}
%    \begin{macrocode}
  \ifAM@output
    \expandafter\AM@readlist\expandafter{\AM@pagestemp}%
    \AM@output{#1}%
  \fi
%    \end{macrocode}
%    \begin{macrocode}
  \AM@CheckAtEnd
  \endgroup
  \AM@ClearShipoutPicture
}
%    \end{macrocode}
%    \macro{\includepdfmerge}
%    This command merges pages of several \PDF\ documents.
%    \begin{macrocode}
\newcommand*{\includepdfmerge}[2][]{%
  \begingroup
  \let\AM@currentdocname\relax
  \AM@readlist{#2}%
  \AM@split@options{pdfpages}{#1}%
  \edef\AM@temp{{pdfpages}{\the\@temptokena}}%
  \expandafter\setkeys\AM@temp
  \AM@output{#1}%
  \AM@CheckAtEnd
  \endgroup
  \AM@ClearShipoutPicture
}
%    \end{macrocode}
%    \macro{\AM@CheckAtEnd}
%    Some simple checks.
%    \begin{macrocode}
\newcommand{\AM@CheckAtEnd}{%
  \ifx\@empty\AM@toclist\else
    \PackageWarning{pdfpages}{%
         There's something wrong with the entries\MessageBreak
         of `addtotoc'. Not all entries were\MessageBreak
         processed. Check `addtotoc'}%
  \fi
  \ifx\@empty\AM@loflist\else
    \PackageWarning{pdfpages}{%
         There's something wrong with the entries\MessageBreak
         of `addtolist'. Not all entries were\MessageBreak
         processed. Check `addtolist'}%
  \fi
}
%    \end{macrocode}
%    \macro{\AM@output}
%    This is the main output routine used by |\includepdf|
%    and |\includepdfmerge|.
%    \begin{macrocode}
\newcommand{\AM@output}[1]{%
%    \end{macrocode}
%    Tune some \LaTeX\ parameters.
%    \begin{macrocode}
  \c@totalnumber=0
  \if@twocolumn\let\AM@twocolumn\relax \onecolumn \fi
%    \end{macrocode}
%    Some macros may already be initialized by |\includepdfset|.
%    So do not reset them here.
%    \begin{macrocode}
  \@ifundefined{AM@xnup}
    {\def\AM@xnup{\@ne}\def\AM@ynup{\@ne}%
     \def\AM@xnupminusi{\z@}\def\AM@ynupminusi{\z@}}{}%
  \@ifundefined{AM@deltax}
    {\def\AM@deltax{-\fboxrule}\def\AM@deltay{-\fboxrule}}{}%
  \@ifundefined{AM@xoffset}
    {\def\AM@xoffset{\z@}\def\AM@yoffset{\z@}}{}%
  \def\AM@xpos{\z@}\def\AM@ypos{\z@}%
%    \end{macrocode}
%    Read in optional parameters.
%    \begin{macrocode}
  \ifAM@pkg@draft \setkeys{Gin}{draft=true}%
  \else \setkeys{Gin}{draft=false}%
  \fi
%    \end{macrocode}
%    Some preparations before starting the output.
%    \begin{macrocode}
  \ifthenelse{\boolean{AM@pkg@draft} \and \boolean{AM@survey}}
    {}{\AM@getpagecount}
%    \end{macrocode}
%    \begin{macrocode}
  \ifthenelse{\boolean{AM@landscape}}
    {\def\AM@lscape@rot{90}%
     \@ifundefined{AM@shortnupsyntax}{}
       {\let\AM@temp\AM@xnup
        \let\AM@xnup\AM@ynup
        \let\AM@ynup\AM@temp}%
    }{}%
  \AM@setphantom
  \ifthenelse{\boolean{AM@openright}}
         {\AM@openright}{}%
  \ifx\AM@signature\@empty\AM@filluppagelist
  \else\AM@prepare@signature\AM@signaturetrue\AM@turnfalse\fi
%    \end{macrocode}
%    \begin{macrocode}
  \@tempcnta=\AM@xnup\relax \advance\@tempcnta\m@ne
  \edef\AM@xnupminusi{\the\@tempcnta}%
  \@tempcnta=\AM@ynup\relax \advance\@tempcnta\m@ne
  \edef\AM@ynupminusi{\the\@tempcnta}%
%    \end{macrocode}
%    \begin{macrocode}
  \ifthenelse{\boolean{AM@column}%
              \and\not\boolean{AM@columnstrict}}
         {\AM@getlastn{\AM@doclist}{\AM@nup}%
          \edef\AM@lastndocs{\AM@lastnitems}%
          \AM@getlastn{\AM@pagelist}{\AM@nup}%
          \edef\AM@lastnpages{\AM@lastnitems}%
          \AM@resort
          \AM@count{\AM@pagelist}%
          \expandafter\ifx\expandafter\\\AM@pagelist\\%
            \edef\AM@pagelist{\AM@resortedpagelist}%
            \edef\AM@doclist{\AM@resorteddoclist}%
          \else
            \edef\AM@pagelist{\AM@pagelist,\AM@resortedpagelist}%
            \edef\AM@doclist{\AM@doclist,\AM@resorteddoclist}%
          \fi}{}%
%    \end{macrocode}
%    \begin{macrocode}
  \ifthenelse{\boolean{AM@frame}}
         {\let\AM@fbox\fbox}
         {\let\AM@fbox\relax
          \setlength{\fboxrule}{\z@}}%
  \ifthenelse{\boolean{AM@reflect}}
         {\let\AM@reflectbox\reflectbox}
         {\let\AM@reflectbox\relax}%
\setbox\AM@pagebox\null
%    \end{macrocode}
%    \begin{macrocode}
  \ifthenelse{\boolean{AM@column}}
         {\def\AM@xnupi{\@ne}%
          \def\AM@ynupi{\z@}}
         {\def\AM@xnupi{\z@}%
          \def\AM@ynupi{\@ne}}%
%    \end{macrocode}
%    \begin{macrocode}
  \AM@firstpagetrue
%    \end{macrocode}
%    \begin{macrocode}
  \setlength{\fboxsep}{\z@}%
%    \end{macrocode}
%    Determine scaling factor:
%    The logical pages are scaled such, that they match on
%    one sheet of paper. To determine the scaling
%    factor all |scale| options given by the user must be 
%    discarded first (|\AM@remove@scale|).
%    But they are \textit{not} discarded when finally being 
%    shipped out.
%    \begin{macrocode}
  \@ifundefined{AM@pagetemplate}
      {\AM@readfirst{\AM@pagelist}%
       \edef\AM@page{\the\toks@}}
      {\edef\AM@page{\AM@pagetemplate}}%
  \AM@readfirst{\AM@doclist}%
  \edef\AM@docname{\the\toks@}%
  \newpage
  \AM@isphantom
  \ifAM@noautoscale
    \def\AM@globalscale{1}%
  \else
    \AM@split@options{Gin@noscale}{#1}%
    \let\AM@filelist@save\@filelist
    \setbox\@tempboxa=\hbox{%
      \expandafter\includegraphics\expandafter[\the\@temptokena,
         page=\AM@page, angle=\AM@lscape@rot]{\AM@docname}}%
%    \end{macrocode}
%    Adjust the paper size.
%    \begin{macrocode}
    \ifthenelse{\boolean{AM@fitpaper}}
      {\setlength{\AM@pagewidth}{\the\wd\@tempboxa}%
       \setlength{\AM@pageheight}{\the\ht\@tempboxa}%
       \setlength{\paperwidth}{\the\wd\@tempboxa}%
       \setlength{\paperheight}{\the\ht\@tempboxa}%
       \AM@fitpaper@special
       \AM@setpagedimen
       \@ifundefined{stockwidth}{}{%
         \setlength{\stockwidth}{\AM@pagewidth}%
         \setlength{\stockheight}{\AM@pageheight}%
         \setlength{\trimtop}{0pt}%
         \setlength{\trimedge}{0pt}}%
      }{}%
%    \end{macrocode}
%    \begin{macrocode}
    \ifdim\AM@pagewidth=\z@
      \AM@pagewidth=210mm
      \PackageWarningNoLine{pdfpages}{%
        Erroneous page width of 0.0pt is corrected}%
    \fi
    \ifdim\AM@pageheight=\z@
      \AM@pageheight=297mm
      \PackageWarningNoLine{pdfpages}{%
        Erroneous page height of 0.0pt is corrected}%
    \fi
%    \end{macrocode}
%    |eso-pic| needs |\paperwidth| and |\paperheight|, which may
%    not be defined, e.g. with |minimal.cls|.
%    \begin{macrocode}
    \ifdim\paperwidth=\z@
      \let\paperwidth\AM@pagewidth
    \fi
    \ifdim\paperheight=\z@
      \let\paperheight\AM@pageheight
    \fi
%    \end{macrocode}
%    Calculate required scaling in horizontal direction.
%    \begin{macrocode}
    \def\AM@xscale{%
      (\paperwidth - \tw@\fboxrule*\AM@xnup 
       - \AM@deltax * \AM@xnupminusi) /
      (\AM@xnup * \real{\strip@pt\wd\@tempboxa})
    }%
    \setlength{\@tempdima}{\AM@xscale}%
    \edef\AM@xscale{\strip@pt\@tempdima}%
%    \end{macrocode}
%    Calculate required scaling in vertical direction.
%    \begin{macrocode}
    \setlength{\@tempdimb}{\ht\@tempboxa + \dp\@tempboxa}%
    \def\AM@yscale{
      (\paperheight - \tw@\fboxrule*\AM@ynup 
       - \AM@deltay *\AM@ynupminusi) /
      (\AM@ynup * \real{\strip@pt\@tempdimb})
    }%
    \setlength{\@tempdima}{\AM@yscale}%
    \edef\AM@yscale{\strip@pt\@tempdima}%
%    \end{macrocode}
%    The lower value of |\AM@xscale| and |\AM@yscale| is used
%    as the overall scaling factor |\AM@globalscale|.
%    \begin{macrocode}
    \@tempdima=\AM@xscale\p@
    \@tempdimb=\AM@yscale\p@
    \ifdim\@tempdima<\@tempdimb
      \let\AM@globalscale\AM@xscale
    \else
      \let\AM@globalscale\AM@yscale
    \fi
  \fi
%    \end{macrocode}
%    Determine horizontal and vertical margins.
%    |\AM@xoffset| and |\AM@yoffset| are \textit{not} 
%    taken into account for this calculation.
%    \begin{macrocode}
  \let\AM@filelist@save\@filelist
  \AM@split@options{Gin}{#1}%
  \setbox\@tempboxa=\hbox{%
    \expandafter\includegraphics\expandafter[\the\@temptokena,
                     page=\AM@page, scale=\AM@globalscale,
                     angle=\AM@lscape@rot]{\AM@docname}}%
  \let\@filelist\AM@filelist@save
  \edef\AM@templatewidth{\the\wd\@tempboxa}%
  \setlength{\@tempdima}{\the\ht\@tempboxa + \the\dp\@tempboxa}%
  \edef\AM@templateheight{\the\@tempdima}%
  \setlength{\@tempdimb}{\ht\@tempboxa + \dp\@tempboxa}%
  \def\AM@xmargin{%
    (\paperwidth - (\wd\@tempboxa+\tw@\fboxrule)*\AM@xnup
     - \AM@deltax * \AM@xnupminusi) * \real{.5}%
  }%
  \def\AM@ymargin{%
    (\paperheight - (\@tempdimb+\tw@\fboxrule)*\AM@ynup
     - \AM@deltay * \AM@ynupminusi) * \real{.5}%
  }%
  \setlength{\@tempdima}{\AM@xmargin}%
  \edef\AM@xmargin{\the\@tempdima}%
  \setlength{\@tempdima}{\AM@ymargin}%
  \edef\AM@ymargin{\the\@tempdima}%
%    \end{macrocode}
%    \begin{macrocode}
  \ifthenelse{\boolean{AM@landscape}}
       {\edef\AM@temp{\AM@xnup}%
        \edef\AM@xnup{\AM@ynup}%
        \edef\AM@ynup{\AM@temp}}
       {}%
  \ifAM@signature
    \ifAM@landscape\AM@sigrotatefalse\else\AM@sigrotatetrue\fi
  \fi
%    \end{macrocode}
%    This loop arranges one or more \PDF\ pages onto each sheet
%    of paper.
%    \begin{macrocode}
  \setboolean{AM@endoflist}{false}%
  \whiledo{\not\boolean{AM@endoflist}}{%
    \AM@getfirst{\AM@pagelist}%
      \edef\AM@page{\the\toks@}%
      \AM@isphantom
      \@tempcnta=\AM@page\relax
      \edef\AM@linktodoc@page{\the\@tempcnta}%
      \advance\@tempcnta\m@ne
      \edef\AM@linktodoc@page@m@ne{\the\@tempcnta}%
    \AM@getfirst{\AM@doclist}%
      \edef\AM@docname{\the\toks@}%
      \ifAM@linkfilename
      \else
        \let\AM@linkfilename\AM@docname
      \fi
      \ifx\@empty\AM@linkname@option \edef\AM@linkname{\the\toks@}%
      \else \edef\AM@linkname{\AM@linkname@option} \fi
%    \end{macrocode}
%    Each logical page has an element number of
%    |(\AM@xnupi,\AM@ynupi)|, where |(1,1)| indicates the upper
%    left position.
%    \begin{macrocode}
    \ifthenelse{\boolean{AM@column}}
      {\@tempcnta=\AM@ynupi\relax
       \@tempcntb=\AM@ynup\relax
       \advance\@tempcnta\@ne
       \ifnum\@tempcnta>\@tempcntb
         \@tempcnta=\@ne
         \@tempcntb=\AM@xnupi\relax
         \advance\@tempcntb\@ne
         \edef\AM@xnupi{\the\@tempcntb}%
       \fi
       \edef\AM@ynupi{\the\@tempcnta}%
       \@tempcnta=\AM@xnupi\relax
       \@tempcntb=\AM@xnup\relax
       \ifnum\@tempcnta>\@tempcntb
         \def\AM@xnupi{\@ne}%
       \fi
      }
      {\@tempcnta=\AM@xnupi\relax
       \@tempcntb=\AM@xnup\relax
       \advance\@tempcnta\@ne
       \ifnum\@tempcnta>\@tempcntb
         \@tempcnta=\@ne
         \@tempcntb=\AM@ynupi\relax
         \advance\@tempcntb\@ne
         \edef\AM@ynupi{\the\@tempcntb}%
       \fi
       \edef\AM@xnupi{\the\@tempcnta}%
       \@tempcnta=\AM@ynupi\relax
       \@tempcntb=\AM@ynup\relax
       \ifnum\@tempcnta>\@tempcntb
         \def\AM@ynupi{\@ne}%
       \fi
      }%
%    \end{macrocode}
%    Load next page and verify if it has the same page size as the
%    page template. If not, adjust the scale |\AM@localscale| and
%    the local offset |\AM@localxoff| and |\AM@localyoff|.
%    \begin{macrocode}
    \setbox\@tempboxa=\hbox{%
      \expandafter\includegraphics\expandafter[\the\@temptokena,
                       page=\AM@page, scale=\AM@globalscale,
                       angle=\AM@lscape@rot]{\AM@docname}}%
    \edef\AM@localwd{\the\wd\@tempboxa}%
    \setlength{\@tempdima}{\the\ht\@tempboxa + \the\dp\@tempboxa}%
    \edef\AM@localht{\the\@tempdima}%
    \AM@rescalefalse
    \ifdim\AM@localwd=\AM@templatewidth \else \AM@rescaletrue \fi
    \ifdim\AM@localht=\AM@templateheight \else \AM@rescaletrue \fi
    \def\AM@localxoff{\z@}%
    \def\AM@localyoff{\z@}%
    \def\AM@rotateoversize{0}%
    \def\AM@localscale{\p@}%
    \ifAM@rescale
      \ifthenelse{\lengthtest{\AM@localwd<\AM@templatewidth} \and
                  \lengthtest{\AM@localht<\AM@templateheight}}{%
%    \end{macrocode}
%    Smaller pages are \emph{not} scaled up, just their local offset
%    is adjusted.
%    \begin{macrocode}
        \setlength{\@tempdima}{(\AM@templatewidth - \AM@localwd) 
             * \real{.5}}%
        \edef\AM@localxoff{\the\@tempdima}%
        \setlength{\@tempdima}{(\AM@templateheight - \AM@localht)
             * \real{.5}}%
        \edef\AM@localyoff{\the\@tempdima}%
      }{%
%    \end{macrocode}
%    Larger pages are scaled down and their local offset is adjusted.
%    \begin{macrocode}
        \ifAM@rotateoversize
          \def\AM@rotateoversize{90}%
          \let\AM@filelist@save\@filelist
          \setbox\@tempboxa=\hbox{%
            \expandafter\includegraphics\expandafter
                [\the\@temptokena, page=\AM@page,
                 scale=\AM@globalscale,
                 angle=\AM@lscape@rot, angle=90]{\AM@docname}}%
          \let\@filelist\AM@filelist@save
          \edef\AM@localwd{\the\wd\@tempboxa}%
          \setlength{\@tempdima}{\the\ht\@tempboxa + \the\dp\@tempboxa}%
          \edef\AM@localht{\the\@tempdima}%
        \fi
        \setlength{\@tempdima}
                  {\p@ * \ratio{\AM@templatewidth}{\AM@localwd}}%
        \edef\AM@localxscale{\the\@tempdima}%
        \setlength{\@tempdima}
                  {\p@ * \ratio{\AM@templateheight}{\AM@localht}}%
        \edef\AM@localyscale{\the\@tempdima}%
        \ifdim\AM@localxscale<\AM@localyscale
          \let\AM@localscale\AM@localxscale
          \setlength{\@tempdima}{\AM@localxscale}%
          \setlength{\@tempdima}{(\AM@templateheight -
            \AM@localht * \real{\strip@pt\@tempdima}) * \real{.5}}%
          \edef\AM@localyoff{\the\@tempdima}%
        \else
          \let\AM@localscale\AM@localyscale
          \setlength{\@tempdima}{\AM@localyscale}%
          \setlength{\@tempdima}{(\AM@templatewidth -
             \AM@localwd * \real{\strip@pt\@tempdima}) * \real{.5}}%
          \edef\AM@localxoff{\the\@tempdima}%
        \fi
      }%
    \fi
    \setlength{\@tempdima}{\AM@localscale}%
    \edef\AM@localscale{\strip@pt\@tempdima}%
%    \end{macrocode}
%    \begin{macrocode}
    \let\AM@filelist@save\@filelist
    \AM@split@options{Gin}{#1}%
    \setbox\@tempboxa=\hbox{%
      \expandafter\includegraphics\expandafter[\the\@temptokena,
                       page=\AM@page, scale=\AM@globalscale,
                       angle=\AM@lscape@rot]{\AM@docname}}%
    \let\@filelist\AM@filelist@save
    \setlength{\@tempdimc}{\ht\@tempboxa + \dp\@tempboxa}%
%    \end{macrocode}
%    Determine the position (coordinates) of the logical pages.
%    These are |\AM@xpos| and |\AM@ypos|.
%    \begin{macrocode}
    \def\AM@add{+}%
    \if@twoside\ifodd\c@page\else\def\AM@add{-}\fi\fi
    \setlength{\@tempdimb}{\ht\@tempboxa + \dp\@tempboxa}%
    \ifthenelse{\boolean{AM@landscape}}
      {\def\AM@xpos{%
         \AM@xmargin \AM@add\AM@xoffset + \AM@localxoff +
         (\AM@templatewidth + \AM@deltax + \tw@\fboxrule) *
         (\AM@ynupi - 1)
       }%
       \def\AM@ypos{%
         \AM@ymargin + \AM@yoffset + \AM@localyoff +
         (\AM@templateheight + \AM@deltay + \tw@\fboxrule) *
         (\AM@xnupi - 1)
       }%
      }
      {\def\AM@xpos{%
         \AM@xmargin \AM@add\AM@xoffset + \AM@localxoff +
         (\AM@templatewidth + \AM@deltax + \tw@\fboxrule) *
         (\AM@xnupi - 1)
       }%
       \def\AM@ypos{%
         \AM@ymargin + \AM@yoffset + \AM@localyoff +
         (\AM@templateheight + \AM@deltay + \tw@\fboxrule) *
         (\AM@ynup-\AM@ynupi)
       }%
      }%
    \setlength{\@tempdima}{\AM@xpos}%
    \edef\AM@xpos{\strip@pt\@tempdima}%
    \setlength{\@tempdima}{\AM@ypos}%
    \edef\AM@ypos{\strip@pt\@tempdima}%
    \setlength{\fboxsep}{\z@}%
%    \end{macrocode}
%    Calculate |fitr| coordinates, if |linkfit=region|.
%    \begin{macrocode}
    \def\AM@region{region}%
    \ifx\AM@linkfit\AM@region
      \setlength{\@tempdima}{\the\ht\@tempboxa + \the\dp\@tempboxa}%
      \edef\AM@linkfit{fitr width\the\wd\@tempboxa\space
                            height0pt depth\the\@tempdima}%
    \fi
%    \end{macrocode}
%    Ship out page.
%    \begin{macrocode}
    \ifAM@phantompage
      \def\AM@shippage{}%
    \else
      \AM@split@options{Gin}{#1}%
      \edef\AM@shippage{%
        \noexpand\put(\AM@xpos,\AM@ypos){%
        \noexpand\raisebox{\dp\@tempboxa}{%
%    /end{macrocode}
%    Raise the target of a link to the top of the included page.
%    /begin{macrocode}
        \noexpand\raise \ht\@tempboxa \hbox{\AM@hyper@begin@i}%
%    \end{macrocode}
%    \begin{macrocode}
        \AM@hyper@begin@ii\noexpand\AM@fbox{%
          \noexpand\AM@ARBug@hook
          \noexpand\AM@reflectbox{%
          \noexpand\includegraphics[\the\@temptokena,
                    page=\AM@page, scale=\AM@globalscale,
                    scale=\AM@localscale,
                    \ifAM@sigrotate angle=180,\fi
                    \ifAM@doublepagestwist\ifAM@doublepagestmp
                      angle=180,\fi\fi
                    angle=\AM@rotateoversize,
                    angle=\AM@lscape@rot]{\AM@docname}}}%
        \AM@hyper@end}}%
      }%
    \fi
    \ifAM@doublepagestwist
      \ifAM@doublepagestmpi
        \ifAM@doublepagestwistx\AM@doublepagestmpifalse\fi
        \ifAM@doublepagestmp\AM@doublepagestmpfalse
        \else\AM@doublepagestmptrue\fi
      \else\AM@doublepagestmpitrue\fi
    \fi
    \AM@AddToShipoutPicture{\setlength{\unitlength}{\p@}%
      \global\let\AM@filelist@save\@filelist}%
%    \end{macrocode}
%    |\AM@pagebox| is only use for option |reflect|, which was added
%    lately. Probabley it would be better to use |\AM@pagebox| in
%    all cases?
%    \begin{macrocode}
    \ifAM@reflectall
      \begin{lrbox}{\AM@pagebox}
        \global\let\AM@filelist@save\@filelist
        \usebox{\AM@pagebox}\AM@shippage
        \global\let\@filelist\AM@filelist@save
      \end{lrbox}
    \else
      \expandafter\AM@AddToShipoutPicture\expandafter{%
        \AM@shippage
        \global\let\@filelist\AM@filelist@save
      }%
    \fi
    \AM@toclof{\AM@page}%
    \ifnum\AM@xnupi=\AM@xnup\relax
      \ifnum\AM@ynupi=\AM@ynup\relax
        \begingroup\AM@pagecommand\endgroup
        \hskip\z@
        \ifthenelse{\boolean{AM@turn}}
          {\ifthenelse{\boolean{AM@landscape}}
             {\AM@setlscape}{}}
          {}%
        \AM@AddToShipoutPicture{\begingroup\AM@picturecommand\endgroup}%
        \ifAM@firstpage
          \AM@AddToShipoutPicture{%
            \begingroup\AM@picturecommandstar\endgroup}%
          \AM@firstpagefalse
        \fi
        \ifAM@reflectall
          \AM@AddToShipoutPicture{%
            \hskip\AM@pagewidth
            \reflectbox{\usebox\AM@pagebox}%
            \global\let\@filelist\AM@filelist@save
          }%
          \AM@ClearShipoutPicture
        \fi
        \newpage
        \ifAM@reflectall \setbox\AM@pagebox\null \fi
        \ifAM@pdflscape\PLS@Rotate{0}\fi
        \AM@ClearShipoutPicture
%    \end{macrocode}
%    When creating signatures, every second page must be rotated
%    by $180^{\circ}$.
%    \begin{macrocode}
        \ifAM@signature
          \ifAM@sigrotate\AM@sigrotatefalse\else\AM@sigrotatetrue\fi
        \fi
      \fi
    \fi
%    \end{macrocode}
%    \begin{macrocode}
  }% whiledo
  \ifx\AM@twocolumn\relax\twocolumn\fi
}% AM@output
%    \end{macrocode}
%    \macro{\AM@readlist}
%    \macro{\AM@readlisti}
%    \macro{\AM@checkrange}
%    \macro{\AM@checklast}
%    \macro{\AM@checkpagenumber}
%    \macro{\AM@setnewdocname}
%    \macro{\AM@append}
%    These macros parse a comma separated list, which contains
%    page numbers, page ranges, and/or document names. The
%    results are stored in two macros: |\AM@pagelist| which
%    contains only page numbers (page ranges are split into
%    several page numbers) and |\AM@doclist| which contains
%    the document names; one name for each page number in
%    |\AM@pagelist|.
%    \begin{macrocode}
\newif\ifAM@defaultone
\newcommand*{\AM@readlist}[1]{%
  \AM@defaultonefalse
  \def\AM@pagelist{}%
  \def\AM@doclist{}%
  \AM@readlisti#1,\END,
  \ifAM@defaultone\AM@append{1}\fi
  \edef\AM@doclist{\expandafter\@gobble\AM@doclist}%
  \edef\AM@pagelist{\expandafter\@gobble\AM@pagelist}%
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@readlisti}{}
\def\AM@readlisti#1,{%
  \ifx\AM@currentdocname\relax
  \else
    \AM@getpagecount
  \fi
  \def\AM@temp{#1}%
  \ifx\END#1
  \else
    \AM@checkrange#1-\END
    \expandafter\AM@readlisti
  \fi
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@checkrange}{}
\def\AM@checkrange#1-#2\END{%
  \edef\AM@tempi{\AM@trim@space{#1}}%
  \ifx\\#2\\%
    \AM@checkinteger{\AM@tempi}%
    \ifAM@integer
      \AM@checkpagenumber{\AM@tempi}%
      \AM@append{\AM@tempi}%
    \else
      \expandafter\ifx\expandafter\\\AM@tempi\\\AM@append{}%
      \else\AM@setnewdocname{\AM@tempi}\fi
    \fi
  \else
    \expandafter\ifx\expandafter\\\AM@tempi\\%
      \@tempcnta=1\relax
      \AM@checklast#2\END
    \else
      \def\AM@cmp{last}%
      \ifx\AM@cmp\AM@tempi
        \@tempcnta=\AM@pagecount\relax
        \AM@checklast#2\END
      \else
        \AM@checkinteger{\AM@tempi}%
        \ifAM@integer
          \@tempcnta=\AM@tempi\relax
          \AM@checkpagenumber{\the\@tempcnta}%
          \AM@checklast#2\END
        \else
          \AM@setnewdocname{\AM@temp}%
        \fi
      \fi
    \fi
  \fi
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@checklast}{}
\def\AM@checklast#1-\END{%
  \edef\AM@tempii{\AM@trim@space{#1}}%
  \expandafter\ifx\expandafter\\\AM@tempii\\
    \@tempcntb=\AM@pagecount\relax
    \advance\@tempcntb\@ne
    \whiledo{\@tempcnta<\@tempcntb}{%
      \AM@append{\the\@tempcnta}%
      \advance\@tempcnta\@ne
    }%
  \else
    \def\AM@cmp{last}%
    \ifx\AM@cmp\AM@tempii
      \let\AM@tempii\AM@pagecount
    \fi
    \AM@checkinteger{\AM@tempii}%
    \ifAM@integer
      \@tempcntb=\AM@tempii\relax
      \AM@checkpagenumber{\the\@tempcntb}%
      \ifnum\@tempcnta<\@tempcntb \def\AM@rel{<}\def\AM@inc{\@ne}%
      \else \def\AM@rel{>}\def\AM@inc{\m@ne}\fi
      \advance\@tempcntb\AM@inc
      \whiledo{\@tempcnta\AM@rel\@tempcntb}{%
        \AM@append{\the\@tempcnta}%
        \advance\@tempcnta\AM@inc
      }%
    \else
      \AM@setnewdocname{\AM@temp}%
    \fi
  \fi
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand*{\AM@checkpagenumber}[1]{%
  \ifnum#1>\AM@pagecount\relax
    \ifthenelse{\boolean{AM@pkg@draft} \and \boolean{AM@survey}}{%
    }{%
      \PackageError{pdfpages}
        {page number #1 of `\AM@currentdocname' does not exist}
        {You have set a wrong page number in the `pages' option.
         Document \MessageBreak `\AM@currentdocname' does not
         have #1 pages.}%
    }%
  \fi
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand*{\AM@setnewdocname}[1]{%
  \ifAM@defaultone
    \AM@append{1}%
  \fi
  \edef\AM@temp{\AM@trim@space{#1}}%
  \AM@findfile{\AM@temp}%
  \AM@defaultonetrue
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand*{\AM@append}[1]{%
  \edef\AM@doclist{\AM@doclist,\AM@currentdocname}%
  \edef\AM@pagelist{\AM@pagelist,#1}%
  \ifAM@doublepages
    \edef\AM@doclist{\AM@doclist,\AM@currentdocname}%
    \edef\AM@pagelist{\AM@pagelist,#1}%
  \fi
  \AM@defaultonefalse
}
%    \end{macrocode}
%    \macro{\AM@getfirst}
%    \macro{\AM@getfirsti}
%    \macro{\AM@getfirstii}
%    Parameter |#1| must be a macro containing a  csv-list. 
%    |\AM@getfirst| removes the first item of this list 
%    \textit{and} stores it in  |\toks@|.
%    \begin{macrocode}
\newif\ifAM@endoflist\AM@endoflistfalse
\newcommand{\AM@getfirst}{}
\def\AM@getfirst#1{\expandafter\AM@getfirsti#1,\END#1\END}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@getfirsti}{}
\def\AM@getfirsti#1,#2\END#3\END{%
  \edef#3{#2}%
  \ifx\\#2\\%
    \setboolean{AM@endoflist}{true}%
    \def#3{}%
  \else
    \edef#3{\AM@getfirstii#2\END}%
  \fi
  \toks@{#1}%
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@getfirstii}{}
\def\AM@getfirstii#1,\END{#1}
%    \end{macrocode}
%    \macro{\AM@readfirst}
%    Read first item of a list and store it in |\toks@|.
%    (Do not remove it.)
%    \begin{macrocode}
\newcommand{\AM@readfirst}{}
\newcommand{\AM@readfirsti}{}
\def\AM@readfirst#1{\expandafter\AM@readfirsti#1,\END}
\def\AM@readfirsti#1,#2\END{\toks@{#1}}
%    \end{macrocode}
%    \macro{\AM@getlast}
%    \macro{\AM@getlasti}
%    \macro{\AM@getlastn}
%    These macros are similar to |\AM@getfirst|. |\AM@getlast|
%    stores the last item in |\AM@lastitem| and removes it
%    from the list. |\AM@getlastn| does the same with the
%    last |n| items which are stored in |\AM@lastnitems|.
%    \begin{macrocode}
\newcommand{\AM@getlast}{}
\def\AM@getlast#1{%
  \let\AM@temp\relax
  \expandafter\AM@getlasti#1,\END
  \@ifundefined{AM@temp}{\def#1{}}{\edef#1{\AM@temp}}%
}
%    \end{macrocode}
%    \begin{macrocode}
\def\AM@ReturnAfterFi#1\fi{\fi#1}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@getlasti}{}
\def\AM@getlasti#1,#2\END{%
  \ifx\\#2\\%
    \def\AM@lastitem{#1}%
  \else
    \@ifundefined{AM@temp}
      {\edef\AM@temp{#1}}
      {\edef\AM@temp{\AM@temp,#1}}%
    \AM@ReturnAfterFi{\AM@getlasti#2\END}%
  \fi
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@getlastn}{}
\def\AM@getlastn#1#2{%
  \let\AM@templist\relax
  \@tempcnta=\z@
  \loop
  \ifnum\@tempcnta<#2
    \AM@getlast{#1}%
    \@ifundefined{AM@templist}
      {\edef\AM@templist{\AM@lastitem}}
      {\edef\AM@templist{\AM@lastitem,\AM@templist}}%
    \advance\@tempcnta\@ne
  \repeat
  \edef\AM@lastnitems{\AM@templist}%
}
%    \end{macrocode}
%    \macro{\AM@count}
%    \macro{\AM@counti}
%    Parameter |#1| must be a macro containing a csv-list.
%    |\AM@count| counts the items of this list, but it does
%    not count the last \textit{empty} items of this list.
%    The number of items is stored in |\@tempcnta|.
%    \begin{macrocode}
\newif\ifAM@again\AM@againtrue
\newcommand{\AM@count}{}
\def\AM@count#1{%
  \edef\AM@templist{#1}%
  \loop
    \AM@getlast{\AM@templist}%
    \expandafter\ifx\expandafter\\\AM@lastitem\\%
    \else
      \AM@againfalse
      \expandafter\ifx\expandafter\\\AM@templist\\%
        \edef\AM@templist{\AM@lastitem}%
      \else
        \edef\AM@templist{\AM@templist,\AM@lastitem}%
      \fi
      \@tempcnta=\z@
      \expandafter\AM@counti\AM@templist,\END,
    \fi
  \ifAM@again
  \repeat
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@counti}{}
\def\AM@counti#1,{%
  \ifx\END#1
  \else
    \advance\@tempcnta\@ne
    \expandafter\AM@counti
  \fi
}
%    \end{macrocode}
%    \macro{\AM@resort}
%    To allow a more pleasant output in |column| mode, the
%    logical pages get resorted if they do not fill the
%    whole sheet of paper.
%    |\AM@lastnpages| must contain the pages and
%    |\AM@lastndocs| the corresponding documents which
%    should get resorted.
%
%    E.g.: After resorting a page that contains only 5 of 9
%    logical pages, it looks like (b) instead of (a).
%
%    \smallskip\par
%    \begin{minipage}{110pt}
%      \centering
%      \begin{tabular}{|c|c|c|}\hline
%      1 & 4 & \phantom{6}\\\hline
%      2 & 5 &\\\hline
%      3 &&\\\hline
%      \end{tabular}\smallskip\par
%      (a)~|columnstrict=false|
%    \end{minipage}
%    \hskip15pt
%    \begin{minipage}{110pt}
%      \centering
%      \begin{tabular}{|c|c|c|}\hline
%      1 & 3 & 5\\\hline
%      2 & 4 & \\\hline
%      &&\\\hline
%      \end{tabular}\smallskip\par
%      (b)~|columnstrict=true|
%    \end{minipage}
%    \smallskip
%    \begin{macrocode}
\newif\ifAM@resort@end\AM@resort@endfalse
\newcommand{\AM@resort}{}
\def\AM@resort{%
  \def\AM@resortedpagelist{}%
  \def\AM@resorteddoclist{}%
  \def\AM@xnupi{\@ne}%
  \def\AM@ynupi{\@ne}%
%    \end{macrocode}
%    For the following algorithm a `last page' is
%    defined, which has the position (|xnuplast| , |ynuplast|).
%    It is marked with $\times$ in the figure below.
%    \smallskip\par
%    \begin{minipage}{110pt}
%      \centering
%      \begin{tabular}{|c|c|c|}\hline
%      1 & 3 & 5\\\hline
%      2 & 4 & $\times$\\\hline
%      &&\\\hline
%      \end{tabular}\smallskip\par
%    \end{minipage}
%    \begin{macrocode}
  \AM@count{\AM@lastnpages}%
  \def\AM@xnuplast{%
    \the\@tempcnta - (\the\@tempcnta / \AM@xnup * \AM@xnup) + 1}%
  \def\AM@ynuplast{1 + (\the\@tempcnta / \AM@xnup)}%
  \setlength{\@tempdima}{\p@*(\AM@xnuplast)}%
  \edef\AM@xnuplast{\strip@pt\@tempdima}%
  \setlength{\@tempdima}{\p@*(\AM@ynuplast)}%
  \edef\AM@ynuplast{\strip@pt\@tempdima}%
%    \end{macrocode}
%    \begin{macrocode}
  \whiledo{\not\boolean{AM@resort@end}}{%
    \@tempcnta=\AM@ynupi\relax
    \@tempcntb=\AM@ynuplast\relax
    \ifnum\@tempcnta=\@tempcntb
        \@tempcnta=\AM@xnupi\relax
        \@tempcntb=\AM@xnuplast\relax
        \ifnum\@tempcnta<\@tempcntb
          \AM@getfirst{\AM@lastndocs}%
          \edef\AM@firstdocitem{\the\toks@}%
          \AM@getfirst{\AM@lastnpages}%
          \edef\AM@resortedpagelist{\AM@resortedpagelist,\the\toks@}%
          \edef\AM@resorteddoclist{%
            \AM@resorteddoclist,\AM@firstdocitem}%
        \else
          \edef\AM@resortedpagelist{\AM@resortedpagelist,}%
          \edef\AM@resorteddoclist{\AM@resorteddoclist,\AM@phantomdoc}%
        \fi
    \else
      \ifnum\@tempcnta<\@tempcntb
        \AM@getfirst{\AM@lastndocs}%
        \edef\AM@firstdocitem{\the\toks@}%
        \AM@getfirst{\AM@lastnpages}%
        \edef\AM@resortedpagelist{\AM@resortedpagelist,\the\toks@}%
        \edef\AM@resorteddoclist{\AM@resorteddoclist,\AM@firstdocitem}%
      \else
        \edef\AM@resortedpagelist{\AM@resortedpagelist,}%
        \edef\AM@resorteddoclist{\AM@resorteddoclist,\AM@phantomdoc}%
      \fi
    \fi
    \@tempcnta=\AM@ynupi\relax
    \advance\@tempcnta\@ne
    \edef\AM@ynupi{\the\@tempcnta}%
    \@tempcntb=\AM@ynup\relax
    \ifnum\@tempcnta>\@tempcntb
      \@tempcntb=\AM@xnupi\relax
      \advance\@tempcntb\@ne
      \edef\AM@xnupi{\the\@tempcntb}%
      \def\AM@ynupi{\@ne}%
      \@tempcnta=\AM@xnup\relax
      \ifnum\@tempcntb>\@tempcnta
        \setboolean{AM@resort@end}{true}%
      \fi
    \fi
  }%
  \edef\AM@resortedpagelist{\expandafter\@gobble\AM@resortedpagelist}%
  \edef\AM@resorteddoclist{\expandafter\@gobble\AM@resorteddoclist}%
}
%    \end{macrocode}
%    \macro{\AM@remove@scale}
%    \macro{\AM@remove@scalei}
%    \macro{\AM@remove@scaleii}
%    Remove the \texttt{scale} item from the options list (|#1|)
%    and then save it in |\AM@options|.
%    \begin{macrocode}
\newif\ifAM@scale
\newcommand{\AM@remove@scale}{}
\def\AM@remove@scale#1{%
  \def\AM@options{}%
  \AM@remove@scalei#1,\END,
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@remove@scalei}{}
\def\AM@remove@scalei#1,{%
  \ifx\END#1
  \else
    \AM@scalefalse
    \AM@remove@scaleii#1=\END
    \ifAM@scale
    \else
      \ifx\empty\AM@options
        \edef\AM@options{#1}%
      \else
        \toks@\expandafter{\AM@options,#1}%
        \edef\AM@options{\the\toks@}%
      \fi
    \fi
    \expandafter\AM@remove@scalei
  \fi
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@remove@scaleii}{}
\def\AM@remove@scaleii#1=#2\END{%
  \ifx\\#2\\%
  \else
    \def\AM@temp{#1}%
    \edef\AM@temp{\AM@trim@space{\AM@temp}}%
    \ifthenelse{\equal{scale}{\AM@temp}}{\AM@scaletrue}{}%
  \fi
}
%    \end{macrocode}
%    \macro{\AM@split@options}
%    \macro{\AM@split@optionsi}
%    \macro{\AM@split@oprionsii}
%    Extracts options from the options list (|#2|) depending
%    on the namespace (|#1|). Possible values for |#1| are:
%    |pdfpages| (options concerning pdfpages), |Gin| (options
%    concerning graphicx) and |Gin@noscale| (options concerning
%    graphicx, omitting the |scale| options). The extracted options
%    are stored in |@temptokena|.
%    \begin{macrocode}
\newif\ifAM@pdfpages@options
\newcommand{\AM@split@options}{}
\def\AM@split@options#1#2{%
  \def\AM@param{#1}%
  \@temptokena{}%
  \AM@split@optionsi#2,\END,
}
%    \end{macrocode}
%    \begin{macrocode}
\def\AM@split@optionsi#1,{%
  \ifx\END#1
  \else
    \AM@pdfpages@optionsfalse \AM@scalefalse
    \AM@split@optionsii#1=\END
    \ifthenelse{\equal{\AM@param}{pdfpages}}
      {\ifAM@pdfpages@options
          \@temptokena\expandafter{\the\@temptokena,#1}%
       \fi}{}%
    \ifthenelse{\equal{\AM@param}{Gin}}
      {\ifAM@pdfpages@options\else
         \@temptokena\expandafter{\the\@temptokena,#1}%
       \fi}{}%
    \ifthenelse{\equal{\AM@param}{Gin@noscale}}
      {\ifAM@pdfpages@options\else
         \ifAM@scale\else
           \@temptokena\expandafter{\the\@temptokena,#1}%
         \fi
       \fi}{}%
    \expandafter\AM@split@optionsi
  \fi
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@split@optionsii}{}
\def\AM@split@optionsii#1=#2\END{%
  \edef\AM@temp{\AM@trim@space{#1}}%
  \ifthenelse{\equal{pages}{\AM@temp}\or
              \equal{nup}{\AM@temp}\or
              \equal{deltax}{\AM@temp}\or
              \equal{deltay}{\AM@temp}\or
              \equal{delta}{\AM@temp}\or
              \equal{offset}{\AM@temp}\or
              \equal{frame}{\AM@temp}\or
              \equal{openright}{\AM@temp}\or
              \equal{pagecommand}{\AM@temp}\or
              \equal{landscape}{\AM@temp}\or
              \equal{turn}{\AM@temp}\or
              \equal{column}{\AM@temp}\or
              \equal{columnstrict}{\AM@temp}\or
              \equal{noautoscale}{\AM@temp}\or
              \equal{thread}{\AM@temp}\or
              \equal{threadname}{\AM@temp}\or
              \equal{link}{\AM@temp}\or
              \equal{linkfit}{\AM@temp}\or
              \equal{linkname}{\AM@temp}\or
              \equal{linktodoc}{\AM@temp}\or
              \equal{linktodocfit}{\AM@temp}\or
              \equal{linkfilename}{\AM@temp}\or
              \equal{survey}{\AM@temp}\or
              \equal{survey-nolink}{\AM@temp}\or
              \equal{output}{\AM@temp}\or
              \equal{xr-prefix}{\AM@temp}\or
              \equal{fitpaper}{\AM@temp}\or
              \equal{addtotoc}{\AM@temp}\or
              \equal{addtolist}{\AM@temp}\or
              \equal{doublepages}{\AM@temp}\or
              \equal{doublepagestwist}{\AM@temp}\or
              \equal{doublepagestwistodd}{\AM@temp}\or
              \equal{doublepagestwist*}{\AM@temp}\or
              \equal{doublepagestwistodd*}{\AM@temp}\or
              \equal{signature}{\AM@temp}\or
              \equal{pagetemplate}{\AM@temp}\or
              \equal{rotateoversize}{\AM@temp}\or
              \equal{picturecommand}{\AM@temp}\or
              \equal{picturecommand*}{\AM@temp}\or
              \equal{newwindow}{\AM@temp}\or
              \equal{reflect}{\AM@temp}\or
              \equal{reflect*}{\AM@temp}}
             {\AM@pdfpages@optionstrue}{}%
  \ifthenelse{\equal{scale}{\AM@temp}}{\AM@scaletrue}{}%
}
%    \end{macrocode}
%    \macro{\AM@trim@space}
%    \macro{\AM@trim@spacei}
%    \macro{\AM@trim@spaceii}
%    Removes leading and trailing spaces and save the result
%    in |\AM@trimmed|.
%    \begin{macrocode}
\newcommand{\AM@trim@space}{}\newcommand{\AM@trim@spacei}{}
\newcommand{\AM@trim@spaceii}{}
\def\AM@trim@space#1{%
  \expandafter\AM@trim@spacei\expandafter{\ifdim\z@=0pt#1}\fi}
\def\AM@trim@spacei#1{\AM@trim@spaceii#1 \END}
\def\AM@trim@spaceii#1 #2\END{#1}
%    \end{macrocode}
%    \macro{\AM@trim@leadingspace}
%    Just removes leading space.
%    \begin{macrocode}
\def\AM@trim@leadingspace#1{\ifdim\z@=0pt#1\fi}
%    \end{macrocode}
%    \macro{\AM@isphantom}
%    Checks, if current page is an empty (phantom) page.
%    \begin{macrocode}
\newif\ifAM@phantompage
\newcommand*{\AM@isphantom}{%
  \expandafter\ifx\expandafter\\\AM@page\\%
    \let\AM@page\AM@phantompage
    \let\AM@ph\phantom
    \AM@phantompagetrue
  \else
    \let\AM@ph\relax
    \AM@phantompagefalse
  \fi
}
%    \end{macrocode}
%    \macro{\AM@hyper@begin@i}
%    \macro{\AM@hyper@begin@ii}
%    \macro{\AM@hyper@end}
%    Add hypertext operations (targets, links and threads) to 
%    the inserted pages.
%    \begin{macrocode}

\newcommand{\AM@hyper@begin@i}{%
%    \end{macrocode}
%    Page is a target for a link.
%    \begin{macrocode}
  \ifAM@link \AM@dest@special\fi
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@hyper@begin@ii}{%
%    \end{macrocode}
%    Survey linking to pages.\par
%    \begin{macrocode}
  \ifAM@survey \ifAM@surveynolink\else
    \AM@survey@special@begin
  \fi\fi
%    \end{macrocode}
%    Page is linked to the original document.\par
%    \begin{macrocode}
  \ifAM@linktodoc\AM@linktodoc@special@begin\fi
%    \end{macrocode}
%    Page is a bead in a thread.
%    \begin{macrocode}
  \ifAM@thread\AM@thread@special@begin\fi
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@hyper@end}{%
  \ifAM@survey \ifAM@surveynolink\else
    \AM@survey@special@end
  \fi \fi
  \ifAM@linktodoc\AM@linktodoc@special@end\fi
  \ifAM@thread\AM@thread@special@end\fi
}
%    \end{macrocode}
%    \macro{\AM@openright}
%    Insert an empty item at the beginning of |\AM@pagelist|.
%    \begin{macrocode}
\newcommand{\AM@openright}{}
\def\AM@openright{%
  \edef\AM@pagelist{,\AM@pagelist}%
  \edef\AM@doclist{\AM@phantomdoc,\AM@doclist}%
}
%    \end{macrocode}
%    \macro{\AM@countpagelist}
%    \macro{\AM@countpagelisti}
%    Count items in |\AM@pagelist|. The number
%    of items is stored in |\@tempcnta|.
%    \begin{macrocode}
\newcommand{\AM@countpagelist}{}
\def\AM@countpagelist{%
  \@tempcnta=\z@
  \expandafter\AM@countpagelisti\AM@pagelist,\END,
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@countpagelisti}{}
\def\AM@countpagelisti#1,{%
  \ifx\END#1
  \else
    \advance\@tempcnta\@ne
    \expandafter\AM@countpagelisti
  \fi
}
%    \end{macrocode}
%    \macro{\AM@filluppagelist}
%    The number of items in |\AM@pagelist| and 
%    |\AM@doclist| should be a multiple of
%    $|\AM@xnup|\nobreak\times\nobreak|\AM@ynup|$.
%    If not, fill up the lists with empty items.
%    \begin{macrocode}
\newcommand{\AM@filluppagelist}{}
\def\AM@filluppagelist{%
  \@tempcnta=\AM@xnup\relax
  \@tempcntb=\AM@ynup\relax
  \multiply\@tempcnta\@tempcntb
  \edef\AM@nup{\the\@tempcnta}%
  \AM@countpagelist
  \@tempcntb=\@tempcnta
  \divide\@tempcntb\AM@nup
  \multiply\@tempcntb\AM@nup
  \advance\@tempcnta-\@tempcntb
  \ifnum\@tempcnta=\z@
    \else
      \advance\@tempcnta-\AM@nup
      \multiply\@tempcnta\m@ne
  \fi
  \whiledo{\@tempcnta > \z@}{%
    \let\saveAM@pagelist\AM@pagelist
    \edef\AM@pagelist{\saveAM@pagelist,}%
    \advance\@tempcnta\m@ne
    \let\saveAM@doclist\AM@doclist
    \edef\AM@doclist{\saveAM@doclist,\AM@phantomdoc}%
  }%
}
%    \end{macrocode}
%    \macro{\AM@prepare@signature}
%    Sort the pages in order to create signatures.
%    \begin{macrocode}
\newcommand{\AM@prepare@signature}{}
\def\AM@prepare@signature{%
  \def\AM@newpagelist{}%
  \def\AM@newdoclist{}%
%    \end{macrocode}
%    Make |\AM@signature| a multiply of 4.
%    \begin{macrocode}
  \@tempcnta=\AM@signature\relax
  \divide\@tempcnta by 4
  \multiply\@tempcnta by 4
  \ifnum\@tempcnta=0\@tempcnta=4\fi
  \edef\AM@signature{\the\@tempcnta}%
%    \end{macrocode}
%    Make |\AM@pagelist| and |\AM@doclist| contain a multiply
%    of |\AM@signature| items. (Similar to |\AM@filluppagelist|.)
%    \begin{macrocode}
  \AM@countpagelist
  \count@=\@tempcnta
  \@tempcntb=\AM@signature\relax
  \divide\count@\@tempcntb
  \multiply\count@\@tempcntb
  \advance\@tempcnta-\count@
  \ifnum\@tempcnta=0 \@tempcntb=0
  \else\advance\@tempcntb-\@tempcnta
  \fi
  \whiledo{\@tempcntb>\z@}{%
    \edef\AM@pagelist{\AM@pagelist,}%
    \edef\AM@doclist{\AM@doclist,\AM@phantomdoc}%
    \advance\@tempcntb\m@ne
  }%
%    \end{macrocode}
%    Now sort the pages.
%    \begin{macrocode}
  \def\AM@sort{%
    \def\AM@sigpagelist{}%
    \def\AM@sigdoclist{}%
    \@tempcntb=\AM@signature\relax
    \AM@getlastn{\AM@pagelist}{\@tempcntb}%
    \edef\AM@lastnpages{\AM@lastnitems}%
    \AM@getlastn{\AM@doclist}{\@tempcntb}%
    \edef\AM@lastndocs{\AM@lastnitems}%
    \@tempcnta=0
    \def\AM@first{%
      \AM@getfirst{\AM@lastnpages}%
      \edef\AM@sigpagelist{\AM@sigpagelist,\the\toks@}%
      \AM@getfirst{\AM@lastndocs}%
      \edef\AM@sigdoclist{\AM@sigdoclist,\the\toks@}%
    }%
    \def\AM@last{%
      \AM@getlast{\AM@lastnpages}%
      \edef\AM@sigpagelist{\AM@sigpagelist,\AM@lastitem}%
      \AM@getlast{\AM@lastndocs}%
      \edef\AM@sigdoclist{\AM@sigdoclist,\AM@lastitem}%
    }%
    \whiledo{\@tempcnta<\@tempcntb}{%
      \ifAM@landscape
        \AM@last\AM@first\AM@last\AM@first
      \else
        \AM@first\AM@last\AM@first\AM@last
      \fi
      \advance\@tempcnta by 4
    }%
    \edef\AM@newpagelist{\AM@sigpagelist\AM@newpagelist}%
    \edef\AM@newdoclist{\AM@sigdoclist\AM@newdoclist}%
    \ifx\AM@pagelist\@empty
    \else\expandafter\AM@sort
    \fi
  }%
  \AM@sort
  \edef\AM@pagelist{\expandafter\@gobble\AM@newpagelist}%
  \edef\AM@doclist{\expandafter\@gobble\AM@newdoclist}%
%    \end{macrocode}
%    \begin{macrocode}
  \ifdim\AM@pagewidth<\AM@pageheight
    \def\AM@xnup{\@ne}\def\AM@ynup{\tw@}%
  \else
    \def\AM@xnup{\tw@}\def\AM@ynup{\@ne}%
  \fi
}
%    \end{macrocode}
%    \macro{\AM@setphantom}
%    \macro{\AM@setphantompage}
%    \macro{\AM@setphantomdoc}
%    The box measures of the phantom page are used to create
%    empty pages. |\AM@phantomdoc| is the name and
%    |\AM@phantompage| is the page number of the phantom page.
%    \begin{macrocode}
\newcommand*{\AM@setphantom}{%
  \@ifundefined{AM@pagetemplate}
    {\expandafter\AM@setphantompage\AM@pagelist,\END,}
    {\edef\AM@phantompage{\AM@pagetemplate}}%
  \expandafter\AM@setphantomdoc\AM@doclist,\END
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@setphantompage}{}
\def\AM@setphantompage#1,{%
  \def\AM@gobble##1\END,{}%
  \ifx\\#1\\%
    \expandafter\AM@setphantompage
  \else 
    \def\AM@phantompage{#1}%
    \expandafter\AM@gobble
  \fi
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@setphantomdoc}{}
\def\AM@setphantomdoc#1,#2\END{\edef\AM@phantomdoc{#1}}
%    \end{macrocode}
%    \macro{\AM@addtotoc} 
%    \macro{\AM@parse@toclist}
%    \macro{\AM@parse@toclisti}
%    \macro{\AM@rm@from@toclist}
%    \macro{\AM@rm@from@toclisti}
%    These macros add entries to the table of contents (toc).
%    
%    |\AM@parse@addtotoc| reads the next entries from the list
%    |\AM@toclist| and prepares some macros (|\AM@toc@page|,
%    |\AM@toc@section|, etc.), which are used by |\AM@addtotoc|.
%    
%    The list |\AM@toclist| is a comma separated list and must
%    contain a multiple of five entries, which there are:
%    \meta{page number}, \meta{section}, \meta{level},
%    \meta{heading} and \meta{label}. 
%    \meta{section} is e.g., `chapter', `section', `subsection', etc.
%    and \meta{level} is a number, denoting depth of section e.g.,
%    chapter=0, section=1, etc.
%    \begin{macrocode}
\newcommand{\AM@addtotoc@hook}{\relax}
\newcommand{\AM@addtotoc}{}
\def\AM@addtotoc{%
  \begingroup
  \def\@seccntformat##1{}\def\@makechapterhead##1{}%
  \def\@endpart{}\def\partname{}%
  \def\autodot{}% KOMA classes
  \let\AM@addcontentsline\addcontentsline
  \def\addcontentsline##1##2##3{%
    \AM@addcontentsline{##1}{##2}{##3}%
    \def\thepart{}}%
  \AM@addtotoc@hook
  \edef\AM@temp{{\AM@toc@section}{\AM@toc@level}%
           {\z@}{\z@}{\z@}{}[\the\AM@toc@title]{}}%
  \edef\AM@tempi{\noexpand\csname @\AM@toc@section\noexpand\endcsname%
                 [\the\AM@toc@title]{}}%
  \@ifundefined{@\AM@toc@section}
    {\expandafter\@sect\AM@temp
     \hskip\z@\par\vskip-\parskip\vskip-\baselineskip\hskip\z@}
    {\AM@tempi}%
  \xdef\@currentlabel{\@currentlabel}%
  \label{\AM@toc@label}%
  \endgroup
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@parse@toclist}{}
\def\AM@parse@toclist{%
  \ifx\AM@toclist\empty \def\AM@toc@page{0}%
  \else \expandafter\AM@parse@toclisti\AM@toclist\END
  \fi
}
%    \end{macrocode}
%    \begin{macrocode}
\newtoks\AM@toc@title
\newcommand{\AM@parse@toclisti}{}
\def\AM@parse@toclisti#1,#2,#3,#4,#5,#6\END{%
  \def\AM@toc@page{\AM@trim@space{#1}}%
  \def\AM@toc@section{\AM@trim@space{#2}}%
  \def\AM@toc@level{\AM@trim@space{#3}}%
  \AM@toc@title\expandafter{\ifdim\z@=0pt#4}\fi
  \def\AM@toc@label{\AM@trim@space{#5}}%
  \AM@checkinteger{\AM@toc@page}%
  \ifAM@integer\else
    \PackageError{pdfpages}
         {Missing number.\MessageBreak
          Page number in option `addtotoc' is not a number}
         {See the pdfpages manual for explanation.}%
   \fi
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@rm@from@toclist}{}
\def\AM@rm@from@toclist{%
    \expandafter\AM@rm@from@toclisti\AM@toclist\END
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@rm@from@toclisti}{}
\def\AM@rm@from@toclisti#1,#2,#3,#4,#5,#6\END{%
  \def\AM@toclist{#6}%
}
%    \end{macrocode}
%    \macro{\AM@addtolist}
%    \macro{\AM@parse@loflist}
%    \macro{\AM@parse@loflisti}
%    \macro{\AM@rm@from@loflist}
%    \macro{\AM@rm@from@loflisti}
%    These macros add entries to the list of figures (lof),
%    the list of tables (lot) or any other list.
%
%    |\AM@loflist| is a comma separated list similar to
%    |\AM@toclist|, which must contain the entries:
%    \meta{page number}, \meta{figure}, \meta{heading} and
%    \meta{label}.
%    \begin{macrocode}
\newcommand{\AM@addtolist@hook}{\relax}
\newcommand{\AM@addtolist}{}
\def\AM@addtolist{
  \def\@captype{\AM@lof@list}%
  \long\def\@makecaption##1##2{}%
  \let\@fs@capt\relax% float.sty
  \caption{\AM@lof@heading}%
  \AM@addtolist@hook
  \@ifundefined{hyper@@anchor}{}{%
    \@ifundefined{float@caption}{%
      \hyper@@anchor{\@currentHref}{\relax}%
  }{}}%
  \label{\AM@lof@label}%
  \vskip-\baselineskip
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@parse@loflist}{}
\def\AM@parse@loflist{%
  \ifx\AM@loflist\empty \def\AM@lof@page{0}%
  \else \expandafter\AM@parse@loflisti\AM@loflist\END
  \fi
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@parse@loflisti}{}
\def\AM@parse@loflisti#1,#2,#3,#4,#5\END{%
  \def\AM@lof@page{\AM@trim@space{#1}}%
  \def\AM@lof@list{\AM@trim@space{#2}}%
  \def\AM@lof@heading{#3}%
  \def\AM@lof@label{\AM@trim@space{#4}}%
  \AM@checkinteger{\AM@lof@page}%
  \ifAM@integer\else 
    \PackageError{pdfpages}
         {Missing number.\MessageBreak
          Page number in option `addtolist' is not a number}
         {See the pdfpages manual for explanation.}%
  \fi
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@rm@fromloflist}{}
\def\AM@rm@from@loflist{%
    \expandafter\AM@rm@from@loflisti\AM@loflist\END
}
%    \end{macrocode}
%    \begin{macrocode}
\newcommand{\AM@rm@from@loflisti}{}
\def\AM@rm@from@loflisti#1,#2,#3,#4,#5\END{%
  \def\AM@loflist{#5}%
}
%    \end{macrocode}
%    \macro{\AM@toclof}
%    \begin{macrocode}
\newcommand{\AM@toclof}{}
\def\AM@toclof#1{%
  \AM@parse@toclist
  \whiledo{#1=\AM@toc@page}{%
    \ifx\AM@toclist\empty
    \else
      \AM@addtotoc
      \AM@rm@from@toclist
      \def\AM@toc@page{0}%
      \AM@parse@toclist
    \fi
  }%
  \AM@parse@loflist
  \whiledo{#1=\AM@lof@page}{%
    \ifx\AM@loflist\empty
    \else
      \AM@addtolist
      \AM@rm@from@loflist
      \def\AM@lof@page{0}%
      \AM@parse@loflist
    \fi
  }%
}
%    \end{macrocode}
%    \macro{\AM@AddToSurvey}
%     Add page to survey.
%    \begin{macrocode}
\ifAM@pkg@survey
  \newcommand{\AddToSurvey}{%
      \protected@write\@auxout{\let\AM@abs@page\relax}
         {\string\newlabel{\AM@xrprefix pdfpages@page\the\c@AM@survey}%
            {{}{\AM@abs@page}}}%
      \stepcounter{AM@survey}%
  }%
  \let\r@TotalPages\undefined
\else
  \newcommand{\AddToSurvey}{}
\fi
%    \end{macrocode}
%    \begin{macrocode}
\newcounter{AM@survey}
%    \end{macrocode}
%    |count1to.sty| saves the absolute page number in |\count1|.
%    \begin{macrocode}
\def\AM@abs@page{\the\count1}
%    \end{macrocode}
%    \macro{\AM@pageref}
%    |\AM@pageref| expands to a page number (and nothing more).
%    \begin{macrocode}
\newcommand{\AM@pageref}{}
\newcommand{\AM@@pageref}{}
\newcommand{\AM@secondarg}{}
\def\AM@pageref#1{\expandafter\AM@@pageref\csname r@#1\endcsname}
\def\AM@@pageref#1{\expandafter\AM@secondarg#1\@nil}
\def\AM@secondarg#1#2#3\@nil{#2}
%    \end{macrocode}
%    Make |\AddToSurvey| work within TeXpower's |\stepwise|.
%    \begin{macrocode}
\def\AM@TeXpower@hook{%
  \ifAM@pkg@survey
  \@ifpackageloaded{texpower}{%
    \releasecounter{AM@survey}%
    \let\AM@SetLabel\relax
    \g@addto@macro\do@insert@firstanchor@TP{%
      \AM@SetLabel\AM@SetTarget}%
    \g@addto@macro\dont@insert@firstanchor@TP{%
      \AM@SetLabel\AM@SetTarget}%
    \let\AM@setanchor\relax
    \def\AM@SetTarget{%
      \begingroup
      \advance\count1\m@ne
      \AM@anchor@special
      \endgroup
    }%
    \let\OrigAddToSurvey\AddToSurvey
    \def\AddToSurvey{%
      \ifthenelse{\boolean{instepwise@TP}}
        {\ifthenelse{\boolean{firstactivation}}{\AM@AddLabel}{}}
        {\AM@AddLabel}%
    }%
    \def\AM@AddLabel{\global\let\AM@SetLabel\OrigAddToSurvey
      \AtShipout{\AM@KillLabel}}%
    \def\AM@KillLabel{\global\let\AM@SetLabel\relax}%
  }{}%
  \fi
}
\AtBeginDocument{\AM@TeXpower@hook}
%    \end{macrocode}
%    \subsection{Options of \texttt{\protect\bslash includepdf}}
%    \begin{macrocode}
\define@key{pdfpages}{pages}{\def\AM@pagestemp{#1}}
\define@key{pdfpages}{nup}{\AM@parse@nup#1x\END}
\define@key{pdfpages}{deltax}{\AM@parse@deltax#1 \\}
\define@key{pdfpages}{deltay}{\AM@parse@deltay#1 \\}
\define@key{pdfpages}{delta}{\AM@parse@delta#1 \\}
\define@key{pdfpages}{offset}{\AM@parse@offset#1 \\}
\define@key{pdfpages}{frame}[true]{\setboolean{AM@frame}{#1}}
\define@key{pdfpages}{openright}[true]{\setboolean{AM@openright}{#1}}
\define@key{pdfpages}{pagecommand}{\def\AM@pagecommand{#1}}
\define@key{pdfpages}{landscape}[true]{\setboolean{AM@landscape}{#1}}
\define@key{pdfpages}{turn}[true]{\setboolean{AM@turn}{#1}}
\define@key{pdfpages}{column}[true]{\setboolean{AM@column}{#1}}
\define@key{pdfpages}{columnstrict}[true]%
                     {\setboolean{AM@columnstrict}{#1}}
\define@key{pdfpages}{noautoscale}[true]%
                     {\setboolean{AM@noautoscale}{#1}}
\define@key{pdfpages}{thread}[true]{\setboolean{AM@thread}{#1}}
\define@key{pdfpages}{threadname}{\def\AM@threadname{#1}}
\define@key{pdfpages}{link}[true]{\setboolean{AM@link}{#1}}
\define@key{pdfpages}{linkfit}{\def\AM@linkfit{#1}}
\define@key{pdfpages}{linkname}{\def\AM@linkname@option{#1}}
\define@key{pdfpages}{linktodoc}[true]{\setboolean{AM@linktodoc}{#1}}
\define@key{pdfpages}{linktodocfit}{\def\AM@linktodocfit{#1}}
\define@key{pdfpages}{linkfilename}{\pdfstringdef\AM@linkfilename{#1}%
                               \AM@linkfilenametrue}
\define@key{pdfpages}{survey}[true]{%
                      \ifAM@pkg@survey\setboolean{AM@survey}{#1}%
                      \else\AM@outputfalse\fi}
\define@key{pdfpages}{survey-nolink}[true]{%
                      \ifAM@pkg@survey\setboolean{AM@surveynolink}{#1}%
                                      \setboolean{AM@survey}{#1}
                      \else\AM@outputfalse\fi}
\define@key{pdfpages}{xr-prefix}{\def\AM@xrprefix{#1}}
\define@key{pdfpages}{fitpaper}[true]{\setboolean{AM@fitpaper}{#1}}
\define@key{pdfpages}{addtotoc}{\def\AM@toclist{#1,}}
\define@key{pdfpages}{addtolist}{\def\AM@loflist{#1,}}
\define@key{pdfpages}{doublepages}[true]%
                     {\setboolean{AM@doublepages}{#1}}
\define@key{pdfpages}{doublepagestwist}[true]%
                     {\setboolean{AM@doublepages}{#1}%
                      \setboolean{AM@doublepagestwist}{#1}%
                      \AM@doublepagestmptrue\AM@doublepagestmpitrue}
\define@key{pdfpages}{doublepagestwistodd}[true]%
                     {\setboolean{AM@doublepages}{#1}%
                      \setboolean{AM@doublepagestwist}{#1}%
                      \AM@doublepagestmpfalse\AM@doublepagestmpitrue}
\define@key{pdfpages}{doublepagestwist*}[true]%
                     {\setboolean{AM@doublepages}{#1}%
                      \setboolean{AM@doublepagestwist}{#1}%
                      \AM@doublepagestmptrue\AM@doublepagestmpitrue
                      \AM@doublepagestwistxtrue}
\define@key{pdfpages}{doublepagestwistodd*}[true]%
                     {\setboolean{AM@doublepages}{#1}%
                      \setboolean{AM@doublepagestwist}{#1}%
                      \AM@doublepagestmpfalse\AM@doublepagestmpitrue
                      \AM@doublepagestwistxtrue}
\define@key{pdfpages}{signature}{\def\AM@signature{#1}}
\define@key{pdfpages}{pagetemplate}{\def\AM@pagetemplate{#1}}
\define@key{pdfpages}{rotateoversize}[true]%
                     {\setboolean{AM@rotateoversize}{#1}}
\define@key{pdfpages}{picturecommand}{\def\AM@picturecommand{#1}}
\define@key{pdfpages}{picturecommand*}{\def\AM@picturecommandstar{#1}}
\define@key{pdfpages}{newwindow}[true]{\setboolean{AM@newwindow}{#1}}
\define@key{pdfpages}{reflect*}[true]{\setboolean{AM@reflect}{#1}}
\define@key{pdfpages}{reflect}[true]{\setboolean{AM@reflectall}{#1}}
%    \end{macrocode}
%    \macro{\AM@parse@nup}
%    Parsing \texttt{nup} item.
%    \begin{macrocode}
\newcommand{\AM@parse@nup}{}
\def\AM@parse@nup#1x#2\END{%
  \ifx\\#2\\%
    \def\AM@shortnupsyntax{}%
    \def\AM@xnup{\@ne}%
    \def\AM@ynup{\@ne}%
    \ifnum#1=\tw@
      \def\AM@xnup{\tw@}%
      \def\AM@ynup{\@ne}%
    \fi
    \ifnum#1=4
      \def\AM@xnup{\tw@}%
      \def\AM@ynup{\tw@}%
    \fi
  \else
    \def\AM@xnup{#1}%
    \AM@parse@nupi#2%
  \fi
}
\def\AM@parse@nupi#1x{\def\AM@ynup{#1}}
%    \end{macrocode}
%    \macro{\AM@parse@deltax}
%    \macro{\AM@parse@deltay}
%    \macro{\AM@parse@offset}
%    Parsing arguments. These lines are derived
%    from \texttt{graphicx.sty}.
%    \begin{macrocode}
\def\AM@parse@deltax#1 #2\\{\AMGin@defaultbp\AM@deltax{#1}}
%    \end{macrocode}
%    \begin{macrocode}
\def\AM@parse@deltay#1 #2\\{\AMGin@defaultbp\AM@deltay{#1}}
%    \end{macrocode}
%    \begin{macrocode}
\def\AM@parse@delta#1 #2 #3\\{%
  \AMGin@defaultbp\AM@deltax{#1}%
  \AMGin@defaultbp\AM@deltay{#2}}
%    \end{macrocode}
%    \begin{macrocode}
\def\AM@parse@offset#1 #2 #3\\{%
  \AMGin@defaultbp\AM@xoffset{#1}%
  \AMGin@defaultbp\AM@yoffset{#2}}
%    \end{macrocode}
%    \begin{macrocode}
\def\AMGin@defaultbp#1#2{%
  \afterassignment\AMGin@def@bp\dimen@#2bp\relax{#1}{#2}}
%    \end{macrocode}
%    \begin{macrocode}
\def\AMGin@def@bp#1\relax#2#3{%
   \if!#1!%
     \def#2{#3bp}%
    \else
      \dimen@.99626\dimen@
      \edef#2{\strip@pt\dimen@ bp}%
    \fi
}
%    \end{macrocode}
%    Load patch file, if one exists.
%    \begin{macrocode}
\InputIfFileExists{pdfpages.fix}{%
  \PackageInfo{pdfpages}{Loading patch file `pdfpages.fix'}}{}
%    \end{macrocode}
%
%
%    \iffalse
%</package>
%
%<*pppdftexdef>
%    \fi
%
%
%    \subsection{Driver files}
%    \subsubsection{\pdfTeX\ driver}
%
%    Check \pdfTeX\ version and output.
%    \begin{macrocode}
\ifnum\pdftexversion<100
  \PackageError{pdfpages}
         {Package pdfpages requires at least\MessageBreak
          pdfTeX version 1.00}
         {Update your TeX distribution.}
  \let\AM@endinput\relax
  \expandafter\endinput
\fi
\ifcase\pdfoutput
  \PackageError{pdfpages}
         {You produce DVI output but PDF output\MessageBreak
          is needed for package pdfpages}
         {Set output to PDF. (use: \pdfoutput = 1)}
  \let\AM@endinput\relax
  \expandafter\endinput
\fi
%    \end{macrocode}
%    Check if the graphics package was loaded with an 
%    incompatible driver option (e.g. dvips).
%    \begin{macrocode}
\begingroup
\@ifundefined{ver@pdftex.def}{%
  \PackageError{pdfpages}
         {The graphics package was loaded with driver\MessageBreak
          `\Gin@driver', which cannot be used with pdfTeX}
         {Check the driver option of the graphics package.}
  \global\let\AM@endinput\relax
  \aftergroup\endinput}{}
\endgroup
%    \end{macrocode}
%    Check for \texttt{pdftex.def} version \texttt{2000/05/12 v0.02u} 
%    or higher:
%    \begin{list}{$\ast$}{\versionlist}
%      \makeatletter\@beginparpenalty=10000\makeatother
%      \item support for multipage \PDF\ files, option `page' added (HO).
%    \end{list}
%    \begin{macrocode}
\AM@ifdriverlater{pdftex}{2000/05/12}{}{%
    \PackageError{pdfpages}
         {Your version of `pdftex.def' is too old.\MessageBreak
          There is no multipage support\MessageBreak
          in `pdftex.def' < 0.02u}
         {Please, update your `pdftex.def'!}}
%    \end{macrocode}
%    Check for \texttt{pdftex.def} version \texttt{2000/09/14 v0.03d}
%     or higher:
%    \begin{list}{$\ast$}{\versionlist}
%      \makeatletter\@beginparpenalty=10000\makeatother
%      \item Fixes for `viewport' and `trim' (HO).
%      \item Clip support added for viewport and trim (HO).
%    \end{list}
%    \begin{macrocode}
\AM@ifdriverlater{pdftex}{2000/09/14}{}{%
    \PackageWarningNoLine{pdfpages}{%
         Your version of `pdftex.def' is too old.\MessageBreak
         There might be problems with\MessageBreak
         the `trim' and `clip' options.\MessageBreak
         Please, update your `pdftex.def'}}
%    \end{macrocode}
%    Get last page number.
%    \begin{macrocode}
\def\AM@getpagecount{%
  \pdfximage{\AM@currentdocname}%
  \edef\AM@pagecount{\the\pdflastximagepages}%
}
%    \end{macrocode}
%    Page dimensions.
%    \begin{macrocode}
\let\AM@pagewidth\pdfpagewidth
\let\AM@pageheight\pdfpageheight
\def\AM@setpagedimen{%
  \setlength{\pdfpagewidth}{\the\wd\@tempboxa}%
  \setlength{\pdfpageheight}{\the\ht\@tempboxa}%
}
%    \end{macrocode}
%    Change paper size.
%    \begin{macrocode}
\let\AM@fitpaper@special\relax
%    \end{macrocode}
%    Find file.
%    \begin{macrocode}
\def\AM@findfile#1{%
  \AM@findfile@i{#1}{pdf}%
  \AM@findfile@ii{#1}%
}
%    \end{macrocode}
%    Rotate page.
%    \begin{macrocode}
\def\AM@setlscape{\pdfpageattr{/Rotate 90}}
%    \end{macrocode}
%    Link to original document.
%    \begin{macrocode}
\def\AM@linktodoc@special@begin{%
    \pdfannot width \wd\@tempboxa
              height \ht\@tempboxa
              depth \dp\@tempboxa
              {/Subtype /Link /Border [0 0 0]
               /A << /S /GoToR
                     /F (\AM@linkfilename)
                     /D [\AM@linktodoc@page@m@ne \AM@linktodocfit]
                     \ifAM@newwindow/NewWindow true\fi >>}%
}
\let\AM@linktodoc@special@end\relax
%    \end{macrocode}
%    Survey.
%    \begin{macrocode}
\def\AM@survey@special@begin{%
    \pdfannot width \wd\@tempboxa
              height \ht\@tempboxa
              depth \dp\@tempboxa
              {/Subtype /Link /Border [0 0 0]
               /A << /S /GoTo
                     /D (pdfpages.\AM@linktodoc@page@m@ne) >>}%
}
\let\AM@survey@special@end\relax
%    \end{macrocode}
%    Thread.
%    \begin{macrocode}
\def\AM@thread@special@begin{%
      \pdfthread width \wd\@tempboxa
                 height \ht\@tempboxa
                 depth \dp\@tempboxa
                 attr {/I <<\threadinfodict>>}%
                 name {\AM@threadname}%
}
\let\AM@thread@special@end\relax
%    \end{macrocode}
%    Destination for links.
%    \begin{macrocode}
\def\AM@dest@special{\pdfdest name {\AM@linkname.\AM@page} \AM@linkfit}
\def\AM@anchor@special{\pdfdest name {pdfpages.\the\count1} fit}
%    \end{macrocode}
%
%    \iffalse
%</pppdftexdef>
%
%<*ppvtexdef>
%    \fi
%
%    \subsubsection{\VTeX\ driver}
%
%    Check \VTeX\ version.
%    \begin{macrocode}
\ifnum\VTeXversion<822
  \PackageError{pdfpages}
         {Package pdfpages requires at least\MessageBreak
          VTeX version 8.22}
         {Update your VTeX distribution.}%
  \let\AM@endinput\relax
\fi
%    \end{macrocode}
%    Check |vtex.def| version.
%    \begin{macrocode}
\AM@ifdriverlater{vtex}{2003/06/16}{}{%
  \PackageError{pdfpages}{%
       Your version of `vtex.def' is too old}
       {Please, update your `vtex.def'!}%
  \let\AM@endinput\relax
  \expandafter\endinput
}
%    \end{macrocode}
%    Get last page number.
%    \begin{macrocode}
\def\AM@getpagecount{%
  \getpagecount\count@ \AM@currentdocname\relax
  \edef\AM@pagecount{\the\count@}%
}
%    \end{macrocode}
%    Page dimensions.
%    \begin{macrocode}
\let\AM@pagewidth\mediawidth
\let\AM@pageheight\mediaheight
\def\AM@setpagedimen{%
  \setlength{\mediawidth}{\the\wd\@tempboxa}%
  \setlength{\mediaheight}{\the\ht\@tempboxa}%
}
%    \end{macrocode}
%    Rotate page.
%    \begin{macrocode}
\def\AM@setlscape{\special{pS:
    [{ThisPage}\string<\string</Rotate 90\string>\string>%]
    /PUT pdfmark}%
}
%    \end{macrocode}
%    Change paper size.
%    \begin{macrocode}
\def\AM@fitpaper@special{%
  \immediate\xspecial{option updatemediasizes="on"}}
%    \end{macrocode}
%    Find file.
%    \begin{macrocode}
\def\AM@findfile#1{%
  \AM@findfile@i{#1}{pdf}%
  \ifx\AM@currentdocname\relax
    \AM@findfile@i{#1}{ps}%
  \fi
  \AM@findfile@ii{#1}%
}
%    \end{macrocode}
%    Link to original document.
%    \begin{macrocode}
\def\AM@linktodoc@special@begin{%
  \special{!aref <\ifAM@newwindow n\fi
           f=\AM@linkfilename>!\AM@linktodoc@page;
           a=</Border [0 0 0]>}%
}
\def\AM@linktodoc@special@end{%
  \special{!endaref}%
}
%    \end{macrocode}
%    Survey.
%    \begin{macrocode}
\def\AM@survey@special@begin{%
  \special{!aref pdfpages.\AM@linktodoc@page@m@ne; a=</Border [0 0 0]>}%
}
\def\AM@survey@special@end{%
  \special{!endaref}%
}
%    \end{macrocode}
%    Thread.
%    \begin{macrocode}
\def\AM@thread@special@begin{%
  \special{!thread <\threadinfodict> \AM@threadname}%
}
\def\AM@thread@special@end{\special{!endthread}}
%    \end{macrocode}
%    Destination for links.
%    \begin{macrocode}
\def\AM@dest@special{\special{!aname \AM@linkname.\AM@page}}
\def\AM@anchor@special{\special{!aname pdfpages.\the\count1}}
%    \end{macrocode}
%
%    \iffalse
%</ppvtexdef>
%    \fi
%
%
%    \section{History}
%
%    \subsection*{2001/01/17 v0.1b}
%    \begin{itemize}
%      \item The first released version.
%    \end{itemize}
%
%    \subsection*{2001/02/03 v0.1c}
%    \begin{itemize}
%      \item Pages are being centered automatically.
%    \end{itemize}
%
%    \subsection*{2001/03/16 v0.1f}
%    \begin{itemize}
%      \item Option |pages| added.
%    \end{itemize}
%
%    \subsection*{2001/04/07 v0.1h}
%    \begin{itemize}
%      \item Hypertext operations added. (Hyperlinks, threads)
%    \end{itemize}
%
%    \subsection*{2001/11/12 v0.2}
%    \begin{itemize}
%      \item Support of |m|$\times$|n| logical pages on each
%        sheet of paper.
%      \item Options |column| and |columnstrict| added.
%      \item New command |\inlcudepdfmerge|.
%    \end{itemize}
%
%    \subsection*{2001/12/26 v0.2c}
%    \begin{itemize}
%      \item Option |fitpaper| added.
%    \end{itemize}
%
%    \subsection*{2001/03/31 v0.2g}
%    \begin{itemize}
%      \item Option |signature| added.
%      \item Options |addtotoc| and |addtolist| added.
%      \item Option |doublepages| added.
%      \item Options now have their own namespace |pdfpages| and
%        do not extent the |Gin| (graphicx) namespace any longer.
%    \end{itemize}
%
%    \subsection*{2002/12/14 v0.2l}
%    \begin{itemize}
%      \item Survey functionality added.
%    \end{itemize}
%
%    \subsection*{2003/06/02 v0.2m}
%    \begin{itemize}
%      \item Support of \PDF s with mixed portrait/landscape pages.
%            Options |pagetemplate| and |rotateoversize| added.
%      \item Support of |\graphicspath|.
%      \item Options |picturecommand| and |picturecommand*| added.
%      \item Reverse page order: |pages=7-3|, |pages=last-5|
%    \end{itemize}
%
%    \subsection*{2003/06/21 v0.3a}
%    \begin{itemize}
%      \item Support of \VTeX.
%      \item Driver layer added. All driver specific macros are
%        defined in |.def| driver files.
%    \end{itemize}
%
%    \subsection*{2003/07/16 v0.3b}
%    \begin{itemize}
%      \item Option |\doublepagestwist| added.
%    \end{itemize}
%
%    \subsection*{2003/12/08 v0.3e}
%    \begin{itemize}
%      \item Option |reflect| added.
%      \item Made |\AddToSurvey| work within TeXpower's |\stepwise|.
%    \end{itemize}

%
%    \Finale
%
%    \iffalse
%<*example1>
\documentclass[a4paper,12pt]{article}
\usepackage[final]{pdfpages}
\usepackage{verbatim}
%% Uncomment the following lines, if you want to produce thumbnails.
%%\usepackage{pdflscape}
%%\usepackage{thumbpdf}

\newcounter{example}
\setcounter{example}{1}

\newenvironment{example}
  {\par\vskip\topsep%
   \noindent\textbf{Example \arabic{example}:}%
   \stepcounter{example}%
   \par\vskip\topsep%
   \minipage{.9\linewidth}%
   \verbatim}
  {\endverbatim%
   \endminipage\par\vskip\topsep}

\begin{document}

\title{A Demonstration of the \texttt{pdfpages} Package}
\author{Andreas MATTHIAS}
\maketitle

This is a demonstration of the \texttt{pdfpages} package.
It is \textit{not} the documentation of the package.
To get the documentation run: `latex pdfpages.dtx'

\tableofcontents

\section{Inserting Pages:}
\begin{example}
\includepdf[pages=3-5]{dummy.pdf}
\end{example}
\includepdf[pages=3-5]{dummy.pdf}

\section{Using the \texttt{nup} Option}
Arranging several logical pages on one sheet of paper.

\begin{example}
\includepdf[nup=1x2, landscape, pages=4-7]{dummy.pdf}
\end{example}
\includepdf[nup=1x2, landscape, pages=4-7]{dummy.pdf}

Use the option \texttt{turn=false}, if the pages
should not be displayed in landscape orientation.
(If the last two pages were not displayed in
landscape orientation, you use a PDF viewer that
does not support this option.)

\begin{example}
\includepdf[nup=1x2, landscape, 
            pages=4-7, turn=false]{dummy.pdf}
\end{example}
\includepdf[nup=1x2, landscape, 
            pages=4-7, turn=false]{dummy.pdf}

\begin{example}
\includepdf[nup=1x2, pages=1-4]{dummy-l.pdf}
\end{example}
\includepdf[nup=1x2, pages=1-4]{dummy-l.pdf}

\noindent
With the option \texttt{pages} special pages and
ranges of pages can be selected.

\begin{example}
\includepdf[nup=3x2, pages={1,4-6,8,10}]{dummy.pdf}
\end{example}
\includepdf[nup=3x2, pages={1,4-6,8,10}]{dummy.pdf}

\noindent
A column-major layout can be achieved with the
option \texttt{column}.

\begin{example}
\includepdf[nup=2x2, pages=1-4, column]{dummy.pdf}
\end{example}
\includepdf[nup=2x2, pages=1-4, column]{dummy.pdf}


\noindent
Sometimes it might be useful to put an empty page
at the beginning. 
\begin{example}
\includepdf[nup=2x2, pages={{},5-7}]{dummy.pdf}
\end{example}
\includepdf[nup=2x2, pages={{},5-7}]{dummy.pdf}


\section{Changing Layout}

To put some space between the logical pages, use the option
\texttt{delta}. 

Any options of \verb|\includegraphics| are allowed in
\verb|\includepdf| as well. See the \texttt{scale}
option in the next example.
\begin{example}
\includepdf[nup=2x2, pages=3-6, scale=.8,
            delta=8mm 11mm, frame]{dummy.pdf}
\end{example}
\includepdf[nup=2x2, pages=3-6, scale=.8,
            delta=8mm 11mm, frame]{dummy.pdf}

\noindent
By default the output is centered, as you could see in
the last examples. With the \texttt{offset} option it is
possible to displace the output.

\begin{example}
\includepdf[nup=2x2, pages=3-6, scale=.8,
            offset=5mm 7mm, frame]{dummy.pdf}
\end{example}
\includepdf[nup=2x2, pages=3-6, scale=.8,
            offset=5mm 7mm, frame]{dummy.pdf}


\noindent
To remove the header and the footer of the inserted
document use the \texttt{trim} and \texttt{clip}
options of the \texttt{graphicx} package.

\begin{example}
\includepdf[nup=2x2, pages=1-4, 
            trim=0 40mm 0 40mm,
            clip, pagecommand={}]{dummy.pdf}
\end{example}


\noindent The option
\verb|pagecommand={\thispagestyle{empty}}|
is set by default. If you don't want the page style
to be set to empty, you can remove this default 
setting by using the \texttt{pagecommand} option
as follows:
\verb|pagecommand={}|.

\includepdf[nup=2x2, pages=1-4, 
            trim=0 40mm 0 40mm,
            clip, pagecommand={}]{dummy.pdf}


\noindent
You like the crazy way? Then try this one \texttt{;-)}
\begin{example}
\includepdf[pages={3,4}, nup=1x2,
            landscape, scale=1.1,
            angle=30, delta=0 -85mm]{dummy.pdf}
\end{example}
\includepdf[pages={3,4}, nup=1x2,
            landscape, scale=1.1,
            angle=30, delta=0 -85mm]{dummy.pdf}


\end{document}
%</example1>
%
%
%
%<*example2>
\documentclass[a4paper,12pt]{article}
\usepackage[final]{pdfpages}
\usepackage{verbatim}
%% Uncomment the following lines, if you want to produce thumbnails.
%%\usepackage{pdflscape}
%%\usepackage{thumbpdf}
\usepackage[bookmarksopen]{hyperref}

\newcounter{example}
\setcounter{example}{1}

\newenvironment{example}
  {\par\vskip\topsep%
   \noindent\textbf{Example \arabic{example}:}%
   \stepcounter{example}%
   \par\vskip\topsep%
   \minipage{.9\linewidth}%
   \verbatim}
  {\endverbatim%
   \endminipage\vskip\topsep}

\newcommand{\meta}[1]{\ensuremath\langle\texttt{#1}\ensuremath\rangle}
\newcommand{\link}[2]{\meta{#1}.\meta{#2}}

\newcommand*{\bookmark}[3][0]{%
  \pdfoutline user {<< /S /GoTo /D (#3) >>} count #1 {#2}}


\begin{document}

\title{A Demonstration of the Hypertext Operations\\
       of the \texttt{pdfpages} Package}
\author{Andreas MATTHIAS}
\maketitle

This is a demonstration of the \texttt{pdfpages} package.
It is \textit{not} the documentation of the package.
To get the documentation run: `latex pdfpages.dtx'

\tableofcontents

\section{Hyperlinks}
\subsection{Links to the inserted Pages}

Hyperlinks are created by using the option \texttt{link}
of the \verb|\includepdf| command. Each inserted page
gets a link name consisting of the filename and
the page number: \link{filename}{page number}

\begin{example}
\includepdf[pages=1-2, link]{dummy.pdf}
\end{example}

In this example the two pages have the link names
`\texttt{dummy.pdf.1}' and `\texttt{dummy.pdf.2}'.
Setting links to these
pages, can be done easily with the \verb|\hyperlink|
macro from the \texttt{hyperref.sty} package:

\bigskip
\verb|\hyperlink{dummy.pdf.1}{Page 1}|\hskip10pt \hyperlink{dummy.pdf.1}{Page 1}\par
\verb|\hyperlink{dummy.pdf.2}{Page 2}|\hskip10pt \hyperlink{dummy.pdf.2}{Page 2}
\bigskip

This way you can refer to the \hyperlink{dummy.pdf.1}{first}
and the \hyperlink{dummy.pdf.2}{second page}.

\includepdf[pages=1-2, link]{dummy.pdf}


Inserting the same page twice would result in two 
identical link names. To prevent this use the option
\texttt{linkname} to specify another name for the links.

\begin{example}
\includepdf[pages=1-2, nup=1x2, landscape,
            link, linkname=mylink]{dummy.pdf}
\end{example}

\noindent
Now the links are called `\texttt{mylink.1}' and
`\texttt{mylink.2}'.

\bigskip
\verb|\hyperlink{mylink.1}{Page 1}|\hskip10pt \hyperlink{mylink.1}{Page 1}\par
\verb|\hyperlink{mylink.2}{Page 2}|\hskip10pt \hyperlink{mylink.2}{Page 2}

\includepdf[pages=1-2, nup=1x2, landscape,
            link, linkname=mylink]{dummy.pdf}

\subsection{Links to the original Document}

Each page can be a hyperlink to the document from
which it was extracted. This can be done with the
option \texttt{linktodoc}.

Click on the inserted pages and see what happens.

\begin{example}
\includepdf[pages=1-4, nup=2x2, linktodoc]{dummy.pdf}
\end{example}
\includepdf[pages=1-4, nup=2x2, linktodoc]{dummy.pdf}


\section{Article Threads}

In a PDF document one or more article threads may be defined.
An article thread is a logical connected sequence of content
items.

With the option \texttt{thread} the inserted pages become
an article thread.

\begin{example}
\includepdf[pages=1-4, nup=2x2, column,
            landscape, thread]{dummy-l.pdf}
\end{example}

In Acrobat Reader the mouse pointer changes to a hand with
a little arrow in it when moved over an article thread.
By clicking on the page you can easily follow the logical
structure of the article thread.

\includepdf[pages=1-4, nup=2x2, column,
            landscape, thread]{dummy-l.pdf}

\end{document}
%</example2>
%
%
%<*example3>
\documentclass[a4paper]{book}
\usepackage{pdfpages}
\usepackage{verbatim}
\usepackage[plainpages=false, pdfpagelabels,
            bookmarksopen]{hyperref}

\begin{document}
\tableofcontents

\chapter{How to create a toc}

The next pages were inserted using the following command:

\begin{verbatim}
\includepdf[pages=1-6,
            pagecommand={},
            addtotoc={1, chapter, 0, Main chapter,   cha:main,
                      1, section, 1, First section,  sec:first,
                      3, section, 1, Second section, sec:second},
            trim=0 120 0 120, clip]{dummy.pdf}
\end{verbatim}

\noindent
See Chapter \ref{cha:main} (\nameref{cha:main}) on page 
\pageref{cha:main}.\par\noindent
See Section \ref{sec:first} (\nameref{sec:first}) on page 
\pageref{sec:first}.\par\noindent
See Section \ref{sec:second} (\nameref{sec:second}) on page 
\pageref{sec:second}.

\includepdf[pages=1-6,
            pagecommand={},
            addtotoc={1, chapter, 0, Main chapter,   cha:main,
                      1, section, 1, First section,  sec:first,
                      3, section, 1, Second section, sec:second},
            trim=0 120 0 120, clip]{dummy.pdf}

\end{document}
%</example3>
%
%\fi
\endinput
