%=======================================================================================================================
% File: texpower.sty
%
% LaTeX Package for creating `dynamic' presentations.
%
%
% DISCLAIMER: This is a PRE-ALPHA release of the texpower package, mainly for getting feedback on the
%             implementation. 
%
%             During the subsequent error correction and extension of the functionality, the syntax and implementation
%             of the macros are liable to change. 
%
%             So far, the texpower package itself contains only scarce inline documentation, as the code is too
%             much of a moving target to make rigorous documentation a sensible endeavour. As soon as the
%             texpower package is ready for beta release, it will be made into a fully documented dtx file.
%
%             Some documentation and examples are contained in the full demo file, available at
%             http://ls1-www.cs.uni-dortmund.de/~lehmke/texpower/doc/texpower-fulldemo.pdf
%
%             A version of the documentation prepared for printout can be found in
%             http://ls1-www.cs.uni-dortmund.de/~lehmke/texpower/doc/texpower-doc.pdf
%
%=======================================================================================================================
% Author: Stephan Lehmke <Stephan.Lehmke@cs.uni-dortmund.de>
%
% v0.0.1 Oct 26, 1999 First pre-alpha version.
% 
% v0.0.2 Feb 15, 2000 Squashing a bug...
% 
% v0.0.3 Mar 13, 2000 Tidying up command syntax; adding some in-line documentation.
% 
% v0.0.4 Mar 17, 2000 In-line documentation for the first pre-alpha version completed.
% 
% v0.0.5 Mar 17, 2000 Fixed some problems with incompatible versions of hyperref (spotted by Marc van Dongen).
%                     (Apr 14: this code no longer exists)
% 
% v0.0.6 Mar 20, 2000 Added papersize settings. (Mar 28: these are now in fixseminar.sty)
%
% v0.0.7 Apr 07, 2000 Removed dependency on hyperref; added support for color emphasis; respect the display option;
%                     now loading tpsettings.cfg and tpoptions.cfg; added \bstep, \switch, \rebstep, \reswitch.
%
% v0.0.7a Apr 28, 2000 \pause and \stepwise now use \leaders for inserting duplicated parts of pages. This way,
%                      processing of whatsits is turned off in the duplicates so that table of contents entries are no
%                      longer duplicated when a section occurs on a page where \pause or \stepwise is used (spotted by
%                      heiner richter). Thanks to Heiko Oberdiek for his suggestion how \leaders can be successfully
%                      applied for this purpose.
%                      \stepwise now does the right thing if no \step command occurs in <contents>.
%                      There was a bug in \save@TP which would become apparent if \stepwise was the first thing on a
%                      page. Spotted and fixed by Ross Moore (thanks!).
%
% v0.0.7b May 04, 2000 \@ifpackagelater{hyperref}{2000/03/22} changed to \@ifpackagelater{hyperref}{2000/03/23}. Spotted
%                      by Ross Moore. 
%
% v0.0.7c May 06, 2000 \eject changed to \newpage in \stepwise to cure some problems with the foils package. Spotted
%                      by Ross Moore. 
%
% v0.0.7d May 18, 2000 \everydisplay finally removed from colormath option because it only causes trouble. Maybe I
%                      should look for a less fragile solution for the whole thing. Fixed a bug in texpower's definition
%                      of \set@page@color (used only if pdftex.def doesn't define it) which would cause a fatal error if
%                      two \pagecolor commands occur. Added command \replacecolor.
%
% v0.0.8  May 24, 2000 Now providing two methods for creating duplicates of page contents (used by \pause and
%                      \stepwise). The former default method using \leaders, which leads to problems with footnotes
%                      (spotted by heiner richter), is now activated by the newly introduced option
%                      robustduplicates. The new default method uses \unvbox as the \pause command from texpause.sty,
%                      but redefines \write for suppressing duplicate toc and bookmark entries due to duplicated
%                      whatsits. 
%                      Changed the way \liststepwise and \parstepwise are implemented. Instead of wrapping the whole
%                      <contents> in a minipage (which caused a lot of problems), an invisible \hrule is inserted in
%                      front of <contents>, which seems to do the job as well. With option robustduplicates, this seems
%                      to be unneccessary for \parstepwise.
%                      Now all counters are saved before \stepwise starts and restored for every \step. This remedies
%                      problems with equation numbers etc.
%                      Added a modification for the slides class so that slides are not centered if the display option
%                      is given.
%                      Option slifonts now also handles math fonts.
%                      Added a \hidetext command which respects line breaks (needs soul package).
%
% v0.0.8a Jun 02, 2000 Fixed a bug in the code which disables \pageDuration if the pdfpageduration key doesn't exist
%                      (spotted by Friedrich Eisenbrand).
%
% v0.0.8b Jun 09, 2000 Added additional `dimmed' and `enhanced' color sets for all standard colors, with corresponding
%                      commands \dimcolors and \enhancecolors.
%                      Added a `color stack correction' option fixcolorstack, which should avoid that the duplication of
%                      ``color push'' and ``color pop'' specials confuses the driver's color stack
%                      (spotted by Ross Moore).
%                      Added new display commands \hidedimmed, \hidevanish, \highlightenhanced.
%                      Added \step variants \dstep and \vstep.
%                      Added patches for \[, equation, eqnarray, and eqnarray* when the colormath option is used.
%                      Now also saving and restoring footnotes at \pause and \stepwise.
%                      Added a command \releasecounter to keep a counter from `freezing' during the execution of
%                      \stepwise. 
%
% v0.0.8c Jun 13, 2000 The default duplication method will now (only) attack \protected@write. There's a new option
%                      hackwrite which restores the former default method (of attacking \write).
%                      Corrected a bug newly introduced into \switch with version 0.0.8b.
%                      Corrected a bug in the color correction code (spotted by Ross Moore).
%
% v0.0.8d Jun 15, 2000 Corrected a minor quirk in \hidetext.
%                      Added a command \addTPcolor for defining new `standard' colors.
%                      In printout versions, the last step will no longer think it's `first activated'.
%
% v0.0.8e Jun 21, 2000 Yet another rewrite of the page duplication code. I hope it's perfect this time :)
%                      The options robustduplicates and hackwrite are obsolete now.
%                      Thanks to Martin Schroeder for permission to use his everyshi code.
%                      Fixed a small quirk in \dstep and \vstep.
%                      \darkbackground and relatives now set both page and text color.
%
% v0.0.8f Jun 27, 2000 A small change in the definition of \liststepwise to enhance vertical spacing.
%


\def\fileversion{0.0.8f}
\def\filedate{2000/06/27}

\NeedsTeXFormat{LaTeX2e}

\ProvidesPackage%
{texpower}%
[\filedate\space Create Dynamic Presentations with LaTeX. v\fileversion]


%=======================================================================================================================
% We need the programming tools provided by these packages.

\RequirePackage{ifthen}
\RequirePackage{calc}

%=======================================================================================================================
% Options and general setup.

% The option verbose turns on some automatic messages.

\newboolean{verbose@TP}
\DeclareOption{verbose}{\setboolean{verbose@TP}{true}}


% The (global) option display is respected and turns on the `dynamic' features.

\provideboolean{display}
\DeclareOption{display}{\setboolean{display}{true}}


% The option printout turns off the `dynamic' features. Can be used to undo a default setting of display.

\DeclareOption{printout}{\setboolean{display}{false}}


% The option robustduplicates switches on a more `robust' method of duplicating material when creating a sequence of
% slides.
% As of Jun 19, 2000, this option is obsolete.

\DeclareOption{robustduplicates}
{%
  \PackageWarning{texpower}
  {%
    Option robustduplicates is obsolete. Please remove.\MessageBreak
    This option will raise an error in future versions.%
    }
  }


% The option hackwrite switches on a more `thorough' method of modifying write operations for avoiding duplication of
% file entries. 
% As of Jun 19, 2000, this option is obsolete.

\DeclareOption{hackwrite}
{%
  \PackageWarning{texpower}
  {%
    Option hackwrite is obsolete. Please remove.\MessageBreak
    This option will raise an error in future versions.%
    }
  }


% The option fixcolorstack switches on a `color stack correction' method which undoes damage to the driver's color stack
% when ``color push'' and ``color pop'' specials are duplicated.

\newboolean{fixcolorstack@TP}
\DeclareOption{fixcolorstack}{\setboolean{fixcolorstack@TP}{true}}


% The option sans makes sans serif the standard Text font.

\newboolean{sans@TP}
\DeclareOption{sans}{\setboolean{sans@TP}{true}}


% The option slifonts makes L. Lamports ``slifonts'' the standard text and math fonts.

\newboolean{slifonts@TP}
\DeclareOption{slifonts}{\setboolean{slifonts@TP}{true}}


% The option coloremph makes \em and \emph switch the text color instead of the font shape.

\newboolean{TPcolor}% Are we using colors at all?
\newboolean{coloremph@TP}
\DeclareOption{coloremph}{\setboolean{TPcolor}{true}\setboolean{coloremph@TP}{true}}


% The option colormath makes math formulae be color highlighted.

\newboolean{colormath@TP}
\DeclareOption{colormath}{\setboolean{TPcolor}{true}\setboolean{colormath@TP}{true}}


% The option colorhighlight makes highlighting commands use colors.

\newboolean{setcolors@TP}% Should we set the page and text color at the beginning of the document?
\newboolean{colorhighlight@TP}
\DeclareOption{colorhighlight}
{\setboolean{TPcolor}{true}\setboolean{colorhighlight@TP}{true}\setboolean{setcolors@TP}{true}}


% The option whitebackground selects standard colors for white backgrounds.

\newboolean{whitebackground@TP}
\setboolean{whitebackground@TP}{true}% This is the default.
\DeclareOption{whitebackground}
{\setboolean{TPcolor}{true}\setboolean{whitebackground@TP}{true}\setboolean{setcolors@TP}{true}}


% The option lightbackground selects standard colors for light (but not white) backgrounds.

\newboolean{lightbackground@TP}
\DeclareOption{lightbackground}
{\setboolean{TPcolor}{true}\setboolean{lightbackground@TP}{true}\setboolean{setcolors@TP}{true}}


% The option blackbackground selects standard colors for black backgrounds.

\newboolean{blackbackground@TP}
\DeclareOption{blackbackground}
{\setboolean{TPcolor}{true}\setboolean{blackbackground@TP}{true}\setboolean{setcolors@TP}{true}}


% The option darkbackground selects standard colors for dark (but not black) backgrounds.

\newboolean{darkbackground@TP}
\DeclareOption{darkbackground}
{\setboolean{TPcolor}{true}\setboolean{darkbackground@TP}{true}\setboolean{setcolors@TP}{true}}


\InputIfFileExists{tpoptions.cfg}{}{}% Allows setting default values for options.


\ProcessOptions


% If the verbose option is set, we give a lot of context information when an error is raised.

\ifthenelse{\boolean{verbose@TP}}{\setcounter{errorcontextlines}{10000}}{}


% We provide a switch which (hopefully) allows to distinguish whether postscript specials (as used by PSTricks) can be
% used safely or not.

\newboolean{psspecialsallowed}
\setboolean{psspecialsallowed}{true} % optimistic default

% The internal switch makingpdf@TP is to determine whether pdfLaTeX is being run and outputting pdf.

\newboolean{makingpdf@TP}

\@ifundefined{pdfoutput}% Definitely not using pdftex.
{}% Standard TeX
{%  Running pdftex.
  \ifnum\pdfoutput=1\relax% Are we outputting pdf?
    \setboolean{psspecialsallowed}{false}\setboolean{makingpdf@TP}{true}%
  \fi
  }

% The following switches centering of slides off for the slides document class because this would disturb dynamic
% building of slides.

\@ifclassloaded{slides}%                Using the slides document class?
{%
  \ifthenelse{\boolean{display}}%       Dynamic features enabled?
  {\let\@topfil\relax}%                 Then don't center slides.
  {}%
  }
{}


%=======================================================================================================================
% Execute Font options.

\ifthenelse{\boolean{sans@TP}}% Option sans given?
{%
  \renewcommand{\familydefault}{\sfdefault}
}{}

\ifthenelse{\boolean{slifonts@TP}}% Option slifonts given?
{%
  \renewcommand{\familydefault}{\sfdefault}
  \renewcommand{\sfdefault}{lcmss}%                        Text fonts.
  \renewcommand{\ttdefault}{lcmtt}
  \SetSymbolFont{operators}{normal}{OT1}{lcmss}{m}{n}%     Math fonts
  \SetSymbolFont{letters}{normal}{OML}{lcmm}{m}{it}
  \SetSymbolFont{symbols}{normal}{OMS}{lcmsy}{m}{n}
%  \SetSymbolFont{largesymbols}{normal}{OMX}{lcmex}{m}{n}% This will mess up nested braces. Maybe a better solution can
%                                                        % be found.
  }
{}


%=======================================================================================================================
% Different macros for text emphasis are set up to use colors.

\ifthenelse{\boolean{TPcolor}}{\RequirePackage{color}}{}% If we are to use colors, we need the color Package.
\@ifpackageloaded{color}{\setboolean{TPcolor}{true}}{}

% \replacecolor{<col1>}{<col2>} will make <col1> have the same definition as <col2>, where <col1> and <col2> are color
% names as given in the first argument of \definecolor.
\newcommand{\replacecolor}[2]
{%
  \expandafter\let\csname\string\color @#1\expandafter\endcsname
  \csname\string\color @#2\endcsname%
}



% Emphasize proper.
\ifthenelse{\boolean{coloremph@TP}}%                       Should \emph use color?
{%  Yes;
  \DeclareRobustCommand{\em}%                              redefine \em.
  {%
    \@nomath\em \color{emcolor}%                           Change color.
    \replacecolor{tmp@TP}{emcolor}% Exchange emcolor and altemcolor.
    \replacecolor{emcolor}{altemcolor}%
    \replacecolor{altemcolor}{tmp@TP}%
    }%
  }%
{}% No; keep original definition.


% Color emphasis for math.
\ifthenelse{\boolean{colormath@TP}}%                       Should we color math?
{%  Yes.
  \AtBeginDocument
  {%
    \expandafter\everymath\expandafter{\the\everymath\color{mathcolor}}% Color inline math using \everymath.
                                                                       % Beware of side effects of this hack.
    \let\o@dm@TP=\[%                                       Color displayed math by overloading LaTeX's own math 
    \def\[{\o@dm@TP\begingroup\color{mathcolor}}%          environments.         
    \let\o@enddm@TP=\]%                                    Note that this doesn't work for the TeX notation $$, which
    \def\]{\endgroup\o@enddm@TP}%                          is deprecated in LaTeX anyway.
    \@ifpackageloaded{amsmath}{}
    {%
    \let\o@eq@TP=\equation%
    \def\equation{\o@eq@TP\begingroup\color{mathcolor}}%
    \let\o@endeq@TP=\endequation%
    \def\endequation{\endgroup\everymath{}\o@endeq@TP}%
    }%
    \let\o@eqa@TP=\eqnarray%
    \def\eqnarray{\begingroup\color{mathcolor}\o@eqa@TP}%
    \let\o@endeqa@TP=\endeqnarray%
    \def\endeqnarray{\o@endeqa@TP\endgroup\@ignoretrue}%
    \expandafter\let\expandafter\o@eqastar@TP\csname eqnarray*\endcsname%
    \@namedef{eqnarray*}{\begingroup\color{mathcolor}\o@eqastar@TP}
    \expandafter\let\expandafter\o@endeqastar@TP\csname endeqnarray*\endcsname%
    \@namedef{endeqnarray*}{\o@endeqastar@TP\endgroup\@ignoretrue}
    }%
  %
  % Sometimes, a math environment is used for something other than displaying math. The macro \origmath will put its
  % argument in math mode, but turn off coloring. If another math environemt should be nested inside the argument of
  % \origmath, it will be coloured. 
  \newcommand{\origmath}[1]{{\everymath{}\ensuremath{\everymath{\color{mathcolor}}#1}}}%
  %
  % We need to redefine some LaTeX macros which internally use math mode, to make sure that not all tabulars and
  % parboxes are coloured. 
  \renewcommand*\labelitemi{\origmath{\m@th\bullet}}%
  \def\@tabular{\leavevmode \hbox \bgroup \everymath{}$\everymath{\color{mathcolor}}\let\@acol\@tabacol
    \let\@classz\@tabclassz
    \let\@classiv\@tabclassiv \let\\\@tabularcr\@tabarray% $
    }%
  \long\def\@iiiparbox#1#2[#3]#4#5{%
    \leavevmode
    \@pboxswfalse
    \setlength\@tempdima{#4}%
    \@begin@tempboxa\vbox{\hsize\@tempdima\@parboxrestore#5\@@par}%
    \ifx\@empty#2\else\ifx\relax#2\else
      \setlength\@tempdimb{#2}%
      \def\@parboxto{to\@tempdimb}%
    \fi\fi
    \if#1b\vbox
      \else\if #1t\vtop
      \else\ifmmode\vcenter
      \else\@pboxswtrue \everymath{}$\everymath{\color{mathcolor}}\vcenter
    \fi\fi\fi
    \@parboxto{\let\hss\vss\let\unhbox\unvbox
      \csname bm@#3\endcsname}%
    \if@pboxsw \m@th$\fi
    \@end@tempboxa}
  \let\o@textsuperscript@TP=\textsuperscript
  \def\textsuperscript#1{{\everymath{}\o@textsuperscript@TP{\everymath{\color{mathcolor}}#1}}}%
  }%
{% No; keep original definition.
  \let\origmath=\ensuremath%      \origmath needs to have a sensible definition.
}


% For the following, we need the hyperref command \texorpdfstring, which is provided here in case it doesn't exist
% already. 

\AtBeginDocument{\providecommand{\texorpdfstring}[2]{##1}}

% \code is a simple emphasizing command for code-like stuff (like shell commands or macro names).
\ifthenelse{\boolean{colorhighlight@TP}}%                  Color highlighting enabled?
{%  Yes;
  \DeclareRobustCommand{\code}[1]
  {%
    \texorpdfstring%                                       The color command should only go in the document itself.
    {\textcolor{codecolor}{\textbf{\texttt{#1}}}}%         There, we change the color.
    {#1}%                                                  Otherwise, e.g. in Bookmarks, output the plain argument.
    }%
  \DeclareRobustCommand{\codeswitch}{\color{codecolor}\bfseries\ttfamily}
  }%
{%  No;
  \DeclareRobustCommand{\code}[1]{\textbf{\texttt{#1}}}%   no color. We don't need to check for Bookmarks.
  \DeclareRobustCommand{\codeswitch}{\bfseries\ttfamily}
  }

% \macroname adds the backslash in front...
\newcommand{\macroname}[1]{\code{\textbackslash#1}}

% ... and \commandapp adds the braces.
\newcommand{\commandapp}[3][]{\code{\macroname{#2}\ifthenelse{\equal{#1}{}}{}{[#1]}\{#3\}}}

% \carg is for denoting arguments.
\newcommand{\carg}[1]{\code{\origmath{\left<\code{#1}\right>}}}


% Additional emphasis command.
\ifthenelse{\boolean{colorhighlight@TP}}%                  Color highlighting enabled?
{%  Yes;
  \DeclareRobustCommand{\underl}{\textcolor{underlcolor}}% use color to highlight.
  }
{%  No;
  \DeclareRobustCommand{\underl}{\textbf}%                 use bold face.
  }


% \concept is for emphasizing names of (new) concepts.
\ifthenelse{\boolean{colorhighlight@TP}}%                  Color highlighting enabled?
{%  Yes;
  \DeclareRobustCommand{\concept}{\textcolor{conceptcolor}}% use color to highlight.
  }
{%  No;
  \DeclareRobustCommand{\concept}{\textbf}%                  use bold face.
  }


% Another emphasis command, this time for `de-emphasising'.
\ifthenelse{\boolean{colorhighlight@TP}}%                  Color highlighting enabled?
{%  Yes;
  \DeclareRobustCommand{\inactive}{\textcolor{inactivecolor}}% use color to highlight.
  }
{%  No;
  \DeclareRobustCommand{\inactive}{\monochromeinactive}%       use monochrome default.
  }

\providecommand{\monochromeinactive}{}% What should \inactive do if colors can't be used? We provide a hook for
                                      % user definitions.


% \present puts its argument into an \fbox with coloured background.
\ifthenelse{\boolean{colorhighlight@TP}}%                  Color highlighting enabled?
{%  Yes; use a colored box.
  \newcommand{\present}[2][]{\leavevmode\llap{\textbf{\footnotesize#1}\,}\fcolorbox{textcolor}{presentcolor}{#2}}%
  }
{%  No; use an \fbox.
  \newcommand{\present}[2][]{\leavevmode\llap{\textbf{\footnotesize#1}\,}\fbox{#2}}%
  }


\newcommand{\colors@TP}%             The list of all standard colors defined by texpower.
{%
  \processme@TP{pagecolor}%
  \processme@TP{textcolor}%
  \processme@TP{emcolor}%
  \processme@TP{altemcolor}%
  \processme@TP{mathcolor}%
  \processme@TP{codecolor}%
  \processme@TP{underlcolor}%
  \processme@TP{conceptcolor}%
  \processme@TP{inactivecolor}%
  \processme@TP{presentcolor}%
  \processme@TP{highlightcolor}%
}

\newcommand{\addTPcolor}[1]%
{\expandafter\def\expandafter\colors@TP\expandafter{\colors@TP\processme@TP{#1}}}

\newcommand{\replacecolors@TP}[3]%  Can be used for replacing a complete color set.
{%
  \def\processme@TP##1{\replacecolor{#1##1}{#2##1#3}}%
  \colors@TP
}

\newcommand{\dimcolors}{\replacecolors@TP{}{d}{}}

\newcommand{\enhancecolors}{\replacecolors@TP{}{e}{}}


\newcommand{\replacecolorsbyone@TP}[2]
{%
  \def\processme@TP##1{\replacecolor{#1##1}{#2}}%
  \colors@TP
}

\newcommand{\vanishcolor}{pagecolor}

\newcommand{\vanishcolors}{\replacecolorsbyone@TP{}{\vanishcolor}}


% The following commands set the `standard' colors for different background colors. Redefine in texpower.cfg as
% convenient. 

\ifthenelse{\boolean{TPcolor}}% Is color.sty loaded at all?
{%
  \definecolor{pagecolor@whitebg}{rgb}{1,1,1}%               Color definitions for white background.
  \definecolor{textcolor@whitebg}{rgb}{0,0,0.5}%
  \definecolor{emcolor@whitebg}{rgb}{0,0,0.8}%
  \definecolor{altemcolor@whitebg}{rgb}{0,0.5,0.8}%
  \definecolor{mathcolor@whitebg}{rgb}{0,0.5,0}%
  \definecolor{codecolor@whitebg}{rgb}{0,0.5,0}%
  \definecolor{underlcolor@whitebg}{rgb}{0.7,0,0.3}%
  \definecolor{conceptcolor@whitebg}{rgb}{0.6,0,0}%
  \definecolor{inactivecolor@whitebg}{rgb}{0.7,0.7,0.7}%
  \definecolor{presentcolor@whitebg}{rgb}{1,1,0.9}%
  \definecolor{highlightcolor@whitebg}{rgb}{1,1,0.8}%
  %
  \definecolor{dtextcolor@whitebg}{rgb}{0.7,0.7,0.8}%        Dimmed color definitions for white background.
  \definecolor{demcolor@whitebg}{rgb}{0.7,0.7,0.9}%
  \definecolor{daltemcolor@whitebg}{rgb}{0.7,0.8,0.9}%
  \definecolor{dmathcolor@whitebg}{rgb}{0.7,0.8,0.7}%
  \definecolor{dcodecolor@whitebg}{rgb}{0.7,0.8,0.7}%
  \definecolor{dunderlcolor@whitebg}{rgb}{0.9,0.7,0.8}%
  \definecolor{dconceptcolor@whitebg}{rgb}{0.8,0.7,0.7}%
  \definecolor{dinactivecolor@whitebg}{rgb}{0.9,0.9,0.9}%
  \definecolor{dpresentcolor@whitebg}{rgb}{1,1,0.95}%
  \definecolor{dhighlightcolor@whitebg}{rgb}{1,1,0.9}%
  %
  \definecolor{etextcolor@whitebg}{rgb}{0,0,0.7}%            Enhanced color definitions for white background.
  \definecolor{eemcolor@whitebg}{rgb}{0,0,1}%
  \definecolor{ealtemcolor@whitebg}{rgb}{0,0.6,0.9}%
  \definecolor{emathcolor@whitebg}{rgb}{0,0.6,0}%
  \definecolor{ecodecolor@whitebg}{rgb}{0,0.6,0}%
  \definecolor{eunderlcolor@whitebg}{rgb}{0.8,0,0.4}%
  \definecolor{econceptcolor@whitebg}{rgb}{0.8,0,0}%
  \definecolor{einactivecolor@whitebg}{rgb}{0.6,0.6,0.6}%
  \definecolor{epresentcolor@whitebg}{rgb}{1,1,0.8}%
  \definecolor{ehighlightcolor@whitebg}{rgb}{1,1,0.7}%
  }{}

\newcommand{\whitebackground}%                             Set standard colors.
{%
  \replacecolors@TP{}{}{@whitebg}%
  \replacecolors@TP{d}{d}{@whitebg}%
  \replacecolors@TP{e}{e}{@whitebg}%
  %\pagecolor{pagecolor}%
  \color{textcolor}%
}

% Execute \whitebackground automatically if either of the color options was given.

\ifthenelse
{%
  \boolean{whitebackground@TP}% This switch is set by default, ...
  \and\boolean{TPcolor}%       so we need to check whether _any_ color option was given.
  }
{\AtEndOfPackage{\whitebackground}}% Execute after texpower.cfg was read (for redefinitions).
{}


\ifthenelse{\boolean{TPcolor}}
{%
  \definecolor{pagecolor@lightbg}{rgb}{1,1,0.9}%               Standard color definitions for light background.
  \definecolor{textcolor@lightbg}{rgb}{0,0,0.5}%
  \definecolor{emcolor@lightbg}{rgb}{0,0,0.8}%
  \definecolor{altemcolor@lightbg}{rgb}{0,0.5,0.8}%
  \definecolor{mathcolor@lightbg}{rgb}{0,0.4,0}%
  \definecolor{codecolor@lightbg}{rgb}{0,0.5,0}%
  \definecolor{underlcolor@lightbg}{rgb}{0.7,0,0.3}%
  \definecolor{conceptcolor@lightbg}{rgb}{0.6,0,0}%
  \definecolor{inactivecolor@lightbg}{rgb}{0.7,0.7,0.7}%
  \definecolor{presentcolor@lightbg}{rgb}{1,1,1}%
  \definecolor{highlightcolor@lightbg}{rgb}{1,1,0.6}%
  %
  \definecolor{dtextcolor@lightbg}{rgb}{0.7,0.7,0.8}%          Dimmed color definitions for light background.
  \definecolor{demcolor@lightbg}{rgb}{0.7,0.7,0.9}%
  \definecolor{daltemcolor@lightbg}{rgb}{0.7,0.8,0.9}%
  \definecolor{dmathcolor@lightbg}{rgb}{0.7,0.8,0.7}%
  \definecolor{dcodecolor@lightbg}{rgb}{0.7,0.9,0.7}%
  \definecolor{dunderlcolor@lightbg}{rgb}{0.9,0.7,0.8}%
  \definecolor{dconceptcolor@lightbg}{rgb}{0.8,0.7,0.7}%
  \definecolor{dinactivecolor@lightbg}{rgb}{0.9,0.9,0.9}%
  \definecolor{dpresentcolor@lightbg}{rgb}{1,1,.95}%
  \definecolor{dhighlightcolor@lightbg}{rgb}{1,1,0.8}%
  %
  \definecolor{etextcolor@lightbg}{rgb}{0,0,0.7}%              Enhanced color definitions for light background.
  \definecolor{eemcolor@lightbg}{rgb}{0,0,1}%
  \definecolor{ealtemcolor@lightbg}{rgb}{0,0.6,0.9}%
  \definecolor{emathcolor@lightbg}{rgb}{0,0.6,0}%
  \definecolor{ecodecolor@lightbg}{rgb}{0,0.65,0}%
  \definecolor{eunderlcolor@lightbg}{rgb}{0.8,0,0.4}%
  \definecolor{econceptcolor@lightbg}{rgb}{0.8,0,0}%
  \definecolor{einactivecolor@lightbg}{rgb}{0.6,0.6,0.6}%
  \definecolor{epresentcolor@lightbg}{rgb}{.95,1,.95}%
  \definecolor{ehighlightcolor@lightbg}{rgb}{1,1,0.4}%
}{}

\newcommand{\lightbackground}%                               Set standard colors.
{%
  \replacecolors@TP{}{}{@lightbg}%
  \replacecolors@TP{d}{d}{@lightbg}%
  \replacecolors@TP{e}{e}{@lightbg}%
  \pagecolor{pagecolor}%
  \color{textcolor}%
}

% Execute \lightbackground automatically if the lightbackground option was given.

\ifthenelse{\boolean{lightbackground@TP}}{\AtEndOfPackage{\lightbackground}}{}


\ifthenelse{\boolean{TPcolor}}
{%
  \definecolor{pagecolor@darkbg}{rgb}{0,0,0.4}%               Standard color definitions for dark background.
  \definecolor{textcolor@darkbg}{rgb}{1,1,0.6}%
  \definecolor{emcolor@darkbg}{rgb}{1,1,0}%
  \definecolor{altemcolor@darkbg}{rgb}{1,0.6,0}%
  \definecolor{mathcolor@darkbg}{rgb}{1,0.5,1}%
  \definecolor{codecolor@darkbg}{rgb}{0,0.7,0}%
  \definecolor{underlcolor@darkbg}{rgb}{0.3,1,0.7}%
  \definecolor{conceptcolor@darkbg}{rgb}{0.4,1,1}%
  \definecolor{inactivecolor@darkbg}{rgb}{0.4,0.4,0.4}%
  \definecolor{presentcolor@darkbg}{rgb}{0,0,0}%
  \definecolor{highlightcolor@darkbg}{rgb}{0,0,0.1}%
  %
  \definecolor{dtextcolor@darkbg}{rgb}{0.5,0.5,0.4}%          Dimmed color definitions for dark background.
  \definecolor{demcolor@darkbg}{rgb}{0.5,0.5,0}%
  \definecolor{daltemcolor@darkbg}{rgb}{0.5,0.4,0}%
  \definecolor{dmathcolor@darkbg}{rgb}{0.5,0.2,0.5}%
  \definecolor{dcodecolor@darkbg}{rgb}{0,0.5,0}%
  \definecolor{dunderlcolor@darkbg}{rgb}{0.1,0.5,0.3}%
  \definecolor{dconceptcolor@darkbg}{rgb}{0.2,0.5,0.5}%
  \definecolor{dinactivecolor@darkbg}{rgb}{0.2,0.2,0.2}%
  \definecolor{dpresentcolor@darkbg}{rgb}{0,0,0.2}%
  \definecolor{dhighlightcolor@darkbg}{rgb}{0,0,0.3}%
  %
  \definecolor{etextcolor@darkbg}{rgb}{1,1,0.8}%               Enhanced color definitions for dark background.
  \definecolor{eemcolor@darkbg}{rgb}{1,1,0.3}%
  \definecolor{ealtemcolor@darkbg}{rgb}{1,0.8,0}%
  \definecolor{emathcolor@darkbg}{rgb}{1,0.6,1}%
  \definecolor{ecodecolor@darkbg}{rgb}{0,0.9,0}%
  \definecolor{eunderlcolor@darkbg}{rgb}{0.4,1,0.8}%
  \definecolor{econceptcolor@darkbg}{rgb}{0.7,1,1}%
  \definecolor{einactivecolor@darkbg}{rgb}{0.5,0.5,0.5}%
  \definecolor{epresentcolor@darkbg}{rgb}{0.1,0,0}%
  \definecolor{ehighlightcolor@darkbg}{rgb}{0,0,0}%
  }{}

\newcommand{\darkbackground}%                               Set standard colors.
{%
  \replacecolors@TP{}{}{@darkbg}%
  \replacecolors@TP{d}{d}{@darkbg}%
  \replacecolors@TP{e}{e}{@darkbg}%
  \pagecolor{pagecolor}%
  \color{textcolor}%
}

% Execute \darkbackground automatically if the darkbackground option was given.

\ifthenelse{\boolean{darkbackground@TP}}{\AtEndOfPackage{\darkbackground}}{}


\ifthenelse{\boolean{TPcolor}}
{%
  \definecolor{pagecolor@blackbg}{rgb}{0,0,0}%               Color definitions for black background.
  \definecolor{textcolor@blackbg}{rgb}{1,1,0.6}%
  \definecolor{emcolor@blackbg}{rgb}{1,1,0}%
  \definecolor{altemcolor@blackbg}{rgb}{1,0.5,0}%
  \definecolor{mathcolor@blackbg}{rgb}{1,0.5,1}%
  \definecolor{codecolor@blackbg}{rgb}{0,0.7,0}%
  \definecolor{underlcolor@blackbg}{rgb}{0.3,1,0.7}%
  \definecolor{conceptcolor@blackbg}{rgb}{0.4,1,1}%
  \definecolor{inactivecolor@blackbg}{rgb}{0.4,0.4,0.4}%
  \definecolor{presentcolor@blackbg}{rgb}{0,0,0.3}%
  \definecolor{highlightcolor@blackbg}{rgb}{0,0,0.4}%
  %
  \definecolor{dtextcolor@blackbg}{rgb}{0.4,0.4,0.3}%             Dimmed color definitions for black background.
  \definecolor{demcolor@blackbg}{rgb}{0.4,0.4,0}%
  \definecolor{daltemcolor@blackbg}{rgb}{.4,0.2,0}%
  \definecolor{dmathcolor@blackbg}{rgb}{0.4,0.2,0.4}%
  \definecolor{dcodecolor@blackbg}{rgb}{0,0.4,0}%
  \definecolor{dunderlcolor@blackbg}{rgb}{0.1,0.4,0.2}%
  \definecolor{dconceptcolor@blackbg}{rgb}{0.1,0.4,0.4}%
  \definecolor{dinactivecolor@blackbg}{rgb}{0.2,0.2,0.2}%
  \definecolor{dpresentcolor@blackbg}{rgb}{0,0,0.1}%
  \definecolor{dhighlightcolor@blackbg}{rgb}{0,0,0.15}%
  %
  \definecolor{etextcolor@blackbg}{rgb}{1,1,0.8}%             Enhanced color definitions for black background.
  \definecolor{eemcolor@blackbg}{rgb}{1,1,0.3}%
  \definecolor{ealtemcolor@blackbg}{rgb}{1,0.4,0}%
  \definecolor{emathcolor@blackbg}{rgb}{1,0.6,1}%
  \definecolor{ecodecolor@blackbg}{rgb}{0,0.9,0}%
  \definecolor{eunderlcolor@blackbg}{rgb}{0.4,1,0.8}%
  \definecolor{econceptcolor@blackbg}{rgb}{0.7,1,1}%
  \definecolor{einactivecolor@blackbg}{rgb}{0.5,0.5,0.5}%
  \definecolor{epresentcolor@blackbg}{rgb}{0,0,0.4}%
  \definecolor{ehighlightcolor@blackbg}{rgb}{0,0,0.5}%
}{}

\newcommand{\blackbackground}%                               Set standard colors.
{%
  \replacecolors@TP{}{}{@blackbg}%
  \replacecolors@TP{d}{d}{@blackbg}%
  \replacecolors@TP{e}{e}{@blackbg}%
  \pagecolor{pagecolor}%
  \color{textcolor}%
}

% Execute \blackbackground automatically if the blackbackground option was given.

\ifthenelse{\boolean{blackbackground@TP}}{\AtEndOfPackage{\blackbackground}}{}


% Not all drivers define \set@page@color, which can lead to an error message when the \pagecolor command is used. When
% running pdftex, we check whether \set@page@color is defined. If it isn't, we can use a solution posted to the
% pdfTeX mailing list by Radhakrishnan C V. 


\ifthenelse{\boolean{TPcolor}}% Is color.sty loaded at all?
{% Yes. 
  \ifthenelse{\boolean{makingpdf@TP}}%    Running pdftex?
  {% Yes.
    \@ifundefined{set@page@color}% Does \set@page@color exist?
    {% No. Old version of pdftex.cfg. But we can use Radhakrishnan C V ' s solution.
      \newlength{\pdfvextent@TP}
      \newlength{\pdfhextent@TP}

      \def\set@page@color
      {%
        \global\let\current@page@color@TP\current@color% Save color setting for later use.
        \ifx\@begindvi\@begindvi@TP%                   % Have we already taken over \@begindvi?
         \else\global\let\orig@begindvi@TP\@begindvi   % No. Save the current definition.
        \fi%          
        \gdef\@begindvi@TP%                              Our own definition of \@begindvi
        {%
          \orig@begindvi@TP%                             Whatever \@begindvi used to mean.
          \setlength{\pdfvextent@TP}{2\pdfpageheight}%   ... just to make sure ...
          \addtolength{\pdfvextent@TP}{\pdfvorigin}%
          \setlength{\pdfhextent@TP}{\pdfpagewidth}%
          \addtolength{\pdfhextent@TP}{\pdfhorigin}%
          \pdfliteral{q \current@page@color@TP\space n -\strip@pt\pdfhorigin\space -\strip@pt\pdfpageheight\space \strip@pt\pdfhextent@TP\space \strip@pt\pdfvextent@TP\space re f Q}% That's the magic part.
          \fix@color@TP%                                  Color management doesn't work with seminar when pdflatex is
                       %                                  used. This is a kluge which almost restores the standard
                       %                                  behaviour of colors with pdflatex (which is quite wrong still).
          \ifx\@begindvi\@begindvi@TP%                   It seems to be a custom (*yuck*) to \global\let \@begindvi to
                                     %                   something else _within_ \@begindvi... So we check whether
                                     %                   \@begindvi still means what _we_ wish it to mean.
           \else% No.
             \global\let\orig@begindvi@TP\@begindvi%      Save the new definition...
             \global\let\@begindvi\@begindvi@TP%          ... and restore our own definition.
          \fi
          }%
        \global\let\@begindvi\@begindvi@TP%              Takeover of \@begindvi completed.
        }%

      \let\fix@color@TP=\relax% Do nothing by default.
  
      \@ifclassloaded{seminar}% Using seminar?
      {% Yes.
        \let\fix@color@TP=\set@color% This kluge will set the text color to \current@color at the beginning of every
                                    % slide. Hope \current@color has a meaningful value at this time...
                                    % Maybe we should use \normalcolor instead?
        }%
      {}% No.
      }
    {% Yes. No changes needed.
      \@ifclassloaded{seminar}% Using seminar?
      {% Yes. We still need to include the \set@color kluge.
        \global\let\orig@begindvi@TP\@begindvi%          \@begindvi is defined by several parties.
        \gdef\@begindvi@TP%                              Our own definition of \@begindvi
        {%
          \orig@begindvi@TP%                             Whatever \@begindvi used to mean.
          \set@color%                                  Color management doesn't work with seminar when pdflatex is
                    %                                  used. This is a kluge which almost restores the standard
                    %                                  behaviour of colors with pdflatex (which is quite wrong still).
          \ifx\@begindvi\@begindvi@TP%                   It seems to be a custom (*yuck*) to \global\let \@begindvi to
                                     %                   something else _within_ \@begindvi... So we check whether
                                     %                   \@begindvi still means what _we_ wish it to mean.
           \else% No.
             \global\let\orig@begindvi@TP\@begindvi%      Save the new definition...
             \global\let\@begindvi\@begindvi@TP%          ... and restore our own definition.
          \fi
          }%
        \global\let\@begindvi\@begindvi@TP%              Takeover of \@begindvi completed.
        }%
      {}%
      }% 
    }%
  {}% No. There's nothing to do.
  }%
{}% No.

% If we should set the page and text color, this is done with \AtBeginDocument.

\ifthenelse{\boolean{setcolors@TP}}
{%
  \AtBeginDocument{\color{textcolor}\pagecolor{pagecolor}}%
  }



%=======================================================================================================================
% Most of the following is snarfed from an email message of Marc van Dongen to the ppower4 mailing list on Thu, 7 Oct
% 1999. 
% The commands set acrobat reader's page transition mode.
% Thanks to Marc for his permission to include his code into this package.

\ifthenelse{\boolean{display}}%       Are dynamic features enabled?
{% Yes.
  \newcommand{\pagetransition}[1]%       Definition for preamble.
  {%
    \@ifpackageloaded{hyperref}%         Can we use \hypersetup?
    {% Yes.
      \hypersetup{pdfpagetransition={#1}}% Set page transition with \hypersetup.
      }
    {% No. In this case, we can't set the page transition.
      \PackageWarning{texpower}
      {Package hyperref not loaded.\MessageBreak Page transition not set}%
      }%
    }%
  \AtBeginDocument%                      Definition for document body.
  {%
    \@ifpackageloaded{hyperref}%         Can we use \hypersetup?
    {% Yes.
      \renewcommand{\pagetransition}[1]{\hypersetup{pdfpagetransition={#1}}}%
      }
    {% No. Disable page transitions.
      \PackageWarning{texpower}
      {Package hyperref not loaded.\MessageBreak Page transitions disabled}%
      \let\pagetransition=\@gobble
      }% 
    }%
  }
{\let\pagetransition=\@gobble}% No. Disable page transitions.


\newcommand{\pageTransitionSplitHO}{\pagetransition{Split /Dm /H /M /O}}% Split Horizontally to the outside.

\newcommand{\pageTransitionSplitHI}{\pagetransition{Split /Dm /H /M /I}}% Split Horizontally to the inside.

\newcommand{\pageTransitionSplitVO}{\pagetransition{Split /Dm /V /M /O}}% Split Vertically to the outside.

\newcommand{\pageTransitionSplitVI}{\pagetransition{Split /Dm /V /M /I}}% Split Vertically to the inside.

\newcommand{\pageTransitionBlindsH}{\pagetransition{Blinds /Dm /H}}% Horizontal Blinds.

\newcommand{\pageTransitionBlindsV}{\pagetransition{Blinds /Dm /V}}% Vertical Blinds.

\newcommand{\pageTransitionBoxO}{\pagetransition{Box /M /O}}% Growing Box.

\newcommand{\pageTransitionBoxI}{\pagetransition{Box /M /I}}% Shrinking Box.


% argument must be number fom 0 to 360
\newcommand{\pageTransitionWipe}[1]{\pagetransition{Wipe /Di #1}}% Wipe from one edge of the page to the facing edge.

 
\newcommand{\pageTransitionDissolve}{\pagetransition{Dissolve}}% Dissolve.
 
% argument must be number fom 0 to 360
\newcommand{\pageTransitionGlitter}[1]{\pagetransition{Glitter /Di #1}}% Glitter from one edge to the facing edge.

\newcommand{\pageTransitionReplace}{\pagetransition{Replace}}% Simple Replace (the default). 



%=======================================================================================================================
% We define a command for setting automatic advancing of pages. 
%
% Usage: \pageDuration{<d>}
%
% <d> should be a (fixed-point) number. Pages will be advanced automatically every <d> seconds. 
%

\ifthenelse{\boolean{display}}%            Are dynamic features enabled?
{% Yes.
  \newcommand{\pageDuration}[1]%           Definition for preamble.
  {%
    \@ifpackageloaded{hyperref}%           Can we use \hypersetup?
    {% Yes.
      \@ifpackagelater{hyperref}{2000/03/23}%         Can we use \hypersetup{pdfpageduration=...}?
      {% Yes.
        \hypersetup{pdfpageduration={#1}}% Set page duration with \hypersetup.
        }
      {% No. In this case, we can't set the page duration.
        \PackageWarning{texpower}
        {Package hyperref too old (older than v6.70a).\MessageBreak Page duration not set}%
        }%
      }%
    {% No. In this case, we can't set the page duration.
      \PackageWarning{texpower}
      {Package hyperref not loaded.\MessageBreak Page duration not set}%
      }%
    }%
  \AtBeginDocument%                      Make sure this also works if texpower is loaded before hyperref.
  {%
    \@ifpackageloaded{hyperref}%                    Can we use \hypersetup?
    {% Yes.
      \@ifpackagelater{hyperref}{2000/03/23}%       Can we use \hypersetup{pdfpageduration=...}?
      {% Yes.
        \renewcommand{\pageDuration}[1]{\hypersetup{pdfpageduration={#1}}}% Set page duration with \hypersetup.
        }%
      {% No. In this case, we can't set the page duration.
        \PackageWarning{texpower}
        {Package hyperref too old (older than v6.70a).\MessageBreak Page duration disabled}%
        \let\pageDuration=\@gobble
        }%
      }%
    {% No. In this case, we can't set the page duration.
      \PackageWarning{texpower}
      {Package hyperref not loaded.\MessageBreak Page duration disabled}%
      \let\pageDuration=\@gobble
      }%
    }%
  }%
{\let\pageDuration=\@gobble}% No. Disable page duration.

\newcommand{\stopAdvancing}{\pageDuration{}}% Stop automatic advancing of pages.


%=======================================================================================================================
% The following code is derived from Klaus Guntermanns texpause package which can be obtained from the PPower4 Web site
%
% http://www-sp.iti.informatik.tu-darmstadt.de/software/ppower4/
%
% The code implements the macro \save@TP (used internally) and the macro \pause.
%
% Usage: \pause
%
% \pause will end the current paragraph, ship out the current page, start a new page and copy whatever was on the
% current page onto the new page, where typesetting is resumed. This will create the effect of a `pause' in the
% presentation, i.e. the presentation stops because the current page ends at the point where the \pause command occurred
% and is resumed at this point when the presenter switches to the next page.  
%
% Thanks to Heiko Oberdiek for his suggestion how \leaders can be used to disable processing of whatsits in the
% duplicated text.

\AtBeginDocument{\shipoutinit@TP}%  The following code from everyshi.sty is used with permission from Martin Schroeder.

\newcommand*{\shipoutinit@TP}
{%
  \let\o@shipout@TP=\shipout
  \let\shipout\shipout@TP
  }%

\newcommand{\shipout@TP}
{%
  \afterassignment\shipout@test@TP
  \global\setbox\@cclv= %
  }%

\newcommand{\shipout@test@TP}
{%
  \ifvoid\@cclv\relax
  \aftergroup\shipout@output@TP
  \else
  \shipout@output@TP
  \fi%
  }%

\newcommand{\shipout@output@TP}
{%
  \shipout@hook@TP%
  \o@shipout@TP\box\@cclv%
  }%

\newcommand{\shipout@hook@TP}
{%
  \filterpage@TP
}

\let\filterpage@TP\relax


\def\colorcorrections@TP{\relax}%    The list of color correction codes (only needed for drivers with color stack).

\ifthenelse{\boolean{fixcolorstack@TP}}
{%
  \ifthenelse{\boolean{TPcolor}}% Is color.sty loaded at all?
  {% Yes. 
    \ifthenelse{\boolean{makingpdf@TP}}% Making PDF?
    {% Yes. No need to change anything.
      \PackageInfo{texpower}
      {pdftex has no color stack. Option fixcolorstack disabled.}%
      }
    {% No. We need to add corrections for the color stack...
                                %
    \expandafter\def\expandafter\shipout@hook@TP\expandafter
    {\shipout@hook@TP\clearcolorcorrections@TP}% This is our own code `smuggled' into \shipout.
                                %
    \newcommand{\clearcolorcorrections@TP}%                   Clear the list on `normal' page breaks.
    {\ifshippingduplicate\else\gdef\colorcorrections@TP{\relax}\fi}%
                                %
    \expandafter\def\expandafter\o@set@color@TP\expandafter%     Pray to god all drivers will support these hacks...
    {%
      \set@color
      \expandafter\aftergroup\csname\current@color\endcsname%
      }%
    \let\o@reset@color@TP=\reset@color
    \def\remove@resetcolor@TP#1\aftergroup\reset@color{\def\pushcolor@TP##1{{\def\current@color{##1}#1}}}%
    \expandafter\remove@resetcolor@TP\set@color
    %
    \def\pushcolorname@TP#1%
    {%
      \begingroup \escapechar\m@ne\xdef\@gtempa{\string#1}\endgroup
      \expandafter\pushcolor@TP\expandafter{\@gtempa}%
      }%
    %
    \def\set@color%           Our own versions of \set@color and \reset@color maintain a `stack' of color corrections.
    {%
%      \typeout{\current@color}%
      \o@set@color@TP
      \expandafter\@temptokena\expandafter{\colorcorrections@TP}%
      \xdef\colorcorrections@TP{\noexpand\o@reset@color@TP\the\@temptokena}%
      }
    \def\reset@color#1%
    {%
%      \typeout{reset: \string#1}%
      \expandafter\addpushtoccor@TP\colorcorrections@TP\@nil{#1}%
      \o@reset@color@TP
      }%
    \def\addpushtoccor@TP#1#2\@nil#3%
    {%
      \ifx\o@reset@color@TP#1%
        \gdef\colorcorrections@TP{#2}%
       \else
        \gdef\colorcorrections@TP{\pushcolorname@TP{#3}#1#2}%
      \fi
      }%
    }%
  }
{%
  \PackageWarning{texpower}
  {color package not loaded. Option fixcolorstack disabled.}%
  }
}
{}
  
  
\newbox\mempageconts@TP
\newinsert\memfootins@TP
\newtoks\memtoks@TP
\newcount\mempageno@TP
\newif\ifshippingduplicate% 

\providecommand{\TPeject}{\newpage}

\newcommand{\outputduplicate@TP}
{%
  \shippingduplicatetrue
  \global\let\filterpage@TP\filterwhatsits@TP
  \TPeject
  \global\let\filterpage@TP\relax
  \shippingduplicatefalse
  }%

\newcommand{\filterwhatsits@TP}
{%
  \global\setbox\@cclv=\hbox{\leaders\copy\@cclv\hskip\wd\@cclv}%
}

\newcommand{\do@colorcorrections@TP}
{%
  {%
    \colorcorrections@TP
    \gdef\colorcorrections@TP{\relax}%
    }%
  }

\newcommand{\filterpageconts@TP}{}%                No filtering needed for the default method.

\newcommand{\insertfirstduplicate@TP}
{\unvcopy\mempageconts@TP}%                        Output the vbox's contents.

\newcommand{\insertsecondduplicate@TP}
{%
  \do@colorcorrections@TP%
  \global\setbox\footins=\copy\memfootins@TP%      Restore footnotes.
  \global\skip\footins=\skip\memfootins@TP
  \global\count\footins=\count\memfootins@TP
  \global\dimen\footins=\dimen\memfootins@TP
  \unvcopy\mempageconts@TP%                        Output the vbox's contents.
  }

\def\save@TP
{%
  \par%                                             Always end current paragraph.
  \global\setbox\mempageconts@TP=\copy\voidb@x%     Initialise \mempageconts@TP (suggested by Ross Moore).
  \global\mempageno@TP=\count0\relax%               Save pagenumber.
  \memtoks@TP=\output%                              Make backup copy of output routine.
  \output={\global\setbox\mempageconts@TP=\box\@cclv}% Copy current contents.
  \eject%                                           Trigger now.
  \global\setbox\memfootins@TP=\copy\footins%       Save footnotes.
  \global\skip\memfootins@TP=\skip\footins
  \global\count\memfootins@TP=\count\footins
  \global\dimen\memfootins@TP=\dimen\footins
  \output=\memtoks@TP%                              Restore output routine.
  \filterpageconts@TP%                              Just in case anything has to be filtered out.
  }


\providecommand\pause% If pause.sty is loaded, the existing definition of \pause is not overwritten.
{%
  \save@TP%                                         Save contents of the page...
  \insertfirstduplicate@TP%                         ... and insert again (with whatsits).
  \ifthenelse{\boolean{display}}%                   Are dynamic features enabled?
  {% Yes.
    \outputduplicate@TP%                            Output page.
    \global\count0=\mempageno@TP\relax%             Restore page number.
    \insertsecondduplicate@TP%                      Reinsert saved contents without whatsits.
    }
  {}%
  }%


%=======================================================================================================================
% The following code implements the macro \stepwise.
%
% Usage: \stepwise{<contents>}
%
% As of itself, \stepwise doesn't do very much. If <contents> contains one or more constructs of the form
% \step{<stepcontents>}, the following happens: 
%
% 1. The current paragraph is ended.
%
% 2. The current contents of the page are saved (as with \pause).
%
% 3. As many pages as there are \step commands in <contents> are produced.
%    Every page starts with what was on the current page when \stepwise started.
%    The first page also contains everything in <contents> which is not in <stepcontents> for any \step command. 
%    The second page additionally contains the <stepcontents> for the first \step command, and so on, until all
%    <stepcontents> are displayed. 
%
% 4. When all <stepcontents> are displayed, \stepwise ends and typesetting is resumed (still on the current page). 
%  
% This will create the effect that the \step commands are executed `step by step'.

% Now for the implementation...

%-----------------------------------------------------------------------------------------------------------------------
% User interface.
%
% Some registers, macros and environments which are used internally are part of the user interface, so no @s.

\newcounter{totalsteps}           % The total number of \step commands occurring in <contents>.

\newcounter{firststep}            % The number at which the counter step starts counting. Can be set in the optional
                                  % argument of \stepwise.

\newcounter{step}                 % The number of the step currently being performed.

\newcounter{stepcommand}          % The number of the current \step command (only useful inside <stepcontents>).

\newcounter{stepsperformed}       % The total number of \step commands which have been activated so far (this can differ
                                  % from \value{step} if the order of \step commands is changed via the optional
                                  % argument of \step.

\newboolean{firstactivation}      % Is this \step command currently active for the first time? (only useful inside
                                  % <stepcontents>) .

\newboolean{active}               % Is this \step command currently active? (only useful inside <stepcontents>).


% The following are custom commands for displaying <stepcontents>. Some of them are selected by the switches \boxedsteps
% and \nonboxedsteps.  

\newcommand{\displayboxed}        % Display <stepcontents> in a box.
{%
  \ifmmode                        % We need to distinguish between math and text mode.
    \expandafter\mathpalette\expandafter\math@db@TP  % In math mode, the style has to be respected.
  \else
    \expandafter\text@db@TP
  \fi
}
\newcommand{\text@db@TP}[1]{\mbox{#1}}            % In text mode, we just use an \mbox.
\newcommand{\math@db@TP}[2]{\mbox{$\m@th#1{#2}$}} % In math mode, the style (#1) is inserted by \mathpalette.

\let\displayidentical=\@iden      % Don't touch <stepcontents>.

\newcommand{\hidephantom}[1]      % Hide <stepcontents>, but display an appropriate amount of white space.
{%
  {% a group makes redefinitions local
    \let\@@switch@TP=\@secondoftwo      % What happes if \step or \switch commands are nested? \step, \switch, \restep
    \let\restep=\proper@step@TP         % and \reswitch are redefined to produce their contents, but don't touch any 
    \let\rebstep=\proper@bstep@TP       % counters.
    \let\reswitch=\proper@switch@TP     
    \leavevmode\phantom{#1}%            % \phantom normally produces an \hbox. \leavevmode makes it behave like \mbox.
    }%
  }

\let\hideignore=\@gobble          % Ignore <stepcontents> completely.

% The command \hidetext makes its argument `invisible', but without putting it into a box, thus preserving line
% breaks. It' implemented using soul.sty.

\AtBeginDocument
{%
  \@ifpackageloaded{soul}%                                      Can we use the soul package?
  {% Yes. Let's define the necessary macros.
    \DeclareRobustCommand*\hidetext
    {%
      \leavevmode
      \let\SOUL@preamble=\relax%                                No special treatment neccessary.
      \let\SOUL@postamble=\relax%
      \let\SOUL@interword=\space%
      \def\SOUL@everytoken{\phantom{\SOUL@actual\kern\dimen@}}% Make current token `invisible'.
      \def\SOUL@everyhyphen
      {%
        \kern-\dimen@
        \discretionary{\kern\dimen3\phantom{\unhcopy\tw@}}{}{}% Output an `invisible' hyphen if needed.
        }%
      \let\SOUL@everysyllable=\relax%
      \SOUL@%
      }%
    }%
  {% No. In this case, there is no useful definition for \hidetext.
    \PackageWarning{texpower}
    {Package soul not loaded.\MessageBreak Command \string\hidetext\space disabled}%
    \let\hidetext=\hidephantom%                                 \hidephantom is a sorry excuse for \hidetext...
    }%
  }


\ifthenelse{\boolean{TPcolor}}% Can we use colors at all?
{% Yes.
  \newcommand{\hidedimmed}[1]%            Make argument appear in `dimmed' colors.
  {\textcolor{dtextcolor}{\dimcolors#1}}
  }
{\let\hidedimmed=\displayidentical}% No. Disable this command.


\ifthenelse{\boolean{TPcolor}}% Can we use colors at all?
{% Yes.
  \newcommand{\hidevanish}[1]%            Make argument `vanish' by changing colors.
  {\textcolor{\vanishcolor}{\vanishcolors#1}}
  }
{\let\hidevanish=\displayidentical}% No. Disable this command.


% The displaying and hiding of <stepcontents> is controlled by the commands \displaystepcontents and
% \hidestepcontents. The following switches define these to be either the boxed or the nonboxed versions defined above.

\newcommand{\boxedsteps}          % Use boxed versions.
{\let\displaystepcontents=\displayboxed\let\hidestepcontents=\hidephantom}

\newcommand{\nonboxedsteps}       % Use nonboxed versions.
{\let\displaystepcontents=\displayidentical\let\hidestepcontents=\hideignore}

\nonboxedsteps                    % The default is to use the nonboxed versions. This can be changed in the optional
                                  % argument of \stepwise.


% There is another command named \activatestep which controls what happens when a \step command is activated for the
% first time. This is defined to do nothing by default.

\let\activatestep=\displayidentical


% We provide a command \highlightboxed which puts its argument into an \mbox with coloured background if the
% colorhighlight option is set, and into an \fbox otherwise. As this is meant as an interpretation of \activatestep, it
% is made sure that the resulting box has the same dimensions as the argument (the outer frame may overlap surrounding
% text).

% There is a new length \highlightboxsep which gives the width of the frame around the box.

\newlength{\highlightboxsep}
\setlength{\highlightboxsep}{.5\fboxsep}

\newcommand{\highlightboxed}
{%
  \ifmmode
    \expandafter\mathpalette\expandafter\math@hb@TP
  \else
    \expandafter\text@hb@TP
  \fi
}

\newcommand{\math@hb@TP}[2]{\text@hb@TP{$\m@th#1{#2}$}}

\ifthenelse{\boolean{colorhighlight@TP}}%                  Color highlighting enabled?
{%  Yes; use a box with colored background.
  \newcommand{\text@hb@TP}[1]
  {%
    \makebox[\width-2\highlightboxsep]
    {%
      \setlength{\fboxsep}{\highlightboxsep}%
      \raisebox{0pt}[\height-\fboxsep][\depth-\fboxsep]{\colorbox{highlightcolor}{#1}}%
      }%
    }%
}
{%  No; use an \fbox.
  \newcommand{\text@hb@TP}[1]
  {%
    \makebox[\width-2\highlightboxsep-2\fboxrule]
    {%
      \setlength{\fboxsep}{\highlightboxsep}%
      \raisebox{0pt}[\height-\fboxsep-\fboxrule][\depth-\fboxsep-\fboxrule]{\fbox{#1}}%
      }%
    }%
  }


% \highlighttext is the counterpart of \highlightboxed for arbitrary text. It puts its argument on a colored background
% without putting it into a box (i.e. line breaks and hyphenation still work) if the colorhighlight option is set, and
% underlines otherwise. As this is meant as an interpretation of \activatestep, it is made sure that the resulting text
% has the same dimensions as the argument (the outer frame may overlap surrounding text). 

\AtBeginDocument
{%
  \@ifpackageloaded{soul}%                                     Can we use the soul package?
  {% Yes. Let's define the necessary macros.
    \ifthenelse{\boolean{colorhighlight@TP}}%                  Color highlighting enabled?
    {%  Yes; use a colored background.
     %  This is implemented as an application of soul (modifying the code for underline). See the documentation of the
     %  soul package for details on soul.
      \newlength{\SOUL@boxheight@TP}
      \newlength{\SOUL@boxtotalheight@TP}
      \newlength{\SOUL@boxdepth@TP}
      \DeclareRobustCommand*\highlighttext
      {%
        \leavevmode
        \SOUL@ulbody
        \def\SOUL@preamble
        {%
          \setlength{\SOUL@boxdepth@TP}{\SOUL@uldepth+\highlightboxsep}%
          \def\SOUL@uldepth{-\SOUL@boxheight@TP}%
          \setlength{\SOUL@boxheight@TP}{\heightof{/}+\highlightboxsep}%
          \setlength{\SOUL@boxtotalheight@TP}{\SOUL@boxdepth@TP+\SOUL@boxheight@TP}%
          \def\SOUL@ulthickness{\SOUL@boxtotalheight@TP}%
          \smash{\llap{\color{highlightcolor}\rule[-\SOUL@boxdepth@TP]{\highlightboxsep}{\SOUL@boxtotalheight@TP}}}%
          \SOUL@ulpreamble
          }%
        \def\SOUL@everytoken
        {%
          {%
            \setbox\@tempboxa\hbox{\SOUL@actual\ifdim\dimen@=\z@\else\kern\dimen@\fi}%
            \dimen@ii\wd\@tempboxa
            \smash{\rlap{\color{highlightcolor}\SOUL@ulleaders\hskip\dimen@ii}}%
            \unhbox\@tempboxa%
            \smash{\rlap{\color{highlightcolor}\rule[-\SOUL@boxdepth@TP]{\highlightboxsep}{\SOUL@boxtotalheight@TP}}}%
            }%
          }%
        \def\SOUL@interword
        {%
          \cleaders\hbox{\smash{\color{highlightcolor}\rule[-\SOUL@boxdepth@TP]{1pt}{\SOUL@boxtotalheight@TP}}}%
          \hskip\spaceskip
          \smash{\llap{\color{highlightcolor}\rule[-\SOUL@boxdepth@TP]{\highlightboxsep}{\SOUL@boxtotalheight@TP}}}%
          }%
        \def\SOUL@everyhyphen
        {%
          \discretionary
          {\advance\dimen3-\dimen@\ifdim\dimen3=\z@\else\kern\dimen3\fi
            \setbox4\hbox{\unhcopy\tw@}%
            \smash{\rlap{\color{highlightcolor}\SOUL@ulleaders\hskip\wd4}}%
            \box4%
            \smash{\rlap{\color{highlightcolor}\rule[-\SOUL@boxdepth@TP]{\highlightboxsep}{\SOUL@boxtotalheight@TP}}}%
            }%
          {\smash{\llap{\color{highlightcolor}\rule[-\SOUL@boxdepth@TP]{\highlightboxsep}{\SOUL@boxtotalheight@TP}}}}%
          {\smash{\color{highlightcolor}\SOUL@ulleaders\hskip\dimen@}}%
          }%
        \SOUL@%
        }%
      }
    {% No. Underline.
      \DeclareRobustCommand*\highlighttext
      {%
        \SOUL@ulbody%                        We modify SOUL's standard definition of underlining, making sure
        \def\SOUL@everytoken%                the result uses no more space than the non-underlined text.
        {%
          {%
            \let\o@llap@TP=\llap
            \def\llap####1{\smash{\o@llap@TP{####1}}}%
            \SOUL@uleverytoken
            }%
          }%
        \def\SOUL@interword{\cleaders\hbox{\smash{\vrule\@depth\dimen8\@height\dimen6\@width.5pt}}\hskip\spaceskip}%
        \def\SOUL@everyhyphen{\discretionary
          {\advance\dimen3-\dimen@\ifdim\dimen3=\z@\else\kern\dimen3\fi
            \setbox4\hbox{\unhcopy\tw@}%
            \smash{\rlap{\SOUL@ulleaders\hskip\wd4}\box4}}{}%
          {\smash{\hbox{\SOUL@ulleaders\hskip\dimen@}}}}%
        \SOUL@%
        }%
      }%
    }
  {% No. In this case, there is no useful definition for \highlighttext.
    \PackageWarning{texpower}
    {Package soul not loaded.\MessageBreak Command \string\highlighttext\space disabled}%
    \let\highlighttext=\@iden
    }%
  }

\ifthenelse{\boolean{TPcolor}}% Can we use colors at all?
{% Yes.
  \newcommand{\highlightenhanced}[1]{\textcolor{etextcolor}{\enhancecolors#1}}
  }
{\let\highlightenhanced=\displayidentical}% No. Disable this command.


% When \stepwise is executed, for every page of the sequence generated, <contents> is wrapped in the environment
% stepcapsule (but not grouped by default). This is empty by default for minimum intrusion. Redefine stepcapsule in the
% optional argument of \stepwise to change this (as is done for instance by \liststepwise).

\newenvironment{stepcapsule}{}{}


% Because \step commands usually occur deep in some nested structure, it is difficult to set local parameters (like page
% transitions) only for certain steps (local settings executed in <stepcontents> would be undone by closing groups).
%
% \afterstep{<setting>} has the effect that <setting> will be performed _after_ the current execution of <contents>,
% right before the page break for this page of the sequence generated.

\newcommand{\afterstep}[1]
{%
  \gdef\@afterstep@TP{#1}% The argument is simply stored in \@afterstep@TP, which is executed in \stepwise.
  }

%-----------------------------------------------------------------------------------------------------------------------
% Implementation of \step, \switch and relatives.
%
% \step takes two optional arguments for influencing the mode of activation, like this:
%
% \step[<activatefirst>][<whenactive>]{<stepcontents>}
%
% Both <activatefirst> and <whenactive> should be conditions in the syntax of the \ifthenelse command.
%
% <activatefirst> checks whether this \step is to be activated for the first time. The default value is
% \value{step}=\value{stepcommand}. By using \value{step}=<n>, this \step can be forced to appear as the n'th one.  
%  
% <whenactive> checks whether this \step is to be considered active at all. The default behaviour is to check whether
% this \step has been activated before (this is saved internally for every step).  
%  
% Both optional arguments allow two syntctical forms: 
%
% 1. enclosed in square brackets [...] like explained above.
%
% 2. enclosed in braces (...). In this case, <activatefirst> and <whenactive> are not treated as conditions in the sense
% of \ifthenelse, but as conditionals like those used internally by \LaTeX. That means, <activatefirst> (when enclosed
% in braces) can contain arbitrary \TeX code which then takes two arguments and expands to one of them, depending on
% whether the condition is fulfilled or not fulfilled. For instance, \step[<activatefirst>]{<stepcontents>} could be
% replaced by \step(\ifthenelse{<activatefirst>}){<stepcontents>}. 
%
% Internally, the default for the treatment of <whenactive> is (\if@first@TP@true), where \if@first@TP@true is an
% internal condition checking whether this \step has been activated before.  
%

% \pickup@s@optargs@TP reads the optional arguments of \step (or \switch, or relatives) and then calls \@do@s@TP.

\newcommand{\pickup@s@optargs@TP}
{%
  \@ifnextchar[%]            Check for first optional argument in [...] syntax.
  {\f@brackstep@TP}%
  {%
    \@ifnextchar(%)          Check for first optional argument in (...) syntax.
    {\f@parenstep@TP}
    {\f@brackstep@TP[]}%     No optional argument given; call with empty argument in [...] syntax (default).
    }%
}

\def\f@brackstep@TP[#1]%     \step was called with first argument in [...] syntax.
{%
  \ifthenelse{\equal{#1}{}}% Optional argument empty?
  {\def\f@step@TPcheck{\ifthenelse{\value{step}=\value{stepcommand}}}}% Yes; use default.
  {\def\f@step@TPcheck{\ifthenelse{#1}}}% No; condition is defined via \ifthenelse.
  \f@step@TP%                Go on and check for second optional argument.
}

\def\f@parenstep@TP(#1)%     \step was called with first argument in (...) syntax.
{%
  \def\f@step@TPcheck{#1}%   Save condition (given as argument).
  \f@step@TP%                Go on and check for second optional argument.
  }

\newcommand{\f@step@TP}%     Pick up the second optional argument of \step.
{%
  \@ifnextchar[%]            Check for second optional argument in [...] syntax.                       
  {\s@brackstep@TP}
  {%
    \@ifnextchar(%)          Check for second optional argument in (...) syntax.                 
    {\s@parenstep@TP}
    {\s@parenstep@TP(\if@first@TP@true)}% No second optional argument given;
    }%                                    call with \if@first@TP@true in (...) syntax (default).
}

\def\s@brackstep@TP[#1]%     \step was called with second argument in [...] syntax.
{%
  \def\s@step@TPcheck{\ifthenelse{#1}}% Condition is defined via \ifthenelse.
  \@do@s@TP%                Go on. 
  }

\def\s@parenstep@TP(#1)%     \step was called with second argument in (...) syntax.
{%
  \def\s@step@TPcheck{#1}%   Save condition (given as argument).
  \@do@s@TP%                Go on.
  }

% The following are needed to switch between the `switch behaviour' and the `step behaviour' of \@@switch@TP, which
% implements the functionality of both \switch and \step.

\newcommand{\deactivate@inner@TP}% \switch behaviour.
{%
  \let\inner@display@TP=\displayidentical% Both \inner@display@TP and \inner@hide@TP just expand to their argument.
  \let\inner@hide@TP=\displayidentical%
  }

\newcommand{\activate@inner@TP}% \step behaviour.
{%
  \let\inner@display@TP=\displaystepcontents% Use the user interface macros \displaystepcontents and \hidestepcontents.
  \let\inner@hide@TP=\hidestepcontents%
  }


% \proper@step@TP is the `real' implementation of \step. Most of the time, \step is defined to execute
% \proper@step@TP.
% 

\newcommand{\proper@step@TP}{\let\@do@s@TP=\@step@TP\pickup@s@optargs@TP}


% \@step@TP implements the functionality of \step by calling \@@switch@TP, which points to \@switch@TP most of the time.

\newcommand{\@step@TP}[1]{\activate@inner@TP\@@switch@TP{#1}{#1}}


% Inside, \@step@TP executes \@@switch@TP, which is the implementation of the \switch command.

% \switch works exactly like \step, but it takes _two_ mandatory arguments and selects the first if `not active', the
% second if `active'.
%
% \proper@switch@TP is the `real' implementation of \switch. Most of the time, \switch is defined to execute
% \proper@switch@TP.

\newcommand{\proper@switch@TP}{\deactivate@inner@TP\let\@do@s@TP=\@@switch@TP\pickup@s@optargs@TP}

% The following macro checks whether the \switch command number \value{stepcommand} has already been activated in this
% \stepwise session and selects one of its arguments accordingly. 

\newcommand{\if@first@TP@true}[2]% 
{%                                
  \expandafter                   % \first@TP@<n> is set to \@undefined if \switch command number <n> has not yet been
  \ifx\csname first@TP@\the\c@stepcommand\endcsname\empty% activated and \empty otherwise.
    #1%
   \else
    #2%
  \fi
  }

% \switch shouldn't change the status quo in AMSLaTeX's measuring pass in typesetting aligned formulae. To guarantee
% this, we check whether AMSLaTeX is measuring with AMSLaTeX's \ifmeasuring@. When AMSLaTeX is not loaded, we provide
% this check ourselves. 

\@ifundefined{ifmeasuring@}{\newif\ifmeasuring@}{}

% \@switch@TP implements the functionality of \switch. Most of the time, \@@switch@TP (which is called after checking for
% optional arguments) is defined to execute \@switch@TP.

\newcommand{\@switch@TP}[2]
{%
  \global\advance\c@stepcommand by 1\relax% This execution of \switch is counted.
  %
  % If the verbose option is set, type out some accounting information which can be used for debugging. 
  \ifthenelse{\boolean{verbose@TP}}
  {%
    \PackageInfo{texpower}
    {Step: \the\c@step, Stepcommand: \the\c@stepcommand,\MessageBreak Stepsperformed: \the\c@stepsperformed}%
    }
  {}%
  %
  \f@step@TPcheck% Is this step to be activated? \f@step@TPcheck is defined by the first optional argument of \switch.
  {% Yes.
    \if@first@TP@true{}% For non-unique conditions given as optional argument or when \reswitch is used, it might happen
    {%       that \first@TP@\value{stepcommand} is already set. In this case, don't advance the counter stepsperformed.
      \ifmeasuring@\else% Do nothing in AMSLaTeX's measuring pass for aligned equations.
        \global\expandafter\let\csname first@TP@\the\c@stepcommand\endcsname=\empty% Set \first@TP@\value{stepcommand}
      \fi
      \global\advance\c@stepsperformed by 1\relax% Advance the counter for `real' first activations.
      }%
    \setboolean{firstactivation}{true}% This switch can be tested in <stepcontents>, but also in <whenactive>.
    }
  {% No.
    \setboolean{firstactivation}{false}% This switch can be tested in <stepcontents>, but also in <whenactive>.
    }% End of \f@step@TPcheck
  %
  \let\o@afterstep@TP=\afterstep% We need to save the current definition of \afterstep.
  %
  \s@step@TPcheck% Is this step active? \s@step@TPcheck is defined by the second optional argument of \switch.
  {% Yes.
    \setboolean{active}{true}%               Make this fact known to the user.
    \ifthenelse{\boolean{firstactivation}}
    {\inner@display@TP{\activatestep{#2}}}%  `First' display of <stepcontents>.
    {\inner@display@TP{#2}}%                 Display <stepcontents>.
    }
  {% No.
    \setboolean{active}{false}%              Make this fact known to the user.
    \let\afterstep=\@gobble%                 Don't execute \afterstep here.
    \ifthenelse{\boolean{firstactivation}}
    {\inner@hide@TP{\activatestep{#1}}}%     Hide <stepcontents>, but with `first activation'.
    {\inner@hide@TP{#1}}%                    Hide <stepcontents>.
    }% End of \s@step@TPcheck
  %
  \let\afterstep=\o@afterstep@TP%            Restore the definition of \afterstep.
  }% End of the definition of \@switch@TP.


%-----------------------------------------------------------------------------------------------------------------------
% \restep is identical with \step, but is displayed at the same time as the previous \step.

\newcommand{\restep}
{%
  \global\advance\c@stepcommand by -1% This is done by simply counting \value{stepcommand} backwards.
  \proper@step@TP%                     Go on with \step.
  }

%-----------------------------------------------------------------------------------------------------------------------
% \reswitch is identical with \switch, but is displayed at the same time as the previous \switch.

\newcommand{\reswitch}
{%
  \global\advance\c@stepcommand by -1% This is done by simply counting \value{stepcommand} backwards.
  \proper@switch@TP%                     Go on with \switch.
  }


%-----------------------------------------------------------------------------------------------------------------------
% \bstep is a variant of \step which is always boxed.

\newcommand{\proper@bstep@TP}{\let\@do@s@TP=\@bstep@TP\pickup@s@optargs@TP}

% \@bstep@TP implements the functionality of \bstep by calling \boxedsteps and \@step@TP.

\newcommand{\@bstep@TP}[1]{{\boxedsteps\@step@TP{#1}}}

%-----------------------------------------------------------------------------------------------------------------------
% \rebstep is identical with \bstep, but is displayed at the same time as the previous \bstep.

\newcommand{\rebstep}
{%
  \global\advance\c@stepcommand by -1% This is done by simply counting \value{stepcommand} backwards.
  \proper@bstep@TP%                     Go on with \bstep.
  }


%-----------------------------------------------------------------------------------------------------------------------
% \dstep is a variant of \step which takes _no_ argument, but switches colors to `dimmed'.

\ifthenelse{\boolean{TPcolor}}% Can we use colors at all?
{% Yes.
  \newcommand{\dstep}{\switch{\dimcolors\color{textcolor}}{\set@color}}
  }
{\newcommand{\dstep}{\switch{}{}}}% No. Disable this command.

%-----------------------------------------------------------------------------------------------------------------------
% \redstep is identical with \dstep, but is displayed at the same time as the previous \dstep.

\ifthenelse{\boolean{TPcolor}}% Can we use colors at all?
{% Yes.
  \newcommand{\redstep}{\reswitch{\dimcolors\color{textcolor}}{\set@color}}
  }
{\newcommand{\redstep}{\reswitch{}{}}}% No. Disable this command.


%-----------------------------------------------------------------------------------------------------------------------
% \vstep is a variant of \step which takes _no_ argument, but switches all colors to \vanishcolor.

\ifthenelse{\boolean{TPcolor}}% Can we use colors at all?
{% Yes.
  \newcommand{\vstep}{\switch{\vanishcolors\color{textcolor}}{\set@color}}
  }
{\newcommand{\vstep}{\switch{}{}}}% No. Disable this command.

%-----------------------------------------------------------------------------------------------------------------------
% \revstep is identical with \vstep, but is displayed at the same time as the previous \vstep.

\ifthenelse{\boolean{TPcolor}}% Can we use colors at all?
{% Yes.
  \newcommand{\revstep}{\reswitch{\vanishcolors\color{textcolor}}{\set@color}}
  }
{\newcommand{\revstep}{\reswitch{}{}}}% No. Disable this command.


%-----------------------------------------------------------------------------------------------------------------------
% Implementation of \stepwise.
%
% Every variant of \stepwise takes an optional argument, like this
% 
% \stepwise[<settings>]{<contents>}
% 
% <settings> will be placed right before the internal loop which produces the sequence of pages.  It can contain
% settings of parameters which modify the behaviour of \stepwise or \step. <settings> is placed inside a group so all
% changes are local to this call of \stepwise. 
%
% Usually, the first page of a sequence produced contains only material which is not part of any <stepcontents>. The
% first <stepcontents> are displayed on the second page of the sequence. 
%
% For special effects, it might be desirable to have the first <stepcontents> active even on the first page of the
% sequence. 
%
% All variants of \stepwise have a starred version (e.\,g.\ \stepwise*) which does exactly that.

\setcounter{firststep}{0}% Default: start with counter step at number 0.

\newcounter{o@fs@TP}% For saving the default value.

\newcommand{\stepwise}
{%
  \global\c@o@fs@TP=\c@firststep\relax%     Save the default value of counter firststep.
  \@ifstar%                                 Using the starred version?
  {% Yes.
    \c@firststep=1\relax\@stepwise@TP%      Start with counter step at number 1.
    }
  {% No.
    \@stepwise@TP%                          Use the default.
    }% End of \@ifstar.
  }%


% Sometimes, it might happen that vertical spacing is different on every page of a sequence generated by \stepwise,
% making lines `wobble'.  
% There are two custom versions of \stepwise which produce better vertical spacing by putting an invisible rule before
% <contents>. 
% 
% \liststepwise{<contents>} works exactly like \stepwise, but <contents> is delimited by a rule of height zero. Use for
% list environments and aligned equations. 
% 
% \parstepwise{<contents>} works like \liststepwise, but \boxedsteps is turned on by default. Use for texts where \steps
% are to be filled into blank spaces. 
%

\newcommand{\list@stepcapsule}
{%
  \renewenvironment{stepcapsule}%    stepcapsule is to put an invisible rule on the vertical list.
  {\vspace*{\parskip}\hrule \@height\z@\relax}{}
  }%

\let\par@stepcapsule=\list@stepcapsule



\newcommand{\liststepwise}
{%
  \@ifstar%                           Check for the star, save it in \star@TP and gon on, checking for the optional
  {\def\star@TP{*}\@liststepwise@TP}% argument. 
  {\def\star@TP{}\@liststepwise@TP}%
  }

\newcommand{\@liststepwise@TP}[1][]
{%
  \expandafter\stepwise\star@TP%                             Re-insert the star (if given).
  [%
    \list@stepcapsule
    #1%                                                      The optional argument of \liststepwise is inserted.
    ]%
  }

\newcommand{\parstepwise}{\@ifstar{\def\star@TP{*}\@parstepwise@TP}{\def\star@TP{}\@parstepwise@TP}}

\newcommand{\@parstepwise@TP}[1][]
{%
  \expandafter\stepwise\star@TP
  [%
    \boxedsteps                      % This is the same as \liststepwise, only \boxedsteps is turned on additionally.
    \par@stepcapsule
    #1%
    ]%
  }


% \count@em@TP is used by \stepwise as a redefinition of \@@switch@TP for counting \step commands.

\newcommand{\count@em@TP}[2]
{%
  \global\advance\c@stepcommand by 1\relax% We simply advance the number of \step commands...
  #2%                                      ... and execute the second argument (to find nested uses of \step).
}

% \savecounters@TP saves the values of all counters that have ever been defined by \newcounter in the macro
% \restorecounters@TP, which can be used later to restore the saved values. The code is snarfed from amsmath.sty.

\def\savecounters@TP{%
  \begingroup
    \def\@elt##1{\global\csname c@##1\endcsname\the\csname c@##1\endcsname}%
    \xdef\restorecounters@TP{\cl@@ckpt}%
  \endgroup
  }

% \saveTPcounters@TP saves the values of all `stepwise-specific' counters in the macro \restoreTPcounters@TP.

\def\cl@@ckpt@TP{\@elt{totalsteps}\@elt{firststep}\@elt{step}\@elt{stepcommand}\@elt{stepsperformed}\@elt{o@fs@TP}}

\newcommand{\releasecounter}[1]%
{\expandafter\def\expandafter\cl@@ckpt@TP\expandafter{\cl@@ckpt@TP\@elt{#1}}}

\def\saveTPcounters@TP{%
  \begingroup
    \def\@elt##1{\global\csname c@##1\endcsname\the\csname c@##1\endcsname}%
    \xdef\restoreTPcounters@TP{\cl@@ckpt@TP}%
  \endgroup
  }


%% \@stepwise@TP implements the functionality of \stepwise. It is called by \stepwise after checking for the star.

\newcommand{\@stepwise@TP}[2][]
{%
  \save@TP%                               Save the current contents of the page.
  \savecounters@TP%                       Save the values of all counters.
  \begingroup%                            A group makes redefinitions local.
    \let\step\proper@step@TP%             By default, \step executes \proper@step@TP.
    \let\bstep\proper@bstep@TP%
    \let\switch\proper@switch@TP%         By default, \switch executes \proper@switch@TP.
    %
    % One big problem with math is that \mathchoice typesets its argument four times. If \step commands are inside the
    % argument of \mathchoice, counters (which are advanced globally by \step) go astray. So far, I don't know any
    % remedy for this apart from (locally) hacking \mathchoice. I know this is a very fragile and non-recommended
    % method, but it works for the examples and will hopefully do until someone helps me find a better solution. 
    \let\orig@mathchoice@TP=\mathchoice%  Save the current definition of \mathchoice...
    \def\mathchoice##1##2##3##4%          ... and redefine.
    {%
      \orig@mathchoice@TP%                The original definition of \mathchoice is called...
      {##1}%                              ... with the first argument untouched...
      {\let\step\restep\let\bstep\rebstep\let\switch\reswitch##2}% ... and in all other arguments, ...
      {\let\step\restep\let\bstep\rebstep\let\switch\reswitch##3}% ... \step redefined to execute \restep.
      {\let\step\restep\let\bstep\rebstep\let\switch\reswitch##4}%
      }%
    %
    \c@stepcommand=0\relax%               Initialize the counter for \step commands.
    \let\@@switch@TP=\count@em@TP%        Next, we count the \step commands in <contents>...
    \setbox\@tempboxa%                    ... by putting <contents> into a \vbox (which is then discarded). 
    =\vbox
    {\let\afterstep=\@gobble#2}%          Inside the \vbox, \afterstep is ignored.
    \c@totalsteps=\c@stepcommand%         Now, we know the total number of \step commands.
    %
    % Next, we have to reset \first@TP@<n> for <n>=0...\value{totalsteps}.
    \c@step=0\relax
    \loop
     \ifnum\c@step<\c@totalsteps
      \advance\c@step by 1\relax
      \expandafter\let\csname first@TP@\the\c@step\endcsname=\@undefined
    \repeat
    %
    % Next, the optional argument of \stepwise is executed. At this point, \value{totalsteps} already has its final
    % value and \value{step} has not yet been set to \value{firststep}, so both totalsteps and firststep can
    % meaningfully be modified in <settings>.
    #1%
    %
    \c@step=\c@firststep%                   Set the counter for the current step to its starting value...
    \c@stepsperformed=0\relax%              ... and also the counter for the \step commands which are already activated.
    \let\@@switch@TP=\@switch@TP%           \step will now act normally.
    \ifthenelse{\boolean{verbose@TP}}%      Some accounting info (if verbose option is set).
    {\PackageInfo{texpower}{Total number of step commands: \the\c@totalsteps}}
    {}%
    %     
    \ifthenelse{\boolean{display}}%         Are dynamic features enabled?
    {}% Yes.
    {%  No. Do only one loop.
      \c@stepsperformed=\c@totalsteps%      Set everything up for the last loop.
      \c@step=0\relax
      \loop
       \ifnum\c@step<\c@totalsteps
        \advance\c@step by 1\relax
        \expandafter\let\csname first@TP@\the\c@step\endcsname=\@empty
      \repeat
      \advance\c@step by 1\relax%           This way, the last step won't think it's `first activated'.
      }%
    \let\insertdup@TP=\insertfirstduplicate@TP% Restore page contents with execution of whatsits.
    \loop%                                  This is the central loop.
      \c@stepcommand=0\relax%               Initialize the counter for the current \step command.
      \saveTPcounters@TP%                   Save the `stepwise-specific' counters.
      \restorecounters@TP%                  Restore the `original' values of all counters...
      \restoreTPcounters@TP%                ... and the current values of the `stepwise-specific' counters.
      \let\@afterstep@TP=\relax%            Reset the container for \afterstep.
      %   
      \insertdup@TP%                        Insert saved page contents.
      \begin{stepcapsule}%                  This is usually empty, but may start a minipage (or whatever).
        #2%                                 Execute <contents>
      \end{stepcapsule}%
      %                                 
      \@afterstep@TP%                       Whatever has been saved with \afterstep is now executed.
     \ifnum\c@stepsperformed<\c@totalsteps% Doing one more round?
      \outputduplicate@TP%                  Shipout this page and round we go again.
      \let\insertdup@TP=\insertsecondduplicate@TP% Restore saved contents without execution of whatsits.
      \advance\c@step by 1\relax%           Round we go again
    \repeat
  \endgroup
  \global\c@firststep=\c@o@fs@TP\relax%     Restore default value of counter firststep.
}% End of the definition of \@stepwise@TP


\InputIfFileExists{tpsettings.cfg}{}{}% This file can contain system-specific settings.

% Local Variables: 
% fill-column: 120
% TeX-master: "dummy"
% End: 

%%
%% End of file `texpower.sty'.