% \iffalse ^^A -*- mode: latex; -*-
\NeedsTeXFormat{LaTeX2e}[1995/12/01]
%<*driver>
\ProvidesFile{totpages.drv}
      [2005/09/19 v2.00 Driver for Totpages Package (muewi)]
\documentclass{ltxdoc}
\usepackage{url}
\usepackage{totpages}
\usepackage[toc]{multitoc}
\GetFileInfo{totpages.sty}
\EnableCrossrefs
\CodelineIndex    % Index code by line number
\RecordChanges    % Changelog to .gls
%\OnlyDescription  % comment out for implementation details
\setcounter{IndexColumns}{2}
%\OldMakeIndex    % use if your MakeIndex is pre-v2.9
\begin{document}
   \setcounter{page}{1234}
   \DocInput{totpages.dtx}
\end{document}
%</driver>
%
% Copyright (c) [1999-2005] by Wilhelm M\"uller.  All rights reserved.
%
% This program may be redistributed and/or modified under the terms
% of the LaTeX Project Public License, either version 1.1 of this
% license, or (at your option) any later version.
% The latest version of this license is in
%   CTAN:macros/latex/base/lppl.txt.
%
% For error reports in case of UNCHANGED versions see totpages.ins
%
% \fi
%
% \CheckSum{286}
%
%% \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 meta-comment
%% ===================================================================
%%  @LaTeX-style-file{
%%     author          = {Wilhelm M\"uller},
%%     version         = "2.00",
%%     date            = "19 September 2005",
%%     filename        = "totpages.sty",
%%     address         = {Wilhelm M\"uller
%%                        Herbststra\ss{}e 66
%%                        D-28215 Bremen
%%     telephone       = "+49-421-1692525",
%%     email           = "muewi@acm.org",
%%     codetable       = "ISO/ASCII",
%%     keywords        = "LaTeX, pages",
%%     supported       = "yes",
%%     docstring       = "LaTeX package which sets count1 to the total
%%                        number of pages in the document.
%%                        Uses the everyshi and keyval packages."
%%
%%  }
%% ===================================================================
% \fi
%
%  \newcommand*{\Count}[1]{\texttt{\bslash{}count#1}}
%  \newcommand*{\package}[1]{\textsf{#1}}
%  \newcommand*{\ftype}[1]{\textsl{#1}}
%  \newcommand*{\NEWfeature}[1]{^^A stolen from ltxguide.cls
%     \hskip 1sp \marginpar{\small\sffamily\raggedright
%     New feature\\#1}}
%
%  ^^A^^A We need to document a label -- we do this by using the macros for 
%  ^^A^^A environments and changing the macros for the index entries.
%  \makeatletter
%  \renewcommand*{\SpecialEnvIndex}[1]{^^A
%         \@bsphack\index{\string#1^^A
%         \actualchar\string\verb\quotechar*\verbatimchar
%         \string#1\verbatimchar
%         \encapchar usage}\@esphack}
%  \renewcommand*{\SpecialMainEnvIndex}[1]{^^A
%         \@bsphack\special@index{\string#1\actualchar
%         \string\verb\quotechar*\verbatimchar
%         \string#1\verbatimchar\encapchar main}%
%         \@esphack}
%  \makeatother
%
%  \changes{v1.00}{1999/07/14}{Initial Version}
%  \changes{v1.10}{2003/02/05}{Fixed hook into \package{hyperref}}
%  \changes{v2.00}{2005/09/19}{
%       Incorporated changes by Ido Tal to compute
%       number of sheets needed;
%       changed option processing to use keyval;
%       corrected a problem when we wanted to write to \ftype{aux}
%       although \texttt{\char`\\nofiles} was requested;
%       moved \texttt{\char`\\StopEventually} to correct place
%  }
%
%  \DoNotIndex{\@empty,\@firstofone,\addtocounter,\arabic}
%  \DoNotIndex{\begingroup,\else,\endgroup}
%  \DoNotIndex{\fi,\ifx,\immediate,\let,\MessageBreak}
%  \DoNotIndex{\ref,\relax,\string,\lowercase,\textlatin}
%  \DoNotIndex{\the,\thepage,\undefined,\do,\divide,\value}
%  \DoNotIndex{\ifHy@pageanchor,\if@filesw,\ifHy@hypertexnames}
%  \DoNotIndex{\ifHy@plainpages,\Hy@temp,\Hy@pagecounter}
%  \DoNotIndex{\end,\documentclass,\ldots,\pageref,\renewcommand}
%  \DoNotIndex{\roman,\setcounter,\usepackage,\begin,\@number}
%  \DoNotIndex{\@currname,\@currext,\noexpand,\gdef,\edef,\def}
%
% ^^A -----------------------------
%
%  \title{\unskip
%         The \package{totpages} package^^A
%              \thanks{^^A
%                 The version number of this file is \fileversion,
%                 last revised \filedate.}
%        }
%  \author{Wilhelm M\"uller\\[0.5ex]
%          \normalsize  Herbststra\ss{}e 66\\
%          \normalsize  D-28215 Bremen\\
%          \normalsize  muewi@acm.org
%         }
%  \date{\filedate}
%  \maketitle
%
% ^^A -----------------------------
%
%
%  \begin{abstract}
%     \noindent This package counts the total number of pages shipped
%     out to the \ftype{dvi} file, which
%     allows sentences like
%     ``This document contains \ref{TotPages} pages,
%     the last one being no.~\pageref{TotPages}.'' to be produced
%     automatically. 
%      The counter itself may be shipped out to the \ftype{dvi} file, too,
%     allowing page access by absolute page numbers, or it may be just
%     a regular \LaTeX\ counter.
%
%     It cooperates with the package \package{hyperref}, producing
%     a hyperlink to the last page---though this is not of much use as hypertext
%     readers usually allow direct access to the last page anyway.
%
%     Optionally, the number of sheets of paper needed to print the document
%     can be computed.
%  \end{abstract}
%
%  \pagestyle{headings}
%
% ^^A -----------------------------
%
%    \tableofcontents
%
% ^^A -----------------------------
%
%  \section{Introduction}
%  ^^A
%  Printing only part of a \ftype{dvi} file can be difficult or
%  impossible if pages in different 
%  parts of the document have the same number---e.\,g., in the 
%  front matter and the first text pages (iii vs. 3).
%
%  \TeX{} provides an easy solution to this problem: whenever a page
%  has been completed by the output routine and is being shipped out to
%  the \ftype{dvi} file,
%  it displays the values of \Count{0} to \Count{9},
%  with trailing zeroes suppressed,
%  (e.\,g., \texttt{[1002.0.3]}) and writes them to the \ftype{log} and
%  \ftype{dvi} files, cf.\ \cite[p.~119]{KnuthTeXa}.
%  So,
%  if you have a \ftype{dvi} driver which allows page selection by other counters
%  than \Count{0}, you will be able to refer to absolute page numbers
%  when you make use of this package.
%
% \section{Using \package{totpages}}
%  ^^A
%  \DescribeEnv{TotPages}
%  Keeping a count of the absolute page number makes it
%  possible to provide the \emph{total} number of pages of the 
%  document (as opposed to the ``number'' on the last page provided
%  by the \package{lastpage} package, cf.\ \cite{package:lastpage}).
%
%  References to the counter itself won't make much sense since it is updated
%  asynchronously whenever an actual shipout occurs.
%  But by referencing the label |TotPages| (with |\ref{TotPages}|)
%  you get the total number of pages the document had at the end
%  of the previous run 
%  of \LaTeX. If, for some reason, you want to know what page number \LaTeX\ 
%  actually (would have) printed, you may use |\pageref{TotPages}|.^^A
%    \footnote{Since all references to this label are obviously forward
%      references, you will have to run \LaTeX\ at least twice to get
%      correct results.}
%
%  \DescribeMacro{\theTotPages}
%  What is actually printed by |\ref{TotPages}| is the result of the
%  macro |\theTotPages|, which normally is simply |\arabic{TotPages}|, but
%  may be redefined to anything (sensible)
%  somewhere before |\end{document}|.
%
%  If you want to use this package, you should load \package{totpages}
%  as the \emph{last} package in your document because it
%  executes some code at |\end{document}| and has to be sure that its 
%  code is the last code to be executed there.\footnote{See
%  \cite{package:lastpage} for a discussion of problems.}
%
%  You \emph{must not} use \package{count1to} or \package{lastpage}
%  together with this package. Package \package{count1to} provides additional
%  functionality, but will not cooperate with \package{hyperref}, whereas
%  any use of \package{lastpage} is covered by \package{totpages}.^^A
%    \footnote{\package{lastpage} requires less resources, though.}
%  If you try to use one (or both) of these packages together with
%  \package{totpages}, you will receive an error message at
%  |\begin{document}|. I don't think that something really bad will happen
%  if you ignore it (unless you use \package{count1to} together with
%  \package{hyperref}), but I won't guarantee anything, either.
%
%
%
% ^^A -----------------------------
%
%  \section{Options}
%  \subsection{Writing absolute page numbers to the \ftype{dvi} file}
%  \DescribeEnv{dvi}
%  \DescribeEnv{nodvi}
%  With option |dvi| (the default), \Count{1} is used for the absolute
%  page counter. This value is put into the \ftype{dvi} file and may be
%  used by the \ftype{dvi} driver.
%
%  Option |nodvi| uses a regular \LaTeX\ counter which will not
%  show up elsewhere.
%
%  No matter what kind of counter is used, its name will always be |TotPages|,
%  e.\,g., if you want to change its format to roman. (But who would want
%  to do that?).
%  
%  ^^A\pagebreak[1]
%  \subsection{Computing the number of sheets of paper}
%  \DescribeEnv{pagespersheet}
%  \DescribeEnv{nopagespersheet}
%  The option |pagespersheet=|$n$ allows to compute the number of
%  \NEWfeature{Provide number of sheets needed for printing}
%  physical sheets of paper needed when the document will be
%  printed.\footnote{Thanks
%    to Ido Tal for suggesting this
%    feature, providing an initial realisation, testing it, and
%    proof-reading the documentation.}
%  To compute this value, you have to specify the positive integer,
%  $n$, telling how many pages will be
%  printed on one physical sheet of paper. For example, when you
%  use a duplex printer and let your printer driver scale and
%  rearrange document pages to print two document pages 
%  on one physical page, you should specify
%  |pagespersheet=4|.  Using |nopagespersheet| (or |pagespersheet=no|)
%  turns this computation off; this is the default setting.
%
%  \DescribeMacro{\TotPerSheet}
%  When |pagespersheet| is set to valid number,
%  its value is available in the macro |\TotPerSheet| (in exactly the
%  same form as you wrote it),
%  otherwise this macro is undefined.
%
%  \DescribeMacro{\TotSheets}
%  The number of sheets, as computed at the end of the previous
%  \LaTeX\ run, will be contained (as decimal
%  digits) in the macro |\TotSheets|.\footnote{The value of
%  |pagespersheet| must, of course, coincide with the options you use
%  when you print the document.}
%  When |pagespersheet| is 
%  used for the first time, the value of this macro will be set to |0000|
%  (four zeroes), which is still a number but different from the
%  representation of an actual zero.  When you say |nopagespersheet|
%  (or never use |pagespersheet| at all), |\TotSheets| will be undefined.
%  When, at the end of the document, the value of |\TotSheets| differs 
%  from the one at |\begin{document}| (the initial |0000|, or as read
%  from \ftype{aux}),
%  a warning will be issued similar to the one you get when labels differ.
%
% ^^A -----------------------------
%
%  \section{Required packages}
%  ^^A
%  This package needs the \package{everyshi} 
%  \cite{package:everyshi} and \package{keyval} \cite{package:keyval} packages.
%
%
% ^^A -----------------------------
%
%  \section{Acknowledgements}
%  ^^A
%  This package uses ideas inspired by
%  Martin Schr\"oder's \package{count1to}
%  package \cite{package:count1to}, Jeff Goldberg's \package{lastpage}
%  package \cite{package:lastpage}, and the \package{lastpage} and
%  \package{keyval} support
%  contained in Sebastian Rahtz's \package{hyperref}
%  package \cite{package:hyperref}, and implements options suggested
%  by and based on ideas of Ido Tal \cite{mail:Tal}.
%
%
% ^^A -----------------------------
%
%  \begin{thebibliography}{HHHHHHHH\,1}
%     \raggedright
%     \bibitem[Carlisle]{package:keyval}
%        David Carlisle.
%        \newblock The \package{keyval} package.
%        \newblock \url{CTAN: tex-archive/macros/latex/required/graphics/keyval.dtx}.
%        \newblock \LaTeXe{} package.
%     \bibitem[Goldberg]{package:lastpage}
%        Jeff Goldberg.
%        \newblock The \package{lastpage}-package.
%        \newblock \url{CTAN: tex-archive/macros/latex/contrib/lastpage/}.
%        \newblock \LaTeXe{} package.
%     \bibitem[Knuth]{KnuthTeXa}
%        Donald~E.\ Knuth.
%        \newblock \emph{The {\TeX}Book}, volume~A of \emph{Computers
%           and Typesetting}.
%        \newblock Addison-Wes\-ley, 1986.
%        \newblock Tenth printing, revised, June 1990.
%     \bibitem[Rahtz]{package:hyperref}
%        Sebastian Rahtz.
%        \newblock Hypertext marks in \LaTeX.
%        \newblock \url{CTAN: tex-archive/macros/latex/contrib/hyperref/}.
%        \newblock \LaTeXe{} package.
%     \bibitem[Schr\"oder\,1]{package:count1to}
%        Martin Schr\"oder.
%        \newblock The \package{count1to} package.
%        \newblock \url{CTAN: tex-archive/macros/latex/contrib/ms/count1to.dtx}.
%        \newblock \LaTeXe{} package.
%     \bibitem[Schr\"oder\,2]{package:everyshi}
%        Martin Schr\"oder.
%        \newblock The \package{everyshi} package.
%        \newblock \url{CTAN: tex-archive/macros/latex/contrib/ms/everyshi.dtx}.
%        \newblock \LaTeXe{} package.
%     \bibitem[Tal]{mail:Tal}
%        Ido Tal.
%        \newblock Private communication.
%  \end{thebibliography}
%
%
%
% ^^A -----------------------------
%
%  \StopEventually{}^^A
%
% ^^A -----------------------------
%
%
%  \section{The implementation}
%  ^^A
%  \setlength{\parindent}{0pt}
%  We need the \package{everyshi} and \package{keyval} packages.
%    \begin{macrocode}
%<*package>
\ProvidesPackage{totpages}
        [2005/09/19 v2.00 Totpages Package (muewi)]
\NeedsTeXFormat{LaTeX2e}[1995/12/01]
\RequirePackage{everyshi}[1994/12/09]
\RequirePackage{keyval}[1998/06/05]
%    \end{macrocode}
%
%    \begin{macro}{\ifTotPagesToDvi}
%  The user can decide if the absolute page number should
%  go to the \ftype{dvi} file or not, the default being yes:
%    \begin{macrocode}
\newif\ifTotPagesToDvi\TotPagesToDvitrue
%    \end{macrocode}
%    \end{macro}
%
%    \begin{macro}{\ifPagesPerSheet}
%    \begin{macro}{\TotPerSheet}
% The user may ask to compute the number of sheets needed for
% printing.
% To do this, we need some variables.  (The number
% of pages per sheet is saved in a macro instead of a counter
% since counters are a scarce resource in some \TeX\ implementations.)
%
%    \begin{macrocode}
\newif\ifPagesPerSheet\PagesPerSheetfalse
\newcommand{\TotPerSheet}{}
%    \end{macrocode}
%    \end{macro}
%    \end{macro}
%
%  We want to parse package options with keyval.  This code has been
%  stolen (more or less) from \package{hyperref}:
%
%    \SpecialMainEnvIndex{dvi}
%    \SpecialMainEnvIndex{nodvi}
%  First, we define the keys.  In case of the boolean keys, |dvi| and
%  |nodvi|, we ignore any value, just taking into account their presence:
%
%    \begin{macrocode}
\define@key{Tot}{dvi}[x]{\TotPagesToDvitrue}
\define@key{Tot}{nodvi}[x]{\TotPagesToDvifalse}
%    \end{macrocode}
%
%    \SpecialMainEnvIndex{pagespersheet}
%    \SpecialMainEnvIndex{nopagespersheet}
%  For the numeric key, a value of |no| may be used
%  to disable the feature.
% 
%    \begin{macrocode}
\define@key{Tot}{nopagespersheet}[x]{\PagesPerSheetfalse}
\define@key{Tot}{pagespersheet}{%
  \lowercase{\def\Tot@temp{#1}}%
  \ifx\Tot@temp\@empty
  \else
    \def\Tot@no{no}
    \ifx\Tot@temp\Tot@no
    \else
      \edef\TotPerSheet{#1}
      \PagesPerSheettrue
    \fi
  \fi
}
%    \end{macrocode}
%
%    \begin{macro}{\Tot@ptionsWithKV}
% Now comes the actual option processing.  We won't use the code from \package{hyperref}
% literally since it will produce a warning when something like |pagespersheet=2|
% is specified as a global option (although it's processed correctly!).  Nevertheless,
% this code has been derived from the code in \package{hyperref}, which, in turn,
% contains the following attribution: ``This section was written by David Carlisle.''
%    \begin{macrocode}
\def\Tot@ptionsWithKV#1{%
  \let\@tempc\relax
  \let\Tot@tempa\@empty
%    \end{macrocode}
%    \begin{macro}{\Tot@tempopt}
% To cope with global options of the form |key=value|, we have to look for
% a definition of |key|, but remove |key=value| from the list of unprocessed
% options.  \TeX's argument parser will help us here:
%    \begin{macrocode}
  \def\Tot@tempopt##1=##2=##3\Tot@tempopt{%
%    \end{macrocode}
% |\Tot@tempopt| should be called with an option string followed by |==\Tot@tempopt|.
% |##1| will always contain the keyword, |##2| and |##3| will vary:
% \begin{center}\small
%   \DeleteShortVerb{\|}
%   \begin{tabular}{l|l|l|l}
%     option string & \verb|##1| & \verb|##2|   & \verb|##3|    \\\hline
%     \verb|key=value|   & \verb|key| & \verb|value| & \verb|=|      \\
%     \verb|key=|        & \verb|key| & (empty) & \verb|=|      \\
%     \verb|key|         & \verb|key| & (empty) & (empty)
%   \end{tabular}\\
%   \MakeShortVerb{\|}
% \end{center}
% Now we can check the existence of the key\ldots
%    \begin{macrocode}
    \@ifundefined{KV@#1@##1}%
    {}%
    {%
%    \end{macrocode}
% \ldots{}and, if found, add the complete string to the list
% of options to be parsed
% here and remove it from the list of unused options:
%    \begin{macrocode}
      \edef\Tot@tempa{\Tot@tempa,\CurrentOption,}%
      \@expandtwoargs\@removeelement\CurrentOption
        \@unusedoptionlist\@unusedoptionlist
    }%
  }%
%    \end{macrocode}
%    \end{macro}
% Add any global options that are known to KV to the start of the list
% being built in |\Tot@tempa| and mark them used by removing them from
% the unused option list.
%    \begin{macrocode}
  \@for\CurrentOption:=\@classoptionslist\do{%
    \expandafter\Tot@tempopt\CurrentOption==\Tot@tempopt
  }%
%    \end{macrocode}
%
% Now stick the package options at the end of the list and wrap in a call
% to |\setkeys|.
%    \begin{macrocode}
  \edef\Tot@tempa{%
    \noexpand\setkeys{#1}{%
      \Tot@tempa\@ptionlist{\@currname.\@currext}%
    }%
  }%
%    \end{macrocode}
%
% Do it.  And drop unused macros
%    \begin{macrocode}
  \Tot@tempa
  \let\Tot@no\relax
  \let\Tot@temp\relax
  \let\Tot@tempa\relax
  \let\Tot@tempopt\relax
  \let\Tot@ptionsWithKV\undefined
}
%    \end{macrocode}
%    \end{macro}
%    \begin{macrocode}
\Tot@ptionsWithKV{Tot}%
%    \end{macrocode}
%
% Unknown package options will be flagged as an error by |\setkeys|, so we
% will turn off \LaTeX's message.  (Don't ask me why this has to be
% wrapped in |\AtEndOfPackage|.  If it isn't, the warning will still appear.)
%    \begin{macrocode}
\AtEndOfPackage{\let\@unprocessedoptions\relax}
%    \end{macrocode}
%
%  Finally, we check if the value given for |pagespersheet| makes sense.
%  This code is not really perfect since using really strange things for
%  the option value will cause havoc.
%
%    \begin{macrocode}
\ifPagesPerSheet
  \ifnum 1 > \TotPerSheet
     \PackageError{totpages}{%
        The number of pages per sheet must be positive.}{%
        You cannot print less than one TeX page per sheet of paper.\MessageBreak
        The option pagespersheet has been disabled.}
     \PagesPerSheetfalse
  \fi
\fi
%    \end{macrocode}
%
%     \begin{macro}{\theTotPages}
%     \SpecialMainEnvIndex{TotPages}
%  If the counter is to go to the \ftype{dvi} file, we have to use a
%  fixed count register: \Count{1}.  (For this to work, we have to copy
%  a few internals from \ftype{latex.ltx}.)  Otherwise, we'll just use a
%  conventional \LaTeX\ counter.
%    \begin{macrocode}
\ifTotPagesToDvi
  \countdef\c@TotPages=1 \c@TotPages=0
  \let\cl@TotPages\@empty
  \newcommand\theTotPages{\arabic{TotPages}}
\else
  \newcounter{TotPages}
\fi
%    \end{macrocode}
%    \end{macro}
%  To save a bit of space,
%  some control sequences for the options are removed.  Some more will be removed
%  at |\begin{document}|.
%    \begin{macrocode}
\let\ifTotPagesToDvi\undefined
\let\TotPagesToDvitrue\undefined
\let\TotPagesToDvifalse\undefined
%    \end{macrocode}
%  When shipout occurs, we step the counter.
%    \begin{macrocode}
\EveryShipout{\stepcounter{TotPages}}
%    \end{macrocode}
%  Nothing outside this package should mess with that counter, of
%  course.---At the beginning of the document, we should be able to
%  find out
%  what packages are used and warn about some we aren't sure we can
%  cooperate with:
%
%    \begin{macrocode}
\AtBeginDocument{%
  \@ifpackageloaded{count1to}{%
    \PackageError{totpages}{%
      Can't use both, count1to and totpages}{%
      You should read the documentation of these packages and\MessageBreak
      decide which one is more appropriate for your intentions.}
  }{}%
  \@ifpackageloaded{lastpage}{%
    \PackageError{totpages}{%
      Can't use both, lastpage and totpages}{%
      You should read the documentation of these packages and\MessageBreak
      decide which one is more appropriate for your intentions.}
  }{}%
%    \end{macrocode}
%    \begin{macro}{\TotPages@putlabel}
%  We define a command which will be executed at the end of the document,
%  but if anybody did it already, we simply hope they did it right.
%    \begin{macrocode}
  \ifx\undefined\TotPages@putlabel
%    \end{macrocode}
%  If the package \package{hyperref} is used,
%  we think we know what to do to produce a correct hyperlink label.
%  (This code was obtained from the \package{lastpage} support of
%  \package{hyperref} itself.)
%    \begin{macrocode}
    \@ifpackageloaded{hyperref}{%
%    \end{macrocode}
%  There are two different ways to produce a warning with \package{hyperref}:
%    \begin{macrocode}
      \ifx\undefined\Hy@WarningNoLine
        \let\Hy@WarningNoLine\hyper@warn
      \fi
      \ifHy@pageanchor
      \else
        \Hy@WarningNoLine{%
          The \string\ref{TotPages} link will not provide hyperlinks\MessageBreak
          with disabled option `pageanchor'%
        }%
      \fi
%    \end{macrocode}
%  When |\nofiles| was requested, we can't do much since no \ftype{aux} is
%  to be written, so we won't define anything.
%    \begin{macrocode}
      \if@filesw
        \def\TotPages@putlabel{%
          \addtocounter{page}{-1}%
          \begingroup
            \let\@number\@firstofone
            \ifHy@pageanchor
              \ifHy@hypertexnames
                \ifHy@plainpages
                  \def\Hy@temp{\arabic{page}}%
                \else
                  \let\textlatin\@firstofone
                  \edef\Hy@temp{\thepage}%
                \fi
              \else
                \def\Hy@temp{\the\Hy@pagecounter}%
              \fi
            \fi
            \immediate\write\@mainaux{%
              \string\newlabel
                {TotPages}{{\theTotPages}{\thepage}{}{%
                  \ifHy@pageanchor page.\Hy@temp\fi}{}}%
            }%
          \endgroup
          \addtocounter{page}{1}%
        }%
      \fi
%    \end{macrocode}
%  Otherwise, we just put a label here, but |\label| may refer
%  to some random counter just stepped some time ago, so we have to
%  produce it ourselves.
%    \begin{macrocode}
    }{%
      \if@filesw
        \def\TotPages@putlabel{%
          \addtocounter{page}{-1}%
          \immediate\write\@mainaux{%
            \string\newlabel{TotPages}{{\theTotPages}{\thepage}}%
          }%
          \addtocounter{page}{1}%
        }%
      \fi
    }%
  \fi
%    \end{macrocode}
%    \end{macro}
%
%    \begin{macro}{\TotSheets}
%    \begin{macro}{\TotPages@putSheets}
% When |pagespersheet| is disabled, any use of |\TotSheets| 
% will be flagged as an error.  Otherwise, the initial value will
% be |0000|.  When the value computed during the previous
% run has been read from the \ftype{aux} file, we just assume it is right
% and check at the end of the document if it is still the same.
%    \SpecialEnvIndex{TotPages}
%    \begin{macrocode}
  \ifPagesPerSheet
    \ifx\undefined\TotSheets
      \newcommand{\TotSheets}{0000}
    \fi
    \def\TotPages@putSheets{%
      \addtocounter{TotPages}{\TotPerSheet}
      \addtocounter{TotPages}{-1}
      \divide \value{TotPages} by \TotPerSheet
      \edef\Tot@temp{\arabic{TotPages}}
      \ifx\Tot@temp\TotSheets \else
        \PackageWarning{totpages}{%
          The number of sheets may have changed (\TotSheets => \Tot@temp).\MessageBreak
          You should run your document through the formatter again.}
      \fi
      \if@filesw
        \immediate\write\@mainaux{%
          \string\gdef\string\TotSheets{\Tot@temp}}%
      \fi
    }%
  \else
    \let\TotSheets\undefined
  \fi
%    \end{macrocode}
%    \end{macro}
%    \end{macro}
%
%  Before we write the value to the \ftype{aux} file we call a \cs{clearpage}
%  to force all pending floats to be output.
%  To do this we have to be sure to be the \emph{last} macro called by
%  \cs{AtEndDocument}---but this is nearly impossible to assure,
%  so we try to do our very best and set our 
%  entry for \cs{AtEndDocument} during |\begin{document}| processing.
%
%  When |\nofiles| is specified, though, we won't have to do anything
%  at the end of the document.
%    \begin{macrocode}
  \if@filesw
    \AtEndDocument{%
%    \end{macrocode}
%  The label \texttt{TotPages} is put onto the last page
%  of the document and holds the total number of pages of the 
%  document, i.\,e., the value of |TotPages|.
%    \begin{macrocode}
      \clearpage
      \TotPages@putlabel
    }%
  \fi
%    \end{macrocode}
%
%  Finally, we may have to compute the number of sheets.  This
%  is done even when no files are written to allow checking for changes.
%    \begin{macrocode}
  \ifPagesPerSheet
    \AtEndDocument{\TotPages@putSheets}
  \fi
  \let\ifPagesPerSheet\undefined
  \let\PagesPerSheettrue\undefined
  \let\PagesPerSheetfalse\undefined
}
%</package>
%    \end{macrocode}
%
%  \section{An example file}
%  And, at last, there
%  is a small example file using features of package \package{totpages}.
%
%    \begin{macrocode}
%<*example>
\documentclass[pagespersheet=2]{article}
\usepackage[dvips]{hyperref}
%%%%% Replace preceding line by the following one for pdflatex:
%%\usepackage[pdftex]{hyperref}
\usepackage[dvi]{totpages}
\renewcommand{\theTotPages}{\roman{TotPages}}
\begin{document}
\setcounter{page}{12345}
This is the number of pages (in Roman numerals): ``\ref{TotPages}''.
On the last page, the number ``\pageref{TotPages}'' is printed.

\clearpage

a second page\ldots

\clearpage

and a last one\ldots\ldots


When printed on a duplex printer in duplex mode, \TotSheets{} sheets of 
paper will be needed.
\end{document}
%</example>
%    \end{macrocode}
%
% ^^A -----------------------------
%
%  \Finale
%
%   ^^A Run ``makeindex -s gind.ist totpages.idx'' and
%   ^^A ``makeindex -s gglo.ist -o totpages.gls totpages.glo''
%   ^^A to format indexes!
%   \PrintChanges
%   \PrintIndex
%   ^^A Make sure that the index is not printed twice
%   ^^A (ltxdoc.cfg might have a second \PrintIndex command)
%   \let\PrintChanges\relax
%   \let\PrintIndex\relax
