%
%    \iffalse
%
%<*(package,pppdftexdef,ppluatexdef,ppvtexdef,ppxetexdef,ppdvipsdef,ppdvipdfmxdef,ppnulldef)>
%% Copyright (C) 2001-2024 Andreas MATTHIAS
%%
%% This work may be distributed and/or modified under the conditions
%% of the LaTeX Project Public License, either version 1.3c
%% 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>.
%%
%% This work has the LPPL maintenance status `maintained'.
%%
%% The Current Maintainer of this work is
%%   Andreas Matthias <andreas.matthias@gmail.com>.
%
%</(package,pppdftexdef,ppluatexdef,ppvtexdef,ppxetexdef,ppdvipsdef,ppdvipdfmxdef,ppnulldef)>
%<*!installer>
%%
%% Please send error reports and suggestions for improvements to
%%   Andreas MATTHIAS <andreas.matthias@gmail.com>.
%</!installer>
%%
%
%<*!(example1,example2,example3,installer)>
%<*dtx>
\makeatletter
%</dtx>
\def\AM@fileversion{v0.6b}
\def\AM@Git@Date@process$#1: #2 #3${\AM@Git@Date@process@i#2\END}
\def\AM@Git@Date@process@i#1-#2-#3\END{\def\AM@Git@Date{#1/#2/#3}}
\def\AM@Git@SHA@process$#1: #2${\def\AM@Git@SHA{#2}}
\AM@Git@Date@process$Date: 2024-08-20 15:16:01 +0200 $
\AM@Git@SHA@process$SHA-1: 8cc873330fc0863d9d32e017e64c98d9f04f579d $
%</!(example1,example2,example3,installer)>
%
%
%<*dtx>
\ProvidesFile{pdfpages.dtx}
%</dtx>
%<package>\NeedsTeXFormat{LaTeX2e}
%<package>\ProvidesPackage{pdfpages}
%<pppdftexdef>\ProvidesFile{pppdftex.def}
%<ppluatexdef>\ProvidesFile{ppluatex.def}
%<ppvtexdef>\ProvidesFile{ppvtex.def}
%<ppxetexdef>\ProvidesFile{ppxetex.def}
%<ppdvipsdef>\ProvidesFile{ppdvips.def}
%<ppdvipdfmxdef>\ProvidesFile{ppdvipdfmx.def}
%<ppnulldef>\ProvidesFile{ppnull.def}
%<driver>\ProvidesFile{pdfpages.drv}
%<*!(example1,example2,example3,installer)>
%    \fi
%
%    \makeatletter
%    \ProvidesFile{pdfpages.dtx}
   [\AM@Git@Date\space\AM@fileversion\space
%
%    \iffalse
%</!(example1,example2,example3,installer)>
%<*none>
%    \fi
]
%    \makeatother
%    \iffalse
%</none>
%<*!(example1,example2,example3,installer)>
%<*dtx>
\makeatother
%</dtx>
%</!(example1,example2,example3,installer)>
%
%<package>    Insert pages of external PDF documents (AM)]
%<pppdftexdef>    Pdfpages driver for pdfTeX (AM)]
%<ppluatexdef>    Pdfpages driver for LuaTeX (AM)]
%<ppvtexdef>    Pdfpages driver for VTeX (AM)]
%<ppxetexdef>    Pdfpages driver for XeTeX (AM)]
%<ppdvipsdef>    Pdfpages driver for dvips (AM)]
%<ppdvipdfmxdef>    Pdfpages driver for dvipdfmx (AM)]
%<ppnulldef>    Pdfpages dummy driver (AM)]
%
%
%    \fi
%
%    \GetFileInfo{pdfpages.dtx}
%
%    \CheckSum{5113}
%
% \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}
\usepackage{graphicx}
\usepackage{booktabs}
\usepackage{cmap}
\usepackage{hypdoc}
\hypersetup{colorlinks, linkcolor=blue, pdfstartview={Fit},
  bookmarksopenlevel=1, bookmarksnumbered=false}
\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{pdfTeX}
%    \def\pdfLaTeX{pdfLaTeX}
%    \def\luaTeX{LuaTeX}
%    \def\VTeX{VTeX}
%    \def\XeTeX{XeTeX}
%    \def\dvips{dvips}
%    \def\dvipdfmx{dvipdfmx}
%    \def\pTeX{pTeX}
%    \def\PDF{{\small PDF}}
%    \def\PS{{\small PS}}
%    \def\DVI{{\small DVI}}
%
%    \pdfstringdefDisableCommands{%
%       \def\pdfTeX{pdfTeX}%
%       \def\luaTeX{LuaTeX}%
%       \def\VTeX{VTeX}%
%       \def\XeTeX{XeTeX}%
%     }
%
%    \makeatletter
%    \title{The \textsf{pdfpages} Package\thanks{This file
%           has version number \AM@fileversion, last revised \AM@Git@Date.}}
%    \author{Andreas \textsc{Matthias}\\
%      \href{mailto:andreas.matthias@gmail.com}{andreas.matthias@gmail.com}}
%    \date{\AM@Git@Date}
%    \makeatother
%
%    \maketitle
%
%    \begin{abstract}
%       \noindent
%       This package simplifies the insertion of external multi-page \PDF\
%       or \PS\ documents. It supports \pdfTeX, \VTeX, \XeTeX, \luaTeX, and
%       \pTeX.
%    \end{abstract}
%
%    \tableofcontents
%
%
%    \section{Introduction}
%    When creating \PDF\ documents, it is sometimes useful to insert pages
%    of 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. When working with \VTeX\ the same is possible with PostScript
%    documents, too. Note that PostScript documents are only supported by
%    \VTeX\ and \emph{not} by \pdfLaTeX.
%
%    When producing \DVI\ output |pdfpages| cannot insert pages of a \PDF\
%    documents. But instead of interrupting execution |pdfpages| will insert
%    empty pages. This feature is important when using packages like
%    |pst-pdf|, which need to produce \DVI\ output at the first run.
%
%    \paragraph{Links and other interactive features of PDF documents}
%    When including pages of a PDF only the so called content stream of
%    these pages is copied but no links. Up to now there are no TeX-engines
%    (\pdfTeX, \XeTeX, \ldots) available that can copy links or other
%    interactive features of a PDF document, too. Thus, all kinds of
%    links\footnote{Actually not only links but all kinds of \emph{PDF
%        annotations} will get lost.}  will get lost during
%    inclusion. (Using |\includepdf|, |\includegraphics|, or other low-level
%    commands.)
%
%    However, there's a glimmer of hope. Some links may be extracted and later
%    reinserted by a package called \emph{pax} which can be downloaded from
%    CTAN \cite{pax}. Have a look at it!
%
%
%    \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[|demo|:] Inserts empty pages instead of the actual PDFs.
%               \item[|nodemo|:] Disables `demo'.
%               \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 reverse 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[openrighteach] Similar to |openright| but affects
%                      \emph{each} file processed by |\includepdfmerge|.
%        \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.
%                     Either `true' or `false' (or no value, which
%                     is equivalent to `true'). \df{reflect=false}
%        \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 multiple 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[signature*] Similar to |signature|, but now for right-edge
%                     binding.
%       \item[booklet] This option is just a shortcut of the `signature'
%                     option, if you choose a signature value
%                     so large that all pages fit into one signature.
%                     Either `true' or `false' (or no value, which
%                     is equivalent to `true'). \df{booklet=false}
%       \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 such that they 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[templatesize] This option is similar to the |pagetemplate|
%                     option, but its arguments specify the size of
%                     the template directly. Its syntax is:
%                     |templatesize={|\meta{width}|}{|\meta{height}|}|
%                     Note: The two lengths should be a bit larger than
%                     desired, to keep away from rounding errors.\par
%                     \df{templatesize=\meta{size of the 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}
%         \item[duplicatepages] Duplicates each page $n$ times,
%                     with $n$ being the argument to this option.
%                     \df{duplicatepages=2}
%      \end{description}
%
%    \item Miscellaneous options:
%      \makeatletter\@beginparpenalty=10000\makeatother
%      \begin{description}
%      \item[lastpage] In \DVI\ mode pdfpages cannot determine the number of
%        pages of the included document. So this option is suitable to
%        specify the number of pages. This option is only used in \DVI\ mode
%        and has no meaning in any other mode. The argument should be a page
%        number. \df{lastpage=1}
%      \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 filename extension (.pdf) is missing
%                         in \meta{filename}.
%                         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, how the viewer displays a linked page.
%                       This option changes the default behavior of the
%                       option \texttt{link}.
%                       Possible values are:
%                       \texttt{Fit},
%                       \texttt{FitH \meta{top}},
%                       \texttt{FitV \meta{left}},
%                       \texttt{FitB},
%                       \texttt{FitBH \meta{top}},
%                       \texttt{FitBV \meta{left}},
%^^A                       \texttt{fitr \meta{left} \meta{bottom}
%^^A                         \meta{right} \meta{top}},
%^^A                       \texttt{xyz \meta{left} \meta{top} \meta{zoom}},
%                       and \texttt{Region}.
%
%                       See \cite{PDFRef} for a details description of these
%                       \PDF\ destinations. The |region| destination was
%                       added by pdfpages and is not a real \PDF\
%                       destinations. It scales a page such that the
%                       included page fits exactly into the window of the
%                       \PDF\ viewer.\par
%                       Note that not all of these options are supported by
%                       all \TeX-engines or drivers, respectively.
%                       \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., 1 for section level, 2 for
%                          subsection level, \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
%      \setlength{\unitlength}{.7mm}
%      \def\thick{.7pt}
%      \def\thin{.2pt}
%      ^^A\fbox{
%        \begin{picture}(145,238)
%          \small
%          \put(0,33){
%            \linethickness{\thick}
%            \put(0,0){\framebox(145,205){}}
%            \linethickness{\thin}
%            \put(10,15){\dashbox(35,49){}}
%            \put(55,15){\dashbox(35,49){}}
%            \put(100,15){\dashbox(35,49){}}
%            \put(10,78){\dashbox(35,49){}}
%            \put(55,78){\dashbox(35,49){}}
%            \put(100,78){\dashbox(35,49){}}
%            \put(10,141){\dashbox(35,49){}}
%            \put(55,141){\dashbox(35,49){}}
%            \put(100,141){\dashbox(35,49){}}
%            \put(5,7){
%              \put(10,15){\framebox(35,49){}}
%              \put(55,15){\framebox(35,49){}}
%              \put(100,15){\framebox(35,49){}}
%              \put(10,78){\framebox(35,49){}}
%              \put(55,78){\framebox(35,49){}}
%              \put(100,78){\framebox(35,49){}}
%              \put(10,141){\framebox(35,49){}}
%              \put(55,141){\framebox(35,49){}}
%              \put(100,141){\framebox(35,49){}}
%              \put(45,36){\vector(1,0){10}}
%              \put(55,36){\vector(-1,0){10}}
%              \put(44.5,38){\textit{delx}}
%              \put(90,36){\vector(1,0){10}}
%              \put(100,36){\vector(-1,0){10}}
%              \put(89.5,38){\textit{delx}}
%              \put(27,64){\vector(0,1){14}}
%              \put(27,78){\vector(0,-1){14}}
%              \put(15,70){\textit{dely}}
%              \put(27,127){\vector(0,1){14}}
%              \put(27,141){\vector(0,-1){14}}
%              \put(15,133){\textit{dely}}
%            }
%            \put(10,15){\vector(1,0){5}}
%            \put(15,15){\vector(0,1){7}}
%            \put(8,8){\textit{offx}}
%            \put(17,17){\textit{offy}}
%          }
%
%          ^^A legend
%
%          \setlength{\fboxsep}{4pt}
%          \put(72.5,10){
%            \makebox(0,0){
%              \fbox{
%                \begin{tabular}{l@{\hskip20pt}l}
%                  \linethickness{\thick}^^A
%                  \raisebox{.8ex}{\line(1,0){5}} physical sheet of paper
%                  &
%                  |delta=|\meta{delx} \meta{dely}
%                  \\
%                  \linethickness{\thin}^^A
%                  \raisebox{.8ex}{\line(1,0){5}} logical pages
%                  &
%                  |offset=|\meta{offx} \meta{offy}
%                  \\
%                  \raisebox{.8ex}{\line(1,0){1}\hskip.55mm\line(1,0){1}
%                    \hskip.55mm\line(1,0){1}} centered position
%                  &
%                  \\
%                \end{tabular}
%              }}
%          }
%        \end{picture}
%        ^^A}% fbox
%      \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 |\includepdf|. 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.
%
%    \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{Hints for Users of platex}
%    \begin{itemize}
%      \item
%      The recommended way to tell |pdfpages| that you are using |platex| is to
%      add |dvipdfmx| as a class option, e.g.:
%
%      \begin{quote}
%        |\documentclass[dvipdfmx]{article}|\\
%        |\usepackage{pdfpages}|
%      \end{quote}
%
%      \item Pdfpages calls program |extractbb| to get the total number of
%      pages of a PDF.  But if an |xbb| file (output of |extractbb|) exists,
%      pdfpages will not call |extractbb| but use this file. However, be
%      very cautious with |xbb| files: \emph{Do not use |xbb| files for PDFs
%      with varying page sizes.} Because an |xbb| file contains only the page
%      size of a single page.
%    \end{itemize}
%
%
%    \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[atbegshi]
%            \texttt{CTAN:macros/latex/contrib/oberdiek/}
%      \item[pdflscape]
%            \texttt{CTAN:macros/latex/contrib/oberdiek/}
%      \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}{9}
%
%    \bibitem{pdftex}
%      H\`an Th\^e\llap{\raise 0.5ex\hbox{\'{}}} Th\`anh,
%      Sebastian Rahtz, Hans Hagen,
%      \textit{The \pdfTeX\ user manual},
%      \url{http://www.tug.org/applications/pdftex}
%
%    \bibitem{PDFRef}
%      \textit{PDF Reference}, Adobe Systems Incorporated,\\
%      \url{http://www.adobe.com/devnet/pdf/pdf_reference.html}
%
%    \bibitem{pax}
%      Heiko Oberdiek,
%      \textit{pax: Extract and reinsert PDF annotations with pdfTeX}
%      \url{http://www.ctan.org/pkg/pax}
%
%    \end{thebibliography}
%    }
%
%
%    \iffalse
%<*package>
%    \fi
%    \section{Implementation}
%
%    \subsection{Package Options}
%    \begin{macrocode}
\newif\ifAM@pkg@draft \AM@pkg@draftfalse
\DeclareOption{draft}{\AM@pkg@drafttrue}
\DeclareOption{final}{\AM@pkg@draftfalse}
\newif\ifAM@pkg@survey \AM@pkg@surveyfalse
\DeclareOption{enable-survey}{\AM@pkg@surveytrue}
\DeclareOption{disable-survey}{\AM@pkg@surveyfalse}
\newif\ifAM@pkg@demo \AM@pkg@demofalse
\DeclareOption{demo}{\AM@pkg@demotrue}
\DeclareOption{nodemo}{\AM@pkg@demofalse}
%    \end{macrocode}
%    |\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}
%    The configuration file |pdfpages.cfg| can be used to make
%    new driver files known to the package.
%    \begin{macrocode}
\InputIfFileExists{pdfpages.cfg}{%
  \PackageInfo{pdfpages}{Loading configuration file `pdfpages.cfg'}}{}
%    \end{macrocode}
%    These options overrule the automatic detection of the \TeX-engine.
%    \begin{macrocode}
\DeclareOption{pdftex}{\def\AM@driver{pdftex}}
\DeclareOption{luatex}{\def\AM@driver{luatex}}
\DeclareOption{vtex}{\def\AM@driver{vtex}}
\DeclareOption{xetex}{\def\AM@driver{xetex}}
\DeclareOption{dvips}{\def\AM@driver{dvips}}
\DeclareOption{dvipdfmx}{\def\AM@driver{dvipdfmx}}
\DeclareOption{null}{\def\AM@driver{null}}
%    \end{macrocode}
%    \begin{macrocode}
\ProcessOptions
%    \end{macrocode}
%    \subsection{Detection of TeX-Engine}
%
%    Automatic detection of \TeX-engine: \pdfTeX, \VTeX\ or \XeTeX.
%    This detection is omitted if |\AM@driver| is already defined. This
%    happens if the driver was given as a package option or if
%    the driver was identified in the configuration files |pdfpages.cfg|
%
%    \begin{macrocode}
\ifAM@pkg@demo
  \def\AM@driver{null}
\fi
\@ifundefined{AM@driver}{
  \begingroup
  \@ifundefined{luatexversion}{%
    \@ifundefined{pdftexversion}{%
      \@ifundefined{XeTeXversion}{%
        \@ifundefined{OpMode}{%
          \gdef\AM@driver{null}
        }{\gedf\AM@driver{vtex}}%
      }{\gdef\AM@driver{xetex}}%
    }{\gdef\AM@driver{pdftex}}%
  }{\gdef\AM@driver{luatex}}%
  \endgroup
}{}
%    \end{macrocode}
%    \subsection{Required Packages and Version Checking}
%
%    \begin{macrocode}
\RequirePackage{ifthen, calc, eso-pic}
%\@ifundefined{kansuji}{%
  \RequirePackage{graphicx}%
%}{%
%  \RequirePackage[dvipdfmx]{graphicx}%
%}
\newif\ifAM@DVIoutput\AM@DVIoutputfalse
\newdimen\AM@pagewidth
\newdimen\AM@pageheight
\newdimen\AM@fboxrule
\input{pp\AM@driver.def}
\ifx\AM@endinput\relax\expandafter\endinput\fi
\ifAM@pkg@survey
  \let\AM@setanchor\AM@anchor@special
  \RequirePackage{count1to}%
  \AddToShipoutPicture{\AM@setanchor}%
\fi
%    \end{macrocode}
%    We use |\PLS@Rotate| from |pdflscape| to ratate pages. But simply
%    loading |pdflscape| modifies the |landscape| environment such that
%    \emph{all} landscape pages are rotated by default which is undesired.
%    To prevent this we postpone the loading of the package.
%
%    If the user loads |pdflscape| explicitely she gets the rotated
%    landscape environment and the packages will not be reloaded by the next
%    commands.  However, if |pdflscape| is not loaded by the user, then we
%    load it and reset the |landscape| environment afterwards.
%    \begin{macrocode}
\AtBeginDocument{%
  \let\AM@orig@landscape\landscape
  \let\AM@orig@endlandscape\endlandscape
  \RequirePackage{pdflscape}%
  \let\landscape\AM@orig@landscape
  \let\endlandscape\AM@orig@endlandscape
}
%    \end{macrocode}
%    Let's save the original meaning of |\includegraphics|, because
%    graphicx.sty in demo mode (`demo' option) will overwrite the definition of
%    |\includegraphics| \emph{after} |\begin{document}|.
%    \begin{macrocode}
\let\AM@Ginclude@graphics\Ginclude@graphics
%    \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}}
 \let\Orig@AM@AddToShipoutPicture\AM@AddToShipoutPicture
%    \end{macrocode}
%    \subsection{Booleans}
%    \begin{macrocode}
\newif\ifAM@openright\AM@openrightfalse
\newif\ifAM@openrighteach\AM@openrighteachfalse
\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@duplicatepages\AM@duplicatepagesfalse
\newif\ifAM@linkfilename\AM@linkfilenamefalse
\newif\ifAM@signature\AM@signaturefalse
\newif\ifAM@signaturestar\AM@signaturestarfalse
\newif\ifAM@booklet\AM@bookletfalse
\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
\newif\ifAM@scale\AM@scaletrue
\newif\ifAM@newpage\AM@newpagefalse
%    \end{macrocode}
%    Check, if memoir is loaded.
%    \begin{macrocode}
\newif\ifAM@memoir\AM@memoirfalse
\@ifclassloaded{memoir}{\AM@memoirtrue}{}
%    \end{macrocode}
%    Pdfpages calls |\includegraphics| several times to retrieve necessary
%    information like width, height, or number of pages without actually
%    typesetting the image. Just the final call to |\includegraphics| will
%    eventually typeset the image.  Packages which hook into
%    |\includegraphics| and whish to check whether or not this is the final
%    call to |\includegraphics| can do so by using the counter
%    |\pdfpages@includegraphics@status|:
%    \begin{quotation}
%      \begin{tabular}{@{}cl@{}}
%             \toprule
%             Status & Use of |\includegraphics| ...\\
%             \midrule
%             0 & outside of pdfpages\\
%             1 & inside of pdfpages: final call\\
%             2 & inside of pdfpages: non-final call, for internal use\\
%             \bottomrule
%       \end{tabular}
%    \end{quotation}
%    \begin{macrocode}
\newcount\pdfpages@includegraphics@status
\pdfpages@includegraphics@status\z@
%    \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@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@checkinteger}
%    Check, if |#1| is a positive integer.
%    (Note: |\AM@checkinteger| was not reliable in older versions (<0.5n) of
%    this package. Let's use the definition from \emph{biblatex.sty} which seems
%    to be much better.)
%    \begin{macrocode}
\newif\ifAM@integer
\def\AM@checkinteger#1{%
  \expandafter\AM@checkinteger@\expandafter{#1}}
%    \end{macrocode}
%    \begin{macrocode}
\def\AM@checkinteger@#1{%
  \begingroup
  \def\do##1{\uccode`##1=`\%}%
  \do\0\do\1\do\2\do\3\do\4\do\5\do\6\do\7\do\8\do\9%
  \makeatletter
  \catcode`\%=9
  \endlinechar\m@ne
  \uppercase{\scantokens{\def\AM@temp{#1}}}%
  \ifx\AM@temp\@empty
    \global\AM@integertrue
  \else
    \global\AM@integerfalse
  \fi
  \endgroup}
%    \end{macrocode}
%    \macro{\AM@findfile}
%    Find file and set |\AM@currentdocname|.
%    \begin{macrocode}
\newcommand*{\AM@findfile@i}[2]{%
  \ifAM@pkg@demo
  \else
    \let\Ginclude@graphics\AM@Ginclude@graphics
  \fi
  \let\AM@currentdocname\relax
  \AM@IfFileExists{#1.#2}{\edef\AM@currentdocname{#1.#2}}{%
     \AM@IfFileExists{#1}{\edef\AM@currentdocname{#1}}{%
       \ifx\Ginput@path\@undefined\else
         \expandafter\@tfor\expandafter\AM@dir\expandafter
                   :\expandafter=\Ginput@path\do{%
           \AM@IfFileExists{\AM@dir#1.#2}{%
             \ifx\AM@currentdocname\relax
               \edef\AM@currentdocname{\AM@dir#1.#2}%
             \fi
           }{%
             \AM@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'}{}%
    \let\AM@filenotfound\relax
  \fi
}
%    \end{macrocode}
%    The options |width| and |height| (of graphics.sty) have no reasonable
%    meaning for |\includepdf|. Quit the contrary they spoil the calculation
%    of the scaling factors and therefore should not be used with pdfpages.
%
%    Nevertheless these options are very usefull for |\includegraphics| and
%    some users even set these options globally:
%
%    \setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
%
%    In this way these options have an undesirable impact on pdfpages as
%    well since pdfpages forwards these options to graphics. Therefore we
%    kind of disable these settings by inserting |width=!,height=!| into
%    |\AM@global@opts| which itself gets finally inserted into the option
%    list of each |\includegraphics| call.
%
%    \begin{macrocode}
\newtoks\AM@global@opts
\newcommand*{\AM@disable@width@height}{width=!,height=!}
\AM@global@opts\expandafter{\AM@disable@width@height}
%    \end{macrocode}
%    \macro{\includepdfset}
%    This command sets global options for |\includepdf|
%    and |\includepdfmerge|.
%    \begin{macrocode}
\newcommand*{\includepdfset}[1]{%
  \AM@global@opts\expandafter{\AM@disable@width@height,#1}%
}
%    \end{macrocode}
%    \macro{\includepdf}
%    This command inserts any pages of an external
%    \PDF\ document.
%    \begin{macrocode}
\newcommand*{\includepdf}[2][]{%
  \begingroup
  \global\pdfpages@includegraphics@status\tw@
  \@ifundefined{@setmarks}{\let\@setmarks\relax}{}
  \AM@pagecnt\@ne
  \let\AM@threadname\relax
  \def\AM@tmp{pdfpages}
  \expandafter\AM@split@options
    \expandafter\AM@tmp
    \expandafter{\the\AM@global@opts,#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}%
    \ifx\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}%
    \expandafter\AM@output\expandafter{\the\AM@global@opts,#1}%
  \fi
%    \end{macrocode}
%    \begin{macrocode}
  \AM@CheckAtEnd
  \endgroup
  \AM@ClearShipoutPicture
  \global\pdfpages@includegraphics@status\z@
}
%    \end{macrocode}
%    \macro{\includepdfmerge}
%    This command merges pages of several \PDF\ documents.
%    \begin{macrocode}
\newcommand*{\includepdfmerge}[2][]{%
  \begingroup
  \global\pdfpages@includegraphics@status\tw@
  \AM@pagecnt\@ne
  \let\AM@currentdocname\relax
  \def\AM@tmp{pdfpages}
  \expandafter\AM@split@options
    \expandafter\AM@tmp
    \expandafter{\the\AM@global@opts,#1}%
  \edef\AM@temp{{pdfpages}{\the\@temptokena}}%
  \expandafter\setkeys\AM@temp
  \AM@readlist{#2}%
  \expandafter\AM@output\expandafter{\the\AM@global@opts,#1}%
  \AM@CheckAtEnd
  \endgroup
  \AM@ClearShipoutPicture
  \global\pdfpages@includegraphics@status\z@
}
%    \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|.
%    Let's stop here if the PDF file doesn't exist and the user did not quit
%    \LaTeX\ yet (which may result from `--interaction=scrollmode`).
%    If we do not quit here, we might run into an infinite loop.
%    \begin{macrocode}
\newcommand\AM@output{%
  \ifdefined\AM@filenotfound
  \else
    \expandafter\AM@output@i
  \fi
}
\newcommand{\AM@output@i}[1]{%
%    \end{macrocode}
%    For the following calculations we need to know the page size.
%    But since we are still before |\newpage| we must not set |\paper{width,height}|
%    and must not call |\AM@setpagedimen| now. This shall be done after |\newpage|.
%    However, to get the calculation right we set and use |\AM@page{width,height}|,
%    which will eventually (after the next |\newpage|) become the real page size.
%    \begin{macrocode}
    \AM@getpagedimen
    \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}
%    Floats are unwanted here. Thus defer all floats until after |\includepdf|.
%    \par
%    1) Floats which are already in \LaTeX's output routine shall be removed from
%    there and pushed onto |\@deferlist| or |\@dbldeferlist|.
%    \begin{macrocode}
  \xdef\@deferlist{\@toplist\@botlist\@deferlist}%
  \gdef\@toplist{}%
  \gdef\@botlist{}%
  \xdef\@dbldeferlist{\@dbltoplist\@dbldeferlist}%
  \gdef\@dbltoplist{}%
%    \end{macrocode}
%    2) Clear |\@deferlist| and |\@dbldeferlist|. But save them first
%    so they can be restored later.
%    \begin{macrocode}
  \global\let\AM@deferlist\@deferlist
  \gdef\@deferlist{}%
  \global\let\AM@dbldeferlist\@dbldeferlist
  \gdef\@dbldeferlist{}%
%    \end{macrocode}
%    Some drivers, like |ppnull|, need a hook to disable
%    |\includegraphics|.
%    \begin{macrocode}
  \AM@disable@includegraphics
%    \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{-\AM@fboxrule}\def\AM@deltay{-\AM@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}
%    \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}\and\not\boolean{AM@openrighteach}}
         {\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}}%
         {\global\let\AM@fbox\fbox
          \setlength\AM@fboxrule{\fboxrule}}%
         {\global\let\AM@fbox\relax
          \setlength\AM@fboxrule{\z@}}%
  \ifthenelse{\boolean{AM@reflect}}%
         {\global\let\AM@reflectbox\reflectbox}%
         {\global\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}
%    Determine scaling factor:
%    The logical pages are scaled such, that they match on
%    one sheet of paper.
%    \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@}%
  \AM@isphantom
  \ifAM@noautoscale
    \def\AM@globalscale{1}%
  \else
    \AM@split@options{Gin@noscale}{#1}%
    \let\AM@filelist@save\@filelist
    \ifAM@DVIoutput
      \setbox\@tempboxa=\hbox{\rule{597pt}{845pt}}%
    \else
      \ifAM@templatesize
        \setbox\@tempboxa=\hbox{%
          \rotatebox{\AM@lscape@rot}{\copy\AM@templatesizebox}}%
      \else
        \edef\AM@opts{[\AM@disable@width@height,\the\@temptokena,
                       page=\AM@page, angle=\AM@lscape@rot]}%
        \setbox\@tempboxa=\hbox{%
          \expandafter\includegraphics\AM@opts{\AM@docname}}%
      \fi
    \fi
%    \end{macrocode}
%    Fit papersize.
%    \begin{macrocode}
    \ifthenelse{\boolean{AM@fitpaper}}{
      \setlength{\AM@pagewidth}{\wd\@tempboxa}%
      \setlength{\AM@pageheight}{\ht\@tempboxa + \dp\@tempboxa}%
    }{}%
%    \end{macrocode}
%    Calculate required scaling in horizontal direction.
%    \begin{macrocode}
    \def\AM@xscale{%
      (\AM@pagewidth - \tw@\AM@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{
      (\AM@pageheight - \tw@\AM@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}%
  \ifAM@templatesize
    \setbox\@tempboxa=\hbox{%
      \scalebox{\AM@scale@factor}{\copy\AM@templatesizebox}}%
    \setbox\@tempboxa=\hbox{%
      \scalebox{\AM@globalscale}{\copy\@tempboxa}}%
    \setbox\@tempboxa=\hbox{%
      \rotatebox{\AM@lscape@rot}{\copy\@tempboxa}}%
  \else
    \edef\AM@opts{[\AM@disable@width@height,\the\@temptokena,
                   page=\AM@page, scale=\AM@globalscale,
                   angle=\AM@lscape@rot]}%
    \setbox\@tempboxa=\hbox{%
      \expandafter\includegraphics\AM@opts{\AM@docname}}%
  \fi
  \let\@filelist\AM@filelist@save
  \edef\AM@templatewidth{\the\wd\@tempboxa}%
  \setlength{\@tempdima}{\ht\@tempboxa + \dp\@tempboxa}%
  \edef\AM@templateheight{\the\@tempdima}%
  \setlength{\@tempdimb}{\ht\@tempboxa + \dp\@tempboxa}%
  \def\AM@xmargin{%
    (\AM@pagewidth - (\wd\@tempboxa+\tw@\AM@fboxrule)*\AM@xnup
     - \AM@deltax * \AM@xnupminusi) * \real{.5}%
  }%
  \def\AM@ymargin{%
    (\AM@pageheight - (\@tempdimb+\tw@\AM@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}%
  \clearpage
  \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}%
         \AM@newpagetrue
       \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}%
         \AM@newpagetrue
       \fi
      }%
%    \end{macrocode}
%    \begin{macrocode}
     \ifAM@newpage
       \clearpage
       \AM@newpagefalse
     \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}
    \edef\AM@opts{[\AM@disable@width@height,\the\@temptokena,
                   page=\AM@page, scale=\AM@globalscale,
                   angle=\AM@lscape@rot]}%
    \setbox\@tempboxa=\hbox{%
      \expandafter\includegraphics\AM@opts{\AM@docname}}%
    \edef\AM@localwd{\the\wd\@tempboxa}%
    \setlength{\@tempdima}{\ht\@tempboxa + \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
          \edef\AM@opts{[\AM@disable@width@height,\the\@temptokena,
                        page=\AM@page, scale=\AM@globalscale,
                        angle=\AM@lscape@rot, angle=90]}%
          \setbox\@tempboxa=\hbox{%
            \expandafter\includegraphics\AM@opts{\AM@docname}}%
          \let\@filelist\AM@filelist@save
          \edef\AM@localwd{\the\wd\@tempboxa}%
          \setlength{\@tempdima}{\ht\@tempboxa + \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}
%    The above calculation are wrong if |noautoscale| is used.
%    Thus reset values here.
%    \begin{macrocode}
    \ifAM@noautoscale
      \def\AM@localxoff{\z@}%
      \def\AM@localyoff{\z@}%
      \def\AM@localscale{1}%
    \fi
%    \end{macrocode}
%    \begin{macrocode}
    \let\AM@filelist@save\@filelist
    \AM@split@options{Gin}{#1}%
    \edef\AM@opts{[\AM@disable@width@height,\the\@temptokena,
                   page=\AM@page, scale=\AM@globalscale,
                   angle=\AM@lscape@rot]}%
    \setbox\@tempboxa=\hbox{%
      \expandafter\includegraphics\AM@opts{\AM@docname}}%
    \let\@filelist\AM@filelist@save
    \setlength{\@tempdimc}{\ht\@tempboxa + \dp\@tempboxa}%
%    \end{macrocode}
%    Eso-pic set the origin of the coordinate system by default to the
%    lower left corner which is what pdfpages assumes. However, with the
%    option |texcoord| eso-pic sets the origin to the upper left corner.
%    Let's take care of this.
%    \begin{macrocode}
    \edef\AM@texcoord{%
      \ifESO@texcoord
        -\AM@pageheight
      \else
         \z@
      \fi
    }%
%    \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@\AM@fboxrule) *
         (\AM@ynupi - 1)
       }%
       \def\AM@ypos{%
         \AM@texcoord +
         \AM@ymargin + \AM@yoffset + \AM@localyoff +
         (\AM@templateheight + \AM@deltay + \tw@\AM@fboxrule) *
         (\AM@xnupi - 1)
       }%
      }
      {\def\AM@xpos{%
         \AM@xmargin \AM@add\AM@xoffset + \AM@localxoff +
         (\AM@templatewidth + \AM@deltax + \tw@\AM@fboxrule) *
         (\AM@xnupi - 1)
       }%
       \def\AM@ypos{%
         \AM@texcoord +
         \AM@ymargin + \AM@yoffset + \AM@localyoff +
         (\AM@templateheight + \AM@deltay + \tw@\AM@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}%
%    \end{macrocode}
%    Calculate |fitr| coordinates, if |linkfit=region|.
%    \begin{macrocode}
     \AM@region@calc
%    \end{macrocode}
%    Ship out page.
%    \begin{macrocode}
    \ifnum\AM@xnupi=1
      \ifnum\AM@ynupi=1
        \ifAM@reflectall \setbox\AM@pagebox\null \fi
      \fi
    \fi
    \ifAM@phantompage
      \def\AM@shippage{}%
    \else
      \AM@split@options{Gin}{#1}%
        \edef\AM@opts{[\AM@disable@width@height,\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]}%
      \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}
        \global\pdfpages@includegraphics@status\@ne
        \fboxsep=\z@
        \AM@hyper@begin@ii\noexpand\AM@fbox{%
          \noexpand\AM@ARBug@hook
          \noexpand\AM@reflectbox{%
            \expandafter\noexpand\expandafter
            \includegraphics\AM@opts{\AM@docname}}}%
        \global\pdfpages@includegraphics@status\tw@
        \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}
%    Adjust paper size:
%    After |\newpage| we may finally set |\paper{width,height}| and call
%    |\AM@setpagedimen|.
%    \begin{macrocode}
    \ifthenelse{\boolean{AM@fitpaper}}{
      \setlength{\paperwidth}{\AM@pagewidth}%
      \setlength{\paperheight}{\AM@pageheight}%
      \AM@fitpaper@special
      \AM@setpagedimen
      \ifAM@memoir
        \setlength{\stockwidth}{\AM@pagewidth}%
        \setlength{\stockheight}{\AM@pageheight}%
        \setlength{\trimtop}{0pt}%
        \setlength{\trimedge}{0pt}%
      \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}
%    \begin{macrocode}
    \if@twocolumn
      \@twocolumnfalse
      \let\AM@twocolumn\relax
    \fi
%    \end{macrocode}
%    |\AM@pagebox| is only used 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}\AND\boolean{AM@landscape}}{%
          \AM@setRotate
        }{}%
        \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
%    \end{macrocode}
%    When creating signatures, every second page must be rotated
%    by $180^{\circ}$ and therefore the xoffset must be multiplied
%    by $-1$.
%    \begin{macrocode}
        \ifAM@signature
          \ifAM@sigrotate\AM@sigrotatefalse\else\AM@sigrotatetrue\fi
          \@tempdima=\AM@xoffset\relax
          \multiply\@tempdima\m@ne
          \edef\AM@xoffset{\the\@tempdima}%
        \fi
      \fi
    \fi
%    \end{macrocode}
%    \begin{macrocode}
  }% whiledo
  \global\let\@deferlist\AM@deferlist
  \global\let\@dbldeferlist\AM@dbldeferlist
  \ifx\AM@twocolumn\relax
    \@twocolumntrue
    \@firstcolumnfalse
  \fi
  \newpage
  \ifthenelse{\boolean{AM@turn}\AND\boolean{AM@landscape}}{%
    \AM@resetRotate
  }{}
}% AM@output
%    \end{macrocode}
%    \macro{\AM@readlist}
%    \macro{\AM@readlisti}
%    \macro{\AM@range@or@docname}
%    \macro{\AM@checkrange}
%    \macro{\AM@expand@range}
%    \macro{\AM@check@valid@pagenumber}
%    \macro{\AM@strip@slash}
%    \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
%    separate page numbers) and |\AM@doclist| which contains
%    the document names; one name for each page number in
%    |\AM@pagelist|.
%    \begin{macrocode}
\newif\ifAM@default@range@added
\newcommand*{\AM@readlist}[1]{%
  \AM@default@range@addedtrue
  \def\AM@pagelist{}%
  \def\AM@doclist{}%
  \AM@readlisti#1,\END,
  \AM@add@default@range
  \edef\AM@doclist{\expandafter\@gobble\AM@doclist\@empty}%
  \edef\AM@pagelist{\expandafter\@gobble\AM@pagelist\@empty}%
}
%    \end{macrocode}
%    \begin{macrocode}
\def\AM@add@default@range{%
  \ifAM@default@range@added
  \else
    \expandafter\AM@read@defaultpages\AM@pagestemp,\END,
  \fi
  \AM@default@range@addedtrue
}
%    \end{macrocode}
%    \begin{macrocode}
\def\AM@read@defaultpages#1,{%
  \ifx\END#1
  \else
    \edef\AM@x{\AM@trim@space{#1}}%
    \ifx\AM@x\@empty
      \AM@append{}%
      \AM@ReturnAfterElseFiFi\AM@read@defaultpages
    \else
      \expandafter\AM@checkrange\AM@x-\END
      \AM@expand@range\AM@i\AM@ii
      \AM@ReturnAfterFiFi\AM@read@defaultpages
    \fi
  \fi
}
%    \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@range@or@docname{#1}%
    \expandafter\AM@readlisti
  \fi
}
%    \end{macrocode}
%    \begin{macrocode}
\def\AM@range@or@docname#1{%
  \edef\AM@arg{\AM@trim@space{#1}}%
  \ifx\AM@arg\@empty
    \AM@append{}%
  \else
    \expandafter\AM@checkrange\AM@arg-\END
    \ifAM@isrange
      \ifx\AM@currentdocname\relax
        \AM@setnewdocname{\AM@arg}%
      \else
        \AM@expand@range\AM@i\AM@ii
        \AM@default@range@addedtrue
      \fi
    \else
      \AM@add@default@range
      \AM@setnewdocname{\AM@arg}%
    \fi
  \fi
}
%    \end{macrocode}
%    \begin{macrocode}
\def\AM@last{last}
\def\AM@empty{}
\newif\ifAM@isrange
%    \end{macrocode}
%    \begin{macrocode}
\def\AM@checkrange#1-#2\END{%
  \AM@israngefalse
  \AM@check@valid@pagenumber{#1}%
  \ifx\\#1\\%
    \def\AM@i{1}%
  \else
    \edef\AM@i{#1}%
  \fi
  \def\AM@ii{}%
  \ifAM@isrange
    \ifx\\#2\\%
    \else
      \edef\AM@ii{\AM@strip@slash#2\END}%
      \AM@check@valid@pagenumber{\AM@ii}%
      \ifx\AM@ii\AM@empty
        \let\AM@ii\AM@last
      \fi
    \fi
  \fi
}
%    \end{macrocode}
%    \begin{macrocode}
\def\AM@expand@range#1#2{%
  \edef\AM@i{#1}%
  \edef\AM@ii{#2}%
  \ifx\AM@i\AM@last
    \let\AM@i\AM@lastpage
    \let\AM@i\AM@pagecount
  \fi
  \ifx\AM@ii\AM@last
    \let\AM@ii\AM@lastpage
    \let\AM@ii\AM@pagecount
  \fi
  \ifx\AM@ii\AM@empty
    \let\AM@ii\AM@i
  \fi
  \@tempcnta=\AM@i\relax
  \@tempcntb=\AM@ii\relax
  \ifnum\@tempcnta<\@tempcntb
    \def\AM@rel{<}%
    \let\AM@inc\@ne
  \else
    \def\AM@rel{>}%
    \let\AM@inc\m@ne
  \fi
  \advance\@tempcntb\AM@inc
  \whiledo{\@tempcnta\AM@rel\@tempcntb}{%
    \AM@checkpagenumber{\the\@tempcnta}%
    \AM@append{\the\@tempcnta}%
    \advance\@tempcnta\AM@inc
  }%
}
%    \end{macrocode}
%    \begin{macrocode}
\def\AM@check@valid@pagenumber#1{%
  \AM@checkinteger{#1}%
  \ifAM@integer
    \AM@israngetrue
  \else
    \AM@israngefalse
  \fi
  \edef\AM@tmp{#1}%
  \ifx\AM@tmp\AM@last
    \AM@israngetrue
  \fi
}
%    \end{macrocode}
%    \begin{macrocode}
\def\AM@strip@slash#1-#2\END{%
  \ifx\\#2\\%
    #1%
  \else
    #1-#2%
  \fi
}
%    \end{macrocode}
%    \begin{macrocode}
\providecommand*{\AM@checkpagenumber}[1]{%
  \ifnum#1>\AM@pagecount\relax
    \ifthenelse{\boolean{AM@pkg@draft} \and \boolean{AM@survey}}{%
    }{%
      \PackageError{pdfpages}
        {Page #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@openrighteach
    \ifodd\AM@pagecnt
      \AM@append{}
    \fi
  \fi
  \AM@add@default@range
  \edef\AM@temp{\AM@trim@space{#1}}%
  \AM@findfile{\AM@temp}%
  \AM@default@range@addedfalse
}
%    \end{macrocode}
%    \begin{macrocode}
\newcount\AM@pagecnt
\newcommand*{\AM@append}[1]{%
  \advance\AM@pagecnt\@ne
  \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
  \ifAM@duplicatepages
    \count@=0
    \loop
    \advance\count@ 1
    \ifnum\count@<\AM@nduplicatepages
    \edef\AM@doclist{\AM@doclist,\AM@currentdocname}%
    \edef\AM@pagelist{\AM@pagelist,#1}%
    \repeat
  \fi
}
%    \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}
\def\AM@ReturnAfterFiFi#1\fi\fi{\fi\fi#1}
\def\AM@ReturnAfterElseFiFi#1\else#2\fi#3\fi{\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@split@firstn}
%    Removes the first |n=#2| items from the cvs=list, which
%    is specified by the name of a macro in |#1|. These |n|
%    items are split into two lists with the names |#1@firstn|
%    and |#1@lastn|. The latter one is sorted backwards. This
%    is needed for a faster processing of the |signature| option.
%    \begin{macrocode}
\newcommand{\AM@split@firstn}{}
\def\AM@split@firstn#1#2{%
  \edef\AM@tmp{\expandafter\@gobble\string#1@firstn}%
  \AM@getfirst{#1}%
  \expandafter\edef\csname\AM@tmp\endcsname{\the\toks@}%
  \@tempcnta=\@ne
  \@tempcntb=#2 \divide\@tempcntb\tw@
  \loop\ifnum\@tempcnta<\@tempcntb
    \AM@getfirst{#1}%
    \expandafter\edef\csname\AM@tmp\endcsname
        {\@nameuse{\AM@tmp},\the\toks@}%
    \advance\@tempcnta\@ne
  \repeat
  \edef\AM@tmp{\expandafter\@gobble\string#1@lastn}%
  \AM@getfirst{#1}%
  \expandafter\edef\csname\AM@tmp\endcsname{\the\toks@}%
  \@tempcnta=\@ne
  \loop\ifnum\@tempcnta<\@tempcntb
    \AM@getfirst{#1}%
    \expandafter\edef\csname\AM@tmp\endcsname
        {\the\toks@,\@nameuse{\AM@tmp}}%
    \advance\@tempcnta\@ne
  \repeat
}
%    \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@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}%
  \def\AM@scale@factor{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{page}{\AM@temp}\or
              \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{openrighteach}{\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{duplicatepages}{\AM@temp}\or
              \equal{signature}{\AM@temp}\or
              \equal{signature*}{\AM@temp}\or
              \equal{booklet}{\AM@temp}\or
              \equal{pagetemplate}{\AM@temp}\or
              \equal{templatesize}{\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}\or
              \equal{lastpage}{\AM@temp}}
             {\AM@pdfpages@optionstrue}{}%
  \ifthenelse{\equal{scale}{\AM@temp}}{%
    \AM@scaletrue
    \def\AM@ooo##1={##1}%
    \setlength{\@tempdima}{\p@ * \AM@scale@factor * \real{\AM@ooo#2}}%
    \edef\AM@scale@factor{\strip@pt\@tempdima}%
  }{}%
}
%    \end{macrocode}
%    \macro{\AM@trim@space}
%    \macro{\AM@trim@spacei}
%    \macro{\AM@trim@spaceii}
%    Removes leading and trailing spaces.
%    \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}
%    Removes leading space.
%    \begin{macrocode}
\DeclareRobustCommand{\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}
%    Calculate value of |\AM@signature| for option |booklet|.
%    \begin{macrocode}
  \ifAM@booklet
    \AM@countpagelist
    \@tempcntb=\@tempcnta
    \divide\@tempcnta by 4
    \multiply\@tempcnta by 4
    \advance\@tempcntb-\@tempcnta
    \ifnum\@tempcntb=0\else \advance\@tempcnta by 4\fi
    \edef\AM@signature{\the\@tempcnta}%
  \fi
%    \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{}%
    \AM@split@firstn{\AM@pagelist}{\AM@signature}%
    \AM@split@firstn{\AM@doclist}{\AM@signature}%
    \def\AM@first{%
      \AM@getfirst{\AM@pagelist@firstn}%
      \edef\AM@sigpagelist{\AM@sigpagelist,\the\toks@}%
      \AM@getfirst{\AM@doclist@firstn}%
      \edef\AM@sigdoclist{\AM@sigdoclist,\the\toks@}%
    }%
    \def\AM@last{%
      \AM@getfirst{\AM@pagelist@lastn}%
      \edef\AM@sigpagelist{\AM@sigpagelist,\the\toks@}%
      \AM@getfirst{\AM@doclist@lastn}%
      \edef\AM@sigdoclist{\AM@sigdoclist,\the\toks@}%
    }%
    \@tempcnta=\z@
    \@tempcntb=\AM@signature\relax
    \whiledo{\@tempcnta<\@tempcntb}{%
      \ifAM@landscape
        \ifAM@signaturestar
          \AM@first\AM@last\AM@first\AM@last
        \else
          \AM@last\AM@first\AM@last\AM@first
        \fi
      \else
        \ifAM@signaturestar
          \AM@last\AM@first\AM@last\AM@first
        \else
          \AM@first\AM@last\AM@first\AM@last
        \fi
      \fi
      \advance\@tempcnta by 4
    }%
    \edef\AM@newpagelist{\AM@newpagelist\AM@sigpagelist}%
    \edef\AM@newdoclist{\AM@newdoclist\AM@sigdoclist}%
    \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}
  \AM@pagesize@boogie
  \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
  \def\ch@pt@c{\the\AM@toc@title}% memoir 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{\leavevmode\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{%
  \edef\AM@toc@page{\AM@trim@space{#1}}%
  \edef\AM@toc@section{\AM@trim@space{#2}}%
  \edef\AM@toc@level{\AM@trim@space{#3}}%
  \AM@toc@title{\ignorespaces #4}%
  \edef\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{}%
  \def\@fs@capt##1##2{}% float.sty
  \AM@addtolist@hook
  \@ifundefined{hyper@@anchor}{%
    \expandafter\caption\expandafter{\the\AM@lof@heading}%
  }{%
    \hyper@makecurrent{\@captype}%
    \expandafter\caption\expandafter{\the\AM@lof@heading}%
    \hyper@@anchor{\@currentHref}{\relax}%
    \let\Hy@float@currentHref\@undefined
  }%
  \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}
\newtoks\AM@lof@heading
\newcommand{\AM@parse@loflisti}{}
\def\AM@parse@loflisti#1,#2,#3,#4,#5\END{%
  \edef\AM@lof@page{\AM@trim@space{#1}}%
  \edef\AM@lof@list{\AM@trim@space{#2}}%
  \AM@lof@heading{\ignorespaces #3}%
  \edef\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}
%    \begin{macrocode}
\def\AM@CheckValue#1#2{%
  \ifx\\#2\\\PackageError{pdfpages}
             {Option `#1' must have a non-empty value}{}%
  \fi
}
%    \end{macrocode}
%    \subsection{Options of \texttt{\protect\bslash includepdf}}
%    \begin{macrocode}
\define@key{pdfpages}{page}{\PackageWarningNoLine{pdfpages}{%
    Option `page' is unknow to \string\includepdf.\MessageBreak
    Did you mean `pages'? (Note the `s'!)\MessageBreak
    OK, I'll proceed as if it were `pages'}%
  \AM@CheckValue{pages}{#1}%
  \def\AM@pagestemp{#1}}
\define@key{pdfpages}{pages}{\AM@CheckValue{pages}{#1}%
                             \edef\AM@pagestemp{#1}}
\define@key{pdfpages}{nup}{\expandafter\AM@parse@nup\expanded{#1}x\END}
\define@key{pdfpages}{deltax}{\expandafter\AM@parse@deltax\expanded{#1} \\}
\define@key{pdfpages}{deltay}{\expandafter\AM@parse@deltay\expanded{#1} \\}
\define@key{pdfpages}{delta}{\expandafter\AM@parse@delta\expanded{#1} \\}
\define@key{pdfpages}{offset}{\expandafter\AM@parse@offset\expanded{#1} \\}
\define@key{pdfpages}{frame}[true]{\setboolean{AM@frame}{#1}}
\define@key{pdfpages}{openright}[true]{\setboolean{AM@openright}{#1}}
\define@key{pdfpages}{openrighteach}[true]{\setboolean{AM@openrighteach}{#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}{\edef\AM@threadname{#1}}
\define@key{pdfpages}{link}[true]{\setboolean{AM@link}{#1}}
\define@key{pdfpages}{linkfit}{\expandafter\AM@convert@dest\expanded{{#1}}}
\define@key{pdfpages}{linkname}{\edef\AM@linkname@option{#1}}
\define@key{pdfpages}{linktodoc}[true]{\setboolean{AM@linktodoc}{#1}}
\define@key{pdfpages}{linktodocfit}{\edef\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}{\edef\AM@xrprefix{#1}}
\define@key{pdfpages}{fitpaper}[true]{\setboolean{AM@fitpaper}{#1}}
\define@key{pdfpages}{addtotoc}{\protected@edef\AM@toclist{#1,}}
\define@key{pdfpages}{addtolist}{\protected@edef\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}{duplicatepages}[2]%
                     {\edef\AM@nduplicatepages{#1}%
                      \AM@duplicatepagestrue}
\define@key{pdfpages}{signature}{\edef\AM@signature{#1}}
\define@key{pdfpages}{signature*}{\edef\AM@signature{#1}%
                                  \AM@signaturestartrue}
\define@key{pdfpages}{booklet}[true]{\setboolean{AM@booklet}{#1}%
                                     \def\AM@signature{x}}
\define@key{pdfpages}{pagetemplate}{\AM@CheckValue{pagetemplate}{#1}%
                                    \def\AM@pagetemplate{#1}}
\define@key{pdfpages}{templatesize}{\expandafter\AM@parse@templatesize\expanded{#1}\END}
\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}}
\define@key{pdfpages}{lastpage}{\edef\AM@pagecount{#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@templatesize}
%    Parsing \texttt{templatesize} item.
%    \begin{macrocode}
\newcommand{\AM@parse@templatesize}{}
\def\AM@parse@templatesize#1#2\END{%
  \setbox\AM@templatesizebox=\hbox{\rule{#1}{#2}}%
  \AM@templatesizetrue
}
\newbox\AM@templatesizebox
\newif\ifAM@templatesize\AM@templatesizefalse
%    \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>
%    \fi
%
%    \subsection{Driver files}
%
%    \subsubsection{\pdfTeX\ and \luaTeX\ drivers}
%
%    The driver file for \pdfTeX\ and \luaTeX\ are mostly the same.
%    So far they only differ in checking of the version numbers of
%    the \TeX-engines and graphicx driver files.
%
%    Check \pdfTeX\ version.
%    \begin{macrocode}
%<*pppdftexdef>
\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
%</pppdftexdef>
%    \end{macrocode}
%    Starting with LuaTeX 0.85 quite a few primitives have been renamed
%    and/or removed. To cope with these changes we have to provide both
%    primitive names depending on which version we are running.
%    \begin{macrocode}
%<*(pppdftexdef,ppluatexdef)>
%<*ppluatexdef>
\ifnum\luatexversion<85
%</ppluatexdef>
  \let\AM@outputmode\pdfoutput
  \let\AM@saveimageresource\pdfximage
  \let\AM@lastsavedimageresourcepages\pdflastximagepages
  \let\AM@luatexpagewidth\pdfpagewidth
  \let\AM@luatexpageheight\pdfpageheight
  \let\AM@annotation\pdfannot
  \let\AM@thread\pdfthread
  \let\AM@destination\pdfdest
%<*ppluatexdef>
\else
  \let\AM@outputmode\outputmode
  \let\AM@saveimageresource\saveimageresource
  \let\AM@lastsavedimageresourcepages\lastsavedimageresourcepages
  \let\AM@luatexpagewidth\pagewidth
  \let\AM@luatexpageheight\pageheight
  \protected\def\AM@annotation {\pdfextension annot }%
  \protected\def\AM@thread {\pdfextension thread }%
  \protected\def\AM@destination {\pdfextension dest }%
\fi
%</ppluatexdef>
%</(pppdftexdef,ppluatexdef)>
%    \end{macrocode}
%    Insert dummy driver |ppnull.def| if we are not running in PDF mode.
%    \begin{macrocode}
%<*pppdftexdef>
\ifcase\pdfoutput
  \input{ppnull.def}
  \expandafter\endinput
\fi
%</pppdftexdef>
%<*ppluatexdef>
\ifcase\AM@outputmode
  \input{ppnull.def}
  \expandafter\endinput
\fi

%</ppluatexdef>
%    \end{macrocode}
%    Check if the graphics package was loaded with an
%    incompatible driver option (e.g. dvips).
%    \begin{macrocode}
%<*pppdftexdef>
\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'}}
%</pppdftexdef>
%    \end{macrocode}
%
%    Get last page number.
%
%    \noindent
%    Note: Do not use |\pdfximage| directly. This compromises packages which
%    manipulate the input path of graphicx.sty.
%
%    Unfortunately, |\pdflastximagepages| is not updated if |\includegraphics|
%    is used repeatedly on the same file. Heiko is aware of this and will provide
%    a solution in pdftex.def. Until then we will use the original graphicx's filename
%    from |\Gread@@pdftex|.
%
%    \def\AM@getpagecount{%
%      \setbox\@tempboxa=\hbox{\includegraphics{\AM@currentdocname}}%
%      \edef\AM@pagecount{\the\AM@lastsavedimageresourcepages}%
%    }
%
%    \begin{macrocode}
%<*(pppdftexdef,ppluatexdef)>
\let\AM@Gread@@pdftex\Gread@@pdftex
\renewcommand*{\Gread@@pdftex}[1]{%
  \xdef\AM@currentdocname@fix{#1}%
  \AM@Gread@@pdftex{#1}%
}
\def\AM@getpagecount{%
  \setbox\@tempboxa=\hbox{\includegraphics{\AM@currentdocname}}%
  \AM@saveimageresource{\AM@currentdocname@fix}%
  \edef\AM@pagecount{\the\AM@lastsavedimageresourcepages}%
}
%    \end{macrocode}
%    Page dimensions.
%    \begin{macrocode}
\def\AM@getpagedimen{%
  \AM@pagewidth=\paperwidth
  \AM@pageheight=\paperheight
}
\def\AM@setpagedimen{%
  \AM@luatexpagewidth\AM@pagewidth
  \AM@luatexpageheight\AM@pageheight
}
\let\AM@pagesize@boogie\relax
%    \end{macrocode}
%    Change paper size.
%    \begin{macrocode}
\let\AM@fitpaper@special\relax
%    \end{macrocode}
%    Find file.
%
%    Package grffile.sty is a dummy package nowadays, and |\grffile@IfFileExists|
%    doesn't exists anymore. (21.11.2019)
%    \begin{macrocode}
\def\AM@findfile#1{%
  \AM@findfile@i{#1}{pdf}%
  \AM@findfile@ii{#1}%
}
\AtBeginDocument{%
  \let\AM@IfFileExists\IfFileExists
  \@ifpackageloaded{grffile}{%
    \@ifundefined{grffile@IfFileExists}{}{%
      \let\AM@IfFileExists\grffile@IfFileExists}%
  }{}%
}
%    \end{macrocode}
%    Rotate page.
%    Use new pdfmanagement macros if available, and fallback to pdflscape
%    if they are not available.
%    \begin{macrocode}
\ExplSyntaxOn
\@ifundefined{pdfmanagement_add:nnn}{%
  \def\AM@setRotate{\PLS@Rotate{90}}%
  \def\AM@resetRotate{\PLS@Rotate{0}}%
}{%
  \def\AM@setRotate{\pdfmanagement_add:nnn{ThisPage}{Rotate}{90}}%
  \def\AM@resetRotate{}%
}%
\ExplSyntaxOff
%    \end{macrocode}
%    Link to original document.
%    \begin{macrocode}
\def\AM@linktodoc@special@begin{%
    \AM@annotation 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{%
    \AM@annotation 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{%
      \AM@thread width \wd\@tempboxa
                 height \ht\@tempboxa
                 depth \dp\@tempboxa
                 attr {/I <<\threadinfodict>>}%
                 name {\AM@threadname}%
}
\let\AM@thread@special@end\relax
%    \end{macrocode}
%    Destination of links.
%    \begin{macrocode}
\def\AM@view{fit}
\def\AM@dest@special{\AM@destination name {\AM@linkname.\AM@page} \AM@view}
\def\AM@anchor@special{\AM@destination name {pdfpages.\the\count1} fit}
%    \end{macrocode}
%    Convert synatx of \PDF\ destinations.
%    \pdfTeX\ does not support positional parameters to |fith| etc.
%    \begin{macrocode}
\def\AM@convert@dest#1{%
  \expandafter\AM@convert@dest@i\ifdim\z@=0pt#1 \END\fi}
\def\AM@convert@dest@i#1 #2\END{%
  \begingroup
  \def\tag{#1}%
  \def\x{FitH}%
  \ifx\x\tag
    \gdef\AM@view{fith}%
  \else
    \def\x{FitBH}%
    \ifx\x\tag
      \gdef\AM@view{fitbh}%
    \else
      \def\x{FitV}%
      \ifx\x\tag
        \gdef\AM@view{fitv}%
      \else
        \def\x{FitBV}%
        \ifx\x\tag
          \gdef\AM@view{fitbv}%
        \else
          \def\x{FitR}%
          \ifx\x\tag
            \gdef\AM@view{fitr}%
            \PackageWarningNoLine{pdfpages}{%
              `linkfit=FitR' is not supported,
              I will try `linkfit=Region'.}%
            \def\tag{region}%
          \else
            \def\x{FitB}%
            \ifx\x\tag
              \gdef\AM@view{fitb}%
            \else
              \def\x{XZY}%
              \ifx\x\tag
                \gdef\AM@view{xyz zoom #2}%
              \else
                \def\x{Region}%
                \ifx\x\tag
                  \gdef\AM@view{fitr
                                width\the\wd\@tempboxa\space
                                height0pt depth\AM@region@depth}%
                \else
                  \gdef\AM@view{fit}%
                \fi
              \fi
            \fi
          \fi
        \fi
      \fi
    \fi
  \fi
  \endgroup
}
\def\AM@region@calc{%
  \setlength{\@tempdima}{\ht\@tempboxa + \dp\@tempboxa}%
  \edef\AM@region@depth{\the\@tempdima}%
}
%    \end{macrocode}
%    Do not disable |\includegraphics|.
%    \begin{macrocode}
\let\AM@disable@includegraphics\relax
%    \end{macrocode}
%
%    \iffalse
%</(pppdftexdef,ppluatexdef)>
%
%<*ppvtexdef>
%    \fi
%
%    \subsubsection{\VTeX\ driver}
%
%    Check if the graphics package was loaded with an
%    incompatible driver option (e.g. dvips).
%    \begin{macrocode}
\begingroup
\@ifundefined{ver@vtex.def}{%
  \PackageError{pdfpages}
         {The graphics package was loaded with driver\MessageBreak
          `\Gin@driver', which cannot be used with VTeX}
         {Check the driver option of the graphics package.}%
  \global\let\AM@endinput\relax
  \aftergroup\endinput}{}
\endgroup
%    \end{macrocode}
%    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}
\def\AM@getpagedimen{%
  \AM@pagewidth=\mediawidth
  \AM@pageheight=\mediaheight
}
\def\AM@setpagedimen{%
  \mediawidth\AM@pagewidth
  \mediaheight\AM@pageheight
}
\let\AM@pagesize@boogie\relax
%    \end{macrocode}
%    Rotate page.
%    Use new pdfmanagement macros if available, and fallback to pdflscape
%    if they are not available.
%    \begin{macrocode}
\def\AM@setRotate{\special{pS:
    [{ThisPage}\string<\string</Rotate 90\string>\string>%]
    /PUT pdfmark}%
}
\def\AM@resetRotate{}
%    \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}%
}
\let\AM@IfFileExists\IfFileExists
%    \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 of links.
%    \begin{macrocode}
\def\AM@dest@special{\special{!aname \AM@linkname.\AM@page}}
\def\AM@anchor@special{\special{!aname pdfpages.\the\count1}}
%    \end{macrocode}
%    Convert synatx of \PDF\ destinations.
%    \begin{macrocode}
\def\AM@convert@dest#1{}
\def\AM@region@calc{}
%    \end{macrocode}
%    Do not disable |\includegraphics|.
%    \begin{macrocode}
\let\AM@disable@includegraphics\relax
%    \end{macrocode}
%
%    \iffalse
%</ppvtexdef>
%
%<*ppxetexdef>
%    \fi
%
%    \subsubsection{\XeTeX\ driver}
%
%    Check if the graphics package was loaded with an
%    incompatible driver option (e.g. dvips).
%    \begin{macrocode}
\begingroup
\@ifundefined{ver@xetex.def}{%
  \PackageError{pdfpages}
         {The graphics package was loaded with driver\MessageBreak
          `\Gin@driver', which cannot be used with XeTeX}
         {Check the driver option of the graphics package.}
  \global\let\AM@endinput\relax
  \aftergroup\endinput}{}
\endgroup
%    \end{macrocode}
%    Packages like ngerman.sty make " with catcode 11 active. So let's
%    use " with catcode 12 to delimit arguments.
%    \begin{macrocode}
{\catcode`\"=12
 \gdef\AM@XeTeXquote{"}%
}
%    \end{macrocode}
%    Get last page number. |\XeTeXpdfpagecount| is only defined
%    for |pdf| files. For all other file types |\AM@pagecount|
%    must be set to |1| explicitely.
%
%    \noindent
%    Note: |import.sty| imports tex-files from sub-directories, allowing
%    these tex-files to use e.g. |\includegraphics|. However, this does not
%    work out of the box for pdfpages with XeTeX-driver (as it does with
%    pdftex-driver). We have to use |\import@path| of |import.sty|.
%
%    Oups: |Subfiles.sty| uses |\import@path| as well. But we shall \emph{not}
%    use |\import@path| in combination with |subfiles.sty|. Let's use macro |\subfix|
%    to check for |subfiles.sty|.
%    \begin{macrocode}
\def\AM@getpagecount{%
  \expandafter\filename@parse\expandafter{\AM@currentdocname}%
  \begingroup\edef\x{%
    \lowercase{\endgroup
      \def\noexpand\type@ext{\expandafter\scantokens\expandafter{\filename@ext\noexpand}}}}%
  \x
  \ifx\type@ext\AM@pdf@ext
    \ifdefined\subfix
      \let\AM@import@path\@empty
    \else
      \ifdefined\import@path
        \let\AM@import@path\import@path
      \else
        \let\AM@import@path\@empty
      \fi
    \fi
    \setbox\@tempboxa=\hbox{\includegraphics{\AM@currentdocname}}%
    \edef\AM@pagecount{\the\XeTeXpdfpagecount\AM@XeTeXquote
      \AM@import@path\AM@currentdocname\AM@XeTeXquote\relax}%
  \else
    \def\AM@pagecount{1}%
  \fi
}
\def\AM@pdf@ext{pdf}
%    \end{macrocode}
%    |\XeTeXversion| has changed from time to time: 0.997, 0.997-dev,
%    0.998.1
%    \begin{macrocode}
\begingroup
\def\gobble@nil#1\@nil{}
\ifnum\XeTeXversion=0
  \afterassignment\gobble@nil
  \count@\expandafter\@gobble\XeTeXrevision.\@nil
  \ifnum\count@<997
    \PackageError{pdfpages}
    {Package pdfpages requires at least XeTeX-0.997}
    {Update your TeX distribution!}
    \global\let\AM@endinput\relax
    \aftergroup\endinput
  \fi
\fi
\endgroup
%    \end{macrocode}
%    Page dimensions.
%    \begin{macrocode}
\def\AM@getpagedimen{%
  \AM@pagewidth=\paperwidth
  \AM@pageheight=\paperheight
}
\def\AM@setpagedimen{%
  \pdfpagewidth\AM@pagewidth
  \pdfpageheight\AM@pageheight
}
\def\AM@pagesize@boogie{%
  \ifdim\AM@pagewidth=\z@
    \ifdim\AM@pageheight=\z@
      \let\AM@pagewidth\paperwidth
      \let\AM@pageheight\paperheight
    \fi
  \fi
}
%    \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}%
}
\long\def\AM@IfFileExists#1#2#3{%
  \openin\@inputcheck=\AM@XeTeXquote#1\AM@XeTeXquote\relax
  \ifeof\@inputcheck
    \ifx\input@path\@undefined
      \def\reserved@a{#3}%
    \else
      \def\reserved@a{\@iffileonpath{#1}{#2}{#3}}%
    \fi
  \else
    \closein\@inputcheck
    \edef\@filef@und{#1 }%
    \def\reserved@a{#2}%
  \fi
  \reserved@a}
%    \end{macrocode}
%    Rotate page.
%    \begin{macrocode}
\ExplSyntaxOn
\@ifundefined{pdfmanagement_add:nnn}{%
  \def\AM@setRotate{\PLS@Rotate{90}}%
  \def\AM@resetRotate{\PLS@Rotate{0}}%
}{%
  \def\AM@setRotate{\pdfmanagement_add:nnn{ThisPage}{Rotate}{90}}%
  \def\AM@resetRotate{}%
}%
\ExplSyntaxOff
%    \end{macrocode}
%    Link to original document.
%    \begin{macrocode}
\def\AM@linktodoc@special@begin{%
  \special{pdf: annot
                width \the\wd\@tempboxa\space
                height \the\ht\@tempboxa\space
                depth \the\dp\@tempboxa\space
                << /Type /Annot
                   /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{%
  \special{pdf: annot
                width \the\wd\@tempboxa\space
                height \the\ht\@tempboxa\space
                depth \the\dp\@tempboxa\space
                << /Type /Annot
                   /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{%
  \special{pdf: thread @\AM@threadname\space
                width \the\wd\@tempboxa\space
                height \the\ht\@tempboxa\space
                depth \the\dp\@tempboxa\space
                <<\threadinfodict>>
              }%
}
\let\AM@thread@special@end\relax
%    \end{macrocode}
%    Destination of links.
%    \begin{macrocode}
\def\AM@view{/Fit}
\def\AM@dest@special{%
  \special{pdf: dest (\AM@linkname.\AM@page) [ @thispage \AM@view ]}}
\def\AM@anchor@special{%
  \special{pdf: dest (pdfpages.\the\count1) [ @thispage /Fit ]}}
%    \end{macrocode}
%    Convert synatx of \PDF\ destinations.
%    \begin{macrocode}
\def\AM@convert@dest#1{%
  \expandafter\AM@convert@dest@i\ifdim\z@=0pt#1 \END\fi}
\def\AM@convert@dest@i#1 #2\END{%
  \begingroup
  \def\tag{#1}%
  \def\x{FitH}%
  \ifx\x\tag
    \gdef\AM@view{/FitH @ypos}%
  \else
    \def\x{FitBH}%
    \ifx\x\tag
      \gdef\AM@view{/FitBH @ypos}%
    \else
      \def\x{FitV}%
      \ifx\x\tag
        \gdef\AM@view{/FitV @xpos}%
      \else
        \def\x{FitBV}%
        \ifx\x\tag
          \gdef\AM@view{/FitBV @xpos}%
        \else
          \def\x{fitr}%
          \ifx\x\tag
            \gdef\AM@view{/XYZ @xpos @ypos null}%
            \PackageWarningNoLine{pdfpages}{%
              `linkfit=FitR' is not supported.}%
          \else
            \def\x{FitB}%
            \ifx\x\tag
              \gdef\AM@view{/FitB}%
            \else
              \def\x{XYZ}%
              \ifx\x\tag
                \gdef\AM@view{/XYZ @xpos @ypos null}%
              \else
                \def\x{Region}%
                \ifx\x\tag
                  \gdef\AM@view{/XYZ @xpos @ypos null}%
                  \PackageWarningNoLine{pdfpages}{%
                    `linkfit=Region' is not supported by XeTeX.}%
                \else
                  \gdef\AM@view{/Fit}%
                \fi
              \fi
            \fi
          \fi
        \fi
      \fi
    \fi
  \fi
  \endgroup
}
\def\AM@region@calc{}
%    \end{macrocode}
%    Do not disable |\includegraphics|.
%    \begin{macrocode}
\let\AM@disable@includegraphics\relax
%    \end{macrocode}
%
%    \iffalse
%</ppxetexdef>
%
%<*ppdvipsdef>
%    \fi
%
%    \subsubsection{Dvips driver}
%
%    \begin{macrocode}
\def\AM@notsupported#1{%
  \PackageWarning{pdfpages}{#1 not supported by driver dvips}}
%    \end{macrocode}
%    Get last page number.
%    \begin{macrocode}
\def\AM@getpagecount{%
  \ifx\AM@pagecount\AM@undefined
    \AM@notsupported{Page selections}
    \def\AM@pagecount{1}%
    \gdef\AM@getpagecount{%
      \def\AM@pagecount{1}%
    }%
  \fi
}
%    \end{macrocode}
%    Page dimensions.
%    \begin{macrocode}
\def\AM@getpagedimen{%
  \AM@pagewidth=\paperwidth
  \AM@pageheight=\paperheight
}
\def\AM@setpagedimen{%
  \paperwidth\AM@pagewidth
  \paperheight\AM@pageheight
}
\let\AM@pagesize@boogie\relax
%    \end{macrocode}
%    Rotate page.
%    \begin{macrocode}
\def\AM@setRotate{\AM@notsupported{Page rotations}}
\def\AM@resetRotate{}
%    \end{macrocode}
%    Change paper size.
%    \begin{macrocode}
\def\AM@fitpaper@special{\AM@notsupported{Option fitpaper}}
%    \end{macrocode}
%    Find file.
%    \begin{macrocode}
\def\AM@findfile#1{%
  \AM@findfile@i{#1}{eps}%
  \ifx\AM@currentdocname\relax
    \AM@findfile@i{#1}{ps}%
  \fi
  \AM@findfile@ii{#1}%
}
\let\AM@IfFileExists\IfFileExists
%    \end{macrocode}
%    Link to original document.
%    \begin{macrocode}
\def\AM@linktodoc@special@begin{Links}
\let\AM@linktodoc@special@end\relax
%    \end{macrocode}
%    Survey.
%    \begin{macrocode}
\def\AM@survey@special@begin{\AM@notsupported{Option survey}}
\let\AM@survey@special@end\relax
%    \end{macrocode}
%    Thread.
%    \begin{macrocode}
\def\AM@thread@special@begin{\AM@notsupported{Option thread}}
\let\AM@thread@special@end\relax
%    \end{macrocode}
%    Destination of links.
%    \begin{macrocode}
\def\AM@dest@special{\AM@notsupported{Links}}
\def\AM@anchor@special{\AM@notsupported{Links}}
%    \end{macrocode}
%    Convert synatx of \PDF\ destinations.
%    \begin{macrocode}
\def\AM@convert@dest#1{}
\def\AM@region@calc{}
%    \end{macrocode}
%    Do not disable |\includegraphics|.
%    \begin{macrocode}
\let\AM@disable@includegraphics\relax
%    \end{macrocode}
%    Add option page to |\includegraphics|.
%    \begin{macrocode}
\@ifundefined{KV@Gin@page}{%
  \define@key{Gin}{page}{%
    \ifnum#1=1 %
    \else
      \PackageError{pdfpages}{%
        Multipage images are not supported by driver dvips%
      }\@ehc
    \fi
  }}{}
%    \end{macrocode}
%
%    \iffalse
%</ppdvipsdef>
%
%<*ppdvipdfmxdef>
%    \fi
%
%    \subsubsection{Dvipdfmx driver}
%
%    Driver |dvipdfmx| must be invoked explicitely by the user. There are
%    several ways to do this. Though only the first of the following ways is
%    recommended.
%
%    \begin{itemize}
%      \item
%      This is the recommended way. PDF output as expected.
%      \begin{quote}
%        |\documentclass[a4paper,dvipdfmx]{article}|\\
%        |\usepackage{pdfpages}|
%      \end{quote}
%
%      \item
%      Warning. Forcing dvipdfmx.def. PDF output as expected.
%      \begin{quote}
%        |\documentclass[a4paper]{article}|\\
%        |\usepackage[dvipdfmx]{pdfpages}|
%      \end{quote}
%
%      \item
%      Assuming user wants to use dvips. Therefor pdfpages will just insert
%      empty pages.
%      \begin{quote}
%        |\documentclass[a4paper]{article}|\\
%        |\usepackage{pdfpages}|
%      \end{quote}
%    \end{itemize}
%
%
%    \noindent
%    Package |graphicx| should be loaded with the |dvipdfmx| driver.
%    However, \break |\RequirePackage[dvipdfmx]{graphicx}| is not recommended
%    because it will cause an `option clash' if a user loaded |graphicx|
%    with additional options previously. Thus, we expect the user to load
%    |graphicx| with |dvipdfmx| driver before loading pdfpages.
%    \begin{macrocode}
\def\AM@tmp{dvipdfmx.def}
\ifx\Gin@driver\AM@tmp\else
  \PackageWarningNoLine{pdfpages}{%
    Graphicx.sty not loaded with driver `dvipdfmx'.\MessageBreak
    Please, specify the driver as a class option\MessageBreak
    \@spaces \string\documentclass[dvipdfmx]{...}\MessageBreak
    or load graphicx explicitely before pdfpages,\MessageBreak
    e.g.:\MessageBreak
    \@spaces \string\usepackage[dvipdfmx]{graphicx}\MessageBreak
    \@spaces \string\usepackage[dvipdfmx]{pdfpages}\MessageBreak
    This time I will try to load `dvipdfmx.def' which \MessageBreak
    will overwrite `\string\Gin@driver'.\MessageBreak
    Let's hope for the best}%
  \input{dvipdfmx.def}%
\fi
%    \end{macrocode}
%    Packages like ngerman.sty make " with catcode 11 active. So let's
%    use " with catcode 12 to delimit arguments.
%    \begin{macrocode}
{\catcode`\"=12
 \gdef\AM@quote{"}%
}%
%    \end{macrocode}
%    Get last page number.
%    This driver uses the external program |extractbb| to retrieve the total number
%    of pages. Many thanks to Noriyuki Abe who provided this code.
%    \begin{macrocode}
\def\AM@getpagecount{%
%    \end{macrocode}
%    Try reading |.xbb| file if available.
%    \begin{macrocode}
  \expandafter\expandafter\expandafter\AM@get@xbb@filename
  \csname Gin@rule@.pdf\endcsname\AM@currentdocname
  \immediate\openin\@inputcheck=\AM@xbb@filename
  \AM@read@xbb\@inputcheck
  \immediate\closein\@inputcheck
%    \end{macrocode}
%    Try reading output of program |extractbb|.
%    \begin{macrocode}
  \ifx\AM@pagecount\AM@undefined
    \immediate\openin\@inputcheck=
      \AM@quote|extractbb -O \AM@currentdocname\AM@quote
    \AM@read@xbb\@inputcheck
    \immediate\closein\@inputcheck
  \fi
%    \end{macrocode}
%    If all fails set number of pages to 1. Maybe it is a graphics file
%    like |jpg|, |png|, etc.
%    \begin{macrocode}
  \ifx\AM@pagecount\AM@undefined
    \def\AM@pagecount{1}
  \fi
}
%    \end{macrocode}
%    Construct filename of |xbb| file.
%    |#1:{pdf}, #2:{.xbb}, #3:{file.pdf}|
%    \begin{macrocode}
\def\AM@get@xbb@filename#1#2#3{%
  \filename@parse{#3}%
  \edef\AM@xbb@filename{\filename@area\filename@base#2}%
}
%    \end{macrocode}
%    Read ouput of program |extractbb|.
%    \begin{macrocode}
\def\AM@read@xbb#1{%
  \@tempswatrue
  \loop
    \ifeof#1
      \@tempswafalse
    \else
      \begingroup
        \catcode`\%=12\relax
        \immediate\global\read#1 to \@tempa
      \endgroup
      \expandafter\AM@find@pages\@tempa:\relax
    \fi
  \if@tempswa\repeat
}
%    \end{macrocode}
%    Find string |%%Pages:|
%    \begin{macrocode}
\long\def\AM@find@pages#1:#2\relax{%
  \def\@tempb{#1}%
  \edef\@tempc{\@percentchar\@percentchar Pages}%
  \ifx\@tempb\@tempc\AM@set@pagecount#2\fi
}
\def\AM@set@pagecount#1:{\def\AM@pagecount{#1}}
%    \end{macrocode}
%    Page dimensions.
%    \begin{macrocode}
\def\AM@getpagedimen{%
  \AM@pagewidth=\paperwidth
  \AM@pageheight=\paperheight
}
\def\AM@setpagedimen{%
  \special{pdf:pagesize width \the\AM@pagewidth\space
                        height \the\AM@pageheight\space}%
}
\def\AM@pagesize@boogie{%
  \ifdim\AM@pagewidth=\z@
    \ifdim\AM@pageheight=\z@
      \let\AM@pagewidth\paperwidth
      \let\AM@pageheight\paperheight
    \fi
  \fi
}
%    \end{macrocode}
%    Rotate page.
%    \begin{macrocode}
\def\AM@setRotate{\special{pdf: put @thispage <</Rotate 90>>}}%
\def\AM@resetRotate{}
%    \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}%
}
\let\AM@IfFileExists\IfFileExists
%    \end{macrocode}
%    Link to original document.
%    \begin{macrocode}
\def\AM@linktodoc@special@begin{%
  \special{pdf: ann
                width \the\wd\@tempboxa\space
                height \the\ht\@tempboxa\space
                depth \the\dp\@tempboxa\space
                << /Type /Annot
                   /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}
\let\AM@survey@special@begin\relax
\let\AM@survey@special@end\relax
%    \end{macrocode}
%    Thread.
%    \begin{macrocode}
\def\AM@thread@special@begin{%
  \special{pdf: thread @\AM@threadname\space
                width \the\wd\@tempboxa\space
                height \the\ht\@tempboxa\space
                depth \the\dp\@tempboxa\space
                <<\threadinfodict>>}%
}
\let\AM@thread@special@end\relax
%    \end{macrocode}
%    Destination of links.
%    \begin{macrocode}
\def\AM@view{/Fit}
\def\AM@dest@special{%
  \special{pdf: dest (\AM@linkname.\AM@page) [ @thispage \AM@view ]}}
\def\AM@anchor@special{%
  \special{pdf: dest (pdfpages.\the\count1) [ @thispage /Fit ]}}
%    \end{macrocode}
%    Convert synatx of \PDF\ destinations.
%    \begin{macrocode}
\def\AM@convert@dest#1{%
  \expandafter\AM@convert@dest@i\ifdim\z@=0pt#1 \END\fi}
\def\AM@convert@dest@i#1 #2\END{%
  \begingroup
  \def\tag{#1}%
  \def\x{FitH}%
  \ifx\x\tag
    \gdef\AM@view{/FitH @ypos}%
  \else
    \def\x{FitBH}%
    \ifx\x\tag
      \gdef\AM@view{/FitBH @ypos}%
    \else
      \def\x{FitV}%
      \ifx\x\tag
        \gdef\AM@view{/FitV @xpos}%
      \else
        \def\x{FitBV}%
        \ifx\x\tag
          \gdef\AM@view{/FitBV @xpos}%
        \else
          \def\x{fitr}%
          \ifx\x\tag
            \gdef\AM@view{/XYZ @xpos @ypos null}%
            \PackageWarningNoLine{pdfpages}{%
              `linkfit=FitR' is not supported.}%
          \else
            \def\x{FitB}%
            \ifx\x\tag
              \gdef\AM@view{/FitB}%
            \else
              \def\x{XYZ}%
              \ifx\x\tag
                \gdef\AM@view{/XYZ @xpos @ypos null}%
              \else
                \def\x{Region}%
                \ifx\x\tag
                  \gdef\AM@view{/XYZ @xpos @ypos null}%
                  \PackageWarningNoLine{pdfpages}{%
                    `linkfit=Region' is not supported by dvipdfmx.}%
                \else
                  \gdef\AM@view{/Fit}%
                \fi
              \fi
            \fi
          \fi
        \fi
      \fi
    \fi
  \fi
  \endgroup
}
\def\AM@region@calc{}
%    \end{macrocode}
%    Do not disable |\includegraphics|.
%    \begin{macrocode}
\let\AM@disable@includegraphics\relax
%    \end{macrocode}
%
%    \iffalse
%</ppdvipdfmxdef>
%
%<*ppnulldef>
%    \fi
%
%    \subsubsection{Null driver}
%    This is a dummy driver used when producing {\small DVI} output.
%
%    \begin{macrocode}
\AM@DVIoutputtrue
\PackageWarningNoLine{pdfpages}{%
  I will use a dummy \string\includepdf\space command\MessageBreak
  which will insert empty pages instead of the actual\MessageBreak
  PDF file because we are running in \ifAM@pkg@demo `demo' mode%
  \else DVI mode or with\MessageBreak dvips driver%
  \fi}
%    \end{macrocode}
% Find file: the file must not exist for this dummy driver. Let's just
% set \cmd{\AM@currentdocname}.
%    \begin{macrocode}
\def\AM@findfile#1{%
  \def\AM@currentdocname{#1}%
}
\let\AM@IfFileExists\IfFileExists
%    \end{macrocode}
%    Get last page number.
%    \begin{macrocode}
\def\AM@getpagecount{%
  \ifx\AM@pagecount\AM@undefined
    \PackageWarningNoLine{pdfpages}{%
      I cannot determine the number of pages of the\MessageBreak
      included document, because we are running in\MessageBreak
      \ifAM@pkg@demo `demo' mode.
      \else DVI mode.
      \fi
      \MessageBreak
      You can use the option `lastpage' to give me a hint}%
    \edef\AM@pagecount{1}%
  \fi
}
%    \end{macrocode}
%    Page dimensions.
%    \begin{macrocode}
\def\AM@getpagedimen{%
  \AM@pagewidth=\paperwidth
  \AM@pageheight=\paperheight
}
\def\AM@setpagedimen{%
  \paperwidth\AM@pagewidth
  \paperheight\AM@pageheight
}
\let\AM@pagesize@boogie\relax
%    \end{macrocode}
%    Change paper size.
%    \begin{macrocode}
\let\AM@fitpaper@special\relax
%    \end{macrocode}
%    Find file.
%    \begin{macrocode}
\def\AM@findfile#1{%
  \def\AM@currentdocname{}%
}
%    \end{macrocode}
%    Rotate page.
%    \begin{macrocode}
\let\AM@setlscape\relax
%    \end{macrocode}
%    Link to original document.
%    \begin{macrocode}
\let\AM@linktodoc@special@begin\relax
\let\AM@linktodoc@special@end\relax
%    \end{macrocode}
%    Survey.
%    \begin{macrocode}
\let\AM@survey@special@begin\relax
\let\AM@survey@special@end\relax
%    \end{macrocode}
%    Thread.
%    \begin{macrocode}
\let\AM@thread@special@begin\relax
\let\AM@thread@special@end\relax
%    \end{macrocode}
%    Destination of links.
%    \begin{macrocode}
\let\AM@dest@special\relax
\let\AM@anchor@special\relax
%    \end{macrocode}
%    Convert synatx of \PDF\ destinations.
%    \begin{macrocode}
\def\AM@convert@dest#1{}
%    \end{macrocode}
%    Disable |\includegraphics|.
%    \begin{macrocode}
\def\AM@disable@includegraphics{%
  \renewcommand\includegraphics[2][]{}%
}
%    \end{macrocode}
%    Don't check page numbers.
%    \begin{macrocode}
\newcommand*{\AM@checkpagenumber}[1]{}
%    \end{macrocode}
%    \begin{macrocode}
\def\AM@region@calc{}
%    \end{macrocode}
%
%    \iffalse
%</ppnulldef>
%    \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}
%
%    \subsection*{2004/02/21 v0.3f}
%    \begin{itemize}
%    \item Option |signature*| (right-edge binding) added.
%    \item Optimizations for a faster processing of signatures.
%    \end{itemize}
%
%    \subsection*{2006/08/05 v0.4a}
%    \begin{itemize}
%    \item Support of \DVI\ mode: Insertion of empty pages instead of
%      interrupting execution.
%    \item Option |lastpage| added.
%    \end{itemize}
%
%    \subsection*{2007/04/21 v0.4b}
%    \begin{itemize}
%    \item Support of \XeTeX.
%    \end{itemize}
%
%    \subsection*{2008/04/27 v0.4d}
%    \begin{itemize}
%    \item A more robust check of |\XeTeXversion|.
%    \end{itemize}
%
%    \subsection*{2008/05/11 v0.4e}
%    \begin{itemize}
%    \item Make |\AM@trim@leadingspace| robust to allow macros
%      in the caption argument of |addtolist|.
%    \end{itemize}
%
%    \subsection*{2008/06/05 v0.4f}
%    \begin{itemize}
%    \item If |fitpaper| is used together with |angle| the resulting
%      |\@tempboxa| might have a depth unequal to zero. Taking this
%      into consideration when calculation page dimensions.
%    \end{itemize}
%
%    \subsection*{2008/10/17 v0.4g}
%    \begin{itemize}
%    \item Macro |\AM@region@calc| was missing in the VTeX driver.
%    \end{itemize}
%
%    \subsection*{2009/06/07 v0.4h}
%    \begin{itemize}
%    \item Added dvips driver provided by Heiko Oberdiek.
%    \end{itemize}
%
%    \subsection*{2009/10/11 v0.4i}
%    \begin{itemize}
%    \item Added dvipdfm driver.
%    \item |\AM@toc@title| uses |\ignorespaces|, |\AM@lof@heading|
%    doesn't need that
%    \end{itemize}
%
%    \subsection*{2010/01/12 v0.4j}
%    \begin{itemize}
%    \item Make |\AM@reflectbox| and |\AM@fbox| global definitions which is
%      necessary for package textpos.sty.
%    \item Refrain from setting |\AM@localxoff|, |\AM@localyoff|,
%    and |\AM@localscale| if option |noautoscale| is used.
%    \end{itemize}
%
%    \subsection*{2010/08/08 v0.4k}
%    \begin{itemize}
%    \item Bugfix for memoir chapter classes.
%    \end{itemize}
%
%    \subsection*{2010/11/26 v0.4l}
%    \begin{itemize}
%    \item Bugfix: In `signatures' the sign of |xoffset| must
%      change on every second page.
%    \end{itemize}
%
%    \subsection*{2010/12/18 v0.4m}
%    \begin{itemize}
%    \item Bugfix: Wrong offset of signature.
%    \end{itemize}
%
%    \subsection*{2011/03/10 v0.4n}
%    \begin{itemize}
%    \item Bugfix: In |\includepdfmerge|, |\AM@readlist| has to be
%          after |\setkeys|.
%    \end{itemize}
%
%
%    \subsection*{2011/07/02 v0.4p}
%    \begin{itemize}
%    \item Bugfix: |templatesize| ignored |scale| option.
%    \end{itemize}
%
%
%    \subsection*{2012/03/08 v0.4q}
%    \begin{itemize}
%    \item Macro |\AM@checkinteger| rewritten.
%    \item Loading |graphicx.sty| without explicit driver information.
%    \end{itemize}
%
%    \subsection*{2012/04/03 v0.4s}
%    \begin{itemize}
%    \item Revert to the older |\AM@checkinteger| but now with changed
%      catcode for |_| (underscore).
%    \end{itemize}
%
%    \subsection*{2012/08/28 v0.4t}
%    \begin{itemize}
%    \item Add option |duplicatepages|. Requested by Allan Pickett.
%    \end{itemize}
%
%    \subsection*{2013/05/30 v0.4u}
%    \begin{itemize}
%    \item Compatibility with |import.sty|.
%    \end{itemize}
%
%    \subsection*{2013/08/25 v0.4v}
%    \begin{itemize}
%    \item |\pdflastximagepages| is not updated if using |\includegraphics|
%    on the same file repeatedly. The provided fix is temporarily until
%    there's a better solution implemented in |pdftex.def|.
%    \end{itemize}
%
%    \subsection*{2015/04/14 v0.4w}
%    \begin{itemize}
%    \item Driver file for \luaTeX:
%    So far \luaTeX\ used the driver file of \pdfTeX, which does not work
%    any more. As of luaTeX-0.80 the deprecated primitive |\pdftexversion| is
%    removed. Thus \luaTeX\ chokes on the code for checking the version number
%    of \pdfTeX. Therefore \luaTeX\ gets its on driver file |ppluatex.def|.
%    \end{itemize}
%
%    \subsection*{2015/05/04 v0.4x}
%    \begin{itemize}
%    \item Issue with uppercase filename extentions in ppxetex.def fixed.
%    \item Issue with suspending of floats, and bang floats, during output fixed.
%    \end{itemize}
%
%    \subsection*{2015/07/06 v0.4z}
%    \begin{itemize}
%    \item Package option `demo' added.
%    \end{itemize}
%
%    \subsection*{2015/07/18 v0.5a}
%    \begin{itemize}
%    \item Driver dvipdfm removed.
%    \item Driver dvipdfmx added.
%    \end{itemize}
%
%    \subsection*{2015/08/13 v0.5b}
%    \begin{itemize}
%      \item Driver dvipdfmx uses |extractbb| to get the total number of
%      pages of a PDF.
%    \end{itemize}
%
%    \subsection*{2015/09/18 v0.5d}
%    \begin{itemize}
%      \item \emph{Iff} pdflscape is \emph{not} loaded by the user explicitly,
%      reset modification of the landscape environment after loading
%      pdflscape.
%    \end{itemize}
%
%    \subsection*{2016/04/10 v0.5e}
%    \begin{itemize}
%      \item Cope with new primitive names introduced in LuaTeX 0.85.
%      \item Respect eso-pic's option |texcoord|.
%    \end{itemize}
%
%    \subsection*{2016/04/19 v0.5f}
%    \begin{itemize}
%      \item Use |\includegraphics[width=!,height=!,...]{...}| to (kind of)
%      disable |width| and |height| options.
%      \item All (really all) options can be made global with
%      |\includepdfset|. (It's no more restricted to options of pdfpages.)
%    \end{itemize}
%
%    \subsection*{2016/12/11 v0.5g}
%    \begin{itemize}
%      \item Conflict between |nup| and |addtotoc| fixed. A |\newpage| was triggered
%      on each page where |addtotoc| inserted a label.
%    \end{itemize}
%
%    \subsection*{2017/01/12 v0.5h}
%    \begin{itemize}
%      \item Do not use |\stockwidth| to check for memoir, |\stockwidth| is used
%      by other packages as well.
%    \end{itemize}
%
%    \subsection*{2017/06/13 v0.5i}
%    \begin{itemize}
%      \item Since 2017/06/01 (v5.0a) xetex.def does not define
%      |\def\G@pdf@ext{.pdf}| any more. In consequence of removing
%      |\G@pdf@ext| pdfpages could no longer determine the number of pages
%      of a PDF correctly.
%    \end{itemize}
%
%    \subsection*{2017/07/14 v0.5j}
%    \begin{itemize}
%      \item Fixed |addtolist| which was broken when used with |float.sty|.
%    \end{itemize}
%
%    \subsection*{2017/08/14 v0.5k}
%    \begin{itemize}
%      \item Documentation.
%    \end{itemize}
%
%
%    \subsection*{2017/10/31 v0.5l}
%    \begin{itemize}
%      \item Signatures for right edge binding were wrong when using
%      |signature*| and |landscape| together.
%    \end{itemize}
%
%    \subsection*{2019/09/19 v0.5m}
%    \begin{itemize}
%      \item Expanding argument for |pages| option: \par
%      |\def\foo{1-4}\includepdf[pages=\foo]{dummy.pdf}|
%    \end{itemize}
%
%    \subsection*{2019/09/21 v0.5n}
%    \begin{itemize}
%      \item |\AM@checkinteger| rewritten.
%      \item File names like `1.pdf' or `1-2.pdf' are now handled correctly by |\includepdfmerge|.
%       Rewritten |\AM@range@or@docname|, |\AM@checkrange|, |\AM@expand@range|, ...
%    \end{itemize}
%
%    \subsection*{2019/11/21 v0.5o}
%    \begin{itemize}
%    \item This update fixes a bug with grffile.sty. Pdfpages tried to use
%      an internal command of grffile.sty, which no longer exists, since
%      grffile.sty is an empty dummy package nowadays.
%    \end{itemize}
%
%    \subsection*{2019/12/17 v0.5p}
%    \begin{itemize}
%    \item Bug fix: Make empty pages empty. Empty pages like [pages={3,,5}]
%      weren't empty, but set as page 1, which was due to a bug in
%      |\AM@range@or@docname|.
%    \end{itemize}
%
%    \subsection*{2020/01/27 v0.5q}
%    \begin{itemize}
%    \item Now |\includepdfmerge| supports option |pages|,
%      too. E.g. |\includepdfmerge[pages={2-}]{a.pdf, b.pdf}| inserts all pages
%      but the first of each pdf.
%    \item Option |openrighteach| added.
%    \end{itemize}
%
%    \subsection*{2021/01/09 v0.5r}
%    \begin{itemize}
%    \item |\pdfpages@includegraphics@status| added.
%    \end{itemize}
%
%    \subsection*{2021/02/05 v0.5s}
%    \begin{itemize}
%    \item Pdfpages redefined |\fboxsep| and |\fboxrule| inside
%      |\includepdf|. Thereby causing unexpected results if |\fbox| was used
%      inside option |picturecommand|. This bug is fixed. Now |\fboxsep| and
%      |\fboxrule| equal the values which were active just before
%      calling |\includepdf|.
%    \end{itemize}
%
%    \subsection*{2021/03/06 v0.5t}
%    \begin{itemize}
%    \item Page rotation: Use new pdfmanagement macros if they are
%      available, and fallback to pdflscape if they are not available.
%    \end{itemize}
%
%    \subsection*{2022/01/29 v0.5u}
%    \begin{itemize}
%    \item Adding |\leavevmode| before |\@chapter|,... in |addtotoc|.
%      Bug fix for \url{https://tex.stackexchange.com/questions/631514/}.
%    \end{itemize}
%
%    \subsection*{2022/05/21 v0.5v}
%    \begin{itemize}
%    \item Do not enter an infinite loop if the PDF file doesn't exist.
%      Bug fix for \url{https://tex.stackexchange.com/questions/644971/}.
%    \end{itemize}
%
%    \subsection*{2022/10/09 v0.5w}
%    \begin{itemize}
%    \item Keyval arguments get fully expanded.
%    \end{itemize}
%
%    \subsection*{2022/12/19 v0.5x}
%    \begin{itemize}
%    \item Expand args of addtotoc and addtolist more graciously.
%    \end{itemize}
%
%    \subsection*{2024/01/21 v0.5y}
%    \begin{itemize}
%    \item Fix issues with twocolumn documents
%      \begin{itemize}
%      \item |\newpage| -> |\clearpage|
%      \item Define |\@setmarks| if undefined.
%      \end{itemize}
%    \end{itemize}
%
%    \subsection*{2024/04/29 v0.6a}
%    \begin{itemize}
%    \item Bugfix for ppxetex driver: Don't use |\import@path| in combination
%      with |subfiles.sty|.
%    \end{itemize}
%
%    \subsection*{2024/08/20 v0.6b}
%    \begin{itemize}
%    \item Make |\includepdf[pages=-]{\detokenize{file.pdf}}| work in xelatex.
%    \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>
%
%<*installer>
\input docstrip
\askforoverwritefalse
\keepsilent

\preamble
\endpreamble

\declarepreamble\package

This file is part of the pdfpages package.

\endpreamble

\declarepreamble\example

This file demonstrates how to use the pdfpages package.
\endpreamble

\generate{\usepreamble\package
          \file{pdfpages.sty}{\from{pdfpages.dtx}{package}}}
\generate{\usepreamble\package
          \file{pppdftex.def}{\from{pdfpages.dtx}{pppdftexdef}}}
\generate{\usepreamble\package
          \file{ppluatex.def}{\from{pdfpages.dtx}{ppluatexdef}}}
\generate{\usepreamble\package
          \file{ppvtex.def}{\from{pdfpages.dtx}{ppvtexdef}}}
\generate{\usepreamble\package
          \file{ppxetex.def}{\from{pdfpages.dtx}{ppxetexdef}}}
\generate{\usepreamble\package
          \file{ppdvips.def}{\from{pdfpages.dtx}{ppdvipsdef}}}
\generate{\usepreamble\package
          \file{ppdvipdfmx.def}{\from{pdfpages.dtx}{ppdvipdfmxdef}}}
\generate{\usepreamble\package
          \file{ppnull.def}{\from{pdfpages.dtx}{ppnulldef}}}

%% \generate{\usepreamble\package
%%           \file{pdfpages.drv}{\from{pdfpages.dtx}{driver}}}

\generate{\usepreamble\example
          \file{pdf-ex.tex}{\from{pdfpages.dtx}{example1}}}
\generate{\usepreamble\example
          \file{pdf-hyp.tex}{\from{pdfpages.dtx}{example2}}}
\generate{\usepreamble\example
          \file{pdf-toc.tex}{\from{pdfpages.dtx}{example3}}}

\Msg{**************************************************************}
\Msg{*}
\Msg{* To finish the installation you have to move the following}
\Msg{* files into a directory searched by LaTeX:}
\Msg{*}
\Msg{*  \space\space pdfpages.sty}
\Msg{*  \space\space pppdftex.def}
\Msg{*  \space\space ppvtex.def}
\Msg{*  \space\space ppxetex.def}
\Msg{*  \space\space ppdvips.def}
\Msg{*  \space\space ppnull.def}
\Msg{*}
\Msg{* To produce the documentation, run the following}
\Msg{* file through LaTeX:}
\Msg{*}
\Msg{*  \space\space pdfpages.dtx}
\Msg{*}
\Msg{* The following files are examples demonstrating how to use}
\Msg{* the pdfpages package.}
\Msg{*}
\Msg{*  \space\space pdf-ex.tex}
\Msg{*  \space\space pdf-hyp.tex}
\Msg{*  \space\space pdf-toc.tex}
\Msg{*}
\Msg{* Happy TeXing!}
\Msg{*}
\Msg{**************************************************************}
\endbatchfile
%</installer>
%
%\fi
\endinput
%%%
%%% Local Variables: ***
%%% fill-column: 76 ***
%%% End: ***