% \iffalse meta-comment
%
% memoir.dtx 
% Author: Peter Wilson (Herries Press) herries dot press at earthlink dot net 
% Maintainer: Lars Madsen (daleif at math dot au dot dk) 
% Copyright 2001--2010 Peter R. Wilson
% Copyright 2011--     Lars Madsen
% 
% This work may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either
% version 1.3 of this license or (at your option) any 
% later version.
% The latest version of the license is in
%    http://www.latex-project.org/lppl.txt
% and version 1.3 or later is part of all distributions of
% LaTeX version 2003/06/01 or later.
%
% This work has the LPPL maintenance status "maintained".
%
% This work consists of the files listed in the README file.
% 
% \fi
% \CheckSum{31004}
%
% \changes{v0.1}{2001/05/20}{First public alpha release}
% \changes{v0.2}{2001/06/03}{First beta release}
% \changes{v0.3}{2001/07/09}{Bug fixing}
% \changes{v0.31}{2001/07/09}{Bug fixing} 
% \changes{v0.32}{2001/08/03}{Fix for old versions of amsmath package}
% \changes{v0.33}{2001/08/03}{Added controllable chapter/LoF spacing}
% \changes{v0.33}{2001/08/03}{Fixed bug in \cs{appendixpage}}
% \changes{v1.0}{2001/10/30}{First production release}
% \changes{v1.0a}{2001/12/07}{Feature fixes} ^^A never released
% \changes{v1.1}{2002/03/10}{More fixups}
% \changes{v1.1}{2002/03/10}{Replaced all the subfigure code}
% \changes{v1.1}{2002/03/28}{Added sidebars}
% \changes{v1.1}{2002/03/28}{Upgraded verse typesetting}
% \changes{v1.2}{2002/07/07}{Added 17pt option}
% \changes{v1.2}{2002/07/07}{Added extra \cs{provide} commands}
% \changes{v1.2}{2002/07/27}{Major verbatim, box and file additions}
% \changes{v1.2}{2002/07/27}{Removed extraneous space from change marks}
% \changes{v1.2}{2002/07/27}{Extra optarg in \cs{chapter} and \cs{chapter*}}
% \changes{v1.2}{2002/07/27}{Twiddled font sizes a little}
% \changes{v1.2}{2002/08/27}{Fixed 12pt bug}
% \changes{v1.3}{2002/09/27}{Minor tweaks wrt v1.2}
% \changes{v1.3}{2002/10/10}{Extra trimming styles}
% \changes{v1.3}{2002/10/10}{Major extensions for indexing}
% \changes{v1.3}{2002/11/14}{Automatically call a patch file}
% \changes{v1.3a}{2002/11/22}{Fixed nasty figure/table bug}
% \changes{v1.4}{2003/02/27}{Added patches v1.1}
% \changes{v1.4}{2003/02/27}{Added patches v1.3}
% \changes{v1.4}{2003/11/16}{Including current patches}
% \changes{v1.4}{2003/11/16}{Added patches v1.2}
% \changes{v1.4}{2003/11/22}{Added patches v1.4}
% \changes{v1.4}{2003/11/22}{Added patches v1.5}
% \changes{v1.4}{2003/11/22}{Added patches v1.6}
% \changes{v1.4}{2003/11/22}{Added patches v1.7}
% \changes{v1.4}{2003/11/30}{Added patches v1.8}
% \changes{v1.4}{2003/11/30}{Added patches v1.9}
% \changes{v1.6}{2004/01/31}{Decided to issue v1.4 as v1.6 on the way to 
%                            the golden section 1.6180339887...}
% \changes{v1.61}{2004/03/14}{Changes to clo files, and footnotes} 
% \changes{v1.61}{2004/03/21}{Removed a potential problem with the 
%                             hangul package}
% \changes{v1.618}{2005/09/02}{Folded in all v1.61 patches}
% \changes{v1.618}{2005/09/15}{Some minor extensions}
% \changes{v1.618}{2005/09/25}{Support for glossaries}
% \changes{v1.6180}{2006/06/12}{Footnote font fix}
% \changes{v1.61803}{2008/05/26}{Folded in all mempatch v4.9a patches}
% \changes{v1.618033}{2008/06/02}{Fixed(?) page layout algorithms}
% \changes{v1.6180339}{2008/07/23}{Unemulated if... packages}
% \changes{v1.6180339}{2008/07/23}{Folded in all mempatch v5.1 patches}
% \changes{v1.6180339a}{2008/08/07}{Removed extra space in footnotes}
% \changes{v1.6180339c}{2009/01/21}{Minor bug fixes and extensions}
% \changes{v1.6180339c}{2009/01/25}{A few more}
% \changes{v1.6180339d}{2009/02/04}{Fixed a bug in the running
%                                   head/foot widths}
% \changes{v1.6180339f}{2009/03/16}{Start of `f' version.}
% \changes{v1.6180339f}{2009/03/16}{Fixed problem with companion pagestyle
%                                   and added 2 col Toc}
% \changes{v1.6180339f}{2009/04/25}{Extended description lists}
% \changes{v1.6180339f}{2009/07/12}{Added three \cs{memlet...} macros}
% \changes{v1.6180339g}{2009/07/13}{Fixed a bug regading extre enties
% in the page note list}
% \changes{v1.61803398}{2009/07/17}{Added bidi (RTL) support}
% \changes{v1.61803398}{2009/07/27}{Fixed bug in \cs{@setclcnt}, added simple pagestyle}
% \changes{v1.61803398}{2009/08/08}{changed the code that defined the
% main function out of \cs{newlistof}}
% \changes{v1.61803398}{2009/09/10}{fixed bug with upquote}
% \changes{v1.61803398b}{2009/09/21}{fixed typo}
% \changes{v1.61803398c}{2009/11/13}{fixed typo}
% \changes{v1.61803398d}{2009/11/13}{fixed infelicity with \cs{@starttoc}}
% \changes{v1.61803398d}{2009/12/01}{fixed bug in ifxetex, ifpdf,...}
% \changes{v1.61803398d}{2009/12/18}{made \cs{subcaptionref} robust}
% \changes{v1.61803398d}{2010/xx/xx}{several changes}
% \changes{v1.618033988}{2010/02/16}{bumped version to v1.618033988}
% \changes{v1.618033988b}{2010/02/17}{fixed typo that broke \cs{feetbelowfloat}}
% \changes{v1.618033988c}{2010/02/20}{fixed sporadic space in \cs{@footnotetext}}
% \changes{v1.618033988d}{2010/02/26}{fixed bug in
% \cs{marginparmargin}\{left\} in twoside mode}
%
% \changes{v3.6}{2010/04/19}{Reversioned memoir to a more suitable scheme}
% \changes{v3.6d}{2010/07/01}{Various bug fixes}
% \changes{v3.6e}{2010/08/20}{Maintenance}
% \changes{v3.6f}{2010/08/22}{Bad typo}
% \changes{v3.6g}{2010/09/19}{Maintenance}
% \changes{v3.6h}{2011/02/13}{Various things}
% \changes{v3.6i}{2011/02/18}{Two bug fixes}
% \changes{v3.6j}{2011/03/06}{Bug fixes}
% \changes{v3.6k}{2013/05/17}{Various fixes and long overdue maintenance}
% \changes{v3.7}{2013/05/22}{Bumped version}
% \changes{v3.7b}{2013/05/30}{Bugfix, sidecaption}
% \changes{v3.7c}{2015/03/05}{Bugfix}
% \changes{v3.7d}{2015/04/23}{Misc. bugfixes}
% \changes{v3.7e}{2015/07/08}{Per request from LaTeX Team, etex is not
% autoloaded on newer kernels}
% \changes{v3.7f}{2016/05/16}{Maintenance, luatex85 and booktabs update}
% 
% \changes{v3.7h}{2018/12/12}{Maintenance, removing some emulated packages}
% 
% \def\dtxfile{memoir.dtx}
%
% \def\fileversion{v0.1}  \def\filedate{2001/05/20}
% \def\fileversion{v0.2}  \def\filedate{2001/06/03}
% \def\fileversion{v0.3}  \def\filedate{2001/07/14}
% \def\fileversion{v0.31} \def\filedate{2001/07/24}
% \def\fileversion{v0.32} \def\filedate{2001/08/03}
% \def\fileversion{v0.33} \def\filedate{2001/08/31}
% \def\fileversion{v1.0}  \def\filedate{2001/11/17}
% \def\fileversion{v1.0a} \def\filedate{2001/12/07}
% \def\fileversion{v1.1}  \def\filedate{2002/03/28}
% \def\fileversion{v1.1a} \def\filedate{2002/04/28}
% \def\fileversion{v1.2}  \def\filedate{2002/08/10}
% \def\fileversion{v1.2}  \def\filedate{2002/08/27}
% \def\fileversion{v1.3}  \def\filedate{2002/11/14}
% \def\fileversion{v1.3a} \def\filedate{2002/11/22}
% \def\fileversion{v1.4}  \def\filedate{2003/12/18}
% \def\fileversion{v1.6}  \def\filedate{2004/01/31}
% \def\fileversion{v1.61}  \def\filedate{2004/04/04}
% \def\fileversion{v1.618}  \def\filedate{2005/09/27}
% \def\fileversion{v1.6180}  \def\filedate{2006/06/12}
% \def\fileversion{v1.61803}  \def\filedate{2008/05/26}
% \def\fileversion{v1.618033}  \def\filedate{2008/06/02}
% \def\fileversion{v1.6180339}  \def\filedate{2008/07/23}
% \def\fileversion{v1.6180339a}  \def\filedate{2008/08/07}
% \def\fileversion{v1.6180339c}  \def\filedate{2009/01/21}
% \def\fileversion{v1.6180339c}  \def\filedate{2009/01/25}
% \def\fileversion{v1.6180339d}  \def\filedate{2009/02/04}
% \def\fileversion{v1.6180339e}  \def\filedate{2009/02/06}
% \def\fileversion{v1.6180339f}  \def\filedate{2009/07/12}
% \def\fileversion{v1.6180339g}  \def\filedate{2009/07/13}
% \def\fileversion{v1.61803398}  \def\filedate{2009/09/10}
% \def\fileversion{v1.61803398b}  \def\filedate{2009/09/21}
% \def\fileversion{v1.61803398c}  \def\filedate{2009/11/17}
% \def\fileversion{v1.61803398d}  \def\filedate{2009/11/23}
% \def\fileversion{v1.618033988}  \def\filedate{2010/02/16}
% \def\fileversion{v1.618033988b}  \def\filedate{2010/02/17}
% \def\fileversion{v1.618033988c}  \def\filedate{2010/02/20}
% \def\fileversion{v3.6}           \def\filedate{2010/04/19}
% \def\fileversion{v3.6d}          \def\filedate{2010/07/01}
% \def\fileversion{v3.6e}          \def\filedate{2010/08/20}
% \def\fileversion{v3.6f}          \def\filedate{2010/08/22}
% \def\fileversion{v3.6g}          \def\filedate{2010/09/19}
% \def\fileversion{v3.6h}          \def\filedate{2011/02/13}
% \def\fileversion{v3.6i}          \def\filedate{2011/02/18}
% \def\fileversion{v3.6j}          \def\filedate{2011/03/06}
% \def\fileversion{v3.6k}          \def\filedate{2013/05/17}
% \def\fileversion{v3.7}          \def\filedate{2013/05/22}
% \def\fileversion{v3.7b}          \def\filedate{2013/05/30}
% \def\fileversion{v3.7c}          \def\filedate{2015/03/05}
% \def\fileversion{v3.7d}          \def\filedate{2015/04/23}
% \def\fileversion{v3.7e}          \def\filedate{2015/07/08}
% \def\fileversion{v3.7f}          \def\filedate{2016/05/16}
% \def\fileversion{v3.7g}          \def\filedate{2018/04/04}
% \def\fileversion{v3.7h}          \def\filedate{2018/12/12} ^^A remember to fix
% \title{The LaTeX \Lpack{memoir} class for configurable book 
%        typesetting: Source code\thanks{This
%        file (\texttt{\dtxfile}) has version number \fileversion, last revised
%        \filedate.}}
%
% \author{%
% Peter Wilson\\ ^^A\thanks{\texttt{herries dot press at earthlink dot net}}\\
% Herries Press \\
% (maintained by Lars Madsen\thanks{\texttt{daleif at math dot au dot dk}}\ )}
% \date{\filedate}
% \maketitle
%
% \begin{abstract}
% The \Lpack{memoir} class is designed for typesetting
% general books such as novels, biographies, histories, 
% and so on, although as it supports all the functionality of the 
% standard \Lpack{book} class it can also be used for technical writing.
% It provides more functions than the standard class as well as 
% presenting a more friendly interface for the book designer.
% It can also simulate the typesetting style of the standard \Lpack{article}
% class.
%
%    The class was first released in mid 2001 and has been well used ever
% since.
% \end{abstract}
%
% \tableofcontents
% \listoftables
%
% \StopEventually{}
%
% 
%
% \section{Introduction}
%
% This document provides the commented source 
% for the LaTeX \Lpack{memoir} class, which is designed for typesetting
% general books such as novels, biographies, histories, 
% and so on. It has all the functionality of the standard \Lpack{book}
% class and, as well as providing some extra functions, also provides
% a more friendly interface for the document designer. As it can encompass
% everything that the \Lpack{book} class provides it may also be used
% for technical writing.
%
%   The default appearance of a document typeset with this class is
% the same as if it had been typeset with the \Lpack{book} class and
% it can be made to simulate the \Lpack{article} class..
% The class, though, includes extra facilities that make it easy to
% change the appearance of such things as the page headers and footers,
% the style of chapter and other sectional headings, and the style of
% captions. It also makes it easy to both change the style of the
% Table of Contents, List of Figures, etc., as well as creating new
% kinds of `List of\ldots'. New types of floats, if needed, can be
% created very simply. Epigraphs can be put into the document in a
% variety of styles.
%
%    The class provides a variety of page, chapter and captioning
% styles that you can choose from if you don't want to create your own.
%
%    Documents can be typeset in 9pt, 10pt, 11pt, 12pt, 14pt or 17pt font
% sizes, and if you have scaleable fonts available they can be set at any size.
% There is a reasonably intuitive means of setting the margins
% and placement of the text on a page. There is an option to put
% trim marks on the printed pages if the stock sheets need to be trimmed
% down to the final page size. For those whose publishers like a
% manuscript to look as though it was typewritten, there is an option
% to do this (double spacing, ragged right, no hyphenation, 
% fixed width font). There is also an unsophisticated means of flagging any
% revisions to the text.
%
%    As this is a new class, by default it does not support the old 
% LaTeX v2.09
% font commands, namely the \cs{bf}, \cs{sl}, \cs{it} and \cs{sc} commands;
% it warns about using the \cs{em} command but does support it.
%
%
% I hope that apart from the font commands the class 
% is compatible with
% `standard' LaTeX.
%
%    Development of this class would never have been started without
% the wonderful work done by Leslie Lamport and others~\cite{CLASSES}
% from whom I have learned a great deal and borrowed much code. 
%
%    Sections~\ref{sec:docstrip} through~\ref{sec:ic} describe some
% administrative elements and code for general use later in the 
% specification.
% The macros forming the class file are defined in sections~\ref{sec:opt}
% through~\ref{sec:init}. 
% 
% This manual is typeset according to the conventions of the
% \LaTeX{} \textsc{docstrip} utility which enables the automatic
% extraction of the \LaTeX{} macro source files~\cite{GOOSSENS94}.
%
%
% \section{A driver for this document} \label{sec:docstrip}
%
% The next series of code contains the documentation driver file for
% \LaTeX, i.e., the file that will produce the documentation you are
% currently reading. This will be extracted from this file by the 
% \textsc{docstrip} program.
%
%    \begin{macrocode}
%<*driver>
\documentclass[twoside]{ltxdoc}
\usepackage[T1]{fontenc}
\usepackage{url,array}
%%\usepackage[draft=false,
%%            plainpages=false,
%%            pdfpagelabels,
%%            bookmarksnumbered,
%%            hyperindex=true
%%           ]{hyperref}  % Doesn't work with indexing of \DescribeMacro
\providecommand{\phantomsection}{} % just in case hyperref not used 
%    \end{macrocode}
%
%    We do want an index, using linenumbers, but not update information.
%    \begin{macrocode}
\EnableCrossrefs
\CodelineIndex
%% \RecordChanges
%    \end{macrocode}
% We had better have page headings to aid navigation, but I don't
% like Uppercased titles.
%    \begin{macrocode}
\makeatletter
  \@mparswitchfalse
\makeatother
\renewcommand{\MakeUppercase}[1]{#1}
\pagestyle{headings}
%    \end{macrocode}
%    We may use so many \file{docstrip} modules that we set the
%    \texttt{StandardModuleDepth} counter to 1.
%    \begin{macrocode}
\setcounter{StandardModuleDepth}{1}
%    \end{macrocode}
%    Some commonly used abbreviations
%    \begin{macrocode}
\newcommand*{\Lopt}[1]{\textsf {#1}}            % typeset an option
\newcommand*{\file}[1]{\texttt {#1}}            % typeset a file
\newcommand*{\Lcount}[1]{\textsl {\small#1}}    % typeset a counter
\newcommand*{\pstyle}[1]{\textsl {#1}}          % typeset a pagestyle
\newcommand*{\Lenv}[1]{\texttt {#1}}            % typeset an environment
\newcommand*{\Lpack}[1]{\textsf {#1}}           % typeset a package
\newcommand*{\ctt}{\textsc{ctt}}                % comp.text.tex
\newenvironment{PW}{\em}{}
\newenvironment{dlf}{\em}{}
\newcommand*{\theTeXbook}{\textit{The \TeX book}}
\let\oldllap\llap
\def\llap#1{\oldllap{#1\quad}} % might be evil
%    \end{macrocode}
%    We want the full details printed.
%    \begin{macrocode}
\begin{document}
\DeleteShortVerb{\|}
\raggedbottom
%\raggedright
\DocInput{\jobname.dtx}
\PrintIndex
%% \PrintChanges
\end{document}
%</driver>
%    \end{macrocode}
%
%
%   ^^A  There are some elements we do not want to appear in the index.
% \DoNotIndex{\',\.,\@M,\@@input,\@addtoreset,\@arabic,\@badmath}
% \DoNotIndex{\@centercr,\@cite}
% \DoNotIndex{\@dotsep,\@empty,\@gobble,\@gobbletwo,\@ignoretrue}
% \DoNotIndex{\@input,\@ixpt,\@m}
% \DoNotIndex{\@minus,\@ne,\@nil,\@nomath,\@plus,\@set@topoint}
% \DoNotIndex{\@tempboxa,\@tempcnta,\@tempdima,\@tempdimb}
% \DoNotIndex{\@tempswafalse,\@tempswatrue,\@viipt,\@viiipt,\@vipt}
% \DoNotIndex{\@vpt,\@warning,\@xiipt,\@xipt,\@xivpt,\@xpt,\@xviipt}
% \DoNotIndex{\@xxpt,\@xxvpt,\\,\ ,\addpenalty,\addtolength,\addvspace}
% \DoNotIndex{\advance,\Alph,\alph}
% \DoNotIndex{\arabic,\ast,\begin,\begingroup,\bfseries,\bgroup,\box}
% \DoNotIndex{\bullet}
% \DoNotIndex{\cdot,\cite,\CodelineIndex,\cr,\day,\DeclareOption}
% \DoNotIndex{\def,\DisableCrossrefs,\divide,\DocInput,\documentclass}
% \DoNotIndex{\DoNotIndex,\egroup,\ifdim,\else,\fi,\em,\endtrivlist}
% \DoNotIndex{\EnableCrossrefs,\end,\endgroup}
% \DoNotIndex{\endlist,\everycr,\everypar,\ExecuteOptions,\expandafter}
% \DoNotIndex{\fbox}
% \DoNotIndex{\filedate,\filename,\fileversion,\fontsize,\framebox,\gdef}
% \DoNotIndex{\global,\halign,\hbox,\hfil,\hfill,\hrule}
% \DoNotIndex{\hsize,\hskip,\hspace,\hss}
%  ^^A \DoNotIndex{\if@tempswa,\fi}
% \DoNotIndex{\ifcase,\or,\fi}
% \DoNotIndex{\ifhmode,\ifvmode,\ifnum,\iftrue,\ifx,\fi,\fi,\fi,\fi,\fi}
% \DoNotIndex{\input}
% \DoNotIndex{\jobname,\kern,\leavevmode,\let}
% \DoNotIndex{\list,\llap,\long,\m@ne,\m@th}
% \DoNotIndex{\month,\newcommand,\newcounter,\newenvironment}
% \DoNotIndex{\NeedsTeXFormat,\newdimen}
% \DoNotIndex{\newlength,\newpage,\nobreak,\noindent,\null,\number}
% \DoNotIndex{\numberline,\OldMakeindex,\OnlyDescription,\p@}
% \DoNotIndex{\par,\paragraph,\paragraphmark,\parfillskip}
% \DoNotIndex{\penalty,\PrintChanges,\PrintIndex,\ProcessOptions}
% \DoNotIndex{\protect,\ProvidesClass}
% \DoNotIndex{\refstepcounter,\relax,\renewcommand,\reset@font}
% \DoNotIndex{\rightskip,\rlap,\rmfamily,\roman}
% \DoNotIndex{\roman,\secdef,\selectfont,\setbox,\setcounter,\setlength}
% \DoNotIndex{\settowidth,\sfcode,\skip,\sloppy,\slshape,\space}
% \DoNotIndex{\symbol,\the,\trivlist,\typeout,\tw@,\undefined,\uppercase}
% \DoNotIndex{\usecounter,\usefont,\usepackage,\vfil,\vfill,\viiipt}
% \DoNotIndex{\viipt,\vipt,\vskip,\vspace}
% \DoNotIndex{\wd,\xiipt,\year,\z@}
% \DoNotIndex{\@namedef,\@nameuse,\csname,\endcsname}
%
%
%
% \section{Identification} \label{sec:id}
%
%    The \Lpack{memoir} document class can only be used with LaTeX2e, 
% so we make
%    sure that an appropriate message is displayed when another \TeX{}
%    format is used.
%    \begin{macrocode}
%<class>\NeedsTeXFormat{LaTeX2e}
%    \end{macrocode}
%
% ^^A Use the Golden Section as the version number (1.6180339887 4989484820 4586834365)
% \changes{v3.6}{2010/04/19}{Not any more, apparently people does not
% know the numeric value of the golden ration very well}
%
%
%    Announce the name, option files and version for LaTeX2e files:
%    \begin{macrocode}
%<class>\ProvidesClass{memoir}%
%<class>  [2018/12/12 v3.7h configurable book, report, article document class]
%    \end{macrocode}
%  In the manual it is useful to know the current version.
%    \begin{macrocode}
%<class>\newcommand\memversion{v3.7h, 2018/12/12}
%<9pt>\ProvidesFile{mem9.clo}%
%<9pt>             [2008/01/30 v0.4 memoir class 9pt size option]
%<10pt>\ProvidesFile{mem10.clo}%
%<10pt>             [2008/01/30 v0.3 memoir class 10pt size option]
%<11pt>\ProvidesFile{mem11.clo}%
%<11pt>             [2008/01/30 v0.3 memoir class 11pt size option]
%<12pt>\ProvidesFile{mem12.clo}%
%<12pt>             [2010/10/19 v0.4b memoir class 12pt size option]
%<14pt>\ProvidesFile{mem14.clo}%
%<14pt>             [2008/01/30 v0.4 memoir class 14pt size option]
%<17pt>\ProvidesFile{mem17.clo}%
%<17pt>             [2008/01/30 v0.3 memoir class 17pt size option]
%<20pt>\ProvidesFile{mem20.clo}%
%<20pt>             [2008/01/31 v0.1 memoir class 20pt size option]
%<25pt>\ProvidesFile{mem25.clo}%
%<25pt>             [2008/01/31 v0.1 memoir class 25pt size option]
%<30pt>\ProvidesFile{mem30.clo}%
%<30pt>             [2008/01/31 v0.1 memoir class 30pt size option]
%<36pt>\ProvidesFile{mem36.clo}%
%<36pt>             [2008/01/31 v0.1 memoir class 36pt size option]
%<48pt>\ProvidesFile{mem48.clo}%
%<48pt>             [2008/01/31 v0.1 memoir class 48pt size option]
%<60pt>\ProvidesFile{mem60.clo}%
%<60pt>             [2008/01/31 v0.1 memoir class 60pt size option]
%    \end{macrocode}
%
%
% \section{Initial Code} \label{sec:ic}
%
%    \begin{macrocode}
%<*class>
%    \end{macrocode}
%
% Note (2001/08/03): Old versions of the \Lpack{amsmath} package did odd
% things with \cs{@tempa}, \cs{@tempb} and \cs{@tempc}. I have now replaced
% any use of these with \cs{@memtempa}, etc.
%
%
%    In this part we define a few commands that are used later on.
%
% \begin{macro}{\@ptsize}
% \begin{macro}{\@memptsize}
%    The \cs{@ptsize} control sequence is normally used to store the 
%    second digit of the
%    pointsize we are typesetting in. So, normally, it's value is one
%    of 0, 1 or 2.
%
% \cs{@memptsize} stores the full pointsize.
% \changes{v1.61803}{2008/01/30}{Added \cs{@memptsize}}
%    \begin{macrocode}
\newcommand*{\@ptsize}{}
\newcommand*{\@memptsize}{}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% Any new lengths that depend on the point size option must be declared
% before the options are executed.
% \begin{macro}{\onelineskip}
% \begin{macro}{\lxvchars}
% \begin{macro}{\xlvchars}
% The length \cs{onelineskip} is the vertical space taken
% by a normal line of text. The lengths \cs{lxvchars} and \cs{xlvchars} are
% the approximate lengths required for typesetting lines with either 65 or 45
% characters.
%    \begin{macrocode}
\newlength{\onelineskip}
\newlength{\lxvchars}
\newlength{\xlvchars}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@memcnta}
% \begin{macro}{\c@memmarkcntra}
% We need a scratch count register and a scratch counter.
% \changes{v1.61803}{2008/10/30}{Added @memmarkcntra scratch counter}
%    \begin{macrocode}
\newcount\@memcnta
\newcounter{@memmarkcntra}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \changes{v1.0a}{2001/11/28}{Deleted count register \cs{@memtempa}}
%
% \begin{macro}{\if@restonecol}
%    When the document has to be printed in two columns, we sometimes
%    have to temporarily switch to one column. This switch is used to
%    remember to switch back.
%    \begin{macrocode}
\newif\if@restonecol
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\if@openright}
% This is TRUE if chapters are to start on righthand (recto) pages;
% this is the default. FALSE means chapters can start on any page.
%    \begin{macrocode}
\newif\if@openright
  \@openrighttrue

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\if@openleft}
% This is TRUE if chapters are to start on lefthand (verso) pages.
%    \begin{macrocode}
\newif\if@openleft
  \@openleftfalse

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\if@mainmatter}
% This is TRUE if the main part of the document is being currently procesed;
% this is the default.
%    \begin{macrocode}
\newif\if@mainmatter
  \@mainmattertrue

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\if@memoldfont}
% This is TRUE if the \Lopt{oldfontcommands} option is used.
% \changes{v1.0a}{2002/01/29}{Added \cs{if@memoldfont}}
%    \begin{macrocode}
\newif\if@memoldfont
  \@memoldfontfalse

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifextrafontsizes}
% This is TRUE if the \Lopt{extrafontsizes} option is used.
% \changes{v1.61803}{2008/01/30}{Added \cs{ifextrafontsizes}}
%    \begin{macrocode}
\newif\ifextrafontsizes
  \extrafontsizesfalse

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@memerror}
% \begin{macro}{\@memwarn}
% Two macros to save some space when reporting errors or warnings.
% The macros take the same arguments, ignoring the first in each case,
% as \cs{ClassError} and \cs{ClassWarning}, e.g., \\
% \verb?\@memwarn{Message}? \\
% instead of \\
% \verb?\ClassWarning{memoir}{Message}?.
% \changes{v1.4}{2003/02/27}{Added \cs{@memerror} and \cs{@memwarn}}
%    \begin{macrocode}
\newcommand*{\@memerror}{\ClassError{memoir}}
\newcommand*{\@memwarn}{\ClassWarning{memoir}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ifsamename}
% \begin{macro}{\nametest}
%    The macro \cs{nametest}\marg{name1}\marg{name2} tests whether the
% characters forming the two arguments are the same or not. If they are the
% same then \cs{ifsamename} is set TRUE, otherwise it is set FALSE. \meta{name1}
% and \meta{name2} must both be either macro names (including the backslash)
% or must both not be macro names. That is, you cannot do 
% \verb?\nametest{\cs}{cs}?.
% \changes{v1.61803398d}{2010/02/13}{added some \% because the macro
% was leaking spaces}
%    \begin{macrocode}
\newif\ifsamename
\newcommand{\nametest}[2]{%
  \samenamefalse%
  \begingroup%
  \def\@memtempa{#1}\def\@memtempb{#2}%
  \ifx \@memtempa\@memtempb%
    \endgroup%
    \samenametrue%
  \else%
    \endgroup%
  \fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ifm@m@And}
% \begin{macro}{\m@m@Andtrue}
% \begin{macro}{\m@m@Andfalse}
% \begin{macro}{\ifm@m@Or}
% \begin{macro}{\m@m@Ortrue}
% \begin{macro}{\m@m@Orfalse}
% \begin{macro}{\ifm@m@Xor}
% \begin{macro}{\m@m@Xortrue}
% \begin{macro}{\m@m@Xorfalse}
% These are for `if A and B', `if A or B' and `if A xor B'.
%
% For A and B:
% \begin{verbatim}
% \m@m@Andfalse
% \ifA
%   \ifB
%     \m@mAndtrue
%   \fi
% \fi
% \end{verbatim}
% For A or B:
% \begin{verbatim}
% \m@m@Ortrue
% \ifA
% \else
%   \ifB
%   \else
%     \m@m@Orfalse
%   \fi
% \fi
% \end{verbatim}
% For A xor B:
% \begin{verbatim}
% \m@m@Xortrue
% \ifA
%   \ifB
%     \m@m@Xfalse
%   \fi
% \else
%   \ifB
%   \else
%     \m@m@Xorfalse
%   \fi
% \fi
% \end{verbatim}
% \changes{v1.618}{2005/09/09}{Added \cs{ifm@m@And}, \cs{ifm@m@Or} and \cs{ifm@m@Xor}}
%    \begin{macrocode}
\newif\ifm@m@And
\newif\ifm@m@Or
\newif\ifm@m@Xor

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \changes{v0.3}{2001/07/09}{Deleted \cs{fillline} and \cs{makecommand} as
% they were not used}
%
%
% \begin{macro}{\kill@lastcounter}
% \cs{kill@lastcounter}\marg{cntr}\footnote{With thanks to Stefan Ulrich
% (\texttt{ulrich@cis.uni-muenchen.de}) who answered a question on this
% on \ctt, 2001/07/09. (Also answered by Heiko Oberdiek,
% \texttt{oberdiek@ruf.uni-freiburg.de}).}
%  kills the counter \meta{cntr}. This macro is an extension to the
% suggestions as it also makes the last count register reusable.
% \emph{The macro must only be used when the last allocated counter is to
% be killed.}
% For example with:\\
% \verb?\newcounter{fred} \kill@lastcounter{fred} \newcounter{fred}? \\
% there is no error with the second \cs{newcounter}.
% \changes{v0.3}{2001/07/09}{Added \cs{kill@counter}}
% \changes{v1.618}{2005/09/02}{Ensured \cs{kill@counter} zeroed the counter}
%    \begin{macrocode}
\newcommand{\kill@lastcounter}[1]{%
%    \end{macrocode}
% Deallocate the last counter register. From \theTeXbook, \verb?\count10? is
% the number of the last register. The counter should be zeroed before being
% deallocated otherwise an immediatally following \cs{newcount} may not
% be zero when allocated\footnote{Discovered and fix provided by Robert 
% Schlicht on 2005/08/31.}.
%    \begin{macrocode}
  \count\count10 \z@
  \advance\count10 \m@ne
%    \end{macrocode}
% Set the internal counter definition to \cs{relax}.
%    \begin{macrocode}
  \expandafter\let\csname c@#1\endcsname\relax}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@name@p@xdf}
% \begin{macro}{\@name@unresp@xdef}
% \begin{macro}{\@namelet}
% \begin{macro}{\@namelongdef}
%  Utility definition macros, along the lines of the kernel's \cs{@namedef}.
% \changes{v1.4}{2003/11/22}{Added \cs{@namelet} and friends (from patch v1.8)}
%    \begin{macrocode}
\newcommand{\@name@p@xdef}[1]{%
  \expandafter\protected@xdef\csname #1\endcsname}
\newcommand{\@name@unresp@xdef}[1]{%
  \expandafter\unrestored@protected@xdef\csname #1\endcsname}
\newcommand{\@namelet}[1]{%
  \expandafter\let\csname #1\endcsname}
\newcommand{\@namelongdef}[1]{%
  \long\expandafter\def\csname #1\endcsname}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memletcmdtxt}
% \begin{macro}{\memlettxttxt}
% \begin{macro}{\memlettxtcmd}
% More utility macros (for the user but perhaps better not to tell them about
% it in the manual) \\
% \verb?\memletcmdtxt{\cmd}{txt}  -> \let\cmd\txt? \\
% \verb?\memlettxttxt{txta}{txtb} -> \let\txta\txtb? \\
% \verb?\memlettxtcmd{txt}{\cmd}  -> \let\txt\cmd? \\
% \changes{v1.6180339f}{2009/06/25}{Added \cs{memletcmdtxt}, \cs{memlettxttxt}
%        and \cs{memlettxtcmd}}
%    \begin{macrocode}
\newcommand*{\memletcmdtxt}[2]{\expandafter\let\expandafter#1\csname#2\endcsname}
\newcommand*{\memlettxttxt}[1]{\expandafter\memletcmdtxt\csname#1\endcsname}
\newcommand*{\memlettxtcmd}[2]{\expandafter\let\csname#1\endcsname#2}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@nameedef}
% A shorthand for using \cs{protected@edef}.
%    \begin{macrocode}
\newcommand{\@nameedef}[1]{%
  \expandafter\protected@edef\csname #1\endcsname}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\memjustarg}
% \begin{macro}{\memgobble}
% Utility macros \emph{that are not to be changed by any user!}
% \changes{v1.618}{2005/09/25}{Added \cs{memjustarg} and \cs{memgobble}}
%    \begin{macrocode}
\newcommand{\memjustarg}[1]{#1}
\newcommand{\memgobble}[1]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \changes{v3.6k}{2013/05/14}{Added macro used macros}
% \begin{macro}{\memsetmacroused}
% \begin{macro}{\memsetmacrounused}
% \begin{macro}{\memifmacroused}
%   We may want to make auto adjustment to the layout unless the user
%   has used certain macros (in which case the user is responsible for
%   their own actions). To make this macro test easier, we provide a
%   few utility macros. Their use should be self explanatory. Though
%   note that the macro being marked as used, is given in full, i.e.,
% \begin{verbatim}
% \memsetmacroused\setlrmargins
% \end{verbatim}
%    \begin{macrocode}
\newcommand\memsetmacroused[1]{%
  \@namedef{mem@macro@used@\expandafter\@gobble\string#1}{00}}
\newcommand\memsetmacrounused[1]{%
  \@namedef{mem@macro@used@\expandafter\@gobble\string#1}{01}}
\newcommand\memifmacroused[1]{%
  \if\@nameuse{mem@macro@used@\expandafter\@gobble\string#1}%
  \expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi}

%    \end{macrocode}
%   
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memsetlengthmin}
% \begin{macro}{\memsetlengthmax}
%   Returns the min or max of two lengths. Note we may alter this in
%   the future to use \cs{dimexpr}.
%    \begin{macrocode}
\newcommand\memsetlengthmin[3]{\ifdim#2<#3\setlength{#1}{#2}\else\setlength{#1}{#3}\fi}
\newcommand\memsetlengthmax[3]{\ifdim#2>#3\setlength{#1}{#2}\else\setlength{#1}{#3}\fi}

%    \end{macrocode}
%   
% \end{macro}
% \end{macro}
%
% \subsection{Classes, Packages and Files}
%
% \begin{macro}{\@memfakeusepackage}
% \cs{@memfakeusepackage}\marg{pack} fools \LaTeX{} into thinking
% that the \meta{pack.sty} package has been loaded.
% \changes{v1.4}{2003/11/22}{Added \cs{@memfakeusepackage} (from patch v1.9)}
%    \begin{macrocode}
\newcommand*{\@memfakeusepackage}[1]{%
  \@namelet{ver@#1.sty}\@empty}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\EmulatedPackage}
% \begin{macro}{\EmulatedPackageWithOptions}
%  There was some discussion on CTT\footnote{\textit{Re: breakurl + pdfetex 
% for generating .dvi}, March 2005.} about how to prevent loading of
% a package. My response was to use \cs{@memfakusepackage}. Donald Arseneau
% came up with this comprehensive solution (there was a little discussion
% about naming with my final suggestion as here). \\
% \cs{EmulatedPackage}\marg{package}\oarg{date} \\
% \cs{EmulatedPackageWithOptions}\marg{option-list}\marg{package}\oarg{date} \\
%
% \changes{v1.618}{2005/09/04}{Added \cs{EmulatedPackage} and
%          \cs{EmulatedPackageWithOptions}}
% \changes{v1.6180339}{2008/07/23}{Extended \cs{EmulatedPackage}}
%    \begin{macrocode}
\providecommand*{\EmulatedPackage}{}
\renewcommand*{\EmulatedPackage}[1]{%
  \@ifnextchar[{\@emulated@package{#1}}%
               {\@emulated@package{#1}[\@empty]}%]
}
\providecommand*{\EmulatedPackageWithOptions}{}
\renewcommand*{\EmulatedPackageWithOptions}[2]{%
  \PassOptionsToPackage{#1}{#2}%
  \EmulatedPackage{#2}%
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@emulated@package}
% The workhorse for the user commands.
%    \begin{macrocode}
\def\@emulated@package#1[#2]{%
  \expandafter\xdef\csname ver@#1.\@pkgextension\endcsname{#2}%
  \@ifundefined{opt@#1.\@pkgextension}%
    {\@namedef{opt@#1.\@pkgextension}{}}{}%
  \wlog{Package #1 \ifx\@empty#2\else[#2] \fi 
        \if,\csname opt@#1.\@pkgextension\endcsname,\else
        (with options \csname opt@#1.\@pkgextension\endcsname) \fi
        emulated by \@currname.}%
}
\@onlypreamble\EmulatedPackage
\@onlypreamble\EmulatedPackageWithOptions
\@onlypreamble\@emulated@package

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\DisemulatePackage}
% \cs{DisemulatePackage}\marg{package} undoes a previous 
% \cs{EmulatedPackage...}
% \changes{v1.61803}{2008/01/30}{Added \cs{DisemulatePackage} from memptach v4.5}
% \changes{v1.6180339}{2008/07/23}{Fixed \cs{DisemulatePackage} from mempatch v5.1}
%    \begin{macrocode}
\newcommand*{\DisemulatePackage}[1]{%
  \@namelet{ver@#1.\@pkgextension}\relax}
\@onlypreamble\DisemulatePackage

%    \end{macrocode}
% \end{macro}
% 
%
%    Code, based on a hint from Morten H{\o}gholm\footnote{CTT posting
% 2005/11/08, \textit{Re: Checking for packages froma class... 
% revisited}} that the \Lpack{scrlfile} package from 
% \Lpack{koma-script} includes commands such as \\
% \cs{AfterFile}\marg{file}\marg{code} \\
% plus before and after classes and packages.
% \changes{v1.16803}{2008/01/30}{Added various \cs{AtBegin...} and 
%         \cs{AtEnd...} macros (mempatch v4.2)}
%
%    Extend the \cs{InputIfFileExists} macro to call hooks before and
% the actual inputting. The kernel version (as of 2005/11/21) is:
% \begin{verbatim}
% \newcommand{\InputIfFileExists}[2]{%
%  \IfFileExists{#1}%
%    {\#2\@addtofilelist{#1}\@@input \@filef@und}}
% \end{verbatim}
%
% \begin{macro}{\InputIfFileExists}
% Effectively all file input is handled by this macro. Extend it
% by adding pre- and post- input hooks.
%    \begin{macrocode}
\renewcommand{\InputIfFileExists}[2]{%
  \IfFileExists{#1}%
    {#2\@addtofilelist{#1}\m@matbeginf{#1}%
     \@@input \@filef@und
     \m@matendf{#1}%
     \killm@matf{#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@matbeginf}
% \begin{macro}{\m@matendf}
% \cs{m@matbeginf}\marg{file} calls macro \cs{file-m@mfb} if it 
% is defined. Similarly \cs{m@matendf}\marg{file} calls
% \cs{file-m@mfe} if it is defined.
%    \begin{macrocode}
\newcommand{\m@matbeginf}[1]{\@ifundefined{#1-m@mfb}{}%
  {\@nameuse{#1-m@mfb}}}
\newcommand{\m@matendf}[1]{\@ifundefined{#1-m@mfe}{}%
  {\@nameuse{#1-m@mfe}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\killm@matf}
% \cs{killm@matf}\marg{file} undefines the \cs{file-m@mfb} and
% \cs{file-m@mfe} macros.
%    \begin{macrocode}
\newcommand*{\killm@matf}[1]{%
  \@namelet{#1-m@mfb}\relax
  \@namelet{#1-m@mfe}\relax}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\AtBeginFile}
% \begin{macro}{\AtEndFile}
% \cs{AtBeginFile}\marg{file}\marg{code} inserts \meta{code}
% just before \meta{file} is input. Similarly \cs{AtEndFile} inserts
% just after input.
%    \begin{macrocode}
\newcommand{\AtBeginFile}[2]{\@ifundefined{#1-m@mfb}%
  {\@namedef{#1-m@mfb}{#2}}%
  {\expandafter\addtodef\csname #1-m@mfb\endcsname{}{#2}}}
\newcommand{\AtEndFile}[2]{\@ifundefined{#1-m@mfe}%
  {\@namedef{#1-m@mfe}{#2}}%
  {\expandafter\addtodef\csname #1-m@mfe\endcsname{}{#2}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\AtBeginPackage}
% \begin{macro}{\AtEndPackage}
% \begin{macro}{\RequireAtEndPackage}
% \cs{AtBeginPackage}\marg{pack}\marg{code} inserts \meta{code} 
% just before the \meta{pack} package is input, and \cs{AtEndPackage}
% is the equivalent for after input. \cs{RequireAtEndPackage} inserts
% \meta{code} either at the end of \meta{pack}, or immediately if
% \meta{pack} has already been input.
%    \begin{macrocode}
\newcommand{\AtBeginPackage}[2]{%
  \AtBeginFile{#1.\@pkgextension}{#2}}
\newcommand{\AtEndPackage}[2]{%
  \AtEndFile{#1.\@pkgextension}{#2}}
\newcommand{\RequireAtEndPackage}[2]{%
  \@ifpackageloaded{#1}{#2}%
  {\AtEndFile{#1.\@pkgextension}{#2}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\AtBeginClass}
% \begin{macro}{\AtEndClass}
% \begin{macro}{\RequireAtEndClass}
% \cs{AtBeginClass}\marg{class}\marg{code} and friends are the class
% equivalents of \cs{AtBeginPackage} and friends.
%    \begin{macrocode}
\newcommand{\AtBeginClass}[2]{%
  \AtBeginFile{#1.\@clsextension}{#2}}
\newcommand{\AtEndClass}[2]{%
  \AtEndFile{#1.\@clsextension}{#2}}
\newcommand{\RequireAtEndClass}[2]{%
  \@ifclassloaded{#1}{#2}%
  {\AtEndFile{#1.\@clsextension}{#2}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%
%
% \begin{macro}{\phantomsection}
% A command needed if the \Lpack{hyperref} package is used, for putting
% before certain \cs{addcontentsline} commands.
%    \begin{macrocode}
\newcommand{\phantomsection}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\nofiles}
% The kernel's \cs{nofiles}, which surprisingly may be called \emph{before} 
% the class is loaded, lets \cs{makeindex} to \cs{relax}. This could 
% cause problems\footnote{As reported by Heiko Oberdiek on 2005/07/09.}
% with my initial version of \cs{makeindex}.
% Here's the kernel \cs{nofiles} definition:
% \begin{verbatim}
% \def\nofiles{%
%   \@fileswfalse%  flag for suppressing \immediate \writes
%   \typeout{No auxiliary output files.^^J}%
%   \long\def\protected@write##1##2##3%
%     {\write\m@ne{}\if@nobreak\ifvmode\nobreak\fi\fi}%
%   \let\makeindex\relax
%   \let\makeglossary\relax}
% \end{verbatim}
% To get it to work for when \cs{makeindex}es optional argument is
% used I let \cs{makeindex} itself deal with \cs{nofiles} (and
% also \cs{makeglossary}).
% \changes{v1.618}{2005/09/25}{Modified the kernel's \cs{nofiles}}
%    \begin{macrocode}
 \renewcommand*{\nofiles}{%
   \@fileswfalse%  flag for suppressing \immediate \writes
   \typeout{No auxiliary output files.^^J}%
   \long\def\protected@write##1##2##3%
     {\write\m@ne{}\if@nobreak\ifvmode\nobreak\fi\fi}%
   }

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\memsetcounter}
% A wrapper round \cs{setcounter}. I want to use this in the \texttt{aux} file.
% \changes{v1.61803}{2008/01/30}{Added \cs{memsetcounter}}
%    \begin{macrocode}
\newcommand*{\memsetcounter}[2]{\setcounter{#1}{#2}}
\AtBeginDocument{\immediate\write\@mainaux{%
  \string\providecommand*{\string\memsetcounter}[2]{}}}

%    \end{macrocode}
% \end{macro}
%
% \subsection{For package documentation}
%
% Some macros that may be useful for documenting LaTeX code. These
% have principally come from \texttt{doc.dtx}.
%
% \begin{macro}{\bs}
% Prints \verb?\?
%    \begin{macrocode}
\def\bs{\texttt{\char`\\}}
%    \end{macrocode}
% \end{macro} 
%
% \begin{macro}{\l@nohyphenation}
% \begin{macro}{\meta}
% \begin{macro}{\meta@font@select}
% From \texttt{doc.dtx} \\
% \cs{meta}\marg{arg} prints \meta{arg}.
%    \begin{macrocode}
\ifx\l@nohyphenation\undefined
  \newlanguage\l@nohyphenation
\fi
\DeclareRobustCommand{\meta}[1]{%
  \ensuremath\langle
  \ifmmode \expandafter \nfss@text \fi
  {%
    \meta@font@select
    \edef\meta@hyphen@restore
      {\hyphenchar\the\font\the\hyphenchar\font}%
    \hyphenchar\font\m@ne
    \language\l@nohyphenation
    #1\/%
    \meta@hyphen@restore
  }\ensuremath\rangle
}
\def\meta@font@select{\itshape}

%    \end{macrocode}
% \end{macro} 
% \end{macro} 
% \end{macro} 
%
% \begin{macro}{\marg}
% \begin{macro}{\oarg}
% \begin{macro}{\parg}
% Robust versions of the \texttt{doc.dtx} macros. \\
% \cs{marg}\marg{arg} prints \marg{arg} \\
% \cs{oarg}\marg{arg} prints \oarg{arg} \\
% \cs{parg}\marg{arg} prints \parg{arg} \\
%    \begin{macrocode}
\DeclareRobustCommand{\marg}[1]{%
  {\ttfamily\char`\{}\meta{#1}{\ttfamily\char`\}}}
\DeclareRobustCommand{\oarg}[1]{%
  {\ttfamily\char`\[}\meta{#1}{\ttfamily\char`\]}}
\DeclareRobustCommand{\parg}[1]{%
  {\ttfamily\char`\(}\meta{#1}{\ttfamily\char`\)}}
%    \end{macrocode}
% \end{macro} 
% \end{macro} 
% \end{macro} 
%
% \begin{macro}{\cs}
% \verb?\cs{arg}? prints \cs{arg}.
%    \begin{macrocode}
\DeclareRobustCommand{\cs}[1]{\texttt{\char`\\#1}}
%    \end{macrocode}
% \end{macro} 
%
%
% \begin{macro}{\cmdprint}
% \begin{macro}{\cmd}
% From Heiko Oberdiek CTT 2001/05/26 (print and index a command) \\
% \verb?\cmdprint{\fred}? prints \verb?\fred? \\
% \verb?\cmd{\fred}? prints and indexes \verb?\fred?. NOTE It assumes that
% \verb!?! is the `actual' character for MakeIndex (it is normally \verb!@!
% but that is not much use if a command includes \verb!@! as part of its name).
%    \begin{macrocode}
\newcommand{\cmdprint}[1]{\texttt{\string#1}}
\newcommand{\cmd}[1]{\cmdprint{#1}%
  \index{\expandafter\@gobble\string#1?\string\cmdprint{\string#1}}}

%    \end{macrocode}
% \end{macro} 
% \end{macro} 
%
%
%
%
% \subsection{Checking the processor}
%
%     Prior to 2008/07/22 the \Lpack{hyperref} package was modified in such a 
% way as to produce warnings about versions of the \Lpack{ifpdf} and 
% \Lpack{ifxetex} packages when \Lpack{hyperref} was used with versions 
% v1.618033, 
% v1.61803, or v1.618 mempatch v4.9 of the class. 
% \Lpack{hyperref}'s author refused to
% make any changes to his package, insisting that emulating a package was 
% `ugly hacking'. He did, though, provide an example code that could be 
% added to memoir
% to use a package if it was available. I have used it for the emulations
% in this section. There will be no further changes to the class to accomodate
% any further changes to \Lpack{hyperref} --- it's easy for a package to 
% determine what class is being used and make arrangements accordingly, 
% especially as there are not all that many classes. There are hundreds 
% of packages that might be used with a particular class and it would be 
% senseless for a class to attempt to take account of everything that might 
% be used with it.
%
% ^^A % Note (2016/05/16): Due to recent changes in Luatex, most notably the
% ^^A % removal of several \cs{pdf...} macro, several PDF tests fail with
% ^^A % LuaLaTeX. As a temporary measure the following is used to restore
% ^^A % the old functionality when a newer LuaLaTeX is used. Code courtesy
% ^^A % of David Carlisle. At some point we will include some of this into
% ^^A % the class.
% \changes{v3.7f}{2016/05/16}{Temp measure to make the class work with
% updated luatex}
% \changes{v3.7g}{2018/03/09}{\Lpack{luatex85} removed again, now
% relying on external \cs{if<engine>} packages and have rewritten the
% macros that use \cs{pdf...}}
% ^^A %    \begin{macrocode}
% ^^A \ifx\pdfextension\@undefined\else
% ^^A   \RequirePackage{luatex85}
% ^^A \fi    
% ^^A 
% ^^A %    \end{macrocode}
% 
%
% \begin{macro}{\ifpdf}
% This can be used to check whether or not a document is being processed
% by \LaTeX{} or pdf\LaTeX.  We will simply require the \Lpack{ifpdf} package.
% \changes{v1.0}{2001/09/21}{Made checking of \cs{pdfouput} more robust}
% \changes{v1.618}{2005/09/03}{Prohibit loading the ifpdf package (mempatch v3.9)}
% \changes{v1.618033}{2008/06/02}{Further improved pdf checking}
% \changes{v1.6180339}{2008/07/23}{Use ifpdf package if available}
% \changes{v1.61803398d}{2009/12/01}{if \cs{ifpdf} is already
% defined, e.g. using \cs{RequirePackage} before \cs{documentclass},
% then using \cs{newif}\cs{ifpdf} will cause TeX to eat up a lot of
% code. We fix this using a hint by Will Robertson.}
% \changes{v3.7g}{2018/03/08}{As of 2018, we will no longer be
% emulating \cs{if}\meta{engine} packages, you'll get an error if you
% do not have them}
%    \begin{macrocode}
\RequirePackage{ifpdf}[2017/03/15] 
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifetex}
% Check if \texttt{etex} is being used. We will simply require the \Lpack{ifetex} package.
% \changes{v1.61803}{2008/01/30}{Added check for etex (mempatch v4.9)}
% \changes{v1.618033}{2008/06/02}{Improved check for etex}
% \changes{v1.6180339}{2008/07/23}{Use an ifetex package if available}
% \changes{v1.6180339c}{2008/12/27}{Changed ifetex message from Warning to Info}
% \changes{v3.7g}{2018/03/08}{As of 2018, we will no longer be
% emulating \cs{if}\meta{engine} packages, you'll get an error if you
% do not have them}
%    \begin{macrocode}
\RequirePackage{ifetex}
%    \end{macrocode}
% \end{macro}
% Having supplied an \cs{ifpdf} to check if pdfLaTeX is being used,
% here's one for XeTeX.
%
% \begin{macro}{\ifxetex}
% Checks if XeTeX is being used. We will simply require the \Lpack{ifxetex} package.
% \changes{v1.61803}{2008/01/30}{Added checks for XeTeX (mempatch v4.9)}
% \changes{v1.6180339}{2008/07/23}{Use ifxetex package if available}
% \changes{v1.61803398d}{2009/12/01}{if \cs{ifxetex} is already
% defined, e.g. using \cs{RequirePackage} before \cs{documentclass},
% then using \cs{newif}\cs{ifxetex} will cause TeX to eat up a lot of
% code. We fix this using a hint by Will Robertson.}
% \changes{v3.7g}{2018/03/08}{As of 2018, we will no longer be
% emulating \cs{if}\meta{engine} packages, you'll get an error if you
% do not have them}
%    \begin{macrocode}
\RequirePackage{ifxetex}[2010/09/12]
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifluatex}
% Check if \texttt{luatex} is being used.  We will simply require the \Lpack{ifluatex} package.
% \changes{v1.61803}{2008/01/30}{Added check for luatex}
% \changes{v1.6180339}{2008/07/23}{Use an ifluatex package if available}
% \changes{v1.6180339c}{2008/12/31}{It seems that Heiko Oberdiek has created an
%           ifluatex package.}
% \changes{v1.61803398d}{2009/12/01}{if \cs{ifluatex} is already
% defined, e.g. using \cs{RequirePackage} before \cs{documentclass},
% then using \cs{newif}\cs{ifluatex} will cause TeX to eat up a lot of
% code. We fix this using a hint by Will Robertson.}
% \changes{v3.7g}{2018/03/08}{As of 2018, we will no longer be
% emulating \cs{if}\meta{engine} packages, you'll get an error if you
% do not have them}
%    \begin{macrocode}
\RequirePackage{ifluatex}[2016/05/16]

%    \end{macrocode}
% \end{macro}
%
% \subsection{Extending an existing macro}
%
%
%    My usual technique for modifying the code of an existing
% macro was to use \cs{renewcommand}. However it slowly became apparent that
% many of such modifications merely consisted of adding some code at
% either the start or end of the existing definition. In June 2000 I 
% posed a question
% on the \texttt{comp.text.tex} newsgroup about this, and 
% Michael Downes\footnote{\texttt{epsmjd@ams.org}} and
% Heiko Oberdiek\footnote{\texttt{oberdiek@ruf.uni-freiburg.de}} 
% were kind enough to respond.
% The responses arrived almost simultaneously, both
% supplying methods for adding code at the end of a macro defined to take
% one argument. Michael Downes' response included a remark about it probably
% being too much effort to formulate a general way of doing this.
% Heiko Oberdiek almost immediately replied with such a generalisation.
%
%    The following code, which I have extracted from a package that I
% wrote but which I did not submit to CTAN, incorporates the work of both
% Michael and Heiko. I have added a bit. All errors are my responsibility.
% Michael went on the write the \Lpack{patchcmd} package which is
% a generalisation of the facilities below and so there was no need for
% my more restricted package.
% \changes{v0.33}{2001/08/31}{Replaced \cs{appendiarg} with \cs{addtodef}
%                             and friends}
%
% \begin{macro}{\wo@dmacro}
%    Heiko Oberdiek suggested\footnote{Via email on 2000/07/12.} that
% \meta{macro} should be tested for being the name of a macro, rather than
% using the normal \LaTeX{} test against it being undefined. He supplied
% the code for performing the macro name test.
%
% \cs{wo@dmacro} is a helper for handling the string `macro:'.
%    \begin{macrocode}
\edef\wo@dmacro{%
  \string m\string a\string c\string r\string o\string :%
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\wo@difmacro@begingroup}
% This seems to take two arguments: 
% \cs{wo@difmacro@begingroup}\marg{macro}\marg{code}, where 
% \meta{macro} should be the name of a defined macro and \meta{code}
% is code to be executed if and only if \meta{macro} \emph{is} a
% defined macro.
%    \begin{macrocode}
\def\wo@difmacro@begingroup#1{%
%    \end{macrocode}
% Start a group.
%    \begin{macrocode}
  \begingroup
%    \end{macrocode}
% Test if \verb?#1? is a defined macro; \cs{wo@dparsemacro} does most of the work.
%    \begin{macrocode}
    \edef\x{%
      \noexpand\wo@dparsemacro\meaning#1\wo@dmacro\string -%
    }%
    \x\@nil{#1}%
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\wo@dparsemacro}
% This is called by \cs{wo@difmacro@begingroup}. If \meta{macro} is not
% a defined macro it prints a warning and closes the group begun by
% \cs{wo@difmacro@begingroup}. Otherwise it process the \meta{code} which
% \emph{must} close the group.
%    \begin{macrocode}
\begingroup
  \edef\x{\endgroup
    \def\noexpand\wo@dparsemacro##1\wo@dmacro##2\string -}%
\x#3\@nil#4{%
  \ifx\\#3\\%
    \endgroup
    \@memwarn{\string `\string #4\string ' is not a macro}%
    \expandafter\@gobble
  \else
    \expandafter\@firstofone
  \fi
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\addtodef}
% \begin{macro}{\addtodef*}
% \begin{macro}{\wo@daddtodef}
% The command \cs{addtodef}\marg{macro}\marg{start-stuff}\marg{end-stuff}
% adds stuff at the start and/or end of an argumentless  macro. 
% Initially the code for appending was a reimplementation of the
% kernel \cs{g@addto@macro} command (from \file{ltclass.dtx}).
% Later, at Michael Downes' suggestion, I combined
% appending and prepending stuff into a single command. 
% Actually, there is no real need to have both
% \cs{addtodef} and \cs{addtodef*} as the body of the command
% being amended has no argument,
% but both versions are provided for consistency.
%
%    The kernel \cs{@star@or@long} and \cs{l@ngrel@x} commands 
% (in \file{ltdefns.dtx}) are used to handle 
% the potential \verb?*? after the command name.
%    \begin{macrocode}
\def\addtodef{\@star@or@long\wo@daddtodef}
%    \end{macrocode}
% The \cs{@star@or@long} command dealt with a possible \verb?*? and now
% \cs{wo@daddtodef} does the work. It picks up the three arguments
% that the user thinks belong to \cs{addtodef}, namely \meta{macro},
% \meta{start-stuff} and \meta{end-stuff}.
%    \begin{macrocode}
\long\def\wo@daddtodef#1#2#3{%
%    \end{macrocode}
% Check if \meta{macro} has been defined. 
%    \begin{macrocode}
  \wo@difmacro@begingroup{#1}{%
%    \end{macrocode}
% If \meta{macro} is defined then store the tokens corresponding to the 
% body of \meta{macro} and the extra \meta{-stuff} in token registers.
%    \begin{macrocode}
    \@temptokena{#2}%
    \toks@\expandafter{#1#3}%
%    \end{macrocode}
% Do an expanded definition for \cs{x}, so that calling \cs{x}
% will \cs{def} a new version of \meta{macro}, whose body consists of the
% saved tokens (i.e., the orginal body plus the extra stuff). 
% As Michael Downes noted, single letter control sequences do not take any of
% \TeX's hash table space.
% \cs{l@ngrel@x}
% has been previously set to either \cs{long} or \cs{relax} by \cs{@star@or@long},
% and so may make the new definition of \meta{macro} to be \cs{long}. 
%    \begin{macrocode}
    \edef\x{\endgroup 
         \l@ngrel@x\def\noexpand#1{\the\@temptokena \the\toks@}}%
%    \end{macrocode}
% Finally, call \cs{x} to perform the new definition.
%    \begin{macrocode}
    \x
  }%
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\addtoiargdef}
% \begin{macro}{\addtoiargdef*}
% \begin{macro}{\wo@daddtoiargdef}
%  This adds stuff at the start and/or end of a macro that takes one argument.
% It is a modification of Michael Downes' appending 
% code\footnote{Posted to \ctt{} on 15~June 2000,\\
% URL: \url{http://www.dejanews.com/getdoc.xp?AN=635057844}.}
% which was:
% \begin{small}\begin{verbatim}
% \def\appendef#1#2{%
%   \begingroup
%     \toks@\expandafter{#1{##1}#2}%
%     \edef\x{\endgroup \def\noexpand#1####1{\the\toks@}}%
%   \x}
% \end{verbatim}
% \par\end{small}
%
%    \begin{macrocode}
\def\addtoiargdef{\@star@or@long\wo@daddtoiargdef}
\long\def\wo@daddtoiargdef#1#2#3{%
  \wo@difmacro@begingroup{#1}{%
    \@temptokena{#2}%
    \toks@\expandafter{#1{##1}#3}%
    \edef\x{\endgroup 
       \l@ngrel@x\def\noexpand#1####1{\the\@temptokena \the\toks@}}%
    \x
  }%
}

%    \end{macrocode}
%    For the record, Heiko Oberdiek produced the following 
% version\footnote{Posted to \ctt{} on 16~June 2000,\\
% URL: \url{http://www.dejanews.com/getdoc.xp?AN=635095381}.}
% which avoids the use of a token register.
% \begin{small}\begin{verbatim}
% \newcommand{\appendiargdef}[2]{%
%   \long\expandafter\def\expandafter#1\expandafter
%   ##\expandafter1\expandafter{#1{##1}#2}}
% \end{verbatim}
% \par\end{small}
%
% \end{macro}
% \end{macro}
% \end{macro}
%
% Continuing the saga, Michael came up with a pretty general solution for
% modifying a macro with any number (up to 9) of arguments which he
% sent to me on 2000/07/13; this became
% the \Lpack{patchcmd} package which is on CTAN. I'm sure that Michael 
% would have given me permission to include it here if he had not tragically
% passed away in 2003. I miss his encouragement, advice, and skills.
%
% \begin{macro}{\patchcmd}
% \cs{patchcmd}\marg{macro}\marg{start-stuff}\marg{end-stuff} inserts
% \meta{start-stuff} at the beginning of the definition of \meta{macro}
% and \meta{end-stuff} at the end of the definition. \meta{macro}
% can have 0--9 arguments and be defined by \cs{newcommand} (and associates)
% or with \cs{DeclareRobustCommand}. For macros that use \cs{futurelet}
% (e.g., those with starred forms or optional arguments) only prepending
% works --- any non-empty \meta{end-stuff} will mess things up. \cs{patchcmd}
% does not work with macros that have delimited arguments.
% \changes{v1.618}{2005/09/05}{Added \cs{patchcmd}}
%
%    \begin{macrocode}
%%%%%%%%%%%%%%%% Michael Downes' patchcmd 2000/07/31 v1.03 %%%%%%%%
\newcommand{\patchcommand}[1]{%
  \expandafter\patchcmd@a\meaning#1??->@\@nil#1%
}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\patchcmd@a}
%    \begin{macrocode}
\long\def\patchcmd@a#1#2#3->#4#5\@nil#6{%
  \ifx @#4\relax \patchcmdError#6#1%
    \expandafter\@gobbletwo % discard the other two arguments
  \else
    \if l#2\toks@{\patchcmd@e{}#6}% l in this position means \long
    \else \toks@{\patchcmd@e*#6}%   not \long
    \fi
    \patchcmd@b #3@#4#5 ? ? ? \@nil#6%
    \expandafter\the\expandafter\toks@
  \fi}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\patchcmd@b}
%    \begin{macrocode}
\def\patchcmd@b#1:#2@#3#4 #5#6 #7 #8\@nil#9{%
  \if \ifx @#7@\expandafter
      \ifx\csname #6\endcsname#9T\else F\fi\else F\fi T%
    \toks@\expandafter{\expandafter\patchcommand\csname #6 \endcsname}%
  \else
    \ifx @#2@% No arguments
      \toks@\expandafter{\the\toks@ 0}%
    \else
      \patchcmd@c 0#2{\string##}0%
    \fi
  \fi}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\patchcmd@c}
%    \begin{macrocode}
\def\patchcmd@c#1#2#3{%
  \if\string###2%      % yes it's a # token
    \ifodd 0#31 % and it's followed by a number
      \if 0#3\patchcmd@d#1\fi % number=0? then we're done
    \else \patchcmd@d D% # not a number: must be a delimited arg
    \fi
  \else \patchcmd@d D% not a # token: must be a delmited arg
  \fi
  \patchcmd@c#3}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\patchcmd@d}
%    \begin{macrocode}
\def\patchcmd@d#1{%
  \if D#1%
%%%    \PackageError{patchcmd}{Cannot change a macro that has
%%%      delimited arguments}\@ehd
    \@memerror{%
      Cannot change a macro that has delimited arguments}{\@ehd}
  \else
    \toks@\expandafter{\the\toks@ #1}%
  \fi
  \begingroup
  \aftergroup\@gobble
  \let\patchcmd@c\endgroup}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\patchcmd@e}
%    \begin{macrocode}
\def\patchcmd@e#1#2#3#4#5{%
  \begingroup
  \edef\@##1{%
    \@temptokena\noexpand\expandafter{%
      \noexpand#2%
        \ifnum#3>0 {####1}\ifnum#3>1 {####2}\ifnum#3>2 {####3}%
        \ifnum#3>3 {####4}\ifnum#3>4 {####5}\ifnum#3>5 {####6}%
        \ifnum#3>6 {####7}\ifnum#3>7 {####8}\ifnum#3>8 {####9}%
        \fi\fi\fi\fi\fi\fi\fi\fi\fi
      ##1%
    }%
  }
  \@{#5}%
  \edef\@##1{\endgroup
    \noexpand\renewcommand#1\noexpand#2\ifcase#3 \else [#3]\fi
    {##1\the\@temptokena}}%
  \@{#4}%
}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\patchcmdError}
%    \begin{macrocode}
\long\def\patchcmdError#1#2{%
  \begingroup
  \toks@{Not redefinable}%
  \ifcat\relax\noexpand#1% Is it a control sequence?
    \begingroup
    \let#1=?\ifx ?\relax % Is it "\relax"?
      \endgroup % accept current value of \toks@
    \else \endgroup
      \if\ifx\relax#1u\else #2\fi u%
        \toks@{Not defined}%
      \fi
    \fi
  \fi
  \edef\@{\endgroup
%%%    \noexpand\PackageError{patchcmd}{%
%%%      \the\toks@: \string#1}\noexpand\@ehd}%
    \noexpand\@memerror{%
      \the\toks@: \string#1}\noexpand\@ehd}%
  \@}

%%%%%%%%%%%%%%%%%%%%% end of patchcmd code %%%%%%%%%%%%%%%%%%%%%%%%%%%

%    \end{macrocode}
% \end{macro}
% 
% Prevent later loading of the original \Lpack{patchcmd} package.
%    \begin{macrocode}
%%\@memfakeusepackage{patchcmd}

%    \end{macrocode}
% 
% \changes{v1.61803398}{2009/07/18}{Added support for bidi}
% \subsection{Support for the bidi package (RTL typesetting)}
%
%   The \Lpack{bidi} package (system) enables bidirectional typesetting. 
% As part of
% being able to accomplish this it often needs to exchange, for example,
% \cs{leftskip} and \cs{rightskip} depending on whether it is setting
% left-to-right (LTR) or right-to-left (RTL). In the case of \Lpack{memoir}
% the initial \Lpack{bidi} system implementation used a \Lpack{bidimemoir} 
% class developed by Vafa Khalighi. Now, with Vafa's help, the necessary 
% changes have been incorporated in \Lpack{memoir}; the \Lpack{bidimemoir}
% class is no longer needed.
%
% \begin{macro}{\memRTLleftskip}
% \begin{macro}{\memRTLrightskip}
% \begin{macro}{\memRTLvleftskip}
% \begin{macro}{\memRTLvrightskip}
% \begin{macro}{\memRTLraggedright}
% \begin{macro}{\memRTLraggedleft}
% \begin{macro}{\memRTLmainraggedright}
% \begin{macro}{\memRTLmainraggedleft}
% These are the hooks required to support the \Lpack{bidi} package,
% plus some we added that \Lpack{bidi} can use. The idea behind the
% \cs{XmainraggedX} macros are documents fully in RTL mode, then it
% makes sense to have the raggedness of the header and footer
% reversed. By default they do what the normally do, but in main RTL
% mode, \Lpack{bidi} can redefine them to reverse the order of the
% headers, i.e. the `left' part of the header is typeset as the
% `right' part. 
% \changes{v3.6h}{2010/10/22}{Added \cs{mem@RTLmainraggedX} macros}
% \changes{v3.6k}{2011/06/24}{the \cs{mem@RTLvX} macros should point
% at \cs{vX} not \cs{X}}
%    \begin{macrocode}
\newcommand*{\memRTLleftskip}{\leftskip}
\newcommand*{\memRTLrightskip}{\rightskip}
\newcommand*{\memRTLvleftskip}{\vleftskip}
\newcommand*{\memRTLvrightskip}{\vrightskip}
\newcommand*{\memRTLraggedright}{\raggedright}
\newcommand*{\memRTLraggedleft}{\raggedleft}
\newcommand*{\memRTLmainraggedright}{\raggedright}
\newcommand*{\memRTLmainraggedleft}{\raggedleft}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% It is expected that the \Lpack{bidi} package will redefine these as:
% \begin{verbatim}
% \renewcommand*{\memRTLleftskip}{\if@RTL\rightskip\else\leftskip\fi}
% \renewcommand*{\memRTLrightskip}{\if@RTL\leftskip\else\rightskip\fi}
% \renewcommand*{\memRTLvleftskip}{\if@RTL\vrightskip\else\vleftskip\fi}
% \renewcommand*{\memRTLvrightskip}{\if@RTL\vleftskip\else\vrightskip\fi}
% \renewcommand*{\memRTLraggedright}{\if@RTL\raggedleft\else\raggedright\fi}
% \renewcommand*{\memRTLraggedleft}{\if@RTL\raggedright\else\raggedleft\fi}
% \renewcommand*{\memRTLmainraggedright}{\if@RTLmain\raggedleft\else\raggedright\fi}
% \renewcommand*{\memRTLmainraggedleft}{\if@RTLmain\raggedright\else\raggedleft\fi}
% \end{verbatim}
%
% \section{Declaration of Options} \label{sec:opt}
%
%
% \subsection{Setting Paper Sizes}
%
%    The variables \cs{paperheight} and \cs{paperwidth} should reflect the
%    physical paper size after trimming. 
%
%    Option \Lopt{letterpaper} will be the default.
%
% \begin{macro}{\stockheight}
% \begin{macro}{\stockwidth}
% \begin{macro}{\trimtop}
% \begin{macro}{\trimedge}
% The lengths \cs{stockheight} and \cs{stockwidth} should be the height and 
% width of the stock sheet before trimming. For example, this is the 
% physical size
% of a single sheet that might be laser-printed. The lengths \cs{trimtop}
% and \cs{trimedge} are the amount that will be trimmed off the top and fore
% edge of the physical sheet.
% For desk printer output the size of the trimmed sheet is often the
% same as the physical sheet. In other words the \cs{paper...} and \cs{stock...}
% sizes are the same and the trims are zero. This class assumes that this
% is the normal case.
%    \begin{macrocode}
\newlength{\stockheight}
\newlength{\stockwidth}
\newlength{\trimtop}
\newlength{\trimedge}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% The class provides an extended range of stock sizes. It may be useful at some
% point to have macros for these.
%
% \begin{macro}{\stockdbill}
% \begin{macro}{\stockstatement}
% \begin{macro}{\stockexecutive}
% \begin{macro}{\stockletter}
% \begin{macro}{\stockold}
% \begin{macro}{\stocklegal}
% \begin{macro}{\stockledger}
% \begin{macro}{\stockbroadsheet}
% US stock sizes.
% \changes{v1.61803}{2008/01/30}{Major expansion of stock size options}
%    \begin{macrocode}
\newcommand*{\stockdbill}     {\stockheight=7in    \stockwidth=3in}
\newcommand*{\stockstatement} {\stockheight=8.5in  \stockwidth=5.5in}
\newcommand*{\stockexecutive} {\stockheight=10.5in \stockwidth=7.25in}
\newcommand*{\stockletter}    {\stockheight=11in   \stockwidth=8.5in}
\newcommand*{\stockold}       {\stockheight=12in   \stockwidth=9in}
\newcommand*{\stocklegal}     {\stockheight=14in   \stockwidth=8.5in}
\newcommand*{\stockledger}    {\stockheight=17in   \stockwidth=11in}
\newcommand*{\stockbroadsheet}{\stockheight=22in   \stockwidth=17in}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\stockpottvo}
% \begin{macro}{\stockfoolscapvo}
% \begin{macro}{\stockcrownvo}
% \begin{macro}{\stockpostvo}
% \begin{macro}{\stocklargecrownvo}
% \begin{macro}{\stocklargepostvo}
% \begin{macro}{\stocksmalldemyvo}
% Traditional British octavo sizes.
%    \begin{macrocode}
\newcommand*{\stockpottvo}      {\stockheight=6.25in \stockwidth=4in}
\newcommand*{\stockfoolscapvo}  {\stockheight=6.75in \stockwidth=4.25in}
\newcommand*{\stockcrownvo}     {\stockheight=7.5in  \stockwidth=5in}
\newcommand*{\stockpostvo}      {\stockheight=8in    \stockwidth=5in}
\newcommand*{\stocklargecrownvo}{\stockheight=8in    \stockwidth=5.25in}
\newcommand*{\stocklargepostvo} {\stockheight=8.25in \stockwidth=5.25in}
\newcommand*{\stocksmalldemyvo} {\stockheight=8.5in  \stockwidth=5.675in}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\stockdemyvo}
% \begin{macro}{\stockmediumvo}
% \begin{macro}{\stocksmallroyalvo}
% \begin{macro}{\stockroyalvo}
% \begin{macro}{\stocksuperroyalvo}
% \begin{macro}{\stockimperialvo}
%    \begin{macrocode}
\newcommand*{\stockdemyvo}      {\stockheight=8.75in  \stockwidth=5.675in}
\newcommand*{\stockmediumvo}    {\stockheight=9in     \stockwidth=5.75in}
\newcommand*{\stocksmallroyalvo}{\stockheight=9.25in  \stockwidth=6.175in}
\newcommand*{\stockroyalvo}     {\stockheight=10in    \stockwidth=6.25in}
\newcommand*{\stocksuperroyalvo}{\stockheight=10.25in \stockwidth=6.75in}
\newcommand*{\stockimperialvo}  {\stockheight=11in    \stockwidth=7.5in}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% 
% \begin{macro}{\stockmcrownvo}
% \begin{macro}{\stockmlargecrownvo}
% \begin{macro}{\stockmdemyvo}
% \begin{macro}{\stockmsmallroyalvo}
% Metric stock sizes.
%    \begin{macrocode}
\newcommand*{\stockmcrownvo}      {\stockheight=186mm \stockwidth=123mm}
\newcommand*{\stockmlargecrownvo} {\stockheight=198mm \stockwidth=129mm}
\newcommand*{\stockmdemyvo}       {\stockheight=216mm \stockwidth=138mm}
\newcommand*{\stockmsmallroyalvo} {\stockheight=234mm \stockwidth=156mm}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\stockao}
% \begin{macro}{\stockai}
% \begin{macro}{\stockaii}
% \begin{macro}{\stockaiii}
% \begin{macro}{\stockaiv}
% \begin{macro}{\stockav}
% \begin{macro}{\stockavi}
% The A series, A0 --- A6.
% \changes{v1.6180339c}{2008/12/26}{Extended the A and B stock/paper size
%     seies with A/B0 through A/B2}
%    \begin{macrocode}
\newcommand*{\stockao}  {\stockheight=1189mm \stockwidth=841mm}
\newcommand*{\stockai}  {\stockheight=841mm \stockwidth=594mm}
\newcommand*{\stockaii} {\stockheight=594mm \stockwidth=420mm}
\newcommand*{\stockaiii}{\stockheight=420mm \stockwidth=297mm}
\newcommand*{\stockaiv} {\stockheight=297mm \stockwidth=210mm}
\newcommand*{\stockav}  {\stockheight=210mm \stockwidth=148mm}
\newcommand*{\stockavi} {\stockheight=148mm \stockwidth=105mm}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\stockbo}
% \begin{macro}{\stockbi}
% \begin{macro}{\stockbii}
% \begin{macro}{\stockbiii}
% \begin{macro}{\stockbiv}
% \begin{macro}{\stockbv}
% \begin{macro}{\stockbvi}
% The B series, B0 --- B6.
%    \begin{macrocode}
\newcommand*{\stockbo}  {\stockheight=1414mm \stockwidth=1000mm}
\newcommand*{\stockbi}  {\stockheight=1000mm \stockwidth=707mm}
\newcommand*{\stockbii} {\stockheight=707mm \stockwidth=500mm}
\newcommand*{\stockbiii}{\stockheight=500mm \stockwidth=353mm}
\newcommand*{\stockbiv} {\stockheight=353mm \stockwidth=250mm}
\newcommand*{\stockbv}  {\stockheight=250mm \stockwidth=176mm}
\newcommand*{\stockbvi} {\stockheight=176mm \stockwidth=125mm}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%    It will be useful also to provide macros that set the page sizes.
%
% \begin{macro}{\pagedbill}
% \begin{macro}{\pagestatement}
% \begin{macro}{\pageexecutive}
% \begin{macro}{\pageletter}
% \begin{macro}{\pageold}
% \begin{macro}{\pagelegal}
% \begin{macro}{\pageledger}
% \begin{macro}{\pagebroadsheet}
% \changes{v1.6180339c}{\cs{pageheight} and \cs{pagewidth} should be
%                       \cs{paperheight} and \cs{paperwidth}
%                       (courtesy Wilhelm Muller)}
% US page sizes.
%    \begin{macrocode}
\newcommand*{\pagedbill}     {\paperheight=7in    \paperwidth=3in}
\newcommand*{\pagestatement} {\paperheight=8.5in  \paperwidth=5.5in}
\newcommand*{\pageexecutive} {\paperheight=10.5in \paperwidth=7.25in}
\newcommand*{\pageletter}    {\paperheight=11in   \paperwidth=8.5in}
\newcommand*{\pageold}       {\paperheight=12in   \paperwidth=9in}
\newcommand*{\pagelegal}     {\paperheight=14in   \paperwidth=8.5in}
\newcommand*{\pageledger}    {\paperheight=17in   \paperwidth=11in}
\newcommand*{\pagebroadsheet}{\paperheight=22in   \paperwidth=17in}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% 
% \begin{macro}{\pagepottvo}
% \begin{macro}{\pagefoolscapvo}
% \begin{macro}{\pagecrownvo}
% \begin{macro}{\pagepostvo}
% \begin{macro}{\pagelargecrownvo}
% \begin{macro}{\pagelargepostvo}
% \begin{macro}{\pagesmalldemyvo}
% British traditional page sizes, octavo.
%    \begin{macrocode}
\newcommand*{\pagepottvo}      {\paperheight=6.25in \paperwidth=4in}
\newcommand*{\pagefoolscapvo}  {\paperheight=6.75in \paperwidth=4.25in}
\newcommand*{\pagecrownvo}     {\paperheight=7.5in  \paperwidth=5in}
\newcommand*{\pagepostvo}      {\paperheight=8in    \paperwidth=5in}
\newcommand*{\pagelargecrownvo}{\paperheight=8in    \paperwidth=5.25in}
\newcommand*{\pagelargepostvo} {\paperheight=8.25in \paperwidth=5.25in}
\newcommand*{\pagesmalldemyvo} {\paperheight=8.5in  \paperwidth=5.675in}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\pagedemyvo}
% \begin{macro}{\pagemediumvo}
% \begin{macro}{\pagesmallroyalvo}
% \begin{macro}{\pageroyalvo}
% \begin{macro}{\pagesuperroyalvo}
% \begin{macro}{\pageimperialvo}
%    \begin{macrocode}
\newcommand*{\pagedemyvo}      {\paperheight=8.75in  \paperwidth=5.675in}
\newcommand*{\pagemediumvo}    {\paperheight=9in     \paperwidth=5.75in}
\newcommand*{\pagesmallroyalvo}{\paperheight=9.25in  \paperwidth=6.175in}
\newcommand*{\pageroyalvo}     {\paperheight=10in    \paperwidth=6.25in}
\newcommand*{\pagesuperroyalvo}{\paperheight=10.25in \paperwidth=6.75in}
\newcommand*{\pageimperialvo}  {\paperheight=11in    \paperwidth=7.5in}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% 
% \begin{macro}{\pagemcrownvo}
% \begin{macro}{\pagemlargecrownvo}
% \begin{macro}{\pagemdemyvo}
% \begin{macro}{\pagemsmallroyalvo}
% Metric sizes.
%    \begin{macrocode}
\newcommand*{\pagemcrownvo}      {\paperheight=186mm \paperwidth=123mm}
\newcommand*{\pagemlargecrownvo} {\paperheight=198mm \paperwidth=129mm}
\newcommand*{\pagemdemyvo}       {\paperheight=216mm \paperwidth=138mm}
\newcommand*{\pagemsmallroyalvo} {\paperheight=234mm \paperwidth=156mm}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\pageao}
% \begin{macro}{\pageai}
% \begin{macro}{\pageaii}
% \begin{macro}{\pageaiii}
% \begin{macro}{\pageaiv}
% \begin{macro}{\pageav}
% \begin{macro}{\pageavi}
% The A series, A0 --- A6.
%    \begin{macrocode}
\newcommand*{\pageao}  {\paperheight=1189mm \paperwidth=841mm}
\newcommand*{\pageai}  {\paperheight=841mm \paperwidth=594mm}
\newcommand*{\pageaii} {\paperheight=594mm \paperwidth=420mm}
\newcommand*{\pageaiii}{\paperheight=420mm \paperwidth=297mm}
\newcommand*{\pageaiv} {\paperheight=297mm \paperwidth=210mm}
\newcommand*{\pageav}  {\paperheight=210mm \paperwidth=148mm}
\newcommand*{\pageavi} {\paperheight=148mm \paperwidth=105mm}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\pagebo}
% \begin{macro}{\pagebi}
% \begin{macro}{\pagebii}
% \begin{macro}{\pagebiii}
% \begin{macro}{\pagebiv}
% \begin{macro}{\pagebv}
% \begin{macro}{\pagebvi}
% The B series, B0 --- B6.
%    \begin{macrocode}
\newcommand*{\pagebo}  {\paperheight=1414mm \paperwidth=1000mm}
\newcommand*{\pagebi}  {\paperheight=1000mm \paperwidth=707mm}
\newcommand*{\pagebii} {\paperheight=707mm \paperwidth=500mm}
\newcommand*{\pagebiii}{\paperheight=500mm \paperwidth=353mm}
\newcommand*{\pagebiv} {\paperheight=353mm \paperwidth=250mm}
\newcommand*{\pagebv}  {\paperheight=250mm \paperwidth=176mm}
\newcommand*{\pagebvi} {\paperheight=176mm \paperwidth=125mm}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%    Declare the stock size options.
%
% Metric paper stock sizes.
% \changes{v1.6180339c}{2008/12/26}{Extended class options to include stock
%                       sizes A0, A1, A2, B0, B1 and B2}
%    \begin{macrocode}
\DeclareOption{a0paper}{\stockao}
\DeclareOption{a1paper}{\stockai}
\DeclareOption{a2paper}{\stockaii}
\DeclareOption{a3paper}{\stockaiii}
\DeclareOption{a4paper}{\stockaiv}
\DeclareOption{a5paper}{\stockav}
\DeclareOption{a6paper}{\stockavi}
\DeclareOption{b0paper}{\stockbo}
\DeclareOption{b1paper}{\stockbi}
\DeclareOption{b2paper}{\stockbii}
\DeclareOption{b3paper}{\stockbiii}
\DeclareOption{b4paper}{\stockbiv}
\DeclareOption{b5paper}{\stockbv}
\DeclareOption{b6paper}{\stockbvi}
\DeclareOption{mcrownvopaper}{\stockmcrownvo}
\DeclareOption{mlargecrownvopaper}{\stockmlargecrownvo}
\DeclareOption{mdemyvopaper}{\stockmdemyvo}
\DeclareOption{msmallroyalvopaper}{\stockmsmallroyalvo}

%    \end{macrocode}
% US paper stock sizes.
%    \begin{macrocode}
\DeclareOption{dbillpaper}{\stockdbill}
\DeclareOption{statementpaper}{\stockstatement}
\DeclareOption{executivepaper}{\stockexecutive}
\DeclareOption{letterpaper}{\stockletter}
\DeclareOption{oldpaper}{\stockold}
\DeclareOption{legalpaper}{\stocklegal}
\DeclareOption{ledgerpaper}{\stockledger}
\DeclareOption{broadsheetpaper}{\stockbroadsheet}

%    \end{macrocode}
% British octavo stock paper sizes.
%    \begin{macrocode}
\DeclareOption{pottvopaper}{\stockpottvo}
\DeclareOption{foolscapvopaper}{\stockfoolscapvo}
\DeclareOption{crownvopaper}{\stockcrownvo}
\DeclareOption{postvopaper}{\stockpostvo}
\DeclareOption{largecrownvopaper}{\stocklargecrownvo}
\DeclareOption{largepostvopaper}{\stocklargepostvo}
\DeclareOption{smalldemyvopaper}{\stocksmalldemyvo}
\DeclareOption{demyvopaper}{\stockdemyvo}
\DeclareOption{mediumvopaper}{\stockmediumvo}
\DeclareOption{smallroyalvopaper}{\stocksmallroyalvo}
\DeclareOption{royalvopaper}{\stockroyalvo}
\DeclareOption{superroyalvopaper}{\stocksuperroyalvo}
\DeclareOption{imperialvopaper}{\stockimperialvo}

%    \end{macrocode}
% Ebook.
%    \begin{macrocode}
\DeclareOption{ebook}
   {\setlength\stockheight {9in}%
    \setlength\stockwidth  {6in}}

%    \end{macrocode}
%
%    The \Lopt{landscape} option switches the values of the height and width,
% assuming that the dimensions were originally given for portrait 
% orientation. (At the suggestion of Wilhelm M\"{u}ller made this independent
% of the option sequence).
% \changes{v1.6180339c}{2008/12/26}{`Stabilised' the landscape option and
%                      added a portrait option}.
% \begin{macro}{\ifmemlandscape}
% \begin{macro}{\memlandscapetrue}
% \begin{macro}{\memlandscapefalse}
%    \begin{macrocode}
\newif\ifmemlandscape
  \memlandscapefalse
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%    \begin{macrocode}
\DeclareOption{landscape}{\memlandscapetrue}
\DeclareOption{portrait}{\memlandscapefalse}

%    \end{macrocode}
%
%
% \subsection{Choosing the type size}
%
%    The type size options are handled by defining \cs{@ptsize} to contain
%    the last digit of the size in question and branching on \cs{ifcase}
%    statements. This is done for historical reasons to stay compatible
%    with other packages that use the \cs{@ptsize} variable to select
%    special actions. It makes the declarations of size options less
%    than 10pt or more than 20pt difficult. In this class \texttt{9} is used 
%    for the \Lopt{9pt} option, assuming that the class will never define a 
%    \Lopt{19pt} option. For larger options the full complement of digits 
%    are used.
%
%    In any event, \cs{@memptsize} holds the complete size.
%
%    Option \Lopt{10pt} will be the default.
% \changes{v1.2}{2002/07/07}{Added 17pt option}
% \changes{v1.61803}{2008/01/30}{Added pt options 20 to 60.}
% \changes{v1.61803}{2008/01/30}{Used \cs{@memptsize}}
%    \begin{macrocode}
\renewcommand*{\@ptsize}{0}
\renewcommand*{\@memptsize}{10}
\DeclareOption{9pt}{\renewcommand*{\@ptsize}{9}\renewcommand*{\@memptsize}{9}}
\DeclareOption{10pt}{\renewcommand*{\@ptsize}{0}\renewcommand*{\@memptsize}{10}}
\DeclareOption{11pt}{\renewcommand*{\@ptsize}{1}\renewcommand*{\@memptsize}{11}}
\DeclareOption{12pt}{\renewcommand*{\@ptsize}{2}\renewcommand*{\@memptsize}{12}}
\DeclareOption{14pt}{\renewcommand*{\@ptsize}{4}\renewcommand*{\@memptsize}{14}}
\DeclareOption{17pt}{\renewcommand*{\@ptsize}{7}\renewcommand*{\@memptsize}{17}}
\DeclareOption{20pt}{\renewcommand*{\@ptsize}{20}\renewcommand*{\@memptsize}{20}}
\DeclareOption{25pt}{\renewcommand*{\@ptsize}{25}\renewcommand*{\@memptsize}{25}}
\DeclareOption{30pt}{\renewcommand*{\@ptsize}{30}\renewcommand*{\@memptsize}{30}}
\DeclareOption{36pt}{\renewcommand*{\@ptsize}{36}\renewcommand*{\@memptsize}{36}}
\DeclareOption{48pt}{\renewcommand*{\@ptsize}{48}\renewcommand*{\@memptsize}{48}}
\DeclareOption{60pt}{\renewcommand*{\@ptsize}{60}\renewcommand*{\@memptsize}{60}}

%    \end{macrocode}
%
% \begin{macro}{\if@nyptsizeopt}
% \begin{macro}{\@nyptsizeopttrue}
% \begin{macro}{\@nyptsizeoptfalse}
% \begin{macro}{\anyptfilebase}
% \begin{macro}{\anyptsize}
%   For any point size:
% \changes{v1.61803}{2008/02/29}{Added *pt option}
%    \begin{macrocode}
\newif\if@nyptsizeopt
  \@nyptsizeoptfalse
\providecommand*{\anyptfilebase}{mem}
\providecommand*{\anyptsize}{10}
\DeclareOption{*pt}{\@nyptsizeopttrue}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%  \subsection{Two-side or one-side printing}
%
%    For two-sided printing we use the switch \cs{if@twoside}. In
%    addition we have to set the \cs{if@mparswitch} to get any margin
%    paragraphs into the outside margin. The default is \Lopt{twoside}.
% \begin{macro}{\if@twoside}
% \begin{macro}{\if@mparswitch}
%    \begin{macrocode}
\DeclareOption{twoside}{\@twosidetrue  \@mparswitchtrue}
\DeclareOption{oneside}{\@twosidefalse \@mparswitchfalse}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
%  \subsection{Two column printing}
%
%    Two-column and one-column printing is again realized via a switch
%    which is defined in the kernel. The default is single column printing.
%
% \begin{macro}{\if@twocolumn}
%    \begin{macrocode}
\DeclareOption{onecolumn}{\@twocolumnfalse}
\DeclareOption{twocolumn}{\@twocolumntrue}
%    \end{macrocode}
% \end{macro}
%
%
%  \subsection{The \Lopt{draft} option}
%
%    If the user requests \Lopt{draft} we show any overfull boxes,
%    marginal notes are allowed, and any copyright notices are not
%    printed. For symmetry, we also define a \Lopt{final} option
%    which is the default.
%
%    The user can use the \cs{ifdraftdoc} flag to add additional effects: \\
% \verb?\ifdraftdoc <additional code> \fi?
% \begin{macro}{\ifdraftdoc}
%    \begin{macrocode}
\newif\ifdraftdoc\draftdocfalse
\setlength{\overfullrule}{\z@}
\DeclareOption{final}{\setlength{\overfullrule}{\z@}
                      \draftdocfalse
                      \msdocfalse}
\DeclareOption{draft}{\setlength\overfullrule{5pt}%
                      \draftdoctrue
                      \msdocfalse}
%    \end{macrocode}
% \end{macro}
%
% \subsection{The \Lopt{ms} option}
%
% \begin{macro}{\ifmsdoc}
%    The \Lopt{ms} option makes the document look as though it was produced
% on a typewriter. We use a flag for remembering this. The user may also
% use the flag for specifying \Lopt{ms} effects.
%    \begin{macrocode}
\newif\ifmsdoc
  \msdocfalse
\DeclareOption{ms}{%
  \msdoctrue
  \draftdocfalse
  \setlength\overfullrule{\z@}
}

%    \end{macrocode}
% \end{macro}
%
% \subsection{The \Lopt{showtrims} option}
%
%    The \Lopt{showtrims} option will display crosses at the corners
% of the logical pages showing where the stock should be trimmed.
%
% \begin{macro}{\ifshowtrims}
%    \begin{macrocode}
\newif\ifshowtrims
  \showtrimsfalse
\DeclareOption{showtrims}{\showtrimstrue}

%    \end{macrocode}
% \end{macro}
%
% \subsection{The \Lopt{article} option}
%
%    The \Lopt{article} option typesets as a simulation of the
% \Lpack{article} class.
% \changes{v0.3}{2001/07/09}{Added article option}
% \begin{macro}{\ifartopt}
% \cs{ifartopt} is a flag (TRUE) if the \Lopt{article} option is called.
%    \begin{macrocode}
\newif\ifartopt
  \artoptfalse
\DeclareOption{article}{\artopttrue}

%    \end{macrocode}
% \end{macro}
%
% \subsection{The \Lopt{subfigure} option}
%
% The \Lopt{subfigure} option has been made a no-op since version 1.1
% and finally removed in version 1.61803. It was:
% \changes{v0.3}{2001/07/09}{Added subfigure option}
% \changes{v1.1}{2002/03/10}{Effectively removed subfigure option}
% \changes{v1.61803}{2008/01/30}{Removed subfigure option}
% \begin{verbatim}
% \DeclareOption{subfigure}{%
%   \ClassWarningNoLine{memoir}{The subfigure option is not required}}
% \end{verbatim}
%
% \subsection{The openright, openleft and openany options}
%
%    The \Lopt{openright} option specifies that Chapters must begin on 
% recto pages. The \Lopt{openleft} option specifies that Chapters
% must begin on verso pages and the \Lopt{openany} option lets Chapters 
% start on any page.
% \changes{v1.0}{2001/10/24}{Added the openleft option}
%    \begin{macrocode}
\DeclareOption{openright}{\@openrighttrue}
\DeclareOption{openany}{\@openrightfalse}
\DeclareOption{openleft}{\@openlefttrue}
%    \end{macrocode}
%
% \begin{macro}{\openright}
% \begin{macro}{\openany}
% \begin{macro}{\openleft}
% Commands that can be used to change the option in the middle of the 
% document\footnote{Openleft provided to meet a request by 
% Vladimir G.~Ivanovic (\texttt{vladimir@acm.org}) in September 2001.}.
%    \begin{macrocode}
\newcommand{\openright}{\@openrighttrue\@openleftfalse%
  \gdef\clearforchapter{\cleartorecto}}
\newcommand{\openany}{\@openrightfalse\@openleftfalse%
  \gdef\clearforchapter{\clearpage}}
\newcommand{\openleft}{\@openlefttrue
  \gdef\clearforchapter{\cleartoverso}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \subsection{Equation numbering on the left}
%
% The \Lopt{leqno} option prints equation numbers on the left. This
% is implemented via an external class option file.
%    \begin{macrocode}
\DeclareOption{leqno}{\input{leqno.clo}}
%    \end{macrocode}
%
% \subsection{Flush left math displays}
%
% The \Lopt{fleqn} option redefines the displayed math environments
% so that they are left adjusted with an indent of \cs{mathindent}
% from the current left margin. This
% is implemented via an external class option file.
%    \begin{macrocode}
\DeclareOption{fleqn}{\input{fleqn.clo}}
%    \end{macrocode}
%
% \subsection{Open bibliography}
%
% The \Lopt{openbib} option redefines the \verb?thebibliography? so that each
% block starts on a new line, and succeeding lines in a block are
% indented by \cs{bibindent}.
% \changes{v1.0a}{2001/11/28}{Replaced \cs{AtEndOfPackage} with \cs{AtEndOfClass}}
%    \begin{macrocode}
\DeclareOption{openbib}{%
  \AtEndOfClass{%
    \renewcommand\@openbib@code{%
      \advance\leftmargin\bibindent
      \itemindent -\bibindent
      \listparindent \itemindent
      \parsep \z@
     }%
    \renewcommand\newblock{\par}}}

%    \end{macrocode}
%
% \subsection{Old font commands}
%
% The \Lopt{oldfontcommands} option enables commands like \cs{bf} and friends.
% \changes{v1.0a}{2002/01/29}{Added the oldfontcommands option}
%    \begin{macrocode}
\DeclareOption{oldfontcommands}{\@memoldfonttrue}
%    \end{macrocode}
%
% \subsection{Extra font sizes}
%
% The \Lopt{extrafontsizes} options indicates that extended font sizes (above 25pt)
% are available.
% \changes{v1.61803}{2008/01/30}{Added extrafontsizes option.}
%    \begin{macrocode}
\DeclareOption{extrafontsizes}{\extrafontsizestrue}

%    \end{macrocode}
%
% \subsection{The \Lopt{fullptlayout} option}
% \changes{v3.7g}{2018/03/09}{Added the \Lopt{fullptlayout} option}
% \begin{macro}{\mem@settopoint}
% By default the class will truncate some layout lengths to a whole
% number of points.\footnote{Presumably because it looks better when
% the layout is written to the log.} This might not be desirable, so the
% \Lopt{fullptlayout} class option disables this truncation.
%    \begin{macrocode}
\newcommand\mem@settopoint[1]{\@settopoint{#1}}
\DeclareOption{fullptlayout}{\renewcommand\mem@settopoint{\@gobble}}

%    \end{macrocode}
% \end{macro}
%
%
% \changes{v1.6180339f}{2009/07/12}{Added dead man switch for etex}
% \subsection{ETeX}
% 
% If found we automatically load the eTeX package right after
% executing the class options. Though, some odd \LaTeX\ installations
% may have the eTeX pacakge, but is not based on eTeX (eventhough that
% is what the LaTeX-project have recommended for several years now),
% so we add a dead mans switch to disable the loading.
%
% \medskip\noindent 
% Update 2015: Since the 2015 LaTeX kernel automatically takes care of
% allocating extra registers, the \Lpack{etex} package is no longer
% needed with newer kernels. Therefore automatic loading \Lpack{etex}
% now only happen if the kernel is pre 2015.
% \begin{macro}{\ifmem@noetex}
% \begin{macro}{\mem@noetextrue}
% \begin{macro}{\mem@noetexfalse}
%    \begin{macrocode}
\newif\ifmem@noetex
  \mem@noetexfalse
\DeclareOption{noetex}{\mem@noetextrue}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \section{Executing Options} \label{sec:xopt}
%
%    Here we execute the default options to initialize certain
%    variables. 
%    \begin{macrocode}
\ExecuteOptions{final,letterpaper,10pt,onecolumn,openright,twoside,
                portrait}
%    \end{macrocode}
%
%    The \cs{ProcessOptions} command causes the execution of the code
%    for every option \Lopt{foo}
%    which is declared and for which the user typed
%    the \Lopt{foo} option in his
%    \cs{documentclass} command.  For every option \Lopt{bar} he typed,
%    which is not declared, the option is assumed to be a global option.
%    All options will be passed as document options to any
%    \cs{usepackage} command in the document preamble.
%
% \cs{ProcessOptions*} processes the options in the order they are given
% in the \cs{documentclass} command, instead of the definition order.
% \changes{v1.6180339c}{2008/12/26}{Change \cs{ProcessOptions} to
%                       \cs{ProcessOptions*} and handle landscape/portrait 
%                       option after \cs{ProcessOptions*}}
%    \begin{macrocode}
\ProcessOptions*
  \ifmemlandscape
    \setlength\@tempdima  {\stockheight}
    \setlength\stockheight{\stockwidth}
    \setlength\stockwidth {\@tempdima}
  \fi

%    \end{macrocode}
% Load the eTeX package if found, and if the user has not explicitly
% asked us not to.
%
% \medskip\noindent
% Update 2015: Since 2015 the LaTeX kernel automatically
% allocate extra registers, thus that part of the \Lpack{etex}
% package is no longer needed for newer \LaTeX\ kernels. At the
% request of the LaTeX Team, we now only load \Lpack{etex} on older
% kernels. 
% \changes{v3.7e}{2015/07/08}{Only load \Lpack{etex} on older kernels}
%    \begin{macrocode}
\ifmem@noetex\relax\else
  \ifx\e@alloc\@undefined
    \IfFileExists{etex.sty}{\RequirePackage{etex}}{}
  \fi
\fi
%    \end{macrocode}
% \begin{macro}{\memoirpostopthook}
% A user could define this \emph{before} the \cs{documentclass} command
% to do something at this point. For example, to set up a new stock size: \\
% \verb?\def\memoirpostopthook{\stockheight=44in \stockwidth=34in}?
% \changes{v1.618033}{2008/06/02}{Added \cs{memoirpostopthook}}
%    \begin{macrocode}
\providecommand*{\memoirpostopthook}{}
  \memoirpostopthook

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cleartorecto}
% A repeat of \cs{cleardoublepage}; clears to a recto (odd-numbered) page.
%    \begin{macrocode}
\def\cleartorecto{\clearpage\if@twoside \ifodd\c@page\else
  \hbox{}\thispagestyle{cleared}%
  \newpage\if@twocolumn\hbox{}\newpage\fi\fi\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cleartoverso}
% Clears to a verso (even-numbered) page.
%    \begin{macrocode}
\def\cleartoverso{\clearpage\if@twoside 
  \ifodd\c@page\hbox{}\thispagestyle{cleared}%
  \newpage\if@twocolumn\hbox{}\newpage\fi\fi\fi}

%    \end{macrocode}
% \end{macro}
%

%    Set \cs{clearforchapter} according to the options.
%    \begin{macrocode}
\if@openleft
  \openleft
\else
  \if@openright
    \openright
  \else
    \openany
  \fi
\fi

%    \end{macrocode}
%
% \begin{macro}{\@ivpt}
% \begin{macro}{\@xxxpt}
% \begin{macro}{\@xxxvipt}
% \begin{macro}{\@xlviiipt}
% \begin{macro}{\@lxpt}
% \begin{macro}{\@lxxiipt}
% \begin{macro}{\@lxxxivpt}
% \begin{macro}{\@xcvipt}
% \begin{macro}{\@cviiipt}
% \begin{macro}{\@cxxpt}
% \begin{macro}{\@cxxxiipt}
% \changes{v1.61803}{2008/01/30}{Added a bunch of \cs{@...pt} macros}
%    \begin{macrocode}
\newcommand*{\@ivpt}{4}
\newcommand*{\@xxxpt}{30}
\newcommand*{\@xxxvipt}{36}
\newcommand*{\@xlviiipt}{48}
\newcommand*{\@lxpt}{60}
\newcommand*{\@lxxiipt}{72}
\newcommand*{\@lxxxivpt}{84}
\newcommand*{\@xcvipt}{96}
\newcommand*{\@cviiipt}{108}
\newcommand*{\@cxxpt}{120}
\newcommand*{\@cxxxiipt}{132}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%  Now that all the options have been executed we can load the
%  chosen class option file that contains all size dependent code. The 
% larger sizes are only made available for the \Lopt{extrafontsizes} option.
%
% \begin{macro}{\memfontfamily}
% \begin{macro}{\memfontenc}
% \begin{macro}{\memfontpack}
%  The default font and coding as set by the kernel is \texttt{cmr} and
% \texttt{OT1} respectively, giving Knuth's original Computer Modern Roman
% font at a set of fixed sizes (maximum of 24.88pt). If we are to have
% any size font we have to go to a scaleable font. As the Latin Modern font
% is a scaleable version of Computer Modern, and all modern LaTeX distributions
% include it, I am using this by default. 
%
% By defining these three macros \emph{before}
% the \cs{documentclass} any other font and package can be used.
%    \begin{macrocode}
\providecommand*{\memfontfamily}{lmr}
\providecommand*{\memfontenc}{T1}
\providecommand*{\memfontpack}{lmodern}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% Deal with the `anyptsize' (\Lopt{*pt}) option first. In this case the macros
% \cs{anyptfilebase} and \cs{anyptsize} should have been defined by the
% author \emph{before} the \cs{documentclass} command, and a file \\
% \verb?\anyptfilebase\anyptsize.clo? should exist (if not the file will
% default to \verb?mem10.clo?).
% \changes{v1.61803}{2008/01/30}{Extended the loading of \texttt{.clo} files.}
%    \begin{macrocode}
\if@nyptsizeopt
  \newcommand*{\@nyptclofile}{\anyptfilebase\anyptsize.clo}
  \IfFileExists{\@nyptclofile}{\def\@memptsize{\anyptsize}}{%
    \@memerror{You have used the `*pt' option but \MessageBreak 
               file \@nyptclofile\space can't be found}%
              {I'll use mem10.clo instead}
    \renewcommand*{\@nyptclofile}{mem10.clo}%
    \def\@memptsize{10}%
  }
  \renewcommand*{\@ptsize}{\@memptsize}
  \usefont{\memfontenc}{\memfontfamily}{m}{n}
  \input{\@nyptclofile}
  \usepackage{\memfontpack}\usepackage[\memfontenc]{fontenc}
\else
%    \end{macrocode}
% Now for the fixed pt size options.
%    \begin{macrocode}
  \ifextrafontsizes
    \usefont{\memfontenc}{\memfontfamily}{m}{n}
    \input{mem\@memptsize.clo}
    \usepackage{\memfontpack}\usepackage[\memfontenc]{fontenc}
  \else
    \ifnum\@memptsize > 17\relax
      \@memerror{The `extrafontsizes' option is required to use \MessageBreak
                 the `\@memptsize pt' option}%
                {The 17pt option will be used instead}
      \input{mem17.clo}
    \else
      \ifnum\@ptsize = 9\relax
        \input{mem\@ptsize.clo}
      \else
        \input{mem1\@ptsize.clo}
      \fi
    \fi
  \fi
\fi

%</class>
%    \end{macrocode}
%
%
% \section{Fonts and spaces} \label{sec:docl}
% \label{sec:maincode}
%
%  In this section we deal with most of the aspects that are related
% to font sizes, and spacing that is related to the size of the body font.
%
% \subsection{Fonts}
%
%    \LaTeX\ offers the user commands to change the size of the font,
%    relative to the `main' size. Each relative size changing command
%    \cs{size} executes the command
%    \verb?\@setfontsize\size? \meta{font-size} \meta{baselineskip} where:
%
%    \begin{description}
%    \item[\meta{font-size}] The absolute size of the font to use from
%        now on.
%
%    \item[\meta{baselineskip}] The normal value of \cs{baselineskip}
%        for the size of the font selected. (The actual value will be
%        \cs{baselinestretch} * \meta{baselineskip}.)
%    \end{description}
%
%    A number of commands, defined in the \LaTeX\ kernel, shorten the
%    following  definitions and are used throughout. They are listed in 
% the first part of Table~\ref{tab:sh}. Those in the second part are introduced
% by the class.
%
% \begin{table}
% \centering
% \caption{Shorthand font point size commands}\label{tab:sh}
% \begin{tabular}{ll@{\qquad}ll@{\qquad}ll} \hline
%            &   &            &   & \cs{@ivpt}   & 4 \\
%  \cs{@vpt} & 5 & \cs{@vipt} & 6 & \cs{@viipt} & 7 \\
%  \cs{@viiipt} & 8 & \cs{@ixpt} & 9 & \cs{@xpt} & 10 \\
%  \cs{@xipt} & 10.95 & \cs{@xiipt} & 12 & \cs{@xivpt} & 14.4\\
%  \cs{@xviipt} & 17.28 & \cs{@xxpt} & 20.74 & \cs{@xxvpt} & 24.88\\ \hline
%  \cs{@xxxpt}  & 30    & \cs{@xxxvipt} & 36 & \cs{@xlviiipt} & 48 \\
%  \cs{@lxpt} & 60 & \cs{@lxxiipt} & 72 & \cs{@lxxxivpt} & 84 \\ 
%  \cs{@xcvipt} & 96 & \cs{@cviiipt} & 108 & \cs{@cxxpt} & 120 \\
%  \cs{@cxxxiipt} & 132 \\ \hline
%  \end{tabular}
%  \end{table}
%
% \begin{macro}{\normalsize}
% \begin{macro}{\@normalsize}
%
%    The user level command for the main size is \cs{normalsize}.
%    Internally \LaTeX\ uses \cs{@normalsize} when it refers to the
%    main size. \cs{@normalsize} will be defined to work like
%    \cs{normalsize} if the latter is redefined from its default
%    definition (that just issues an error message). Otherwise, in the standard
% classes \cs{@normalsize} simply selects a 10pt/12pt size, but here
% it selects among the wider range.
%
%    The \cs{normalsize} macro also sets new values for\\
%    \cs{abovedisplayskip}, \cs{abovedisplayshortskip} and
%    \cs{belowdisplayshortskip}.
%
% For the larger sizes I have set \cs{abovedisplayskip} to the font size
% and \cs{belowdisplayshortskip} to 0.5\cs{onelineskip}.
%
%    \begin{macrocode}
%<*9pt|10pt|11pt|12pt|14pt|17pt|20pt|25pt|30pt|36pt|48pt|60pt>
%    \end{macrocode}
% \changes{v0.11 (mem14.clo)}{2001/10/30}{Changed baseline skip from 17.28pt to 17.5pt}
% \changes{v1.61803}{2008/01/30}{Added files mem20.clo through mem60.clo}
% \changes{v1.61803}{2008/01/30}{Changed .clo files to accomodate \cs{extrafontsizes}}
%    \begin{macrocode}
\renewcommand{\normalsize}{%
%<*9pt>
   \@setfontsize\normalsize\@ixpt\@xpt
   \abovedisplayskip 9\p@ \@plus 2\p@ \@minus 4.5\p@
   \abovedisplayshortskip \z@ \@plus 3\p@
   \belowdisplayshortskip 5.5\p@ \@plus 2.5\p@ \@minus 3\p@
%</9pt>
%<*10pt>
   \@setfontsize\normalsize\@xpt\@xiipt
   \abovedisplayskip 10\p@ \@plus2\p@ \@minus5\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6\p@ \@plus3\p@ \@minus3\p@
%</10pt>
%<*11pt>
   \@setfontsize\normalsize\@xipt{13.6}%
   \abovedisplayskip 11\p@ \@plus3\p@ \@minus6\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6.5\p@ \@plus3.5\p@ \@minus3\p@
%</11pt>
%<*12pt>
   \@setfontsize\normalsize\@xiipt{14.5}%
   \abovedisplayskip 12\p@ \@plus3\p@ \@minus7\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6.5\p@ \@plus3.5\p@ \@minus3\p@
%</12pt>
%<*14pt>
   \@setfontsize\normalsize\@xivpt{17.5}%
   \abovedisplayskip 14\p@ \@plus3\p@ \@minus8\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 7\p@ \@plus3.5\p@ \@minus3\p@
%</14pt>
%<*17pt>
   \@setfontsize\normalsize\@xviipt{22}%
   \abovedisplayskip 15\p@ \@plus4\p@ \@minus8\p@
   \abovedisplayshortskip \z@ \@plus4\p@
   \belowdisplayshortskip 8\p@ \@plus4\p@ \@minus3\p@
%</17pt>
%<*20pt>
   \@setfontsize\normalsize\@xxpt{25}%
   \abovedisplayskip 20\p@ \@plus5\p@ \@minus9\p@
   \abovedisplayshortskip \z@ \@plus5\p@
   \belowdisplayshortskip 12.5\p@ \@plus6\p@ \@minus3\p@
%</20pt>
%<*25pt>
   \@setfontsize\normalsize\@xxvpt{30}%
   \abovedisplayskip 25\p@ \@plus6\p@ \@minus10\p@
   \abovedisplayshortskip \z@ \@plus6\p@
   \belowdisplayshortskip 15\p@ \@plus7.5\p@ \@minus4\p@
%</25pt>
%<*30pt>
   \@setfontsize\normalsize\@xxxpt{37}%
   \abovedisplayskip 30\p@ \@plus7\p@ \@minus11\p@
   \abovedisplayshortskip \z@ \@plus7\p@
   \belowdisplayshortskip 18\p@ \@plus9\p@ \@minus4\p@
%</30pt>
%<*36pt>
   \@setfontsize\normalsize\@xxxvipt{45}%
   \abovedisplayskip 36\p@ \@plus8\p@ \@minus12\p@
   \abovedisplayshortskip \z@ \@plus8\p@
   \belowdisplayshortskip 22\p@ \@plus11\p@ \@minus5\p@
%</36pt>
%<*48pt>
   \@setfontsize\normalsize\@xlviiipt{60}%
   \abovedisplayskip 48\p@ \@plus9\p@ \@minus13\p@
   \abovedisplayshortskip \z@ \@plus9\p@
   \belowdisplayshortskip 30\p@ \@plus15\p@ \@minus7\p@
%</48pt>
%<*60pt>
   \@setfontsize\normalsize\@lxpt{72}%
   \abovedisplayskip 60\p@ \@plus10\p@ \@minus14\p@
   \abovedisplayshortskip \z@ \@plus10\p@
   \belowdisplayshortskip 36\p@ \@plus18\p@ \@minus9\p@
%</60pt>
%    \end{macrocode}
%    The \cs{belowdisplayskip} is always equal to the
%    \cs{abovedisplayskip}. The parameters of the first level list are
%    always given by \cs{@listI}.
%    \begin{macrocode}
   \belowdisplayskip \abovedisplayskip
   \let\@listi\@listI}
%    \end{macrocode}
%
%    We initially choose the normalsize font.
%    \begin{macrocode}
\normalsize
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\small}
%    This code is similar to that for \cs{normalsize}.
% (Robert Schlicht\footnote{\texttt{w.m.l@gmx.net}, via email on 2004/03/11.}
% noted that in some cases \% signs were missing after \verb?\@setfontsize?).
%
% For the larger sizes I have set \cs{topsep} to 2/3\cs{onelineskip}
% and \cs{parsep} to 1/2\cs{topsep}.
% \changes{v1.61}{2004/03/12}{Added missing percent signs to some uses of
%                             \cs{@setfontsize}}
%    \begin{macrocode}
\newcommand{\small}{%
%<*9pt>
    \@setfontsize\small\@viiipt{9.5}%
    \abovedisplayskip 6\p@ \@plus 2\p@ \@minus 4\p@
    \abovedisplayshortskip \z@ \@plus 2\p@
    \belowdisplayshortskip 4\p@ \@plus 2\p@ \@minus 2\p@
    \def\@listi{\leftmargin\leftmargini
                \topsep 2\p@ \@plus 2\p@ \@minus 2\p@
                \parsep 1\p@ \@plus\p@ \@minus\p@
                \itemsep \parsep
%%                \itemindent\z@
                }%
%</9pt>
%<*10pt>
   \@setfontsize\small\@ixpt{11}%
   \abovedisplayskip 8.5\p@ \@plus3\p@ \@minus4\p@
   \abovedisplayshortskip \z@ \@plus2\p@
   \belowdisplayshortskip 4\p@ \@plus2\p@ \@minus2\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 4\p@ \@plus2\p@ \@minus2\p@
               \parsep 2\p@ \@plus\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</10pt>
%<*11pt>
   \@setfontsize\small\@xpt\@xiipt
   \abovedisplayskip 10\p@ \@plus2\p@ \@minus5\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6\p@ \@plus3\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 6\p@ \@plus2\p@ \@minus2\p@
               \parsep 3\p@ \@plus2\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</11pt>
%<*12pt>
   \@setfontsize\small\@xipt{13.6}%
   \abovedisplayskip 11\p@ \@plus3\p@ \@minus6\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6.5\p@ \@plus3.5\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 9\p@ \@plus3\p@ \@minus5\p@
               \parsep 4.5\p@ \@plus2\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</12pt>
%<*14pt>
   \@setfontsize\small\@xiipt{14.5}%
   \abovedisplayskip 12\p@ \@plus3\p@ \@minus7\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6.5\p@ \@plus3.5\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 11\p@ \@plus4\p@ \@minus6\p@
               \parsep 6\p@ \@plus3\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</14pt>
%<*17pt>
   \@setfontsize\small\@xivpt{17}%
   \abovedisplayskip 12\p@ \@plus3\p@ \@minus7\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 7\p@ \@plus4\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 11\p@ \@plus4\p@ \@minus6\p@
               \parsep 6\p@ \@plus3\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</17pt>
%<*20pt>
   \@setfontsize\small\@xviipt{22}%
   \abovedisplayskip 17\p@ \@plus4\p@ \@minus8\p@
   \abovedisplayshortskip \z@ \@plus4\p@
   \belowdisplayshortskip 11\p@ \@plus4\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 14\p@ \@plus5\p@ \@minus7\p@
               \parsep 7\p@ \@plus2\p@ \@minus3\p@
               \itemsep \parsep}%
%</20pt>
%<*25pt>
   \@setfontsize\small\@xxpt{25}%
   \abovedisplayskip 20\p@ \@plus5\p@ \@minus9\p@
   \abovedisplayshortskip \z@ \@plus5\p@
   \belowdisplayshortskip 12.5\p@ \@plus6\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 16\p@ \@plus5\p@ \@minus8\p@
               \parsep 8\p@ \@plus3\p@ \@minus4\p@
               \itemsep \parsep}%
%</25pt>
%<*30pt>
   \@setfontsize\small\@xxvpt{30}%
   \abovedisplayskip 25\p@ \@plus6\p@ \@minus10\p@
   \abovedisplayshortskip \z@ \@plus6\p@
   \belowdisplayshortskip 15\p@ \@plus7.5\p@ \@minus4\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 20\p@ \@plus7\p@ \@minus10\p@
               \parsep 10\p@ \@plus4\p@ \@minus5\p@
               \itemsep \parsep}%
%</30pt>
%<*36pt>
   \@setfontsize\small\@xxxpt{37}%
   \abovedisplayskip 30\p@ \@plus7\p@ \@minus11\p@
   \abovedisplayshortskip \z@ \@plus7\p@
   \belowdisplayshortskip 18\p@ \@plus9\p@ \@minus4\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 24\p@ \@plus8\p@ \@minus12\p@
               \parsep 12\p@ \@plus4\p@ \@minus6\p@
               \itemsep \parsep}%
%</36pt>
%<*48pt>
   \@setfontsize\small\@xxxvipt{45}%
   \abovedisplayskip 36\p@ \@plus8\p@ \@minus12\p@
   \abovedisplayshortskip \z@ \@plus8\p@
   \belowdisplayshortskip 22\p@ \@plus11\p@ \@minus5\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 30\p@ \@plus10\p@ \@minus15\p@
               \parsep 15\p@ \@plus5\p@ \@minus7\p@
               \itemsep \parsep}%
%</48pt>
%<*60pt>
   \@setfontsize\small\@xlviiipt{60}%
   \abovedisplayskip 48\p@ \@plus9\p@ \@minus13\p@
   \abovedisplayshortskip \z@ \@plus9\p@
   \belowdisplayshortskip 30\p@ \@plus15\p@ \@minus7\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 40\p@ \@plus13\p@ \@minus20\p@
               \parsep 20\p@ \@plus6\p@ \@minus10\p@
               \itemsep \parsep}%
%</60pt>
   \belowdisplayskip \abovedisplayskip
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\footnotesize}
%    This code is similar to that for \cs{small}.
%    \begin{macrocode}
\newcommand{\footnotesize}{%
%<*9pt>
    \@setfontsize\footnotesize\@viipt{8}%
    \abovedisplayskip 6\p@ \@plus 2\p@ \@minus 4\p@
    \abovedisplayshortskip \z@ \@plus 2\p@
    \belowdisplayshortskip 4\p@ \@plus 2\p@ \@minus 2\p@
    \def\@listi{\leftmargin\leftmargini
                \topsep 2\p@ \@plus 2\p@ \@minus 2\p@
                \parsep 1\p@ \@plus\p@ \@minus\p@
                \itemsep \parsep
%%                \itemindent\z@
               }%
%</9pt>
%<*10pt>
   \@setfontsize\footnotesize\@viiipt{9.5}%
   \abovedisplayskip 6\p@ \@plus2\p@ \@minus4\p@
   \abovedisplayshortskip \z@ \@plus\p@
   \belowdisplayshortskip 3\p@ \@plus\p@ \@minus2\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 3\p@ \@plus\p@ \@minus\p@
               \parsep 2\p@ \@plus\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</10pt>
%<*11pt>
   \@setfontsize\footnotesize\@ixpt{11}%
   \abovedisplayskip 8\p@ \@plus2\p@ \@minus4\p@
   \abovedisplayshortskip \z@ \@plus\p@
   \belowdisplayshortskip 4\p@ \@plus2\p@ \@minus2\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 4\p@ \@plus2\p@ \@minus2\p@
               \parsep 2\p@ \@plus\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</11pt>
%<*12pt>
   \@setfontsize\footnotesize\@xpt\@xiipt
   \abovedisplayskip 10\p@ \@plus2\p@ \@minus5\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6\p@ \@plus3\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 6\p@ \@plus2\p@ \@minus2\p@
               \parsep 3\p@ \@plus2\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</12pt>
%<*14pt>
   \@setfontsize\footnotesize\@xipt{13.6}%
   \abovedisplayskip 11\p@ \@plus3\p@ \@minus6\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6.5\p@ \@plus3.5\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 6.5\p@ \@plus3.5\p@ \@minus3\p@
               \parsep 4\p@ \@plus3\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</14pt>
%<*17pt>
   \@setfontsize\footnotesize\@xiipt{14}%
   \abovedisplayskip 12\p@ \@plus3\p@ \@minus7\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6.5\p@ \@plus3.5\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 6.5\p@ \@plus3.5\p@ \@minus3\p@
               \parsep 4\p@ \@plus3\p@ \@minus\p@
               \itemsep \parsep
%%               \itemindent\z@
              }%
%</17pt>
%<*20pt>
   \@setfontsize\footnotesize\@xivpt{17.5}%
   \abovedisplayskip 14\p@ \@plus3\p@ \@minus8\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 7\p@ \@plus3.5\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 12\p@ \@plus4\p@ \@minus6\p@
               \parsep 6\p@ \@plus2\p@ \@minus3\p@
               \itemsep \parsep}%
%</20pt>
%<*25pt>
   \@setfontsize\footnotesize\@xviipt{22}%
   \abovedisplayskip 17\p@ \@plus4\p@ \@minus8\p@
   \abovedisplayshortskip \z@ \@plus4\p@
   \belowdisplayshortskip 11\p@ \@plus4\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 14\p@ \@plus5\p@ \@minus7\p@
               \parsep 7\p@ \@plus2\p@ \@minus3\p@
               \itemsep \parsep}%
%</25pt>
%<*30pt>
   \@setfontsize\footnotesize\@xxpt{25}%
   \abovedisplayskip 20\p@ \@plus5\p@ \@minus9\p@
   \abovedisplayshortskip \z@ \@plus5\p@
   \belowdisplayshortskip 12.5\p@ \@plus6\p@ \@minus3\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 16\p@ \@plus5\p@ \@minus8\p@
               \parsep 8\p@ \@plus3\p@ \@minus4\p@
               \itemsep \parsep}%
%</30pt>
%<*36pt>
   \@setfontsize\footnotesize\@xxvpt{30}%
   \abovedisplayskip 25\p@ \@plus6\p@ \@minus10\p@
   \abovedisplayshortskip \z@ \@plus6\p@
   \belowdisplayshortskip 15\p@ \@plus7.5\p@ \@minus4\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 20\p@ \@plus7\p@ \@minus10\p@
               \parsep 10\p@ \@plus4\p@ \@minus5\p@
               \itemsep \parsep}%
%</36pt>
%<*48pt>
   \@setfontsize\footnotesize\@xxxpt{37}%
   \abovedisplayskip 30\p@ \@plus7\p@ \@minus11\p@
   \abovedisplayshortskip \z@ \@plus7\p@
   \belowdisplayshortskip 18\p@ \@plus9\p@ \@minus4\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 24\p@ \@plus8\p@ \@minus12\p@
               \parsep 12\p@ \@plus4\p@ \@minus6\p@
               \itemsep \parsep}%
%</48pt>
%<*60pt>
   \@setfontsize\footnotesize\@xxxvipt{45}%
   \abovedisplayskip 36\p@ \@plus8\p@ \@minus12\p@
   \abovedisplayshortskip \z@ \@plus8\p@
   \belowdisplayshortskip 22\p@ \@plus11\p@ \@minus5\p@
   \def\@listi{\leftmargin\leftmargini
               \topsep 30\p@ \@plus10\p@ \@minus15\p@
               \parsep 15\p@ \@plus5\p@ \@minus7\p@
               \itemsep \parsep}%
%</60pt>
   \belowdisplayskip \abovedisplayskip
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\miniscule}
% \begin{macro}{\scriptsize}
% \begin{macro}{\tiny}
% \begin{macro}{\large}
% \begin{macro}{\Large}
% \begin{macro}{\LARGE}
% \begin{macro}{\huge}
% \begin{macro}{\Huge}
% \begin{macro}{\HUGE}
%    These are all much simpler than the previous macros, they just
%    select a new fontsize, but leave the parameters for displays and
%    lists alone. The class provides two additional sizes, \cs{miniscule}
% and \cs{HUGE}, with respect to the usual set. For the larger sizes (e.g.,
% 72pt and above) I have
% made the \cs{baselineskip} approximately 20 precent larger than the pt size.
% \changes{v1.2}{2002/07/27}{Added \cs{miniscule} and \cs{HUGE} font sizes}
% \changes{v1.2}{2002/07/27}{Twiddled some font sizes to get regular steps}
% \changes{v1.2a}{2002/08/27}{Fixed 12pt scriptsize bug}
%    \begin{macrocode}
%<*9pt>
\ifextrafontsizes
  \newcommand*{\miniscule}{\@setfontsize\miniscule\@ivpt{5}}
\else
  \newcommand*{\miniscule}{\@setfontsize\miniscule\@vpt{6}}
\fi
\newcommand*{\tiny}{\@setfontsize\tiny\@vpt{6}}
\newcommand*{\scriptsize}{\@setfontsize\scriptsize\@vipt{7}}
\newcommand*{\large}{\@setfontsize\large\@xpt{12}}
\newcommand*{\Large}{\@setfontsize\Large\@xipt{13.6}}
\newcommand*{\LARGE}{\@setfontsize\LARGE\@xiipt{14.5}}
\newcommand*{\huge}{\@setfontsize\huge\@xivpt{18}}
\newcommand*{\Huge}{\@setfontsize\Huge\@xviipt{22}}
\newcommand*{\HUGE}{\@setfontsize\HUGE\@xxpt{25}}
%</9pt>
%<*10pt>
\newcommand*{\miniscule}{\@setfontsize\miniscule\@vpt{6}}
\newcommand*{\tiny}{\@setfontsize\tiny\@vipt{7}}
\newcommand*{\scriptsize}{\@setfontsize\scriptsize\@viipt{8}}
\newcommand*{\large}{\@setfontsize\large\@xipt{13.6}}
\newcommand*{\Large}{\@setfontsize\Large\@xiipt{14.5}}
\newcommand*{\LARGE}{\@setfontsize\LARGE\@xivpt{18}}
\newcommand*{\huge}{\@setfontsize\huge\@xviipt{22}}
\newcommand*{\Huge}{\@setfontsize\Huge\@xxpt{25}}
\newcommand*{\HUGE}{\@setfontsize\HUGE\@xxvpt{30}}
%</10pt>
%<*11pt>
\newcommand*{\miniscule}{\@setfontsize\miniscule\@vipt{7}}
\newcommand*{\tiny}{\@setfontsize\tiny\@viipt{8}}
\newcommand*{\scriptsize}{\@setfontsize\scriptsize\@viiipt{9.5}}
\newcommand*{\large}{\@setfontsize\large\@xiipt{14.5}}
\newcommand*{\Large}{\@setfontsize\Large\@xivpt{18}}
\newcommand*{\LARGE}{\@setfontsize\LARGE\@xviipt{22}}
\newcommand*{\huge}{\@setfontsize\huge\@xxpt{25}}
\newcommand*{\Huge}{\@setfontsize\Huge\@xxvpt{30}}
\ifextrafontsizes
  \newcommand*{\HUGE}{\@setfontsize\HUGE\@xxxpt{37}}
\else
  \let\HUGE=\Huge
\fi
%</11pt>
%<*12pt>
\newcommand*{\miniscule}{\@setfontsize\miniscule\@viipt{8}}
\newcommand*{\tiny}{\@setfontsize\tiny\@viiipt{9.5}}
\newcommand*{\scriptsize}{\@setfontsize\scriptsize\@ixpt\@xpt}
\newcommand*{\large}{\@setfontsize\large\@xivpt{18}}
\newcommand*{\Large}{\@setfontsize\Large\@xviipt{22}}
\newcommand*{\LARGE}{\@setfontsize\LARGE\@xxpt{25}}
\newcommand*{\huge}{\@setfontsize\huge\@xxvpt{30}}
\ifextrafontsizes
  \newcommand*{\Huge}{\@setfontsize\Huge\@xxxpt{37}}
  \newcommand*{\HUGE}{\@setfontsize\HUGE\@xxxvipt{45}}
\else
  \let\Huge=\huge
  \let\HUGE=\huge
\fi
%</12pt>
%<*14pt>
\newcommand*{\miniscule}{\@setfontsize\miniscule\@viiipt{9.5}}
\newcommand*{\tiny}{\@setfontsize\tiny\@ixpt{10}}
\newcommand*{\scriptsize}{\@setfontsize\scriptsize\@xpt{12}}
\newcommand*{\large}{\@setfontsize\large\@xviipt{22}}
\newcommand*{\Large}{\@setfontsize\Large\@xxpt{25}}
\newcommand*{\LARGE}{\@setfontsize\LARGE\@xxvpt{30}}
\ifextrafontsizes
  \newcommand*{\huge}{\@setfontsize\Huge\@xxxpt{37}}
  \newcommand*{\Huge}{\@setfontsize\Huge\@xxxvipt{45}}
  \newcommand*{\HUGE}{\@setfontsize\HUGE\@xlviiipt{60}}
\else
  \let\huge=\LARGE
  \let\Huge=\LARGE
  \let\HUGE=\LARGE
\fi
%</14pt>
%<*17pt>
\newcommand*{\miniscule}{\@setfontsize\miniscule\@ixpt{10}}
\newcommand*{\tiny}{\@setfontsize\tiny\@xpt{12}}
\newcommand*{\scriptsize}{\@setfontsize\scriptsize\@xipt{13.6}}
\newcommand*{\large}{\@setfontsize\large\@xxpt{25}}
\newcommand*{\Large}{\@setfontsize\Large\@xxvpt{30}}
\ifextrafontsizes
  \newcommand*{\LARGE}{\@setfontsize\LARGE\@xxxpt{37}}
  \newcommand*{\huge}{\@setfontsize\huge\@xxxvipt{45}}
  \newcommand*{\Huge}{\@setfontsize\Huge\@xlviiipt{60}}
  \newcommand*{\HUGE}{\@setfontsize\HUGE\@lxpt{72}}
\else
  \let\LARGE=\Large
  \let\huge=\Large
  \let\Huge=\Large
  \let\HUGE=\Large
\fi
%</17pt>
%<*20pt>
\newcommand*{\miniscule}{\@setfontsize\miniscule\@xpt{12}}
\newcommand*{\tiny}{\@setfontsize\tiny\@xipt{13.6}}
\newcommand*{\scriptsize}{\@setfontsize\scriptsize\@xiipt{14.5}}
\newcommand*{\large}{\@setfontsize\large\@xxvpt{30}}
\newcommand*{\Large}{\@setfontsize\Large\@xxxpt{37}}
\newcommand*{\LARGE}{\@setfontsize\LARGE\@xxxvipt{45}}
\newcommand*{\huge}{\@setfontsize\huge\@xlviiipt{60}}
\newcommand*{\Huge}{\@setfontsize\Huge\@lxpt{72}}
\newcommand*{\HUGE}{\@setfontsize\HUGE\@lxxiipt{86}}
%</20pt>
%<*25pt>
\newcommand*{\miniscule}{\@setfontsize\miniscule\@xipt{13.6}}
\newcommand*{\tiny}{\@setfontsize\tiny\@xiipt{14.5}}
\newcommand*{\scriptsize}{\@setfontsize\scriptsize\@xivpt{17.5}}
\newcommand*{\large}{\@setfontsize\large\@xxxpt{37}}
\newcommand*{\Large}{\@setfontsize\Large\@xxxvipt{45}}
\newcommand*{\LARGE}{\@setfontsize\LARGE\@xlviiipt{60}}
\newcommand*{\huge}{\@setfontsize\huge\@lxpt{72}}
\newcommand*{\Huge}{\@setfontsize\Huge\@lxxiipt{86}}
\newcommand*{\HUGE}{\@setfontsize\HUGE\@lxxxivpt{100}}
%</25pt>
%<*30pt>
\newcommand*{\miniscule}{\@setfontsize\miniscule\@xiipt{14.5}}
\newcommand*{\tiny}{\@setfontsize\tiny\@xivpt{17.5}}
\newcommand*{\scriptsize}{\@setfontsize\scriptsize\@xviipt{22}}
\newcommand*{\large}{\@setfontsize\large\@xxxvipt{45}}
\newcommand*{\Large}{\@setfontsize\Large\@xlviiipt{60}}
\newcommand*{\LARGE}{\@setfontsize\LARGE\@lxpt{72}}
\newcommand*{\huge}{\@setfontsize\huge\@lxxiipt{86}}
\newcommand*{\Huge}{\@setfontsize\Huge\@lxxxivpt{100}}
\newcommand*{\HUGE}{\@setfontsize\HUGE\@xcvipt{116}}
%</30pt>
%<*36pt>
\newcommand*{\miniscule}{\@setfontsize\miniscule\@xivpt{17.5}}
\newcommand*{\tiny}{\@setfontsize\tiny\@xviipt{22}}
\newcommand*{\scriptsize}{\@setfontsize\scriptsize\@xxpt{25}}
\newcommand*{\large}{\@setfontsize\large\@xlviiipt{60}}
\newcommand*{\Large}{\@setfontsize\Large\@lxpt{72}}
\newcommand*{\LARGE}{\@setfontsize\LARGE\@lxxiipt{86}}
\newcommand*{\huge}{\@setfontsize\huge\@lxxxivpt{100}}
\newcommand*{\Huge}{\@setfontsize\Huge\@xcvipt{116}}
\newcommand*{\HUGE}{\@setfontsize\HUGE\@cviiipt{132}}
%</36pt>
%<*48pt>
\newcommand*{\miniscule}{\@setfontsize\miniscule\@xviipt{22}}
\newcommand*{\tiny}{\@setfontsize\tiny\@xxpt{25}}
\newcommand*{\scriptsize}{\@setfontsize\scriptsize\@xxvpt{30}}
\newcommand*{\large}{\@setfontsize\large\@lxpt{72}}
\newcommand*{\Large}{\@setfontsize\Large\@lxxiipt{86}}
\newcommand*{\LARGE}{\@setfontsize\LARGE\@lxxxivpt{100}}
\newcommand*{\huge}{\@setfontsize\huge\@xcvipt{116}}
\newcommand*{\Huge}{\@setfontsize\Huge\@cviiipt{132}}
\newcommand*{\HUGE}{\@setfontsize\HUGE\@cxxpt{144}}
%</48pt>
%<*60pt>
\newcommand*{\miniscule}{\@setfontsize\miniscule\@xxpt{25}}
\newcommand*{\tiny}{\@setfontsize\tiny\@xxvpt{30}}
\newcommand*{\scriptsize}{\@setfontsize\scriptsize\@xxxpt{37}}
\newcommand*{\large}{\@setfontsize\large\@lxxiipt{86}}
\newcommand*{\Large}{\@setfontsize\Large\@lxxxivpt{100}}
\newcommand*{\LARGE}{\@setfontsize\LARGE\@xcvipt{116}}
\newcommand*{\huge}{\@setfontsize\huge\@cviiipt{132}}
\newcommand*{\Huge}{\@setfontsize\Huge\@cxxpt{144}}
\newcommand*{\HUGE}{\@setfontsize\HUGE\@cxxxiipt{162}}
%</60pt>
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%    \begin{macrocode}
%</9pt|10pt|11pt|12pt|14pt|17pt|20pt|25pt|30pt|36pt|48pt|60pt>
%<*class>
%    \end{macrocode}
%
% \begin{macro}{\captionsize}
%  This internal command holds the font size for captions. 
%    \begin{macrocode}
\newcommand{\captionsize}{\normalsize}
%    \end{macrocode}
% \end{macro}
%
% \subsection{Paragraphing}
%
% \begin{macro}{\lineskip}
% \begin{macro}{\normallineskip}
%    These parameters control \TeX's behaviour when two lines tend to
%    come too close together.
%    \begin{macrocode}
\setlength\lineskip{1\p@}
\setlength\normallineskip{1\p@}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\baselinestretch}
%    This is used as a multiplier for \cs{baselineskip}. The default is
%    to \emph{not} stretch the baselines.
%    \begin{macrocode}
\renewcommand{\baselinestretch}{}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\parskip}
% \begin{macro}{\onelineskip}
%
% \cs{parskip} is additional vertical space between paragraphs;  default
% is zero.
%
%
%    \cs{onelineskip} is the default space between baselines.
% \changes{v0.11 (mem14.clo)}{2001/10/30}{Changed \cs{onelineskip} from 17.28pt to 17.5pt}
%    \begin{macrocode}
\setlength\parskip{0\p@ \@plus \p@}
%</class>
%<*9pt|10pt|11pt|12pt|14pt|17pt|20pt|25pt|30pt|36pt|48pt|60pt>
%<9pt>\setlength{\onelineskip}{\@xpt\p@}
%<10pt>\setlength{\onelineskip}{\@xiipt\p@}
%<11pt>\setlength{\onelineskip}{13.6\p@}
%<12pt>\setlength{\onelineskip}{14.5\p@}
%<14pt>\setlength{\onelineskip}{17.5\p@}
%<17pt>\setlength{\onelineskip}{22\p@}
%<20pt>\setlength{\onelineskip}{25\p@}
%<25pt>\setlength{\onelineskip}{30\p@}
%<30pt>\setlength{\onelineskip}{37\p@}
%<36pt>\setlength{\onelineskip}{45\p@}
%<48pt>\setlength{\onelineskip}{60\p@}
%<60pt>\setlength{\onelineskip}{72\p@}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\parindent}
%    \cs{parskip} gives extra vertical space between paragraphs and
%    \cs{parindent} is the width of the paragraph indentation. 
%    \begin{macrocode}
\if@twocolumn
  \setlength\parindent{1em}
\else
%<9pt>  \setlength\parindent{12\p@}
%<10pt>  \setlength\parindent{15\p@}
%<11pt>  \setlength\parindent{17\p@}
%<12pt>  \setlength\parindent{1.5em}
%<14pt>  \setlength\parindent{1.5em}
%<17pt>  \setlength\parindent{1.5em}
%<20pt>  \setlength\parindent{1.5em}
%<25pt>  \setlength\parindent{1.5em}
%<30pt>  \setlength\parindent{1.5em}
%<36pt>  \setlength\parindent{1.5em}
%<48pt>  \setlength\parindent{1.5em}
%<60pt>  \setlength\parindent{1.5em}
\fi
%</9pt|10pt|11pt|12pt|14pt|17pt|20pt|25pt|30pt|36pt|48pt|60pt>
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\smallskipamount}
% \begin{macro}{\medskipamount}
% \begin{macro}{\bigskipamount}
% The values for these three parameters are set in the LaTeX kernel.
% Historically they have been size invariant, but I have changed them for
% the larger sizes (\cs{smallskipamount} is 1/4 the fontsize, and the others
% each double up on the next lower).
% \changes{v1.61803}{2008/01/30}{(small/med/big)skips not invraiant for larger font sizes.}
% \changes{v1.61803}{2008/01/30}{Changed (small/med/big)skips for 17pt}
%    \begin{macrocode}
%<*9pt|10pt|11pt|12pt|14pt>
\setlength\smallskipamount{3\p@ \@plus 1\p@ \@minus 1\p@}
\setlength\medskipamount{6\p@ \@plus 2\p@ \@minus 2\p@}
\setlength\bigskipamount{12\p@ \@plus 4\p@ \@minus 4\p@}
%</9pt|10pt|11pt|12pt|14pt>
%<*17pt|20pt|25pt|30pt|36pt|48pt|60pt>
%<*17pt>
\setlength\smallskipamount{4\p@ \@plus1\p@ \@minus1\p@}
\setlength\medskipamount{8\p@ \@plus2\p@ \@minus2\p@}
\setlength\bigskipamount{17\p@ \@plus4\p@ \@minus4\p@}
%</17pt>
%<*20pt>
\setlength\smallskipamount{5\p@ \@plus1\p@ \@minus1\p@}
\setlength\medskipamount{10\p@ \@plus2\p@ \@minus2\p@}
\setlength\bigskipamount{20\p@ \@plus4\p@ \@minus4\p@}
%</20pt>
%<*25pt>
\setlength\smallskipamount{6\p@ \@plus1\p@ \@minus1\p@}
\setlength\medskipamount{12\p@ \@plus2\p@ \@minus2\p@}
\setlength\bigskipamount{24\p@ \@plus4\p@ \@minus4\p@}
%</25pt>
%<*30pt>
\setlength\smallskipamount{5\p@ \@plus1\p@ \@minus1\p@}
\setlength\medskipamount{10\p@ \@plus2\p@ \@minus2\p@}
\setlength\bigskipamount{20\p@ \@plus4\p@ \@minus4\p@}
%</30pt>
%<*36pt>
\setlength\smallskipamount{9\p@ \@plus2\p@ \@minus2\p@}
\setlength\medskipamount{18\p@ \@plus4\p@ \@minus4\p@}
\setlength\bigskipamount{36\p@ \@plus8\p@ \@minus8\p@}
%</36pt>
%<*48pt>
\setlength\smallskipamount{12\p@ \@plus3\p@ \@minus3\p@}
\setlength\medskipamount{24\p@ \@plus6\p@ \@minus6\p@}
\setlength\bigskipamount{48\p@ \@plus12\p@ \@minus12\p@}
%</48pt>
%<*60pt>
\setlength\smallskipamount{15\p@ \@plus4\p@ \@minus4\p@}
\setlength\medskipamount{30\p@ \@plus8\p@ \@minus8\p@}
\setlength\bigskipamount{60\p@ \@plus16\p@ \@minus16\p@}
%</60pt>
%</17pt|20pt|25pt|30pt|36pt|48pt|60pt>
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@lowpenalty}
% \begin{macro}{\@medpenalty}
% \begin{macro}{\@highpenalty}%
%    The commands \cs{nopagebreak} and \cs{nolinebreak} put in penalties
%    to discourage these breaks at the point they are put in.
%    They use \cs{@lowpenalty}, \cs{@medpenalty} or \cs{@highpenalty},
%    dependent on their argument.
%    \begin{macrocode}
%<*class>
\@lowpenalty   51
\@medpenalty  151
\@highpenalty 301
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\clubpenalty}
% \begin{macro}{\widowpenalty}
%    These penalties are used to discourage club and widow lines.
%    The default values are 150 each, but we want stronger discouragement.
%    \begin{macrocode}
\clubpenalty  1000
\widowpenalty 1000
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\displaywidowpenalty}
% \begin{macro}{\predisplaypenalty}
% \begin{macro}{\postdisplaypenalty}
%    Discourage, but do not prevent, widows in front of a math display
%    and forbid breaking directly in front of a display. Allow break
%    after a display without a penalty. The default values are
%    used, therefore we only show them here.
%    \begin{macrocode}
% \displaywidowpenalty 50
% \predisplaypenalty   10000
% \postdisplaypenalty  0
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\interlinepenalty}
%    Allow the breaking of a page in the middle of a paragraph.
%    \begin{macrocode}
% \interlinepenalty 0
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\brokenpenalty}
%    We allow the breaking of a page after a hyphenated line.
%    \begin{macrocode}
% \brokenpenalty 100
%    \end{macrocode}
% \end{macro}
%
% 
%
%
% \subsection{Vertical spacing}
%
% \begin{macro}{\headheight}
% \begin{macro}{\headsep}
% \begin{macro}{\topskip}
% \begin{macro}{\footskip}
%    The \cs{headheight} is the height of the box that will contain the
%    running head. In this class it is point size dependent --- 
% \cs{onelineskip} (normally it is a constant 12pt). 
%
% The \cs{headsep} is the distance between the bottom
%    of the running head and the top of the text. For the larger sizes
% this is 1.8 times the fontsize.
%
% The \cs{topskip} is the \cs{baselineskip} for the first line on a page; 
%    \LaTeX's output routine will not work properly if it has the
%    value 0pt, so do not do that! For the lareger sizes this is the font size.
%
%    The distance from the baseline of the box which contains the
%    running footer to the baseline of last line of text is controlled
%    by the \cs{footskip}. For the larger sizes this is 2.5 times the
% font size.
% \changes{v0.11 (mem14.clo)}{2001/10/30}{Changed \cs{headheight} from 16pt to 17.5pt}
% \changes{v0.11 (mem11.clo)}{2002/03/10}{Changed \cs{headheight} from 13pt to 13.6pt}
% \changes{v0.4b (mem12.clo)}{2010/10/19}{Changed \cs{headheight} from 14pt to 14.5pt}
%    \begin{macrocode}
%</class>
%<*9pt|10pt|11pt|12pt|14pt|17pt|20pt|25pt|30pt|36pt|48pt|60pt>
%<*9pt>
\setlength\headheight{11\p@}
\setlength\headsep{.225in}
\setlength\topskip{9\p@}
\setlength\footskip{.33in}
%</9pt>
%<*10pt>
\setlength\headheight{12\p@}
\setlength\headsep{.25in}
\setlength\topskip{10\p@}
\setlength\footskip{.35in}
%</10pt>
%<*11pt>
\setlength\headheight{13.6\p@}
\setlength\headsep{.275in}
\setlength\topskip{11\p@}
\setlength\footskip{.38in}
%</11pt>
%<*12pt>
\setlength\headheight{14.5\p@}
\setlength\headsep{.275in}
\setlength\topskip{12\p@}
\setlength\footskip{30\p@}
%</12pt>
%<*14pt>
\setlength\headheight{17.5\p@}
\setlength\headsep{.30in}
\setlength\topskip{14.4\p@}
\setlength\footskip{.4in}
%</14pt>
%<*17pt>
\setlength\headheight{22\p@}
\setlength\headsep{.30in}
\setlength\topskip{14.4\p@}
\setlength\footskip{.4in}
%</17pt>
%<*20pt>
\setlength\headheight{25\p@}
\setlength\headsep{36\p@}
\setlength\topskip{20\p@}
\setlength\footskip{50\p@}
%</20pt>
%<*25pt>
\setlength\headheight{30\p@}
\setlength\headsep{45\p@}
\setlength\topskip{25\p@}
\setlength\footskip{62\p@}
%</25pt>
%<*30pt>
\setlength\headheight{37\p@}
\setlength\headsep{54\p@}
\setlength\topskip{30\p@}
\setlength\footskip{75\p@}
%</30pt>
%<*36pt>
\setlength\headheight{45\p@}
\setlength\headsep{65\p@}
\setlength\topskip{36\p@}
\setlength\footskip{90\p@}
%</36pt>
%<*48pt>
\setlength\headheight{60\p@}
\setlength\headsep{86\p@}
\setlength\topskip{48\p@}
\setlength\footskip{120\p@}
%</48pt>
%<*60pt>
\setlength\headheight{72\p@}
\setlength\headsep{108\p@}
\setlength\topskip{60\p@}
\setlength\footskip{150\p@}
%</60pt>
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\maxdepth}
% \begin{macro}{\@maxdepth}
%    The \TeX\ primitive register \cs{maxdepth} has a function that is
%    similar to that of \cs{topskip}. The register \cs{@maxdepth} should
%    always contain a copy of \cs{maxdepth}. In both plain \TeX\ and
%    \LaTeX~2.09 \cs{maxdepth} had a fixed value of \texttt{4pt}; in
%    native \LaTeX 2e mode we let the value depend on the typesize. We
%    set it so that \cs{maxdepth} $+$ \cs{topskip} $=$ typesize $\times
%    1.5$. As it happens, in these classes \cs{topskip} is equal to the
%    typesize, therefor we set \cs{maxdepth} to half the value of
%    \cs{topskip}.
%    \begin{macrocode}
\setlength\maxdepth{.5\topskip}
\setlength\@maxdepth\maxdepth
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
%
% \subsection{Footnotes}
%
% \begin{macro}{\footnotesep}
%    \cs{footnotesep} is the height of the strut placed at the beginning
%    of every footnote. It equals the height of a normal \cs{footnotesize}
% strut, so no extra space appears between footnotes.
% \changes{v1.61803}{2007/01/30}{Changed nearly all \cs{footnotesep}}
%    \begin{macrocode}
%<9pt>\setlength\footnotesep{5.6\p@}
%<10pt>\setlength\footnotesep{6.65\p@}
%<11pt>\setlength\footnotesep{7.7\p@}
%<12pt>\setlength\footnotesep{8.4\p@}
%<14pt>\setlength\footnotesep{9.5\p@} 
%<17pt>\setlength\footnotesep{10.15\p@}
%<20pt>\setlength\footnotesep{12.6\p@}
%<25pt>\setlength\footnotesep{15.4\p@}
%<30pt>\setlength\footnotesep{17.5\p@}
%<36pt>\setlength\footnotesep{21\p@}
%<48pt>\setlength\footnotesep{25.9\p@}
%<60pt>\setlength\footnotesep{31.5\p@}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\footins}
%    \verb?\skip\footins? is the space between the last line of the main
%    text and the top of the first footnote.
%    \begin{macrocode}
%<9pt>\setlength{\skip\footins}{8\p@ \@plus 2\p@ \@minus 2\p@}
%<10pt>\setlength{\skip\footins}{9\p@ \@plus 4\p@ \@minus 2\p@}
%<11pt>\setlength{\skip\footins}{10\p@ \@plus 4\p@ \@minus 2\p@}
%<12pt>\setlength{\skip\footins}{10.8\p@ \@plus 4\p@ \@minus 2\p@}
%<14pt>\setlength{\skip\footins}{13\p@ \@plus 4\p@ \@minus 2\p@}
%<17pt>\setlength{\skip\footins}{16\p@ \@plus 5\p@ \@minus 3\p@}
%<20pt>\setlength{\skip\footins}{19\p@ \@plus 7\p@ \@minus 3\p@}
%<25pt>\setlength{\skip\footins}{24\p@ \@plus 8\p@ \@minus 4\p@}
%<30pt>\setlength{\skip\footins}{29\p@ \@plus 10\p@ \@minus 5\p@}
%<36pt>\setlength{\skip\footins}{35\p@ \@plus 12\p@ \@minus 6\p@}
%<48pt>\setlength{\skip\footins}{47\p@ \@plus 16\p@ \@minus 8\p@}
%<60pt>\setlength{\skip\footins}{59\p@ \@plus 20\p@ \@minus 10\p@}
%    \end{macrocode}
% \end{macro}
%
% \subsection{Floats}
%
% \paragraph{Floats on a text page}
%
% \begin{macro}{\floatsep}
% \begin{macro}{\textfloatsep}
% \begin{macro}{\intextsep}
%    When a floating object is placed on a page with text, these
%    parameters control the separation between the float and the other
%    objects on the page. These parameters are used for both
%    one-column mode and single-column floats in two-column mode.
%
%    \cs{floatsep} is the space between adjacent floats that are moved
%    to the top or bottom of the text page. For the larger sizes this is 
% \cs{bigskip}.
%
%    \cs{textfloatsep} is the space between the main text and floats
%    at the top or bottom of the page. For the larger sizes this is
% 1.45\cs{onelineskip}.
%
%    \cs{intextsep} is the space between in-text floats and the text.
%    \begin{macrocode}
%<*9pt>
\setlength\floatsep    {12\p@ \@plus 2\p@ \@minus 2\p@}
\setlength\textfloatsep{20\p@ \@plus 2\p@ \@minus 4\p@}
\setlength\intextsep   {12\p@ \@plus 2\p@ \@minus 2\p@}
%</9pt>
%<*10pt>
\setlength\floatsep    {12\p@ \@plus 2\p@ \@minus 2\p@}
\setlength\textfloatsep{20\p@ \@plus 2\p@ \@minus 4\p@}
\setlength\intextsep   {12\p@ \@plus 2\p@ \@minus 2\p@}
%</10pt>
%<*11pt>
\setlength\floatsep    {12\p@ \@plus 2\p@ \@minus 2\p@}
\setlength\textfloatsep{20\p@ \@plus 2\p@ \@minus 4\p@}
\setlength\intextsep   {12\p@ \@plus 2\p@ \@minus 2\p@}
%</11pt>
%<*12pt>
\setlength\floatsep    {12\p@ \@plus 2\p@ \@minus 2\p@}
\setlength\textfloatsep{20\p@ \@plus 2\p@ \@minus 4\p@}
\setlength\intextsep   {14\p@ \@plus 4\p@ \@minus 4\p@}
%</12pt>
%<*14pt>
\setlength\floatsep    {14\p@ \@plus 4\p@ \@minus 4\p@}
\setlength\textfloatsep{20\p@ \@plus 4\p@ \@minus 4\p@}
\setlength\intextsep   {14\p@ \@plus 4\p@ \@minus 4\p@}
%</14pt>
%<*17pt>
\setlength\floatsep    {15\p@ \@plus 4\p@ \@minus 4\p@}
\setlength\textfloatsep{25\p@ \@plus 4\p@ \@minus 5\p@}
\intextsep \floatsep
%</17pt>
%<*20pt>
\setlength\floatsep    {20\p@ \@plus 4\p@ \@minus 4\p@}
\setlength\textfloatsep{36\p@ \@plus 4\p@ \@minus 8\p@}
\intextsep \floatsep
%</20pt>
%<*25pt>
\setlength\floatsep    {24\p@ \@plus 4\p@ \@minus 4\p@}
\setlength\textfloatsep{43\p@ \@plus 4\p@ \@minus 8\p@}
\intextsep \floatsep
%</25pt>
%<*30pt>
\setlength\floatsep    {30\p@ \@plus 6\p@ \@minus 6\p@}
\setlength\textfloatsep{54\p@ \@plus 6\p@ \@minus 12\p@}
\intextsep \floatsep
%</30pt>
%<*36pt>
\setlength\floatsep    {36\p@ \@plus 8\p@ \@minus 8\p@}
\setlength\textfloatsep{65\p@ \@plus 8\p@ \@minus 16\p@}
\intextsep \floatsep
%</36pt>
%<*48pt>
\setlength\floatsep    {48\p@ \@plus 12\p@ \@minus 12\p@}
\setlength\textfloatsep{87\p@ \@plus 12\p@ \@minus 24\p@}
\intextsep \floatsep
%</48pt>
%<*60pt>
\setlength\floatsep    {60\p@ \@plus 16\p@ \@minus 16\p@}
\setlength\textfloatsep{104\p@ \@plus 16\p@ \@minus 32\p@}
\intextsep \floatsep
%</60pt>
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\dblfloatsep}
% \begin{macro}{\dbltextfloatsep}
%    When floating objects that span the whole \cs{textwidth} are placed
%    on a text page and \LaTeX{} is in twocolumn mode the separation
%    between the float and the text is controlled by \cs{dblfloatsep}
%    and \cs{dbltextfloatsep}.
%
%    \cs{dblfloatsep} is the space between adjacent floats that are moved
%    to the top or bottom of the text page.
%
%    \cs{dbltextfloatsep} is the space between the main text and floats
%    at the top or bottom of the page.
%
%    \begin{macrocode}
%<*9pt>
\setlength\dblfloatsep    {12\p@ \@plus 2\p@ \@minus 2\p@}
\setlength\dbltextfloatsep{20\p@ \@plus 2\p@ \@minus 4\p@}
%</9pt>
%<*10pt>
\setlength\dblfloatsep    {12\p@ \@plus 2\p@ \@minus 2\p@}
\setlength\dbltextfloatsep{20\p@ \@plus 2\p@ \@minus 4\p@}
%</10pt>
%<*11pt>
\setlength\dblfloatsep    {12\p@ \@plus 2\p@ \@minus 2\p@}
\setlength\dbltextfloatsep{20\p@ \@plus 2\p@ \@minus 4\p@}
%</11pt>
%<*12pt>
\setlength\dblfloatsep    {14\p@ \@plus 2\p@ \@minus 4\p@}
\setlength\dbltextfloatsep{20\p@ \@plus 2\p@ \@minus 4\p@}
%</12pt>
%<*14pt>
\setlength\dblfloatsep    {14\p@ \@plus 2\p@ \@minus 4\p@}
\setlength\dbltextfloatsep{20\p@ \@plus 2\p@ \@minus 4\p@}
%</14pt>
%<*17pt>
\setlength\dblfloatsep    {15\p@ \@plus 4\p@ \@minus 4\p@}
\setlength\dbltextfloatsep{25\p@ \@plus 5\p@ \@minus 5\p@}
%</17pt>
%<*20pt>
\dblfloatsep \floatsep
\dbltextfloatsep \textfloatsep
%</20pt>
%<*25pt>
\dblfloatsep \floatsep
\dbltextfloatsep \textfloatsep
%</25pt>
%<*30pt>
\dblfloatsep \floatsep
\dbltextfloatsep \textfloatsep
%</30pt>
%<*36pt>
\dblfloatsep \floatsep
\dbltextfloatsep \textfloatsep
%</36pt>
%<*48pt>
\dblfloatsep \floatsep
\dbltextfloatsep \textfloatsep
%</48pt>
%<*60pt>
\dblfloatsep \floatsep
\dbltextfloatsep \textfloatsep
%</60pt>
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \paragraph{Floats on their own page or column}
%
% \begin{macro}{\@fptop}
% \begin{macro}{\@fpsep}
% \begin{macro}{\@fpbot}
%    When floating objects are placed on separate pages the layout of
%    such pages is controlled by these parameters. At the top of the
%    page \cs{@fptop} amount of stretchable whitespace is inserted, at
%    the bottom of the page we get an \cs{@fpbot} amount of stretchable
%    whitespace. Between adjacent floats the \cs{@fpsep} is inserted.
% For the larger sizes \cs{@fpsep} is .7\cs{onelineskip}.
%
%    These parameters are used for the placement of floating objects
%    in one column mode, or in single column floats in two column
%    mode.
%
%    Note that at least one of the two parameters \cs{@fptop} and
%    \cs{@fpbot} should contain a \verb?plus ...fil? to allow filling the
%    remaining empty space.
%    \begin{macrocode}
%<*9pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{9\p@ \@plus 2fil}
\setlength\@fpbot{0\p@ \@plus 1fil}
%</9pt>
%<*10pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{8\p@ \@plus 2fil}
\setlength\@fpbot{0\p@ \@plus 1fil}
%</10pt>
%<*11pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{8\p@ \@plus 2fil}
\setlength\@fpbot{0\p@ \@plus 1fil}
%</11pt>
%<*12pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{10\p@ \@plus 2fil}
\setlength\@fpbot{0\p@ \@plus 1fil}
%</12pt>
%<*14pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{10\p@ \@plus 2fil}
\setlength\@fpbot{0\p@ \@plus 1fil}
%</14pt>
%<*17pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{12\p@ \@plus 2fil}
\setlength\@fpbot{0\p@ \@plus 1fil}
%</17pt>
%<*20pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{17\p@ \@plus 2fil}
\@fpbot \@fptop
%</20pt>
%<*25pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{21\p@ \@plus 2fil}
\@fpbot \@fptop
%</25pt>
%<*30pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{26\p@ \@plus 2fil}
\@fpbot \@fptop
%</30pt>
%<*36pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{31\p@ \@plus 2fil}
\@fpbot \@fptop
%</36pt>
%<*48pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{42\p@ \@plus 2fil}
\@fpbot \@fptop
%</48pt>
%<*60pt>
\setlength\@fptop{0\p@ \@plus 1fil}
\setlength\@fpsep{50\p@ \@plus 2fil}
\@fpbot \@fptop
%</60pt>
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@dblfptop}
% \begin{macro}{\@dblfpsep}
% \begin{macro}{\@dblfpbot}
%    Double column floats in two column mode are handled with similar
%    parameters.
%    \begin{macrocode}
%<*9pt>
\setlength\@dblfptop{0\p@ \@plus 1fil}
\setlength\@dblfpsep{7\p@ \@plus 2fil}
\setlength\@dblfpbot{0\p@ \@plus 1fil}
%</9pt>
%<*10pt>
\setlength\@dblfptop{0\p@ \@plus 1fil}
\setlength\@dblfpsep{8\p@ \@plus 2fil}
\setlength\@dblfpbot{0\p@ \@plus 1fil}
%</10pt>
%<*11pt>
\setlength\@dblfptop{0\p@ \@plus 1fil}
\setlength\@dblfpsep{8\p@ \@plus 2fil}
\setlength\@dblfpbot{0\p@ \@plus 1fil}
%</11pt>
%<*12pt>
\setlength\@dblfptop{0\p@ \@plus 1fil}
\setlength\@dblfpsep{10\p@ \@plus 2fil}
\setlength\@dblfpbot{0\p@ \@plus 1fil}
%</12pt>
%<*14pt>
\setlength\@dblfptop{0\p@ \@plus 1fil}
\setlength\@dblfpsep{12\p@ \@plus 2fil}
\setlength\@dblfpbot{0\p@ \@plus 1fil}
%</14pt>
%<*17pt>
\setlength\@dblfptop{0\p@ \@plus 1fil}
\setlength\@dblfpsep{12\p@ \@plus 2fil}
\setlength\@dblfpbot{0\p@ \@plus 1fil}
%</17pt>
%<*20pt>
\@dblfptop \@fptop
\@dblfpsep \@fpsep
\@dblfpbot \@dblfptop
%</20pt>
%<*25pt>
\@dblfptop \@fptop
\@dblfpsep \@fpsep
\@dblfpbot \@dblfptop
%</25pt>
%<*30pt>
\@dblfptop \@fptop
\@dblfpsep \@fpsep
\@dblfpbot \@dblfptop
%</30pt>
%<*36pt>
\@dblfptop \@fptop
\@dblfpsep \@fpsep
\@dblfpbot \@dblfptop
%</36pt>
%<*48pt>
\@dblfptop \@fptop
\@dblfpsep \@fpsep
\@dblfpbot \@dblfptop
%</48pt>
%<*60pt>
\@dblfptop \@fptop
\@dblfpsep \@fpsep
\@dblfpbot \@dblfptop
%</60pt>
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsection{The measure}
%
% The width of a line of text (and therefore the text block) is termed
% the \emph{measure}.
%
% \begin{macro}{\lxvchars}
% The length \cs{lxvchars} is the approximate length of a normal
% text line containing 65 characters (a typesetters rule of thumb is
% that there should be about 60--70 characters per line).
%    \begin{macrocode}
%<9pt>\setlength\lxvchars{276\p@}  %
%<10pt>\setlength\lxvchars{300\p@} % standard 345pt
%<11pt>\setlength\lxvchars{324\p@} % standard 360pt
%<12pt>\setlength\lxvchars{336\p@} % standard 390pt
%<14pt>\setlength\lxvchars{408\p@} %
%<17pt>\setlength\lxvchars{444\p@} %
%<20pt>\setlength\lxvchars{528\p@} %
%<25pt>\setlength\lxvchars{626\p@} %
%<30pt>\setlength\lxvchars{748\p@} %
%<36pt>\setlength\lxvchars{891\p@} %
%<48pt>\setlength\lxvchars{1177\p@} %
%<60pt>\setlength\lxvchars{1463\p@} %
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\xlvchars}
% The length \cs{xlvchars} is the approximate length of a normal
% double column text line containing 45 characters 
% (a typesetters rule of thumb is
% that there should be about 40--50 characters per column line).
%    \begin{macrocode}
%<9pt>\setlength\xlvchars{192\p@}  %
%<10pt>\setlength\xlvchars{204\p@} % 
%<11pt>\setlength\xlvchars{216\p@} % 
%<12pt>\setlength\xlvchars{240\p@} % 
%<14pt>\setlength\xlvchars{288\p@} %
%<17pt>\setlength\xlvchars{312\p@} %
%<20pt>\setlength\xlvchars{365\p@} %
%<25pt>\setlength\xlvchars{438\p@} %
%<30pt>\setlength\xlvchars{518\p@} %
%<36pt>\setlength\xlvchars{617\p@} %
%<48pt>\setlength\xlvchars{815\p@} %
%<60pt>\setlength\xlvchars{1014\p@} %
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\marginparsep}
% \begin{macro}{\marginparpush}
% \cs{marginparsep} is the horizontal space between the text block and 
% marginal notes, while \cs{marginparpush} is the minimum vertical
% separation between the notes.
%    \begin{macrocode}
\if@twocolumn
%<*9pt|10pt|11pt|12pt|14pt>
  \setlength\marginparsep{10\p@}
%</9pt|10pt|11pt|12pt|14pt>
%<*17pt|20pt|25pt|30pt|36pt|48pt|60pt>
  \setlength\marginparsep{1em}
%</17pt|20pt|25pt|30pt|36pt|48pt|60pt>
\else
%<*9pt|10pt|11pt|12pt|14pt>
  \setlength\marginparsep{7\p@}
%</9pt|10pt|11pt|12pt|14pt>
%<*17pt|20pt|25pt|30pt|36pt|48pt|60pt>
  \setlength\marginparsep{0.7em}
%</17pt|20pt|25pt|30pt|36pt|48pt|60pt>
\fi
%<9pt|10pt|11pt>\setlength{\marginparpush}{5\p@}
%<12pt|14pt>\setlength{\marginparpush}{7\p@}
%<*17pt|20pt|25pt|30pt|36pt|48pt|60pt>
  \setlength\marginparpush{0.5em}
%</17pt|20pt|25pt|30pt|36pt|48pt|60pt>
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%    \begin{macrocode}
%</9pt|10pt|11pt|12pt|14pt|17pt|20pt|25pt|30pt|36pt|48pt|60pt>
%<*class>
%    \end{macrocode}
%
% \section{Page Layout}
%
%
% \subsection{The typeblock and margins}
%
%    All margin dimensions are measured from a point one inch from the
%    top and lefthand side of the page.
%
% \begin{macro}{\setlxvchars}
% \begin{macro}{\setxlvchars}
% These were suggested and supplied by Morten H{\o}gholm (18 May 2003).
%
% \cs{setlxvchars}\oarg{fontspec} sets \cs{lxvchars} to the length of a line
% containing 65 characters in the \meta{fontspec}. 
%
% Similarly
% \cs{setxlvchars}\oarg{fontspec} sets \cs{xlvchars} for 45 characters.
% \changes{v1.4}{2003/11/22}{Added \cs{setlxvchars} and \cs{setxlvchars}
%                              (from patch v1.6)}
%    \begin{macrocode}
\newcommand*{\setlxvchars}[1][\normalfont]{\begingroup
  #1
  \settowidth{\lxvchars}{abcdefghijklmnopqrstuvwxyz}%
  \setlength{\lxvchars}{2.042\lxvchars}%
  \addtolength{\lxvchars}{33.41pt}%
  \global\lxvchars=\lxvchars
  \endgroup}
\newcommand*{\setxlvchars}[1][\normalfont]{\begingroup
  #1
  \settowidth{\xlvchars}{abcdefghijklmnopqrstuvwxyz}%
  \setlength{\xlvchars}{1.415\xlvchars}%
  \addtolength{\xlvchars}{23.03pt}%
  \global\xlvchars=\xlvchars
  \endgroup}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setrectanglesize}
%  The macro \cs{setrectanglesize}\marg{H}\marg{W}\marg{r}
% calculates the height and width of a rectangle given any two out of
% the three arguments. An unvalued argument is denoted by \verb?*?.
%
% Table~\ref{tab:setrect} shows the argument combinations and the result
% for each combination.
% \begin{table}
% \centering
% \caption{Arguments and results for \cs{setrectanglesize}}\label{tab:setrect}
% \begin{tabular}{ccc|l} \hline
%  H & W & r & Result  \\ \hline
%  * & W & r & $H = rW$  \\{}
%  * & W & * & $H = W$   \\{}
%  * & * & r & ambiguous   \\{}
%  * & * & * & ambiguous   \\{}
%  H & W & r & $H, W$  \\
%  H & W & * & $H, W$   \\
%  H & * & r & $W = rH$  \\
%  H & * & * & $W = H$   \\
%  \hline
% \end{tabular}
% \end{table}
%
% The
% calculated height and width are stored in \cs{@tempdima} and \cs{@tempdimb}
% respectively. Both lengths are set to zero if there is an error.
% \changes{v1.61803}{2008/01/30}{Used \cs{setlength} instead of TeX syntax so that the calc package 
%          can be used with page layout (Morten H{\o}gholm mempatch v4.5)}
%    \begin{macrocode}
\newcommand*{\setrectanglesize}[3]{%
  \nametest{#1}{*}%
  \ifsamename                           % H = *
    \nametest{#2}{*}%
    \ifsamename                         % W = *
      \@memerror{%
        The combination of argument values is ambiguous.\MessageBreak
        The lengths will be set to zero}{\@ehd}%
      \setlength{\@tempdima}{0pt}%
      \setlength{\@tempdimb}{0pt}%
    \else                               % W
      \nametest{#3}{*}%
      \ifsamename                       % r = *
        \setlength{\@tempdimb}{#2}%
        \setlength{\@tempdima}{\@tempdimb}%
      \else                             % r
        \setlength{\@tempdimb}{#2}%
        \setlength{\@tempdima}{#3\@tempdimb}%
      \fi
    \fi
  \else                                 % H
    \nametest{#2}{*}%
    \ifsamename                         % W = *
      \nametest{#3}{*}%
      \ifsamename                       % r = *
        \setlength{\@tempdima}{#1}%
        \setlength{\@tempdimb}{\@tempdima}%
      \else                             % r
        \setlength{\@tempdima}{#1}%
        \setlength{\@tempdimb}{#3\@tempdima}%
      \fi
    \else                               % W
      \setlength{\@tempdima}{#1}%
      \setlength{\@tempdimb}{#2}%
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setfillsize}
% Consider a set of 4 lengths, $T$, $L$, $C$, and $R$, such that
% $T = L + C + R$, where $T$ is a fixed size and normally $C$ is also fixed.
% Also $L$ and $R$ may be specified independently of each other or as a
% ratio (i.e., $L = rR$ or $R = rL$).
%  The macro 
% \cs{setfillsize}\marg{T}\marg{C}\marg{L}\marg{R}\marg{r}
% maintains these constraints among the variables, where an unvalued 
% argument is denoted by \verb?*?.
%
% Table~\ref{tab:setfill} shows the argument combinations and the result
% for each combination.
% \begin{table}
% \centering
% \caption{Arguments and results for \cs{setfillsize}}\label{tab:setfill}
% \begin{tabular}{cccc|ll} \hline
%  C & L & R & r & Result                     &   \\ \hline
%  * & * & R & r & $L = rR$,                  & $C = T - L - R$ \\{}
%  * & * & R & * & $L = R$,                   & $C = T - L - R$ \\{}
%  * & * & * & r & ambigous                   & \\{}
%  * & * & * & * & ambiguous                  & \\{}
%  * & L & R & r & $L$, $R$,                  & $C = T - L - R$ \\{}
%  * & L & R & * & $L$, $R$,                  & $C = T - L - R$ \\{}
%  * & L & * & r & $R = rL$,                  & $C = T - L - R$ \\{}
%  * & L & * & * & $R = L$,                   & $C = T - L - R$ \\{}
%  C & * & R & r & $L = T - C - R$            & $C$ \\
%  C & * & R & * & $L = T - C - R$,           & $C$ \\
%  C & * & * & r & $L + R = T - C$, $R = rL$, & $C$ \\
%  C & * & * & * & $L + R = T - C$, $R = L$,  & $C$ \\
%  C & L & R & r & ambiguous                  & $C$ \\
%  C & L & R & * & ambiguous                  & $C$ \\ 
%  C & L & * & r & $R = T - C - L$,           & $C$ \\
%  C & L & * & * & $R = T - C - L$,           & $C$ \\
%  \hline
% \end{tabular}
% ^^A \MakeShortVerb{\|}
% \end{table}
%
%
% The
% calculated values of \texttt{C}, \texttt{L} and \texttt{R} are stored 
% \cs{@tempdimc}, 
% \cs{@tempdima} and \cs{@tempdimb} respectively. If there is an error
% the lengths are set to zero.
%    \begin{macrocode}
\newcommand*{\setfillsize}[5]{%
  \nametest{#2}{*}%
  \ifsamename                                % C = *
    \nametest{#3}{*}%
    \ifsamename                              % L = *
      \nametest{#4}{*}%
      \ifsamename                            % R = *
        \@memerror{%
          The combination of argument values is ambiguous.\MessageBreak
          The lengths will be set to zero}{\@ehd}
        \setlength{\@tempdima}{0pt}%
        \setlength{\@tempdimb}{0pt}%
        \setlength{\@tempdimc}{0pt}%
      \else                                  % R 
        \nametest{#5}{*}%
        \ifsamename                          % r = *
          \setlength{\@tempdimb}{#4}%
          \setlength{\@tempdima}{\@tempdimb}%
          \setlength{\@tempdimc}{#1}%
          \advance\@tempdimc -\@tempdima
          \advance\@tempdimc -\@tempdimb
        \else                                % r 
          \setlength{\@tempdimb}{#4}%
          \setlength{\@tempdima}{#5\@tempdimb}%
          \setlength{\@tempdimc}{#1}%
          \advance\@tempdimc -\@tempdima
          \advance\@tempdimc -\@tempdimb
        \fi
      \fi
    \else                                    % L 
      \nametest{#4}{*}%
      \ifsamename                            % R = *
        \nametest{#5}{*}%
        \ifsamename                          % r = *
          \setlength{\@tempdima}{#3}%
          \setlength{\@tempdimb}{\@tempdima}
          \setlength{\@tempdimc}{#1}%
          \advance\@tempdimc -\@tempdima
          \advance\@tempdimc -\@tempdimb
        \else                                % r 
          \setlength{\@tempdima}{#3}%
          \setlength{\@tempdimb}{#5\@tempdima}
          \setlength{\@tempdimc}{#1}%
          \advance\@tempdimc -\@tempdima
          \advance\@tempdimc -\@tempdimb
        \fi
      \else                                  % R
        \setlength{\@tempdima}{#3}%
        \setlength{\@tempdimb}{#4}%
        \setlength{\@tempdimc}{#1}%
        \advance\@tempdimc -\@tempdima
        \advance\@tempdimc -\@tempdimb
      \fi
    \fi
  \else                                      % C is valued
    \nametest{#3}{*}%
    \ifsamename                              % L = *
      \nametest{#4}{*}%
      \ifsamename                            % R = *
        \nametest{#5}{*}%
        \ifsamename                          % r = *
          \setlength{\@tempdimc}{#2}%
          \setlength{\@tempdima}{#1}%
          \advance\@tempdima -\@tempdimc
          \@tempdima = 0.5\@tempdima
          \@tempdimb = \@tempdima
        \else                                % r (CODE PERHAPS FIXED)
          \setlength{\@tempdimc}{#2}         % C
          \setlength{\@tempdimb}{#1}         % T
          \advance\@tempdimb -\@tempdimc % T - C
          \@tempdima = 1000sp
          \setlength{\@tempdima}{#5\@tempdima}        % 1000r sp
          \advance\@tempdima by 1000sp   % 1000(1+r)sp
          \@tempcnta = \@tempdima        % 1000(1+r)
          \@tempdima = \@tempdimb        % T - C
          \divide\@tempdima by \@tempcnta  % (T-C)/1000(1+r) pts
          \@tempdima = 1000\@tempdima      % (T-C)/(1+r)  pts = L
          \advance\@tempdimb by -\@tempdima % = R
        \fi
      \else                                  % R 
        \setlength{\@tempdimc}{#2}%
        \setlength{\@tempdimb}{#4}%
        \setlength{\@tempdima}{#1}%
        \advance\@tempdima -\@tempdimc
        \advance\@tempdima -\@tempdimb
      \fi
    \else                                    % L 
      \nametest{#4}{*}%
      \ifsamename                            % R = *
        \setlength{\@tempdimc}{#2}%
        \setlength{\@tempdima}{#3}%
        \setlength{\@tempdimb}{#1}%
        \advance\@tempdimb -\@tempdimc
        \advance\@tempdimb -\@tempdima
      \else                                  % R
        \@memerror{%
          The combination of argument values is ambiguous.\MessageBreak
          The lengths will be set to zero}{\@ehd}%
        \setlength{\@tempdima}{0pt}%
        \setlength{\@tempdimb}{0pt}%
        \setlength{\@tempdimc}{#2}%
      \fi
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setstocksize}
% \begin{macro}{\settrims}
% \begin{macro}{\settrimmedsize}
% \cs{setstocksize}\marg{height}\marg{width} sets the height
% and width of the stock material and 
% \cs{settrims}\marg{top}\marg{edge} sets the trim lengths
% for the top and side (fore edge) of the stock.
% The macro \cs{settrimmedsize}\marg{height}\marg{width}\marg{ratio}
% sets the size for the trimmed page, based on \cs{setrectanglesize}.
%    \begin{macrocode}
\newcommand{\setstocksize}[2]{%
  \setlength{\stockheight}{#1}%
  \setlength{\stockwidth}{#2}}
\newcommand{\settrims}[2]{%
  \setlength{\trimtop}{#1}%
  \setlength{\trimedge}{#2}}
\newcommand{\settrimmedsize}[3]{%
  \setrectanglesize{#1}{#2}{#3}%
  \setlength{\paperheight}{\@tempdima}%
  \setlength{\paperwidth}{\@tempdimb}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\settypeblocksize}
% \cs{settypeblocksize}\marg{height}\marg{width}\marg{ratio}
% calulates the \cs{textheight} and \cs{textwidth} from two out of the
% three arguments. 
% \changes{v3.6k}{2013/05/14}{Marked \cs{settypeblocksize} as being used}
%    \begin{macrocode}
\newcommand{\settypeblocksize}[3]{%
  \memsetmacroused\settypeblocksize%
  \setrectanglesize{#1}{#2}{#3}%
  \setlength{\textheight}{\@tempdima}%
  \setlength{\textwidth}{\@tempdimb}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\binding}
% \begin{macro}{\setbinding}
% The length \cs{binding} is an allowance on the spine margin for
% binding. \cs{setbinding}\marg{length} sets the \cs{binding}.
% \changes{v1.6180339c}{2008/12/29}{Added binding offset code to the
% layout functions}
%    \begin{macrocode}
\newlength{\binding}
\newcommand*{\setbinding}[1]{\setlength{\binding}{#1}}
  \setbinding{0pt}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\spinemargin}
% \begin{macro}{\foremargin}
% \begin{macro}{\setlrmargins}
% \cs{setlrmargins}\marg{L}\marg{R}\marg{r} sets the Left (spine)
% and Right (fore edge) margins with constant typeblock.
% \changes{v1.6180339c}{2008/12/29}{Added binding to \cs{setlrmargins}}
% \changes{v3.6k}{2013/05/14}{Marked \cs{setlrmargins} as being used}
%    \begin{macrocode}
\newlength{\spinemargin}
\newlength{\foremargin}
\newcommand{\setlrmargins}[3]{%
  \memsetmacroused\setlrmargins%
  \advance\paperwidth -\binding
  \setfillsize{\paperwidth}{\textwidth}{#1}{#2}{#3}%
  \setlength{\textwidth}{\@tempdimc}%
  \setlength{\spinemargin}{\@tempdima}%
  \setlength{\foremargin}{\@tempdimb}%
  \advance\paperwidth \binding
  \advance\spinemargin \binding}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setlrmarginsandblock}
% \cs{setlrmarginsandblock}\marg{L}\marg{R}\marg{r} sets the Left (spine)
% and Right (fore edge) margins with variable typeblock.
% \changes{v1.6180339c}{2008/12/29}{Added binding to \cs{setlrmarginsandblock}}
%    \begin{macrocode}
\newcommand{\setlrmarginsandblock}[3]{%
  \advance\paperwidth -\binding
  \setfillsize{\paperwidth}{*}{#1}{#2}{#3}%
  \setlength{\textwidth}{\@tempdimc}%
  \setlength{\spinemargin}{\@tempdima}%
  \setlength{\foremargin}{\@tempdimb}%
  \advance\paperwidth \binding
  \advance\spinemargin \binding}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\uppermargin}
% \begin{macro}{\lowermargin}
% \begin{macro}{\setulmargins}
% \cs{setulmargins}\marg{L}\marg{R}\marg{r} sets the Left (upper)
% and Right (lower) margins with constant typeblock.
% \changes{v3.6k}{2013/05/14}{Marked \cs{setulmargins} as being used}
%    \begin{macrocode}
\newlength{\uppermargin}
\newlength{\lowermargin}
\newcommand{\setulmargins}[3]{%
  \memsetmacroused\setulmargins%
  \setfillsize{\paperheight}{\textheight}{#1}{#2}{#3}%
  \setlength{\textheight}{\@tempdimc}%
  \setlength{\uppermargin}{\@tempdima}%
  \setlength{\lowermargin}{\@tempdimb}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setulmarginsandblock}
% \cs{setulmarginsandblock}\marg{L}\marg{R}\marg{r} sets the Left (upper)
% and Right (lower) margins with variable typeblock.
%    \begin{macrocode}
\newcommand{\setulmarginsandblock}[3]{%
  \setfillsize{\paperheight}{*}{#1}{#2}{#3}%
  \setlength{\textheight}{\@tempdimc}%
  \setlength{\uppermargin}{\@tempdima}%
  \setlength{\lowermargin}{\@tempdimb}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\headdrop}
% \begin{macro}{\setheaderspaces}
% \cs{setheaderspaces}\marg{L}\marg{R}\marg{r} sets the Left (head margin)
% and Right (headsep) spacing with constant headheight.
%    \begin{macrocode}
\newlength{\headdrop}
\newcommand{\setheaderspaces}[3]{%
  \setfillsize{\uppermargin}{\headheight}{#1}{#2}{#3}%
  \setlength{\headheight}{\@tempdimc}%
  \setlength{\headdrop}{\@tempdima}%
  \setlength{\headsep}{\@tempdimb}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setheadfoot}
% \cs{setheadfoot}\marg{headheight}\marg{footskip}
% sets the headheight and the footskip.
%    \begin{macrocode}
\newcommand{\setheadfoot}[2]{%
  \setlength{\headheight}{#1}%
  \setlength{\footskip}{#2}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setcolsepandrule}
% \cs{setcolsepandrule}\marg{colsep}\marg{thickness}
% sets the column separation and the rule thickness.
% \changes{v1.0}{2001/09/20}{Changed \cs{setcolseprule} to 
% \cs{setcolsepandrule} to match the documentation.}
%    \begin{macrocode}
\newcommand{\setcolsepandrule}[2]{%
  \setlength{\columnsep}{#1}%
  \setlength{\columnseprule}{#2}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setmarginnotes}
% \cs{setmarginnotes}\marg{sep}\marg{width}\marg{push}
% sets the marginpar parameters.
% \changes{v3.6k}{2013/05/14}{Marked \cs{setmarginnotes} as being used}
%    \begin{macrocode}
\newcommand{\setmarginnotes}[3]{%
  \memsetmacroused\setmarginnotes%
  \setlength{\marginparsep}{#1}%
  \setlength{\marginparwidth}{#2}%
  \setlength{\marginparpush}{#3}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setfootins}
%   \cs{setfootins}\marg{length}\marg{length} sets
%   \cs{skip}\cs{footins} and its minipage counterpart. It will also
%   set \cs{skip}\cs{footinsv@r} and similar for minipages to the same
%   values. These are used by for example \cs{twocolumnfootnotes}.
%    \begin{macrocode}
\newcommand\setfootins[2]{
  \setlength{\skip\footins}{#1}
  \setlength{\skip\footinsv@r}{#1}
  \setlength{\skip\@mpfootins}{#2}
  % not explicitly used 
  \setlength{\skip\@mpfootinsv@r}{#2}
}

%    \end{macrocode}
%   
% \end{macro}
%
%
%    Initialise the paper size and trimming to their default values.
%    \begin{macrocode}
\settrimmedsize{\stockheight}{\stockwidth}{*}
\settrims{\z@}{\z@}

%    \end{macrocode}
%
%    What now follows is the standard class's method for setting up
% the dimensions.
%
%    Set \cs{@tempdimb} to size-dependent initial line length and
% set \cs{@tempdima} to the maximum textwidth for the paper width, 
% an inch margin on either side. In the standard classes the initial
% line length is about 14\% greater than \cs{lxvchars}.
%    \begin{macrocode}
\setlength{\@tempdimb}{1.14\lxvchars}
\setlength\@tempdima{\paperwidth}
  \addtolength\@tempdima{-2in}
%    \end{macrocode}
%
% \begin{macro}{\textwidth}
% Now set the \cs{textwidth} depending on the number of columns. In twocolumn
% mode each column should be no wider than \cs{@tempdimb}.
%    \begin{macrocode}
\if@twocolumn
  \ifdim\@tempdima>2\@tempdimb\relax
    \setlength\textwidth{2\@tempdimb}
  \else
    \setlength\textwidth{\@tempdima}
  \fi
%    \end{macrocode}
% In onecolumn
% the text should not be wider than the minumum of the paperwidth (less
% 2in for the margins) and the maximum length of the character line.
%    \begin{macrocode}
\else
  \ifdim\@tempdima>\@tempdimb\relax
    \setlength\textwidth{\@tempdimb}
  \else
    \setlength\textwidth{\@tempdima}
  \fi
\fi
%    \end{macrocode}
% Adjust the width to be a whole number of points.
% \changes{v3.7g}{2018/03/09}{Switch to private truncating macro so we
% can disable truncation via class option}
%    \begin{macrocode}
\mem@settopoint\textwidth

%    \end{macrocode}
% \end{macro}
%  
% \begin{macro}{\textheight}
%    The \cs{textheight} is the height of the text block, excluding
% headers and footers. This is set according to the \cs{paperheight},
% to an integral number of lines, and allowing a 1in margin at the
% top and bottom and a further 1.5in for headers and footers.
%    \begin{macrocode}
\setlength\@tempdima{\paperheight}
  \addtolength\@tempdima{-3.5in}
%    \end{macrocode}
% Divide this height by the \cs{baselineskip} to get the number of lines.
% Then (re)calculate the \cs{textheight} and finally add the \cs{topskip}.
%    \begin{macrocode}
  \divide\@tempdima\baselineskip
\@tempcnta=\@tempdima
\setlength\textheight{\@tempcnta\baselineskip}
  \addtolength\textheight{\topskip}

%    \end{macrocode}
% \end{macro}
%
%    The margins are calculated. 
%
% \begin{macro}{\oddsidemargin}
% \begin{macro}{\marginparwidth}
% \begin{macro}{\evensidemargin}
%    The margins depend on the paper size, also for two sided
% printing the inner margin is made smaller than the outer.
%    \begin{macrocode}
\if@twoside
  \setlength\@tempdima       {\paperwidth}
  \addtolength\@tempdima     {-\textwidth}
  \setlength\oddsidemargin   {.4\@tempdima}
  \addtolength\oddsidemargin {-1in}
  \setlength\marginparwidth  {.6\@tempdima}
  \addtolength\marginparwidth{-\marginparsep}
  \addtolength\marginparwidth{-0.4in}
\else
  \setlength\@tempdima       {\paperwidth}
  \addtolength\@tempdima     {-\textwidth}
  \setlength\oddsidemargin   {.5\@tempdima}
  \addtolength\oddsidemargin {-1in}
  \setlength\marginparwidth  {.5\@tempdima}
  \addtolength\marginparwidth{-\marginparsep}
  \addtolength\marginparwidth{-0.8in} % don't know why this isn't .4
\fi
\ifdim\marginparwidth>2in
  \setlength\marginparwidth{2in}%
\fi
%    \end{macrocode}
% Set these values to integer numbers of points, and afterwards calculate the
% \cs{evensidemargin}.
% Jonathon Stickel (\url{jjstickel@vcn.com}) on 2008/05/30 noted that
% \cs{marginparwidth} had to be positive for the initial setting of the sidebar
% geometry through \cs{setsidebars}.
% \changes{v1.618033}{2008/06/02}{Ensured initial value of \cs{marginparwidth}
%  was positive}
% \changes{v3.7g}{2018/03/09}{Switch to private truncating macro so we
% can disable truncation via class option}
%    \begin{macrocode}
\mem@settopoint\oddsidemargin
\mem@settopoint\marginparwidth
\ifdim\marginparwidth<1pt \setlength\marginparwidth{1pt}\fi

\setlength\evensidemargin  {\paperwidth}
\addtolength\evensidemargin{-2in}
\addtolength\evensidemargin{-\textwidth}
\addtolength\evensidemargin{-\oddsidemargin}
\mem@settopoint\evensidemargin
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\topmargin}
%    The \cs{topmargin} is the distance below the top of the printable
% area (1in below the top of the paper) and the top of the box
% containing the running head.
% \changes{v3.7g}{2018/03/09}{Switch to private truncating macro so we
% can disable truncation via class option}
%    \begin{macrocode}
\setlength\topmargin  {\paperheight}
\addtolength\topmargin{-2in}
\addtolength\topmargin{-\headheight}
\addtolength\topmargin{-\headsep}
\addtolength\topmargin{-\textheight}
\addtolength\topmargin{-\footskip}
\addtolength\topmargin{-.5\topmargin}
\mem@settopoint\topmargin

%    \end{macrocode}
% \end{macro}
%
% That is the end of the classical algorithm. Now calculate the 
% user-friendly dimensions. The calculations are simpler than in
% the general case as the \cs{paperwidth} and \cs{paperheight} is the 
% same as the \cs{stockwidth} and \cs{stockheight}. 
%
%    We can get the spine 
% and edge margins from the \cs{oddsidemargin}.
%    \begin{macrocode}
\setlength{\spinemargin}{\oddsidemargin}
\addtolength{\spinemargin}{1in}
\setlrmargins{\spinemargin}{*}{*}

%    \end{macrocode}
%
%    Similarly we can get the upper and lower margins from the
% \cs{topmargin}, \cs{headheight} and \cs{headskip}.
%    \begin{macrocode}
\setlength{\uppermargin}{\topmargin}
\addtolength{\uppermargin}{1in}
\addtolength{\uppermargin}{\headheight}
\addtolength{\uppermargin}{\headsep}
\setulmargins{\uppermargin}{*}{*}

%    \end{macrocode}
%
% \begin{macro}{\@memznegtest}
% DA suggested this in a private email (2003/002/13) to make error
% checking and reporting a bit more (space) efficient. Use like \\
% \verb?\@memznegtest{\marginparsep}? instead of \\
% \begin{verbatim}
% \ifdim\marginparsep>\z@\else
%    \@memerror{\protect\marginparsep\space is zero or negative}{\@ehd}%
% \fi
% \end{verbatim}
% If its length variable argument is zero or less it reports an error.
% 
% \changes{v1.4}{2003/02/27}{Added \cs{@memznegtest}}
% \changes{v1.618033}{2008/06/02}{Changed \cs{@memznegtest} and 
%         \cs{@memnegtest} to issue warnings instead of errors}
%
%    \begin{macrocode}
\newcommand*{\@memznegtest}[1]{%
  \ifdim#1>\z@\else
 %%%%   \@memerror{\protect#1\space is zero or negative}{\@ehd}%
    \@memwarn{\protect#1\space is zero or negative}%
  \fi}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@memnegtest}
% Reports an error if its length variable argument is negative.
% \changes{v1.4}{2003/02/27}{Added \cs{@memnegtest}}
%    \begin{macrocode}
\newcommand*{\@memnegtest}[1]{%
  \ifdim#1<\z@
%%%%    \@memerror{\protect#1\space is negative}{\@ehd}%
    \@memwarn{\protect#1\space is negative}%
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mclassicht}
% The classic adjustment of the \cs{textheight} to get an integral number 
% of lines (given an integral number of baselineskips returns a height
% giving one more line in the block).
% \changes{v1.61803}{2008/01/30}{Added \cs{m@mclassicht}, \cs{m@mlinesht}
%             and \cs{m@mnearestht} (mempatch v4.5)}
%    \begin{macrocode}
\newcommand*{\m@mclassicht}{%
  \setlength{\@tempdima}{\textheight}%
  \divide\@tempdima \baselineskip
  \@tempcnta=\@tempdima
  \setlength{\textheight}{\@tempcnta\baselineskip}%
  \addtolength{\textheight}{\topskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mlinesht}
% The adjustment of the \cs{textheight} to get an integral number 
% of lines (given an inegral number of baselineskips returns a height
% giving that number of lines).
%    \begin{macrocode}
\newcommand*{\m@mlinesht}{%
  \setlength{\@tempdima}{\textheight}%
  \advance\@tempdima -\baselineskip
  \divide\@tempdima \baselineskip
  \@tempcnta=\@tempdima
  \setlength{\textheight}{\@tempcnta\baselineskip}%
  \addtolength{\textheight}{\topskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mnearestht}
% The adjustment of the \cs{textheight} to get an integral number 
% of lines with the calculated height being as the closest to the given 
% height. Algorithm supplied by Lars Madsen and Morten H{\o}gholm on
% 2006/07/27.
%    \begin{macrocode}
\newcommand*{\m@mnearestht}{%
  \setlength{\@tempdima}{\textheight}%
  \advance\@tempdima -\topskip
  \advance\@tempdima 0.5\baselineskip
  \divide\@tempdima \baselineskip
  \@tempcnta=\@tempdima
  \setlength{\textheight}{\@tempcnta\baselineskip}%
  \addtolength{\textheight}{\topskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@autoadjust@marginparwidth}
% This macro implements an algorithm, to automatically adjust
% \cs{marginparwidth} to the current values of \cs{spinemargin} and
% \cs{foremargin} (i.e., the inner and outer margins). It may be used
% within \cs{fixthelayout} in case the user has not changed 
% \cs{marginparwidth} using \cs{setmarginnotes}.
%    \begin{macrocode}
\newcommand\mem@autoadjust@marginparwidth{%
  \if@twocolumn
    \memsetlengthmin\marginparwidth\spinemargin\foremargin
  \else
    \if@twoside
      \ifcase\m@mmpar@margin\relax% 0 - left
        \memsetlengthmin\marginparwidth\spinemargin\foremargin
      \or% 1 - right
        \memsetlengthmin\marginparwidth\spinemargin\foremargin
      \or% 2 - outer
        \setlength\marginparwidth{\foremargin}
      \or% 3 - inner
        \setlength\marginparwidth{\spinemargin}
      \fi
    \else % oneside
      \ifnum\m@mmpar@margin=0% left
        \setlength\marginparwidth{\spinemargin}
      \else% right
        \setlength\marginparwidth{\foremargin}
      \fi
    \fi
  \fi
  \addtolength\marginparwidth{-2\marginparsep}
  \ifdim\marginparwidth<1pt\setlength\marginparwidth{1pt}\fi%
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@reset@used@macros}
%   This macro is used to unset used macros. It is a manually
%   maintained macro. A better version would have been to let
%   \cs{memsetmacroused} record its use in a list, and then loop over
%   this list. Maybe some other time.
%    \begin{macrocode}
\newcommand\mem@reset@used@macros{%
  \memsetmacrounused\setmarginnotes
  \memsetmacrounused\settypeblocksize
  \memsetmacrounused\setulmargins
  \memsetmacrounused\setlrmargins
}

%    \end{macrocode}
%   
% \end{macro}
%
% \begin{macro}{\checkthelayout}
% \cs{checkthelayout}\oarg{text} is the user level macro for
% checking the layout. The \meta{text} argument controls which
% algorithm should be used to calculate the \cs{textheight}.
% \changes{v1.61803}{2008/01/30}{Extended \cs{checkthelayout} to include a choice
%          of algorithms (mempatch v4.5)}
% \changes{v1.61803}{2008/01/30}{Changed some page layout tests to negative from zero or negative 
%                   (mempatch v4.5)}
%    \begin{macrocode}
\newcommand*{\checkthelayout}[1][classic]{%
%    \end{macrocode}
% First check the dimensions are not (zero or) negative.
%    \begin{macrocode}
  \@memnegtest{\trimedge}
  \@memnegtest{\trimtop}
  \@memznegtest{\stockwidth}
  \@memznegtest{\paperwidth}
  \@memznegtest{\textwidth}
%%%  \@memznegtest{\spinemargin}
  \@memnegtest{\spinemargin}
%%%  \@memznegtest{\foremargin}
  \@memnegtest{\foremargin}
  \@memznegtest{\marginparsep}
  \@memznegtest{\marginparwidth}
  \@memznegtest{\stockheight}
  \@memznegtest{\paperheight}
  \@memznegtest{\textheight}
%%%  \@memznegtest{\uppermargin}
  \@memnegtest{\uppermargin}
%%%  \@memznegtest{\lowermargin}
  \@memnegtest{\lowermargin}
%%%  \@memznegtest{\headheight}
  \@memnegtest{\headheight}
%%%  \@memznegtest{\headsep}
  \@memnegtest{\headsep}
%%%  \@memznegtest{\footskip}
  \@memnegtest{\footskip}
%    \end{macrocode}
%
%    Carry on regardless. We may need to adjust the \cs{textheight} 
% to get an integral number of lines.
%    \begin{macrocode}
  \nametest{#1}{classic}%
  \ifsamename
    \m@mclassicht
  \else
    \nametest{#1}{lines}%
    \ifsamename
      \m@mlinesht
    \else
      \nametest{#1}{nearest}%
      \ifsamename
        \m@mnearestht
      \else
        \nametest{#1}{fixed}
        \ifsamename
        \else%    not classic, lines, nearest, or fixed
          \@memerror{Optional argument is not one of:\MessageBreak
                     classic, fixed, lines, or nearest. \MessageBreak
                     I will assume the default}%
                    {\@ehc}%
        \fi
      \fi
    \fi
  \fi
  \setulmargins{\uppermargin}{*}{*}
%    \end{macrocode}
%
% Check that all the sums add up correctly, or
% at least to within a small (\cs{@tempdimb}) error.
% \changes{v1.618033}{2008/06/02}{Added more information about problematic
%  layout values}
%    \begin{macrocode}
  \@tempdimb = -1pt  
  \@tempdima=\stockwidth
  \advance\@tempdima -\trimedge
  \advance\@tempdima -\paperwidth
  \ifdim\@tempdima<\@tempdimb
    \@tempdima = -\@tempdima
    \@memerror{\protect\paperwidth\space (\the\paperwidth) and/or 
                        \protect\trimedge\space (\the\trimedge)
                        are too large for \protect\stockwidth\space (\the\stockwidth)
                        by \the\@tempdima}%
                       {\@ehd}
  \fi
  \@tempdima = \paperwidth
  \advance\@tempdima -\foremargin
  \advance\@tempdima -\textwidth
  \advance\@tempdima -\spinemargin
  \ifdim\@tempdima<\@tempdimb
    \@tempdima = -\@tempdima
    \@memerror{\protect\spinemargin\space (\the\spinemargin) and/or 
                        \protect\textwidth\space (\the\textwidth) and/or
                        \protect\foremargin\space (\the\foremargin)
                        are too large for \protect\paperwidth\space (\the\paperwidth)
                        by \the\@tempdima}%
                       {\@ehd}
  \fi
  \@tempdima = \stockheight
  \advance\@tempdima -\trimtop
  \advance\@tempdima -\paperheight
  \ifdim\@tempdima<\@tempdimb
    \@tempdima = -\@tempdima
    \@memerror{\protect\paperheight\space (\the\paperheight) and/or 
                        \protect\trimtop\space (\the\trimtop)
                        are too large for \protect\stockheight\space (\the\stockheight)
                        by \the\@tempdima}%
                       {\@ehd}
  \fi
  \@tempdima = \paperheight
  \advance\@tempdima -\uppermargin
  \advance\@tempdima -\textheight
  \advance\@tempdima -\lowermargin
  \ifdim\@tempdima<\@tempdimb
    \@tempdima = -\@tempdima
    \@memerror{\protect\uppermargin\space (\the\uppermargin) and/or 
                        \protect\textheight\space (\the\textheight) and/or 
                        \protect\lowermargin\space (\the\lowermargin)
                        are too large for \protect\paperheight\space (\the\paperheight)
                        by \the\@tempdima}%
                       {\@ehd}
  \fi
  \@tempdima = \uppermargin
  \advance\@tempdima -\headheight
  \advance\@tempdima -\headsep
  \ifdim\@tempdima<\@tempdimb
    \@tempdima = -\@tempdima
    \@memerror{\protect\headheight\space (\the\headheight) and/or 
                        \protect\headsep\space (\the\headsep)
                        are too large for \protect\uppermargin\space (\the\uppermargin)
                        by \the\@tempdima}%
                       {\@ehd}
  \fi
  \@tempdima = \lowermargin
  \advance\@tempdima -\footskip
  \ifdim\@tempdima<\z@
    \@tempdima = -\@tempdima
    \@memerror{\protect\footskip\space (\the\footskip)
                        is too large for \protect\lowermargin\space (\the\lowermargin)
                        by \the\@tempdima}%
                       {\@ehd}
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\fixthelayout}
%   Calculate the normal
% \LaTeX{} page layout parameter values. We'll do the heights first
% as they are independent of the number of columns and the side printing.
% \changes{v1.0a}{2002/01/18}{Added \cs{fixthelayout}}
%    \begin{macrocode}
\newcommand*{\fixthelayout}{%
  \topmargin = \trimtop
    \advance\topmargin \uppermargin
    \advance\topmargin -\headsep
    \advance\topmargin -\headheight
    \advance\topmargin -1in\relax
%    \end{macrocode}
%
%    Now the \cs{oddsidemargin}.
%    \begin{macrocode}
  \oddsidemargin = \stockwidth
    \advance\oddsidemargin -\trimedge
    \advance\oddsidemargin -\paperwidth
    \advance\oddsidemargin \spinemargin
    \advance\oddsidemargin -1in\relax
%    \end{macrocode}
%
%    And the \cs{evensidemargin}.
%    \begin{macrocode}
  \evensidemargin = \trimedge
    \advance\evensidemargin \foremargin
    \advance\evensidemargin -1in\relax
%    \end{macrocode}
%
%
%    Set the values to the nearest whole point.
% \changes{v3.7g}{2018/03/09}{Switch to private truncating macro so we
% can disable truncation via class option}
%    \begin{macrocode}
  \mem@settopoint\textwidth
  \mem@settopoint\oddsidemargin
  \mem@settopoint\evensidemargin
%    \end{macrocode}
% Fix standard page layouts after possible change of \cs{textwidth}.
% \changes{v1.6180339f}{2009/03/16}{Added \cs{fixheaderwidths} to \cs{fixthelayout}}
%    \begin{macrocode}
  \fixheaderwidths
%    \end{macrocode}
% Autoadjust \cs{marginparwidth} unless the user have used
% \cs{setmarginnotes}. Plus add a reset of the recordedmacros, just in
% case \cs{fixthelayout} is being used several times.
% \changes{v3.6k}{2013/05/15}{Added autoadjust}
%    \begin{macrocode}
  \memifmacroused\setmarginnotes{}{\mem@autoadjust@marginparwidth}
  \mem@reset@used@macros
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\typeoutlayout}
% \begin{macro}{\settypeoutlayoutunit}
% \begin{macro}{\mem@typeouttwolengths}
% \begin{macro}{\mem@typeoutonelength}
% Why not type out the calculated versions of the designed values?
% \changes{v1.0a}{2002/01/18}{Added \cs{typeoutlayout}}
% \changes{v1.0a}{2002/01/25}{Added column info to \cs{typeoutlayout}}
% \changes{v1.61803}{2008/01/30}{Added sidecap and sidebar data to \cs{typeoutlayout}
%                   (mempatch v4.6)}
% \changes{v1.61803398d}{2010/02/04}{Added information about side feet}
% \changes{v3.6g}{2010/09/17}{Added feature such that user can change
% the unit used by \cs{typeoutlayout}, requested by Rasmus Villemoes}
% Using the macro \cs{settypeoutlayoutunit}\marg{unit} before
% \cs{typeoutlayout} (or more often \cs{checkandfixthelayout}), the
% user can choose the unit in which the list is typeset. The code is
% inspired by the \texttt{printlen} package.
%    \begin{macrocode}
\newcommand\settypeoutlayoutunit[1]{
  \nametest{#1}{pt}
  \ifsamename
    \def\mem@tl@unit{#1}
    \def\mem@tl@unitperpt{1.0}
  \else 
    \nametest{#1}{pc}
    \ifsamename
      \def\mem@tl@unit{#1}
      \def\mem@tl@unitperpt{0.083333}
    \else
      \nametest{#1}{in}
      \ifsamename
        \def\mem@tl@unit{#1}
        \def\mem@tl@unitperpt{0.013837}
      \else
        \nametest{#1}{mm}
        \ifsamename
          \def\mem@tl@unit{#1}
          \def\mem@tl@unitperpt{0.351459}
        \else
          \nametest{#1}{cm}
          \ifsamename
            \def\mem@tl@unit{#1}
            \def\mem@tl@unitperpt{0.0351459}
          \else
            \nametest{#1}{bp}
            \ifsamename
              \def\mem@tl@unit{#1}
              \def\mem@tl@unitperpt{0.996264}
            \else
              \nametest{#1}{dd}
              \ifsamename
                \def\mem@tl@unit{#1}
                \def\mem@tl@unitperpt{0.9345718}
              \else
                \nametest{#1}{cc}
                \ifsamename
                  \def\mem@tl@unit{#1}
                  \def\mem@tl@unitperpt{0.0778809}
                \else
                  \@memerror{Unknown unit '#1' not suitable for layout listing}{}
                \fi
              \fi
            \fi
          \fi
        \fi
      \fi
    \fi
  \fi
}
%    \end{macrocode}
% Default value is \texttt{pt}, other supported are \texttt{mm},
% \texttt{cm}, \texttt{in}, \texttt{bp}, \texttt{dd} and \texttt{cc}.
%    \begin{macrocode}
\settypeoutlayoutunit{pt}
%    \end{macrocode}
% To help with the typesetting, we need to helper macros:
%    \begin{macrocode}
\newcommand\mem@typeouttwolengths[4]{
  % #1 = text before
  % #2 = first length
  % #3 = text between
  % #4 = second length
  \setlength\@tempdimc{\mem@tl@unitperpt #2}
  \edef\l@first{\strip@pt\@tempdimc}% 
  \setlength\@tempdimc{\mem@tl@unitperpt #4}
  \edef\l@second{\strip@pt\@tempdimc}% 
  \typeout{#1: \l@first\mem@tl@unit\space#3\space\l@second\mem@tl@unit}
}
\newcommand\mem@typeoutonelength[2]{
  % #1 = text before
  % #2 = first length
  \setlength\@tempdimc{\mem@tl@unitperpt #2}
  \edef\l@first{\strip@pt\@tempdimc}% 
  \typeout{#1: \l@first\mem@tl@unit}
}
%    \end{macrocode}
% Thirdly \cs{typeoutlayout} need to be rewritten to take care of the
% extra convertions
%    \begin{macrocode}
\newcommand*{\typeoutlayout}{%
  \typeout{}
  \typeout{******************************************************}
 %   \typeout{Stock height and width: 
 %                  \the\stockheight\space by \the\stockwidth}
 %   \typeout{Top and edge trims: 
 %                  \the\trimtop\space and \the\trimedge}
 %   \typeout{Page height and width: 
 %                  \the\paperheight\space by \the\paperwidth}
 %   \typeout{Text height and width: 
 %                  \the\textheight\space by \the\textwidth}
 %   \typeout{Spine and edge margins: 
 %                  \the\spinemargin\space and \the\foremargin}
 %   \typeout{Upper and lower margins: 
 %                  \the\uppermargin\space and \the\lowermargin}
 %   \typeout{Headheight and headsep: 
 %                  \the\headheight\space and \the\headsep}
 %   \typeout{Footskip: 
 %                  \the\footskip}
 %   \typeout{Columnsep and columnseprule: 
 %                  \the\columnsep\space and \the\columnseprule}
 %   \typeout{Marginparsep and marginparwidth: 
 %                  \the\marginparsep\space and \the\marginparwidth}
 %   \typeout{Sidecapsep and sidecapwidth:
 %                   \the\sidecapsep\space and \the\sidecapwidth}
 %   \typeout{Sidebarhsep and sidebarwidth:
 %                   \the\sidebarhsep\space and \the\sidebarwidth}
 %   \typeout{Sidebarvsep and sidebartopsep:
 %                   \the\sidebarvsep\space and \the\sidebartopsep}
 %   \typeout{Sidebarheight:
 %                   \the\dimen\sideins}
 %   \typeout{Sidefoothsep and sidefootwidth:
 %                   \the\sidefoothsep\space and \the\sidefootwidth}
 %   \typeout{Sidefootvsep and sidefootheight:
 %                   \the\sidefootvsep\space and \the\sidefootheight}
  \mem@typeouttwolengths{Stock height and width}{\stockheight}{by}{\stockwidth}
  \mem@typeouttwolengths{Top and edge trims}{\trimtop}{and}{\trimedge}
  \mem@typeouttwolengths{Page height and width}{\paperheight}{by}{\paperwidth}
  \mem@typeouttwolengths{Text height and width}{\textheight}{by}{\textwidth}
  \mem@typeouttwolengths{Spine and edge margins}{\spinemargin}{and}{\foremargin}
  \mem@typeouttwolengths{Upper and lower margins}{\uppermargin}{and}{\lowermargin}
  \mem@typeouttwolengths{Headheight and headsep}{\headheight}{and}{\headsep}
  \mem@typeoutonelength{Footskip}{\footskip}
  \mem@typeouttwolengths{Columnsep and columnseprule}{\columnsep}{and}{\columnseprule}
  \mem@typeouttwolengths{Marginparsep and marginparwidth}{\marginparsep}{and}{\marginparwidth}
  \mem@typeouttwolengths{Sidecapsep and sidecapwidth}{\sidecapsep}{and}{\sidecapwidth}
  \mem@typeouttwolengths{Sidebarhsep and sidebarwidth}{\sidebarhsep}{and}{\sidebarwidth}
  \mem@typeouttwolengths{Sidebarvsep and sidebartopsep}{\sidebarvsep}{and}{\sidebartopsep}
  \mem@typeoutonelength{Sidebarheight}{\dimen\sideins}
  \mem@typeouttwolengths{Sidefoothsep and sidefootwidth}{\sidefoothsep}{and}{\sidefootwidth}
  \mem@typeouttwolengths{Sidefootvsep and sidefootheight}{\sidefootvsep}{and}{\sidefootheight}
  \typeout{******************************************************}
  \typeout{}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\checkandfixthelayout}
% This macro checks and fixes the layout, and reports the result. It takes the
% same optional argument as \cs{checkthelayout}.
% \changes{v0.2}{2001/06/03}{Replaced \cs{fixpagelayout} by \cs{checkandfixthelayout}}
% \changes{v1.0a}{2002/01/18}{Partitioned \cs{checkandfixthelayout}}
% \changes{v1.61803}{2008/01/30}{Changed \cs{checkandfixthelayout}
%          for the extended \cs{checkthelayout} (mempatch v4.5)}
%    \begin{macrocode}
\newcommand*{\checkandfixthelayout}[1][classic]{%
  \checkthelayout[#1]%
  \fixthelayout
  \typeoutlayout}

%    \end{macrocode}
% \end{macro}
%
% 
% \begin{macro}{\mem@fixpagelayout}
% \changes{v3.7g}{2018/03/09}{Changed to use this instead of
% \cs{fixpdflayout} and \cs{fixdvipslayout}, then we no longer need \Lpack{luatex85}}
% Outputting the size of the output document. This is a little tricky as
% the various engines do not quite agree on which variables to use. As
% of 2018 we will be using this: First of \cs{pdfpageheight/width} is
% used by pdf(e)tex based enginges. We set them if they are
% defined. Just incase someone need to be able to patch this, we make
% it into a macro and just run it at the start of the cocument
%    \begin{macrocode}
\newcommand\mem@fixpagelayout{%
  \@ifundefined{pdfpageheight}{}{\pdfpageheight=\the\stockheight}
  \@ifundefined{pdfpagewidth}{}{\pdfpagewidth=\the\stockwidth}
%    \end{macrocode}
% Next comes the two macros that recent luaTeX versions use instead of
% the \cs{pdf...} equivalents.
%    \begin{macrocode}
  \@ifundefined{pageheight}{}{\pageheight=\the\stockheight}
  \@ifundefined{pagewidth}{}{\pagewidth=\the\stockwidth}
%    \end{macrocode}
% If is unclear why these were added to the class sources in the first
% place, we'll just leave them.
%    \begin{macrocode}
  \@ifundefined{pdfvorigin}{}{\ifdim\pdfvorigin=0pt\pdfvorigin=1in\fi}
  \@ifundefined{pdfhorigin}{}{\ifdim\pdfhorigin=0pt\pdfhorigin=1in\fi}
%    \end{macrocode}
% Lastly we need to output a special to the DVI, but other engines can
% also understand specials, so to not end up getting those pesky
% non-PDF special warnings, we need some engine tests before emiting
% the data to the DVI.
%    \begin{macrocode}
  \ifluatex\else
    \ifxetex\else
      \ifpdf\else
        \AtBeginDvi{\special{papersize=\the\stockwidth,\the\stockheight}}
      \fi
    \fi
  \fi    
}

\AtBeginDocument{\mem@fixpagelayout}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\fixpdflayout}
% \begin{macro}{\fixdvipslayout}
% As of 2018 these are disabled
% ^^A % Page layout with pdf\LaTeX{} seems a bit iffy.
% ^^A % At the suggestion of Lars Madsen, help with 
% ^^A % setting viewer (e.g., ghostview)
% ^^A % window sizes for dvi/ps. \cs{fixdvipslayout} does for \file{dvi} output
% ^^A % as \cs{fixpdflayout} does for \file{pdf} output.
% \changes{v1.4}{2003/11/22}{Added \cs{fixpdflayout} (from patch v1.6)}
% \changes{v1.4}{2003/12/01}{Added \cs{fixdvipslayout} }
% \changes{v1.61803398}{2009/08/17}{on ctt dynamotwain suggested a
% change to \cs{fixpdflayout} and the following \cs{AtBeginDocument}
% such that the \cs{special} is not outputtet when running xelatex}
%    \begin{macrocode}
\newcommand*{\fixpdflayout}{%
  \ClassWarning{memoir}{As of 2018, \string\fixpdflayout\ is no longer used}
 % \pdfpageheight=\the\stockheight
 % \pdfpagewidth=\the\stockwidth
 % \ifxetex\else
 % \ifdim\pdfvorigin=0pt\pdfvorigin=1in\fi
 % \ifdim\pdfhorigin=0pt\pdfhorigin=1in\fi
 % \fi
}
\newcommand*{\fixdvipslayout}{%
  \ClassWarning{memoir}{As of 2018, \string\fixdvipslayout\ is no longer used}
  %\AtBeginDvi{\special{papersize=\the\stockwidth,\the\stockheight}}
}
%    \end{macrocode}

% ^^A % \AtBeginDocument{%
% ^^A %   \ifxetex
% ^^A %     \fixpdflayout
% ^^A %   \else
% ^^A %     \ifpdf
% ^^A %       \ifnum\pdfoutput<\@ne
% ^^A %         \fixdvipslayout
% ^^A %       \else
% ^^A %         \fixpdflayout
% ^^A %       \fi
% ^^A %     \else
% ^^A %       \fixdvipslayout
% ^^A %     \fi
% ^^A %   \fi}

%
% ^^A % With a landscape document when going \texttt{latex -> dvips} the 
% ^^A % resulting \file{.ps} file
% ^^A % may apear upside down in \texttt{ghostview}. If this happens, try putting
% ^^A % the following in the document preamble:
% ^^A % \begin{verbatim}
% ^^A % \addtodef{\fixdvipslayout}{}{%
% ^^A %   \special{!TeXDict begin /landplus90{true}store end }}
% ^^A % \end{verbatim}
% ^^A % See \texttt{http://www.radicaleye.com.dvips.html} (DVIPS Home Page) for
% ^^A % an explanation.
% ^^A %
% ^^A %  Some other potential specials for PostScript printing may be 
% ^^A % (at least for an HP 5SiMx LaserJet duplex printer):
% ^^A % \begin{verbatim}
% ^^A % \special{!TeXDict begin <</Duplex true>> 
% ^^A %                         setpagedevice end} % duplex
% ^^A % \special{!TeXDict begin <</Tumble true>> 
% ^^A %                         setpagedevice end} % short side binding
% ^^A % \end{verbatim}
% \end{macro}
% \end{macro}
%
% 
% \begin{macro}{\typeoutstandardlayout}
% Types out the current values of the standard page layout parameters.
% \changes{v1.0a}{2002/01/25}{Added \cs{typeoutstandardlayout}}
% \changes{v3.6g}{2010/09/17}{changed such that the user can change
% the unit being used}
%    \begin{macrocode}
\newcommand{\typeoutstandardlayout}{%
  \typeout{}
  \typeout{******************************************************}
 %   \typeout{Page height and width: 
 %                 \the\paperheight\space by \the\paperwidth}
 \mem@typeouttwolengths{Page height and width}{\paperheight}{by}{\paperwidth}
 %   \typeout{Text height and width: 
 %                \the\textheight\space by \the\textwidth}
 \mem@typeouttwolengths{Text height and width}{\textheight}{by}{\textwidth}
 %   \typeout{Oddside and evenside margins: 
 %                 \the\oddsidemargin\space and \the\evensidemargin}
 \mem@typeouttwolengths{Oddside and evenside margins}{\oddsidemargin}{and}{\evensidemargin}
 %   \typeout{Topmargin and footskip: 
 %                 \the\topmargin\space and \the\footskip}
 \mem@typeouttwolengths{Topmargin and footskip}{\topmargin}{and}{\footskip}
 %   \typeout{Headheight and headsep: 
 %                 \the\headheight\space and \the\headsep}
 \mem@typeouttwolengths{Headheight and headsep}{\headheight}{and}{\headsep}
 %   \typeout{Columnsep and columnseprule: 
 %                 \the\columnsep\space and \the\columnseprule}
 \mem@typeouttwolengths{Columnsep and columnseprule}{\columnsep}{and}{\columnseprule}
 %   \typeout{Marginparsep and marginparwidth: 
 %                 \the\marginparsep\space and \the\marginparwidth}
 \mem@typeouttwolengths{Marginparsep and marginparwidth}{\marginparsep}{and}{\marginparwidth}
  \typeout{******************************************************}
  \typeout{}
}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Some predefined layouts}
%
% A few predefined layouts for the textblock are presented. The \cs{checkandfixthelayout}
% macro \emph{must} be called afterwards.
%
% \begin{macro}{\medievalpage}
% This implements Jan Tschichold's reconstruction of the page and textblock
% layout used by medieval scribes and the early printers~\cite{}.
% The spine, top, edge and bottom margins are in the ratios 2:3:4:6.
%
% \cs{medievalpage}\oarg{num} positions the typeblock on the page with the
% margins in the above ratios. The spine margin is (page width)/\meta{num} 
% (default 9). This must be an integer.
% \changes{v1.61803}{2008/01/30}{Added \cs{medievalpage}}
%    \begin{macrocode}
%%%% s = w/#1, t = 1.5s, e = 2s, f = 3s
\newcommand*{\medievalpage}[1][9]{%
  \spinemargin=\paperwidth
  \divide\spinemargin #1\relax
  \uppermargin = 1.5\spinemargin
  \setlrmarginsandblock{\spinemargin}{*}{2}
  \setulmarginsandblock{\uppermargin}{*}{2}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\isopage}
% An implementation of Bringhurst's layout for ISO proportioned pages.
% It works for any page though. The edge margin is twice the spine,
% and the bottom margin is twice the top. 
%
% \cs{isopage}\oarg{num} positions and sizes the typeblock on the page
% according to the above ratios. The spine is (page width)/\meta{num}
% and the top margin id (page height)/\meta{num}. \meta{num} must be
% an integer.
% \changes{v1.61803}{2008/01/30}{Added \cs{isopage}}
%    \begin{macrocode}
% s = w/#1, e = 2s, t = h/#1, f = 2h
\newcommand*{\isopage}[1][9]{%
  \spinemargin=\paperwidth
  \divide\spinemargin #1\relax
  \uppermargin=\paperheight
  \divide\uppermargin #1\relax
  \setlrmarginsandblock{\spinemargin}{*}{2}
  \setulmarginsandblock{\uppermargin}{*}{2}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\semiisopage}
% An variation on Bringhurst's layout for ISO proportioned pages.
% It works for any page though. The top margin is the same as the spine,
% and the edge and bottom margins are twice the spine.
%
% \cs{semiisopage}\oarg{num} positions and sizes the typeblock on the page
% according to the above ratios. The spine is (page width)/\meta{num}.
% \meta{num} must be  an integer.
% \changes{v1.61803}{2008/01/30}{Added \cs{isopage}}
%    \begin{macrocode}
%%% s = w/#1, t = s, e = 2s, f = e
\newcommand*{\semiisopage}[1][9]{%
  \spinemargin=\paperwidth
  \divide\spinemargin #1\relax
  \uppermargin=\spinemargin
  \setlrmarginsandblock{\spinemargin}{*}{2}
  \setulmarginsandblock{\uppermargin}{*}{2}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setpagebl}
% \begin{macro}{\setpageml}
% \begin{macro}{\setpagetl}
% \begin{macro}{\setpagetm}
% \cs{setpagebl}\marg{height}\marg{width}\marg{ratio} sets a page smaller than
% the stock size at the bottom left of the stock. The arguments are the
% the same as for \cs{settrimmedsize};
% \meta{height}, \meta{width} and \meta{ratio} of height and width 
% (choose any two) of the desired page size. The trims are adjusted to suit.
% \cs{setpagetl} puts the page at the top left, \cs{setpageml} at the
% middle left, and \cs{setpagetm} at the top middle.
% \changes{v1.61803}{2008/01/30}{Added \cs{setpagebl}, \cs{setpageml}, and
%                    \cs{setpagetl}}
% \changes{v1.6180339c}{2008/12/26}{Added \cs{setpagetm}}
%    \begin{macrocode}
\newcommand*{\setpagebl}[3]{%
  \settrimmedsize{#1}{#2}{#3}%
  \trimtop=\stockheight \advance\trimtop -\paperheight
  \trimedge=\stockwidth \advance\trimedge -\paperwidth}
\newcommand*{\setpageml}[3]{%
  \settrimmedsize{#1}{#2}{#3}
  \trimtop=\stockheight \advance\trimtop -\paperheight 
    \advance\trimtop -0.5\trimtop
  \trimedge=\stockwidth \advance\trimedge -\paperwidth}
\newcommand*{\setpagetl}[3]{%
  \settrimmedsize{#1}{#2}{#3}
  \trimtop=0pt
  \trimedge=\stockwidth \advance\trimedge -\paperwidth}
\newcommand*{\setpagetm}[3]{%
  \settrimmedsize{#1}{#2}{#3}%
  \trimtop=0pt
  \trimedge=\stockwidth \advance\trimedge -\paperwidth
  \advance\trimedge -0.5\trimedge}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setpagetr}
% \begin{macro}{\setpagemr}
% \begin{macro}{\setpagebr}
% \begin{macro}{\setpagebm}
% \begin{macro}{\setpagecc}
% Similar to those above, these macros set the page on the stock
% at the top right, middle right, bottom right, bottom middle, and centered.
% \changes{v1.6180339c}{2008/12/26}{Added \cs{setpagetr}, \cs{setpagemr}, \cs{setpagebr},
%                       \cs{setpagebm} and \cs{setpagecc}}
%    \begin{macrocode}
\newcommand*{\setpagetr}[3]{%
  \settrimmedsize{#1}{#2}{#3}%
  \trimtop=0pt
  \trimedge=0pt}
\newcommand*{\setpagemr}[3]{%
  \settrimmedsize{#1}{#2}{#3}%
  \trimtop=\stockheight \advance\trimtop -\paperheight
    \advance\trimtop -0.5\trimtop
  \trimedge=0pt}
\newcommand*{\setpagebr}[3]{%
  \settrimmedsize{#1}{#2}{#3}%
  \trimtop=\stockheight  \advance\trimtop -\paperheight
  \trimedge=0pt}
\newcommand*{\setpagebm}[3]{%
  \settrimmedsize{#1}{#2}{#3}%
  \trimtop=\stockheight \advance\trimtop -\paperheight
  \trimedge=\stockwidth \advance\trimedge -\paperwidth
    \advance\trimedge -0.5\trimedge}
\newcommand*{\setpagecc}[3]{%
  \settrimmedsize{#1}{#2}{#3}%
  \trimtop=\stockheight \advance\trimtop -\paperheight
    \advance\trimtop -0.5\trimtop
  \trimedge=\stockwidth \advance\trimedge -\paperwidth
    \advance\trimedge -0.5\trimedge}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%
% \subsection{Float placement parameters}
%
%
% All float parameters are given default values in the \LaTeX{}
% kernel. For this reason counters only need to be set with
% \cs{setcounter} and other parameters are set using \cs{renewcommand}.
%
% \paragraph{Limits for the placement of floating objects}
%
% The settings here make it easier to place floats than with the
% standard classes.
%
% \begin{macro}{\c@topnumber}
%    The \Lcount{topnumber} counter holds the maximum number of
%    floats that can appear on the top of a text page (classically 2)
%    \begin{macrocode}
\setcounter{topnumber}{3}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\topfraction}
%    This indicates the maximum part of a text page that can be
%    occupied by floats at the top (classically 0.7).
%    \begin{macrocode}
\renewcommand{\topfraction}{.85}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\c@bottomnumber}
%    The \Lcount{bottomnumber} counter holds the maximum number of
%    floats that can appear on the bottom of a text page (classically 1).
%    \begin{macrocode}
\setcounter{bottomnumber}{2}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\bottomfraction}
%    This indicates the maximum part of a text page that can be
%    occupied by floats at the bottom (classically 0.3).
%    \begin{macrocode}
\renewcommand{\bottomfraction}{.5}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\c@totalnumber}
%    This indicates the maximum number of floats that can appear on
%    any text page (classically 3).
%    \begin{macrocode}
\setcounter{totalnumber}{4}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\textfraction}
%    This indicates the minimum part of a text page that has to be
%    occupied by text (classically 0.2).
%    \begin{macrocode}
\renewcommand{\textfraction}{.1}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\floatpagefraction}
%    This indicates the minimum part of a page that has to be
%    occupied by floating objects before a `float page' is 
%    produced (classically 0.5).
%    \begin{macrocode}
\renewcommand{\floatpagefraction}{.7}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\c@dbltopnumber}
%    The \Lcount{dbltopnumber} counter holds the maximum number of
%    two column floats that can appear on the top of a two column text
%    page (classically 2).
%    \begin{macrocode}
\setcounter{dbltopnumber}{3}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\dbltopfraction}
%    This indicates the maximum part of a two column text page that
%    can be occupied by two column floats at the top (classically 0.7).
%    \begin{macrocode}
\renewcommand{\dbltopfraction}{.85}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\dblfloatpagefraction}
%    This indicates the minimum part of a page that has to be
%    occupied by two column wide floating objects before a `float
%    page' is produced (classically 0.5).
%    \begin{macrocode}
\renewcommand{\dblfloatpagefraction}{.7}
%    \end{macrocode}
% \end{macro}
%
%
% \section{Page Styles}
%
%    The page style \pstyle{foo} is defined by defining the command
%    \cs{ps@foo}.   This command should make only local definitions.
%    There should be no stray spaces in the definition, since they
%    could lead to mysterious extra spaces in the output.
%
% \begin{macro}{\@evenhead}
% \begin{macro}{\@oddhead}
% \begin{macro}{\@evenfoot}
% \begin{macro}{\@oddfoot}
%    The \cs{ps@...} command defines the macros \cs{@oddhead},
%    \cs{@oddfoot}, \cs{@evenhead}, and \cs{@evenfoot} to define the running
%    heads and feet---e.g., \cs{@oddhead} is the macro to produce the
%    contents of the heading box for odd-numbered pages.  It is called
%    inside an \cs{hbox} of width \cs{textwidth}.
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsection{Marking conventions}
%
%    To make headings determined by the sectioning commands, the page
%    style defines the commands \cs{chaptermark}, \cs{sectionmark},
%    \ldots,\\
%     where \cs{chaptermark}\marg{TEXT} is called by
%    \cs{chapter} to set a mark, and so on.
%
%    The \cs{...mark} commands and the \cs{...head} macros are defined
%    with the help of the following macros.  (All the \cs{...mark}
%    commands should be initialized to no-ops.)
%
%    \LaTeX{} extends \TeX's \cs{mark} facility by producing two kinds
%    of marks, a `left' and a `right' mark, using the following
%    commands:
%    \begin{flushleft}
%     \cs{markboth}\marg{LEFT}\marg{RIGHT}: Adds both marks.
%
%     \cs{markright}\marg{RIGHT}: Adds a `right' mark.
%
%     \cs{leftmark}: Used in the \cs{@oddhead}, \cs{@oddfoot}, \cs{@evenhead}
%                  or \cs{@evenfoot} macros, it gets the current `left'
%                  mark.  \cs{leftmark} works like \TeX's \cs{botmark}
%                  command.
%
%     \cs{rightmark}: Used in the \cs{@oddhead}, \cs{@oddfoot}, \cs{@evenhead}
%                   or  \cs{@evenfoot} macros, it gets the current
%                   `right' mark. \cs{rightmark} works like \TeX's
%                   \cs{firstmark} command.
%    \end{flushleft}
%
%    The marking commands work reasonably well for right marks
%    `numbered within' left marks--e.g., the left mark is changed by a
%    \cs{chapter} command and the right mark is changed by a \cs{section}
%    command.  However, it does produce somewhat anomalous results if
%    two \cs{markboth}'s occur on the same page.
%
%
%    Commands like \cs{tableofcontents} that should set the marks in some
%    page styles use a \cs{@mkboth} command, which is \cs{let} by the
%    pagestyle command (\cs{ps@...})  to \cs{markboth} for setting the
%    heading or to \cs{@gobbletwo} to do nothing.
%
%
%
% \subsection{Defining the page styles}
%
%    This class provides a set of commands for the user to define new
% pagestyles. Essentially defining a pagestyle consists of defining the
% macros \cs{@evenhead}, \cs{@oddhead}, \cs{@evenfoot}, and \cs{@oddfoot}.
% For this class, each header and footer is treated as three parts: a left,
% center, and right part. In this case, defining a pagestyle consists of
% specifying these 12 portions of the running headers and footers. The
% width of the headers/footers may also be specified, rules may be drawn
% below the headers and/or above the footers, and the complete header and/or
% footer may be offset with respect to the textblock when the width is not
% the same as the textwidth.
%
%    In the following \meta{style} is the name of a pagestyle being defined
% (e.g., \verb?ruled?).
% 
% \changes{v1.61803398d}{2010/02/09}{Added the following three macros}
% \begin{macro}{\mem@set@ps@xtra@info}
% \begin{macro}{\mem@ps@find@real}
% \begin{macro}{\mem@ps@safe@change}
% The class supports an aliasing feature, where a page style name can
% actually call the code from another. Quite handy. But There might be
% problems if a use try to modify an alias page style. We care for
% this by storing some information about each page style, and throwing
% an error if the user atempts to alter a page style marked as an
% alias.
% 
% \verb?\mem@set@ps@xtra@info? store two things: the name of the style
% we are an alias for (if we are not an alias it will be blank) and an
% indicator whether we are an alias (00 if we are and 01 if we are not).
%    \begin{macrocode}
\newcommand\mem@set@ps@xtra@info[3]{%
  \@namedef{ps@#1@aliasfor}{#2}%
  \@namedef{ps@#1@isalias}{#3}}

%    \end{macrocode}
% \verb?\mem@ps@find@real? starts at a given page style, if it is
% marked as an alias, it will recursively go down the chain of aliases
% and save the name of the first real page style in \verb?\@tempa?.
%    \begin{macrocode}
\newcommand\mem@ps@find@real[1]{%
  \if\@nameuse{ps@#1@isalias}\relax
  \mem@ps@find@real{\@nameuse{ps@#1@aliasfor}}
  \else\def\@tempa{#1}\fi}

%    \end{macrocode}
% \verb?\mem@ps@safe@change? takes a page style name, checks to see if
% it is defined, if it is, it checks to see if it is safe to change
% it.
% \changes{v3.7c}{2014/05/20}{Typo reported by Werner Grundlingh}
%    \begin{macrocode}
\newcommand\mem@ps@safe@change[1]{%
 \@ifundefined{ps@#1}{%
    \@memerror{Undefined pagestyle '#1', so I cannot change it}{}}{}
  \if\@nameuse{ps@#1@isalias}\relax \mem@ps@find@real{#1}
  \@memerror{The pagestyle '#1' is marked as an alias page style.^^J
    Modifying an alias page style may give unexpected results.^^J The
    alias chain resolves to the real page style '\@tempa', so try
    issuing^^J \string\copypagestyle{#1}{\@tempa}^^J
    before modifying '#1'}{} \fi }

%    \end{macrocode}
%
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\makeevenhead}
% The command 
% \cs{makeevenhead}\marg{style}\marg{left}\marg{center}\marg{right}
% specifies that the left, center and right portions of the even header for
% pagestyle \meta{style} are defined as the other three arguments, respectiveley.
% Internally it defines the commands \cs{styleeheadl}, \cs{styleeheadc} and
% \cs{styleeheadr} to be \meta{left}, \meta{center} and \meta{right} respectively.
% \changes{v1.61803398d}{2010/02/09}{Added safe change test}
%    \begin{macrocode}
\newcommand{\makeevenhead}[4]{%
  \mem@ps@safe@change{#1}
  \@namedef{#1eheadl}{#2}
  \@namedef{#1eheadc}{#3}
  \@namedef{#1eheadr}{#4}
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makeoddhead}
% \begin{macro}{\makeevenfoot}
% \begin{macro}{\makeoddfoot}
%  These three macros are similar to \cs{makeevenhead} except that they are
% for the oddhead, evenfoot and oddfoot.
% \changes{v1.61803398d}{2010/02/09}{Added safe change test}
%    \begin{macrocode}
\newcommand{\makeoddhead}[4]{%
  \mem@ps@safe@change{#1}
  \@namedef{#1oheadl}{#2}
  \@namedef{#1oheadc}{#3}
  \@namedef{#1oheadr}{#4}
}
\newcommand{\makeevenfoot}[4]{%
  \mem@ps@safe@change{#1}
  \@namedef{#1efootl}{#2}
  \@namedef{#1efootc}{#3}
  \@namedef{#1efootr}{#4}
}
\newcommand{\makeoddfoot}[4]{%
  \mem@ps@safe@change{#1}
  \@namedef{#1ofootl}{#2}
  \@namedef{#1ofootc}{#3}
  \@namedef{#1ofootr}{#4}
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\makerunningwidth}
% \begin{macro}{\makerunningheadwidth}
% \begin{macro}{\makerunningfootwidth}
% \begin{macro}{\m@mhfstyle}
% \begin{macro}{\m@mopthfwidth}
%  The macro \cs{makerunningwidth}\marg{style}\oarg{ftlength}\marg{length} 
% sets the
% width of the headers and footers of pagestyle \meta{style} to 
% be \meta{length}, but if \meta{ftlength} is present the footer
% width is set to \meta{ftlength}. The lengths are stored as the
% macros \cs{styleheadrunwidth} and \cs{stylefootrunwidth}. The two
% widths can be set individually using
% \cs{makerunningheadwidth}\marg{style}\marg{length} and
% \cs{makerunningfootwidth}\marg{style}\marg{length}. 
% \changes{v1.6180339c}{2008/12/26}{Enabled the width of headers and footers 
%                       to be different 
%                       (requested by Wilhelm M\"{u}ller).}
% \changes{v1.6180339c}{2009/01/13}{Added \cs{makerunningheadwidth}
% and \cs{makerunningfootwidth}}.
% \changes{v1.6180339d}{2009/02/04}{Fixed a mental bug, /daleif}
% \changes{v1.61803398d}{2010/02/09}{Added safe change test}
%    \begin{macrocode}
\newcommand*{\makerunningwidth}[1]{%
  \mem@ps@safe@change{#1}%
  \def\m@mhfstyle{#1}%
  \m@mopthfwidth}
\newcommand*{\m@mopthfwidth}[2][\@mpty]{%
%  \setlength\@tempdima{#2}
  \@namedef{\m@mhfstyle headrunwidth}{#2}%
%  \expandafter\edef\csname \m@mhfstyle headrunwidth\endcsname{\the\@tempdima}
  \ifx\@mpty #1
    \@namedef{\m@mhfstyle footrunwidth}{#2}%
%    \expandafter\edef\csname \m@mhfstyle footrunwidth\endcsname{\the\@tempdima}
  \else
    \@namedef{\m@mhfstyle footrunwidth}{#1}%
%    \setlength\@tempdima{#1}
%    \expandafter\edef\csname \m@mhfstyle footrunwidth\endcsname{\the\@tempdima}
  \fi}
\newcommand*{\makerunningheadwidth}[2]{%
%  \setlength\@tempdima{#2}%
%  \expandafter\edef\csname \m@mhfstyle headrunwidth\endcsname{\the\@tempdima}%
  \mem@ps@safe@change{#1}%
  \@namedef{#1headrunwidth}{#2}%
}
\newcommand*{\makerunningfootwidth}[2]{%
%  \setlength\@tempdima{#2}%
  \mem@ps@safe@change{#1}%
  \@namedef{#1footrunwidth}{#2}%
%  \expandafter\edef\csname \m@mhfstyle footrunwidth\endcsname{\the\@tempdima}%
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\normalrulethickness}
% \begin{macro}{\footruleheight}
% \begin{macro}{\footruleskip}
% \begin{macro}{\makeheadrule}
% \begin{macro}{\makefootrule}
% \cs{normalrulethickness} is the thickness of a normal horizontal 
% or vertical rule. 
% \cs{footruleheight} is the height of a normal rule above a footer (actually zero).
% \cs{footruleskip} is a distance sufficient to ensure that a foot rule 
% will appear between the bottom of the textblock and above any actual footer.
%
% (There was a \ctt{} thread \textit{ngerman, fancyhdr and \cs{footrulewidth} --- bug?}
%  in December 2002 that bears on the definitions below).
% \changes{v1.4}{2003/02/27}{Make \cs{normalrulethickness} a length, 
%                            not a macro (patch 1.1)}
% \changes{v1.4}{2003/02/27}{Initialise \cs{footruleheight} to 0pt, not
%                            \cs{z@skip} (patch 1.1)}
%    \begin{macrocode}
\newlength{\normalrulethickness}
  \setlength{\normalrulethickness}{0.4pt}
\newcommand{\footruleheight}{0pt}
\newcommand{\footruleskip}{0.3\normalbaselineskip}
%    \end{macrocode}
% The macro \cs{makeheadrule}\marg{style}\marg{width}\marg{height}
% specifies the width and height of the header rule for \meta{style}. 
%
% Similarly
% \cs{makefootrule}\marg{style}\marg{width}\marg{height}\marg{skip}
% specifies the width, height and skip for the footrule.
% \changes{v1.61803398d}{2010/02/09}{Added safe change test}
% \changes{v3.7d}{2015/04/22}{Moved \cs{...(head|foot)ruleprefix} out and
% added them else where}
%    \begin{macrocode}
\newcommand{\makeheadrule}[3]{%
  \mem@ps@safe@change{#1}%
  \@namedef{#1headrule}{%
    \hrule\@width #2\@height #3 \vskip-#3}}
\newcommand{\makefootrule}[4]{%
  \mem@ps@safe@change{#1}%
  \@namedef{#1footrule}{%
    \vskip-#4\vskip-#3%
    \hrule\@width #2\@height #3 \vskip #4}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%  
% \changes{v3.6h}{2011/01/25}{Added this macro}
% \begin{macro}{\makeheadfootruleprefix}
% We insert a maro at the start of the head and foot rule. By default
% it does nothing, but it can be ised to specify a different color to
% the head or foot rules.
%    \begin{macrocode}
\newcommand\makeheadfootruleprefix[3]{%
  \@namedef{#1headruleprefix}{#2}%
  \@namedef{#1footruleprefix}{#3}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makeheadposition}
% \cs{makeheadposition}\marg{style}\marg{eheadpos}\marg{oheadpos}\marg{efootpos}\marg{ofootpos}
% specifies the horizontal positioning of the even and odd headers and footers,
% respectively, 
% for the pagestyle \meta{style}. Each of the \meta{...pos} arguments may be
% either \verb?flushleft?, \verb?center? or \verb?flushright?, with the obvious meanings.
% An empty argument (or an unrecognised one) is equivalent to \verb?center?.
% \changes{v1.61803398d}{2010/02/09}{Added safe change test}
%    \begin{macrocode}
\newcommand{\makeheadposition}[5]{%
  \mem@ps@safe@change{#1}%
%    \end{macrocode}
% Do the even head position first.
%    \begin{macrocode}
  \nametest{flushleft}{#2}
  \ifsamename
    \@namedef{#1evenheadpl}{\relax} \@namedef{#1evenheadpr}{\hss}
  \else
    \nametest{flushright}{#2}
    \ifsamename
      \@namedef{#1evenheadpl}{\hss} \@namedef{#1evenheadpr}{\relax}
    \else
      \@namedef{#1evenheadpl}{\hss} \@namedef{#1evenheadpr}{\hss}
    \fi
  \fi
%    \end{macrocode}
% And similarly for the odd head and even \& odd footers.
%    \begin{macrocode}   
  \nametest{flushleft}{#3}
  \ifsamename
    \@namedef{#1oddheadpl}{\relax} \@namedef{#1oddheadpr}{\hss}
  \else
    \nametest{flushright}{#3}
    \ifsamename
      \@namedef{#1oddheadpl}{\hss} \@namedef{#1oddheadpr}{\relax}
    \else
      \@namedef{#1oddheadpl}{\hss} \@namedef{#1oddheadpr}{\hss}
    \fi
  \fi
  \nametest{flushleft}{#4}
  \ifsamename
    \@namedef{#1evenfootpl}{\relax} \@namedef{#1evenfootpr}{\hss}
  \else
    \nametest{flushright}{#4}
    \ifsamename
      \@namedef{#1evenfootpl}{\hss} \@namedef{#1evenfootpr}{\relax}
    \else
      \@namedef{#1evenfootpl}{\hss} \@namedef{#1evenfootpr}{\hss}
    \fi
  \fi
  \nametest{flushleft}{#5}
  \ifsamename
    \@namedef{#1oddfootpl}{\relax} \@namedef{#1oddfootpr}{\hss}
  \else
    \nametest{flushright}{#5}
    \ifsamename
      \@namedef{#1oddfootpl}{\hss} \@namedef{#1oddfootpr}{\relax}
    \else
      \@namedef{#1oddfootpl}{\hss} \@namedef{#1oddfootpr}{\hss}
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makepsmarks}
% \begin{macro}{\makepshook}
% The macro \cs{makepsmarks}\marg{style}\marg{code} specifies that
% \meta{code} is the definition of the hook for pagestyle \meta{style}.
% \cs{makepshook} was a deprecated version of \cs{makepsmarks} and is
% now deleted.
% \changes{v1.0}{2001/11/15}{Added \cs{makepsmarks} and deprecated 
%                                  \cs{makepshook}}
% \changes{v1.4}{2003/12/14}{Deleted \cs{makepshook}}
% \changes{v1.61803398d}{2010/02/09}{Added safe change test}
%    \begin{macrocode}
\newcommand{\makepsmarks}[2]{\mem@ps@safe@change{#1}\@namedef{#1pshook}{#2}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mhe@dreset}
% To cater for potential baselineskip changes, such as \verb?\linespread{2}?,
% we have to ensure they don't percolate into the header/footer.
% (See CTT thread \textit{memoir + linespread}, 2004/02/11)
% \changes{v1.61}{2004/03/14}{Added \cs{m@mhe@dreset}}
%    \begin{macrocode}
\newcommand*{\m@mhe@dreset}{\def\baselinestretch{1}\normalsize}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makeheadfootvposition}
%   The headers and footers are typeset inside \cs{parbox}'es, using
%   \cs{makeheadfootvposition}\marg{style}\marg{headvpos}\marg{footvpost}
%   users can specify whether the alignment should be b,t or~c.The
%   default is~b.
%   \changes{v1.6180339c}{2009/01/13}{Added support for 
%   controlling the alignment of the headers and footers}
% \changes{v1.61803398d}{2010/02/09}{Added safe change test}
%    \begin{macrocode}
\newcommand*\makeheadfootvposition[3]{%
  \mem@ps@safe@change{#1}%
  \@namedef{#1headvplacement}{#2}\@namedef{#1footvplacement}{#3}}

%    \end{macrocode}
% \end{macro}
% \begin{macro}{\mem@maxheadheight}
% \begin{macro}{\mem@maxfootheight}
% \begin{macro}{\mem@sayonce@head}
% \begin{macro}{\mem@sayonce@foot}
% \begin{macro}{\mem@hf@measure@vbox}
% \begin{macro}{\mem@toolarge@header@message}
% \begin{macro}{\mem@toolarge@footer@message}
% \changes{v3.6h}{2010/10/21}{Added the above seven macros to be able
% to measure the headers and warn users if their design takes them outside.}  
% \verb?\mem@maxheadheight? and \verb?\mem@maxfootheight? globally
% stores the max measured head and foot heights. Actually the footer
% ought to be measuring the total height and depth. We may add this
% later. The two XsayonceX macros are toggles used such that we can
% add a warning at only the first bad head/foot. We repeat the message
% at the end of the document.
%    \begin{macrocode}
\newlength\mem@maxheadheight
\newlength\mem@maxfootheight
\newcommand\mem@sayonce@head{00}
\newcommand\mem@sayonce@foot{00}
%    \end{macrocode}
% This is the work horse of this construction. First argument is the
% height to compare against, second should be \texttt{head} or
% \texttt{foot}, third is the warning message, and the fourth is the
% material to be measured. The idea to taken from \Lpack{fancyhdr}.
%    \begin{macrocode}
\newcommand\mem@hf@measure@vbox[4]{%
  \setbox0\vbox{#4}%
  \ifdim\ht0>#1\relax%
    \setlength\@tempdima{\@nameuse{mem@max#2height}}%
    \ifdim\ht0>\@tempdima\relax%
      \expandafter\global\@nameuse{mem@max#2height}=\ht0%
      \expandafter\if\@nameuse{mem@sayonce@#2}\relax%
        \@memwarn{#3}%
          \global\@namedef{mem@sayonece@#2}{01}%
      \fi%
    \fi%
  \fi%
  \box0%
}
%    \end{macrocode}
% Warning messages
%    \begin{macrocode}
\newcommand\mem@toolarge@header@message{%
  The material used in the headers is too large^^J%
  (\the\mem@maxheadheight) for the given head height
  (\the\headheight), it is recommended to^^J%
  either increase the head height or redesign the header^^J%
  (in both cases you will find help in the memoir manual).%
}
\newcommand\mem@toolarge@footer@message{%
  The material used in the footer is too large^^J%
  (\the\mem@maxfootheight) for the given foot skip
  (\the\footskip), it is recommended to^^J%
  either increase the foot skip or redesign the footer^^J%
  (in both cases you will find help in the memoir manual).%
}
%    \end{macrocode}
% To make things easier to read we make two short cut macros
%    \begin{macrocode}
\newcommand\mem@hvboxm[1]{%
  \mem@hf@measure@vbox\headheight{head}\mem@toolarge@header@message{#1}}
\newcommand\mem@fvboxm[1]{%
  \mem@hf@measure@vbox\footskip{foot}\mem@toolarge@footer@message{#1}}
%    \end{macrocode}
% Make sure to repeat the message at the end of the document. This
% will show the max value up until the point where the end of document
% stuff is executed. 
%    \begin{macrocode}
\AtEndDocument{
  \ifdim\mem@maxheadheight>\headheight
    \@memwarn{\mem@toolarge@header@message}
  \fi
  \ifdim\mem@maxfootheight>\footskip
    \@memwarn{\mem@toolarge@footer@message}
  \fi
}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\mem@ps@entry@wrap}
%   \changes{v3.6h}{2010/10/06}{Added this to help bidi control the
%   typesetting direction of the header and footer}
%   This macro is wrapped around eash entry in the headers and
%   footers. By default it does nothing, but can be redefined by
%   packages such as \Lpack{bidi} to control the typesetting direction
%   in the header. Bidi for example has two modes such that headers
%   can be RTL locally while the header stay at LTR. If this macro is
%   changed, it will be a good idea to coordinate it with the bidi
%   maintainer. 
%    \begin{macrocode}
\newcommand\mem@ps@entry@wrap{}
%    \end{macrocode}
%   
% \end{macro}
% \begin{macro}{\mem@ps@HLH}
%   \changes{v3.6d}{2010/10/06/24}{Factored \cs{makepagestyle}}
%   The entries in the header used in \cs{makepagestyle} (below) are
%   more or less the same. It depends on \emph{head/foot},
%   \emph{odd/even} and a shorter \emph{o/e}. So to make the code more
%   maintainable we factor this out into a generator macro. The
%   explanation for the code being used is kept below (see
%   \cs{makepagestyle}). 
% \changes{v3.6k}{2012/05/31}{Forgot to separate head/foot position into the
% factorization, propblem reported by Wybo Dekker on
% http://tex.stackexchange.com/q/56141/3929}
%    \begin{macrocode}
\newcommand\mem@ps@HLH[4]{%
  % #1 ps name
  % #2 type: head, foot
  % #3 odd/even
  % #4 odd/even short (o,e)
  \@namedef{#1@#3#2}{%
    \@nameuse{#1#3#2pl}\hb@xt@\@nameuse{#1#2runwidth}{\m@mhe@dreset%
%    \end{macrocode}
% In footers the line goes before the text, so we test and add the
% footline if \texttt{\#2} equals \texttt{foot}.
% \changes{v3.6h}{2010/10/06}{added the entry wrapper}
% \changes{v3.6h}{201010/10/21}{Added the header/footer measuring feature.}
% For the header/footer measuring stuff we look at \#2 and make the
% suiting macro from that value.
% \changes{v3.6h}{2010/10/22}{Added \cs{memRTLmainraggedX} macros such
% that \Lpack{bidi} can also change the order of the header if RTL is
% the main direction of the document.}
%    \begin{macrocode}
      \nametest{#2}{head}\ifsamename\let\mem@hfboxer\mem@hvboxm\else\let\mem@hfboxer\mem@fvboxm\fi%
%    \end{macrocode}
% \changes{v3.7d}{2015/04/22}{Moved \cs{...footruleprefix} outside
% \cs{...footrule}. Otherwise copy does not work correctly. Reported
% at http://tex.stackexchange.com/q/231454/3929}
%    \begin{macrocode}
      \mem@hfboxer{\nametest{#2}{foot}\ifsamename%
          \begingroup% to prevent colors from bleeding into the footer
          \@nameuse{#1#2ruleprefix}%
          \@nameuse{#1#2rule}%
          \endgroup%
        \fi%
        \hbox{%
          \rlap{%
            \parbox[\@nameuse{#1#2vplacement}]{\@nameuse{#1#2runwidth}}{%
              \memRTLmainraggedright\@nameuse{#1ps#2strut}%
              \mem@ps@entry@wrap{\@nameuse{#1#4#2l}}%
              \@nameuse{#1ps#2strut}}}\hfill
          \parbox[\@nameuse{#1#2vplacement}]{\@nameuse{#1#2runwidth}}{%
            \centering\@nameuse{#1ps#2strut}%
            \mem@ps@entry@wrap{\@nameuse{#1#4#2c}}%
            \@nameuse{#1ps#2strut}}\hfill
          \llap{%
            \parbox[\@nameuse{#1#2vplacement}]{\@nameuse{#1#2runwidth}}{%
              \memRTLmainraggedleft\@nameuse{#1ps#2strut}%
              \mem@ps@entry@wrap{\@nameuse{#1#4#2r}}%
              \@nameuse{#1ps#2strut}}}%
        }%
%    \end{macrocode}
% In the header the line goes under the text, so we test and add the
% headline if \texttt{\#2} equals \texttt{head}.
% \changes{v3.6k}{2012/05/31}{Forgot to separate head/foot position into the
% factorization}
% \changes{v3.7d}{2015/04/22}{Moved \cs{...headruleprefix} outside
% \cs{...headrule}. Otherwise copy does not work correctly.}
%    \begin{macrocode}
        \nametest{#2}{head}\ifsamename%
          \@nameuse{#1#2ruleprefix}%
          \@nameuse{#1#2rule}%
        \fi%
      }}\@nameuse{#1#3#2pr}}%
%    \end{macrocode}
% And end by letting the LaTeX head/foot use our version
%    \begin{macrocode}
  \@namedef{@#3#2}{\@nameuse{#1@#3#2}}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makepagestyle}
%  At last we can put everything together for defining a new pagestyle,
% via the macro \cs{makepagestyle}\marg{style} which initially sets up 
% a new pagestyle \meta{style} corresponding the the \LaTeX{} \verb?empty?
% pagestyle. The prior macros can then be used to make modifications
% to the style.
% \changes{v1.0}{2001/11/15}{Now 2 stage process for defining \cs{@evenhead}
%                            and friends}
% \changes{v1.61}{2004/03/14}{Added \cs{m@mhe@dreset} at several points in
%                             \cs{makepagestyle} (from patch 2.1)}
% \changes{v1.61803}{2008/01/30}{Removed extraneous spaces from pagestyle code 
%                    (mempatch v4.6)}
% \changes{v1.61803398d}{2010/02/09}{Added storing extra information
% about page styles}
% We also make sure to specify that this is a `real' page style, and
% thus sets the empty alias name and the alias test to 01.
%    \begin{macrocode}
\newcommand{\makepagestyle}[1]{%
  \mem@set@ps@xtra@info{#1}{}{01}%
%    \end{macrocode}
% First define the macro \cs{ps@style}, which in turn defines the macros
% \cs{@evenhead}, \cs{@oddhead}, \cs{@evenfoot} and \cs{@oddfoot}.
%   \changes{v3.6d}{20101/06/24}{Factored \cs{makepagestyle}, such
%   that \cs{#1@evenhead} and friends are made using \emph{one} single
%   macro. We keep the original code just in case.}
%    \begin{macrocode}
  \@namedef{ps@#1}{%
      \mem@ps@HLH{#1}{head}{even}{e}%
      \mem@ps@HLH{#1}{head}{odd}{o}%
      \mem@ps@HLH{#1}{foot}{even}{e}%
      \mem@ps@HLH{#1}{foot}{odd}{o}%
 %    \@namedef{#1@evenhead}{%
%    \end{macrocode}
% The code for the definition of \cs{@evenhead} and friends is based on code
% from Piet van Oostrum's \Lpack{fancyhdr} package~\cite{FANCYHDR}. The three
% parts of the header are put into parboxes, with fills between them, and
% the whole lot is put into a box the width of the header. Fillers are put
% before and after the main box which control the header position.
%
% First the left filler which is either \cs{relax} or \cs{hss}, and then
% start the main box.
% \changes{v1.6180339c}{2008/12/26}{Replaced \cs{...runwidth} by \cs{...headrunwidth}
%                       or \cs{...footrunwidth}, as appropriate for headers and footers.}
% \changes{v1.6180339c}{2009/01/13}{Replaced \cs{parbox}\texttt[b]
% with \cs{parbox}\texttt{[\cs{nameuse{#1headvplacement}}]} etc.}
%    \begin{macrocode}
 %      \@nameuse{#1evenhpl}\hb@xt@\@nameuse{#1headrunwidth}{\m@mhe@dreset%
 %        \vbox{\hbox{%
%    \end{macrocode}
% The left part of the header.
%    \begin{macrocode}
 %        \rlap{\parbox[\@nameuse{#1headvplacement}]{\@nameuse{#1headrunwidth}}{%
 %          \raggedright\@nameuse{#1eheadl}\strut}}\hfill
%    \end{macrocode}
% The center part of the header.
%    \begin{macrocode}
 %               \parbox[\@nameuse{#1headvplacement}]{\@nameuse{#1headrunwidth}}{%
 %           \centering\@nameuse{#1eheadc}\strut}\hfill
%    \end{macrocode}
% The right part of the header.
%    \begin{macrocode}
 %        \llap{\parbox[\@nameuse{#1headvplacement}]{\@nameuse{#1headrunwidth}}{%
 %         \raggedleft\@nameuse{#1eheadr}\strut}}}%
%    \end{macrocode}
% Finally, the header rule and finish with the right filler, which
% is either \cs{relax} or \cs{hss}.
%    \begin{macrocode}
 %       \@nameuse{#1headrule}}}\@nameuse{#1evenhpr}}%
%    \end{macrocode}
% The code for the \cs{@oddhead}, \cs{@evenfoot} and \cs{@oddfoot} follows
% a similar pattern. Here is \cs{@oddhead}.
%    \begin{macrocode}
 %   \@namedef{#1@oddhead}{%
 %     \@nameuse{#1oddhpl}\hb@xt@\@nameuse{#1headrunwidth}{\m@mhe@dreset%
 %       \vbox{\hbox{%
 %       \rlap{\parbox[\@nameuse{#1headvplacement}]{\@nameuse{#1headrunwidth}}{%
 %         \raggedright\@nameuse{#1oheadl}\strut}}\hfill
 %             \parbox[\@nameuse{#1headvplacement}]{\@nameuse{#1headrunwidth}}{%
 %         \centering\@nameuse{#1oheadc}\strut}\hfill
 %       \llap{\parbox[\@nameuse{#1headvplacement}]{\@nameuse{#1headrunwidth}}{%
 %         \raggedleft\@nameuse{#1oheadr}\strut}}}%
 %       \@nameuse{#1headrule}}}\@nameuse{#1oddhpr}}%
%    \end{macrocode}
% And \cs{@evenfoot}. For the footers the rules come \emph{before} any foot
% entries.
%    \begin{macrocode}
 %   \@namedef{#1@evenfoot}{%
 %     \@nameuse{#1evenfpl}\hb@xt@\@nameuse{#1footrunwidth}{\m@mhe@dreset%
 %       \vbox{\@nameuse{#1footrule}\hbox{%
 %       \rlap{\parbox[\@nameuse{#1footvplacement}]{\@nameuse{#1footrunwidth}}{%
 %         \raggedright\@nameuse{#1efootl}\strut}}\hfill
 %             \parbox[\@nameuse{#1footvplacement}]{\@nameuse{#1footrunwidth}}{%
 %         \centering\@nameuse{#1efootc}\strut}\hfill
 %       \llap{\parbox[\@nameuse{#1footvplacement}]{\@nameuse{#1footrunwidth}}{%
 %         \raggedleft\@nameuse{#1efootr}\strut}}}%
 %       }}\@nameuse{#1evenfpr}}%
%    \end{macrocode}
% Lastly the \cs{@oddfoot}.
%    \begin{macrocode}
 %   \@namedef{#1@oddfoot}{%
 %     \@nameuse{#1oddfpl}\hb@xt@\@nameuse{#1footrunwidth}{\m@mhe@dreset%
 %       \vbox{\@nameuse{#1footrule}\hbox{%
 %       \rlap{\parbox[\@nameuse{#1footvplacement}]{\@nameuse{#1footrunwidth}}{%
 %         \raggedright\@nameuse{#1ofootl}\strut}}\hfill
 %             \parbox[\@nameuse{#1footvplacement}]{\@nameuse{#1footrunwidth}}{%
 %         \centering\@nameuse{#1ofootc}\strut}\hfill
 %       \llap{\parbox[\@nameuse{#1footvplacement}]{\@nameuse{#1footrunwidth}}{%
 %         \raggedleft\@nameuse{#1ofootr}\strut}}}%
 %       }}\@nameuse{#1oddfpr}}%
%    \end{macrocode}
% Now we define \cs{@evenhead} etc., in terms of \verb?#1@evenhead?.
%    \begin{macrocode}
 %    \def\@evenhead{\@nameuse{#1@evenhead}}%
 %    \def\@oddhead{\@nameuse{#1@oddhead}}%
 %    \def\@evenfoot{\@nameuse{#1@evenfoot}}%
 %    \def\@oddfoot{\@nameuse{#1@oddfoot}}%
%    \end{macrocode}
% To finish off the definition of \cs{ps@style}, add in a hook which can be
% defined so that it adds additional code, if required.
%    \begin{macrocode}
    \@nameuse{#1pshook}}%
%    \end{macrocode}
% \changes{v3.6d}{2010/06/24}{Added strut initialization} Next we
% initialize the struts being used. Remember the for the
% \pstyle{empty} style, the strut should be empty.
%    \begin{macrocode}
    \nametest{#1}{empty}%
    \ifsamename%
      \@namedef{#1psheadstrut}{}\@namedef{#1psfootstrut}{}%
    \else%
      \@namedef{#1psheadstrut}{\strut}\@namedef{#1psfootstrut}{\strut}%
    \fi%
%    \end{macrocode}
%
% The final part of setting up the new pagestyle
% is defining all the macros called by \cs{ps@style}, and giving them
% default values. Make the headers and footers empty.
%    \begin{macrocode}
  \makeevenhead{#1}{}{}{}%
  \makeoddhead{#1}{}{}{}%
  \makeevenfoot{#1}{}{}{}%
  \makeoddfoot{#1}{}{}{}%
%    \end{macrocode}
% Make the headers/footers the same width as the \cs{textwidth},
% center them, and ensure that the rules have zero height so that they
% will be invisible. Also initialize the head/foot prefixes.
% \changes{v3.6h}{2011/01/25}{Added the \cs{makeheadfootruleprefix}}
%    \begin{macrocode}
  \makerunningwidth{#1}{\textwidth}%
  \makeheadposition{#1}{}{}{}{}%
  \makeheadrule{#1}{\textwidth}{0pt}%
  \makefootrule{#1}{\textwidth}{\footruleheight}{\footruleskip}%
  \makeheadfootruleprefix{#1}{}{}
%    \end{macrocode}
% Set the initial vertical header and footer positions.
% \changes{v1.6180339c}{2009/01/13}{Added head/foot position initialisation}
%    \begin{macrocode}
  \makeheadfootvposition{#1}{b}{b}%
%    \end{macrocode}
% Finally, there is no addtional code needed, so make the hook empty, and
% we are done.
%    \begin{macrocode}
  \makepsmarks{#1}{}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\aliaspagestyle}
% The command \cs{aliaspagestyle}\marg{alias}\marg{original}
% defines the \meta{alias} pagestyle to be an alias for the
% \meta{original} pagestyle.
% \changes{v1.61803398d}{2010/02/09}{Added page style storing info}
% We remember to set the stored alias name, and sets the alias test to
% true (00).
%    \begin{macrocode}
\newcommand{\aliaspagestyle}[2]{%
  \mem@set@ps@xtra@info{#1}{#2}{00}%
  \@namedef{ps@#1}{\@nameuse{ps@#2}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\copypagestyle}
% The command \cs{copypagestyle}\marg{new}\marg{original}
% defines the \meta{new} pagestyle to be a copy of the
% \meta{original} pagestyle.
%
% It first makes the \meta{new} (empty) pagestyle then defines the internals
% in terms of the \meta{original} internals.
% \changes{v1.2}{2002/08/10}{Added \cs{copypagestyle}}
% \changes{v1.61803}{2008/01/30}{Added missing elements to \cs{copypagestyle}
%          (per Erik Quaeghebeur mempatch v4.9)}
%    \begin{macrocode}
\newcommand{\copypagestyle}[2]{%
  \makepagestyle{#1}%
%    \end{macrocode}
% Do the headers and footers.
%    \begin{macrocode}
  \makeevenhead{#1}{\@nameuse{#2eheadl}}%
               {\@nameuse{#2eheadc}}{\@nameuse{#2eheadr}}%
  \makeoddhead{#1}{\@nameuse{#2oheadl}}%
               {\@nameuse{#2oheadc}}{\@nameuse{#2oheadr}}%
  \makeevenfoot{#1}{\@nameuse{#2efootl}}%
               {\@nameuse{#2efootc}}{\@nameuse{#2efootr}}%
  \makeoddfoot{#1}{\@nameuse{#2ofootl}}%
              {\@nameuse{#2ofootc}}{\@nameuse{#2ofootr}}%
%    \end{macrocode}
% Set the width.
%    \begin{macrocode}
  \makerunningwidth{#1}[\@nameuse{#2footrunwidth}]{\@nameuse{#2headrunwidth}}%
%    \end{macrocode}
% Specify the \cs{headposition}.
% \changes{v3.6k}{2012/05/31}{some macro renaming}
%    \begin{macrocode}
  \@namedef{#1evenheadpl}{\@nameuse{#2evenheadpl}}%
  \@namedef{#1oddheadpl}{\@nameuse{#2oddheadpl}}%
  \@namedef{#1evenheadpr}{\@nameuse{#2evenheadpr}}%
  \@namedef{#1oddheadpr}{\@nameuse{#2oddheadpr}}%
%    \end{macrocode}
% Also vertically
% \changes{v1.6180339c}{2008/01/13}{Also copy the vertical positions}
% \changes{v1.6180339e}{2008/02/06}{Bug fix, reported by Per
% Starb\"ack on ctt}
%    \begin{macrocode}
  \makeheadfootvposition{#1}{\@nameuse{#2headvplacement}}{\@nameuse{#2footvplacement}}%
%    \end{macrocode}
% Specify the feet
% \changes{v3.6k}{2012/05/31}{some macro renaming}
%    \begin{macrocode}
  \@namedef{#1evenfootpl}{\@nameuse{#2evenfootpl}}%
  \@namedef{#1oddfootpl}{\@nameuse{#2oddfootpl}}%
  \@namedef{#1evenfootpr}{\@nameuse{#2evenfootpr}}%
  \@namedef{#1oddfootpr}{\@nameuse{#2oddfootpr}}%
%    \end{macrocode}
% Specify the head and foot rules and the prefixes.
% \changes{v3.6h}{2011/01/25}{Added the \cs{makeheadfootruleprefix}}
%    \begin{macrocode}
  \@namedef{#1headrule}{\@nameuse{#2headrule}}%
  \@namedef{#1footrule}{\@nameuse{#2footrule}}%
  \@namedef{#1headruleprefix}{\@nameuse{#2headruleprefix}}%
  \@namedef{#1footruleprefix}{\@nameuse{#2footruleprefix}}%
%    \end{macrocode}
% \changes{v3.6d}{2010/06/24}{Added strut copying to \cs{copypagestyle}}
% And remember the struts
%    \begin{macrocode}
  \@namedef{#1psheadstrut}{\@nameuse{#2psheadstrut}}
  \@namedef{#1psfootstrut}{\@nameuse{#2psfootstrut}}
%    \end{macrocode}
% \end{macro}
% And pick up the hook. We end the macro here.
%    \begin{macrocode}
  \makepsmarks{#1}{\@nameuse{#2pshook}}}

%    \end{macrocode}
%
%
% \begin{macro}{\ifonlyfloats}
% \cs{ifonlyfloats}\marg{yes}\marg{no} processes \meta{yes} if the macro is
% called on a page consisting only of floats, otherwise \meta{no} is 
% processed. \cs{if@fcolmade} is specified in \file{ltoutput.dtx}.
% \changes{v1.0}{2001/11/14}{Added \cs{ifonlyfloats}}
%    \begin{macrocode}
\newcommand{\ifonlyfloats}[2]{\if@fcolmade #1\else #2\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mergepagefloatstyle}
% \cs{mergepagefloatstyle}\marg{style}\marg{textstyle}\marg{floatstyle}
% makes a new page style \meta{style} that is \meta{textstyle} on normal
% pages but uses \meta{floatstyle} on float-only pages. Both \meta{textstyle}
% and \meta{floatstyle} must have been previously defined.
% \changes{v1.0}{2001/11/15}{Added \cs{mergepagefloatstyle}}
%    \begin{macrocode}
\newcommand{\mergepagefloatstyle}[3]{%
%    \end{macrocode}
% Make sure that the two styles have been called, otherwise we get some
% undefined errors.
%    \begin{macrocode}
  \@nameuse{ps@#3}\@nameuse{ps@#2}%
%    \end{macrocode}
% Specify the pagestyle's headers and footers.
%    \begin{macrocode}
  \@namedef{ps@#1}{%
  \def\@evenhead{\ifonlyfloats{\@nameuse{#3@evenhead}}%
                {\@nameuse{#2@evenhead}}}%
  \def\@oddhead{\ifonlyfloats{\@nameuse{#3@oddhead}}%
               {\@nameuse{#2@oddhead}}}%
  \def\@evenfoot{\ifonlyfloats{\@nameuse{#3@evenfoot}}%
                {\@nameuse{#2@evenfoot}}}%
  \def\@oddfoot{\ifonlyfloats{\@nameuse{#3@oddfoot}}%
               {\@nameuse{#2@oddfoot}}}%
%    \end{macrocode}
% Set the hook to the \meta{textstyle} on the assumption that that is
% more complex that required for a float page.
%    \begin{macrocode}
  \@namedef{#1pshook}{\@nameuse{#2pshook}}%
%    \end{macrocode}
% That's it.
%    \begin{macrocode}
}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makeheadfootstrut}
%   \changes{v3.6d}{2010/06/24}{Added \cs{makeheadfootstrut}}
%   In each `field' of the header a strut is added to keep alignment
%   right. This macro can be used to change a particular strut
%   configuration. Each combination is initialy set by
%   \cs{makepagestyle} to be equal to \cs{strut}, except the
%   \pstyle{empty} style, where the strut is empty by default.
%    \begin{macrocode}
\newcommand*\makeheadfootstrut[3]{%
  \@namedef{#1psheadstrut}{#2}\@namedef{#1psfootstrut}{#3}}
%    \end{macrocode}
% \end{macro}
%
%    The pagestyles \pstyle{empty} and \pstyle{plain} are defined 
%    in \file{latex.dtx}. However, I will redefine them here, just in
% case someone takes a fancy to modifying them.
%
% \begin{macro}{\ps@empty}
% The \pstyle{empty} pagestyle is simple, it's just what we get when
% we call \cs{makepagestyle}.
%    \begin{macrocode}
\makepagestyle{empty}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ps@plain}
% The \pstyle{plain} pagestyle is also simple, it just puts the
% page number at the bottom middle of the page.
% We call \verb?\makepagestyle{plain}? and then adjust as required.
%    \begin{macrocode}
\makepagestyle{plain}
  \makeevenfoot{plain}{}{\thepage}{}
  \makeoddfoot{plain}{}{\thepage}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ps@simple}
% The \pstyle{simple} page style simply puts the page number in the header
% at the outer margin.
% \changes{v1.61803398}{2009/07/26}{PW: Added the `simple' pagestyle}
%    \begin{macrocode}
\makepagestyle{simple}
  \makeevenhead{simple}{\thepage}{}{}
  \makeoddhead{simple}{}{}{\thepage}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\nouppercaseheads}
% \begin{macro}{\uppercaseheads}
% \begin{macro}{\memUChead}
% Spurred by Lars Madsen's \Lpack{memexsupp} v0.5 package here is a 
% way of switching uppercasing in the headings pagestyle. 
% \changes{v1.61803}{2008/01/30}{Added \cs{(no)uppercaseheads} and
%          \cs{memUChead} (mempatch v4.9)}
% \changes{v3.6k}{2011/05/20}{Making \cs{memUChead} equal to
% \cs{relax} can cause problems when users want to \cs{provide} it in
% other applications. It is now redefined into the empty string.}
% \changes{v3.6k}{2012/09/13}{Default upper case now \cs{MakeTextUppercase}}
%    \begin{macrocode}
\newcommand*{\nouppercaseheads}{\def\memUChead{}}
\newcommand*{\uppercaseheads}{\def\memUChead{\MakeTextUppercase}}
\uppercaseheads

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% The macros \cs{createplainmark}, \cs{createmark} and \cs{addtopsmarks}
% are modified versions of code supplied by Lars Madsen.
% \changes{v1.61803}{2008/01/30}{Added, and used, \cs{createplainmark},
%                    \cs{createmark} and \cs{addtopsmarks}} 
% \begin{macro}{\createplainmark}
% \cs{createplainmark}\marg{type}\marg{marks}\marg{text} creates a
% \cs{typemark} (\meta{type} is \texttt{toc}, \texttt{bib}, etc)
% with \meta{marks} (left, both, right) whose contents are \meta{text}.
% For example \verb?\createplainmark{toc}{both}{\contentsname}?. The
% difference between plain and regular marks, is that plain marks use
% a fixed text, whereas regular marks recieve dynamic text and thus
% is given an argument.
%    \begin{macrocode}
\newcommand*{\createplainmark}[3]{%
  \nametest{#2}{left}%
  \ifsamename
    \@namedef{#1mark}{\markboth{\memUChead{#3}}{}}%
  \else
    \nametest{#2}{right}%
    \ifsamename
      \@namedef{#1mark}{\markright{\memUChead{#3}}}%
    \else
      \nametest{#2}{both}%
      \ifsamename\else
        \@memerror{%
          Unknown mark setting type `#2' for #1mark}{%
          I expected `left', `both' or `right'. \MessageBreak
          I will assume you meant `both'}%	
      \fi
      \@namedef{#1mark}{\markboth{\memUChead{#3}}{\memUChead{#3}}}%
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\createmark}
% \cs{createmark}\marg{division}\marg{marks}\marg{show}\marg{prefix}\marg{postfix}
% creates a \cs{divisionmark} with \meta{marks} (= \texttt{left}, \texttt{both}
% or \texttt{right}) controlling which marks are set, 
% \meta{show} (= \texttt{shownumber} or \texttt{nonumber}) controls the
% display of the divison number in \cs{mainmatter}, \meta{prefix} is text
% before the number and \meta{postfix} is text after the number.
%    \begin{macrocode}
\newcommand\createmark[5]{%
%    \end{macrocode}
% Handle \texttt{(show/no)number}, fails to \texttt{shownumber}.
%    \begin{macrocode}
  \def\@tempa{00}
  \nametest{#3}{nonumber}%
  \ifsamename
    \def\@tempa{01}%
  \else
    \nametest{#3}{shownumber}
    \ifsamename\else
      \@memerror{Unknown numbering value `#3' for #1mark}%
      {I expected `shownumber' or `nonumber'.\MessageBreak
       I will assume you meant `shownumber'}%
    \fi
  \fi
  \expandafter\if\@tempa%          compares the two \@tempa digits
    \@namedef{#1marksn}##1{##1}%
  \else
    \@namedef{#1marksn}{\@gobble}%
  \fi
%    \end{macrocode}
% The three \meta{marks} cases, \texttt{left}, \texttt{both} and
% \texttt{right}; fails to \texttt{both}.
% \changes{v3.7f}{2015/08/25}{Sporious spaces}
%    \begin{macrocode}
  \nametest{#2}{left}%
  \ifsamename
    \@namedef{#1mark}##1{%
      \@setclcnt{#1}{@memmarkcntra}%
      \advance\c@@memmarkcntra\m@ne
      \markboth{%
        \memUChead{%
          \ifnum \c@secnumdepth > \c@@memmarkcntra
            \if@mainmatter
              \@nameuse{#1marksn}{#4\@nameuse{the#1}#5}%
            \fi
          \fi
          ##1}}{}}%
  \else
    \nametest{#2}{right}
    \ifsamename
      \@namedef{#1mark}##1{%
        \@setclcnt{#1}{@memmarkcntra}%
        \advance\c@@memmarkcntra\m@ne
        \markright{%
          \memUChead{%
            \ifnum \c@secnumdepth > \c@@memmarkcntra
              \if@mainmatter%
                \@nameuse{#1marksn}{#4\@nameuse{the#1}#5}%
              \fi%
            \fi%
            ##1}}}%
    \else
      \nametest{#2}{both}%
      \ifsamename\else
        \@memerror{%
        Unknown mark setting type `#2' for #1mark}{%
        I expected `left', `both' or `right'. \MessageBreak
        I will assume you meant `both'}%	
      \fi
    \@namedef{#1mark}##1{%
      \@setclcnt{#1}{@memmarkcntra}%
      \advance\c@@memmarkcntra\m@ne
      \markboth{%
        \memUChead{%
          \ifnum \c@secnumdepth > \c@@memmarkcntra
            \if@mainmatter
              \@nameuse{#1marksn}{#4\@nameuse{the#1}#5}%
            \fi
          \fi
          ##1}}{%
        \memUChead{%
          \ifnum \c@secnumdepth > \c@@memmarkcntra
            \if@mainmatter
              \@nameuse{#1marksn}{#4\@nameuse{the#1}#5}%
            \fi
          \fi
          ##1}}}%
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\addtopsmarks}
% \cs{addtopsmarks}\marg{pagestyle}\marg{prepend}\marg{append} inserts
% \meta{prepend} and \meta{append} at the start and end of the current
% definition of \cs{pagestylepshook}.
% \changes{v1.61803398d}{2010/02/09}{Added safe to change test}
%    \begin{macrocode}
\newcommand\addtopsmarks[3]{%
  \mem@ps@safe@change{#1}%
  \expandafter\addtodef\expandafter{\csname #1pshook\endcsname}{#2}{#3}}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\clearplainmark}
% \begin{macro}{\clearmark}
%  For some page styles it is handy to be able to make sure that no
%  section or otherwise add data to the \cs{left-} and
%  \cs{rightmark}. The macros \cs{clearplainmark} and \cs{clearmark}
%  will take one argument specifying which mark to clear, and then
%  redefine this mark to do nothing or to gobble its given argument.
%    \begin{macrocode}
\newcommand\clearplainmark[1]{%
  \@namedef{#1mark}{}}
\newcommand\clearmark[1]{%
  \@namedef{#1mark}{\@gobble}}
%    \end{macrocode}
%  
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ps@headings}
%    The \pstyle{headings} pagestyle behaves differently for
% twosided and onesided printing. This is a rewrite of the
% standard style.
% \changes{v1.1}{2002/03/10}{Added \cs{tocmark} etc., to \cs{ps@headings}}
% \changes{v1.61803}{2008/01/30}{Used \cs{memUChead} in \cs{ps@headings}
%              (mempatch v4.9)}
% \changes{v1.61803}{2008/01/30}{For twosided docs set both marks for ToC, etc. (mempatch v4.9)}
% \changes{v1.61803}{2008/01/30}{Eliminated \cs{@mkboth} as never used
%                    (mempatch v4.9)}
% \changes{v1.61803}{2008/01/30}{Added \cs{glossarymark} to \cs{ps@headings}}
%    \begin{macrocode}
\if@twoside
%    \end{macrocode}
% The footer is empty and the header contains the page number and
% one of the marks.
%    \begin{macrocode}
  \makepagestyle{headings}
    \makepsmarks{headings}{%
      \def\chaptermark##1{%
        \markboth{\memUChead{%
          \ifnum \c@secnumdepth >\m@ne
            \if@mainmatter
              \@chapapp\ \thechapter. \ %
            \fi
          \fi
          ##1}}{}}%
      \def\tocmark{\markboth{\memUChead{\contentsname}}{\memUChead{\contentsname}}}%
      \def\lofmark{\markboth{\memUChead{\listfigurename}}{\memUChead{\listfigurename}}}%
      \def\lotmark{\markboth{\memUChead{\listtablename}}{\memUChead{\listtablename}}}%
      \def\bibmark{\markboth{\memUChead{\bibname}}{\memUChead{\bibname}}}%
      \def\indexmark{\markboth{\memUChead{\indexname}}{\memUChead{\indexname}}}%
      \def\sectionmark##1{%
        \markright{\memUChead{%
          \ifnum \c@secnumdepth > \z@
            \thesection. \ %
          \fi
          ##1}}}}
%    \end{macrocode}
% And here's a version of the above \cs{makepsmarks} using \cs{createmark} and 
% \cs{createplainmark}.
%    \begin{macrocode}
    \makepsmarks{headings}{%
      \createmark{chapter}{left}{shownumber}{\@chapapp\ }{. \ }
      \createmark{section}{right}{shownumber}{}{. \ }
      \createplainmark{toc}{both}{\contentsname}
      \createplainmark{lof}{both}{\listfigurename}
      \createplainmark{lot}{both}{\listtablename}
      \createplainmark{bib}{both}{\bibname}
      \createplainmark{index}{both}{\indexname}
      \createplainmark{glossary}{both}{\glossaryname}
    }
    \makeevenhead{headings}{\thepage}{}{\slshape\leftmark}
    \makeoddhead{headings}{\slshape\rightmark}{}{\thepage}
\else
%    \end{macrocode}
% For one sided printing even and odd pages are treated the same,
% so no need to bother with the evenhead, and
% just the \cs{rightmark} is used.     
%    \begin{macrocode}
  \makepagestyle{headings}
    \makepsmarks{headings}{%
      \def\chaptermark##1{%
        \markright{\memUChead{%
          \ifnum \c@secnumdepth >\m@ne
            \if@mainmatter
              \@chapapp\ \thechapter. \ %
            \fi
          \fi
          ##1}}}%
      \def\tocmark{\markright{\memUChead{\contentsname}}}%
      \def\lofmark{\markright{\memUChead{\listfigurename}}}%
      \def\lotmark{\markright{\memUChead{\listtablename}}}%
      \def\bibmark{\markright{\memUChead{\bibname}}}%
      \def\indexmark{\markright{\memUChead{\indexname}}}}
%    \end{macrocode}
% And here's a version of the above \cs{makepsmarks} using \cs{createmark} and 
% \cs{createplainmark}.
%    \begin{macrocode}
    \makepsmarks{headings}{%
      \createmark{chapter}{right}{shownumber}{\@chapapp\ }{. \ }
      \createplainmark{toc}{right}{\contentsname}
      \createplainmark{lof}{right}{\listfigurename}
      \createplainmark{lot}{right}{\listtablename}
      \createplainmark{bib}{right}{\bibname}
      \createplainmark{index}{right}{\indexname}
      \createplainmark{glossary}{right}{\glossaryname}
    }
    \makeoddhead{headings}{\slshape\rightmark}{}{\thepage}
\fi

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ps@myheadings}
%    The \pstyle{myheadings} page style is simpler because the user
% has to specify the contents using \cs{markboth} and \cs{markright}
% commands. This is the definition used in the standard classes.
% \changes{v1.1}{2002/03/10}{Added \cs{tocmark} etc., to \cs{ps@myheadings}}
%    \begin{verbatim}}
% \newcommand{\ps@myheadings}{%
%   \let\@oddfoot\@empty\let\@evenfoot\@empty
%   \def\@evenhead{\thepage\hfil{\slshape\leftmark}}%
%   \def\@oddhead{{\slshape\rightmark}\hfil\thepage}%
%   \let\@mkboth\@gobbletwo
%   \let\chaptermark\@gobble
%   \let\sectionmark\@gobble
% }
% \end{verbatim}
% Translating that into our terms we get:
% \changes{v1.0}{2001/11/15}{Changed the code for creating the myheadings pagestyle}
% \changes{v1.4}{2003/11/22}{Further change to myheadings pagestyle code}
%    \begin{macrocode}
\makepagestyle{myheadings}
  \makepsmarks{myheadings}{%
    \let\chaptermark\@gobble
    \let\sectionmark\@gobble
    \def\tocmark{}%
    \def\lofmark{}%
    \def\lotmark{}%
    \def\bibmark{}%
    \def\indexmark{}%
    \def\glossarymark{}}
  \makeevenhead{myheadings}{\thepage}{}{\slshape\leftmark}
  \makeoddhead{myheadings}{\slshape\rightmark}{}{\thepage}

%    \end{macrocode}
% (Kai von Fintel (\texttt{fintel@mit.edu}) emailed me on 2003/02/24
% saying that the original \verb?\let\tocmark\@gobble? in the myheadings
% pagestyle did nasty things
% to the ToC, etc. Now using \verb?\def\tocmark{}?.)
% \end{macro}
%
% \begin{macro}{\ps@chapter}
% \begin{macro}{\ps@part}
% \begin{macro}{\ps@cleared}
%  The standard classes use the \pstyle{plain} pagestyle for the first page
% of a chapter. This class uses the \pstyle{chapter} instead, which is
% aliased to \pstyle{plain}. Similarly for parts. 
% Further, \cs{cleardoublepage} uses whatever
% pagestyle is in effect for the empty verso page. I find that this
% looks odd if the header contains a chapter name. This class uses
% the \pstyle{cleared} pagestyle in this case. I have aliased this
% to \pstyle{empty}; the \pstyle{plain} would be another reasonable choice.
%    \begin{macrocode}
\aliaspagestyle{chapter}{plain}
\aliaspagestyle{part}{plain}
\aliaspagestyle{cleared}{empty}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\cleardoublepage}
% A slight adjustment to the kernel definition to set a pagestyle.
%    \begin{macrocode}
\def\cleardoublepage{\clearpage\if@twoside \ifodd\c@page\else
  \hbox{}\thispagestyle{cleared}%
  \newpage\if@twocolumn\hbox{}\newpage\fi\fi\fi}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\ps@ruled}
%    Partly to show how it is done, the class provides a \pstyle{ruled} pagestyle.
% In this style the headers and footers are the same width as the textblock,
% there is a rule under the header, page numbers are set in the footers
% at the outside of the page. Even page headers have the chapter number
% and title at the left, and odd page headers have the section title
% at the right.
%
%    Start by making the (empty) \pstyle{ruled} pagestyle.
%    \begin{macrocode}
\makepagestyle{ruled}
%    \end{macrocode}
% There is no need to change the default width (which is the \cs{textwidth}),
% nor the default positions (centered),
% nor to make the footrule visible. We do, though, have to put the page
% numbers into the footers.
%    \begin{macrocode}
\makeevenfoot{ruled}{\thepage}{}{}
\makeoddfoot{ruled}{}{}{\thepage}
%    \end{macrocode}
% Make the header rule visible and equal to the \cs{textwidth}.
%    \begin{macrocode}
\makeheadrule{ruled}{\textwidth}{\normalrulethickness}
%    \end{macrocode}
%
% \begin{macro}{\@ruledmarks}
% We have to make sure that the \cs{chapter} and \cs{section} commands make
% the appropriate marks for use in the headers. We use the hook for this.
% Note that contrary to normal \LaTeX{} practice, the titles are not
% automatically upper-cased. The marks for the tocbibinds also need adjusting.
% \changes{v1.1}{2002/03/10}{Changed \cs{@ruledmarks} to cater for tocbibind}
%    \begin{macrocode}
\newcommand{\@ruledmarks}{%
  \def\chaptermark##1{%
    \markboth{%
      \ifnum \c@secnumdepth >\m@ne
        \if@mainmatter
          \thechapter. \ %
        \fi
      \fi
      ##1}{}}
  \def\sectionmark##1{\markright{##1}}
  \def\tocmark{\markboth{\contentsname}{}}
  \def\lofmark{\markboth{\listfigurename}{}}
  \def\lotmark{\markboth{\listtablename}{}}
  \def\bibmark{\markboth{\bibname}{}}
  \def\indexmark{\markboth{\indexname}{}}
  \def\glossarymark{\markboth{\glossaryname}{}}
}
%    \end{macrocode}
% And here's a version using \cs{createmark} and friends.
%    \begin{macrocode}
\renewcommand*{\@ruledmarks}{%
  \nouppercaseheads
  \createmark{chapter}{left}{shownumber}{}{. \space}
  \createmark{section}{right}{shownumber}{}{. \space}
  \createplainmark{toc}{both}{\contentsname}
  \createplainmark{lof}{both}{\listfigurename}
  \createplainmark{lot}{both}{\listtablename}
  \createplainmark{bib}{both}{\bibname}
  \createplainmark{index}{both}{\indexname}
  \createplainmark{glossary}{both}{\glossaryname}}
\makepsmarks{ruled}{\@ruledmarks}
%    \end{macrocode}
% \end{macro}
%
% We can now define the even page header which is to have the chapter title
% at the left. As the chapter mark did no upper-casing we will print it
% using small caps, but just use the normal font for section title on
% the odd page header.
%    \begin{macrocode}
\makeevenhead{ruled}{\scshape\leftmark}{}{}
\makeoddhead{ruled}{}{}{\rightmark}

%    \end{macrocode}
% \end{macro}
% This is all that we need to do for the \pstyle{ruled} pagestyle.
%
% \begin{macro}{\ps@Ruled}
%    Also define a \pstyle{Ruled} pagestyle similar to \pstyle{ruled} except that the
% headers and footers are 10\% wider than the textblock, sticking out
% into the fore edge.
%    \begin{macrocode}
\makepagestyle{Ruled}
\makerunningwidth{Ruled}{1.1\textwidth}
\makeheadposition{Ruled}{flushright}{flushleft}{flushright}{flushleft}
\makeevenfoot{Ruled}{\thepage}{}{}
\makeoddfoot{Ruled}{}{}{\thepage}
\makeheadrule{Ruled}{1.1\textwidth}{\normalrulethickness}
\makepsmarks{Ruled}{\@ruledmarks}
\makeevenhead{Ruled}{\scshape\leftmark}{}{}
\makeoddhead{Ruled}{}{}{\rightmark}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\headwidth}
% \begin{macro}{\ps@companion}
% A \pstyle{companion} pagestyle like the one in the 
% \textit{\LaTeX{} Companion} series.
% We need the \cs{headwidth} length for this.
% \changes{v1.1}{2002/03/10}{Added \cs{tocmark} etc., to \cs{ps@companion}}
%    \begin{macrocode}
\newlength{\headwidth}

\makepagestyle{companion}
\setlength{\headwidth}{\textwidth}
  \addtolength{\headwidth}{\marginparsep}
  \addtolength{\headwidth}{\marginparwidth}
\makerunningwidth{companion}{\headwidth}
\makeheadrule{companion}{\headwidth}{\normalrulethickness}
\makeheadposition{companion}{flushright}{flushleft}{}{}
\makepsmarks{companion}{%
  \def\chaptermark##1{\markboth{##1}{##1}}    % left mark & right marks
  \def\sectionmark##1{\markright{%
    \ifnum \c@secnumdepth>\z@
      \thesection. \ %
    \fi
    ##1}}
  \def\tocmark{\markboth{\contentsname}{\contentsname}}
  \def\lofmark{\markboth{\listfigurename}{\listfigurename}}
  \def\lotmark{\markboth{\listtablename}{\listtablename}}
  \def\bibmark{\markboth{\bibname}{\bibname}}
  \def\indexmark{\markboth{\indexname}{\indexname}}}
%    \end{macrocode}
% And here's a version of the above \cs{makepsmarks} using \cs{createmark} and 
% \cs{createplainmark}.
%    \begin{macrocode}
\makepsmarks{companion}{%
  \nouppercaseheads
  \createmark{chapter}{both}{nonumber}{}{}
  \createmark{section}{right}{shownumber}{}{. \space}
  \createplainmark{toc}{both}{\contentsname}
  \createplainmark{lof}{both}{\listfigurename}
  \createplainmark{lot}{both}{\listtablename}
  \createplainmark{bib}{both}{\bibname}
  \createplainmark{index}{both}{\indexname}
  \createplainmark{glossary}{both}{\glossaryname}}
\makeevenhead{companion}{\normalfont\bfseries\thepage}{}%
                        {\normalfont\bfseries\leftmark}
\makeoddhead{companion}{\normalfont\bfseries\rightmark}{}%
                       {\normalfont\bfseries\thepage}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% Another pagestyle called \pstyle{showlocs} can be used to show the
% locations of the header, footer and textblock. I would expect that
% this would be mainly used as an example for authors to create their
% own similar styles.
% \changes{v1.6180339c}{2008/12/28}{Added the showlocs pagestyle and supporting
%                       macros}
% \changes{v1.6180339c}{2009/01/25}{Added more supporting macros for the 
%                       showlocs pagestyle}
%
% \begin{macro}{\ifshowheadfootloc}
% \begin{macro}{\showheadfootloctrue}
% \begin{macro}{\showheadfootlocfalse}
% \begin{macro}{\showheadfootlocon}
% \begin{macro}{\showheadfootlocoff}
% \begin{macro}{\ifshowtextblockloc}
% \begin{macro}{\showtextblockloctrue}
% \begin{macro}{\showtextblocklocfalse}
% \begin{macro}{\showtextblocklocon}
% \begin{macro}{\showtextblocklocoff}
% Booleans controlling the appearance, or not, of the header/footer lines
% and text frame in \pstyle{showlocs}.
%    \begin{macrocode}
\newif\ifshowheadfootloc
  \showheadfootloctrue
\newcommand*{\showheadfootlocon}{\showheadfootloctrue}
\newcommand*{\showheadfootlocoff}{\showheadfootlocfalse}
\newif\ifshowtextblockloc
  \showtextblockloctrue
\newcommand*{\showtextblocklocon}{\showtextblockloctrue}
\newcommand*{\showtextblocklocoff}{\showtextblocklocfalse}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \begin{macro}{\framepichook}
% \changes{v3.6k}{2013/05/08}{Added \cs{framepichook}}
%   The two macros \cs{framepichead} and \cs{framepictextfoot} are used
%   to make up the \texttt{showlocs} page style. They are both zero
%   width \texttt{picture} environments. The very first thing in these
%   \texttt{picture} environments, is a call to \cs{framepichook}
%   (empty by default), which could be used to change the color of the
%   frame.
%    \begin{macrocode}
\newcommand\framepichook{}
%    \end{macrocode}
%   
% \end{macro}
% \begin{macro}{\framepichead}
% For producing a zero-sized picture of a line at the base of the header.
% It is meant to be used as the left part of the header for a pagestyle.
% \changes{v1.6180339c}{2008/12/28}{Added \cs{framepichead}}
% \changes{v3.6k}{2013/05/08}{Added \cs{framepichook}}
%    \begin{macrocode}
\newcommand*{\framepichead}{%
\ifshowheadfootloc
  \begin{picture}(0,0)
    \framepichook
    \unitlength 1pt
    \put(0,0){\line(1,0){\strip@pt\textwidth}}
  \end{picture}%
\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\framepictextfoot}
% For producing a zero-sized picture of a line at the base of the footer
% and a frame around the text block. It is meant to be used as the left
% part of a footer for a pagestyle.
% \changes{v1.6180339c}{2008/12/28}{Added \cs{framepictextfoot}}
% \changes{v3.6k}{2013/05/08}{Added \cs{framepichook}}
%    \begin{macrocode}
\newcommand*{\framepictextfoot}{%
  \begin{picture}(0,0)
    \framepichook
    \unitlength 1pt
    \ifshowheadfootloc
      \put(0,0){\line(1,0){\strip@pt\textwidth}}
    \fi
    \ifshowtextblockloc
      \put(0,\strip@pt\footskip)%
        {\framebox(\strip@pt\textwidth,\strip@pt\textheight){}}
    \fi
  \end{picture}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ps@showlocs}
% The \pstyle{showlocs} pagestyle. This is more to show what can be done.
% \changes{v1.6180339c}{2008/12/28}{Added the showlocs pagestyle}
%    \begin{macrocode}
\makepagestyle{showlocs}
\makeevenhead{showlocs}{\framepichead\thepage}{\thepage}{\thepage}
\makeoddhead{showlocs}{\framepichead\thepage}{\thepage}{\thepage}
\makeevenfoot{showlocs}{\framepictextfoot\thepage}{\thepage}{\thepage}
\makeoddfoot{showlocs}{\framepictextfoot\thepage}{\thepage}{\thepage}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\fixheaderwidths}
% The companion pagestyle, at least, needs adjusting (at \cs{fixthelayout} time)
% if the \cs{textwidth} has changed from its initial value.
% \changes{v1.6180339f}{2009/03/16}{Added \cs{fixheaderwidths}}
%    \begin{macrocode}
\newcommand*{\fixheaderwidths}{%
  % companion pagestyle
  \setlength{\headwidth}{\textwidth}
    \addtolength{\headwidth}{\marginparsep}
    \addtolength{\headwidth}{\marginparwidth}
  \makerunningwidth{companion}{\headwidth}
  \makeheadrule{companion}{\headwidth}{\normalrulethickness}
  \makefootrule{companion}{\textwidth}{\footruleheight}{\footruleskip}
}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Page numbering}
%
%    The kernel includes the \cs{pagenumbering} command for setting the
% style (arabic, roman, etc.) of the page numbers, and at the same
% time it resets the page counter. I want a version that resets the style
% but not the number\footnote{Added to meet a request by Daniel Richard G.
% (\texttt{skunk@mit.edu}) September 2001.}.
%
% \begin{macro}{\pagenumbering}
% \begin{macro}{\pagenumbering*}
% \cs{pagenumbering}\marg{style} is the normal version whereas
% the starred version does not reset the counter.
% \changes{v1.0}{2001/09/21}{Added \cs{pagenumbering} and \cs{pagenumbering*} }
%    \begin{macrocode}
\renewcommand{\pagenumbering}{%
  \@ifstar{\@smempnum}{\@mempnum}}
%    \end{macrocode}
% \begin{macro}{\@smempnum}
%    \begin{macrocode}
\newcommand{\@smempnum}[1]{%
  \gdef\thepage{\csname @#1\endcsname \c@page}}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\@mempnum}
%    \begin{macrocode}
\newcommand{\@mempnum}[1]{%
  \@smempnum{#1}\global\c@page \@ne}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\c@storedpagenumber}
% A counter to store the page number.
%    \begin{macrocode}
\newcounter{storedpagenumber}
  \setcounter{storedpagenumber}{1}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\savepagenumber}
% \begin{macro}{\restoregenumber}
% \cs{savepagenumber} saves the current page number and \cs{restorepagenumber}
% sets the page number to the stored value.
% \changes{v1.0}{2001/09/24}{Added \cs{savepagenumber} and \cs{restorepagenumber}}
%    \begin{macrocode}
\newcommand{\savepagenumber}{\global\c@storedpagenumber \c@page}
\newcommand{\restorepagenumber}{\global\c@page \c@storedpagenumber}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% \section{Non-traditional spacing}
% \changes{v1.61803}{2008/01/30}{Added non-traditional spacing 
%                     (mempatch v4.6)}
%
% \subsection{Double spacing}
%
% This is an embedding and extension of the code from the \Lpack{setspace} 
% package, with
% names changed.
%
% \begin{macro}{\setSpacing}
% \cs{setSpacing}\marg{num} effectively increases the \cs{baselineskip} to 
% \meta{num}*\cs{baselineskip}.
% (In package was \cs{setstretch}).
%    \begin{macrocode}
\newcommand*{\setSpacing}[1]{%
  \def\baselinestretch{#1}%
  \@currsize}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setSingleSpace}
% \begin{macro}{\setFootnoteSpacing}
% \begin{macro}{\setFloatSpacing}
% \cs{setSingleSpace}\marg{num} effectively increases the \cs{baselineskip} for
% single spacing to \meta{num}*\cs{baselineskip} (\meta{num} should be 
% close to 1.0). (In package was \cs{SetSinglespace}). We extend with
% two extra macros \cs{setFootnoteSpacing} and \cs{setFloatSpacing}
% which can be used to explicitly set the spacing inside page notes
% (fotnotes and friends) and inside floats. Changing
% \cs{setSingleSpace} will also set page note and float spacings to
% the same value.
% \changes{v3.6g}{2010/09/19}{Added two extra 'single' spacing macros}
%    \begin{macrocode}
\newcommand*{\setSingleSpace}[1]{%
  \def\m@m@singlespace{#1}%
  \def\m@m@footnote@spacing{#1}%
  \def\m@m@float@spacing{#1} %
}
\setSingleSpace{1}
\newcommand*\setPagenoteSpacing[1]{\def\m@m@footnote@spacing{#1}}
\newcommand*\setFloatSpacing[1]   {\def\m@m@float@spacing{#1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\SingleSpacing}
% \begin{macro}{\SingleSpacing*}
% \cs{SingleSpacing} starts single spacing. (In package was \cs{singlespacing}).
% \changes{v3.6g}{2010/09/19}{Added reset of the float and page note spacings}
%    \begin{macrocode}
\newcommand*{\SingleSpacing}{%
  \setSpacing{\m@m@singlespace}%
  \edef\m@m@footnote@spacing{\baselinestretch}%
  \edef\m@m@float@spacing{\baselinestretch}%
%    \end{macrocode}
% \changes{v3.7h}{2018/09/19}{Added the ifstar and \cs{@noocument}}
% We can have a strange interaction with \Lpack{tikz} if this
% \cs{vskip} is emitted in the preamble. We use a trick (via David
% Carlisle) to check whether we are in the preamble, and only emit the
% vskip if we are not. \cs{@ifstar} added to let the user disable the
% vskip if needed.
%    \begin{macrocode}
  \@ifstar{}{\ifx\@nodocument\relax\vskip\baselineskip\fi}% correction for coming into single spacing
}
\SingleSpacing

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@OnehalfSpacing}
% \begin{macro}{\OnehalfSpacing}
% \cs{OnehalfSpacing} starts `one and a half' spacing, which to most 
% thesis nitpickers will look like double spacing.
% (In package was \cs{onehalfspacing}). The starred version
% \cs{OnehalfSpacing*} will also give page notes and floats the same spacing
% \changes{v3.6g}{2010/09/19}{Made \cs{OnehalfSpacing} into a starred
% version such that the starred version makes everything one half
% spaced including page notes and floats}
%    \begin{macrocode}
\newcommand*{\@OnehalfSpacing}{
  \setSpacing{1.25}% default (10pt)
  \ifcase \@ptsize \relax   % 10pt
    \setSpacing{1.25}%
  \or%  11pt
    \setSpacing{1.213}%
  \or%  12pt
    \setSpacing{1.241}%
  \or\or% 14pt
    \setSpacing{1.20}%
  \or\or\or% 17pt
    \setSpacing{1.16}%
  \or\or% 9pt
    \setSpacing{1.35}%
  \else% the extended sizes
    \setSpacing{1.16}%
  \fi}
\newcommand*\OnehalfSpacing{%
  \@ifstar{%
    \@OnehalfSpacing%
    \edef\m@m@footnote@spacing{\baselinestretch}%
    \edef\m@m@float@spacing{\baselinestretch}%
  }{\@OnehalfSpacing}%
}
    
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\DoubleSpacing}
% \begin{macro}{\@DoubleSpacing}
% \cs{DoubleSpacing} starts double spacing, which to most thesis nitpickers
% will look far too spaced out. (In package was
% \cs{doublespacing}). The starred version will also set the page note
% and float spacing to the same value.
% \changes{v3.6g}{2010/09/19}{Extended with a starred version.}
%    \begin{macrocode}
\newcommand*{\@DoubleSpacing}{
  \setSpacing{1.667}% default (10pt)
  \ifcase \@ptsize \relax   % 10pt
    \setSpacing{1.667}%
  \or%  11pt
    \setSpacing{1.618}%
  \or%  12pt
    \setSpacing{1.655}%
  \or\or% 14pt
    \setSpacing{1.60}%
  \or\or\or% 17pt
    \setSpacing{1.545}%
  \or\or% 9pt
    \setSpacing{1.8}%
  \else%       larger sizes
    \setSpacing{1.5}%
  \fi}
\newcommand*\DoubleSpacing{%
  \@ifstar{%
    \@DoubleSpacing%
    \edef\m@m@footnote@spacing{\baselinestretch}%
    \edef\m@m@float@spacing{\baselinestretch}%
  }{\@DoubleSpacing}%
}
    
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@setsize}
% Modify the kernel command.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% check what this does!!!!!!!!
%    \begin{macrocode}
\renewcommand*{\@setsize}[4]{%
  \@nomath#1%
  \let\@currsize#1%
  \baselineskip #2%
  \baselineskip \baselinestretch\baselineskip
  \parskip \baselinestretch\parskip
  \setbox\strutbox \hbox{%
    \vrule height.7\baselineskip
           depth .3\baselineskip
           width \z@}%
  \skip\footins \baselinestretch\skip\footins
  \normalbaselineskip\baselineskip#3#4}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{environment}{SingleSpace}
% Environment form of \cs{SingleSpacing}. (In package was \texttt{singlespace}).
%    \begin{macrocode}
\newenvironment{SingleSpace}{%
  \vskip\baselineskip
  \setSpacing{\m@m@singlespace}%
  \vskip -\baselineskip
}{\par}

%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{SingleSpace*}
% Don't use this; it's only here to match the \Lpack{setspace} package. 
% (In package was \texttt{singlespace*}).
%    \begin{macrocode}
\newenvironment{SingleSpace*}{%
%%  \vskip\baselineskip
  \setSpacing{\m@m@singlespace}%
  \vskip 0.5\baselineskip
}{\vskip -0.5\baselineskip}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\m@mrestore@spacing}
%    \begin{macrocode}
\newcommand*{\m@mrestore@spacing}{%
  \par
  \vskip \parskip
  \vskip \baselineskip
  \endgroup
  \vskip -\parskip
  \vskip -\baselineskip}

%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{Spacing}
% \verb?\begin{Spacing}{num}? increases the \cs{baselineskip} 
% to \verb?num*\baselineskip?. (In package was \texttt{spacing}).
%    \begin{macrocode}
\newenvironment{Spacing}[1]{%
  \par
  \begingroup
    \setSpacing{#1}}{\m@mrestore@spacing}

%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{OnehalfSpace}
% Environment form of \cs{OnehalfSpacing}. (In package was \texttt{onehalfspace}).
% \changes{v3.6g}{2010/09/19}{Added starred version of environment to
% complement the starred macro version}
%    \begin{macrocode}
\newenvironment{OnehalfSpace}{%
  \begingroup
    \OnehalfSpacing}{\m@mrestore@spacing}
\newenvironment{OnehalfSpace*}{%
  \begingroup
    \OnehalfSpacing*}{\m@mrestore@spacing}

%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{DoubleSpace}
% Environment form of \cs{DoubleSpacing}. (In package was \texttt{doublespace}).
% \changes{v3.6g}{2010/09/19}{Added starred version of environment to
% complement the starred macro version}
%    \begin{macrocode}
\newenvironment{DoubleSpace}{%
  \begingroup
    \DoubleSpacing}{\m@mrestore@spacing}
\newenvironment{DoubleSpace*}{%
  \begingroup
    \DoubleSpacing}{\m@mrestore@spacing}

%    \end{macrocode}
% \end{environment}
%
%
%  Deal with spacing around displays.
%
% \begin{macro}{\memdskipstretch}
% \begin{macro}{\setDisplayskipStretch}
% \begin{macro}{\noDisplayskipStretch}
% \cs{setDisplayskipStretch}\marg{num} changes space around displays by the
% factor (1+\meta{num}). \cs{noDisplaydkipStretch} keeps the regular
% spacing around displays. (In package were \cs{setdisplayskipstretch} and
% the \texttt{nodisplayskipstretch} option).
%    \begin{macrocode}
\newcommand*{\memdskipstretch}{0.0}
\newcommand*{\setDisplayskipStretch}[1]{%
  \renewcommand*{\memdskipstretch}{#1}}
\newcommand*{\noDisplayskipStretch}{\setDisplayskipStretch{0.0}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memdskips}
% Macro added to the kernel hook \cs{everydisplay}, changing the settings 
% of displayskips
%    \begin{macrocode}
\newcommand*{\memdskips}{%
  \advance\abovedisplayskip \memdskipstretch\abovedisplayskip
  \advance\belowdisplayskip \memdskipstretch\belowdisplayskip
  \advance\abovedisplayshortskip \memdskipstretch\abovedisplayshortskip
  \advance\belowdisplayshortskip \memdskipstretch\belowdisplayshortskip}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\everydisplay}
%    \begin{macrocode}
\everydisplay\expandafter{%
  \the\everydisplay
  \memdskips}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@xfloat}
%   Reset \cs{baselinestretch} in floats. Because of a package like
%   \Lpack{fixltx2e} (recommended package), we have to delay the
%   addition.
%   \changes{v3.7d}{2014/07/28}{Delayed addition to
%   \cs{@xfloat}. Reported by Ulrike Fischer}.
%   \changes{v3.7g}{2017/05/08}{Delayed the addition of the adjustment
%   to the float until after \cs{normalsize}. Reported at \protect\url{https://tex.stackexchange.com/q/368422/3929}}
%    \begin{macrocode}
\AtBeginDocument{
  \let\m@m@xfloat\@xfloat
  \def\@xfloat #1[#2]{%
    \m@m@xfloat #1[#2]%
    \def\baselinestretch{\m@m@float@spacing}%
    \normalsize%
    \@nameuse{#1adjustment}%
  }
}

%    \end{macrocode}
% \end{macro}
%
%  The extra spacing does not add space before and after a minipage.
% The solution, hinted at by Donald Arseneau, is to create a new
% environment. I came up with a solution which DA then much improved upon
% (CTT \textit{setspace and minipages}, 2006/11/28). 
% This is like minipage from an author's view, except that it is 
% always top positioned and acts like a paragraph.
% \begin{macro}{\memPD}
%    \begin{macrocode}
\newdimen\memPD
%    \end{macrocode}
% \end{macro}
% \begin{environment}{vminipage}
% The user view, just as for \texttt{minipage}, but ensures the \texttt{t}
% position and as a new paragraph. It is like \texttt{minipage} but with 
% better fore and aft spacing.
%    \begin{macrocode}
\newenvironment{vminipage}{%
  \par
  \@ifnextchar[%]
    \@ivminipage
    {\@iiiminipage t\relax[s]}
}{%
  \par\global\memPD=\prevdepth
  \endminipage
  \par
  \kern-\memPD%     no pagebreak allowed here
  \hbox{\vrule depth \memPD width \z@}}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\@ivminipage}
% Deal with first optional argument to \texttt{vminipage}.
%    \begin{macrocode}
 \def\@ivminipage[#1]{%
  \@ifnextchar[%]
    {\@iiminipage{t}}{\@iiiminipage{t}\relax[s]}}
%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Abnormal parskips}
%
% Non-zero, positive \cs{parskip}, which is not to be encouraged. Code
% based on Robin Fairbairns \Lpack{parskip} package and the NTG classes.
%
% \begin{macro}{\ifm@mnzpskip}
% \begin{macro}{\m@mnzpskiptrue}
% \begin{macro}{\m@mnzpskipfalse}
% \cs{ifm@mnzpskip} is TRUE if \cs{parskip} set to anything but 0pt.
%    \begin{macrocode}
\newif\ifm@mnzpskip
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\traditionalparskip}
% \begin{macro}{\m@mabparskip}
% \begin{macro}{\abnormalparskip}
% \begin{macro}{\nonzeroparskip}
% \cs{traditionalparskip} sets \cs{parskip} to 0pt.
% \cs{abnormalparskip}\marg{length} sets \cs{parskip} to \meta{length}.
% \cs{nonzeroparskip} sets \cs{parskip} to a non-zero value that might be 
% not too bad (any non-zero \cs{parskip} is not good).
% \changes{v1.61803398c}{2009/11/13}{\cs{parskip} was set to \cs{z@},
% thus the stretch was missing, this broke \cs{flushbottom}}
%    \begin{macrocode}
\newcommand*{\traditionalparskip}{%
  \setlength\parskip{0\p@ \@plus \p@}
  \m@mnzpskipfalse}
\newskip\m@mabparskip
\newcommand*{\abnormalparskip}[1]{%
  \setlength{\parskip}{#1}\m@mabparskip=#1\relax
  \m@mnzpskiptrue}
\newcommand*{\nonzeroparskip}{\abnormalparskip{%
  0.5\baselineskip 
  \@plus .1\baselineskip \@minus .1\baselineskip% NTG
%%  0.5/baselineskip \@plus 2pt% RF
}}
\traditionalparskip

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@minpagerestore}
% This needs extending: here's what NTG does, but I've put the
% appropriate code later.
% \begin{verbatim}
% \providecommand*{\@minipagerestore}{%
%   \parskip=.5\baselineskip \@plus .1\baselineskip \@minus .1\baselineskip}
% \end{verbatim}
% \end{macro}
%
% \section{Titles}
%
%    For books the title is usually designed specifically for the particular
% work, so originally the class did not provide a \cs{maketitle} command or 
% any of the \cs{title} and other commands that normally go along with this. 
%    After some thought I decided to add in the code from the 
% \Lpack{titling} package~\cite{TITLING}. However, in this case life
% is a bit simpler as there is no pre-existing class code.
% \changes{v0.3}{2001/07/09}{Added titling code}
%
% \begin{macro}{\pretitle}
% \begin{macro}{\@bspretitle}
% \begin{macro}{\posttitle}
% \begin{macro}{\@bsposttitle}
% \begin{macro}{\preauthor}
% \begin{macro}{\@bspreauthor}
% \begin{macro}{\postauthor}
% \begin{macro}{\@bspostauthor}
% \begin{macro}{\predate}
% \begin{macro}{\@bspredate}
% \begin{macro}{\postdate}
% \begin{macro}{\@bspostdate}
%    To provide some flexibilty in the titling style of the document,
% user level commands are provided that can be changed to reconfigure
% the appearance resulting from \cs{maketitle}. 
%    \begin{macrocode}
\newcommand{\pretitle}[1]{\def\@bspretitle{#1}}
\newcommand{\posttitle}[1]{\def\@bsposttitle{#1}}
\newcommand{\preauthor}[1]{\def\@bspreauthor{#1}}
\newcommand{\postauthor}[1]{\def\@bspostauthor{#1}}
\newcommand{\predate}[1]{\def\@bspredate{#1}}
\newcommand{\postdate}[1]{\def\@bspostdate{#1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% These are defined initially
% to mimic the normal \LaTeX{} style.
%    \begin{macrocode}
  \pretitle{\begin{center}\LARGE}
  \posttitle{\par\end{center}\vskip 0.5em}
  \preauthor{\begin{center}
    \large \lineskip .5em%
    \begin{tabular}[t]{c}}
  \postauthor{\end{tabular}\par\end{center}}
  \predate{\begin{center}\large}
  \postdate{\par\end{center}}

%    \end{macrocode}
%
% \begin{macro}{\maketitlehooka}
% \begin{macro}{\maketitlehookb}
% \begin{macro}{\maketitlehookc}
% \begin{macro}{\maketitlehookd}
% The four hooks which will be called by \cs{maketitle}. These are initially
% vacuous.
%    \begin{macrocode}
\newcommand{\maketitlehooka}{}
\newcommand{\maketitlehookb}{}
\newcommand{\maketitlehookc}{}
\newcommand{\maketitlehookd}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\thanksmarkseries}
% \begin{macro}{\@bsmarkseries}
% \begin{macro}{\symbolthanksmark}
%  These are for specifying the kind of series for thanks markers.
%    \begin{macrocode}
\newcommand{\thanksmarkseries}[1]{%
  \def\@bsmarkseries{\renewcommand{\thefootnote}%
                     {\@nameuse{#1}{footnote}}}}
\newcommand{\symbolthanksmark}{\thanksmarkseries{\fnsymbol}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\continuousmarks}
% \begin{macro}{\@bscontmark}
% These are for (non) zeroing of the footnote counter.
%    \begin{macrocode}
\newcommand{\@bscontmark}{\setcounter{footnote}{0}}
\newcommand{\continuousmarks}{\def\@bscontmark{}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\thanksheadextra}
% \begin{macro}{\@bsthanksheadpre}
% \begin{macro}{\@bsthanksheadpost}
% These are for inserting stuff before and after a mark in the titling.
%    \begin{macrocode}
\newcommand{\thanksheadextra}[2]{%
  \def\@bsthanksheadpre{#1}%
  \def\@bsthanksheadpost{#2}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \changes{v1.2}{2002/08/10}{Deprecated \cs{thanksfootextra}}
% \changes{v1.2}{2002/08/10}{Removed \cs{thanksfootpre} and \cs{thanksfootpost}}
% \changes{v1.4}{2003/12/14}{Removed \cs{thanksfootextra}}
%
% \begin{macro}{\thanksmark}
% This adds a thanks mark. The \cs{footnotemark} could have been used directly
% but it is fragile in a moving argument.
%    \begin{macrocode}
\DeclareRobustCommand{\thanksmark}[1]{\footnotemark[#1]}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\thanksgap}
% This specifies some horizontal space.
%    \begin{macrocode}
\newcommand{\thanksgap}[1]{\hspace{#1}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\tamark}
% This stores the current definition of \cs{@thefnmark}. For some reason
% using \cs{@thefnmark} directly only gave the last value.
%    \begin{macrocode}
\newcommand{\tamark}{\@thefnmark}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\thanksmarkwidth}
% A length determining the size of the box for typesetting
% a thanks marker.
%    \begin{macrocode}
\newlength{\thanksmarkwidth}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\thanksmarksep}
% A length determining the inset of thanks footnotes.
% \changes{v1.2}{2002/08/10}{Replaced \cs{thanksmargin} by \cs{thanksmarksep}}
%    \begin{macrocode}
\newlength{\thanksmarksep}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\thanksmarkstyle}
% \begin{macro}{\thanksscript}
% \cs{thanksscript} is a wrapper round the actual mark stuff to be typeset. 
% The user can define this via \cs{thanksmarkstyle}\marg{code}.
% The default is a superscript mark.
% \changes{v1.2}{2002/08/10}{Added \cs{thanksmarkstyle}}
%    \begin{macrocode}
\newcommand{\thanksmarkstyle}[1]{\def\thanksscript##1{#1}}
\thanksmarkstyle{\textsuperscript{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\makethanksmarkhook}
% A vacuous macro used as a hook into \cs{makethanksmark}.
%    \begin{macrocode}
\newcommand{\makethanksmarkhook}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\thanksfootmark}
% This typesets the thanks footnote mark.
% \changes{v1.2}{2002/08/10}{Complete rewrite of \cs{thanksfootmark}}
%    \begin{macrocode}
\newcommand{\thanksfootmark}{%
  \ifdim\thanksmarkwidth < \z@
%    \end{macrocode}
% Negative width, mark is in the margin.
%    \begin{macrocode}
    \llap{\hb@xt@ -\thanksmarkwidth{%
          \hss\normalfont\thanksscript{\tamark}}%
          \hspace*{-\thanksmarkwidth}}%
  \else
    \ifdim\thanksmarkwidth = \z@
%    \end{macrocode}
% Zero width, mark is at (inside) the margin.
%    \begin{macrocode}
      {\normalfont\thanksscript{\tamark}}%
    \else
%    \end{macrocode}
% Positive width.
%    \begin{macrocode}
      \hb@xt@\thanksmarkwidth{\hss\normalfont\thanksscript{\tamark}}%
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makethanksmark}
% This sets the general indentations for the thanks footnote, 
% and typesets the mark. The code is a simplified version of that
% for typesetting ToC entries.
% \changes{v1.2}{2002/08/10}{Minor changes to \cs{makethanksmark}}
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{makethanksmark}}
% \changes{v1.61803398b}{2009/09/21}{fixed typo, \cs{thanksmarksep}
% not \cs{thanksmark}}
%    \begin{macrocode}
\newcommand{\makethanksmark}{%
  \leavevmode%
  \parindent 1em\noindent
%%%  \leftskip\thanksmarksep\relax
  \memRTLleftskip\thanksmarksep\relax
%%%  \advance\leftskip\thanksmarkwidth 
  \advance\memRTLleftskip\thanksmarkwidth
%%%  \null\nobreak\hskip-\leftskip\relax
  \null\nobreak\hskip-\memRTLleftskip\relax
  \makethanksmarkhook\relax
  \thanksfootmark}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\usethanksrule}
% \begin{macro}{\cancelhanksrule}
%  Simple macros that let \cs{footnoterule} to another rule definition.
%    \begin{macrocode}
\newcommand{\usethanksrule}{\let\footnoterule\thanksrule}
\newcommand{\cancelthanksrule}{\let\footnoterule\@bsfootnoterule}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
%    Now set up the rest of the thanks defaults, styling having been
% done earlier.
%    \begin{macrocode}
\thanksmarkseries{fnsymbol}  % symbols
\thanksheadextra{}{}
\setlength{\thanksmarkwidth}{1.8em}
\setlength{\thanksmarksep}{-\thanksmarkwidth}

%    \end{macrocode}
% \begin{macro}{\thanksrule}
% \begin{macro}{\@bsfootnoterule}
% These are saved versions of the \cs{footnoterule} definition as it
% is at the end of the preamble.
%    \begin{macrocode}
\AtBeginDocument{%
  \let\thanksrule\footnoterule
  \let\@bsfootnoterule\footnoterule
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\droptitle}
% A titling block has \cs{droptitle} amount of additional vertical space 
% above it (normally zero).
%    \begin{macrocode}
\newlength{\droptitle}
\setlength{\droptitle}{0pt}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\maketitle}
% The following is a
% modification of \cs{maketitle} as in the \Lpack{article}, \Lpack{report},
% and \Lpack{book} classes. It sets the pagestyle to \pstyle{title}.
% \changes{v1.4}{2004/01/21}{Removed the \cs{rlap} from \cs{@makefnmark}
%                            in \cs{maketitle} so multiple \cs{thanks}
%                            work per \cs{footnote}}
% \changes{v1.618}{2005/09/03}{Fix to remove extra blank page when
%   \cs{maketitle} (and \cs{@maketitle}) is used within adjustwidth
%    inside a titlingpage (mempatch v3.2)}
%    \begin{macrocode}
\newcommand{\maketitle}{\par
  \begingroup
    \@bsmarkseries
    \def\@makefnmark{\@textsuperscript{%
       \normalfont\@bsthanksheadpre \tamark \@bsthanksheadpost}}%
    \long\def\@makefntext##1{\makethanksmark ##1}
    \if@twocolumn
      \ifnum \col@number=\@ne
        \@maketitle
      \else
        \twocolumn[\@maketitle]%
      \fi
    \else
      \ifdim\pagetotal>\z@
        \newpage
      \fi
      \global\@topnum\z@
      \@maketitle
    \fi
    \thispagestyle{title}\@thanks
  \endgroup
  \@bscontmark  %  \setcounter{footnote}{0}%
  }
\aliaspagestyle{title}{plain}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@mem@titlefootkill}
% \cs{@mem@titlefootkill}\marg{note} Warn about footnotes in titles.
%    \begin{macrocode}
\newcommand*{\@mem@titlefootkill}[1]{%
  \@memwarn{Do not use \string\footnote\space in 
            \string\maketitle.\MessageBreak
            Use \protect\thanks\space instead}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@maketitle}
% Our version of \cs{@maketitle}.
% Footnotes are killed in the title; see the thread `\cs{title}, \cs{author}
% and \cs{footnote} feature in memoir class', February 2003.
% \changes{v1.4}{2003/11/16}{Killed footnote in titles (from patch v1.4)}
%    \begin{macrocode}
\newcommand{\@maketitle}{%               
  \let\footnote\@mem@titlefootkill
  \ifdim\pagetotal>\z@
    \newpage
  \fi
  \null
  \vskip 2em%
        \vspace*{\droptitle}
  \maketitlehooka
  {\@bspretitle \@title \@bsposttitle}
  \maketitlehookb
  {\@bspreauthor \@author \@bspostauthor}
  \maketitlehookc
  {\@bspredate \@date \@bspostdate}
  \maketitlehookd
  \par
  \vskip 1.5em}

%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{mem@titlingpage}
% \begin{environment}{titlingpage}
% \begin{environment}{titlingpage*}
% \begin{macro}{\titlingpageend}
%   The \Lenv{titlingpage} environment sets the pagestyle to be \pstyle{titlingpage},
% disables the footnote rule and ensures that the page is single
% column. At the end it switches back to twocolumn if neccessary,
% and then starts a new page as number 1. On the other hand
% \Lenv{titlingpage*}, does \emph{not} reset the page counter.
%
% At the end of the titlingpage we clear the page to let the next data
% start on a new page. However there is a slight complication
% here. Should we clear to next page or to next righthand page. One
% could argue that under \Lopt{twoside} going to next right hand page
% would be best, but then there is also \Lopt{openany}. In order to
% make this configurable we will factor this out in a configurable
% macro, and leave the defaults as they are so not to mess with
% existing documents.
% \changes{v3.6k}{2012/12/24}{Added \Lenv{titlingpage*} env}
% \changes{v3.7g}{2018/03/06}{Added \cs{titlingpageend}}
%    \begin{macrocode}
\newcommand\titlingpageend[2]{%
  \def\mem@titlingpage@clear@for@twoside{#1}%
  \def\mem@titlingpage@clear@for@oneside{#2}%
}
 % default
\titlingpageend{\cleardoublepage}{\clearpage}
\newenvironment{mem@titlingpage}%
  {\let\footnoterule\relax
   \let\footnotesize\small
   \if@twocolumn
     \@restonecoltrue\onecolumn
   \else
     \@restonecolfalse
   \fi
   \thispagestyle{titlingpage}%
   \if\mem@titlpg@reset\setcounter{page}{\@ne}\fi%
  }{%
   \thispagestyle{titlingpage}%
   \if@restonecol \twocolumn \fi
   % \if@twoside \cleardoublepage \else \clearpage \fi
   \if@twoside \mem@titlingpage@clear@for@twoside \else \mem@titlingpage@clear@for@oneside \fi
   \if\mem@titlpg@reset\setcounter{page}{\@ne}\fi}
\newenvironment{titlingpage}{%
  \def\mem@titlpg@reset{00}%
  \begin{mem@titlingpage}}{%
  \end{mem@titlingpage}}
\newenvironment{titlingpage*}{%
  \def\mem@titlpg@reset{01}%
  \begin{mem@titlingpage}}{%
  \end{mem@titlingpage}}
\aliaspagestyle{titlingpage}{empty}

%    \end{macrocode}
% \end{macro}
% \end{environment}
% \end{environment}
% \end{environment}
%
% \begin{macro}{\emptythanks}
% This macro discards all prior \cs{thanks} texts.
%    \begin{macrocode}
\newcommand{\emptythanks}{\global\let\@thanks\@empty}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\andnext}
%  The kernel \cs{and} macro puts space between author's names. The
% \cs{andnext} macro puts a newline between the names.
% \changes{v1.6}{2004/01/28}{Added \cs{andnext}}
%    \begin{macrocode}
\newcommand*{\andnext}{%
  \end{tabular}\\ \begin{tabular}[t]{c}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@bsmtitlempty}
%    \cs{@bsmtitlempty} is a helper macro to save some macro space. 
% It empties some elements of \cs{maketitle}.
% \changes{v3.6k}{2012/07/01}{Removed \cs{thanksfootextra}, seems to
% have been forgotten back in 2003.}
%    \begin{macrocode}
\newcommand{\@bsmtitlempty}{%
  \global\let\maketitle\relax
  \global\let\@maketitle\relax
  \global\let\title\relax
  \global\let\author\relax
  \global\let\date\relax
  \global\let\thanksmarkseries\relax
  \global\let\thanksfootextra\relax
  \global\let\thanksmark\relax
  \global\let\thanksgap\relax}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\keepthetitle}
% This macro undefines all the titling commands except for
% \cs{thetitle}, \cs{theauthor} and \cs{thedate}.
% \changes{v1.6}{2004/01/28}{changed \cs{keepthetitle} to cater for \cs{andnext}}
%    \begin{macrocode}
\newcommand{\keepthetitle}{%
  \@bsmtitlempty
  \global\let\thanks\relax
  \global\let\and\relax
  \global\let\andnext\relax
  \global\let\@thanks\@empty
  \global\let\@title\@empty
  \global\let\@author\@empty
  \global\let\@date\@empty}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\killtitle}
% \cs{killtitle} undefines the remaining macros of \cs{maketitle}.
%    \begin{macrocode}
\newcommand{\killtitle}{%
  \keepthetitle
  \global\let\thetitle\relax
  \global\let\theauthor\relax
  \global\let\thedate\relax}

%    \end{macrocode}
% \end{macro}
%
% 
% \begin{macro}{\thetitle}
% \begin{macro}{\theauthor}
% \begin{macro}{\thedate}
%    In order to make the \cs{title}, etc., values available for printing
% their definitions (in \file{ltsect.dtx}) need extending to save their 
% arguments. We have to make sure that extraneous material,
% like \cs{thanks}, is excluded from the saved texts.
% \changes{v1.4}{2003/11/16}{Gobble footnotes in \cs{title}, \cs{author}
%               and \cs{date} (from patch v1.4)}
% \changes{v1.6}{2004/01/28}{Added \cs{andnext} handling to \cs{author}}
%    \begin{macrocode}
\addtoiargdef{\title}{%
  \begingroup\let\footnote\@gobble}{%
  \begingroup
    \renewcommand{\thanks}[1]{}
    \renewcommand{\thanksmark}[1]{}
    \renewcommand{\thanksgap}[1]{}
    \protected@xdef\thetitle{#1}
  \endgroup\endgroup}
\addtoiargdef{\author}{%
  \begingroup\let\footnote\@gobble}{%
  \begingroup
    \renewcommand{\thanks}[1]{}
    \renewcommand{\and}{\unskip, }
    \renewcommand{\andnext}{\unskip, }
    \renewcommand{\thanksmark}[1]{}
    \renewcommand{\thanksgap}[1]{}
    \protected@xdef\theauthor{#1}
  \endgroup\endgroup}
\addtoiargdef{\date}{%
  \begingroup\let\footnote\@gobble}{%
  \begingroup
    \renewcommand{\thanks}[1]{}
    \renewcommand{\thanksmark}[1]{}
    \renewcommand{\thanksgap}[1]{}
    \protected@xdef\thedate{#1}
  \endgroup\endgroup}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% 
% \section{Parts, chapters and other divisions}
%
% \subsection{Building blocks} The definitions in this part of a
%    class file usually make use of two internal macros, \cs{@startsection} and
%    \cs{secdef}. To understand
%    what is going on here, we describe their syntax.
%
% \DescribeMacro{\@startsection}
%    The macro \cs{@startsection} has 6 required arguments, optionally
%    followed by  a $*$, an optional argument and a required argument:
%
%    \cs{@startsection}\meta{name}\meta{level}\meta{indent}^^A
%                    \meta{beforeskip}\meta{afterskip}\meta{style}
%            optional * %\\
%    \null\hphantom{\bslash @startsection}^^A
%            \oarg{altheading}\meta{heading}
%
%    It is a generic command to start a section, the arguments have
%    the following meaning:
%
%    \begin{description}
%    \item[\meta{name}] The name of the user level command, e.g.,
%          `section'.
%    \item[\meta{level}] A number, denoting the depth of the section
%          --- e.g., chapter = 0, section = 1, etc.  A section number
%          will be printed if and only if \meta{level} $<=$  the value
%          of the \Lcount{secnumdepth} counter.
%    \item[\meta{indent}] The indentation of the heading from the left
%          margin
%    \item[\meta{beforeskip}] The absolute value of this argument
%          gives the skip to leave above the heading. If it is
%          negative, then the paragraph indent of the text following
%          the heading is suppressed.
%    \item[\meta{afterskip}] If positive, this gives the skip to leave
%          below the heading, else it gives the skip to leave to the
%          right of a run-in heading.
%    \item[\meta{style}] Commands to set the style of the heading.
%    \item[$*$] When this is missing the heading is numbered and the
%          corresponding counter is incremented.
%    \item[\meta{altheading}] Gives an alternative heading to use in
%          the table of contents and in the running heads. This should
%          be present when the $*$ form is used.
%    \item[\meta{heading}] The heading of the new section.
%    \end{description}
%  A sectioning command is normally defined to \cs{@startsection} and
%  its first six arguments.
%
% \DescribeMacro{\secdef}
%    The macro \cs{secdef} can be used when a sectioning command is
%    defined without using \cs{@startsection}. It has two arguments:
%
%    \cs{secdef}\meta{unstarcmds}\meta{starcmds}
%
%    \begin{description}
%    \item[\meta{unstarcmds}] Used for the normal form of a
%          sectioning command.
%    \item[\meta{starcmds}] Used for the $*$-form of a
%          sectioning command.
%    \end{description}
%
%    You can use \cs{secdef} as follows:
% \begin{verbatim}
%       \def\chapter { ... \secdef \CMDA \CMDB }
%       \def\CMDA    [#1]#2{ ... }  % Command to define
%                                   % \chapter[...]{...}
%       \def\CMDB    #1{ ... }      % Command to define
%                                   % \chapter*{...}
% \end{verbatim}
%
% \DescribeMacro{\@hangfrom}
% Internally the \cs{@startsection} macro uses \verb?\@hangfrom{NUM}?, where
% \verb?NUM? is the sectional number, to produce a hanging paragraph. That is,
% the second and later lines of a multiline title are indented from the
% left margin by the width of the number.
% The definition of \cs{@hangfrom}, from \file{ltsect.dtx}, is:
% \begin{verbatim}
% \def\@hangfrom#1{\setbox\@tempboxa\hbox{{#1}}%
%   \hangindent \wd\@tempboxa\noindent\box\@tempboxa}
% \end{verbatim}
%
% To get a normal paragraphed title you can do: \\
% \verb?\renewcommand{\@hangfrom}[1]{#1}? \\
% or as a block paragraph: \\
% \verb?\renewcommand{\@hangfrom}[1]{\noindent #1}? \\
%
% \DescribeMacro{\@seccntformat}
% The \cs{@startsection} macro also uses \verb?\@seccntformat{NUM}? to format
% the section number, including the space after it. Its definition,
% from \file{ltsect.dtx}, is
% \begin{verbatim}
% \def\@seccntformat#1{\csname the#1\endcsname\quad}
% \end{verbatim}
% This is the command to change if you need different number formatting. For
% example the combination
% \begin{verbatim}
% \renewcommand{\@seccntformat}[1]{\llap{\csname the#1\endcsname\quad}}
% \renewcommand{\@hangfrom}[1]{\noindent #1}
% \end{verbatim}
% will hang the section numbers in the margin.
%
% \begin{table}
% \centering
% \caption{Document division levels}\label{tab:levels}
% \begin{tabular}{lr} \hline
% Division & Level \\ \hline
% book          & -2 \\
% part          & -1 \\
% chapter       &  0 \\
% section       &  1 \\
% subsection    &  2 \\
% subsubsection &  3 \\
% paragraph     &  4 \\
% subparagraph  &  5 \\ 
% \hline
% \end{tabular}
% \end{table}
%
%     The values used for the document division levels are the same
% as defined by the standard \LaTeX{} classes, with the exception
% of the book division which is a memoir addition, and are given in 
% Table~\ref{tab:levels}.
% \changes{v1.61803}{2008/01/30}{Added book division (from mempatch v4.4)}
% \subsection{Mark commands}
%
% \begin{macro}{\bookpagemark}
% \begin{macro}{\partmark}
% \begin{macro}{\chaptermark}
% \begin{macro}{\sectionmark}
% \begin{macro}{\subsectionmark}
% \begin{macro}{\subsubsectionmark}
% \begin{macro}{\paragraphmark}
% \begin{macro}{\subparagraphmark}
%  The default initialisations of the \cs{...mark} commands for use in
% the pagestyles. Most are already defined in the kernel but they are
% all noted here.
%    \begin{macrocode}
\newcommand*{\bookpagemark}[1]{}
\newcommand*{\partmark}[1]{}
\newcommand*{\chaptermark}[1]{}
% \newcommand*{\sectionmark}[1]{}
% \newcommand*{\subsectionmark}[1]{}
% \newcommand*{\subsubsectionmark}[1]{}
% \newcommand*{\paragraphmark}[1]{}
% \newcommand*{\subparagraphmark}[1]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\bibmark}
%  Marks for the bibliography, which may be filled with \cs{bibname}.
% \changes{v1.1}{2002/03/10}{Added \cs{bibmark}}
%    \begin{macrocode}
\newcommand*{\bibmark}{}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\indexmark}
% Marks for the index, which may be filled with \cs{indexname}.
% \changes{v1.1}{2002/03/10}{Added \cs{indexmark}}
%    \begin{macrocode}
\newcommand*{\indexmark}{}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\glossarymark}
% Marks for the glossary, which may be filled with \cs{glossaryname}.
% \changes{v1.618}{2005/09/25}{Added \cs{glossarymark}}
%    \begin{macrocode}
\newcommand*{\glossarymark}{}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Define Counters}
%
% \begin{macro}{\c@secnumdepth}
%    The value of the counter \Lcount{secnumdepth} gives the depth of
%    the highest-level sectioning command that is to produce section
%    numbers.
%    \begin{macrocode}
\setcounter{secnumdepth}{2}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\c@book}
% \begin{macro}{\c@part}
% \begin{macro}{\c@chapter}
% \begin{macro}{\c@section}
% \begin{macro}{\c@subsection}
% \begin{macro}{\c@subsubsection}
% \begin{macro}{\c@paragraph}
% \begin{macro}{\c@subparagraph}
%    These counters are used for the sectioning numbers. The macro\\
%    \cs{newcounter}\marg{newctr}\oarg{oldctr}\\
%     defines\meta{newctr} to be a counter, which is reset to zero when
%    counter \meta{oldctr} is stepped. Counter \meta{oldctr} must
%    already be defined.
%
%    Book, part and chapter are the top level document divisions.
%    \begin{macrocode}
\newcounter{book} \setcounter{book}{0}
\newcounter{part} \setcounter{part}{0}
\newcounter{chapter} \setcounter{chapter}{0}
%    \end{macrocode}
%    The lower level divisions get reset by higher level divisions.
%    \begin{macrocode}
\newcounter{section}[chapter]
\newcounter{subsection}[section]
\newcounter{subsubsection}[subsection]
\newcounter{paragraph}[subsubsection]
\newcounter{subparagraph}[paragraph]
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\thebook}
% \begin{macro}{\thepart}
% \begin{macro}{\thechapter}
% \begin{macro}{\thesection}
% \begin{macro}{\thesubsection}
% \begin{macro}{\thesubsubsection}
% \begin{macro}{\theparagraph}
% \begin{macro}{\thesubparagraph}
%    For any counter \Lcount{CTR}, \cs{theCTR} is a macro that defines
%    the printed version of counter \Lcount{CTR}.  It is defined in
%    terms of the following macros:
%
%    \cs{arabic}\marg{COUNTER} prints the value of
%    \meta{COUNTER} as an arabic numeral.
%
%    \cs{roman}\marg{COUNTER} prints the value of
%    \meta{COUNTER} as a lowercase roman numeral.
%
%    \cs{Roman}\marg{COUNTER} prints the value of
%    \meta{COUNTER} as an uppercase roman numeral.
%
%    \cs{alph}\marg{COUNTER} prints the value of \meta{COUNTER}
%    as a lowercase letter: $1 =$~a, $2 =$~ b, etc.
%
%    \cs{Alph}\marg{COUNTER} prints the value of \meta{COUNTER}
%    as an uppercase letter: $1 =$~A, $2 =$~B, etc.
%
%    \begin{macrocode}
\renewcommand*{\thebook}{\@Roman\c@book}
\renewcommand*{\thepart}{\@Roman\c@part}
\renewcommand*{\thechapter}{\@arabic\c@chapter}
\renewcommand*{\thesection}{\thechapter.\@arabic\c@section}
\renewcommand*{\thesubsection}{%
              \thesection.\@arabic\c@subsection}
\renewcommand*{\thesubsubsection}{%
              \thesubsection.\@arabic\c@subsubsection}
\renewcommand*{\theparagraph}{%
              \thesubsubsection.\@arabic\c@paragraph}
\renewcommand*{\thesubparagraph}{%
              \theparagraph.\@arabic\c@subparagraph}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@chapapp}
% \cs{@chapapp} is initially defined as \cs{chaptername}. The \cs{appendix}
% command redfines it as \cs{appendixname}.
%    \begin{macrocode}
\newcommand{\@chapapp}{\chaptername}

%    \end{macrocode}
% \end{macro}
%
% \subsection{Front, main and back matter}
%
% These are the three main logical divisions in a book. As noted earlier,
% the boolean \cs{if@mainmatter} is TRUE iff the main matter is being
% processed. Chapters will be unnumbered when \cs{if@mainmatter} is FALSE.
%
% \begin{macro}{\frontmatter}
% \begin{macro}{\frontmatter*}
% The \cs{frontmatter} command starts roman numbering and turns off 
% chapter numbering.
% It ensures that lower level divisions will not have chapter numbers,
% nor will figures or tables. It
% also ensures that the next page will be recto.
% The starred version makes no changes to the page numbering\footnote{The
% starred versions were added to meet a request by Daniel Richard G.
% (\texttt{skunk@mit.edu}) in September 2001.}.
% \changes{v0.3}{2001/07/09}{\cs{frontmatter} switches off numbering via
%                the secnumdepth counter}
% \changes{v1.0}{2001/09/21}{Added \cs{frontmatter*} command}
%    \begin{macrocode}
\newcommand{\frontmatter}{%
  \@ifstar{\@smemfront}{\@memfront}}
%    \end{macrocode}
% \begin{macro}{\@memfront@floats}
% \changes{v1.6180339f}{Added \cs{@memfront@floats}}
%   Factoring out the float counter domination, in case someone wants
%   something added or changed
%    \begin{macrocode}
\newcommand\@memfront@floats{%
  \counterwithout{figure}{chapter}
  \counterwithout{table}{chapter}
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\@smemfront}
%    \begin{macrocode}
\newcommand{\@smemfront}{%
  \cleardoublepage
  \@mainmatterfalse
  \setcounter{secnumdepth}{-10}
  \@memfront@floats
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\@memfront}
%    \begin{macrocode}
\newcommand{\@memfront}{%
  \@smemfront\pagenumbering{roman}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\mainmatter}
% \begin{macro}{\mainmatter*}
% The \cs{mainmatter} command starts arabic numbering and turns on chapter numbering.
% It sets numbering to the normal state. It
% also ensures that the next page will be recto. The starred version does 
% not change the page numbering.
%
% Romano Giannetti suggested that \cs{mainmatter} (and \cs{backmatter}) should
% be almost no-ops with the article option.
% \changes{v0.3}{2001/07/09}{\cs{mainmatter} switches on section numbering
%                via the secnumdepth counter}
% \changes{v1.0}{2001/09/21}{Added \cs{mainmatter*} command}
%    \begin{macrocode}
\newcommand{\mainmatter}{%
  \@ifstar{\@smemmain}{\@memmain}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@memmain@floats}
% \changes{v1.6180339f}{}{Added \cs{@memmain@floats}}
%   Factoring out the float counter domination, in case someone wants
%   something added or changed
%    \begin{macrocode}
\newcommand\@memmain@floats{%
   \counterwithin{figure}{chapter}
   \counterwithin{table}{chapter}
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\@smemmain}
% If \cs{frontmatter} and \cs{mainmatter} are used with the article option,
% then a page numbering / margin problem can occur if the frontmatter ends
% on an odd page --- the first mainmatter next page is odd as well which throws
% puts two odd-margined pages together.
%
% One fix from Morten is to always \cs{cleardoublepage} for twosided articles.
%
% One fix from me is for the ...matter macros to just switch on/off section
% numbering.
%
% Morten's is simpler to implement.
%
% \changes{v1.1}{2002/03/10}{Modified \cs{@smemmain} to reset the secnumdepth
%                counter to maxsecnumdepth}
% \changes{v1.4}{2003/11/22}{Included cognizance of article option in \cs{@smemmain}
%                            (from patch v1.7)}
% \changes{v1.61803}{2008/01/30}{Changed timing of \cs{clear[double]page} in
%     \cs{@smemmain} (David Wilson, mempatch v4.5)}
% \changes{v1.61803}{2008/01/30}{Changed clear pages in \cs{@smemmain}
%                              (mempatch v4.9)}
%    \begin{macrocode}
\newcommand*{\@smemmain}{%
  \@mainmattertrue
  \setcounter{secnumdepth}{\value{maxsecnumdepth}}
  \ifartopt
    \if@twoside
      \cleardoublepage
    \else
      \clearpage
    \fi
  \else
    \cleardoublepage
    \@memmain@floats
  \fi}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@memmain}
%    \begin{macrocode}
\newcommand{\@memmain}{%
  \@smemmain\pagenumbering{arabic}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@memback@floats}
% \changes{v1.6180339f}{Added \cs{@memback@floats}}
%   Factoring out the float counter domination, in case someone wants
%   something added or changed
%    \begin{macrocode}
\newcommand\@memback@floats{%
    \counterwithout{figure}{chapter}
    \counterwithout{table}{chapter}
    \setcounter{figure}{0}
    \setcounter{table}{0}
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\backmatter}
% This command turns off chapter numbering but leaves the page numbering alone. 
% It twiddles the numbering caption numbering.
% The back matter may start on any new page.
% \changes{v0.3}{2001/07/09}{\cs{backmatter} uses the secnumdepth counter}
% \changes{v1.4}{2003/11/22}{Included cognizance of article option in \cs{backmatter}
%                            (from patch v1.7)}
%    \begin{macrocode}
\newcommand{\backmatter}{%
  \ifartopt
    \clearpage
  \else
    \if@openright
      \cleardoublepage
    \else
      \clearpage
    \fi
  \fi
  \@mainmatterfalse
  \setcounter{secnumdepth}{-10}
  \ifartopt\else
    \@memback@floats
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Book}
%
% This was added at the request of Frederic Connes who said that in
% Frency typography there was often a division above the \cs{part} level.
%
% \begin{macro}{\theHbook}
% \begin{macro}{\toclevel@book}
% These are needed if the \Lpack{hyperref} is used.
%    \begin{macrocode}
\newcommand*{\theHbook}{\arabic{book}}
\newcommand*{\toclevel@book}{-2}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\book}
% \begin{macro}{\book*}
% \cs{book}\marg{title} starts a new book division called \meta{title}.
% The actual typesetting of the title is done by \cs{@book} or \cs{@sbook}.
% \changes{v1.61803}{2008/01/30}{Added \cs{book} and its entourage (mempatch v4.4)}
%    \begin{macrocode}
\newcommand*{\book}{%
  \@setupbook
  \secdef\@book\@sbook}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\beforebookskip}
% \begin{macro}{\midbookskip}
% \begin{macro}{\afterbookskip}
% These three macros are the skips before, in the middle, and after the
% Book heading.
%    \begin{macrocode}
\newcommand*{\beforebookskip}{\null\vfil}
\newcommand*{\midbookskip}{\par\vskip 2\onelineskip}
\newcommand*{\afterbookskip}{\vfil\newpage}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@setupbook}
% This macro does the work of setting up for the \cs{book} command.
% A single column page, normally recto, with a \pstyle{book} pagestyle is 
% started.
%    \begin{macrocode}
\newcommand{\@setupbook}{%
  \if@openright
    \cleardoublepage
  \else
    \clearpage
  \fi
  \thispagestyle{book}%
  \if@twocolumn
    \onecolumn
    \@tempswatrue
  \else
    \@tempswafalse
  \fi
  \beforebookskip}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\booknamefont}
% \begin{macro}{\booknumfont}
% \begin{macro}{\booktitlefont}
% These three macros specify the fonts for the book name and number, and
% for the book title, respectively.
%    \begin{macrocode}
\newcommand*{\booknamefont}{\normalfont\huge\bfseries}
\newcommand*{\booknumfont}{\normalfont\huge\bfseries}
\newcommand*{\booktitlefont}{\normalfont\Huge\bfseries}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\printbookname}
% \begin{macro}{\booknamenum}
% \begin{macro}{\printbooknum}
% \begin{macro}{\printbooktitle}
% Macros to print the various books of a Book heading.
%    \begin{macrocode}
\newcommand*{\printbookname}{\booknamefont \bookname}
\newcommand*{\booknamenum}{\space}
\newcommand*{\printbooknum}{\booknumfont \thebook}
\newcommand*{\printbooktitle}[1]{\booktitlefont #1}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\membookinfo}
% \begin{macro}{\membookstarinfo}
%    \begin{macrocode}
\newcommand{\membookinfo}[3]{}
\newcommand{\membookstarinfo}[1]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@book}
% \cs{@book}\oarg{short}\marg{long} typesets the title of a \cs{book}
% book. There is a number if \cs{secnumdepth} is greater than -3.
%    \begin{macrocode}
\long\def\@book[#1]#2{%
  \M@gettitle{#1}%
%    \end{macrocode}
% For continuity we store the toc entry in \verb?\f@rtoc? before
% writing it to the \verb?.toc? file. We also provide a hook to be
% able to transform it.
% \changes{v3.6k}{2012/09/18}{Provided \cs{f@rtoc} and hook}
% \changes{v3.6k}{2013/04/24}{Added \cs{mempreaddbooktotochook} and \cs{mempostaddbooktotochook}}
%    \begin{macrocode}
  \def\f@rtoc{#1}%
  \@nameuse{book@f@rtoc@before@write@hook}%
  \phantomsection
  \mempreaddbooktotochook
  \ifnum \c@secnumdepth >-3\relax
    \refstepcounter{book}%
    \addcontentsline{toc}{book}%
      {\protect\booknumberline{\thebook}\f@rtoc}%
    \membookinfo{\thebook}{\f@rtoc}{#2}%
  \else
    \addcontentsline{toc}{book}{\f@rtoc}%
    \membookinfo{}{\f@rtoc}{#2}%
  \fi
  \mempostaddbooktotochook
%    \end{macrocode}
% Empty the marks, center the title on the page, and set the normal font.
% \changes{v3.6j}{2011/03/03}{Set \cs{parskip} to zero, such that a
% non-zero \cs{parskip} does not interfer with the title layout}
%    \begin{macrocode}
  \bookpagemark{#1}%
  {\centering
   \interlinepenalty \@M
   \parskip\z@
   \normalfont
%    \end{macrocode}
% Print the number, if there is one, then the title below. Macro \cs{@endbook}
% tidies everything up at the end.
%    \begin{macrocode}
   \ifnum \c@secnumdepth >-3\relax
     \printbookname \booknamenum \printbooknum
     \midbookskip
   \fi
   \printbooktitle{#2}\par}%
  \@endbook}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mempreaddbooktotochook}
% \begin{macro}{\mempostaddbooktotochook}
% Hooks executed just before and just after \cs{book} adds something
% to the ToC. Does nothing by default
%    \begin{macrocode}
\newcommand\mempreaddbooktotochook{}
\newcommand\mempostaddbooktotochook{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@sbook}
% \cs{@sbook}\marg{long} formats the title of a \cs{book*} book. It is 
% simpler than \cs{@book} because there is no  number to print.
% \changes{v1.4}{2003/11/16}{Added \cs{M@gettitle} to \cs{@sbook}}
% \changes{v3.6j}{2011/03/03}{Set \cs{parskip} to zero here as well}
%    \begin{macrocode}
\long\def\@sbook#1{%
  \M@gettitle{#1}%
  \phantomsection
  \membookstarinfo{#1}%
  {\centering
   \interlinepenalty \@M
   \parskip\z@
   \normalfont
   \printbooktitle{#1}\par}%
  \@endbook}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifm@mnobooknewpage}
% \begin{macro}{\m@mnobooknewpagetrue}
% \begin{macro}{\m@mnobooknewpagefalse}
% \begin{macro}{\bookblankpage}
% \begin{macro}{\nobookblankpage}
%    The declaration \cs{nobookblankpage} prevents \cs{book} from
% outputting a further (blank) page when it finishes. The default is set by
% \cs{bookblankpage}. 
%    \begin{macrocode}
\newif\ifm@mnobooknewpage
  \m@mnobooknewpagefalse
\newcommand*{\bookblankpage}{\m@mnobooknewpagefalse}
\newcommand*{\nobookblankpage}{\m@mnobooknewpagetrue}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% 
% \begin{macro}{\bookpageend}
% \begin{macro}{\@endbook}
% This finishes off both \cs{@book} and \cs{@sbook}. 
% Following a \cs{nobookblankpage} nothing is done, otherwise
% (after \cs{bookblankpage}) the current page is flushed,
% and an extra blank page is created if both \Lopt{twoside} and 
% \Lopt{openright} are in effect. 
% At the end, if necessary, two column mode is switched back on.
% \changes{v1.61803398}{2009/07/26}{PW: Added \cs{bookpageend} as cover for \cs{@endbook}}
%    \begin{macrocode}
\newcommand*{\bookpageend}{\afterbookskip
  \ifm@mnobooknewpage
  \else
    \if@twoside
      \if@openright
        \null
        \thispagestyle{afterbook}%
        \newpage
      \fi
    \fi
  \fi
  \if@tempswa
    \twocolumn
  \fi}
\def\@endbook{\bookpageend}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ps@book}
% \begin{macro}{\ps@afterbook}
% Pagestyles for the book page and the (blank) page after a book page.
%    \begin{macrocode}
\aliaspagestyle{book}{empty}
\aliaspagestyle{afterbook}{empty}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \subsection{Part}
%
% \begin{macro}{\part}
% \cs{part}\marg{title} starts a new Part called \meta{title}.
% The actual typesetting of the title is done by \cs{@part} or \cs{@spart}.
%    \begin{macrocode}
\newcommand{\part}{%
  \@setuppart
  \secdef\@part\@spart}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\beforepartskip}
% \begin{macro}{\midpartskip}
% \begin{macro}{\afterpartskip}
% These three macros are the skips before, in the middle, and after the
% Part heading.
% \changes{v1.61803}{2008/01/30}{Changed \cs{midpartskip} (mempatch v4.9)}
%    \begin{macrocode}
\newcommand{\beforepartskip}{\null\vfil}
\newcommand{\midpartskip}{\par\vskip 2\onelineskip}
\newcommand{\afterpartskip}{\vfil\newpage}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@setuppart}
% This macro does the work of setting up for the \cs{part} command.
% A single column page, normally recto, with a \pstyle{part} pagestyle is started.
%    \begin{macrocode}
\newcommand{\@setuppart}{%
  \if@openright
    \cleardoublepage
  \else
    \clearpage
  \fi
  \thispagestyle{part}%
  \if@twocolumn
    \onecolumn
    \@tempswatrue
  \else
    \@tempswafalse
  \fi
  \beforepartskip}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\partnamefont}
% \begin{macro}{\partnumfont}
% \begin{macro}{\parttitlefont}
% These three macros specify the fonts for the part name and number, and
% for the part title, respectively.
% \changes{v0.2}{2001/06/03}{Rewrote the typesetting for Part titles}
%    \begin{macrocode}
\newcommand{\partnamefont}{\normalfont\huge\bfseries}
\newcommand{\partnumfont}{\normalfont\huge\bfseries}
\newcommand{\parttitlefont}{\normalfont\Huge\bfseries}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\printpartname}
% \begin{macro}{\partnamenum}
% \begin{macro}{\printpartnum}
% \begin{macro}{\printparttitle}
% Macros to print the various parts of a Part heading.
%    \begin{macrocode}
\newcommand{\printpartname}{\partnamefont \partname}
\newcommand{\partnamenum}{\space}
\newcommand{\printpartnum}{\partnumfont \thepart}
\newcommand{\printparttitle}[1]{\parttitlefont #1}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\mempartinfo}
% \begin{macro}{\mempartstarinfo}
% \verb?\mempartinfo{\thepart}{short}{long}? \\
% \verb?\mempartstarinfo{long}? \\
% \changes{v1.61803}{2008/01/30}{Made \cs{mempartinfo} long (mempatch v4.9).}
%    \begin{macrocode}
\newcommand{\mempartinfo}[3]{}
\newcommand{\mempartstarinfo}[1]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@part}
% \cs{@part}\oarg{short}\marg{long} typesets the title of a \cs{part}
% part. There is a number if \cs{secnumdepth} is greater than -2.
% \changes{v1.3}{2002/11/14}{Used \cs{partnumberline} in \cs{@part}}
% \changes{v1.4}{2003/11/16}{Added \cs{M@gettitle} to \cs{@part}}
% \changes{v1.618}{2005/09/03}{Replaced \cs{markboth} by \cs{partmark} 
%          in \cs{@part} courtesy of Frederic Connes (mempatch v3.11)}
%    \begin{macrocode}
\long\def\@part[#1]#2{%
  \M@gettitle{#1}%
%    \end{macrocode}
% For continuity we store the toc entry in \verb?\f@rtoc? before
% writing it to the \verb?.toc? file. We also provide a hook to be
% able to transform it.
% \changes{v3.6k}{2012/09/18}{Provided \cs{f@rtoc} and hook}
% \changes{v3.6k}{2013/04/24}{Added \cs{mempreaddparttotochook} and \cs{mempostaddparttotochook}}
%    \begin{macrocode}
  \def\f@rtoc{#1}%
  \@nameuse{part@f@rtoc@before@write@hook}%
  \phantomsection
  \mempreaddparttotochook
  \ifnum \c@secnumdepth >-2\relax
    \refstepcounter{part}%
    \addcontentsline{toc}{part}%
      {\protect\partnumberline{\thepart}\f@rtoc}%
    \mempartinfo{\thepart}{\f@rtoc}{#2}%
  \else
    \addcontentsline{toc}{part}{\f@rtoc}%
    \mempartinfo{}{\f@rtoc}{#2}%
  \fi
  \mempostaddparttotochook
%    \end{macrocode}
% Empty the marks, center the title on the page, and set the normal font.
% \changes{v3.6j}{2011/03/03}{Set \cs{parskip} to zero inside the
% group, such that a non-zero \cs{parskip} does not interfer with the
% title layout}
%    \begin{macrocode}
  \partmark{#1}%
  {\centering
   \interlinepenalty \@M
   \parskip\z@
   \normalfont
%    \end{macrocode}
% Print the number, if there is one, then the title below. Macro \cs{@endpart}
% tidies everything up at the end.
%    \begin{macrocode}
   \ifnum \c@secnumdepth >-2\relax
     \printpartname \partnamenum \printpartnum
     \midpartskip
   \fi
   \printparttitle{#2}\par}%
  \@endpart}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mempreaddparttotochook}
% \begin{macro}{\mempostaddparttotochook}
% Hooks executed just before and just after \cs{part} adds something
% to the ToC. Does nothing by default
%    \begin{macrocode}
\newcommand\mempreaddparttotochook{}
\newcommand\mempostaddparttotochook{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@spart}
% \cs{@spart}\marg{long} formats the title of a \cs{part*} part. It is 
% simpler than \cs{@part} because there is no  number to print.
% \changes{v1.4}{2003/11/16}{Added \cs{M@gettitle} to \cs{@spart}}
% \changes{v3.6j}{2011/03/03}{Set \cs{parskip} to zero here as well}
%    \begin{macrocode}
\long\def\@spart#1{%
  \M@gettitle{#1}%
  \phantomsection
  \mempartstarinfo{#1}%
  {\centering
   \interlinepenalty \@M
   \parskip\z@
   \normalfont
   \printparttitle{#1}\par}%
  \@endpart}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifm@mnopartnewpage}
% \begin{macro}{\m@mnopartnewpagetrue}
% \begin{macro}{\m@mnopartnewpagefalse}
% \begin{macro}{\partblankpage}
% \begin{macro}{\nopartblankpage}
%    The declaration \cs{nopartblankpage} prevents \cs{part} from
% outputting a blank page when it finishes. The default is set by
% \cs{partblankpage}. This code was originally supplied by Frederic Connes.
% \changes{v1.61803}{2008/01/30}{Added \cs{partblankpage} and 
%                    \cs{nopartblankpage} (mempatch v v4.4).}
%    \begin{macrocode}
\newif\ifm@mnopartnewpage
  \m@mnopartnewpagefalse
\newcommand*{\partblankpage}{\m@mnopartnewpagefalse}
\newcommand*{\nopartblankpage}{\m@mnopartnewpagetrue}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% 
% \begin{macro}{\partpageend}
% \begin{macro}{\@endpart}
% This finishes off both \cs{@part} and \cs{@spart}. 
% Following a \cs{nopartblankpage} nothing is done, otherwise
% (after \cs{partblankpage}) the current page is flushed.
% In the standard \Lpack{book} class if 
% two-sided mode is on a blank page is then produced. I think that this looks
% odd when the \Lopt{openany} option is in force, so here it only produces
% an extra blank page if both \Lopt{twoside} and \Lopt{openright} are
% in effect. 
%
% At the end, if necessary, two column mode is switched back on.
% \changes{v1.61803}{2008/01/30}{Used the afterpart pagestyle in \cs{@endpart}}
% \changes{v1.61803398}{2009/07/26}{PW: Added \cs{partpageend} as cover for \cs{@endpart}}
%    \begin{macrocode}
\newcommand*{\partpageend}{\afterpartskip
  \ifm@mnopartnewpage
  \else
    \if@twoside
      \if@openright
        \null
        \thispagestyle{afterpart}%
        \newpage
      \fi
    \fi
  \fi
  \if@tempswa
    \twocolumn
  \fi}
\def\@endpart{\partpageend}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ps@afterpart}
% Pagestyle for the (blank) page after a part page.
% \changes{v1.61803}{2008/01/30}{Added afterpart pagestyle (mempatch v4.4)}
%    \begin{macrocode}
\aliaspagestyle{afterpart}{empty}

%    \end{macrocode}
% \end{macro}
%
% \subsection{Chapter}
%
% \begin{macro}{\chapter}
%    The command to start a new chapter. Chapters always start on a new page
% with a \pstyle{chapter} pagestyle. Floats are not allowed at the top of the page.
% The typesetting is done by either \cs{@chapter} or \cs{@schapter}.
% \changes{v0.3}{2001/07/09}{Changed \cs{chapter} for article option}
% \changes{v1.0}{2001/10/24}{Changed chapter page clearing to \cs{clearforchapter}}
% \changes{v1.2}{2002/07/27}{New optarg in \cs{chapter} for short heading}
% \changes{v1.618}{2005/09/03}{Made article chapter start on a newline (mempatch v3.5)}
% \changes{v3.6e}{2010/07/16}{Factored out the \cs{@afterindentfalse}}
% \changes{v3.6h}{2011/02/07}{Added the chapter block}
%    \begin{macrocode}
\newcommand\chapter{%
%    \end{macrocode}
% The block macro can be defined to execute a \cs{FloatBlock} when we
% are in article mode. Outside article mode \cs{clearforchapter} is
% expected to be used for this.
%    \begin{macrocode}
  \ifartopt\par\@nameuse{chapterblock}\else
    \clearforchapter
    \thispagestyle{chapter}
    \global\@topnum\z@
  \fi
%  \@afterindentfalse
  \m@mindentafterchapter
  \@ifstar{\@m@mschapter}{\@m@mchapter}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mindentafterchapter}
% \begin{macro}{\indentafterchapter}
% \begin{macro}{\noindentafterchapter}
%   In order to make whether to indent the first paragraph after af
%   chapter configurable, we store \verb?\@afterindenttrue/false? in
%   \verb?\m@mindentafterchapter?, and provide
%   \verb?\indentafterchapter? and \verb?\noindentafterchapter? to set
%   it to a suitable value. 
%    \begin{macrocode}
\newcommand*\indentafterchapter{\def\m@mindentafterchapter{\@afterindenttrue}}
\newcommand*\noindentafterchapter{\def\m@mindentafterchapter{\@afterindentfalse}}
%    \end{macrocode}
%  Default is not to indent.
%    \begin{macrocode}
\noindentafterchapter

%    \end{macrocode}
%  
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@m@mchapter}
% \begin{macro}{\ch@pt@c}
% \begin{macro}{\m@m@empty}
% Intermediate and support macros for the extra optional argument
% to \cs{chapter}. Have to do this long windedly otherwise dear old
% \Lpack{hyperref} barfs.
%
% The code for two optional arguments is based on a posting
% to \ctt{} by Robin Fairbairns (1997/04/12 \textit{Re: Several optional 
% arguments for macro?}). 
% \changes{v1.618}{2005/09/04}{Major changes to \cs{chapter} macros (from Morten Hogholm 2005/08/30)}
%    \begin{macrocode}
\newcommand{\@m@mchapter}[1][]{%
  \def\ch@pt@c{#1}% capture first optional arg
  \@ifnextchar[{\@chapter}{\@chapter[]}%
}
\def\m@m@empty{\@empty}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memchapinfo}
% \begin{macro}{\memchapstarinfo}
% \begin{macro}{\memappchapinfo}
% \begin{macro}{\memappchapstarinfo}
% \verb?\memchapinfo{num}{toc}{head}{full}? \\
% \verb?\memchapstarinfo{short}{full}?
% \changes{v1.618}{2005/09/06}{Added \cs{memchapinfo}}
%    \begin{macrocode}
\newcommand{\memchapinfo}[4]{}
\newcommand{\memchapstarinfo}[2]{}
\newcommand{\memappchapinfo}[4]{}
\newcommand{\memappchapstarinfo}[2]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ifm@mpn@new@chap}
% \begin{macro}{\m@mpn@new@chapfalse}
% \begin{macro}{\m@mpn@new@chaptrue}
% \begin{macro}{\ifm@mpn@new@schap}
% \begin{macro}{\m@mpn@new@schapfalse}
% \begin{macro}{\m@mpn@new@schaptrue}
% These are for supporting the page/end notes, flagging that a 
% \verb?\chapter(*)? has been called.
% \changes{v1.61803}{2008/01/30}{Added \cs{ifm@mpn@new@chap} and
%          \cs{ifm@mpn@new@chap} (mempatch v4.5)}
%    \begin{macrocode}
\newif\ifm@mpn@new@chap
  \m@mpn@new@chapfalse
\newif\ifm@mpn@new@schap
  \m@mpn@new@schapfalse

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@chapter}
% \begin{macro}{\f@rtoc}
% \begin{macro}{\f@rhdr}
% \begin{macro}{\f@rbody}
% \cs{@chapter}\oarg{tocmark}\marg{title}
% typesets the title of a \cs{chapter}. 
% There is a number if \cs{secnumdepth} is greater than -1 and \cs{@mainmatter}
% is TRUE. 
%
% \changes{v1.2}{2002/07/27}{Complete rewrite of \cs{@chapter}}
% \changes{v1.3}{2002/11/14}{Changed \cs{numberline} to \cs{chapternumberline}
%                            in \cs{@chapter}}
% \changes{v1.61803}{2008/01/30}{Added \cs{f@rbody} to \cs{@chapter},
%      plus newchapter flag (mempatch v4.5)}
% \changes{v1.6180339g}{2009/07/13}{added \cs{m@mpn@new@schapfalse}
% otherwise both might end up true at the same time}
%    \begin{macrocode}
\def\@chapter[#1]#2{%
  \m@mpn@new@chaptrue%
  \m@mpn@new@schapfalse%
  \def\f@rbdy{#2}%
  \ifx\ch@pt@c\@empty % no optional args
    \def\f@rtoc{#2}%
    \def\f@rhdr{#2}%
  \else                  % at least one opt arg
    \let\f@rtoc\ch@pt@c
    \ifx\@empty#1\@empty
      \let\f@rhdr\ch@pt@c
    \else
      \def\f@rhdr{#1}%
    \fi
  \fi
  \m@m@Andfalse
  \ifnum \c@secnumdepth >\m@ne
    \if@mainmatter
      \m@m@Andtrue
    \fi
  \fi
  \ifm@m@And
    \refstepcounter{chapter}%
  \fi
%    \end{macrocode}
% Deal with the \Lopt{article} option.
%    \begin{macrocode}
  \ifartopt
    \@makechapterhead{#2}%
    \@afterheading
    \chaptermark{\f@rhdr}%
  \else
%    \end{macrocode} 
% Store the (short) title via \cs{chaptermark}, and add some whitespace to
% the LoF and LoT. Then fiddle when we are using two columns, calling
% \cs{@makechapterhead} to do the typesetting.
% \changes{v0.3}{2001/07/09}{Changed \cs{@chapter} for article option}
%    \begin{macrocode}
    \chaptermark{\f@rhdr}
    \insertchapterspace
    \if@twocolumn
      \@topnewpage[\@makechapterhead{#2}]%
    \else
      \@makechapterhead{#2}%
    \fi
    \@afterheading
  \fi
%    \end{macrocode}
% When working with \Lpack{hyperref} it is not possible to add, say,
% upper casing to ToC entries via \cs{cftchapterfont}. We provide a
% hook, such that users can transform \cs{f@rtoc} before it is
% actually written to the \texttt{.toc} file.
% \changes{v3.6k}{2012/09/18}{Added}
%    \begin{macrocode}
  \@nameuse{chapter@f@rtoc@before@write@hook}%     
%    \end{macrocode}
% Vittorio De Martino (\texttt{demartino.vittoria@grtn.it}) on
% 31 March 2003 reported that for articled chapters, which do not do
% any \cs{clearpage}, \cs{addcontents} had to come after the title.
% \changes{v1.4}{2003/11/16}{Changed \cs{@chapter} to match patches v1.n}
% \changes{v3.6k}{2013/04/24}{Added pretoc and posttoc hooks}
%    \begin{macrocode}
  \mempreaddchaptertotochook%
  \ifm@m@And
    \ifanappendix
      \addcontentsline{toc}{appendix}{%
        \protect\chapternumberline{\thechapter}\f@rtoc}%
      \memappchapinfo{\thechapter}{\f@rtoc}{\f@rhdr}{#2}%
    \else
      \addcontentsline{toc}{chapter}{%
        \protect\chapternumberline{\thechapter}\f@rtoc}%
      \memchapinfo{\thechapter}{\f@rtoc}{\f@rhdr}{#2}%
    \fi
  \else
    \addcontentsline{toc}{chapter}{\f@rtoc}%
    \ifanappendix
      \memappchapinfo{}{\f@rtoc}{\f@rhdr}{#2}%
    \else
      \memchapinfo{}{\f@rtoc}{\f@rhdr}{#2}%
    \fi
  \fi
  \mempostaddchaptertotochook%
%    \end{macrocode}
% Add hook for title referencing.
% \changes{v1.4}{2003/11/16}{Added \cs{M@gettitle} to \cs{@chapter}}
% \changes{v3.6k}{2013/04/24}{Added \cs{memendofchapterhook}}.
% The hook at the very end can be used to automatically add a new page
% right after \cs{chapter}.
%    \begin{macrocode}
  \ifheadnameref\M@gettitle{\f@rhdr}\else\M@gettitle{\f@rtoc}\fi%
  \memendofchapterhook%
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \begin{macro}{\mempreaddchaptertotochook}
% \begin{macro}{\mempostaddchaptertotochook}
% \begin{macro}{\memendofchapterhook}
%   These two hooks are executed before \cs{chapter} adds anything to
%   the TOC and after it does so. It can be used to add hooks into the
%   TOC such that parts can be switched on and off. By default they do nothing.
%    \begin{macrocode}
\newcommand\mempreaddchaptertotochook{}
\newcommand\mempostaddchaptertotochook{}
\newcommand\memendofchapterhook{}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\settocpreprocessor}
% \changes{v3.6k}{2012/09/18}{Added}
% This can be used to set a hook which users can fill in in order to
% get the toc material preprocessed before writing it to the
% \verb?.toc? file. The primary use for this is as a workaround when
% \Lpack{hyperref} is used, and one want to have, say, upper cased toc
% entries. Example of use
% \begin{verbatim}
% \makeatletter
% \settocpreprocessor{chapter}{%
%  \let\temp@f@rtoc\f@rtoc
%  \def\f@rtoc{\texorpdfstring{\MakeTextUppercase{\temp@f@rtoc}}{\temp@f@rtoc}}
%  }
% \makeatother
% \end{verbatim}
% The idea comes from \url{http://tex.stackexchange.com/q/11892/3929}
% eliminating the need for patching.
%    \begin{macrocode}
\newcommand\settocpreprocessor[2]{%
  \@namedef{#1@f@rtoc@before@write@hook}{#2}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@makechapterhead}
% This \emph{really} typesets a \cs{chapter}. Leave some whitespace and prepare to
% set \cs{raggedright}.
% \changes{v1.3}{2002/10/10}{Added \cs{printchapternonum} to 
%                            \cs{@makechapterhead}}
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{@makechapterhead}}
% \changes{v3.6j}{2011/03/01}{Set \cs{parskip} to zero such that a
% non-zero \cs{parskip} to not interfer with the placement of the title}
%    \begin{macrocode}
\def\@makechapterhead#1{%
  \chapterheadstart%  \vspace*{50\p@}%
  {%\parindent \z@ \raggedright \normalfont
   \parskip \z@
   \parindent \z@ \memRTLraggedright \normalfont
%    \end{macrocode}
% If there is a number, typeset it, otherwise call \cs{printchapternonum}.
%    \begin{macrocode}
   \ifm@m@And
     \printchaptername \chapternamenum \printchapternum 
     \afterchapternum % \par\nobreak \vskip 20\p@
   \else
     \printchapternonum
   \fi
%    \end{macrocode}
% Typeset the title.
%    \begin{macrocode}
   \interlinepenalty\@M
   \printchaptertitle{#1} % \Huge \bfseries #1
   \afterchaptertitle % \par\nobreak \vskip 40\p@
  }}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\insertchapterspace}
% By default, a \cs{chapter} inserts some vertical space into the LoF and LoT.
% The macro \cs{insertchapterspace} performs the insertion.
% \changes{v0.33}{2001/08/31}{Added \cs{insertchapterspace}}
%    \begin{macrocode}
\newcommand*{\insertchapterspace}{%
  \addtocontents{lof}{\protect\addvspace{10pt}}%
  \addtocontents{lot}{\protect\addvspace{10pt}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\beforechapskip}
% \begin{macro}{\midchapskip}
% \begin{macro}{\afterchapskip}
% Lengths separating the various parts of a chapter heading.
%    \begin{macrocode}
\newlength{\beforechapskip}\setlength{\beforechapskip}{50pt}
\newlength{\midchapskip}\setlength{\midchapskip}{20pt}
\newlength{\afterchapskip}\setlength{\afterchapskip}{40pt}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@chs@def@ult}
% This sets up all the definitions and defaults used in \cs{@makechapterhead}
% and \cs{@makeschapterhead}.
% \changes{v1.3}{2002/10/10}{Added \cs{printchapternonum} to \cs{@chs@def@ult}}
% \changes{v1.61803}{2008/01/30}{Made \cs{@chs@def@ult} set all default chapter values}
% \begin{macro}{\chapterheadstart}
% \begin{macro}{\printchaptername}
% \begin{macro}{\chapternamenum}
% \begin{macro}{\printchapternum}
% \begin{macro}{\afterchapternum}
% \begin{macro}{\printchapternum}
% \begin{macro}{\printchapternonum}
% \begin{macro}{\printchaptertitle}
% \begin{macro}{\afterchaptertitle}
%    \begin{macrocode}
\newcommand{\@chs@def@ult}{%
  \def\chapterheadstart{\vspace*{\beforechapskip}}%
  \def\printchaptername{\chapnamefont \@chapapp}%
  \def\chapternamenum{\space}%
  \def\printchapternum{\chapnumfont \thechapter}%
  \def\afterchapternum{\par\nobreak\vskip \midchapskip}%
  \def\printchapternonum{}%
  \def\printchaptertitle##1{\chaptitlefont ##1}%
  \def\afterchaptertitle{\par\nobreak\vskip \afterchapskip}%
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% 
% \begin{macro}{\chapnamefont}
% \begin{macro}{\chapnumfont}
% \begin{macro}{\chaptitlefont}
% Fonts for setting chapter name, number, and title.
%    \begin{macrocode}
  \def\chapnamefont{\normalfont\huge\bfseries}%
  \def\chapnumfont{\normalfont\huge\bfseries}%
  \def\chaptitlefont{\normalfont\Huge\bfseries}%
  \setlength{\beforechapskip}{50pt}%
  \setlength{\midchapskip}{20pt}%
  \setlength{\afterchapskip}{40pt}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% 
%
% \begin{macro}{\@m@mschapter}
% This deals with the new optional argument for starred chapters.
%    \begin{macrocode}
\newcommand{\@m@mschapter}[2][\@empty]{%
  \@schapter{#2}%
  \ifx \@empty#1
    \def\f@rhdr{#2}%
  \else%                    opt arg
    \def\f@rhdr{#1}%
    \setcounter{secnumdepth}{-10}%
    \chaptermark{#1}%
    \setcounter{secnumdepth}{\value{maxsecnumdepth}}%
  \fi
  \ifanappendix
    \memappchapstarinfo{\f@rhdr}{#2}%
  \else
    \memchapstarinfo{\f@rhdr}{#2}%
  \fi
  \ifheadnameref\M@gettitle{\f@rhdr}\else\M@gettitle{#2}\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@schapter}
% \begin{macro}{\f@rbdy}
% \cs{@schapter}\marg{long} typesets the title of a 
% \cs{chapter*}. It is easier than the \cs{@chapter} as there is no number
% to worry about.
% \changes{v0.3}{2001/07/09}{Changed \cs{@schapter} for article option}
% \changes{v1.2}{2002/07/27}{Major rewrite of \cs{@schapter}}
% \changes{v1.4}{2003/11/16}{Added \cs{M@gettitle} to \cs{@schapter}}
% \changes{v1.61803}{2008/01/30}{Changed \cs{@schapter} like 
%          \cs{@chapter} (mempatch v4.5)}
% \changes{v1.6180339g}{2009/07/13}{added \cs{m@mpn@new@chapfalse}
% otherwise both might end up true at the same time}
%    \begin{macrocode}
\newcommand{\@schapter}[1]{%
  \m@mpn@new@schaptrue%
  \m@mpn@new@chapfalse%
  \def\f@rbdy{#1}%
  \ifartopt
    \@makeschapterhead{#1}%
  \else
    \if@twocolumn
      \@topnewpage[\@makeschapterhead{#1}]%
    \else
      \@makeschapterhead{#1}%
    \fi
  \fi
  \@afterheading}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@makeschapterhead}
% This \emph{really} typesets a \cs{chapter*}, and is similar to \cs{@makechapterhead}.
% \changes{v1.3}{2002/10/10}{Added \cs{printchapternonum} to 
%                            \cs{@makeschapterhead}}
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{@makeschapterhead}}
% \changes{v3.6j}{2011/0301}{Made sure the \cs{parskip} is zero inside
% the title area, otherwise placement might come out wrong}
%    \begin{macrocode}
\def\@makeschapterhead#1{%
  \chapterheadstart
  {%\parindent \z@ \raggedright \normalfont
   \parskip \z@% 
   \parindent \z@ \memRTLraggedright \normalfont
   \printchapternonum
   \interlinepenalty\@M
   \printchaptertitle{#1}%
   \afterchaptertitle}%
}

%    \end{macrocode}
% \end{macro}
%
%
% \subsubsection{Chapter styling}
%
%
% \begin{macro}{\makechapterstyle}
% \begin{macro}{\chapterstyle}
% \cs{chapterstyle}\marg{style} is like \cs{pagestyle}, except it's for 
% chapters. 
%
% \cs{makechapterstyle}\marg{style}\marg{text} creates
% or overrides the \meta{style} chapter style defining it as \meta{text}
% So, \verb?\makechapterstyle{fred}{code}? specifies that the chapter style 
% \pstyle{fred}
% is defined as the macro \verb?\chs@fred{code}?, 
% and \verb?\chapterstyle{fred}? calls the macro \cs{chs@fred}.
%    \begin{macrocode}
\newcommand{\makechapterstyle}[2]{\@namedef{chs@#1}{\@chs@def@ult #2}}
\newcommand{\chapterstyle}[1]{\@nameuse{chs@#1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% Set the \pstyle{default} chapter style.
% \changes{v0.2}{2001/06/03}{Added code when making the default chapterstyle}
% \changes{v1.61803}{2008/01/30}{Simplified specification of the default chapterstyle}
%    \begin{macrocode}
\makechapterstyle{default}{}%
 %%  \setlength{\beforechapskip}{50pt}
 %%  \def\chapterheadstart{\vspace*{\beforechapskip}}
 %%  \def\chapnamefont{\normalfont\huge\bfseries}
 %%  \def\printchaptername{\chapnamefont \@chapapp}
 %%  \def\chapternamenum{\space}
 %%  \def\chapnumfont{\normalfont\huge\bfseries}
 %%  \def\printchapternum{\chapnumfont \thechapter}
 %%  \setlength{\midchapskip}{20pt}
 %%  \def\afterchapternum{\par\nobreak\vskip \midchapskip}
 %%  \def\printchapternonum{}
 %%  \def\chaptitlefont{\normalfont\Huge\bfseries}
 %%  \def\printchaptertitle##1{\chaptitlefont ##1}
 %%  \setlength{\afterchapskip}{40pt}
 %%  \def\afterchaptertitle{\par\nobreak\vskip \afterchapskip}
\chapterstyle{default}

%    \end{macrocode}
%
% \begin{macro}{\chs@section}
% The \pstyle{section} chapter style. It prints the heading as though it
% were a section.
% \changes{v1.0a}{2002/01/18}{Made \cs{chapnumfont} change in section 
%                 chapterstyle explicit}
%    \begin{macrocode}
\makechapterstyle{section}{%
  \chapterstyle{default}
  \renewcommand{\printchaptername}{}
  \renewcommand{\chapternamenum}{}
  \renewcommand{\chapnumfont}{\normalfont\Huge\bfseries}
  \renewcommand{\printchapternum}{\chapnumfont \thechapter\space}
  \renewcommand{\afterchapternum}{}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@article}
% The \pstyle{article} chapter style. It prints the heading as though it
% were a section in an \Lpack{article} class document.
% \changes{v0.3}{2001/07/09}{Added article chapterstyle}
% \changes{v1.0a}{2002/01/18}{Made \cs{chapnumfont} change in article chapterstyle explicit}
% \changes{v1.4}{2003/11/22}{Replaced \cs{space} by \cs{quad} in article chapterstyle
%               (from patch v1.7)}
%    \begin{macrocode}
\makechapterstyle{article}{%
  \chapterstyle{default}
  \setlength{\beforechapskip}{3.5ex \@plus 1ex \@minus .2ex}
  \renewcommand*{\chapterheadstart}{\vspace{\beforechapskip}}
  \setlength{\afterchapskip}{2.3ex \@plus .2ex}
  \renewcommand{\printchaptername}{}
  \renewcommand{\chapternamenum}{}
  \renewcommand{\chaptitlefont}{\normalfont\Large\bfseries}
  \renewcommand{\chapnumfont}{\chaptitlefont}
  \renewcommand{\printchapternum}{\chapnumfont \thechapter\quad}
  \renewcommand{\afterchapternum}{}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@reparticle}
% The \pstyle{reparticle} chapter style. It replicates the appearance
% of a \cs{section} in an \Lpack{article} class document.
% \changes{v1.61803}{2008/01/30}{Added reparticle chapterstyle (mempatch v4.3)}
%    \begin{macrocode}
\makechapterstyle{reparticle}{%
  \chapterstyle{default}
  \setlength{\beforechapskip}{3.5ex \@plus 1ex \@minus .2ex}
  \renewcommand*{\chapterheadstart}{\vspace{\beforechapskip}}
  \setlength{\afterchapskip}{2.3ex \@plus .2ex}
  \renewcommand*{\printchaptername}{}
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\chaptitlefont}{\normalfont\Large\bfseries}
  \renewcommand*{\chapnumfont}{\chaptitlefont}
  \renewcommand*{\printchapternum}{\@hangfrom{\chapnumfont \thechapter\quad}}%
  \renewcommand*{\afterchapternum}{}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\reparticle}
% Call this to get division heads to replicate the \Lopt{article} class.
% For example: \\
% \verb?\ifartopt \reparticle \fi? \\
% The \cs{chapter} commands must still be used, though.
% \changes{v1.61803}{2008/01/30}{Added \cs{reparticle} (mempatch v4.3)}
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{reparticle}}
%    \begin{macrocode}
\newcommand*{\reparticle}{%
  \chapterstyle{reparticle}
%%%  \setsecheadstyle{\normalfont\large\bfseries\raggedright}
  \setsecheadstyle{\normalfont\large\bfseries\memRTLraggedright}%
%%%  \setsubsecheadstyle{\normalfont\bfseries\raggedright}
  \setsubsecheadstyle{\normalfont\bfseries\memRTLraggedright}%
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@hangnum}
% The \pstyle{hangnum} style puts the chapter number in the margin.
%    \begin{macrocode}
\makechapterstyle{hangnum}{%
  \chapterstyle{default}
  \renewcommand*{\chapnumfont}{\chaptitlefont}
  \settowidth{\chapindent}{\chapnumfont 999}
  \renewcommand*{\printchaptername}{}
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\printchapternum}{%
    \noindent\llap{\makebox[\chapindent][l]{\chapnumfont \thechapter}}}
  \renewcommand*{\afterchapternum}{}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chapindent}
% \begin{macro}{\chs@companion}
% The \pstyle{companion} style is like that in the \textit{\LaTeX{} Companion}
% series. It requires the \cs{chapindent} length. The user needs
% to be careful to have a wide enough spine margin on verso pages
% if the title may appear on a verso page.
% \changes{v0.31}{2001/07/24}{Changed adjustwidth* to adjustwidth in companion chapterstyle}
%    \begin{macrocode}
\newlength{\chapindent}

\makechapterstyle{companion}{%
  \chapterstyle{default}
  \renewcommand*{\chapnamefont}{\normalfont\LARGE\scshape}
  \renewcommand*{\printchaptername}{\raggedleft\chapnamefont \@chapapp}
  \renewcommand*{\chapnumfont}{\normalfont\Huge}
  \setlength{\chapindent}{\marginparsep}
  \addtolength{\chapindent}{\marginparwidth}
  \renewcommand*{\printchaptertitle}[1]{%
    \begin{adjustwidth}{}{-\chapindent}
      \raggedleft \chaptitlefont ##1\par\nobreak
    \end{adjustwidth}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\chs@demo}
% An exotic chapter style for demonstration purposes.
%    \begin{macrocode}
\makechapterstyle{demo}{%
  \chapterstyle{default}
  \renewcommand*{\printchaptername}{\centering}
  \renewcommand*{\printchapternum}{\chapnumfont \numtoName{\c@chapter}}
  \renewcommand*{\chaptitlefont}{\normalfont\Huge\sffamily}
  \renewcommand*{\printchaptertitle}[1]{%
    \hrule\vskip\onelineskip \raggedleft \chaptitlefont ##1}
  \renewcommand*{\afterchaptertitle}%
               {\vskip\onelineskip \hrule\vskip \afterchapskip}}

%    \end{macrocode}
% \end{macro}
%
% \changes{v1.61803}{2008/01/30}{Added chapterstyles: bianchi, bringhurst,
%          brotherton, chappel, culver, dash, demo2, ell, Ger,
%          lyhne, madsen, pedersen, southall, thatcher, veelo,
%          verville, demo3 (mempatch v4.6)}
% \begin{macro}{\chs@bianchi}
% Posted to CTT on 2003/12/09, \textit{New chapter style: chapter vs chapter*}
% by Stefano Bianchi.
%    \begin{macrocode}
\makechapterstyle{bianchi}{%
  \chapterstyle{default}
  \renewcommand*{\chapnamefont}{\normalfont\Large\sffamily\itshape}
  \renewcommand*{\chapnumfont}{\normalfont\huge}
  \renewcommand*{\printchaptername}{%
    \chapnamefont\centering\@chapapp}
  \renewcommand*{\printchapternum}{\chapnumfont \textit{\thechapter}}
  \renewcommand*{\chaptitlefont}{\normalfont\Huge\sffamily}
  \renewcommand*{\printchaptertitle}[1]{%
    \hrule\vskip\onelineskip \centering \chaptitlefont\textbf{##1}\par}
  \renewcommand*{\afterchaptertitle}{\vskip\onelineskip \hrule\vskip
    \afterchapskip}
  \renewcommand*{\printchapternonum}{%
    \vphantom{\chapnumfont \textit{9}}\afterchapternum}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@bringhurst}
% My bringhurst style.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to bringhurst chapterstyle}
% \changes{c3.6k}{2012/09/18}{\cs{MakeLowercase} $\to$ \cs{MakeTextLowercase}}
%    \begin{macrocode}
\makechapterstyle{bringhurst}{%
  \chapterstyle{default}
  \renewcommand*{\chapterheadstart}{}
  \renewcommand*{\printchaptername}{}
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\printchapternum}{}
  \renewcommand*{\afterchapternum}{}
  \renewcommand*{\printchaptertitle}[1]{%
 %%%    \raggedright\Large\scshape\MakeLowercase{##1}}
    \memRTLraggedright\Large\scshape\MakeTextLowercase{##1}}
  \renewcommand*{\afterchaptertitle}{%
  \vskip\onelineskip \hrule\vskip\onelineskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@brotherton}
% An extremely simple chapterstyle created by William Adams for Mike 
% Brotherton's science fiction novel \textit{Star Dragon}, posted to CTT
% 2006/12/09, \textit{An example of a novel?}.
%    \begin{macrocode}
\makechapterstyle{brotherton}{%
  \chapterstyle{default}
  \renewcommand*{\printchapternum}{\chapnumfont 
    \ifanappendix \thechapter \else \numtoName{\c@chapter}\fi}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@chappell}
% My Chappell style
%    \begin{macrocode}
\makechapterstyle{chappell}{%
  \chapterstyle{default}
  \setlength{\beforechapskip}{0pt}
  \renewcommand*{\chapnamefont}{\large\centering}
  \renewcommand*{\chapnumfont}{\large}
  \renewcommand*{\printchapternonum}{%
    \vphantom{\printchaptername \chapnumfont 1}
    \afterchapternum
    \vskip \onelineskip \vskip -\topskip}
  \renewcommand*{\chaptitlefont}{\Large\itshape}
  \renewcommand*{\printchaptertitle}[1]{%
    \hrule\vskip\onelineskip \centering\chaptitlefont ##1}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@culver}
% By me in an answer to Christopher Culver on CTT, 
% \textit{"Biblical" formatting, how?} on 2004/03/29,where I called it 
% the `biblical' style.
%    \begin{macrocode}
\makechapterstyle{culver}{%
  \chapterstyle{default}
  \chapterstyle{article}%
  \renewcommand*{\thechapter}{\Roman{chapter}}
  \renewcommand*{\printchapternum}{% center number/title
    \centering\chapnumfont \thechapter\space\space}%
  \renewcommand*{\printchapternonum}{\centering}
  \renewcommand*{\clearforchapter}{}% no new page
  \aliaspagestyle{chapter}{headings}}% no special pagestyle

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@dash}
% A very simple style of mine but I couldn't think of a good name for it.
%    \begin{macrocode}
\makechapterstyle{dash}{%
  \chapterstyle{default}
  \setlength{\beforechapskip}{5\onelineskip}
  \renewcommand*{\printchaptername}{}
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\chapnumfont}{\normalfont\large}
  \settoheight{\midchapskip}{\chapnumfont 1}
  \renewcommand*{\printchapternum}{\centering \chapnumfont 
    \rule[0.5\midchapskip]{1em}{0.4pt} \thechapter\ 
    \rule[0.5\midchapskip]{1em}{0.4pt}}
  \renewcommand*{\afterchapternum}{\par\nobreak\vskip 0.5\onelineskip}
  \renewcommand*{\printchapternonum}{\centering 
                 \vphantom{\chapnumfont 1}\afterchapternum}
  \renewcommand*{\chaptitlefont}{\normalfont\Large}
  \renewcommand*{\printchaptertitle}[1]{\centering \chaptitlefont ##1}
  \setlength{\afterchapskip}{2.5\onelineskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@demo2}
% My second version of the demo chapterstyle.
%    \begin{macrocode}
\makechapterstyle{demo2}{%
  \chapterstyle{default}
  \renewcommand*{\printchaptername}{\centering}
  \renewcommand*{\printchapternum}{\chapnumfont 
     \ifanappendix \thechapter \else \numtoName{\c@chapter}\fi}
  \renewcommand*{\chaptitlefont}{\normalfont\Huge\sffamily}
  \renewcommand*{\printchaptertitle}[1]{%
    \hrule\vskip\onelineskip \raggedleft \chaptitlefont ##1}
  \renewcommand*{\afterchaptertitle}{%
    \vskip\onelineskip \hrule\vskip \afterchapskip}
  \setlength{\beforechapskip}{3\baselineskip}
  \renewcommand*{\printchapternonum}{%
    \vphantom{\chapnumfont One}
    \afterchapternum%
    \vskip\topskip}
  \setlength{\beforechapskip}{2\onelineskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@demo3}
% My third version of the demo chapterstyle.
%    \begin{macrocode}
\makechapterstyle{demo3}{%
  \chapterstyle{default}
  \renewcommand*{\printchaptername}{\centering}
  \renewcommand*{\chapnumfont}{\normalfont\HUGE\itshape}
  \renewcommand*{\printchapternum}{\chapnumfont 
     \ifanappendix \thechapter \else \numtoName{\c@chapter}\fi}
  \renewcommand*{\chaptitlefont}{\normalfont\Huge\sffamily}
  \renewcommand*{\printchaptertitle}[1]{%
    \hrule\vskip\onelineskip \raggedleft \chaptitlefont ##1}
  \renewcommand*{\afterchaptertitle}{%
    \vskip\onelineskip \hrule\vskip \afterchapskip}
  \setlength{\beforechapskip}{0pt}
  \setlength{\midchapskip}{2\onelineskip}
  \setlength{\afterchapskip}{2\onelineskip}
  \renewcommand*{\printchapternonum}{%
    \vphantom{\chapnumfont One}
    \afterchapternum%
    \vskip\topskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@ell}
% Another of my styles which I'll probably use for my next book.
%
% James Dietrich\footnote{\texttt{jdietrch@fastmail.fm}} (2014/05/29)
% reports that the line and number part of the \textsf{ell} chapter
% style does not align correctly if the page is excessively
% stretched. The style is reimplemented using \Lenv{tabularx} instead.
% \changes{v3.7d}{2014/11/05}{Reimplemeted the ell chapter style}
% \begin{macro}{\chs@ell@helper}
%   For code reuse (the slightly strange values come from trial and
%   error to match the original look):
%    \begin{macrocode}
\newcommand\chs@ell@helper[1]{%
  \par%
    \begin{adjustwidth}{}{-\chapindent}
      \begin{tabularx}{\linewidth}{>{\raggedleft\arraybackslash}X|}%|emacs
        \leavevmode\chapnumfont #1\vphantom{1}%
        \hspace*{3.6pt}%
        \rule[-13.5pt]{0pt}{14.8mm}%
        \\%
        \hline%
      \end{tabularx}%
    \end{adjustwidth}%
    \par%
  }%

%    \end{macrocode}
% \end{macro}
% 
%    \begin{macrocode}
\makechapterstyle{ell}{%
  \chapterstyle{default}
  \renewcommand*{\chapnumfont}{\normalfont\HUGE\sffamily}
  \renewcommand*{\chaptitlefont}{\normalfont\huge\sffamily}
  \settowidth{\chapindent}{\chapnumfont 111}
  % \renewcommand*{\chapterheadstart}{\begingroup
  %   \vspace*{\beforechapskip}%
  %   \begin{adjustwidth}{}{-\chapindent}%
  %   \hrulefill
  %   \smash{\rule{0.4pt}{15mm}}
  %   \end{adjustwidth}\endgroup}
  \renewcommand*{\printchaptername}{}
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\printchapternum}{% 
    % \begin{adjustwidth}{}{-\chapindent}
    % \hfill
    % \raisebox{10mm}[0pt][0pt]{\chapnumfont \thechapter}%
    %                           \hspace*{1em}
    % \end{adjustwidth}\vspace*{-3.0\onelineskip}
    \chs@ell@helper{\thechapter}%
  }
  \renewcommand\printchapternonum{%
    \chs@ell@helper{}\afterchapternum}
  \renewcommand*{\printchaptertitle}[1]{%
    %\vskip\onelineskip
    \raggedleft {\chaptitlefont ##1}\par\nobreak}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@ger}
% Posted to CTT on 2002/04/12 \textit{Fancy Headings, Chapter Headings} by Gerardo Garcia.
%    \begin{macrocode}
\makechapterstyle{ger}{%
  \chapterstyle{default}
  \renewcommand*{\chapterheadstart}{\vspace*{\beforechapskip}
  \mbox{}\\\mbox{}\rule[0pt]{\textwidth}{0.4pt}\par}
  \setlength{\midchapskip}{20pt}
  \renewcommand*{\printchaptertitle}[1]{\chaptitlefont ##1
    \\\mbox{}\rule[5pt]{\textwidth}{0.4pt}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@lyhne}
% Posted to CTT 2006/02/09 \textit{Glossary}, by Anders Lyhne.
% It requires the \Lpack{graphicx} package. I have modified it to remove the
% new length and adjusted the unnumbered appearance.
%    \begin{macrocode}
\makechapterstyle{lyhne}{%  needs graphicx package
  \chapterstyle{default}
  \setlength{\beforechapskip}{1.5cm}
  \setlength{\afterchapskip}{1cm}
  \setlength{\midchapskip}{2cm}
  \renewcommand*{\chapnamefont}{\normalfont\normalsize\scshape\raggedleft}
  \renewcommand*{\chaptitlefont}{\normalfont\normalsize\bfseries\sffamily\raggedleft}
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\printchapternum}{\makebox[0pt][l]{\hspace{0.2em}%
    \resizebox{!}{2ex}{\chapnamefont\bfseries\sffamily\thechapter}}}
  \renewcommand*{\afterchapternum}{\par\hspace{1.5cm}\hrule\vspace{0.2cm}}
 \renewcommand*{\printchapternonum}{\vphantom{\chapnamefont 1}\afterchapternum}
  \renewcommand*{\afterchaptertitle}{\vskip 0.2cm 
    \hrule\vskip\afterchapskip}}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\chs@madsen}
% Posted to CTT on 2003/12/09, \textit{New chapter style: chapter vs chapter*}
% by Lars Madsen. 
% This requires the \Lpack{graphicx} package,
% \changes{v1.61803398c}{2009/11/15}{Updated to provide a better
% unnumbered look}
% \changes{v3.6d}{2010/05/13}{the unnumbered version may be executed
% in a context where \cs{thechapter} is not weldefined, replaced with
% a 1}
%    \begin{macrocode}
\makechapterstyle{madsen}{% requires graphicx package
  \chapterstyle{default}
  \renewcommand*{\chapnamefont}{%
    \normalfont\Large\scshape\raggedleft}
  \renewcommand*{\chaptitlefont}{%
    \normalfont\Huge\bfseries\sffamily\raggedleft}
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\printchapternum}{%
    \makebox[0pt][l]{\hspace{0.4em}%
      \resizebox{!}{4ex}{%
        \chapnamefont\bfseries\sffamily\thechapter}%
    }%
  }%
  \renewcommand*{\printchapternonum}{%
    \chapnamefont \phantom{\printchaptername \chapternamenum%
      \makebox[0pt][l]{\hspace{0.4em}%
        \resizebox{!}{4ex}{%
          \chapnamefont\bfseries\sffamily 1}%
      }%
    }%
    \afterchapternum %
  }% 
  \renewcommand*{\afterchapternum}{%
    \par\hspace{1.5cm}\hrule\vskip\midchapskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\colorchapnum}
% \begin{macro}{\colorchaptitle}
% \begin{macro}{\chs@pedersen}
% Posted to CTT 2006/01/31, \textit{Chapter style}, by Troels Pedersen.
% It requires the \Lpack{graphicx} package and possibly the \Lpack{color}
% package. I have used a \cs{sidebar} instead of the original \cs{marginpar},
% and eliminated a new length. The original color specification, the same for
% the title and nunmber, can now be set via \cs{colorchapnum} and
% \cs{colorchaptitle}.
%    \begin{macrocode}
\newcommand*{\colorchapnum}{}
\newcommand*{\colorchaptitle}{}
\makechapterstyle{pedersen}{%
  \chapterstyle{default}
  \setlength{\beforechapskip}{-20pt}
  \setlength{\afterchapskip}{10pt}
  \renewcommand*{\chapnamefont}{\normalfont\LARGE\itshape}
  \renewcommand*{\chapnumfont}{\normalfont\HUGE\itshape\colorchapnum}
  \renewcommand*{\chaptitlefont}{\normalfont\huge\itshape\colorchaptitle}
  \renewcommand*{\afterchapternum}{}
  \renewcommand*{\printchaptername}{}
  \setlength{\midchapskip}{20mm}% was \numberheight
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\printchapternum}{%
    \sidebar{\raisebox{0pt}[0pt][0pt]{\makebox[0pt][l]{%
      \resizebox{!}{\midchapskip}{\chapnumfont\thechapter}}}}}
  \renewcommand*{\printchaptertitle}[1]{\chaptitlefont ##1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\chs@southall}
% Style provided by Thomas Dye. I have modified the original to eliminate
% the use of new lengths.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to southall chapterstyle}
%    \begin{macrocode}
%% Thomas Dye's southall chapter style
\makechapterstyle{southall}{%
  \chapterstyle{default}
  \setlength{\afterchapskip}{5\baselineskip}
  \setlength{\beforechapskip}{36pt}%    \headindent
  \setlength{\midchapskip}{\textwidth}% \rightblock
  \addtolength{\midchapskip}{-\beforechapskip}
  \renewcommand*{\chapterheadstart}{\vspace*{2\baselineskip}}
%%%  \renewcommand*{\chaptitlefont}{\huge\rmfamily\raggedright}
  \renewcommand*{\chaptitlefont}{\huge\rmfamily\memRTLraggedright}
  \renewcommand*{\chapnumfont}{\chaptitlefont}
  \renewcommand*{\printchaptername}{}
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\afterchapternum}{}
  \renewcommand*{\printchapternum}{%
    \begin{minipage}[t][\baselineskip][b]{\beforechapskip}
      {\vspace{0pt}\chapnumfont%%%\figureversion{lining} 
                   \thechapter}
    \end{minipage}}
  \renewcommand*{\printchaptertitle}[1]{%
    \hfill\begin{minipage}[t]{\midchapskip}
      {\vspace{0pt}\chaptitlefont ##1\par}\end{minipage}}
  \renewcommand*{\afterchaptertitle}{%
    \par\vspace{\baselineskip}%
    \hrulefill \par\nobreak\noindent \vskip \afterchapskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@thatcher}
%  Original posted to CTT on 2006/01/18 by Scott Thatcher,
% \textit{memoir: chapter headings capitalize math symbols}. I have modified
% it to cater for multiline titles, appendices, and unnumbered
% chapters.
% \changes{c3.6k}{2012/09/18}{\cs{MakeUppercase} $\to$ \cs{MakeTextUppercase}}
% \changes{c3.6k}{2012/09/18}{\cs{MakeLowercase} $\to$ \cs{MakeTextLowercase}}
%    \begin{macrocode}
\makechapterstyle{thatcher}{%
  \chapterstyle{default}
  \renewcommand*{\chapterheadstart}{}
  \renewcommand*{\printchaptername}{%
    \centerline{\chapnumfont{\@chapapp\ \thechapter}}}
  \renewcommand*{\chapternamenum}{}
  \renewcommand*{\chapnumfont}{\normalfont\scshape\MakeTextLowercase}
  \renewcommand*{\printchapternum}{}
  \renewcommand*{\afterchapternum}{%
    \par\centerline{\parbox{0.5in}{\hrulefill}}\par}
  \renewcommand*{\printchapternonum}{%
    \vphantom{\chapnumfont \@chapapp 1}\par 
    \parbox{0.5in}{}\par}
  \renewcommand*{\chaptitlefont}{\normalfont\large}
  \renewcommand*{\printchaptertitle}[1]{%
    \centering \chaptitlefont\MakeTextUppercase{##1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@veelo}
% This, from Baastian Veelo, has been noted in the documentation for 
% quite a time.
% I have modified the original to eliminate the need for extra lengths.
% It well suits trimmed documents.
% We are scaling the chapter number, which most DVI viewers
% will not display accurately. It requires the graphicx package.
% \changes{c3.6k}{2012/09/18}{\cs{MakeUppercase} $\to$ \cs{MakeTextUppercase}}
%    \begin{macrocode}
\makechapterstyle{veelo}{%
%  \chapterstyle{default}
   \setlength{\afterchapskip}{40pt}
  \renewcommand*{\chapterheadstart}{\vspace*{40pt}}
  \renewcommand*{\afterchapternum}{\par\nobreak\vskip 25pt}
   \renewcommand*{\chapnamefont}{\normalfont\LARGE\flushright}
   \renewcommand*{\chapnumfont}{\normalfont\HUGE}
   \renewcommand*{\chaptitlefont}{\normalfont\HUGE\bfseries\flushright}
   \renewcommand*{\printchaptername}{%
     \chapnamefont\MakeTextUppercase{\@chapapp}}
   \renewcommand*{\chapternamenum}{}
%   \setlength{\numberheight}{18mm}
%   \setlength{\barlength}{\paperwidth}
%   \addtolength{\barlength}{-\textwidth}
%   \addtolength{\barlength}{-\spinemargin}
  \setlength{\beforechapskip}{18mm}%  \numberheight
  \setlength{\midchapskip}{\paperwidth}% \barlength
  \addtolength{\midchapskip}{-\textwidth}
  \addtolength{\midchapskip}{-\spinemargin}
   \renewcommand*{\printchapternum}{%
     \makebox[0pt][l]{%
       \hspace{.8em}%
       \resizebox{!}{\beforechapskip}{\chapnumfont \thechapter}%
       \hspace{.8em}%
       \rule{\midchapskip}{\beforechapskip}%
     }%
   }%
   \makeoddfoot{plain}{}{}{\thepage}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@verville}
% I posted the original to CTT on 2005/01/18, \textit{Headers and special
% formatting of sections}, in answer to a question by 
% Guy Verville. This version caters for unnumbered chapters.
%    \begin{macrocode}
\makechapterstyle{verville}{%
 % \chapterstyle{default}
  \setlength{\beforechapskip}{0pt}
  \renewcommand*{\printchaptername}{}
  \renewcommand*{\printchapternum}{%
    \hrule \vskip 0.5\onelineskip
    \Huge \centering \thechapter.\ }
  \renewcommand*{\printchapternonum}{%
    \hrule \vskip 0.5\onelineskip
    \Huge \centering}
  \renewcommand*{\afterchapternum}{}
  \setlength{\midchapskip}{0pt}
  \renewcommand*{\printchaptertitle}[1]{%
    ##1 \par
    \vskip 0.5\onelineskip
   \hrule}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@crosshead}
% A centered chapterstyle (from Bringhurst)
% \changes{v1.61803}{2008/01/30}{Added chapterstyles: crosshead, dowding, 
%                    komalike, ntglike, tandh, and wilsondob}
%    \begin{macrocode}
\makechapterstyle{crosshead}{%
  \setlength{\beforechapskip}{2\onelineskip}%
  \renewcommand*{\chapterheadstart}{\vspace{\beforechapskip}}%
  \setlength{\afterchapskip}{2\onelineskip \@plus .2\onelineskip 
                             \@minus 0.2\onelineskip}%
  \renewcommand*{\printchaptername}{}%
  \renewcommand*{\chapternamenum}{}%
  \renewcommand*{\chapnumfont}{\normalfont\LARGE\bfseries}%
  \renewcommand*{\chaptitlefont}{\chapnumfont}%
  \renewcommand*{\printchapternum}{%
    \centering\chapnumfont \thechapter\quad}%
  \renewcommand{\afterchapternum}{}%
  \renewcommand*{\printchapternonum}{\centering}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@dowding}
% A centered chapterstyle (from Dowding's \textit{Finer Points})
%    \begin{macrocode}
\makechapterstyle{dowding}{%
  \setlength{\beforechapskip}{2\onelineskip}%
  \setlength{\afterchapskip}{1.5\onelineskip \@plus .1\onelineskip 
                            \@minus 0.167\onelineskip}%
  \renewcommand*{\chapnamefont}{\normalfont}%
  \renewcommand*{\chapnumfont}{\chapnamefont}%
  \renewcommand*{\printchapternum}{\centering\chapnumfont \ifanappendix \thechapter
                 \else \numtoName{\c@chapter}\fi}%
  \renewcommand*{\chaptitlefont}{\normalfont\itshape\huge\centering}%
  \renewcommand*{\printchapternonum}{%
    \vphantom{\printchaptername}\vskip\midchapskip}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@komalike}
% A chapterstyle approximating the KOMA script style (\texttt{scrbook.cls})
%    \begin{macrocode}
\makechapterstyle{komalike}{%
  \setlength{\beforechapskip}{2\onelineskip}%
  \setlength{\afterchapskip}{1.5\onelineskip \@plus .1\onelineskip 
                             \@minus 0.167\onelineskip}%
  \renewcommand*{\printchaptername}{}%
  \renewcommand*{\chapternamenum}{}%
  \renewcommand*{\chapnumfont}{\normalfont\LARGE\sffamily\bfseries}%
  \renewcommand*{\printchapternum}{\chapnumfont \thechapter\space}%
  \renewcommand*{\afterchapternum}{}%
  \renewcommand*{\chaptitlefont}{\normalfont\LARGE\sffamily\bfseries}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@ntglike}
% A chapterstyle approximating the NTG style (\texttt{boek.cls})
%    \begin{macrocode}
\makechapterstyle{ntglike}{%
  \setlength{\beforechapskip}{50pt \@plus 20pt}%
  \renewcommand*{\chapnamefont}{\normalfont\Large\bfseries}%
  \renewcommand*{\chapnumfont}{\normalfont\Large\bfseries}%
  \renewcommand*{\chaptitlefont}{\normalfont\Large\bfseries}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@tandh}
% A chapterstyle based on Thames \& Hudson \textit{Typography}.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to tandh chapterstyle}
%    \begin{macrocode}
\makechapterstyle{tandh}{%
  \setlength{\beforechapskip}{1\onelineskip}%
  \setlength{\afterchapskip}{2\onelineskip \@plus .1\onelineskip 
                            \@minus 0.167\onelineskip}%
  \renewcommand*{\printchaptername}{}%
  \renewcommand*{\chapternamenum}{}%
  \renewcommand*{\chapnumfont}{\normalfont\huge\bfseries}%
  \renewcommand*{\printchapternum}{\chapnumfont \thechapter\quad}%
  \renewcommand*{\afterchapternum}{}%
%%%  \renewcommand*{\chaptitlefont}{\chapnumfont\raggedright}}
  \renewcommand*{\chaptitlefont}{\chapnumfont\memRTLraggedright}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chs@wilsondob}
% A chapterstyle based on Adrian Wilson's \textit{Design of books}.
%    \begin{macrocode}
\makechapterstyle{wilsondob}{%
  \setlength{\beforechapskip}{2\onelineskip}%
  \setlength{\afterchapskip}{4\onelineskip \@plus .1\onelineskip 
                             \@minus 0.167\onelineskip}%
  \renewcommand*{\printchaptername}{}%
  \renewcommand*{\chapternamenum}{}%
  \renewcommand*{\chapnumfont}{\normalfont\Huge\itshape}%
  \renewcommand*{\printchapternum}{\raggedleft\chapnumfont \thechapter\quad}%
  \renewcommand*{\afterchapternum}{}%
  \renewcommand*{\chaptitlefont}{\chapnumfont}%
  \renewcommand*{\printchapternonum}{\raggedleft}}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Lower level headings}
%
%    These commands all make use of \cs{@startsection}. However,
% for the purposes of the class the kernel version needs modification
% to support:
% \begin{itemize}
% \item make short pages (where a section heading is moved to the top
%       of the next page) ragged bottom;
% \item provide headings with two optional arguments.
% \end{itemize}
%
%
%    We will tweak \cs{@startsection} so that a short page (where a section
% heading is moved from the bottom of the page to the top of the next)
% can be set \cs{raggedbottom}. 
%
% \begin{macro}{\ifraggedbottomsection}
% \begin{macro}{\raggedbottomsectiontrue}
% \begin{macro}{\raggedbottomsectionfalse}
% \begin{macro}{\raggedbottomsection}
% \begin{macro}{\normalbottomsection}
% \begin{macro}{\bottomsectionpenalty}
% \cs{raggedbottomsectiontrue} for ragged short pages.
% \changes{v1.3}{2002/11/14}{Added \cs{ifraggedbottomsection}}
% \changes{v1.61803}{2008/01/30}{Added \cs{raggedbottomsection} and 
%                               \cs{normalbottomsection}}
% \changes{v3.6k}{2012/07/22}{Made the \cs{raggedbottomsection}
% penalty configurable}
%    \begin{macrocode}
\newif\ifraggedbottomsection
  \raggedbottomsectionfalse
\newcommand*{\raggedbottomsection}{\raggedbottomsectiontrue}
\newcommand*{\normalbottomsection}{\raggedbottomsectionfalse}
\newcommand*{\bottomsectionpenalty}{\z@}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\bottomsectionskip}
% Decreasing this length increases short page bottom flushness.
% \changes{v1.3}{2002/11/14}{Added \cs{bottomsectionskip}}
%    \begin{macrocode}
\newlength{\bottomsectionskip}
  \setlength{\bottomsectionskip}{10mm}

%    \end{macrocode}
% \end{macro}
%
% We will add a second optional argument for \cs{section}, etc.
% See the \ctt{} thread \textit{`Long headers'} 15 Jan 2003.
%
% The kernel \cs{@dblarg} is used in situations where the default
% value for an optional argument is the same as the required argument.
% Schematically, \\
% \verb?\@dblarg -> Main, Main? \\
% The macros \cs{@trplargomm} and \cs{@trplargoom} are extensions to this
% idea for two optional arguments.
%
% \begin{macro}{\@trplargomm}
% \begin{macro}{\@xtrplargomm}
% \begin{macro}{\@xxtrplarg}
% \verb?\@trplargomm -> Opt, Main, Main?
%    \begin{macrocode}
\newcommand{\@trplargomm}[1]{%
  \@ifnextchar[{\@xtrplargomm{#1}}%
               {\@xxtrplarg{#1}}}
\long\def\@xtrplargomm#1[#2]{\@dblarg{#1[#2]}}
\newcommand{\@xxtrplarg}[2]{#1[{#2}][{#2}]{#2}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@trplargoom}
% \begin{macro}{\@xtrplargoom}
% \verb?\@trplargoom -> Opt, Opt, Main?
%    \begin{macrocode}
\newcommand{\@trplargoom}[1]{%
  \@ifnextchar[{\@xtrplargoom{#1}}%
               {\@xxtrplarg{#1}}}
\long\def\@xtrplargoom#1[#2]{%
  \@ifnextchar[{#1[{#2}]}%
               {#1[{#2}][{#2}]}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memsecinfo}
% \begin{macro}{\memsecstarinfo}
% \verb?\memsecinfo{secname}{\thenum}{toc}{head}{title}? \\
% \verb?\memsecstarinfo{secname}{title}? \\
%    \begin{macrocode}
\newcommand{\memsecinfo}[5]{}
\newcommand{\memsecstarinfo}[2]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@startsection}
% \begin{macro}{\m@msecn@me}
% Change kernel \cs{@startsection} to: \\
% \begin{itemize}
% \item Make short pages raggedbottom. This is based on the thread 
% \textit{Can \cs{flushbottom} and \cs{section} be made to live together?} 
% on \ctt{} in September 2002.
% \changes{v1.3}{2002/11/14}{Modified \cs{@startsection} for raggedbottoming}
% \item add an extra optional argument.
% \changes{v1.4}{2003/11/22}{Added extra optional arg to \cs{@startsection}
%                            (from patch v1.4)}
% \item make sure it is not effected by a non-zero \cs{parskip}
% \changes{v3.6j}{2011/03/02}{added the above feature}
% \end{itemize}
% The original is in \file{ltsect.dtx}. \\
% \cs{@startsection}\marg{name}\marg{level}\marg{indent} \\
% \hspace*{1.5in} \marg{beforeskip}\marg{afterskip}\marg{style}
%    \begin{macrocode}
\renewcommand{\@startsection}[6]{%
%    \end{macrocode}
% \changes{v3.6h}{2011/02/07}{Added float block hook}
%    \begin{macrocode}
  \@nameuse{#1block}%
%    \end{macrocode}
% Do raggedbottom stuff.
% \changes{v3.6k}{2012/07/22}{Made the \cs{raggedbottomsection}
% penalty configurable}
%    \begin{macrocode}
  \ifraggedbottomsection\if@nobreak\else
    \vskip\z@\@plus\bottomsectionskip
    \penalty\bottomsectionpenalty
    \vskip\z@\@plus -\bottomsectionskip
  \fi\fi
%    \end{macrocode}
% Save the section name.
%    \begin{macrocode}
  \def\m@msecn@me{#1}%
%    \end{macrocode}
% The original code.
%    \begin{macrocode}
  \if@noskipsec \leavevmode \fi
  \par
  \@tempskipa #4\relax
  \@afterindenttrue
  \ifdim \@tempskipa <\z@
    \@tempskipa -\@tempskipa \@afterindentfalse
  \fi
  \if@nobreak
    \everypar{}%
  \else
%    \end{macrocode}
% Slight change such that the effect of \cs{parskip} is cancelled
% \changes{v3.6j}{2011/03/02}{Adding a negative \cs{parskip} seem to
% be able to remove the effect of a non-zero \cs{parskip}}
%    \begin{macrocode}
    \addpenalty\@secpenalty\addvspace\@tempskipa
    \addvspace{-\parskip}% <--- added 2011/03/02
  \fi
%    \end{macrocode}
% For the extra optional argument, change the original \verb?\@dblarg{\@sect{...?
% below to \verb?\@trplargoom{\M@sect{...?.
%    \begin{macrocode}
  \@ifstar
    {\@ssect{#3}{#4}{#5}{#6}}%
    {\@trplargoom{\M@sect{#1}{#2}{#3}{#4}{#5}{#6}}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \changes{v3.6j}{2011/03/02}{Added the change of the kernel \cs{@xsect}}
% \begin{macro}{\@xsect}
%   In order to fulfill removing the effect that a non-zero
%   \cs{parskip} has on the sectional spacing, we also have to patch
%   the kernel \cs{@xsect}. (The original is found in latex.ltx) 
%    \begin{macrocode}
\def\@xsect#1{%
  \@tempskipa #1\relax
  \ifdim \@tempskipa>\z@
    \par \nobreak
    \vskip \@tempskipa
    \vskip-\parskip%<--- added 2011/03/02
    \@afterheading
  \else
    \@nobreakfalse
    \global\@noskipsectrue
    \everypar{%
      \if@noskipsec
        \global\@noskipsecfalse
       {\setbox\z@\lastbox}%
        \clubpenalty\@M
        \begingroup \@svsechd \endgroup
        \unskip
        \@tempskipa #1\relax
        \hskip -\@tempskipa
      \else
        \clubpenalty \@clubpenalty
        \everypar{}%
      \fi}%
  \fi
  \ignorespaces}

%    \end{macrocode}
% \end{macro}
% %
% \begin{macro}{\M@sect}
% At least the \Lpack{hyperref} and \Lpack{nameref} packages, and
% possibly other packages,  modify the kernel \cs{@sect} assuming 8 args.
% That's why I've called my version, which has 9 args, something 
% else (i.e., \cs{M@sect}). This version also has the support
% for title referencing. \\
% \cs{M@sect}\marg{name}\marg{level}\marg{indent}\marg{beforeskip}\marg{afterskip}\marg{style}\\ \hspace*{0.5in} \oarg{toc}\oarg{head}\marg{title}
% \changes{v1.4}{2003/11/22}{Added \cs{M@sect}}
%    \begin{macrocode}
\def\M@sect#1#2#3#4#5#6[#7][#8]#9{%
  \ifheadnameref\M@gettitle{#8}\else\M@gettitle{#7}\fi
  \ifnum #2>\c@secnumdepth
    \let\@svsec\@empty
    \memsecinfo{#1}{}{#7}{#8}{#9}%
  \else
    \refstepcounter{#1}%
    \protected@edef\@svsec{\@seccntformat{#1}\relax}%
    \memsecinfo{#1}{\@nameuse{the#1}}{#7}{#8}{#9}%
  \fi
  \@tempskipa #5\relax
  \ifdim \@tempskipa>\z@
    \begingroup
      #6{%
      \@hangfrom{\hskip #3\relax\@svsec}%
        \interlinepenalty \@M #9\@@par}%
    \endgroup
    \csname #1mark\endcsname{#8}%
    \addcontentsline{toc}{#1}{%
      \ifnum #2>\c@secnumdepth \else
        \protect\numberline{\csname the#1\endcsname}%
      \fi
      #7}%
  \else
    \def\@svsechd{%
      #6{\hskip #3\relax
     \@svsec #9}%
     \csname #1mark\endcsname{#8}%
     \addcontentsline{toc}{#1}{%
       \ifnum #2>\c@secnumdepth \else
        \protect\numberline{\csname the#1\endcsname}%
       \fi
       #7}}%
  \fi
  \@xsect{#5}}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\@ssect}
% Add hook for name reference to \cs{section*} etc. \\
% \cs{@ssect}\marg{indent}\marg{beforeskip}\marg{afterskip}\marg{style}\marg{title}
% \changes{v1.61803}{2008/01/30}{Used corrected number of arguments to 
%         \cs{memsecstarinfo} in \cs{@ssect} (Gabriel Guernik, mempatch v4.1)}
%    \begin{macrocode}
\let\@mem@old@ssect\@ssect
\def\@ssect#1#2#3#4#5{%
  \M@gettitle{#5}%
  \memsecstarinfo{\m@msecn@me}{#5}%
  \@mem@old@ssect{#1}{#2}{#3}{#4}{#5}}

%    \end{macrocode}
% \end{macro}
%
%
% 
% \begin{macro}{\section}
% A normal heading with white space above and below and no indentation
% of the first paragraph. 
% By default the heading is set in a \verb?\Large\bfseries? font.
%    \begin{macrocode}
\newcommand{\section}{%
  \sechook%
  \@startsection{section}{1}%  level 1
      {\secindent}%            heading indent
      {\beforesecskip}%        skip before the heading
      {\aftersecskip}%         skip after the heading
      {\normalfont\secheadstyle}} % font
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sechook}
% \begin{macro}{\setsechook}
% \cs{sechook} is called at the start of a \cs{section} and 
% \cs{setsechook}\marg{code} redefines it.
%    \begin{macrocode}
\newcommand{\sechook}{}
\newcommand{\setsechook}[1]{\renewcommand{\sechook}{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\secindent}
% \begin{macro}{\beforesecskip}
% \begin{macro}{\aftersecskip}
% \begin{macro}{\secheadstyle}
% \begin{macro}{\setsecindent}
% \begin{macro}{\setbeforesecskip}
% \begin{macro}{\setaftersecskip}
% \begin{macro}{\setsecheadstyle}
% \cs{secindent} is the indentation of the section heading from the left margin,
% \cs{beforesecskip} and \cs{aftersecskip} specify the white space before
% and after the heading, and \cs{secheadstyle} specifies the heading style.
% These are set to the default values for the \Lpack{book} class,
% except that the heading will be \cs{raggedright}, thus preventing
% hyphenation. The
% \cs{set...} commands are for the user to change the values.
% \changes{v1.61803398}{@009/07/17}{Added bidi support to default secheadstyle}
%    \begin{macrocode}
\newlength{\secindent}
\newcommand{\setsecindent}[1]{\setlength{\secindent}{#1}}
  \setsecindent{\z@}
\newskip\beforesecskip
\newcommand{\setbeforesecskip}[1]{\setlength{\beforesecskip}{#1}}
  \setbeforesecskip{-3.5ex \@plus -1ex \@minus -.2ex}
\newskip\aftersecskip
\newcommand{\setaftersecskip}[1]{\setlength{\aftersecskip}{#1}}
  \setaftersecskip{2.3ex \@plus .2ex}
\newcommand{\secheadstyle}{}
\newcommand{\setsecheadstyle}[1]{\renewcommand{\secheadstyle}{#1}}
%%%  \setsecheadstyle{\Large\bfseries\raggedright}
  \setsecheadstyle{\Large\bfseries\memRTLraggedright}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\subsection}
% A normal heading with white space above and below and no indentation
% of the first paragraph.
% By default the heading is set in a \verb?\large\bfseries? font.
%    \begin{macrocode}
\newcommand{\subsection}{%
  \subsechook%
  \@startsection{subsection}{2}%  level 2
      {\subsecindent}%            heading indent
      {\beforesubsecskip}%        skip before the heading
      {\aftersubsecskip}%         skip after the heading
      {\normalfont\subsecheadstyle}} % font
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\subsechook}
% \begin{macro}{\setsubsechook}
% \cs{subsechook} is called at the start of a \cs{subsection} and 
% \cs{setsubsechook}\marg{code} redefines it.
%    \begin{macrocode}
\newcommand{\subsechook}{}
\newcommand{\setsubsechook}[1]{\renewcommand{\subsechook}{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\subsecindent}
% \begin{macro}{\beforesubsecskip}
% \begin{macro}{\aftersubsecskip}
% \begin{macro}{\subsecheadstyle}
% \begin{macro}{\setsubsecindent}
% \begin{macro}{\setbeforesubsecskip}
% \begin{macro}{\setaftersubsecskip}
% \begin{macro}{\setsubsecheadstyle}
% The macros for controlling \cs{subsection} headings.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to default subsec headstyle}
%    \begin{macrocode}
\newlength{\subsecindent}
\newcommand{\setsubsecindent}[1]{\setlength{\subsecindent}{#1}}
  \setsubsecindent{\z@}
\newskip\beforesubsecskip
\newcommand{\setbeforesubsecskip}[1]{\setlength{\beforesubsecskip}{#1}}
  \setbeforesubsecskip{-3.25ex \@plus -1ex \@minus -.2ex}
\newskip\aftersubsecskip
\newcommand{\setaftersubsecskip}[1]{\setlength{\aftersubsecskip}{#1}}
  \setaftersubsecskip{1.5ex \@plus .2ex}
\newcommand{\subsecheadstyle}{}
\newcommand{\setsubsecheadstyle}[1]{\renewcommand{\subsecheadstyle}{#1}}
%%%  \setsubsecheadstyle{\large\bfseries\raggedright}
  \setsubsecheadstyle{\large\bfseries\memRTLraggedright}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\subsubsection}
% A normal heading with white space above and below and no indentation
% of the first paragraph.
% By default the heading is set in a \verb?\normalsize\bfseries? font.
%    \begin{macrocode}
\newcommand{\subsubsection}{%
  \subsubsechook%
  \@startsection{subsubsection}{3}%  level 3
      {\subsubsecindent}%            heading indent
      {\beforesubsubsecskip}%        skip before the heading
      {\aftersubsubsecskip}%         skip after the heading
      {\normalfont\subsubsecheadstyle}} % font
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\subsubsechook}
% \begin{macro}{\setsubsubsechook}
% \cs{subsubsechook} is called at the start of a \cs{subsubsection} and 
% \cs{setsubsubsechook}\marg{code} redefines it.
%    \begin{macrocode}
\newcommand{\subsubsechook}{}
\newcommand{\setsubsubsechook}[1]{\renewcommand{\subsubsechook}{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\subsubsecindent}
% \begin{macro}{\beforesubsubsecskip}
% \begin{macro}{\aftersubsubsecskip}
% \begin{macro}{\subsubsecheadstyle}
% \begin{macro}{\setsubsubsecindent}
% \begin{macro}{\setbeforesubsubsecskip}
% \begin{macro}{\setaftersubsubsecskip}
% \begin{macro}{\setsubsubsecheadstyle}
% The macros for controlling \cs{subsubsection} headings.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to default subsubsec headstyle}
%    \begin{macrocode}
\newlength{\subsubsecindent}
\newcommand{\setsubsubsecindent}[1]{%
            \setlength{\subsubsecindent}{#1}}
  \setsubsubsecindent{\z@}
\newskip\beforesubsubsecskip
\newcommand{\setbeforesubsubsecskip}[1]{%
            \setlength{\beforesubsubsecskip}{#1}}
  \setbeforesubsubsecskip{-3.25ex \@plus -1ex \@minus -.2ex}
\newskip\aftersubsubsecskip
\newcommand{\setaftersubsubsecskip}[1]{%
            \setlength{\aftersubsubsecskip}{#1}}
  \setaftersubsubsecskip{1.5ex \@plus .2ex}
\newcommand{\subsubsecheadstyle}{}
\newcommand{\setsubsubsecheadstyle}[1]{%
            \renewcommand{\subsubsecheadstyle}{#1}}
%%%  \setsubsubsecheadstyle{\normalsize\bfseries\raggedright}
  \setsubsubsecheadstyle{\normalsize\bfseries\memRTLraggedright}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% 
%
% \begin{macro}{\paragraph}
% A runin heading with white space above and to the right of the heading.
% By default the heading is set in a \verb?\normalsize\bfseries? font.
%    \begin{macrocode}
\newcommand{\paragraph}{%
  \parahook%
  \@startsection{paragraph}{4}%  level 4
      {\paraindent}%            heading indent
      {\beforeparaskip}%        skip before the heading
      {\afterparaskip}%         skip after the heading
      {\normalfont\paraheadstyle}} % font
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\parahook}
% \begin{macro}{\setparahook}
% \cs{parahook} is called at the start of a \cs{paragraph} and 
% \cs{setparahook}\marg{code} redefines it.
%    \begin{macrocode}
\newcommand{\parahook}{}
\newcommand{\setparahook}[1]{\renewcommand{\parahook}{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\paraindent}
% \begin{macro}{\beforeparaskip}
% \begin{macro}{\afterparaskip}
% \begin{macro}{\paraheadstyle}
% \begin{macro}{\setparaindent}
% \begin{macro}{\setbeforeparaskip}
% \begin{macro}{\setafterparaskip}
% \begin{macro}{\setparaheadstyle}
% The macros for controlling \cs{paragraph} headings.
%    \begin{macrocode}
\newlength{\paraindent}
\newcommand{\setparaindent}[1]{\setlength{\paraindent}{#1}}
  \setparaindent{\z@}
\newskip\beforeparaskip
\newcommand{\setbeforeparaskip}[1]{\setlength{\beforeparaskip}{#1}}
  \setbeforeparaskip{3.25ex \@plus 1ex \@minus .2ex}
\newskip\afterparaskip
\newcommand{\setafterparaskip}[1]{\setlength{\afterparaskip}{#1}}
  \setafterparaskip{-1em}
\newcommand{\paraheadstyle}{}
\newcommand{\setparaheadstyle}[1]{\renewcommand{\paraheadstyle}{#1}}
  \setparaheadstyle{\normalsize\bfseries}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% 
%
% \begin{macro}{\subparagraph}
% A runin heading with white space above and to the right of the heading.
% By default the heading is set in a \verb?\normalsize\bfseries? font.
%    \begin{macrocode}
\newcommand{\subparagraph}{%
  \subparahook%
  \@startsection{subparagraph}{5}%  level 5
      {\subparaindent}%            heading indent
      {\beforesubparaskip}%        skip before the heading
      {\aftersubparaskip}%         skip after the heading
      {\normalfont\subparaheadstyle}} % font
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\subparahook}
% \begin{macro}{\setsubparahook}
% \cs{subparahook} is called at the start of a \cs{subparagraph} and 
% \cs{setsubparahook}\marg{code} redefines it.
%    \begin{macrocode}
\newcommand{\subparahook}{}
\newcommand{\setsubparahook}[1]{\renewcommand{\subparahook}{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\subparaindent}
% \begin{macro}{\beforesubparaskip}
% \begin{macro}{\aftersubparaskip}
% \begin{macro}{\subparaheadstyle}
% \begin{macro}{\setsubparaindent}
% \begin{macro}{\setbeforesubparaskip}
% \begin{macro}{\setaftersubparaskip}
% \begin{macro}{\setsubparaheadstyle}
% The macros for controlling \cs{subparagraph} headings.
%    \begin{macrocode}
\newlength{\subparaindent}
\newcommand{\setsubparaindent}[1]{%
            \setlength{\subparaindent}{#1}}
  \setsubparaindent{\parindent}
\newskip\beforesubparaskip
\newcommand{\setbeforesubparaskip}[1]{%
            \setlength{\beforesubparaskip}{#1}}
  \setbeforesubparaskip{3.25ex \@plus 1ex \@minus .2ex}
\newskip\aftersubparaskip
\newcommand{\setaftersubparaskip}[1]{%
            \setlength{\aftersubparaskip}{#1}}
  \setaftersubparaskip{-1em}
\newcommand{\subparaheadstyle}{}
\newcommand{\setsubparaheadstyle}[1]{%
            \renewcommand{\subparaheadstyle}{#1}}
  \setsubparaheadstyle{\normalsize\bfseries}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\sethangfrom}
% The macro \cs{sethangfrom}\marg{code} is a user-level command
% for changing the definition of \cs{@hangfrom}. Use \verb?#1? in \meta{code}
% for the argument to \cs{@hangfrom} (or \verb?##1? if used inside another macro).
% \changes{v0.2}{2001/06/03}{Added \cs{sethangfrom}}
%    \begin{macrocode}
\newcommand{\sethangfrom}[1]{\renewcommand{\@hangfrom}[1]{#1}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setsecnumformat}
% The macro \cs{setsecnumformat}\marg{code} is a user-level command
% for changing the definition of \cs{@seccntformat}. Use \verb?#1? in \meta{code}
% for the argument to \cs{@seccntformat} (or \verb?##1? if used inside another macro).
% \changes{v0.2}{2001/06/03}{Added \cs{setsecnumformat}}
%    \begin{macrocode}
\newcommand{\setsecnumformat}[1]{\renewcommand{\@seccntformat}[1]{#1}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hangsecnum}
% \begin{macro}{\defaultsecnum}
% These are declarations for putting sectional numbers in the margin,
% or the default sectional number formatting.
% \changes{v0.2}{2001/06/03}{Added \cs{hangsecnum} and \cs{defaultsecnum}}
%    \begin{macrocode}
\newcommand{\hangsecnum}{%
  \def\@seccntformat##1{\llap{\csname the##1\endcsname\quad}}}
\newcommand{\defaultsecnum}{%
  \def\@seccntformat##1{\csname the##1\endcsname\quad}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \subsubsection{Anonymous headings}
%
% \begin{macro}{\plainbreak}
% \cs{plainbreak}\marg{num} generates \meta{num} blanks lines and
% suppresses the indentation of a following paragraph. The starred
% version, \cs{plainbreak*}, does not suppress paragraph indentation.
% \changes{v0.2}{2001/06/03}{Added starred version of \cs{plainbreak}}
%    \begin{macrocode}
\newcommand{\plainbreak}{\@ifstar{\@spbreak}{\@pbreak}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@pbreak}
% \begin{macro}{\@spbreak}
% These are the internal forms for the two versions of \cs{plainbreak}.
% The code for \cs{@pbreak} is almost a straight copy of code posted to
% \ctt{} by Donald Arseneau on 2001/03/26.
%    \begin{macrocode}
\newcommand*{\@pbreak}[1]{\par
  \penalty -100
  \vskip #1\onelineskip \@plus 2\onelineskip
  \penalty -20
  \vskip \z@ \@plus -2\onelineskip
  \@afterindentfalse
  \@afterheading}
\newcommand*{\@spbreak}[1]{\par
  \penalty -100
  \vskip #1\onelineskip \@plus 2\onelineskip
  \penalty -20
  \vskip \z@ \@plus -2\onelineskip
  \@afterindenttrue
  \@afterheading}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\fancybreak}
% \cs{fancybreak}\marg{text} typesets \meta{text} centered. For example,
% \verb?\fancybreak{{*}\\{* * *}\\{*}}?. It suppresses indentation of the 
% following paragraph. The starred version leaves indentation as is.
% \changes{v0.2}{2001/06/03}{Added starred version of \cs{fancybreak}}
% \changes{v1.3}{2002/11/14}{Tweaked \cs{fancybreak} to remove underfull hbox}
% \changes{v1.61803}{2008/01/30}{Changed fancybreak code to end the paragraph
%                   it started (Dan Leucking mempatch v4.5)}
%    \begin{macrocode}
\newcommand{\fancybreak}{\@ifstar{\@sfbreak}{\@fbreak}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@fbreak}
% \begin{macro}{\@sfbreak}
% These are the internal forms for the two versions of \cs{fancybreak}.
%    \begin{macrocode}
\newcommand{\@fbreak}[1]{\par
  \penalty -100
  \noindent\parbox{\linewidth}{\centering #1}%%\null
  \par
%%  \penalty -20
%%  \vskip -\onelineskip
  \@afterindentfalse
  \@afterheading}
\newcommand{\@sfbreak}[1]{\par
  \penalty -100
  \noindent\parbox{\linewidth}{\centering #1}%%\null
  \par
%%  \penalty -20
%%  \vskip -\onelineskip
  \@afterindenttrue
  \@afterheading}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\plainfancybreak}
% The \cs{plainfancybreak}\marg{space}\marg{num}\marg{text} acts
% like \cs{plainbreak}\marg{num} in the middle of a page and like
% \cs{fancybreak}\marg{text} at the bottom of a page. The \meta{space}
% argument is the vertical space required for the \meta{num} blank lines
% and some additional lines of text. From experiments, it seems that
% \meta{space} should be at least (3+\meta{num}) lines (\cs{onelineskip}).
% There is also a starred version, \cs{plainfancybreak*}, to match the other
% starred break commands.
% \changes{v0.2}{2001/06/03}{Added \cs{plainfancybreak} and supporting macros}
%    \begin{macrocode}
\newcommand{\plainfancybreak}{\@ifstar{\@spfbreak}{\@pfbreak}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@pfbreak}
% \begin{macro}{\@spfbreak}
% These are the internal macros for the unstarred and starred versions
% of \cs{plainfancybreak}. They essentially do the same thing, except they call, 
% respectively, the unstarred and starred internal versions of \cs{plainbreak}
% and \cs{fancybreak}. The code for checking the amount of space left on the
% page is from an early, and abandoned, version of the code for \cs{needspace}.
%    \begin{macrocode}
\newcommand{\@pfbreak}[3]{\par
  \@tempdimc\pagegoal \advance\@tempdimc-\pagetotal
  \ifdim #1>\@tempdimc \@fbreak{#3}\else \@pbreak{#2}\fi}
\newcommand{\@spfbreak}[3]{\par
  \@tempdimc\pagegoal \advance\@tempdimc-\pagetotal
  \ifdim #1>\@tempdimc \@sfbreak{#3}\else \@spbreak{#2}\fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% From the thread \textit{Customizing section hooks in memoir.cls} on \ctt{}
% in October 2002 it appeared that \cs{plainfancybreak} may be fragile.
% Donald Arseneau said that \cs{plainfancybreak} guessed at the amount
% of space available and gave code based on a modified output routine
% to make it more robust. The following code is based on that thread.
% \changes{v1.3}{2002/11/14}{Added lots of code for new \cs{pfbreak}}
%
% \begin{macro}{\pen@ltyabovepfbreak}
% \begin{macro}{\pen@ltybelowpfbreak}
% Penalities for communication with the output routine.
%    \begin{macrocode}
\newcommand*{\pen@ltyabovepfbreak}{2}
\newcommand*{\pen@ltybelowpfbreak}{-4}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\pfbreakskip}
% The vertical space taken by the plain and fancy breaks.
%    \begin{macrocode}
\newlength{\pfbreakskip}
  \setlength{\pfbreakskip}{2\baselineskip}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pfbreakdisplay}
% This is the fancybreak display, which must fit into \cs{pfbreakskip}
% vertical space.
%    \begin{macrocode}
\newcommand{\pfbreakdisplay}{*\quad*\quad*}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pfbre@kdispl@y}
% Typesets \cs{pfbreakdisplay} vertically and horizontally centered.
%    \begin{macrocode}
\def\pfbre@kdispl@y{\vbox to 1\pfbreakskip{\vss
  \hb@xt@ \columnwidth{\hss \pfbreakdisplay \hss}%
  \vss}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\nopfbreakOutput}
% Save the current output routine.
%    \begin{macrocode}
\edef\nopfbreakOutput{\the\output}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pfbreakOutput}
% Special output to handle the \cs{pfbreak}.
%    \begin{macrocode}
\def\pfbreakOutput{%
  \ifnum\outputpenalty=\pen@ltyabovepfbreak
    \nopfbreakOutput
    \pfbre@kdispl@y
    \nobreak
    \vskip-\pfbreakskip
  \else\ifnum\outputpenalty=\pen@ltybelowpfbreak
    \unvbox 255\relax
    \nobreak
    \vskip-\pfbreakskip
    \pfbre@kdispl@y
    \break
  \else
    \nopfbreakOutput
  \fi
  \fi}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\output}
% Use the new \cs{pfbreak} output routine.
%    \begin{macrocode}
\output={\pfbreakOutput}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pfbreak}
% Typesets a plain break in the middle of the page, otherwise
% a fancybreak at either the bottom or top of the page.
%    \begin{macrocode}
\newcommand{\pfbreak}{\@ifstar{\@spfbreakgap}{\@pfbreakgap}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@pfbreakgap}
% Unstarred version of \cs{pfbreak}.
% \changes{v3.6h}{2010/10/06}{fixed \cs{@pfbreakgab} kudos to DA for
% the fix}
%    \begin{macrocode}
\newcommand{\@pfbreakgap}{%
  \par {%
  \skip@\lastskip
  \nobreak
  \vskip -\ifdim\prevdepth>\maxdepth \maxdepth
          \else\ifdim\prevdepth>-1000pt\prevdepth
            \else\ifinner 0pt
              \else \pagedepth
          \fi \fi \fi
  \vskip -\skip@
  \ifdim\skip@<\pfbreakskip
    \advance\skip@ -1\skip@ \advance\skip@ 1\pfbreakskip
  \fi
  \penalty\pen@ltyabovepfbreak
  \prevdepth\z@ % added
  \vskip\skip@
  \penalty\pen@ltybelowpfbreak
  }
  \@afterindentfalse
  \@afterheading
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@spfbreakgap}
% Starred version of \cs{pfbreak}.
% \changes{v3.6h}{2010/10/06}{fixed \cs{@pfbreakgab} kudos to DA for
% the fix}
%    \begin{macrocode}
\newcommand{\@spfbreakgap}{%
  \par {%
  \skip@\lastskip
  \nobreak
  \vskip -\ifdim\prevdepth>\maxdepth \maxdepth
          \else\ifdim\prevdepth>-1000pt\prevdepth
            \else\ifinner 0pt
              \else \pagedepth
          \fi \fi \fi
  \vskip -\skip@
  \ifdim\skip@<\pfbreakskip
    \advance\skip@ -1\skip@ \advance\skip@ 1\pfbreakskip
  \fi
  \penalty\pen@ltyabovepfbreak
  \prevdepth\z@ % added
  \vskip\skip@
  \penalty\pen@ltybelowpfbreak
  }
  \@afterindenttrue
  \@afterheading
}

%    \end{macrocode}
% \end{macro}
%
%
%    While on the subject of breaks\ldots
%
% \begin{macro}{\noprelistbreak}
% Putting this immediately before a list (e.g., \Lenv{itemize}) should
% prevent a page break at that point.
% \changes{v1.2}{2002/07/27}{Added \cs{noprelistbreak}}
%    \begin{macrocode}
\newcommand*{\noprelistbreak}{\@nobreaktrue\nopagebreak}

%    \end{macrocode}
% \end{macro}
%
% \subsection{Division head styles}
%
%   The styles of the division heads should go together. As an aid the
% class supplies some ready made collections.
% \changes{v1.6180}{2008/01/30}{Added division head styles}
%
% \begin{macro}{\makeheadstyles}
% \begin{macro}{\headstyles}
% \begin{macro}{\@hds@def@ult}
% \begin{macro}{\hds@default}
% \cs{makeheadstyles}\marg{name}\marg{code} creates the \meta{name} collection 
% of division head styles, defined by \meta{code}. \cs{headstyles}\marg{name}
% makes the \meta{name} division head styles the current styles.
%    \begin{macrocode}
\newcommand{\makeheadstyles}[2]{%
  \@namedef{hds@#1}{\@hds@def@ult #2}}
\newcommand*{\headstyles}[1]{\@nameuse{hds@#1}}
%    \end{macrocode}
% \cs{@hds@def@ult} is the default set of division head styles.
%    \begin{macrocode}
\newcommand*{\@hds@def@ult}{%
% Default \cs{book} style
%    \begin{macrocode}
% book
  \renewcommand*{\beforebookskip}{\null\vfil}%
  \renewcommand*{\midbookskip}{\par\vskip 20pt}%
  \renewcommand*{\afterbookskip}{\vfil\newpage}%
  \renewcommand*{\booknamefont}{\normalfont\huge\bfseries}%
  \renewcommand*{\booknumfont}{\normalfont\huge\bfseries}%
  \renewcommand*{\booktitlefont}{\normalfont\Huge\bfseries}%
  \renewcommand*{\printbookname}{\booknamefont \bookname}%
  \renewcommand*{\booknamenum}{\space}%
  \renewcommand*{\printbooknum}{\booknumfont \thebook}%
  \renewcommand*{\printbooktitle}[1]{\booktitlefont{##1}}%
%    \end{macrocode}
% Default \cs{part} style
%    \begin{macrocode}
% part
  \renewcommand*{\beforepartskip}{\null\vfil}%
  \renewcommand*{\midpartskip}{\par\vskip 20pt}%
  \renewcommand*{\afterpartskip}{\vfil\newpage}%
  \renewcommand*{\partnamefont}{\normalfont\huge\bfseries}%
  \renewcommand*{\partnumfont}{\normalfont\huge\bfseries}%
  \renewcommand*{\parttitlefont}{\normalfont\Huge\bfseries}%
  \renewcommand*{\printpartname}{\partnamefont \partname}%
  \renewcommand*{\partnamenum}{\space}%
  \renewcommand*{\printpartnum}{\partnumfont \thepart}%
  \renewcommand*{\printparttitle}[1]{\parttitlefont{##1}}%
%    \end{macrocode}
% Default \cs{chapter} style.
%    \begin{macrocode}
  \@chs@def@ult%               default chapterstyle
%    \end{macrocode}
% Default \cs{section} style
% \changes{v1.61803398}{2009/07/17}{Added bidi support to default sec headstyle}
%    \begin{macrocode}
% section
  \setsechook{}
  \setsecindent{\z@}%
  \setbeforesecskip{-3.5ex \@plus -1ex \@minus -.2ex}%
  \setaftersecskip{2.3ex \@plus .2ex}%
%%%  \setsecheadstyle{\Large\bfseries\raggedright}%
  \setsecheadstyle{\Large\bfseries\memRTLraggedright}%
%    \end{macrocode}
% Default \cs{subsection} style
% \changes{v1.61803398}{2009/07/17}{Added bidi support to default subsec headstyle}
%    \begin{macrocode}
% subsection
  \setsubsechook{}%
  \setsubsecindent{\z@}%
  \setbeforesubsecskip{-3.25ex \@plus -1ex \@minus -.2ex}%
  \setaftersubsecskip{1.5ex \@plus .2ex}%
%%%  \setsubsecheadstyle{\large\bfseries\raggedright}%
  \setsubsecheadstyle{\large\bfseries\memRTLraggedright}%
%    \end{macrocode}
% Default \cs{subsubsection} style
% \changes{v1.61803398}{2009/07/17}{Added bidi support to default subsubsec headstyle}
%    \begin{macrocode}
% subsubsection
  \setsubsubsechook{}%
  \setsubsubsecindent{\z@}%
  \setbeforesubsubsecskip{-3.25ex \@plus -1ex \@minus -.2ex}%
  \setaftersubsubsecskip{1.5ex \@plus .2ex}%
%%%  \setsubsubsecheadstyle{\normalsize\bfseries\raggedright}%
  \setsubsubsecheadstyle{\normalsize\bfseries\memRTLraggedright}%
%    \end{macrocode}
% Default \cs{paragraph} style
%    \begin{macrocode}
% paragraph
  \setparahook{}%
  \setparaindent{\z@}%
  \setbeforeparaskip{3.25ex \@plus 1ex \@minus .2ex}%
  \setafterparaskip{-1em}%
  \setparaheadstyle{\normalsize\bfseries}%
%    \end{macrocode}
% Default \cs{paragraph} style
%    \begin{macrocode}
% subparagraph
  \setsubparahook{}%
  \setsubparaindent{\parindent}%
  \setbeforesubparaskip{3.25ex \@plus 1ex \@minus .2ex}%
  \setaftersubparaskip{-1em}%
  \setsubparaheadstyle{\normalsize\bfseries}}

%    \end{macrocode}
% Set up and use the default head styles
%    \begin{macrocode}
\makeheadstyles{default}{}
\headstyles{default}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\addperiod}
% Puts a period at the end of its argument.
%    \begin{macrocode}
\newcommand*{\addperiod}[1]{#1.}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hds@memman}
% Head styles used in the \textit{The Memoir Class} user guide. In this,
% as the later ones, only changes from the defaults need specifying.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to the memman headstyles}
%    \begin{macrocode}
\makeheadstyles{memman}{%
% book changes
  \renewcommand*{\booknamefont}{\normalfont\huge\sffamily}
  \renewcommand*{\booknumfont}{\normalfont\huge\sffamily}
  \renewcommand*{\booktitlefont}{\normalfont\Huge\sffamily}
  \renewcommand*{\midbookskip}{\par\vskip 2\onelineskip}%
% part changes
  \renewcommand*{\partnamefont}{\normalfont\huge\sffamily}
  \renewcommand*{\partnumfont}{\normalfont\huge\sffamily}
  \renewcommand*{\parttitlefont}{\normalfont\Huge\sffamily}
  \renewcommand*{\midpartskip}{\par\vskip 2\onelineskip}%
% chapter
  \chapterstyle{demo3}
% section
  \setbeforesecskip{-1.333\onelineskip 
                    \@plus -0.5\onelineskip \@minus -.5\onelineskip}%
  \setaftersecskip{0.667\onelineskip \@plus 0.1\onelineskip}%
%%%  \setsecheadstyle{\normalfont\scshape\raggedright}%
  \setsecheadstyle{\normalfont\scshape\memRTLraggedright}%
% subsection
  \setbeforesubsecskip{-0.667\onelineskip 
                       \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsecskip{0.333\onelineskip \@plus 0.1\onelineskip}%
%%%  \setsubsecheadstyle{\normalfont\bfseries\raggedright}%
  \setsubsecheadstyle{\normalfont\bfseries\memRTLraggedright}%
% subsubsection
  \setbeforesubsubsecskip{-0.667\onelineskip 
                          \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsubsecskip{0.333\onelineskip \@plus 0.1\onelineskip}%
%%%  \setsubsubsecheadstyle{\normalfont\normalsize\itshape\raggedright}%
  \setsubsubsecheadstyle{\normalfont\normalsize\itshape\memRTLraggedright}%
% paragraph
  \setbeforeparaskip{1.0\onelineskip 
                     \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setafterparaskip{-1em}%
  \setparaheadstyle{\normalfont\normalsize\itshape\addperiod}%
% subparagraph
  \setsubparaindent{\parindent}%
  \setbeforesubparaskip{1.0\onelineskip 
                        \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setaftersubparaskip{-1em}%
  \setsubparaheadstyle{\normalfont\normalsize\itshape\addperiod}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hds@bringhurst}
% Head styles based on Bringhurst's book
% \changes{v1.61803398}{2009/07/17}{Added bidi support to bringhurst headstyles}
% \changes{c3.6k}{2012/09/18}{\cs{MakeLowercase} $\to$ \cs{MakeTextLowercase}}
%    \begin{macrocode}
\makeheadstyles{bringhurst}{%
% chapter
\chapterstyle{bringhurst}
% section
  \setbeforesecskip{-1\onelineskip 
                    \@plus -0.5\onelineskip \@minus -.5\onelineskip}%
  \setaftersecskip{1\onelineskip \@plus 0.1\onelineskip}%
%%%  \setsecheadstyle{\normalfont\raggedright\scshape\MakeLowercase}%
  \setsecheadstyle{\normalfont\memRTLraggedright\scshape\MakeTextLowercase}%
% subsection
  \setbeforesubsecskip{-1.0\onelineskip 
                       \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsecskip{1.0\onelineskip \@plus 0.1\onelineskip}%
%%%  \setsubsecheadstyle{\sethangfrom{\noindent ####1}\normalfont\itshape\raggedright}%
  \setsubsecheadstyle{\sethangfrom{\noindent ####1}\normalfont\itshape\memRTLraggedright}%
% subsubsection
  \setbeforesubsubsecskip{1.0\onelineskip 
                          \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setaftersubsubsecskip{-1em}%
  \setsubsubsecheadstyle{\normalfont\normalsize\scshape\MakeTextLowercase}%
% paragraph
  \setbeforeparaskip{1.0\onelineskip 
                     \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setafterparaskip{-1em}%
  \setparaheadstyle{\normalfont\normalsize\itshape\addperiod}%
% subparagraph
  \setsubparaindent{\parindent}%
  \setbeforesubparaskip{1.0\onelineskip 
                        \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setaftersubparaskip{-1em}%
  \setsubparaheadstyle{\normalfont\normalsize\itshape\addperiod}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hds@crosshead}
% Head styles based on one of Bringhurst's suggestions.
% \changes{c3.6k}{2012/09/18}{\cs{MakeUppercase} $\to$ \cs{MakeTextUppercase}}
%    \begin{macrocode}
\makeheadstyles{crosshead}{%
  \chapterstyle{crosshead}
% section
  \setbeforesecskip{-1.25\onelineskip 
                    \@plus -0.5\onelineskip \@minus -.5\onelineskip}%
  \setaftersecskip{0.75\onelineskip \@plus 0.1\onelineskip}%
  \setsecheadstyle{\normalfont\centering\MakeTextUppercase}%
% subsection
  \setbeforesubsecskip{-1.25\onelineskip 
                       \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsecskip{0.75\onelineskip \@plus 0.1\onelineskip}%
  \setsubsecheadstyle{\normalfont\centering\bfseries}%
% subsubsection
  \setbeforesubsubsecskip{-.667\onelineskip 
                          \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsubsecskip{.333\onelineskip \@plus 0.1\onelineskip}%
  \setsubsubsecheadstyle{\normalfont\normalsize\centering\scshape\MakeTextLowercase}%
% paragraph
  \setbeforeparaskip{-.667\onelineskip 
                     \@plus -02.5\onelineskip \@minus -0.25\onelineskip}%
  \setafterparaskip{.333\onelineskip \@plus 0.1\onelineskip}%
  \setparaheadstyle{\normalfont\normalsize\centering\itshape}%
% subparagraph
  \setsubparaindent{\parindent}%
  \setbeforesubparaskip{1.0\onelineskip 
                        \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setaftersubparaskip{-1em}%
  \setsubparaheadstyle{\normalfont\normalsize\scshape\MakeTextLowercase}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hds@dowding}
% Head styles based on Dowding's \textit{Finer Points}.
% \changes{c3.6k}{2012/09/18}{\cs{MakeUppercase} $\to$ \cs{MakeTextUppercase}}
% \changes{c3.6k}{2012/09/18}{\cs{MakeLowercase} $\to$ \cs{MakeTextLowercase}}
%    \begin{macrocode}
\makeheadstyles{dowding}{%
% chapter
  \chapterstyle{dowding}
% section
  \setbeforesecskip{-2\onelineskip 
                    \@plus -0.5\onelineskip \@minus -.5\onelineskip}%
  \setaftersecskip{1\onelineskip \@plus 0.1\onelineskip}%
  \setsecheadstyle{\normalfont\centering\MakeTextUppercase}%
% subsection
  \setbeforesubsecskip{-1.2\onelineskip 
                       \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsecskip{0.8\onelineskip \@plus 0.1\onelineskip}%
  \setsubsecheadstyle{\normalfont\scshape\centering\MakeTextLowercase}%
% subsubsection
  \setbeforesubsubsecskip{-0.667\onelineskip 
                          \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsubsecskip{0.333\onelineskip \@plus 0.1\onelineskip}%
  \setsubsubsecheadstyle{\normalfont\normalsize\centering\itshape}%
% paragraph
  \setbeforeparaskip{1.0\onelineskip 
                     \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setafterparaskip{-1em}%
  \setparaheadstyle{\normalfont\normalsize\itshape\addperiod}%
% subparagraph
  \setsubparaindent{\parindent}%
  \setbeforesubparaskip{1.0\onelineskip 
                        \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setaftersubparaskip{-1em}%
  \setsubparaheadstyle{\normalfont\normalsize\itshape\addperiod}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hds@komalike}
% Head styles based on KOMA script classes (\texttt{scrbook.cls}).
% \changes{v1.61803398}{2009/07/17}{Added bidi support to komalike headstyles}
%    \begin{macrocode}
\makeheadstyles{komalike}{%
% part
  \renewcommand*{\partnamefont}{\huge\sffamily\bfseries}%
  \renewcommand*{\partnumfont}{\huge\sffamily\bfseries}%
  \renewcommand*{\parttitlefont}{\huge\sffamily\bfseries}%
% chapter
  \chapterstyle{komalike}
% section
  \setbeforesecskip{-3.5ex \@plus -1ex \@minus -.2ex}%
  \setaftersecskip{2.3ex \@plus .2ex}%
%%%  \setsecheadstyle{\normalfont\Large\sffamily\bfseries\raggedright}%
  \setsecheadstyle{\normalfont\Large\sffamily\bfseries\memRTLraggedright}%
% subsection
  \setbeforesubsecskip{-3.25ex \@plus -1ex \@minus -.2ex}%
  \setaftersubsecskip{1.5ex \@plus .2ex}%
%%%  \setsubsecheadstyle{\normalfont\large\sffamily\bfseries\raggedright}%
  \setsubsecheadstyle{\normalfont\large\sffamily\bfseries\memRTLraggedright}%
% subsubsection
  \setbeforesubsubsecskip{-3.25ex \@plus -1ex \@minus -.2ex}%
  \setaftersubsubsecskip{1.5ex \@plus .2ex}%
%%%  \setsubsubsecheadstyle{\normalfont\normalsize\sffamily\bfseries\raggedright}%
  \setsubsubsecheadstyle{\normalfont\normalsize\sffamily\bfseries\memRTLraggedright}%
% paragraph
  \setbeforeparaskip{3.25ex \@plus 1ex \@minus .2ex}%
  \setafterparaskip{-1em}%
  \setparaheadstyle{\normalfont\normalsize\sffamily\bfseries}%
% subparagraph
  \setsubparaindent{\parindent}%
  \setbeforesubparaskip{3.25ex \@plus 1ex \@minus .2ex}%
  \setaftersubparaskip{-1em}%
  \setsubparaheadstyle{\normalfont\normalsize\sffamily\bfseries}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hds@ntglike}
% Head styles based on the NTG classes (\texttt{boek.cls}).
% \changes{c3.6k}{2012/09/18}{\cs{MakeUppercase} $\to$ \cs{MakeTextUppercase}}
%    \begin{macrocode}
\makeheadstyles{ntglike}{%
% part
  \renewcommand*{\partnamefont}{\Large\bfseries\MakeTextUppercase}%
  \renewcommand*{\partnumfont}{\Large\bfseries}%
  \renewcommand*{\parttitlefont}{\Large\MakeTextUppercase}%
% chapter
  \chapterstyle{ntglike}
% section
  \setbeforesecskip{-2\onelineskip 
                    \@plus -1\onelineskip \@minus -.5\onelineskip}%
  \setaftersecskip{0.5\onelineskip}%
  \setsecheadstyle{\normalfont\large\bfseries}%
% subsection
  \setbeforesubsecskip{-1\onelineskip 
                       \@plus -.5\onelineskip \@minus -.25\onelineskip}%
  \setaftersubsecskip{0.01\onelineskip}%
  \setsubsecheadstyle{\normalfont\normalsize\bfseries}%
% subsubsection
  \setbeforesubsubsecskip{-1\onelineskip 
                          \@plus -.5\onelineskip \@minus -.25\onelineskip}%
  \setaftersubsubsecskip{0.01\onelineskip}%
  \setsubsubsecheadstyle{\normalfont\normalsize\slshape}%
% paragraph
  \setbeforeparaskip{3.25ex \@plus 1ex \@minus .2ex}%
  \setafterparaskip{-1em}%
  \setparaheadstyle{\normalfont\normalsize\slshape}%
% subparagraph
  \setsubparaindent{\parindent}%
  \setbeforesubparaskip{3.25ex \@plus 1ex \@minus .2ex}%
  \setaftersubparaskip{-1em}%
  \setsubparaheadstyle{\normalfont\normalsize\slshape}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hds@tandh}
% Head styles based on Thames \& Hudson \textit{Typography}.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to tandh headstyles}
% \changes{c3.6k}{2012/09/18}{\cs{MakeUppercase} $\to$ \cs{MakeTextUppercase}}
%    \begin{macrocode}
\makeheadstyles{tandh}{%
% chapter
  \chapterstyle{tandh}
% section
  \setbeforesecskip{-2\onelineskip 
                    \@plus -0.5\onelineskip \@minus -.5\onelineskip}%
  \setaftersecskip{1\onelineskip \@plus 0.1\onelineskip}%
%%%  \setsecheadstyle{\normalfont\raggedright\MakeUppercase}%
  \setsecheadstyle{\normalfont\memRTLraggedright\MakeTextUppercase}%
% subsection
  \setbeforesubsecskip{-1.2\onelineskip 
                       \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsecskip{0.8\onelineskip \@plus 0.1\onelineskip}%
%%%  \setsubsecheadstyle{\normalfont\Large\itshape\raggedright}%
  \setsubsecheadstyle{\normalfont\Large\itshape\memRTLraggedright}%
% subsubsection
  \setbeforesubsubsecskip{-0.667\onelineskip 
                          \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsubsecskip{0.333\onelineskip \@plus 0.1\onelineskip}%
%%%  \setsubsubsecheadstyle{\normalfont\normalsize\bfseries\raggedright}%
  \setsubsubsecheadstyle{\normalfont\normalsize\bfseries\memRTLraggedright}%
% paragraph
  \setbeforeparaskip{1.0\onelineskip 
                     \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setafterparaskip{-1em}%
  \setparaheadstyle{\normalfont\normalsize\itshape\addperiod}%
% subparagraph
  \setsubparaindent{\parindent}%
  \setbeforesubparaskip{1.0\onelineskip 
                        \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setaftersubparaskip{-1em}%
  \setsubparaheadstyle{\normalfont\normalsize\itshape\addperiod}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hds@wilsondob}
% Head styles based on Adrian Wilson's \textit{The Design of Books}.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to wilsondob headstyles}
% \changes{c3.6k}{2012/09/18}{\cs{MakeUppercase} $\to$ \cs{MakeTextUppercase}}
%    \begin{macrocode}
\makeheadstyles{wilsondob}{%
% chapter
  \chapterstyle{wilsondob}
% section
  \setbeforesecskip{-1.333\onelineskip 
                    \@plus -0.5\onelineskip \@minus -.5\onelineskip}%
  \setaftersecskip{0.667\onelineskip \@plus 0.1\onelineskip}%
%%%  \setsecheadstyle{\normalfont\raggedright\MakeUppercase}%
  \setsecheadstyle{\normalfont\memRTLraggedright\MakeTextUppercase}%
% subsection
  \setbeforesubsecskip{-0.667\onelineskip 
                       \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsecskip{0.333\onelineskip \@plus 0.1\onelineskip}%
%%%  \setsubsecheadstyle{\normalfont\Large\itshape\raggedright}%
  \setsubsecheadstyle{\normalfont\Large\itshape\memRTLraggedright}%
% subsubsection
  \setbeforesubsubsecskip{-0.667\onelineskip 
                          \@plus -0.25\onelineskip \@minus -0.25\onelineskip}%
  \setaftersubsubsecskip{0.333\onelineskip \@plus 0.1\onelineskip}%
%%%  \setsubsubsecheadstyle{\normalfont\normalsize\raggedright\scshape\MakeLowercase}%
  \setsubsubsecheadstyle{\normalfont\normalsize\memRTLraggedright\scshape\MakeTextLowercase}%
% paragraph
  \setbeforeparaskip{1.0\onelineskip 
                     \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setafterparaskip{-1em}%
  \setparaheadstyle{\normalfont\normalsize\itshape\addperiod}%
% subparagraph
  \setsubparaindent{\parindent}%
  \setbeforesubparaskip{1.0\onelineskip 
                        \@plus 0.5\onelineskip \@minus 0.2\onelineskip}%
  \setaftersubparaskip{-1em}%
  \setsubparaheadstyle{\normalfont\normalsize\itshape\addperiod}}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Appendices}
%
% \begin{macro}{\ifanappendix}
% \begin{macro}{\anappendixtrue}
% \begin{macro}{\anappendixfalse}
% \begin{macro}{\appendix}
% In the standard \Lpack{book} class the \cs{appendix} command does the 
% following:
%    \begin{itemize}
%    \item Resets the chapter and section counters to zero
%    \item Sets \cs{@chapapp} to \cs{appendixname}.
%    \item Redefines \cs{thechapter} to produce alphabetic appendix numbers.
%    \end{itemize}
% \changes{v1.618}{2005/09/03}{Added \cs{ifanappendix} (mempatch v3.12)}
%    \begin{macrocode}
\newif\ifanappendix
  \anappendixfalse
\newcommand{\appendix}{\par
  \setcounter{chapter}{0}%
  \setcounter{section}{0}%
  \gdef\@chapapp{\appendixname}%
  \gdef\thechapter{\@Alph\c@chapter}%
  \anappendixtrue}

%    \end{macrocode}
% \end{macro}  
% \end{macro}  
% \end{macro}  
% \end{macro}  
%
%
% This class provides additional appendixing capabilities.
%
%
% \begin{macro}{\appendixpage}
% \begin{macro}{\appendixpage*}
% The command to typeset a page announcing the start of the appendices.
% It is based on the \cs{part} definition. The normal version
% makes an entry in the ToC but the starred version does not.
% \changes{v0.33}{2001/08/31}{Changed implementation of \cs{appendixpage}}
%    \begin{macrocode}
\newcommand{\appendixpage}{%
  \@ifstar{\@sapppage}{\@apppage}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memapppageinfo}
% \begin{macro}{\memapppagestarinfo}
% \verb?\memapppageinfo{\appendixpagename}? \\
% \verb?\memapppagestarinfo{\appendixpagename}? \\
%    \begin{macrocode}
\newcommand{\memapppageinfo}[1]{}
\newcommand{\memapppagestarinfo}[1]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@apppage}
% \cs{@apppage} typesets an appendix page and makes an entry in the ToC.
% \changes{v3.6k}{2013/04/25}{Added \cs{mempre/postaddchaptertotochook}}
%    \begin{macrocode}
\def\@apppage{%
  \@setuppart
  \mempreaddapppagetotochook
  \addappheadtotoc
  \mempostaddapppagetotochook
  \partmark{\appendixpagename}%
  \memapppageinfo{\appendixpagename}%
  {\centering
   \interlinepenalty \@M
   \normalfont
   \printparttitle{\appendixpagename}\par}%
  \@endpart}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\mempreaddapppagetotochook}
% \begin{macro}{\mempostaddapppagetotochook}
%   Hooks before and after adding something to the ToC. Does nothing
%   by default.
%    \begin{macrocode}
\newcommand\mempreaddapppagetotochook{}
\newcommand\mempostaddapppagetotochook{}

%    \end{macrocode}
%   
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@sapppage}
% \cs{@sapppage} typesets an appendix page and does not make an entry in the ToC.
%    \begin{macrocode}
\def\@sapppage{%
  \@setuppart
  \partmark{\appendixpagename}%
  \memapppagestarinfo{\appendixpagename}%
  {\centering
   \interlinepenalty \@M
   \normalfont
   \printparttitle{\appendixpagename}\par}%
  \@endpart}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\addappheadtotoc}
% This command adds an `appendices' line to the ToC. The style is the same
% as used in \Lpack{tocbibind} for the `List of figures' line. That is,
% as a Chapter heading.
% \changes{v1.61803}{2008/01/30}{Added \cs{phantomsection} to \cs{addappheadtotoc}
%                    (mempatch v4.9)}
%    \begin{macrocode}
\def\addappheadtotoc{%
  \phantomsection\addcontentsline{toc}{chapter}{\appendixtocname}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@ppsavesec}
% \begin{macro}{\@pprestoresec}
% \begin{macro}{\@ppsaveapp}
% \begin{macro}{\restoreapp}
%  For the \Lenv{appendices} environment we need to save and restore the
% main document division number and the appendix number. The \cs{restoreapp}
% command is the one for the user.
%    \begin{macrocode}
\newcounter{@ppsavesec}
\newcounter{@ppsaveapp}
\setcounter{@ppsaveapp}{0}
\newcommand{\@ppsavesec}{%
  \setcounter{@ppsavesec}{\value{chapter}}}
\newcommand{\@pprestoresec}{%
  \setcounter{chapter}{\value{@ppsavesec}}}
\newcommand{\@ppsaveapp}{%
  \setcounter{@ppsaveapp}{\value{chapter}}}
\newcommand{\restoreapp}{%
  \setcounter{chapter}{\value{@ppsaveapp}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@resets@pp}
% Resets the appropriate sectioning counters and names. This does almost
% exactly
% what the default \cs{appendix} command does, except that it saves and 
% restores sectional numbering. It saves the sectional number at the start
% and restores the appendix number at the end.
%    \begin{macrocode}
\newcommand{\@resets@pp}{%
  \par
  \@ppsavesec
  \setcounter{section}{0}%
  \setcounter{chapter}{0}%
  \renewcommand\@chapapp{\appendixname}%
  \renewcommand\thechapter{\@Alph\c@chapter}%
  \restoreapp
}

%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{appendices}
%  This is the heart of the package. Start it off by doing the resetting
% done by the \cs{appendix} command but also save the main counters. At the
% end of the environment save the appendix number and restore the main counters.
%    \begin{macrocode}
\newenvironment{appendices}%
  {\@resets@pp\anappendixtrue}%
  {\@ppsaveapp\@pprestoresec\anappendixfalse}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\setthesection}
% The user commands for specifying the numbering style for subappendices.
%    \begin{macrocode}
\newcommand{\setthesection}{\thechapter.\Alph{section}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@resets@ppsub}
% Similar to \cs{@resets@pp} except that it is for use within the 
% \Lenv{subappendices} environment; as such, it is a bit simpler.
%    \begin{macrocode}
\newcommand{\@resets@ppsub}{
  \par
  \setcounter{section}{0}
  \renewcommand{\thesection}{\setthesection}
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifnamesubappendix}
% \begin{macro}{\namesubappendixtrue}
% \begin{macro}{\namesubappendixfalse}
% \begin{macro}{\namedsubappendices}
% \begin{macro}{\unnamedsubappendices}
% Switch for adding an `appendix' name before subappendix numbers.
% \changes{v1.0}{2001/11/13}{Added \cs{ifnamesubappendix}}
% \changes{v1.61803}{2008/01/30}{Added \cs{namedsubappendices} and
%                                \cs{unnamedsubappendices}}
%    \begin{macrocode}
\newif\ifnamesubappendix
  \namesubappendixfalse
\newcommand*{\namedsubappendices}{\namesubappendixtrue}
\newcommand*{\unnamedsubappendices}{\namesubappendixfalse}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{environment}{subappendices}
%  The environment for subappendices. Start it off by doing the resetting
% of the \cs{section} command. 
% \changes{v1.0}{2001/11/13}{Modified subappendices environment}
%    \begin{macrocode}
\newenvironment{subappendices}{%
  \@resets@ppsub
%    \end{macrocode}
% Change the definition of \cs{addappheadtotoc} to give a \texttt{section} entry.
% \changes{v1.618}{2005/09/02}{Fixed bookmark for \cs{appendixpage} (mempatch v2.3)}
%    \begin{macrocode}
  \def\addappheadtotoc{\phantomsection
    \addcontentsline{toc}{section}{\appendixtocname}}
%    \end{macrocode}
% To implement the naming we do cunning things with the
% \cs{@seccntformat} command.
%    \begin{macrocode}
  \ifnamesubappendix
    \def\sectionname{\appendixname}
    \def\@seccntformat##1{\@ifundefined{##1name}%
                         {}{\csname ##1name\endcsname\ }%
        \csname the##1\endcsname\quad}
  \fi
%    \end{macrocode}
% That's it.
%    \begin{macrocode}
  }{}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\@formatsecmark@pp}
% Formats the page header for a redefined \cs{sectionmark}.
%    \begin{macrocode}
% unused?
% \newcommand{\@formatsecmark@pp}[1]{%
%   \MakeUppercase{\appendixname\space
%     \ifnum \c@secnumdepth >\z@
%       \thesection\quad
%     \fi
%     #1}}
%    \end{macrocode}
% \end{macro}
%
% \subsection{Appendixpage-like pages}
% \changes{v1.618}{2005/09/03}{Added \cs{newleadpage} and friends (mempatch v3.0)}
%
%
% This capability was suggested to me by Lars Madsen on 2004/11/28.
%
% \begin{macro}{\leadpagetoclevel}
% \begin{macro}{\newleadpage}
% \begin{macro}{\renewleadpage}
% \verb?\newleadpage[<page-style>]{<cmdname>}{<title>}? creates new macros 
% called \verb?\cmdname? and \verb?\cmdname*? that when called typeset a 
% page like an  Appendixpage, with a title \verb?<title>? using
% page style \verb?<page-style>? (default empty). The
% plain version adds an entry to the ToC but the starred \verb?\cmdname*? 
% does not. \cs{renewleadpage} changes the definitions.
%
%    The ToC entry style is set by \cs{leadpagetoclevel} (default chapter). To have a part-type entry: \\
% \verb?\renewcommand*{\leadpagetoclevel}{part}?. \\
% The \cs{partmark} command is used if you need to mark the title.
%    \begin{macrocode}
\newcommand*{\leadpagetoclevel}{chapter}
\newcommand*{\newleadpage}[3][empty]{%
  \@namedef{#2}{\@ifstar{\dlfm@msapppage{#1}{#2}{#3}}%
                        {\dlfm@mapppage{#1}{#2}{#3}}}}
\newcommand*{\renewleadpage}[3][empty]{%
  \@namedef{#2}{\@ifstar{\dlfm@msapppage{#1}{#2}{#3}}%
                        {\dlfm@mapppage{#1}{#2}{#3}}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memleadpageinfo}
% \begin{macro}{\memleadpagestarinfo}
% \verb?\memleadpageinfo{pstyle}{name}{title}? \\
% \verb?\memleadpagestarinfo{pstyle}{name}{title}? \\
%    \begin{macrocode}
\newcommand{\memleadpageinfo}[3]{}
\newcommand{\memleadpagestarinfo}[3]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\dlfm@msapppage}
% \begin{macro}{\dlfm@mapppage}
% Implement the starred and regular versions of \verb?\(re)newleadpage?
%    \begin{macrocode}
\newcommand*{\dlfm@msapppage}[3]{%
  \@setuppart
  \partmark{#3}%
  \memleadpagestarinfo{#1}{#2}{#3}%
  {\centering
  \interlinepenalty \@M
  \normalfont
  \printparttitle{#3}\par
  \thispagestyle{#1}}%
  \dlfm@m@endpart{#1}}
\newcommand*{\dlfm@mapppage}[3]{%
  \@setuppart
  \phantomsection
  \addcontentsline{toc}{\leadpagetoclevel}{#3}%
  \partmark{#3}%
  \memleadpageinfo{#1}{#2}{#3}%
  {\centering
  \interlinepenalty \@M
  \normalfont
  \printparttitle{#3}\par
  \thispagestyle{#1}}%
  \dlfm@m@endpart{#1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\dlfm@m@endpart}
% Finishes off a part-like page.
%    \begin{macrocode}
\newcommand*{\dlfm@m@endpart}[1]{%
  \if@twoside
    \if@openright
      \null
      \thispagestyle{#1}%
      \newpage
    \fi
  \fi
  \if@tempswa
    \twocolumn
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \subsection{Paragraphs}
%
% Much of the code in this section is taken from my \textit{Glisterings} 
% columns~\cite{GLISTER07,GLISTER08}.
% \changes{v1.6180339c}{2009/01/09}{Added several new paragraph types}
%
% \begin{macro}{\memorigdbs}
% \begin{macro}{\memorigpar}
% \begin{macro}{\atcentercr}
% \cs{memorigdbs} saves the original definition of \verb?\\? and 
% \cs{memorigpar} saves the original \cs{par}. The macro \cs{atcentercr}
% provides a user call to \cs{@centercr}. These could come in handy for
% odd paragraph shapes.
% \changes{v1.6180339c}{2009/01/09}{Added \cs{memorigdbs} and 
%          \cs{memorigpar} \cs{atcentercr}}
%    \begin{macrocode}
\let\memorigdbs\\
\let\memorigpar\par
\let\atcentercr\@centercr

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsubsection{Normal (block) paragraphs}
%
%
% \begin{macro}{\flushleftright}
%  Sets the paragraphing to \LaTeX's normal form.
% \changes{v1.61803}{2008/01/30}{Used \cs{@flushglue} in \cs{flushleftright} and
%          \cs{centerlastline} (mempatch v4.7)}
% \changes{v1.6180339c}{2009/01/09}{Extended \cs{flushleftright} to set all
%          the regular paragraphing controls}
%    \begin{macrocode}
\newcommand*{\flushleftright}{%
  \let\\\memorigdbs
  \leftskip\z@skip 
  \rightskip\leftskip
  \parfillskip\@flushglue
  \everypar{}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\linenottooshort}
% This declaration \cs{linenottooshort}\oarg{length} specifies paragraphs
% such that the last line is at least about \meta{length} long (the default
% is 4em).
% \changes{v1.6180339c}{2009/01/09}{Added \cs{linenottooshort} paragraph}
%    \begin{macrocode}
\newcommand*{\linenottooshort}[1][4em]{%
  \@tempdima=\hsize
  \advance\@tempdima -#1
  \leftskip\z@skip
  \rightskip\leftskip
  \parfillskip=\@tempdima \@minus \@tempdima}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\russianpar}
% Using \cs{russianpar} instead of \cs{par} to end a paragraph causes it
% to be set according to Russian typography, where the last line of a 
% multiline paragraph must be either at least as
% long as \cs{parindent} and have at least \cs{parindent} space at the
% right, or it must be flushleft and flushright.
% \changes{v1.6180339c}{2009/01/09}{Added \cs{russianpar} paragraph}
%    \begin{macrocode}
\newcommand*{\russianpar}{\ifhmode\unskip
  \strut\vadjust{}\nobreak
  \discretionary{}%
  {\hbox{\hskip2\parindent
         \vrule depth 273sp width 0sp height \ht\strutbox}}%
  {\hbox{\hskip\parindent}}%
  \hskip-2\parindent \@minus 2\parindent
  \hskip\hsize \@minus \hsize
  \kern\z@ \parfillskip\z@
  \memorigpar
  \ifdim\prevdepth=273sp
    \nobreak
    \vskip-2\baselineskip
    \hbox{\strut}%
  \fi\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\lastlineparrule}
% \begin{macro}{\lastlinerulefill}
% Using \cs{lastlinerulefill} instead of \cs{par} to end a paragraph
% causes all short lines to be filled at the right by a rule 
% (\cs{lastlineparrule}) extending to the righthand margin.
% \changes{v1.6180339c}{2009/01/09}{Added \cs{lastlineparrule} and 
%          \cs{lastlinerulefill} paragraph}
%    \begin{macrocode}
\newcommand*{\lastlineparrule}{%
  \hrule height 0.5ex depth \@tempdimb\relax}
\newcommand*{\lastlinerulefill}{%
  \let\\\@centercr
  \@tempdimb=-0.5ex \advance\@tempdimb 0.4pt
  \unskip\nobreak\space
  \leaders\lastlineparrule\hskip\@flushglue
  \vadjust{}{\parfillskip\z@\memorigpar}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \subsubsection{Centered lines}
%
% \begin{macro}{\centerlastline}
% This declaration specifies normal paragraphs except that the last line of
% each is centered.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{centerlastline}}
%    \begin{macrocode}
\newcommand*{\centerlastline}{%
%%%  \leftskip\@flushglue
  \memRTLleftskip\@flushglue
%%%  \rightskip=\z@ plus -1fil
  \memRTLrightskip=\z@ plus -1fil
  \parfillskip=\z@ plus 2fil}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\leftcenterright}
% This declaration specifies paragraphs where the first line is flushleft 
% (raggedright), the
% last is flushright (raggedleft) and all inbetween are centered.
% Set \verb?\everypar{}? afterwards.
% \changes{v1.6180339c}{2009/01/09}{Added \cs{leftcenterright} paragraph}
%    \begin{macrocode}
\newcommand*{\leftcenterright}{%;
  \let\\\break
  \parindent\z@
  \leftskip\@flushglue
  \rightskip\leftskip
  \parfillskip \z@ \@plus -1fil
  \everypar={\hskip \z@ \@plus -1fil}}

%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\centerfloat}
% This is a version of \cs{centering} that can be used to center a wide
% float with respect to the text block (normally the left of a wide float
% is aligned with the left of the textblock). This can only be used for
% centering something where LaTeX knows the width (e.g., a figure or a 
% table / tabular). 
%    
%  This is a modified version of code by Robin Fairbairns 
% (CTT, \textit{Re: Centering a table: problem with rotating.sty, maybe
% a strange document class?}, 3 Jan 2009).
% \changes{v1.6180339c}{2009/01/11}{Added \cs{centerfloat}}
%    \begin{macrocode}
\newcommand*{\centerfloat}{%
  \parindent \z@
  \leftskip \z@ \@plus 1fil \@minus \textwidth
  \rightskip\leftskip
  \parfillskip \z@skip}

%    \end{macrocode}
% \end{macro}
%
% \subsubsection{Ragged}
%
% The kernel code for raggedright (in \file{ltmiscen.dtx}):
% \begin{verbatim}
% \def\raggedright{%
%   \let\\\@centercr\@rightskip\@flushglue \rightskip\@rightskip
%   \leftskip\z@skip
%   \parindent\z@}
% %% \@flushglue = 0pt plus 1fil      %% from ltalloc.dtx
% %% \z@skip = 0pt plus 0pt minus 0pt %%
% \end{verbatim}
% produces very ragged text with no paragraph indent. 
%
% \begin{macro}{\ragrparindent}
% \begin{macro}{\raggedyright}
% \cs{raggedyright}\oarg{plus} provides controllable ragged right paragraphs.
% \changes{v1.4}{2003/12/10}{Added \cs{raggedyright}}
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{raggedyright}}
%    \begin{macrocode}
\newdimen\ragrparindent
  \setlength{\ragrparindent}{\parindent}
\newcommand{\raggedyright}[1][2em]{%
  \let\\\@centercr\@rightskip \z@ \@plus #1\relax 
%%%  \rightskip\@rightskip
  \memRTLrightskip\@rightskip
%%%  \leftskip\z@skip
  \memRTLleftskip\z@skip
  \parindent\ragrparindent}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\justlastraggedleft}
% This declaration specifies paragraphs where the lines are justified, 
% except for the last which is raggedleft (flushright)..
% \changes{v1.6180339c}{2009/01/09}{Added \cs{justlastraggedleft} paragraph}
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{justlastraggedleft}}
%    \begin{macrocode}
\newcommand*{\justlastraggedleft}{%
%%%  \leftskip\@flushglue
  \memRTLleftskip\@flushglue
%%%  \rightskip-\leftskip
  \memRTLrightskip-\memRTLleftskip
  \parfillskip\leftskip
  \parindent \z@}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\raggedrightthenleft}
% This declaration specifies paragraphs where the first line is raggedright
% (flushleft) and all the rest are raggedleft (flushright). Note that
% this alters \cs{everpar}, which may need to be reset afterwards to
% \verb?\everypar{}?.
% \changes{v1.6180339c}{2009/01/09}{Added \cs{raggedrightthenleft} paragraph}
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{raggedrightthenleft}}
%    \begin{macrocode}
\newcommand*{\raggedrightthenleft}{%
  \parindent \z@
%%%  \leftskip \z@ \@plus 1fill
  \memRTLleftskip \z@ \@plus 1fill
%%%  \rightskip\@flushglue
  \memRTLrightskip\@flushglue
  \parfillskip \z@
  \everypar{\hskip \z@ \@plus -1fill}}

%    \end{macrocode}
% \end{macro}
%
%
% \subsubsection{Hanging}
%
% \begin{macro}{\hangfrom}
% This is a user-level
% version of the kernel \cs{@hangfrom} macro (only the name is
% changed) as defined in \file{ltsec.dtx}.
%
% \cs{hangfrom}\marg{text} puts \meta{text} in a box and makes a hanging
% paragraph of the following material (a bit like a description item).
% \changes{v1.4}{2003/11/22}{Added \cs{hangfrom} (from patch v1.9)}
%    \begin{macrocode}
\newcommand{\hangfrom}[1]{%
  \setbox\@tempboxa\hbox{{#1}}%
  \hangindent \wd\@tempboxa\noindent\box\@tempboxa}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hangpara}
% \cs{hangpara}\marg{indent}\marg{afternum} at the start of a 
% paragraph will make it hung. If \meta{indent} is positive the left
% will be indented, otherwise the right. If \meta{afternum}, say N,
% is positive the N+1 th lines onwards will be indented. For N negative,
% the first N lines will be indented.
%    \begin{macrocode}
\newcommand{\hangpara}[2]{\hangindent#1\hangafter#2\noindent}
%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{hangparas}
% \verb?\begin{hangparas}?\marg{indent}\marg{afternum} hangs 
% a series of paragraphs.
%    \begin{macrocode}
\newenvironment{hangparas}[2]{\setlength{\parindent}{\z@}
  \everypar={\hangpara{#1}{#2}}}{\par}

%    \end{macrocode}
% \end{environment}
%
% \subsubsection{Miscellaneous}
%
% \begin{macro}{\leftspringright}
% \cs{leftspringright}\marg{leftfrac}\marg{rightfrac}\marg{lefttext}\marg{righttext}
% sets the \meta{lefttext} flushleft (raggedright) in a column \meta{leftfrac} 
% of the current textwidth and the \meta{righttext} flushright (raggedleft) 
% in a column \meta{rightfrac} of the textwidth, with space 
% (1.0 - \meta{leftfrac} - \meta{rightfrac})
% of the textwidth between them. Both \meta{leftfrac} and \meta{rightfrac}
% must be given as decimal numbers (e.g., \texttt{0.25} not \texttt{1/4}).
% \changes{v1.6180339c}{2009/01/09}{Added \cs{leftspringright} paragraph}
%    \begin{macrocode}
\newcommand{\leftspringright}[4]{%
  \@tempdimb=\hsize
  \par\noindent\hbox to\@tempdimb{%
    \vtop{\hsize=#1\@tempdimb \flushleft#3\par}\hss
    \vtop{\hsize=#2\@tempdimb \flushright#4\par}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sourceatright}
% Putting \cs{sourceatright}\oarg{length}\marg{text} at the end of a 
% paragraph will set \meta{text} flushright on the same line provided the line
% is short enough to allow \meta{length} (default 2em) between the end of the
% line and \meta{text}. If there is not enough space then \meta{text} is
% set flushright on the following line.
% \changes{v1.6180339c}{2009/01/09}{Added \cs{sourceatright} paragraph}
%    \begin{macrocode}
\newcommand*{\sourceatright}[2][2em]{{%
  \unskip\nobreak\hfil\penalty50
  \hskip#1\hbox{}\nobreak\hfil{#2}
  \parfillskip\z@\finalhyphendemerits=0\par}}

%    \end{macrocode}
% \end{macro}
%
%
% \section{Lists}
%
% \subsection{General List Parameters}
%
% The following commands are used to set the default values for the list
% environment's parameters. See the \LaTeX{} manual for an explanation
% of the meanings of the parameters.  Defaults for the list
% environment are set as follows.  First, \cs{rightmargin},
% \cs{listparindent} and \cs{itemindent} are set to 0pt.  Then, for a Kth
% level list, the command \cs{@listK} is called, where `K' denotes `i',
% '`i', ... , `vi'.  (I.e., \cs{@listiii} is called for a third-level
% list.)  By convention, \cs{@listK} should set \cs{leftmargin} to
% \cs{leftmarginK}.
%
%
% \begin{macro}{\leftmargin}
% \begin{macro}{\leftmargini}
% \begin{macro}{\leftmarginii}
% \begin{macro}{\leftmarginiii}
% \begin{macro}{\leftmarginiv}
% \begin{macro}{\leftmarginv}
% \begin{macro}{\leftmarginvi}
% For efficiency, level-one list's values are defined at top level, and
% \cs{@listi} is defined to set only \cs{leftmargin}.
%
% In two column mode the margins should be smaller than in one column typesetting.
%    \begin{macrocode}
\if@twocolumn
  \setlength{\leftmargini}{2em}
\else
  \setlength{\leftmargini}{2.5em}
\fi
%    \end{macrocode}
%    The value of \cs{leftmargin} has to be set at this outer level.
%    \begin{macrocode}
\leftmargin \leftmargini
%    \end{macrocode}
%    Lower level list margins are calculated so that they are indented
% more than the label in an outer list.
%    \begin{macrocode}
\setlength{\leftmarginii}{2.2em}
\setlength{\leftmarginiii}{1.87em}
\setlength{\leftmarginiv}{1.7em}
\if@twocolumn
  \setlength{\leftmarginv}{.5em}
  \setlength{\leftmarginvi}{.5em}
\else
  \setlength{\leftmarginv}{1em}
  \setlength{\leftmarginvi}{1em}
\fi
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\itemindent}
%    Here we set the \cs{itemindent} which is the extra indentation before
%    a label.
%    \begin{macrocode}
\setlength{\itemindent}{\z@}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\labelsep}
% \begin{macro}{\labelwidth}
%    \cs{labelsep} is the distance between the label and the text of an
%    item; \cs{labelwidth} is the width of the label.
%    \begin{macrocode}
\setlength{\labelsep}{0.5em}
\setlength{\labelwidth}{\leftmargini}
  \addtolength{\labelwidth}{-\labelsep}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@beginparpenalty}
% \begin{macro}{\@endparpenalty}
%    These penalties are inserted before and after a list or paragraph
%    environment. They are set to a bonus value to encourage page
%    breaking at these points.
% \begin{macro}{\@itempenalty}
%    This penalty is inserted between list items.
%    \begin{macrocode}
\@beginparpenalty -\@lowpenalty
\@endparpenalty   -\@lowpenalty
\@itempenalty     -\@lowpenalty

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% \begin{macro}{\everylistparindent}
% \begin{macro}{\list}
% The kernel sets \cs{listparindent} to zero within a \cs{list}, where it
% can be overridden in \cs{list}'s second argument. Here it is set to
% \cs{everyparlistindent} by default, which in turn is 0pt.
%    \begin{macrocode}
\newdimen\everylistparindent
  \everylistparindent \z@
\renewcommand*{\list}[2]{%
  \ifnum \@listdepth >5\relax
    \@toodeep
  \else
    \global\advance\@listdepth\@ne
  \fi
  \rightmargin\z@
  \listparindent\everylistparindent
  \itemindent\z@
  \csname @list\romannumeral\the\@listdepth\endcsname
  \def\@itemlabel{#1}%
  \let\makelabel\@mklab
  \@nmbrlistfalse
  #2\relax
  \@trivlist
  \parskip\parsep
  \parindent\listparindent
  \advance\linewidth -\rightmargin
  \advance\linewidth -\leftmargin
  \advance\@totalleftmargin \leftmargin
  \parshape \@ne \@totalleftmargin \linewidth
  \ignorespaces}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\parsepi}
% \begin{macro}{\topsepi}
% \begin{macro}{\itemsepi}
% \begin{macro}{\parsepii}
% \begin{macro}{\topsepii}
% \begin{macro}{\topsepiii}
% Lists may be nested and the exact layout depends on the level
% of nesting. These lengths are used to control the nesting-level
% aspects.
%    \begin{macrocode}
\newlength{\parsepi}
\newlength{\topsepi}
\newlength{\itemsepi}
\newlength{\parsepii}
\newlength{\topsepii}
\newlength{\topsepiii}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\itemsepii}
% \begin{macro}{\itemsepiii}
% \begin{macro}{\partopsepii}
% \begin{macro}{\partopsepii}
% We need some new lengths for lists to cater for non-zero \cs{parskip}.
% \changes{v1.61803}{2008/01/30}{Added \cs{itemsepii}, \cs{itemsepiii} and
%            \cs{partopsepii} (mempatch v4.6)}
%    \begin{macrocode}
\newlength{\itemsepii}
\newlength{\itemsepiii}
\newlength{\partopsepii}
\newlength{\partopsepiii}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setnzplist}
% Common code for non-zero \cs{parskip} in lists.
%    \begin{macrocode}
\newcommand*{\setnzplist}{%
  \partopsep \p@ \@plus\z@ \@minus\p@
  \topsepi\z@
  \parsepi\parskip
  \itemsepi\z@
  \topsepii\z@
  \parsepii\parskip
  \itemsepii\z@
  \topsepiii\z@
%%    \parsepiii\parskip
  \itemsepiii\z@}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\defaultlists}
% The standard \LaTeX\ classes have list parameters that give some
% separation between lists and \cs{item}s in lists. This macro sets
% those values. This is a simplification of memoir's original, and will 
% apply to any font size.
% \changes{v1.61803}{2008/01/30}{Complete replacement of \cs{defaultlists}
%                  (mempatch 4.5)}
%    \begin{macrocode}
\newcommand*{\defaultlists}{%
  \setlength{\partopsep}{0.2\onelineskip \@plus 0.1\onelineskip 
                                         \@minus 0.1\onelineskip}%
  \parsepi = 0.3333\onelineskip \@plus 0.1667\onelineskip \@minus \p@
  \itemsepi = \parsepi
  \topsepi = 0.6667\onelineskip \@plus 0.3333\onelineskip 
                                \@minus 0.2\onelineskip
  \parsepii = 0.1667\onelineskip \@plus \p@ \@minus \p@
  \topsepii = \parsepi
  \topsepiii = \parsepii
  \everylistparindent \listparindent
%    \end{macrocode}
% Additional code to cater for non-zero \cs{parskip}s.
% \changes{v1.61803}{2008/01/30}{Modified \cs{defaultlists} for
%                    non-zero \cs{parskip} (memptach v4.6)}
%    \begin{macrocode}
  \itemsepii\parsepii
  \itemsepiii\topsepiii
  \partopsepiii \p@ \@plus\z@ \@minus\p@
  \ifm@mnzpskip
    \setnzplist
  \fi}
\defaultlists

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\firmlists}
% \begin{macro}{\firmlists*}
% \begin{macro}{\m@msfirmlists}
% \begin{macro}{\m@mfirmlists}
% These give approximately half the vertical spacing of the default lists, 
% with all spaces equal. The starred version allows slightly less space
% before and after the list when it is preceded by a blank line.
% \changes{v1.61803}{2008/01/30}{Added \cs{firmlists}, etc. (mempatch v4.5)}
%    \begin{macrocode}
\newcommand*{\firmlists}{%
  \@ifstar{\m@msfirmlists}{\m@mfirmlists}}

\newcommand*{\m@msfirmlists}{
  \setlength{\partopsep}{\z@ \@plus \p@ \@minus \p@}%
  \parsepi = 0.1667\onelineskip \@plus 0.0833\onelineskip \@minus \p@
  \itemsepi = \parsepi
  \topsepi = \parsepi
  \parsepii = 0.0833\onelineskip \@plus \p@ \@minus \p@
  \topsepii = \parsepi
  \topsepiii = \parsepii
  \everylistparindent\listparindent}

\newcommand*{\m@mfirmlists}{
  \setlength{\partopsep}{0.1\onelineskip \@plus 0.05\onelineskip 
                                         \@minus 0.05\onelineskip}%
  \parsepi = 0.1667\onelineskip \@plus 0.0833\onelineskip \@minus \p@
  \itemsepi = \parsepi
  \topsepi = \parsepi
  \parsepii = 0.0833\onelineskip \@plus \p@ \@minus \p@
  \topsepii = \parsepi
  \topsepiii = \parsepii
  \everylistparindent\listparindent}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\tightlists}
% \begin{macro}{\tightlists*}
% \begin{macro}{\m@mstightlists}
% \begin{macro}{\m@mtightlists}
% This macro sets the parameters for lists that have less open vertical
% space in them. I think that these look neater than the defaults.
% Effectively, no additional vertical space is added. 
% The starred version allows slightly no extra space
% before and after the list when it is preceded by a blank line,
% whereas the unstarred version puts half a \cs{onelineskip}
% before \emph{and} after.
% \changes{v1.61803}{2008/01/30}{Revised \cs{tightlists}, etc. (mempatch v4.5)}
% \changes{v1.61803}{2008/01/30}{Revised \cs{tightlists} for non-zero
%          \cs{parskip}(mempatch v4.6)}
%    \begin{macrocode}
\newcommand*{\tightlists}{%
  \@ifstar{\m@mstightlists}{\m@mtightlists}}

\newcommand*{\m@mstightlists}{%
  \setlength{\partopsep}{\z@ \@plus \p@ \@minus \p@}%
  \parsepi = \z@ \@plus \p@ \@minus \p@
  \itemsepi = \parsepi
  \topsepi = \z@ \@plus \p@ \@minus \p@
  \parsepii = \z@ \@plus \p@ \@minus \p@
  \topsepii = \parsepi
  \topsepiii = \parsepii
  \everylistparindent\parindent
  \ifm@mnzpskip
    \setnzplist
    \partopsepiii\partopsep
  \fi}

\newcommand*{\m@mtightlists}{%
  \setlength{\partopsep}{0.5\onelineskip \@plus \p@ \@minus \p@}%
  \parsepi = \z@ \@plus \p@ \@minus \p@
  \itemsepi = \parsepi
  \topsepi = \z@ \@plus \p@ \@minus \p@
  \parsepii = \z@ \@plus \p@ \@minus \p@
  \topsepii = \parsepi
  \topsepiii = \parsepii
  \everylistparindent\parindent
  \ifm@mnzpskip
    \setnzplist
    \partopsepiii\partopsep
  \fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\firmlist}
% \begin{macro}{\tightlist}
% These two macros can be used at the start of a list environment to
% reduce the vertical gaps. \cs{tightlist} removes all interior spaces
% while \cs{firmlist} only removes some.
% \changes{v0.3}{2001/07/09}{Added \cs{firmlist} and reimplemented the
% original \cs{tightlist}}
%    \begin{macrocode}
\newcommand{\firmlist}{%
  \setlength{\itemsep}{0.5\itemsep}\setlength{\parskip}{0.5\parskip}}
\newcommand{\tightlist}{%
  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%    The space before and after a \Lenv{trivlist} environment is controlled
% by the \cs{topsep} and \cs{partopsep} skips. There are several environments,
% such as \Lenv{center}, that are defined as a \Lenv{trivlist}.
% 
% \begin{macro}{\m@msavetopsep}
% \begin{macro}{\m@msavepartopsep}
% \begin{macro}{\savetrivseps}
% \begin{macro}{\restoretrivseps}
% Two skips to store the \cs{topsep} and \cs{partopsep} values and a means
% of setting them and restoring them.
% \changes{v1.6}{2004/01/28}{Added methods for adjusting the space around
%                            a trivlist}
%    \begin{macrocode}
\newskip\m@msavetopsep
\newskip\m@msavepartopsep
\newcommand*{\savetrivseps}{%
  \m@msavetopsep\topsep
  \m@msavepartopsep\partopsep}
\newcommand*{\restoretrivseps}{%
  \topsep\m@msavetopsep
  \partopsep\m@msavepartopsep}
%    \end{macrocode}
% Save the initial \cs{topsep} and \cs{partopsep} values.
%    \begin{macrocode}
\savetrivseps

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\zerotrivseps}
%  A macro to zero \cs{topsep} and \cs{partopsep}.
%    \begin{macrocode}
\newcommand*{\zerotrivseps}{%
  \topsep\z@
  \partopsep\z@}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\@listI}
% \begin{macro}{\@listi}
% \cs{@listI} defines top level and \cs{@listi} values of
% \cs{leftmargin}, \cs{parsep}, \cs{topsep}, and \cs{itemsep}
%
%    \begin{macrocode}
\def\@listi{\leftmargin\leftmargini
  \parsep\parsepi
  \topsep\topsepi
  \itemsep\itemsepi}
\let\@listI\@listi
%    \end{macrocode}
%    We should initialise these parameters to the standard defaults
%    \begin{macrocode}
\defaultlists
\@listi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@listii}
% \begin{macro}{\@listiii}
% \begin{macro}{\@listiv}
% \begin{macro}{\@listv}
% \begin{macro}{\@listvi}
%    Here are the same macros for the lower level lists.
%    \begin{macrocode}
\def\@listii{\leftmargin\leftmarginii
             \labelwidth\leftmarginii
             \advance\labelwidth-\labelsep
             \topsep\topsepii
             \parsep\parsepii
%    \end{macrocode}
% \changes{v3.7g}{2016/11/22}{Typo: \cs{itemsep} should here point at
% \cs{itemsepii}, reported by Thomas Koeppe, private email}
%    \begin{macrocode}
             \itemsep\itemsepii}

\def\@listiii{\leftmargin\leftmarginiii
              \labelwidth\leftmarginiii
              \advance\labelwidth-\labelsep
              \topsep\topsepiii
              \parsep\z@
%%%              \itemsep\topsep
%%%              \partopsep \p@ \@plus\z@ \@minus\p@
              \itemsep\itemsepiii
              \partopsep\partopsepiii}

\def\@listiv{\leftmargin\leftmarginiv
             \labelwidth\leftmarginiv
             \advance\labelwidth-\labelsep}

\def\@listv{\leftmargin\leftmarginv
            \labelwidth\leftmarginv
            \advance\labelwidth-\labelsep}

\def\@listvi{\leftmargin\leftmarginvi
             \labelwidth\leftmarginvi
             \advance\labelwidth-\labelsep}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \subsection{Enumerate}
%
%
%    The enumerate environment uses four counters: \Lcount{enumi},
%    \Lcount{enumii}, \Lcount{enumiii} and \Lcount{enumiv}, where
%    \Lcount{enumN} controls the numbering of the Nth level
%    enumeration.
%
% \begin{macro}{\theenumi}
% \begin{macro}{\theenumii}
% \begin{macro}{\theenumiii}
% \begin{macro}{\theenumiv}
%    The counters are already defined in \file{latex.dtx}, but their
%    representation is changed here.
%
%    \begin{macrocode}
\renewcommand{\theenumi}{\@arabic\c@enumi}
\renewcommand{\theenumii}{\@alph\c@enumii}
\renewcommand{\theenumiii}{\@roman\c@enumiii}
\renewcommand{\theenumiv}{\@Alph\c@enumiv}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\labelenumi}
% \begin{macro}{\labelenumii}
% \begin{macro}{\labelenumiii}
% \begin{macro}{\labelenumiv}
%    The label for each item is generated by the commands\\
%    \cs{labelenumi} \ldots\ \cs{labelenumiv}.
%    \begin{macrocode}
\newcommand{\labelenumi}{\theenumi.}
\newcommand{\labelenumii}{\theenumii)}
\newcommand{\labelenumiii}{\theenumiii.}
\newcommand{\labelenumiv}{\theenumiv.}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\p@enumii}
% \begin{macro}{\p@enumiii}
% \begin{macro}{\p@enumiv}
%    The expansion of \verb?\p@enumN\theenumN? defines the output of a
%    \cs{ref} command when referencing an item of the Nth level of an
%    enumerated list.
%    \begin{macrocode}
\renewcommand{\p@enumii}{\theenumi}
\renewcommand{\p@enumiii}{\theenumi(\theenumii)}
\renewcommand{\p@enumiv}{\p@enumiii\theenumiii}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%    The following is taken directly from David Carlisle's 
% \Lpack{enumerate} package.
%
% START OF DAVID CARLISLE'S CODE AND COMMENTARY
%
% This package gives the enumerate environment an optional argument
% which determines the style in which the counter is printed.
%
% An occurence of one of the tokens \verb?A a I i? or \verb?1? produces the value
% of the counter printed with (respectively) \verb?\Alph \alph \Roman \roman?
% or \cs{arabic}.
%
% These letters may be surrounded by any strings involving any other
% \TeX\ expressions, however the tokens \verb?A a I i 1? must be inside a
% \verb?{ }? group if they are not to be taken as special.
%
%
% \begin{macro}{\@enlab}
% Internal token register used to build up the label command from the
% optional argument.
%    \begin{macrocode}
\newtoks\@enLab
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@enQmark}
% This just expands to a `?'. \cs{ref} will produce this, if no counter
% is printed.
%    \begin{macrocode}
\def\@enQmark{?}
%    \end{macrocode}
% \end{macro}
%
% The next four macros build up the command that will print the item
% label. They each gobble one token or group from the optional argument,
% and add corresponding tokens to the register \cs{@enLab}. They each end
% with a call to \cs{@enloop}, which starts the processing of the next
% token.
% \begin{macro}{\@enLabel}
% Add the counter to the label. \verb?#2? will be one of the `special'
% tokens \verb?A a I i 1?, and is thrown away. \verb?#1? will be a command
% like \cs{Roman}.
%    \begin{macrocode}
\def\@enLabel#1#2{%
  \edef\@enThe{\noexpand#1{\@enumctr}}%
  \@enLab\expandafter{\the\@enLab\csname the\@enumctr\endcsname}%
  \@enloop}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@enSpace}
% \begin{macro}{\@enSp@ce}
% Add a space to the label. The tricky bit is to gobble the space token,
% as you can not do this with a macro argument.
%    \begin{macrocode}
\def\@enSpace{\afterassignment\@enSp@ce\let\@memtempa= }
\def\@enSp@ce{\@enLab\expandafter{\the\@enLab\space}\@enloop}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@enGroup}
% Add a \verb?{ }? group to the label.
%    \begin{macrocode}
\def\@enGroup#1{\@enLab\expandafter{\the\@enLab{#1}}\@enloop}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@enOther}
% Add anything else to the label
%    \begin{macrocode}
\def\@enOther#1{\@enLab\expandafter{\the\@enLab#1}\@enloop}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@enloop}
% \begin{macro}{\@enloop@}
% The body of the main loop.
% Eating tokens this way instead of using \cs{@tfor} lets you see
% spaces and \textbf{all} braces. \cs{@tfor} would treat \verb?a? and
% \verb?{a}? as  special, but not \verb?{{a}}?.
%    \begin{macrocode}
\def\@enloop{\futurelet\@entemp\@enloop@}
%    \end{macrocode}
%    \begin{macrocode}
\def\@enloop@{%
  \ifx A\@entemp         \def\@memtempa{\@enLabel\Alph  }\else
  \ifx a\@entemp         \def\@memtempa{\@enLabel\alph  }\else
  \ifx i\@entemp         \def\@memtempa{\@enLabel\roman }\else
  \ifx I\@entemp         \def\@memtempa{\@enLabel\Roman }\else
  \ifx 1\@entemp         \def\@memtempa{\@enLabel\arabic}\else
  \ifx \@sptoken\@entemp \let\@memtempa\@enSpace         \else
  \ifx \bgroup\@entemp   \let\@memtempa\@enGroup         \else
  \ifx \@enum@\@entemp   \let\@memtempa\@gobble          \else
                         \let\@memtempa\@enOther
%    \end{macrocode}
%    Hook for possible extensions
%    \begin{macrocode}
                         \@enhook
%    \end{macrocode}
%
%    \begin{macrocode}
             \fi\fi\fi\fi\fi\fi\fi\fi
%    \end{macrocode}
% \end{macro}
% Process the current token, then look at the next.
%    \begin{macrocode}
  \@memtempa}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@enhook}
% Hook for possible extensions.
% Some packages may want to extend the number of special characters
% that are associated with counter representations. This feature
% was requested to enable Russian alphabetic counting, but here
% I give an example of a footnote symbol counter, triggered by \verb?*?.
%
% To enable a new counter type based on a letter, you just need
% to add a new \cs{ifx} clause by analogy with the code above.
% So for example to make \verb?*? trigger footnote symbol counting.
% a package should do the following.
%
% Initialise the hook, in case the package is loaded before
% \textsf{enumerate}.
%\begin{verbatim}
% \providecommand\@enhook{}
%\end{verbatim}
%
% Add to the hook a new \cs{ifx} clause that associates \verb?*? with the
% \cs{fnsymbol} counter command.
%\begin{verbatim}
% \g@addto@macro\@enhook{%
%   \ifx *\@entemp
%     \def\@memtempa{\@enLabel\fnsymbol}%
%   \fi}
%\end{verbatim}
% This code sequence should work whether it is loaded before or after
% this enumerate package. Any number of new counter types may be added
% in this way.
%
% At this point we just need initialise the hook, taking care not
% to over write any definitions another package may already have added.
% (PRW: as this is now in a class, it can be defined instead of
% \cs{provide}d).
%    \begin{macrocode}
%% \providecommand\@enhook{}
  \newcommand\@enhook{}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\enumerate}
% The new \Lenv{enumerate} environment. This is the first half of the
% original enumerate environment. If there is an optional argument, call
% \cs{@@enum@} to define the label commands, otherwise call
% \cs{@enum@} which is the second half of the original definition.
%    \begin{macrocode}
\def\enumerate{%
  \ifnum \@enumdepth >3 \@toodeep\else
      \advance\@enumdepth \@ne
      \edef\@enumctr{enum\romannumeral\the\@enumdepth}\fi
  \@ifnextchar[{\@@enum@}{\@enum@}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@@enum@}
% Handle the optional argument..
%    \begin{macrocode}
\def\@@enum@[#1]{%
%    \end{macrocode}
% Initialise the loop which will break apart the optional argument.
% The command to print the label is built up in \cs{@enlab}.
% \cs{@enThe} will be used to define \cs{theenum}\,$n$.
%    \begin{macrocode}
  \@enLab{}\let\@enThe\@enQmark
%    \end{macrocode}
% The \cs{@enum@} below is never expanded, it is used to detect the end
% of the token list.
%    \begin{macrocode}
  \@enloop#1\@enum@
%    \end{macrocode}
% Issue a warning if we did not find one of the `special' tokens.
%    \begin{macrocode}
  \ifx\@enThe\@enQmark\@warning{The counter will not be printed.%
   ^^J\space\@spaces\@spaces\@spaces The label is: \the\@enLab}\fi
%    \end{macrocode}
% Define \cs{labelenum}$\,n$ and \cs{theenum}$\,n$.
%    \begin{macrocode}
  \expandafter\edef\csname label\@enumctr\endcsname{\the\@enLab}%
  \expandafter\let\csname the\@enumctr\endcsname\@enThe
%    \end{macrocode}
% Set the counter to 7 so that we get the width of `vii' if roman
% numbering is in force then set \cs{leftmargin}$\,n$. to the width of the
% label plus \cs{labelsep}.
%    \begin{macrocode}
  \csname c@\@enumctr\endcsname7
  \expandafter\settowidth
            \csname leftmargin\romannumeral\@enumdepth\endcsname
            {\the\@enLab\hspace{\labelsep}}%
%    \end{macrocode}
% Finally call \cs{@enum@} which is the second half of the original
% definition.
%    \begin{macrocode}
  \@enum@}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@enum@}
% All the list parameters have now been defined, so call \cs{list}. This
% is taken straight from the original definition of \cs{enumerate}.
%    \begin{macrocode}
\def\@enum@{\list{\csname label\@enumctr\endcsname}%
           {\usecounter{\@enumctr}\def\makelabel##1{\hss\llap{##1}}}}

%    \end{macrocode}
% \end{macro}
%
% END OF DAVID CARLISLE'S CODE AND COMMENTARY
%
%
%
% \subsection{Itemize}
%
%
% \begin{macro}{\labelitemi}
% \begin{macro}{\labelitemii}
% \begin{macro}{\labelitemiii}
% \begin{macro}{\labelitemiii}
%    Itemization is controlled by the commands: \cs{labelitemi},
%    \cs{labelitemii}, etc., which define
%    the labels of the various itemization levels: the symbols used are:
%    bullet (\textbullet), bold en-dash (\textbf{\textendash}),
% centered asterisk (\textasteriskcentered), and centered dot
% (\textperiodcentered).
%
%    \begin{macrocode}
\newcommand{\labelitemi}{\textbullet}
\newcommand{\labelitemii}{\normalfont\bfseries \textendash}
\newcommand{\labelitemiii}{\textasteriskcentered}
\newcommand{\labelitemiv}{\textperiodcentered}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% It seems like a reasonable idea to give the \Lenv{itemize} environment
% an optional argument to match \Lenv{enumerate}. Fortunately this seems
% to be much simpler and I might even be able to work it out for myself.
%
% \begin{environment}{itemize}
% This is a hack at the kernel code for \Lenv{itemize}.
%    \begin{macrocode}
\renewcommand{\itemize}[1][\@empty]{%
  \ifnum \@itemdepth >\thr@@\@toodeep\else
    \advance\@itemdepth\@ne
    \ifx \@empty #1\else % optional argument
      \@namedef{labelitem\romannumeral\the\@itemdepth}{#1}%
    \fi
    \edef\@itemitem{labelitem\romannumeral\the\@itemdepth}%
    \expandafter
    \list
      \csname\@itemitem\endcsname
       {\def\makelabel##1{\hss\llap{##1}}}%
  \fi}
\let\enditemize =\endlist

%    \end{macrocode}
% \end{environment}
%
% \subsection{Description}
%
% The class defines two description environment, the standard one and a `block'
% one, and also two semi-configurable versions.
%
% \changes{v1.2}{2002/07/27}{Now two `description' environments.}
%
% \begin{environment}{description}
%    The description environment is defined here -- while the default itemize
%    and enumerate environments are defined in \file{latex.dtx}.
%
% \changes{v1.2}{2002/07/27}{The \texttt{description} environment now matches
%                            the standard layout.}
%    \begin{macrocode}
\newenvironment{description}%
               {\list{}{\labelwidth\z@ \itemindent-\leftmargin
                        \let\makelabel\descriptionlabel}}%
               {\endlist}
%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\descriptionlabel}
%    To change the formatting of the label, you must redefine
%    \cs{descriptionlabel}. 
%
%    \begin{macrocode}
\newcommand*{\descriptionlabel}[1]{\hspace\labelsep
                                   \normalfont\bfseries #1}
%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{blockdescription}
%    The `block' description environment.
%
% \changes{v1.2}{2002/07/27}{Renamed original \texttt{description} environment
%                            to \texttt{blockdescription}.}
%    \begin{macrocode}
\newenvironment{blockdescription}%
               {\list{}{\labelwidth\z@ \itemindent 0.5em \labelsep 0.5em
                        \let\makelabel\blockdescriptionlabel}}%
               {\endlist}
%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\blockdescriptionlabel}
%    In order to change the formatting of the label, you must redefine 
% the macro \cs{blockdescriptionlabel}. 
%
%    \begin{macrocode}
\newcommand*{\blockdescriptionlabel}[1]{%%% \hspace\labelsep
                                   \normalfont\bfseries #1}
%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{labelled}
% This is a version of the description environment which takes the
% name, without the backslash, of some \cs{labelcode} as its argument.
% For example: 
% \begin{verbatim}
% \newcommand*{\sflabel}[1]{\hspace\labelsep \normalfont\sffamily #1}
% \begin{labelled}{sflabel}
%   \item[label] using a sans font for the labels 
% \end{verbatim}
% \changes{v1.6180339f}{2009/04/25}{Added labelled environment}
%    \begin{macrocode}
\newenvironment{labelled}[1]%
  {\list{}{\labelwidth\z@ \itemindent-\leftmargin
           \def\m@malabel{\@nameuse{#1}} \let\makelabel\m@malabel}}%
  {\endlist}

%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{flexlabelled}
% \verb?\begin{flexlabelled}{labelcode}{labelwidth}{labelsep}{itemindent}{leftmargin}{rightmargin}?
% lets you specify some of the parameters for a description-like list.
% The first argument is as for the labelled environment. The others are all
% lengths for the various parameters; a \verb?*? instead of a length means 
% that that argument is to be ignored.
% \changes{v1.6180339f}{2009/04/25}{Added flexlabelled environment}
%    \begin{macrocode}
\newenvironment{flexlabelled}[6]%
  {\list{}{\nametest{#2}{*}%
           \ifsamename\else \labelwidth #2  \fi
           \nametest{#3}{*}%
           \ifsamename\else \labelsep #3 \fi
           \nametest{#4}{*}%
           \ifsamename\else \itemindent #4 \fi
           \nametest{#5}{*}%
           \ifsamename\else \leftmargin #5 \fi
           \nametest{#6}{*}%
           \ifsamename\else  \rightmargin #6 \fi
           \def\m@malabel{\@nameuse{#1}} \let\makelabel\m@malabel}}%
  {\endlist}

%    \end{macrocode}
% \end{environment}
%
%
% \subsection{Quotation}
%
% \begin{environment}{quotation}
%   The quotation environment is defined by making clever use of
%   the list environment's parameters. The lines in the environment
%   are set smaller than \cs{textwidth}. The first line of a paragraph
%   inside this environment is indented.
%
%    \begin{macrocode}
\newenvironment{quotation}%
               {\list{}{\listparindent 1.5em%
                        \itemindent    \listparindent
                        \rightmargin   \leftmargin
                        \parsep        \z@ \@plus\p@}%
                \item[]}%
               {\endlist}
%    \end{macrocode}
% \end{environment}
%
% \subsection{Quote}
%
%
% \begin{environment}{quote}
%   The quote environment is like the quotation environment except
%   that paragraphs are not indented.
%
%    \begin{macrocode}
\newenvironment{quote}%
               {\list{}{\rightmargin\leftmargin}%
                \item[]}%
               {\endlist}
%    \end{macrocode}
% \end{environment}
%
% \subsection{Theorem}
%
%    This document class does not define it's own theorem environments,
%    the defaults, supplied by \file{latex.dtx} are available.
%
% \subsection{Listing of symbols and abbreviations}
%
%    Another element is the listing of symbols
%    and abbreviations. 
%
% \begin{environment}{symbols}
% \begin{macro}{\symbollabel}
%    \begin{macrocode}
\newcommand{\symbollabel}[1]{{#1 \hfill}}
%    \end{macrocode}
% \end{macro}
%    \begin{macrocode}
\newenvironment{symbols}{\list{}%
    {\itemindent 0em \leftmargin 8em
     \labelsep 1em \labelwidth 5em
     \let\makelabel\symbollabel}}%
    {\endlist}
%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\symboldef}
%    Within a \Lenv{symbols} environment the command 
%    \cs{symboldef}\marg{symbol}\marg{meaning}
%    is used to specify and explain each symbol or abbreviation.
%    \begin{macrocode}
\newcommand{\symboldef}[2]{\item[#1] #2}
%    \end{macrocode}
% \end{macro}
%
% \section{Abstracts}
%
% Books usually do not have abstracts, but I decided to add in the code 
% from the \Lpack{abstract} 
% package~\cite{ABSTRACT}.
% \changes{v0.3}{2001/07/09}{Added code for abstracts}
%
%
% We just have the \Lpack{report} or \Lpack{article} style for the
% abstract with no \Lopt{titlepage} option. The original code,
% from \file{classes.dtx} for this is:
% \begin{verbatim}
% \newenvironment{abstract}{%
%   \if@twocolumn
%     \section*{\abstractname}
%   \else
%     \small
%     \begin{center}%
%       {\bfseries \abstractname\vspace{-.5em}\vspace{\z@}}%%
%     \end{center}%
%     \quotation
%   \fi}%
%   {\if@twocolumn\else\endquotation\fi}
% \end{verbatim}
%
%
%    The following \cs{if...} commands are for implementing various options.
% \begin{macro}{\if@bsonecol}
% \begin{macro}{\ifadd@bstotoc}
% \begin{macro}{\ifnumber@bs}
% \begin{macro}{\if@bsrunin}
%    \begin{macrocode}
\newif\if@bsonecol
  \@bsonecoltrue
\newif\ifadd@bstotoc
  \add@bstotocfalse
\newif\ifnumber@bs
  \number@bsfalse
\newif\if@bsrunin
  \@bsruninfalse

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\abstractcol}
% \begin{macro}{\abstractintoc}
% \begin{macro}{\abstractnum}
% \begin{macro}{\abstractrunin}
% These are the use-level commands for setting the options. If
% the abstract is runin, then it must not be numbered otherwise
% adding it to the ToC might result in something peculiar.
%    \begin{macrocode}
\newcommand{\abstractcol}{\@bsonecolfalse}
\newcommand{\abstractintoc}{\add@bstotoctrue}
\newcommand{\abstractnum}{\number@bstrue\@bsruninfalse}
\newcommand{\abstractrunin}{\@bsrunintrue\number@bsfalse}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% 
%    The next set of macros comprise the 
% implementation of the \Lenv{abstract} environment.
%
% \begin{macro}{\abstractnamefont}
% \begin{macro}{\abstracttextfont}
%    These two macros are for specifying the fonts for typesetting the
% abstract's title and text. They are initialised for the default case
% (i.e., no class options).
%    \begin{macrocode}
\newcommand{\abstractnamefont}{\normalfont\small\bfseries}
\newcommand{\abstracttextfont}{\normalfont\small}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\abscolnamefont}
% \begin{macro}{\abscoltextfont}
%    These two macros are for specifying the fonts for typesetting the
% abstract's title and text in a two column document where the abstarct
% is part of a column. 
% \changes{v1.61803}{2008/01/30}{Added \cs{abscolnamefont} and 
%                    \cs{abscoltextfont} (mempatch v4.8)}
%    \begin{macrocode}
\newcommand{\abscolnamefont}{\normalfont\Large\bfseries}
\newcommand{\abscoltextfont}{\normalfont}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\absnamepos}
% \begin{macro}{\abstitleskip}
%    \cs{absnamepos} specifies the environment in which the abstract's title
% name will be typeset, and the length \cs{abstitleskip} is an adjustement
% to the vertical space between the title and the abstract's text. These
% are initialised for the default case.
%    \begin{macrocode}
\newcommand{\absnamepos}{center}
\newlength{\abstitleskip} \setlength{\abstitleskip}{-0.5em}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\absleftindent}
% \begin{macro}{\abs@leftindent}
% \begin{macro}{\absrightindent}
% \begin{macro}{\absparindent}
% \begin{macro}{\absparsep}
%    The abstract's text is typeset as a single item list, called 
% \texttt{@bstr@ctlist}. These lengths set the left and right margin indents, the
% paragraph indentation, and the inter-paragraph vertical space. Their
% initial values are all class option-dependent.
% \changes{v1.618}{2005/09/03}{Added \cs{abs@leftindent} per Lars Madsen (mempatch v3.0)}
%    \begin{macrocode}
\newlength{\absleftindent} 
  \absleftindent=\leftmargin
\newdimen\abs@leftindent
  \abs@leftindent=\leftmargin
\newlength{\absrightindent}
  \absrightindent=\leftmargin
\newlength{\absparindent}
\newlength{\absparsep}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\abslabeldelim}
% \begin{macro}{\@bslabeldelim}
% The contents of \cs{abslabeldelim} are typeset after a run-in heading.
%    \begin{macrocode}
\newcommand{\abslabeldelim}[1]{\def\@bslabeldelim{#1}}
\abslabeldelim{}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@bsrunintitle}
% This macro typeset the run-in heading.
%    \begin{macrocode}
\newcommand{\@bsrunintitle}{%
  \hspace*{\abstitleskip}{\abstractnamefont\abstractname\@bslabeldelim}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setup@bstract}
%    Now arrange to set all the class option-dependent values.
% \changes{v1.618}{2005/09/03}{Used \cs{abs@leftindent} in \cs{setup@bstract} (mempatch v3.0)}
% \changes{v1.61803}{2008/01/30}{Changed \cs{setup@bstract} to cater for
%                    \cs{abscolnamefont}, etc., and don't set 
%                    \cs{absrightindent} to \cs{absleftindent}.}
%    \begin{macrocode}
\newcommand{\setup@bstract}{%
  \abs@leftindent=\absleftindent
  \if@twocolumn
%    \end{macrocode}
% Values for the \Lopt{twocolumn} class option.
%    \begin{macrocode}
    \if@bsonecol 
    \else
      \abs@leftindent=\z@
      \absrightindent=\z@
      \renewcommand*{\abstractnamefont}{\abscolnamefont}
      \renewcommand*{\abstracttextfont}{\abscoltextfont}
      \renewcommand*{\absnamepos}{flushleft}
      \setlength{\abstitleskip}{-2ex}
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
%    \begin{macrocode}
\AtBeginDocument{\setlength{\absparindent}{\parindent}
                 \setlength{\absparsep}{\parskip}}

%    \end{macrocode}
%
% \begin{environment}{@bstr@ctlist}
%    The abstract's text is typeset within the \Lenv{@bstr@ctlist} list environment.
% \changes{v1.618}{2005/09/03}{Used \cs{abs@leftindent} in \cs{@bstr@ctlist} (mempatch v3.0)}
%    \begin{macrocode}
\newenvironment{@bstr@ctlist}{%
  \list{}{%
          %%\topsep        \z@
          \partopsep     \z@
          \listparindent \absparindent
          \itemindent    \listparindent
          \leftmargin    \abs@leftindent
          \rightmargin   \absrightindent
          \parsep        \absparsep}%
  \item\relax}
  {\endlist}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\put@bsintoc}
%    This macro adds the abstract's title to the ToC. It does nothing if
% the abstract is being numbered.
%    \begin{macrocode}
\newcommand{\put@bsintoc}{%
  \ifadd@bstotoc
    \ifnumber@bs\else
      \phantomsection
      \addcontentsline{toc}{chapter}{\abstractname}
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\num@bs}
%    This macro generates a numbered abstract heading.
%    \begin{macrocode}
\newcommand{\num@bs}{\chapter{\abstractname}}

%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{abstract}
%  At last we are in position to define the \Lenv{abstract} environment. This
% follows very much along the lines of the standard class definitions, but with
% macros inserted at strategic points.
%
% The \Lopt{twocolumn} option and the default case. These use the same code
% as any style differences are embedded in the new macros.
%    \begin{macrocode}
\newenvironment{abstract}{%
  \setup@bstract
  \if@bsrunin\else
    \ifnumber@bs \num@bs \else
      \begin{\absnamepos}\abstractnamefont\abstractname\end\absnamepos%
      \vspace{\abstitleskip}%
    \fi
  \fi
  \put@bsintoc%
  \begin{@bstr@ctlist}\if@bsrunin\@bsrunintitle\fi\abstracttextfont}%
  {\par\end{@bstr@ctlist}}

%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{onecolabstract}
%  An environment for typesetting a single column abstract, 
% particularly as the optional argument to the \cs{twocolumn} command.
%    \begin{macrocode}
\newenvironment{onecolabstract}{%
  \begin{@twocolumnfalse}\begin{abstract}}{%
  \end{abstract}\end{@twocolumnfalse}}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\thanks}
% \begin{macro}{\@bs@thanks}
%    We have to keep the contents of the \cs{thanks} commands as normally these
% are emptied by the \cs{maketitle} command. I do this by extending the definition
% of the \cs{thanks} (from \file{ltsect.dtx}) command, 
% so that \cs{@bs@thanks} has a copy of the contents
% of \cs{@thanks}.
%    \begin{macrocode}
\addtoiargdef{\thanks}{}{%
  \protected@xdef\@bs@thanks{\@bs@thanks
    \protect\footnotetext[\the\c@footnote]{#1}}%
}
\let\@bs@thanks\@empty

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\saythanks}
% This macro typesets any \cs{thanks} commands \emph{after} using 
% \texttt{onecolabstract}. 
%    \begin{macrocode}
\newcommand{\saythanks}{\begingroup
  \renewcommand{\thefootnote}{\fnsymbol{footnote}}\@bs@thanks
  \endgroup\global\let\@bs@thanks\@empty}
  
%    \end{macrocode}
% \end{macro}
%
%
% \section{Verse}
%
% The class provides a more flexible \Lenv{verse} environment than the 
% standard classes. This is based on the \Lpack{verse} 
% package~\cite{VERSE}.
% \changes{v1.0}{2001/10/30}{Complete rewrite of verse typesetting}
%
% \subsection{Environments}
%
%    Before proceeding with the main, here are some macros for aspects
% of line numbering.
%
% \begin{macro}{\c@vslineno}
% \begin{macro}{\c@poemline}
% \begin{macro}{\c@modulo@vs}
% \begin{macro}{\c@memfvsline}
% We need counters for stanza and poem lines. The \texttt{memfvsline}
% counter is for adjusting the starting line for verse line numbers. 
% \changes{v1.1}{2002/03/10}{Added poemline and modulo@vs counters}
% \changes{v1.61803}{2008/01/30}{Added memfvsline counter (mempatch v4.9)}
%    \begin{macrocode}
\newcounter{vslineno}
\newcounter{poemline}
\newcounter{modulo@vs}
\newcounter{memfvsline}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\poemlines}
% \cs{poemlines}\marg{nth} specifies that every \meta{nth} line of
% a poem is to be numbered. 
% \changes{v1.1}{2002/03/10}{Added \cs{poemlines}}
% \changes{v1.2}{2002/07/27}{\cs{poemlines} now just calls \cs{linenumberfrequency}}
% \changes{v1.61803}{2008/01/30}{Deleted \cs{poemlines}.}
%    \begin{macrocode}
%%%\newcommand{\poemlines}[1]{\linenumberfrequency{#1}%
%%%  \@memwarn{Use \string\linenumberfrequency\space
%%%                        instead of \string\poemlines}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\linenumberfont}
% \begin{macro}{\vlvnumfont}
%  Set line numbering font(s).
%    \begin{macrocode}
\newcommand{\linenumberfont}[1]{\def\vlvnumfont{#1}}
%%% \linenumberfont{\small\rmfamily}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ifbvcountlines}
% \begin{macro}{\bvcountlinestrue}
% \begin{macro}{\bvcountlinesfalse}
% Looking ahead, TRUE for (boxed) verbatim line numbers to be printed. Default
% is not to print them. Not that \cs{linenumberfrequency} twiddles with this.
%    \begin{macrocode}
\newif\ifbvcountlines%  TRUE to print line numbers of (boxed) verbatim lines
  \bvcountlinesfalse

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\linenumberfrequency}
% \begin{macro}{\linemodnum}
% Set numbering intervals (number modulo). Default is modulus 0.
%    \begin{macrocode}
\newcommand{\linenumberfrequency}[1]{%
  \ifnum #1< \@ne
    \def\linemodnum{0\relax}
    \bvcountlinesfalse
  \else
    \def\linemodnum{#1\relax}
    \bvcountlinestrue
  \fi}

%%%%\linenumberfrequency{0}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setverselinenums}
% \cs{setverselinenums}\marg{firstline}\marg{startnumsat} sets the first line
% number to \meta{firstline} and the first line number to be printed is
% \meta{startnumsat}. Use within the \Lenv{verse} environment before the
% first verse. Note that \\
% \verb?firstline <= startnumsat < firstline + linenumberfrequency?
% \changes{v1.61803}{2008/01/30}{Added \cs{setverselinenums} (mempatch v4.9)}
%    \begin{macrocode}
\newcommand*{\setverselinenums}[2]{%
  \c@poemline #1\relax \advance\c@poemline \m@ne
  \refstepcounter{poemline}%
  \ifnum\z@<\linemodnum%   we are printing line numbers
    \@tempcnta #2\relax
    \divide\@tempcnta\linemodnum
    \multiply\@tempcnta\linemodnum
    \c@memfvsline #2\relax
    \advance\c@memfvsline-\@tempcnta
  \fi}

%    \end{macrocode}
% \end{macro} 
%
% \changes{v1.1}{2002/03/24}{Added \cs{getmodulo@vs}}
% \changes{v1.2}{2002/07/27}{Using \cs{getthelinenumber} instead of \cs{getmodulo@vs}}
%
% \begin{macro}{\getthelinenumber}
% \cs{getthelinenumber}\marg{counter}\marg{start} returns \cs{thecounter} 
% if it is exactly divisible by \cs{linenumberfrequency}, provided this is 
% not zero. \meta{start} is the first number.
% \changes{v1.61802}{2008/01/30}{Generalised \cs{getthelinenumber} to cater
%          for set of first line number.}
%    \begin{macrocode}
\newcommand{\getthelinenumber}[2]{%
  \ifnum\@ne>\linemodnum%  no line numbers
  \else
    \ifnum\@ne=\linemodnum% every line numbered
      \@nameuse{the#1}%
    \else
      \@tempcnta=\@nameuse{c@#1}%
      \advance\@tempcnta -\@nameuse{c@#2}%
      \divide\@tempcnta \linemodnum
      \multiply\@tempcnta \linemodnum
      \advance\@tempcnta \@nameuse{c@#2}%
      \ifnum\@tempcnta=\@nameuse{c@#1}\@nameuse{the#1}\fi
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifaltindent}
% This should be set TRUE for indenting alternate lines.
%    \begin{macrocode}
\newif\ifaltindent
  \altindentfalse
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifpattern}
% This should be set TRUE for indenting lines according to a pattern.
%    \begin{macrocode}
\newif\ifpattern
  \patternfalse
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifstarpattern}
% This should be set TRUE for indenting lines according in a \Lenv{patverse*}
% environment.
% \changes{v1.1}{2002/03/8}{Added \cs{ifstarpattern}}
%    \begin{macrocode}
\newif\ifstarpattern
  \starpatternfalse

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\vleftskip}
% \begin{macro}{\vrightskip}
% Skips to the left and right of a line of verse.
% \changes{v1.1}{2002/03/24}{Added \cs{vleftskip} and \cs{vrightskip}}
% \changes{v1.2}{2002/07/27}{Changed defaults for \cs{vleftskip} and \cs{vrightskip}}
%    \begin{macrocode}
\newlength{\vleftskip}
  \setlength{\vleftskip}{3em}
\newlength{\vrightskip}
  \setlength{\vrightskip}{1em}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\stanzaskip}
% Skip between stanzas.
% \changes{v1.2}{2002/07/07}{Added \cs{stanzaskip}}
%    \begin{macrocode}
\newlength{\stanzaskip}
  \setlength{\stanzaskip}{\onelineskip}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\flagverse}
% \cs{flagverse}\marg{flag} inserts \meta{flag} at the left (of a line).
% \changes{v1.1}{2002/03/24}{Added \cs{flagverse}}
% \changes{v1.61803398}{2009/07/17}{Added bidi suport to \cs{flagverse}}
%    \begin{macrocode}
\newcommand{\flagverse}[1]{%
%%%  \hskip-\vleftskip\llap{#1}\hskip\vleftskip\ignorespaces}
  \hskip-\memRTLvleftskip\llap{#1}\hskip\memRTLvleftskip\ignorespaces}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\versewidth}
% The length \cs{versewidth} is a convenience length for the user.
%    \begin{macrocode}
\newlength{\versewidth}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\vgap}
% \begin{macro}{\vin}
% \begin{macro}{\vindent}
% The length \cs{vgap} is used as the basis for spacing. \cs{vin} makes
% a horizontal space of \cs{vgap} and \cs{vindent} is the indentation
% of wrapped lines.
%    \begin{macrocode}
\newlength{\vgap} \setlength{\vgap}{1.5em}
\newcommand{\vin}{\hspace*{\vgap}}
\newlength{\vindent} \setlength{\vindent}{2\vgap}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\vinphantom}
% Macro to leave blank space coresponding to a string.
% \changes{v1.4}{2003/02/27}{Added \cs{vinphantom} (patch 1.1)}
%    \begin{macrocode}
\newcommand{\vinphantom}[1]{\leavevmode\phantom{#1}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\vleftofline}
% Macro to insert something immediately to the left of the start 
% of the line.
% \changes{v1.618}{2005/09/14}{Added \cs{vleftofline}}
%    \begin{macrocode}
\newcommand*{\vleftofline}[1]{\leavevmode\llap{#1}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\vleftmargin}
% Length to adjust the default left margin within a verse environment.
% \changes{v1.618}{2005/09/18}{Added \cs{vleftmargin}}
%    \begin{macrocode}
\newdimen\vleftmargin
  \vleftmargin=\leftmargini

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\verselinebreak}
% Break a verse line by inserting \cs{newline}. 
% \changes{v1.1}{2002/03/28}{Modified \cs{verselinebreak}}
% \changes{v1.61803}{2008/01/30}{Removed extraneous space from \cs{verselinebreak} (mempatch v4.4, Aaron Rendahl)}
%    \begin{macrocode}
\newcommand{\verselinebreak}[1][\z@]{\newline\hspace*{#1}\ignorespaces}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\incr@vsline}
% Increment the line counters.
% \changes{v1.1}{2002/03/24}{Added poemline counter to \cs{incr@vsline}}
%    \begin{macrocode}
\newcommand{\incr@vsline}{%
  \refstepcounter{poemline}%
  \stepcounter{vslineno}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@vsifbang}
% Like the kernel \cs{@ifstar} except it looks for an exclamation mark!
% \changes{v1.1}{2002/03/24}{Added \cs{@vsifbang}}
%    \begin{macrocode}
\newcommand{\@vsifbang}[1]{\@ifnextchar !{\@firstoftwo{#1}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@vsifgt}
% Like the kernel \cs{@ifstar} except it looks for a \verb?>? character.
% \changes{v1.1}{2002/03/28}{Added \cs{@vsifgt}}
%    \begin{macrocode}
\newcommand{\@vsifgt}[1]{\@ifnextchar >{\@firstoftwo{#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\verselinenumbersright}
% \begin{macro}{\verselinenumbersleft}
% \begin{macro}{\@vstypelinenum}
% Declarations for setting line numbers at the right (the default)
% or the left..
% \changes{v1.61803}{2008/01/30}{Added \cs{verselinenumbersright} and
%          \cs{verselinenumbersleft} (mempatch v4.4, v4.9)}
%    \begin{macrocode}
\newcommand*{\verselinenumbersright}{\def\@vstypelinenum{\@vslnumright}}
\newcommand*{\verselinenumbersleft}{\def\@vstypelinenum{\@vslnumleft}}
\verselinenumbersright

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@vslnumright}
% \begin{macro}{\@vslnumleft}
% Internal code for right/left line numbers.
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{@vslnumright}
% and \cs{@vslnumleft}}
% \changes{v3.7g}{2018/02/28}{Added \cs{nobreak} to both
% \cs{@vslnumright} and \cs{@vslnumleft}, reported on
% \protect\url{https://tex.stackexchange.com/a/415939/3929}, to avoid strange
% double line breaks}
%    \begin{macrocode}
\newcommand*{\@vslnumright}{%
  \nobreak%
  \hfill\rlap{%\kern\vrightskip\kern\rightmargin%
              \kern\memRTLvrightskip\kern\rightmargin%
              \vlvnumfont\getthelinenumber{poemline}{memfvsline}}}
\newcommand*{\@vslnumleft}{%
  \nobreak%
  \hfill\rlap{%\kern-\textwidth\kern-\vrightskip%
              \kern-\textwidth\kern-\memRTLvrightskip%
              \vlvnumfont\getthelinenumber{poemline}{memfvsline}}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@vscentercr}
% This puts the poem line number in the margin, increments
% the line numbers, and then deals with the options. It is based
% on the kernel \cs{@centercr}.
% This has to handle various forms of the \verb?\\? command: \verb?\\?,
% \verb?\\*?, \verb?\\!?, and \verb?\\>?, together with an optional length argument.
% \changes{v1.1}{2002/03/28}{Major rewrite of \cs{@vscentercr} and friends}
% \changes{v1.2}{2002/07/27}{Changed \cs{@vscentercr} to use general
%                linenumbering}
% \changes{v1.61803}{2008/01/30}{Changed \cs{@vscentercr} for left/right numbers
%                    (mempatch v4.4)}
%    \begin{macrocode}
\newcommand{\@vscentercr}{%
  \ifhmode \unskip\else \@nolnerr\fi
  \@vstypelinenum%
%    \end{macrocode}
% For \verb?>? call \cs{verselinebreak} to process it.
%    \begin{macrocode}
  \@vsifgt{\verselinebreak}{%
    \incr@vsline
%    \end{macrocode}
% If the call is \verb?\\*...? call \cs{@vsxcentercr} to handle the \verb?*...?.
% If the call is \verb?\\!?, do nothing.
% If the call is \verb?\\![...]?, call \cs{@vsicentercr} to handle the \verb?[...]?.
% Otherwise, call \cs{@vsxcentercr}.
%    \begin{macrocode}
    \par\@ifstar{\nobreak\@vsxcentercr}{%
%    \end{macrocode}
%    \begin{macrocode}
      \@vsifbang{\@ifnextchar[ {\@vsicentercr}{}}{\@vsxcentercr}}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@vsxcentercr}
% Processes \verb?\\*?, and either calls cs{@vsicentercr} to handle a \verb?[length]?,
% or \cs{start@vsline}.
% \changes{v1.1}{2002/03/24}{Added \cs{@vsxcentercr}}
%    \begin{macrocode}
\newcommand{\@vsxcentercr}{\addvspace{-\parskip}%
  \@ifnextchar[ {\@vsicentercr}{\start@vsline}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@vsicentercr}
% Processes \verb?(\\...)[length]? and then calls \cs{start@vsline}.
% \changes{v1.1}{2002/03/24}{Added \cs{@vsicentercr}}
%    \begin{macrocode}
\def\@vsicentercr[#1]{\vskip #1\ignorespaces \start@vsline}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\start@vsline}
% This is called at the start of every verse line except the first.
% \changes{v1.1}{2002/03/28}{Added \cs{ifstarpattern} to \cs{start@vsline}}
% \changes{v1.61}{2004/03/21}{Used counter for vslineno, not \cs{thevslineno}
%                in \cs{start@vsline}}
%    \begin{macrocode}
\newcommand{\start@vsline}{%
  \ifaltindent\ifodd\c@vslineno\else\vin\fi\fi%
  \ifpattern\get@vsindent\fi%
  \ifstarpattern\getstar@vsindent\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\theHpoemline}
% For the \Lpack{hyperref} package need a way of distinguishing
% lines of a poem. See the thread \textit{PDFTEX/Hyperef hates memoir verse
% environment?} on \ctt{} October 2002.
% \changes{v1.3}{2002/11/14}{Added verse counter and \cs{theHpoemline}}
%    \begin{macrocode}
\newcounter{verse}
\setcounter{verse}{0}
\newcommand{\theHpoemline}{\theverse.\thepoemline}

%    \end{macrocode}
% \end{macro}
% 
% \begin{environment}{verse}
% The extended \Lenv{verse} environment. It sets the verse line counter,
% then defines the particular list environment adjusting the margins
% to center according to the length parameter. If the length parameter
% is at least the \cs{linewidth} then the `centering' defaults to
% the original \Lenv{verse} layout.
% \changes{v1.1}{2001/08/03}{Initialise the line counter to 1, not 0, in
%                all cases}
% \changes{v1.1}{2002/03/28}{Changes to verse environment for line numbering}
% \changes{v1.3}{2002/11/14}{Changes to verse environment for hyperref}
% \changes{v1.4}{2002/02/27}{Let verses wider than the \cs{linewidth}
%                            take the full width (patch(1.1)}
% \changes{v1.618}{2005/09/03}{Fix vertical spacing in the verse environment (mempatch v3.3)}
%    \begin{macrocode}
\newenvironment{verse}[1][\linewidth]{%
  \refstepcounter{verse}%
  \setcounter{poemline}{0}\refstepcounter{poemline}%
  \setcounter{vslineno}{1}%
  \let\\=\@vscentercr
  \list{}{\itemsep     \z@
          \itemindent  -\vindent
          \listparindent\itemindent
          \leftmargin   \vleftmargin
          \parsep       \stanzaskip
          \ifdim #1<\linewidth%   %% short line
            \rightmargin        \z@
            \leftmargin         \linewidth
            \advance\leftmargin -#1\relax
            \advance\leftmargin -0.5\leftmargin
            \advance\leftmargin \vindent
          \else
            \ifdim #1>\linewidth%  %% long line
              \rightmargin \z@
              \leftmargin  \vindent
            \else%                   %% default
              \rightmargin \leftmargin
              \advance\leftmargin \vindent
            \fi
          \fi}
  \item[]}{\endlist}

%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{altverse}
% This sets \cs{altindenttrue} (afterwards false) and initialises the line counter.
% \changes{v1.1}{2002/03/28}{Added \cs{starpatternfalse} to altverse}
%    \begin{macrocode}
\newenvironment{altverse}%
  {\starpatternfalse\patternfalse\altindenttrue
   \setcounter{vslineno}{1}}%
  {\altindentfalse}

%    \end{macrocode}
% \end{environment}
%
%
% \subsection{Patterns}
%
%    The pattern code is based on the idea of converting a string of
% digits to an array of digits, and then being able to access the
% digit at a particular position in the array.
%
%
% \begin{macro}{\ifbounderror}
% A flag set TRUE if an attempt is made to access an array element outside
% the array limits.
%    \begin{macrocode}
\newif\ifbounderror
  \bounderrorfalse
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifinteger}
%  A flag to indicate if a `number' is an integer (TRUE) or not (FALSE).
%    \begin{macrocode}
\newif\ifinteger

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\c@chrsinstr}
% A counter for the number of characters.
%    \begin{macrocode}
\newcounter{chrsinstr}  % CHARactersINSTRing

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\newarray}
% \cs{newarray}\marg{arrayname}\marg{low}\marg{high} defines
% an array called \meta{arrayname} (no backslash e.g. \verb?MyArray?), 
% with low and high limts \meta{low} and \meta{high}.
%    \begin{macrocode}
\newcommand{\newarray}[3]{%
  \@nameedef{#1-low}{#2}%
  \@nameedef{#1-high}{#3}%
  \ifnum #3<#2
    \@memerror{Limits for array #1 are in reverse order}{\@ehc}%
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\stringtoarray}
% \cs{stringtoarray}\marg{arrayname}\marg{string} puts each character
% from \meta{string} sequentially into the \meta{arrayname} array, starting
% with \meta{low} = 1. It checks for an empty \meta{string} and handles that
% specially.
%    \begin{macrocode}
\newcommand{\stringtoarray}[2]{%
  \def\@vsarrayname{#1}%
  \protected@edef\the@vsstring{#2}%
  \newarray{\@vsarrayname}{1}{1}%
  \@ifmtarg{#2}{%
    \c@chrsinstr \z@
    \@namedef{\@vsarrayname-1}{}
  }{%
    \c@chrsinstr \@ne
    \expandafter\@vsstringtoarray \the@vsstring\@vsend
  }}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\@vsstringtoarray}
% Recursively adds characters to the array \cs{@vsarrayname}, incrementing
% the array's high limit.
%    \begin{macrocode}
\def\@vsstringtoarray #1#2\@vsend{%
  \@namedef{\@vsarrayname-\the\c@chrsinstr}{#1}
  \@nameedef{\@vsarrayname-high}{\the\c@chrsinstr}
  \@ifmtarg{#2}{%
    \def\@vsinext{}%
  }{%
    \advance\c@chrsinstr \@ne
    \def\@vsinext{%
      \@vsstringtoarray #2\@vsend%
    }%
  }
  \@vsinext}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\setarrayelement}
% \cs{setarrayelement}\marg{arrayname}\marg{index}\marg{value} sets
% the \meta{arrayname} array's element at \meta{index} to \meta{value}.
%    \begin{macrocode}
\newcommand{\setarrayelement}[3]{%
  \checkarrayindex{#1}{#2}%
  \@nameedef{#1-#2}{#3}}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\getarrayelement}
% \cs{getarrayelement}\marg{arrayname}\marg{index}\marg{value}
% defines the parameterless macro \meta{value} (e.g., \cs{result}) to be
% the value at \meta{index} in the \meta{arrayname} array.
%    \begin{macrocode}
\newcommand{\getarrayelement}[3]{%
  \checkarrayindex{#1}{#2}%
  \protected@edef#3{\@nameuse{#1-#2}}}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\checkarrayindex}
% \cs{checkarrayindex}\marg{arrayname}\marg{index} checks that
% the \meta{index} of the \meta{arrayname} array is valid. \cs{ifbounderror}
% is set FALSE if everything is OK, otherwise it is set TRUE.
%    \begin{macrocode}
\newcommand{\checkarrayindex}[2]{%
  \bounderrorfalse
  \expandafter\ifx\csname #1-low\endcsname\relax%
    \ifpattern\else
      \@memerror{No array called #1}{\@ehc}%
    \fi
    \bounderrortrue
  \fi
  \ifnum #2<\@nameuse{#1-low}\relax%
    \ifpattern\else
      \@memerror{Index #2 outside limits for array #1}{\@ehc}%
    \fi
    \bounderrortrue
  \fi
  \ifnum #2>\@nameuse{#1-high}\relax%
    \ifpattern\else
      \@memerror{Index #2 outside limits for array #1}{\@ehc}%
    \fi
    \bounderrortrue
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\arraytostring}
% \cs{arraytostring}\marg{arrayname}\marg{string} converts the
% characters in the \meta{arrayname} array into the parameterless macro
% \meta{string} (e.g., \cs{MyString}).
%    \begin{macrocode}
\newcommand{\arraytostring}[2]{%
  \def#2{}%
  \c@chrsinstr = \@nameuse{#1-low}%
  \@vsarraytostring{#1}{#2}}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\@vsarraytostring}
% \cs{@vsarraytostring}\marg{arrayname}\marg{string} recursively
% adds the (character) elements from \meta{arrayname} to \meta{string}.
%    \begin{macrocode}
\newcommand{\@vsarraytostring}[2]{%
  \ifnum\c@chrsinstr>\@nameuse{#1-high}\else
    \protected@edef#2{#2\@nameuse{#1-\thechrsinstr}}%
    \advance\c@chrsinstr\@ne%
    \@vsarraytostring{#1}{#2}%
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\checkifinteger}
% \cs{checkifinteger}\marg{num} checks if \meta{num} is an integer.
% If it is, then \cs{ifinteger} is set TRUE, otherwise it is set FALSE.
% (Code based on Donald Arseneau's \Lpack{cite} package).
%    \begin{macrocode}
\newcommand{\checkifinteger}[1]{%
  \protected@edef\@vsa{#1}%
  \ifcat _\ifnum9<1\gobm{#1} _\else A\fi
    \integertrue%
  \else
    \integerfalse%
  \fi}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\gobm}
% \cs{gobm}\marg{num} is defined as \meta{num}. It could be defined as: \\
% \verb?\newcommand{\gobm}[1]{\ifx-#1\expandafter\gobm\else#1\fi}? \\
% which would remove a leading minus sign (hyphen) from its argument
% (\verb?gobm? = gobble minus sign).
% (Code from a posting to \ctt{} by Donald Arseneau on 1997/07/21).
%    \begin{macrocode}
\newcommand{\gobm}[1]{#1}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\indentpattern}
% \cs{indentpattern}\marg{digits} stores \meta{digits} for use as
% a verse indentation pattern.
%    \begin{macrocode}
\newcommand{\indentpattern}[1]{%
  \stringtoarray{Array@vs}{#1}}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\get@vsindent}
% \cs{get@vsindent} gets the indent pattern digit for the \cs{thevslineno},
% then uses this to specify the line indentation as \verb?digit*\vgap?.
% \changes{v1.61}{2004/03/21}{Changed \cs{get@vsindent} to use counter
% value number instead of \cs{thevslineno}}
%    \begin{macrocode}
\newcommand{\get@vsindent}{%
  \getarrayelement{Array@vs}{\number\value{vslineno}}{\@vspat}%
  \ifbounderror
    \arraytostring{Array@vs}{\@vsp@t}%
    \@memwarn{%
      Index `\thevslineno' for pattern `\@vsp@t' is out of bounds}%
    \def\@vspat{0}%
  \else
    \checkifinteger{\@vspat}%
    \ifinteger\else
      \arraytostring{Array@vs}{\@vsp@t}%
      \@memwarn{%
       `\@vspat' at index `\thevslineno' in pattern `\@vsp@t' 
       is not a digit}%
      \def\@vspat{0}%
    \fi
  \fi
  \ifcase\@vspat\else\hspace*{\@vspat\vgap}\fi}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\getstar@vsindent}
% \cs{getstar@vsindent} gets the indent pattern digit for the \Lenv{patverse*}
% environment,
% then uses this to specify the line indentation as \verb?digit*\vgap?.
% It lets the pattern repeat by resetting the \texttt{vslineno} counter.
% \changes{v1.1}{2002/03/28}{Added \cs{getstar@vsindent}}
%    \begin{macrocode}
\newcommand{\getstar@vsindent}{%
  \expandafter\ifx\csname Array@vs-high\endcsname\relax
    \@memerror{A pattern has not been specified}{\@ehc}
  \else
    \ifnum\c@vslineno>\@nameuse{Array@vs-high}%
      \setcounter{vslineno}{1}%
     \fi
     \get@vsindent
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{environment}{patverse}
% The environment for setting verse line indents according to a pattern.
% It starts by setting \cs{ifpattern} TRUE, any other flags to FALSE,
% and initialises the line number. It ends by setting \cs{ifpattern} FALSE.
% \changes{v1.1}{2002/03/28}{Added \cs{starpatternfalse} to patverse}
%    \begin{macrocode}
\newenvironment{patverse}%
  {\starpatternfalse\patterntrue\altindentfalse
   \setcounter{vslineno}{1}}%
  {\patternfalse}

%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{patverse*}
% The environment for setting verse line indents according to a repeating
% pattern.
% It starts by setting \cs{ifstarpattern} TRUE, any other flags to FALSE,
% and initialises the line number. It ends by setting \cs{ifstarpattern} FALSE.
% \changes{v1.1}{2002/03/28}{Added patverse* environment}
%    \begin{macrocode}
\newenvironment{patverse*}%
  {\starpatterntrue\patternfalse\altindentfalse
   \setcounter{vslineno}{1}}%
  {\starpatternfalse}

%    \end{macrocode}
% \end{environment}
%
%
% \subsection{Titles}
%
% \begin{macro}{\poemtitle}
% Typeset a poem title (like \cs{section} or other). The actual work
% is done by \cs{@vsptitle} (plain) or \cs{@vssptitle} (starred).
%    \begin{macrocode}
\newcommand{\poemtitle}{\par%
  \secdef\@vsptitle\@vssptitle}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\poemtoc}
% The kind of entry \cs{poemtitle} is to make in the ToC.
%    \begin{macrocode}
\newcommand{\poemtoc}{section}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mempoeminfo}
% \begin{macro}{\mempoemstarinfo}
% \verb?\mempoeminfo{title}? \\
% \verb?\mempoemstarinfo{title}? \\
% \changes{v1.61803}{2008/01/30}{Made \cs{mempoeminfo} and fiends \cs{long}
%                   (mempatch v4.9)}
%    \begin{macrocode}
\newcommand{\mempoeminfo}[1]{}
\newcommand{\mempoemstarinfo}[1]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@vsptitle}
% Typeset a \cs{poemtitle}.
% \changes{v1.3}{2002/11/14}{Added \cs{phantomsection} to \cs{@vsptitle}}
% \changes{v1.4}{2003/11/16}{Added \cs{M@gettitle} to \cs{@vsptitle}}
%    \begin{macrocode}
\long\def\@vsptitle[#1]#2{%
  \phantomsection
  \addcontentsline{toc}{\poemtoc}{#1}%
  \M@gettitle{#1}%
  \mempoeminfo{#1}%
  \poemtitlemark{#1}%
  \@vstypeptitle{#2}%
  \@afterheading}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@vssptitle}
% Typeset a \cs{poemtitle*}.
% \changes{v1.4}{2003/11/16}{Added \cs{M@gettitle} to \cs{@vssptitle}}
%    \begin{macrocode}
\long\def\@vssptitle#1{%
  \M@gettitle{#1}%
  \mempoemstarinfo{#1}%
  \@vstypeptitle{#1}%
  \@afterheading}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@vstypeptitle}
% This \emph{really} typesets the title.
%    \begin{macrocode}
\newcommand{\@vstypeptitle}[1]{%
  \vspace{\beforepoemtitleskip}%
  {\poemtitlefont #1\par}%
  \vspace{\afterpoemtitleskip}%
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\poemtitlefont}
% \begin{macro}{\poemtitlemark}
% Sets the appearance to the title of a poem, and something for a header.
%    \begin{macrocode}
\newcommand{\poemtitlefont}{\normalfont\large\bfseries\centering}
\newcommand{\poemtitlemark}[1]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\beforepoemtitleskip}
% \begin{macro}{\afterpoemtitleskip}
% Lengths before and after a poem title, using approximately \cs{section} 
% values.
%    \begin{macrocode}
\newlength{\beforepoemtitleskip}
  \setlength{\beforepoemtitleskip}{3.5ex \@plus 1ex \@minus .2ex}
\newlength{\afterpoemtitleskip}
  \setlength{\afterpoemtitleskip}{2.3ex \@plus.2ex}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\if@numptitle}
% \begin{macro}{\@numptitletrue}
% \begin{macro}{\@numptitlefalse}
% \begin{macro}{\NumberPoemTitle}
% \begin{macro}{\PlainPoemTitle}
% Following the \cs{NumberPoemTitle} declaration \cs{PoemTitle}s are numbered.
% The \cs{PlainPoemTitle} declaration produces unnumbered titles.
%    \begin{macrocode}
\newif\if@numptitle
\newcommand*{\NumberPoemTitle}{\@numptitletrue}
\newcommand*{\PlainPoemTitle}{\@numptitlefalse}
\NumberPoemTitle

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\c@poem}
% \begin{macro}{\thepoem}
% \begin{macro}{\theHpoem}
% Counter for poem titles.
%    \begin{macrocode}
\newcounter{poem}\setcounter{poem}{0}
  \renewcommand*{\thepoem}{\@arabic\c@poem}
\newcommand*{\theHpoem}{\arabic{poem}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\poemtitlestarmark}
% \begin{macro}{\poemtitlepstyle}
% \begin{macro}{\poemtitlestarpstyle}
% \cs{poemtitlemark}\marg{poemf@rhdr} is used for marks for a \cs{PoemTitle} and 
% \cs{poemtitlestarmark}\marg{poemf@hdr} is for marks for \cs{PoemTitle*}. 
% The \cs{poemtitlepstyle} and \cs{poemtitlestarpstyle} macros are provided
% as hooks so that, for example, pagestyles can be set for the regular
% and starred versions of \cs{PoemTitle}. By default these macros do nothing.
%    \begin{macrocode}
\newcommand*{\poemtitlestarmark}[1]{}
\newcommand*{\poemtitlepstyle}{}
\newcommand*{\poemtitlestarpstyle}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\PoemTitle}
%    The command to produce a article style chapter-like (numbered) poem title.
% \changes{v1.618}{2005/09/09}{Added \cs{PoemTitle}}
%    \begin{macrocode}
\newcommand\PoemTitle{%
  \par
  \@afterindentfalse
  \@ifstar{\@m@msPoemTitle}{\@m@mPoemTitle}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@m@mPoemTitle}
% \begin{macro}{\poemt@c}
% Intermediate and support macros for the extra optional argument
% to \cs{PoemTitle}. Have to do this long windedly otherwise dear old
% \Lpack{hyperref} barfs.
%    \begin{macrocode}
\newcommand{\@m@mPoemTitle}[1][]{%
  \def\poemt@c{#1}% capture first optional arg
  \@ifnextchar[{\@PoemTitle}{\@PoemTitle[]}%
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memPoemTitleinfo}
% \begin{macro}{\memPoemTitlestarinfo}
% \verb?\memPoemTitleinfo{num}{toc}{head}{full}? \\
% \verb?\memPoemTitlestarinfo{short}{full}?
%    \begin{macrocode}
\newcommand{\memPoemTitleinfo}[4]{}
\newcommand{\memPoemTitlestarinfo}[2]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@PoemTitle}
% \begin{macro}{\poemf@rtoc}
% \begin{macro}{\poemf@rhdr}
% \cs{@PoemTitle}\oarg{tocmark}\marg{title}
% typesets the title of a \cs{PoemTitle}. 
% There is a number for \cs{@numptitletrue} and \cs{@mainmattertrue}.
%    \begin{macrocode}
\def\@PoemTitle[#1]#2{%
  \phantomsection
  \ifx\poemt@c\@empty % no optional args
    \def\poemf@rtoc{#2}%
    \def\poemf@rhdr{#2}%
  \else                  % at least one opt arg
    \let\poemf@rtoc\poemt@c
    \ifx\@empty#1\@empty
      \let\poemf@rhdr\poemt@c
    \else
      \def\poemf@rhdr{#1}%
    \fi
  \fi
  \m@m@Andfalse
  \if@numptitle
    \if@mainmatter
      \m@m@Andtrue
    \fi
  \fi
  \ifm@m@And
    \refstepcounter{poem}%
  \fi
%    \end{macrocode}
% Store the (short) title via \cs{poemtitlemark} and call
% \cs{\@makePoemTitlehead} to do the typesetting.
%    \begin{macrocode}
  \@makePoemTitlehead{#2}%
  \@afterheading
  \poemtitlemark{\poemf@rhdr}%
  \poemtitlepstyle
%    \end{macrocode}
% Add the title to the ToC.
%    \begin{macrocode}
  \ifm@m@And
    \addcontentsline{toc}{\poemtoc}{%
      \protect\numberline{\thepoem}\poemf@rtoc}%
    \memPoemTitleinfo{\thepoem}{\poemf@rtoc}{\poemf@rhdr}{#2}%
  \else
    \addcontentsline{toc}{\poemtoc}{\poemf@rtoc}%
    \memPoemTitleinfo{}{\poemf@rtoc}{\poemf@rhdr}{#2}%
  \fi
%    \end{macrocode}
% Add hook for title referencing.
%    \begin{macrocode}
  \ifheadnameref\M@gettitle{\poemf@rhdr}\else\M@gettitle{\poemf@rtoc}\fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@makePoemTitlehead}
% This \emph{really} typesets a \cs{PoemTitle}. Leave some whitespace.
%    \begin{macrocode}
\def\@makePoemTitlehead#1{{%
  \PoemTitleheadstart
  \parindent \z@ \normalfont
%    \end{macrocode}
% If there is a number, typeset it, otherwise call \cs{printPoemTitlenonum}.
%    \begin{macrocode}
   \ifm@m@And
     \printPoemTitlenum 
     \afterPoemTitlenum
   \else
     \printPoemTitlenonum
   \fi
%    \end{macrocode}
% Typeset the title.
%    \begin{macrocode}
   \interlinepenalty\@M
   \printPoemTitletitle{#1}% 
   \afterPoemTitle}}

%    \end{macrocode}
% \end{macro}
%
%
%
% \begin{macro}{\@PTchs@def@ult}
% This sets up all the definitions used in \cs{@makePoemTitlehead}
% and \cs{@makesPoemTitlehead}.
% \begin{macro}{\PoemTitleheadstart}
% \begin{macro}{\printPoemTitlenum}
% \begin{macro}{\afterPoemTitlenum}
% \begin{macro}{\printPoemTitlenonum}
% \begin{macro}{\printPoemTitletitle}
% \begin{macro}{\afterPoemTitle}
%    \begin{macrocode}
\newcommand{\@PTchs@def@ult}{%
  \def\PoemTitleheadstart{\vspace{\beforePoemTitleskip}}
  \def\printPoemTitlenum{\PoemTitlenumfont \thepoem}
  \def\afterPoemTitlenum{\par\nobreak\vskip \midPoemTitleskip}
  \def\printPoemTitlenonum{}
  \def\printPoemTitletitle##1{\PoemTitlefont ##1}
  \def\afterPoemTitle{\par\nobreak\vskip \afterPoemTitleskip}}
\@PTchs@def@ult

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% 
% \begin{macro}{\PoemTitlenumfont}
% \begin{macro}{\PoemTitlefont}
% Fonts for setting the Poem Title number and title.
%    \begin{macrocode}
\newcommand*{\PoemTitlenumfont}{\normalfont\large\centering}
\newcommand*{\PoemTitlefont}{\normalfont\large\centering}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\beforePoemTitleskip}
% \begin{macro}{\midPoemTitleskip}
% \begin{macro}{\afterPoemTitleskip}
% Lengths separating the various parts of a Poem Title heading.
%    \begin{macrocode}
\newlength{\beforePoemTitleskip}
  \setlength{\beforePoemTitleskip}{1\onelineskip}
\newlength{\midPoemTitleskip}
  \setlength{\midPoemTitleskip}{0pt}
\newlength{\afterPoemTitleskip}
  \setlength{\afterPoemTitleskip}{1\onelineskip}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@m@msPoemTitle}
% This deals with the optional argument for starred PoemTitles.
%    \begin{macrocode}
\newcommand{\@m@msPoemTitle}[2][\@empty]{%
  \@sPoemTitle{#2}%
  \ifx \@empty#1
    \def\poemf@rhdr{#2}%
  \else   % opt arg
    \def\poemf@rhdr{#1}%
  \fi
  \poemtitlestarmark{\poemf@rhdr}%
  \poemtitlestarpstyle
  \memPoemTitlestarinfo{\poemf@rhdr}{#2}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@sPoemTitle}
% \cs{@sPoemTitle}\marg{long} typesets the title of a 
% \cs{PoemTitle*}. It is easier than the \cs{@PoemTitle} as there is no number
% or ToC entry to worry about.
%    \begin{macrocode}
\newcommand{\@sPoemTitle}[1]{%
  \@makesPoemTitlehead{#1}%
  \@afterheading
  \M@gettitle{#1}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@makesPoemTitlehead}
% This \emph{really} typesets a \cs{PoemTitle*}, and is similar to 
% \cs{@makePoemTitlehead}.
%    \begin{macrocode}
\def\@makesPoemTitlehead#1{{%
  \PoemTitleheadstart
  \parindent \z@ \normalfont
  \printPoemTitlenonum
  \interlinepenalty\@M
  \printPoemTitletitle{#1}
  \afterPoemTitle}}

%    \end{macrocode}
% \end{macro}
%
%
%
%
% \section{Setting parameters for existing environments}
%
% \subsection{Array and tabular}
%
% \begin{macro}{\arraycolsep}
%    The columns in an array environment are separated by
%    2\cs{arraycolsep}.
%    \begin{macrocode}
\setlength\arraycolsep{5\p@}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\tabcolsep}
%    The columns in an tabular environment are separated by
%    2\cs{tabcolsep}.
%    \begin{macrocode}
\setlength\tabcolsep{6\p@}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\arrayrulewidth}
%    The width of rules in the array and tabular environments is given
%    by\\ \cs{arrayrulewidth}.
%    \begin{macrocode}
\setlength\arrayrulewidth{.4\p@}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\doublerulesep}
%    The space between adjacent rules in the array and tabular
%    environments is given by \cs{doublerulesep}.
%    \begin{macrocode}
\setlength\doublerulesep{2\p@}
%    \end{macrocode}
% \end{macro}
%
% \subsection{Tabbing}
%
% \begin{macro}{\tabbingsep}
%    This controls the space that the \verb?\'? command puts in. (See
%    \LaTeX{} manual for an explanation.)
%    \begin{macrocode}
\setlength\tabbingsep{\labelsep}

%    \end{macrocode}
% \end{macro}
%
% \subsection{Minipage}
%
% \begin{macro}{\@minipagerestore}
%    The macro \cs{@minipagerestore} is called upon entry to a minipage
%    environment to set up things that are to be handled differently
%    inside a minipage environment. In the standard styles it does
%    nothing, as was the case originally for memoir.
%
% Memoir extends it to support verbatim footnotes (see later) in minipages
% and also for abnormal parskips (see later).
% \changes{v1.61803}{2008/01/30}{Collected \cs{@minipagerestore} modifications together}
%    \begin{macrocode}
\newcommand{\@minipagerestore}{%
%    \end{macrocode}
% For \cs{verbfootnote} to work in a minipage we have to use 
% \cs{@verbmpfootnotetext} instead of \cs{@verbfootnotetext}.
%    \begin{macrocode}
  \let\@verbfootnotetext\@verbmpfootnotetext
%    \end{macrocode}
% The next is for enabling the extended footnotes in a minipage.
%    \begin{macrocode}
  \m@mdoextrafeetmini
%    \end{macrocode}
% And this is for abnormal parskips.
%    \begin{macrocode}
  \ifm@mnzpskip \parskip=\m@mabparskip\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@mpfootins}
%    Minipages have their own footnotes; \verb?\skip\@mpfootins? plays
%    the same r\^ole for footnotes in a minipage as \verb?\skip\footins? does
%    for ordinary footnotes.
%
%    \begin{macrocode}
\skip\@mpfootins = \skip\footins

%    \end{macrocode}
% \end{macro}
%
% \subsection{Framed boxes}
%
% \begin{macro}{\fboxsep}
%    The space left by \cs{fbox} and \cs{framebox} between the box and the
%    text in it.
% \begin{macro}{\fboxrule}
%    The width of the rules in the box made by \cs{fbox} and \cs{framebox}.
%    \begin{macrocode}
\setlength\fboxsep{3\p@}
\setlength\fboxrule{.4\p@}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \subsection{Equation and eqnarray}
%
% \begin{macro}{\theequation}
%    The equation counter will be reset at beginning of a new chapter
%    and the equation number will be prefixed by the chapter number.
%
%    This code  must follow the \cs{chapter} definition, or more exactly
%    the definition of the chapter counter.
%    \begin{macrocode}
\@addtoreset{equation}{chapter}
\renewcommand{\theequation}{%
  \ifnum \c@chapter>\z@ \thechapter.\fi \@arabic\c@equation}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\jot}
%    \cs{jot} is the extra space added between lines of an eqnarray
%    environment. The default value is used.
%    \begin{macrocode}
% \setlength\jot{3pt}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@eqnnum}
%    The macro \cs{@eqnnum} defines how equation numbers are to appear in
%    equations. Again the default is used.
%
%    \begin{macrocode}
% \def\@eqnnum{(\theequation)}

%    \end{macrocode}
% \end{macro}
%
%
% \section{Array and tabularx}
%
% \subsection{Array}%
%
% Here ealier versions of the class had an embedded copy of the
% \Lpack{array} package. Now replaced by requiring the packge instead.
%    \begin{macrocode}
\RequirePackage{array}[2018/04/30]
%    \end{macrocode}
% The embeded copy is outcommented for now and will be removed in a
% later version.
%
% \changes{v3.7h}{2018/09/06}{Outcommented the embedded copy of
% \Lpack{array} and replaced it with requiring the \Lpack{array} package
% instead.}
%
% ^^A % The description and code are essentially copied from the \Lpack{array}
% ^^A package~\cite{ARRAY}.
% ^^A
%    \begin{macrocode}
 % 
 % %%%%%%%%%% Array package code %%%%%%%%%%%%%%%%%%%%%
 % %%%%%%%%%% With acknowledgements to %%%%%%%%%%%%%%%%%%%%%
 % %%%%%%%%%% Frank Mittelbach & David Carlisle %%%%%%%%%%%%%%%%%%%%%
 % 
 % %%%%%%%%%% Copy corresponds to array.sty 2016/10/06 v2.4d %%%%%%%%% 
%    \end{macrocode}
% ^^A \changes{v3.7g}{2018/03/05}{Updated the embedded copy of the
% ^^A \Lpack{array} package to version 2.4d, 2016/10/06}
% ^^A \begin{dlf}
% ^^A  dlf: The \Lpack{array} package has redundant code (caused by a
% ^^A  quick mashing of and earlier \Lpack{array} version and the
% ^^A  \Lpack{newaray} package). In thus update (2018/03/05) this
% ^^A  redundant code is \emph{not} removed as it makes it very hard to
% ^^A  see where there are class changes to the \Lpack{array} code, and
% ^^A  when stuff is simply removed. We'll leave it up to the LaTeXteam to
% ^^A  clean up the \Lpack{array} code at some point.
% ^^A
% ^^A The following is a carbon copy of the DTX code from
% ^^A \verb|array.dtx|, package specific \cs{changes} lines have been
% ^^A removed, and we have made any error/warning messages class specific,
% ^^A instead of package specific.
% ^^A \end{dlf}
% ^^A
% ^^A 
% ^^A \subsubsection{The construction of the preamble}
% ^^A
% ^^A It is obvious that those environments will consist mainly of an
% ^^A \verb=\halign=, because \TeX\ typesets tables using this primitive.
% ^^A That is why we will now take a look at the algorithm which determines
% ^^A a preamble for a \verb=\halign= starting with a given user preamble
% ^^A using the options mentioned above.
% ^^A
% ^^A The most interesting macros of this implementation are without doubt
% ^^A those which are responsible for the construction of the preamble for
% ^^A the \verb=\halign=. The underlying algorithm was developed by
% ^^A \textsc{Lamport} (resp.\ \textsc{Knuth}, see texhax V87\#??), and it
% ^^A has been extended and improved.
% ^^A
% ^^A The user preamble will be read \textsf{token} by \textsf{token}.  A
% ^^A \textsf{token} is a single character like \texttt{c} or a block
% ^^A enclosed in \verb={...}=. For example the preamble of
% ^^A \verb=\begin{tabular}=\linebreak[0]\verb={lc||c@{\hspace{1cm}}}= consists of
% ^^A the \textsf{token} \texttt{l}, \texttt{c}, \texttt{|}, \texttt{|},
% ^^A \texttt{@} and \verb=\hspace{1cm}=.
% ^^A
% ^^A The currently used \textsf{token} and the one, used before, are needed
% ^^A to decide on how the construction of the preamble has to be
% ^^A continued.
% ^^A In the example mentioned above the \texttt{l} causes the preamble
% ^^A to begin with \verb=\hskip\tabcolsep=. Furthermore
% ^^A \verb=# \hfil= would be appended to define a flush left column.
% ^^A The next \textsf{token} is a \texttt{c}. Because it was preceded by an
% ^^A \texttt{l} it generates a new column. This is done with
% ^^A \verb=\hskip \tabcolsep & \hskip \tabcolsep=. The column which is to
% ^^A be centered will be appended with \verb=\hfil # \hfil=.
% ^^A The \textsf{token} \texttt{|} would then add a space of
% ^^A \verb=\hskip \tabcolsep=
% ^^A and a vertical line because the last
% ^^A \textsf{tokens} was a \texttt{c}.
% ^^A The following \textsf{token} \texttt{|} would only add a space
% ^^A \verb=\hskip \doublerulesep= because it was preceded by the
% ^^A \textsf{token} \texttt{|}. We will not discuss our example further but
% ^^A  rather take a look at the general case of constructing preambles.
% ^^A
% ^^A The example shows that the desired preamble for the
% ^^A \verb=\halign= can be constructed as soon as the action of all
% ^^A combinations
% ^^A of the preamble \textsf{tokens} are specified. There are 18 such
% ^^A \textsf{tokens}
% ^^A so we have $19 \cdot 18 = 342$ combinations if we count the
% ^^A beginning of
% ^^A the preamble as a special \textsf{token}. Fortunately, there are many
% ^^A combinations which generate the same spaces, so we can define
% ^^A \textsf{token} classes. We will identify a
% ^^A \textsf{token} within a class with a number, so we can insert the
% ^^A formatting (for example of a column).
% ^^A Table~\ref{tab:Klassen} lists all \textsf{token} classes and
% ^^A their corresponding numbers.
% ^^A \begin{table}[ht]
% ^^A \begin{center}
% ^^A       \begin{tabular}[t]{>{\ttfamily}ccc}
% ^^A       \textsf{token} & \verb=\@chclass= & \verb=\@chnum= \\[2mm]
% ^^A       c   & 0  & 0 \\
% ^^A       l   & 0  & 1 \\
% ^^A       r   & 0  & 2 \\
% ^^A       p-arg    & 0  & 3 \\
% ^^A       t-arg    & 0  & 4 \\
% ^^A       b-arg    & 0  & 5 \\
% ^^A       |   & 1  & 0 \\
% ^^A       !-arg    & 1  & 1 \\
% ^^A       <-arg    & 2  & --- \\
% ^^A       >-arg    & 3  & ---
% ^^A    \end{tabular}
% ^^A    \kern3mm \vrule \kern3mm%
% ^^A    \begin{tabular}[t]{>{\ttfamily}ccc}
% ^^A       \textsf{token} & \verb=\@chclass= & \verb=\@chnum= \\[2mm]
% ^^A       Start    & 4  & --- \\
% ^^A       @-arg    & 5  & --- \\
% ^^A       !   & 6  & --- \\
% ^^A       @   & 7  & --- \\
% ^^A       <   & 8  & --- \\
% ^^A       >   & 9  & --- \\
% ^^A       p   & 10 & 3 \\
% ^^A       t   & 10 & 4 \\
% ^^A       b   & 10 & 5
% ^^A    \end{tabular}
% ^^A \end{center}
% ^^A \caption{Classes of preamble \textsf{tokens}}
% ^^A \label{tab:Klassen}
% ^^A \end{table}
% ^^A
% ^^A
% ^^A \begin{macro}{\@chclass}
% ^^A \begin{macro}{\@chnum}
% ^^A \begin{macro}{\@lastchclass}
% ^^A    The class and the number of the current \textsf{token} are saved in
% ^^A    the
% ^^A    \textsf{count} registers \verb=\@chclass=
% ^^A    and \verb=\@chnum=, while the class of the previous
% ^^A    \textsf{token} is stored in the
% ^^A    \textsf{count} register \verb=\@lastchclass=.
% ^^A    All of the mentioned registers are already allocated in
% ^^A    \texttt{latex.tex},
% ^^A    which is the reason why the following three lines of code are
% ^^A    commented out.
% ^^A    Later throughout the text I will not mention it again explicitly
% ^^A    whenever I use a \verb=%= sign. These parts are already defined in
% ^^A    \texttt{latex.tex}.
%    \begin{macrocode}
 % % \newcount \@chclass
 % % \newcount \@chnum
 % % \newcount \@lastchclass
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \end{macro}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A
% ^^A \begin{macro}{\@addtopreamble}
% ^^A    We will save the already constructed preamble for
% ^^A    the \verb=\halign=
% ^^A    in the global macro \verb=\@preamble=. This will then be
% ^^A     enlarged with
% ^^A    the command \verb=\@addtopreamble=.
%    \begin{macrocode}
 % \def\@addtopreamble#1{\xdef\@preamble{\@preamble #1}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A
% ^^A
% ^^A
% ^^A \subsubsection{The character class of a \textsf{token}}
% ^^A
% ^^A \begin{macro}{\@testpach}
% ^^A    With the help of \verb=\@lastchclass= we can now define a macro
% ^^A    which determines the class and the number of a given preamble
% ^^A    \textsf{token}
% ^^A    and assigns them to the registers
% ^^A    \verb=\@chclass= and \verb=\@chnum=.
%    \begin{macrocode}
 % \def\@testpach{\@chclass
%    \end{macrocode}
% ^^A    First we deal with the cases in which the \textsf{token}
% ^^A    (\verb=#1=) is the argument of \texttt{!}, \texttt{@}, \texttt{<} or
% ^^A    \texttt{>}. We can see this from the value of \verb=\@lastchclass=:
%    \begin{macrocode}
 %  \ifnum \@lastchclass=6 \@ne \@chnum \@ne \else
 %   \ifnum \@lastchclass=7 5 \else
 %    \ifnum \@lastchclass=8 \tw@ \else
 %     \ifnum \@lastchclass=9 \thr@@
%    \end{macrocode}
% ^^A    Otherwise we will assume that the \textsf{token} belongs to the
% ^^A    class $0$
% ^^A    and assign the corresponding number to \verb=\@chnum= if our
% ^^A    assumption is correct.
%    \begin{macrocode}
 %    \else \z@
%    \end{macrocode}
% ^^A    If the last \textsf{token} was a \texttt{p}, \texttt{m} or a
% ^^A    \texttt{b}, \verb=\@chnum= already has the right value. This is the
% ^^A    reason for the somewhat curious choice of the \textsf{token}
% ^^A    numbers in class $10$.
%    \begin{macrocode}
 %    \ifnum \@lastchclass = 10 \else
%    \end{macrocode}
% ^^A    Otherwise we will check if \verb=\@nextchar= is either a \texttt{c},
% ^^A    \texttt{l} or an \texttt{r}.  Some applications change the
% ^^A    catcodes of certain characters like ``\texttt{@}'' in
% ^^A    \texttt{amstex.sty}. As a result the tests below would fail since
% ^^A    they assume non-active character tokens. Therefore we evaluate
% ^^A    \verb=\@nextchar= once thereby turning the first token of its
% ^^A    replacement text into a char. At this point here this should have
% ^^A    been the only char present in \verb=\@nextchar= which put into via a
% ^^A    \verb=\def=.
%    \begin{macrocode}
 %    \edef\@nextchar{\expandafter\string\@nextchar}%
 %    \@chnum
 %    \if \@nextchar c\z@ \else
 %     \if \@nextchar l\@ne \else
 %      \if \@nextchar r\tw@ \else
%    \end{macrocode}
% ^^A    If it is a different \textsf{token}, we know that the class was
% ^^A    not $0$. We assign the value $0$ to \verb=\@chnum= because this value
% ^^A    is needed for the \texttt{|}--\textsf{token}. Now we must check
% ^^A    the remaining classes.  Note that the value of \verb=\@chnum= is
% ^^A    insignificant here for most classes.
%    \begin{macrocode}
 %    \z@ \@chclass
 %    \if\@nextchar |\@ne \else
 %     \if \@nextchar !6 \else
 %      \if \@nextchar @7 \else
 %       \if \@nextchar <8 \else
 %        \if \@nextchar >9 \else
%    \end{macrocode}
% ^^A    The remaining permitted \textsf{tokens} are \texttt{p},
% ^^A    \texttt{m} and \texttt{b} (class $10$).
%    \begin{macrocode}
 %   10
 %   \@chnum
 %   \if \@nextchar m\thr@@\else
 %    \if \@nextchar p4 \else
 %     \if \@nextchar b5 \else
%    \end{macrocode}
% ^^A    Now the only remaining possibility is a forbidden \textsf{token},
% ^^A    so we choose class $0$ and number $0$ and give an error message.
% ^^A    Then we finish the macro by closing all \verb=\if='s.
%    \begin{macrocode}
 %    \z@ \@chclass \z@ \@preamerr \z@ \fi \fi \fi \fi
 %    \fi \fi  \fi  \fi  \fi  \fi  \fi \fi \fi \fi \fi \fi}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A
% ^^A
% ^^A
% ^^A \subsubsection{Multiple columns ($*$--form)}
% ^^A
% ^^A \begin{macro}{\@xexpast}
% ^^A \begin{macro}{\the@toks}
% ^^A \begin{macro}{\the@toksz}
% ^^A    \label{@xexpast} Now we discuss the macro that deletes all forms
% ^^A    of type \verb=*{=\textit{N\/}\verb=}{=\textit{String\/}\verb=}= from a user
% ^^A    preamble and replaces them with \textit{N} copies of
% ^^A    \textit{String}.  Nested $*$--expressions are dealt with
% ^^A    correctly, that means $*$--expressions are not substituted if
% ^^A    they are in explicit braces, as in \verb=@{*}=.
% ^^A
% ^^A    This macro is called via
% ^^A    \verb=\@xexpast=\meta{preamble}\verb=*0x\@@=.
% ^^A    The $*$--expression \verb=*0x= is being used to terminate the
% ^^A    recursion,
% ^^A    as we shall see later, and \verb=\@@= serves as an argument
% ^^A    delimiter. \verb=\@xexpast= has four arguments. The first
% ^^A    one is the part of the
% ^^A    user preamble before the first $*$--expression while the second
% ^^A    and third ones are the arguments of the first $*$--expression
% ^^A    (that is \textit{N} and \textit{String} in the notation mentioned
% ^^A    above).
% ^^A    The fourth argument is the rest of the preamble.
%    \begin{macrocode}
 % \def\@xexpast#1*#2#3#4\@@{%
%    \end{macrocode}
% ^^A    The number of copies of \textit{String} (\verb=#2=) that are to be
% ^^A    produced will be saved in a \textsf{count} register.
%    \begin{macrocode}
 %    \@tempcnta #2
%    \end{macrocode}
% ^^A    We save the part of the preamble which does not
% ^^A    contain a $*$--form (\verb=#1=)
% ^^A    in a \PlainTeX\ \textsf{token} register.
% ^^A    We also save \textit{String} (\verb=#3=) using a \LaTeX\
% ^^A    \textsf{token} register.
%    \begin{macrocode}
 %    \toks@={#1}\@temptokena={#3}%
%    \end{macrocode}
% ^^A    Now we have to use a little trick to produce \textit{N} copies of
% ^^A    \textit{String}.
% ^^A    We could try \verb=\def\@tempa{#1}= and then
% ^^A    \textit{N} times \verb=\edef\@tempa{\@tempa#3}=. This would have the
% ^^A    undesired effect that all macros within \verb=#1= and \verb=#3=
% ^^A    would be expanded, although, for example, constructions like
% ^^A    \verb=@{..}= are not supposed to be changed.
% ^^A    That is why we \verb=\let= two control sequences to
% ^^A    be equivalent to \verb=\relax=.
%    \begin{macrocode}
 %    \let\the@toksz\relax \let\the@toks\relax
%    \end{macrocode}
% ^^A    Then we ensure that \verb=\@tempa= contains
% ^^A    \verb={\the@toksz\the@toks...\the@toks}= (the macro
% ^^A    \verb=\the@toks= exactly \textit{N\/} times) as substitution text.
%    \begin{macrocode}
 %    \def\@tempa{\the@toksz}%
 %    \ifnum\@tempcnta >0 \@whilenum\@tempcnta >0\do
 %      {\edef\@tempa{\@tempa\the@toks}\advance \@tempcnta \m@ne}%
%    \end{macrocode}
% ^^A    If \textit{N\/} was greater than zero we prepare for another call
% ^^A    of \verb=\@xexpast=. Otherwise we assume we have reached the end of
% ^^A    the user preamble, because we had appended \verb=*0x\@@= when we first
% ^^A    called \verb=\@xexpast=.  In other words: if the user inserts
% ^^A    \verb=*{0}{..}= in his preamble, \LaTeX\ ignores the rest of it.
%    \begin{macrocode}
 %        \let \@tempb \@xexpast \else
 %        \let \@tempb \@xexnoop \fi
%    \end{macrocode}
% ^^A    Now we will make sure that the part of the user preamble, which
% ^^A    was already dealt with, will be saved again in \verb=\@tempa=.
%    \begin{macrocode}
 %    \def\the@toksz{\the\toks@}\def\the@toks{\the\@temptokena}%
 %    \edef\@tempa{\@tempa}%
%    \end{macrocode}
% ^^A    We have now evaluated the first $*$--expression, and the user
% ^^A    preamble up to this point
% ^^A    is saved in \verb=\@tempa=. We will put the contents of
% ^^A    \verb=\@tempa= and the rest of the user preamble together and work
% ^^A    on the result with \verb=\@tempb=. This macro either corresponds
% ^^A    to \verb=\@xexpast=, so that the next
% ^^A    $*$--expression is handled, or to the macro \verb=\@xexnoop=,
% ^^A    which only ends the recursion by deleting its argument.
%    \begin{macrocode}
 %    \expandafter \@tempb \@tempa #4\@@}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \end{macro}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\@xexnoop}
% ^^A    So the first big problem is solved. Now it is easy to
% ^^A    specify \verb=\@xexnoop=.
% ^^A    Its argument is delimited by \verb=\@@= and it simply expands to
% ^^A    nothing.
%    \begin{macrocode}
 % %  \def\@xexnoop#1\@@{}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A
% ^^A
% ^^A \subsubsection{The insertion of declarations
% ^^A           (\texttt{>}, \texttt{<}, \texttt{!}, \texttt{@})}
% ^^A
% ^^A
% ^^A The preamble will be enlarged with the help of \verb=\xdef=, but the
% ^^A arguments of \texttt{>}, \texttt{<},~\texttt{!}\ and \texttt{@} are
% ^^A not supposed to be expanded during the construction (we want an
% ^^A implementation that doesn't need a \verb=\protect=). So we have to find a
% ^^A way to inhibit the expansion of those arguments.
% ^^A
% ^^A We will solve this problem with \textsf{token} registers. We need
% ^^A one register for every \texttt{!}\ and \texttt{@}, while we need two
% ^^A for every \texttt{c}, \texttt{l}, \texttt{r}, \texttt{m}, \texttt{p}
% ^^A or \texttt{b}. This limits the number of columns of a table because
% ^^A there are only 256 \textsf{token} registers. But then, who needs
% ^^A tables with more than 100 columns?
% ^^A
% ^^A One could also find a solution which only needs two or three
% ^^A \textsf{token} registers by proceeding similarly as in the macro
% ^^A \verb=\@xexpast= (see page \pageref{@xexpast}). The advantage of our
% ^^A approach is the fact that we avoid some of the problems that arise
% ^^A with the other method\footnote{Maybe there are also historical
% ^^A  reasons.}.
% ^^A
% ^^A So how do we proceed? Let us assume that we had \verb=!{foo}= in the
% ^^A user preamble and say we saved \texttt{foo} in
% ^^A \textsf{token} register $5$. Then we call
% ^^A \verb=\@addtopreamble{\the@toks5}= where
% ^^A \verb=\the@toks= is defined in a way that it does not expand
% ^^A (for example it could be equivalent to \verb=\relax=). Every
% ^^A following call
% ^^A of \verb=\@addtopreamble= leaves \verb=\the@toks5= unchanged in
% ^^A \verb=\@preamble=. If the construction of the preamble is completed
% ^^A we change the definition of \verb=\the@toks= to
% ^^A \verb=\the\toks= and expand \verb=\@preamble= for the last time.
% ^^A During this process all parts of the form
% ^^A    \verb=\the@toks=\meta{Number}
% ^^A will be substituted by the contents of the respective \textsf{token}
% ^^A registers.
% ^^A
% ^^A As we can see from this informal discussion the construction of the
% ^^A preamble has to take place within a group, so that the
% ^^A \textsf{token} registers we use will be freed later on. For that
% ^^A reason we keep all assignments to \verb=\@preamble= global; therefore the
% ^^A replacement text of this macro will remain the same after we leave
% ^^A the group.
% ^^A
% ^^A \begin{macro}{\count@}
% ^^A    We further need a \textsf{count} register to remember which
% ^^A    \textsf{token} register is to be used next. This will be
% ^^A    initialized with $-1$ if we want to begin with the \textsf{token}
% ^^A    register $0$. We use the \PlainTeX\ scratch register \verb=\count@=
% ^^A    because everything takes place locally. All we have to do is
% ^^A    insert \verb=\the@toks= \verb=\the= \verb=\count@= into the preamble.
% ^^A    \verb=\the@toks= will remain unchanged and \verb=\the\count@= expands into
% ^^A    the saved number.
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\prepnext@tok}
% ^^A    The macro \verb=\prepnext@tok= is in charge of preparing the next
% ^^A    \textsf{token} register. For that purpose we increase
% ^^A    \verb=\count@= by $1$:
%    \begin{macrocode}
 % \def\prepnext@tok{\advance \count@ \@ne
%    \end{macrocode}
% ^^A    Then we locally delete any contents the
% ^^A    \textsf{token} register might have.
%    \begin{macrocode}
 %    \toks\count@{}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\save@decl}
% ^^A    During the construction of the preamble the current
% ^^A    \textsf{token} is always saved in the macro \verb=\@nextchar= (see the
% ^^A    definition of \verb=\@mkpream= on page \pageref{@mkpream}). The macro
% ^^A    \verb=\save@decl= saves it into the next free \textsf{token} register,
% ^^A    i.e.\ in \verb=\toks\count@=.
%    \begin{macrocode}
 % \def\save@decl{\toks\count@ \expandafter{\@nextchar}}
%    \end{macrocode}
% ^^A    The reason for the  use of \verb=\relax= is the following
% ^^A    hypothetical situation in the preamble:
% ^^A    \quad \verb=..\the\toks1\the\toks2..= \quad \TeX\ expands
% ^^A    \verb=\the\toks2= first in order to find out if the digit \verb=1=
% ^^A    is followed by other digits. E.g.\ a \verb=5= saved in the
% ^^A    \textsf{token} register $2$ would lead \TeX\ to insert the contents
% ^^A    of \textsf{token} register $15$ instead of $1$ later on.
% ^^A
% ^^A The example above referred to an older version of \verb=\save@decl= which
% ^^A inserted a \verb=\relex= inside the token register. This is now moved to
% ^^A the places where the actual token registers are inserted (look for
% ^^A \verb=\the@toks=) because the old version would still make= @=
% ^^A expressions to moving arguments since after expanding the second
% ^^A register while looking for the end of the number the contents of the
% ^^A token register is added so that later on the whole register will be
% ^^A expanded.  This serious bug was found after nearly two years
% ^^A international use of this package  by Johannes Braams.
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A
% ^^A How does the situation look like, if we want to add another column
% ^^A to the preamble, i.e.\ if we have found a \texttt{c}, \texttt{l},
% ^^A \texttt{r}, \texttt{p}, \texttt{m} or \texttt{b} in the user
% ^^A preamble?  In this case we have the problem of the \textsf{token}
% ^^A register from \verb=>{..}= and \verb=<{..}= having to be inserted at this
% ^^A moment because formatting instructions like \verb=\hfil= have to be set
% ^^A around them. On the other hand it is not known yet, if any \verb=<{..}=
% ^^A instruction will appear in the user preamble at all.
% ^^A
% ^^A We solve this problem by adding two \textsf{token} registers at a
% ^^A time.  This explains, why we have freed the \textsf{token} registers
% ^^A in \verb=\prepnext@tok=.
% ^^A
% ^^A \begin{macro}{\insert@column}
% ^^A \begin{macro}{\@sharp}
% ^^A    We now define the macro \verb=\insert@column= which will do
% ^^A    this work for us.
%    \begin{macrocode}
 % \def\insert@column{%
%    \end{macrocode}
% ^^A    Here, we assume that the \textsf{count} register
% ^^A    \verb=\@tempcnta= has saved the value $\verb=\count@= - 1$.
%    \begin{macrocode}
 %    \the@toks \the \@tempcnta
%    \end{macrocode}
% ^^A    Next follows the \verb=#= sign which specifies the place
% ^^A    where the text of the column shall be inserted. To avoid
% ^^A    errors during the expansions in
% ^^A    \verb=\@addtopreamble= we hide this sign in the command
% ^^A    \verb=\@sharp= which is temporarily occupied with
% ^^A    \verb=\relax= during the build-up of the preamble.
% ^^A    To remove unwanted spaces before and after the column text, we set
% ^^A    an \verb=\ignorespaces=  in front and a \verb=\unskip= afterwards.
%    \begin{macrocode}
 %    \ignorespaces \@sharp \unskip
%    \end{macrocode}
% ^^A    Then the second \textsf{token} register follows whose number should
% ^^A    be saved in \verb=\count@=.
% ^^A    We make sure that there will be no further expansion after reading
% ^^A    the number, by finishing with \verb=\relax=. The case above is not
% ^^A    critical since it is ended by \verb=\ignorespaces=.
%    \begin{macrocode}
 %    \the@toks \the \count@ \relax}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A
% ^^A
% ^^A \subsubsection{The separation of columns}
% ^^A
% ^^A \begin{macro}{\@addamp}
% ^^A    In the preamble a \verb=&= has to be inserted between any two columns;
% ^^A    before the first column there should not be a \verb=&=. As the user
% ^^A    preamble may start with a \texttt{|} we have to remember somehow
% ^^A    if we have already inserted a \verb=#= (i.e.\ a column). This is done
% ^^A    with the boolean variable \verb=\if@firstamp= that we test in
% ^^A    \verb=\@addamp=, the macro that inserts the \verb=&=.
%    \begin{macrocode}
 % %    \newif \@iffirstamp
 % %    \def\@addamp{\if@firstamp \@firstampfalse
 % %                 \else \@addtopreamble &\fi}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\@acol}
% ^^A \begin{macro}{\@acolampacol}
% ^^A \begin{macro}{\col@sep}
% ^^A    We will now define some abbreviations for the extensions,
% ^^A    appearing most often in the preamble build-up.
% ^^A    Here \verb=\col@sep= is a \textsf{dimen} register which is set
% ^^A    equivalent to \verb=\arraycolsep= in an \textsf{array}--environment,
% ^^A    otherwise it is set equivalent to \verb=\tabcolsep=.
%    \begin{macrocode}
 % \newdimen\col@sep
 % \def\@acol{\@addtopreamble{\hskip\col@sep}}
 % %    \def\@acolampacol{\@acol\@addamp\@acol}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \end{macro}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A \subsubsection{The macro \texttt{\textbackslash @mkpream}}
% ^^A
% ^^A \begin{macro}{\@mkpream}
% ^^A \begin{macro}{\the@toks}
% ^^A    \label{@mkpream}
% ^^A    Now we can define the macro which builds up the preamble for the
% ^^A    \verb=\halign=.
% ^^A    First we initialize \verb=\@preamble=, \verb=\@lastchclass=
% ^^A    and the boolean variable \verb=\if@firstamp=.
%    \begin{macrocode}
 % \def\@mkpream#1{\gdef\@preamble{}\@lastchclass 4 \@firstamptrue
%    \end{macrocode}
% ^^A    During the build-up of the preamble we cannot directly use the
% ^^A    \verb=#= sign; this would lead to an error message in the next
% ^^A    \verb=\@addtopreamble= call.
% ^^A    Instead, we use the command \verb=\@sharp= at places where later
% ^^A    a \verb=#= will be.
% ^^A    This command is at first given the meaning \verb=\relax=;
% ^^A    therefore it will not be expanded when the preamble
% ^^A    is extended.
% ^^A    In the macro \verb=\@array=, shortly before the \verb=\halign=
% ^^A    is carried out, \verb=\@sharp= is given its final meaning.
% ^^A
% ^^A    In a similar way,
% ^^A    we deal with the commands \verb=\@startpbox= and
% ^^A    \verb=\@endpbox=, although the reason is different here: these
% ^^A    macros expand in many \textsf{tokens} which would delay the
% ^^A    build-up of the preamble.
%    \begin{macrocode}
 %    \let\@sharp\relax \let\@startpbox\relax \let\@endpbox\relax
%    \end{macrocode}
% ^^A    Now we remove possible  $*$-forms in the user preamble with the
% ^^A    command \verb=\@xexpast=.  As we already know, this command saves
% ^^A    its result in the macro \verb=\@tempa=.
%    \begin{macrocode}
 %    \@xexpast #1*0x\@@
%    \end{macrocode}
% ^^A    Afterwards we initialize all registers and macros, that we need
% ^^A    for the build-up of the preamble.
% ^^A    Since we want to start with the \textsf{token} register $0$,
% ^^A    \verb=\count@= has to contain the value $-1$.
%    \begin{macrocode}
 %    \count@\m@ne
 %    \let\the@toks\relax
%    \end{macrocode}
% ^^A    Then we call up \verb=\prepnext@tok= in order to prepare the
% ^^A    \textsf{token} register $0$ for use.
%    \begin{macrocode}
 %    \prepnext@tok
%    \end{macrocode}
% ^^A    To evaluate the user preamble (without stars) saved in
% ^^A    \verb=\@tempa= we use the \LaTeX--macro \verb=\@tfor=.
% ^^A    The strange appearing construction with \verb=\expandafter= is
% ^^A    based on the fact that we have to put the replacement text of
% ^^A    \verb=\@tempa= and not the macro \verb=\@tempa= to this
% ^^A    \LaTeX--macro.
%    \begin{macrocode}
 %    \expandafter \@tfor \expandafter \@nextchar
 %     \expandafter :\expandafter =\@tempa \do
%    \end{macrocode}
% ^^A    The body of this loop (the group after the \verb=\do=)
% ^^A    is executed for one \textsf{token} at a time, whereas
% ^^A    the current \textsf{token} is saved in \verb=\@nextchar=.
% ^^A    At first we evaluate the current \textsf{token} with the already
% ^^A    defined macro \verb=\@testpach=, i.e.\ we assign to
% ^^A    \verb=\@chclass= the character class and to \verb=\@chnum=
% ^^A    the character number of this \textsf{token}.
%    \begin{macrocode}
 %    {\@testpach
%    \end{macrocode}
% ^^A    Then we branch out depending on the value of \verb=\@chclass= into
% ^^A    different macros that extend the preamble respectively.
%    \begin{macrocode}
 %    \ifcase \@chclass \@classz \or \@classi \or \@classii
 %      \or \save@decl \or \or \@classv \or \@classvi
 %      \or \@classvii \or \@classviii  \or \@classix
 %      \or \@classx \fi
%    \end{macrocode}
% ^^A    Two cases deserve our special attention: Since the current
% ^^A    \textsf{token} cannot have the character class $4$ (start) we
% ^^A    have skipped this possibility. If the character class is $3$,
% ^^A    only the content of \verb=\@nextchar= has to be saved into the current
% ^^A    \textsf{token} register; therefore we call up \verb=\save@decl=
% ^^A    directly and save a macro name.  After the preamble has been
% ^^A    extended we assign the value of \verb=\@chclass= to the counter
% ^^A    \verb=\@lastchclass= to assure that this information will be available
% ^^A    during the next run of the loop.
%    \begin{macrocode}
 %    \@lastchclass\@chclass}%
%    \end{macrocode}
% ^^A    After the loop has been finished space must still be added to
% ^^A    the created preamble, depending on the last \textsf{token}.
% ^^A    Depending on the value of \verb=\@lastchclass= we perform
% ^^A    the necessary operations.
%    \begin{macrocode}
 %    \ifcase\@lastchclass
%    \end{macrocode}
% ^^A    If the last class equals $0$ we add a
% ^^A    \verb=\hskip \col@sep=.
%    \begin{macrocode}
 %    \@acol \or
%    \end{macrocode}
% ^^A    If it equals $1$ we do not add any additional space so that the
% ^^A    horizontal lines do not exceed the vertical ones.
%    \begin{macrocode}
 %    \or
%    \end{macrocode}
% ^^A    Class $2$ is treated like class $0$ because a \verb=<{...}=  can
% ^^A    only directly follow after class $0$.
%    \begin{macrocode}
 %    \@acol \or
%    \end{macrocode}
% ^^A    Most of the other possibilities can only appear if the user
% ^^A    preamble was defective. Class $3$ is not allowed since after a
% ^^A    \verb=>{..}= there must always follow a \texttt{c}, \texttt{l},
% ^^A    \texttt{r}, \texttt{p},\texttt{m} or \texttt{b}. We report an
% ^^A    error and ignore the declaration given by \verb={..}=.
%    \begin{macrocode}
 %    \@preamerr \thr@@ \or
%    \end{macrocode}
% ^^A    If \verb=\@lastchclass= is $4$ the user preamble has been empty.
% ^^A    To continue, we insert a \verb=#= in the preamble.
%    \begin{macrocode}
 %    \@preamerr \tw@ \@addtopreamble\@sharp \or
%    \end{macrocode}
% ^^A    Class $5$ is allowed again. In this case
% ^^A    (the user preamble ends with \verb=@{..}=) we need not
% ^^A    do anything.
%    \begin{macrocode}
 %    \or
%    \end{macrocode}
% ^^A    Any other case means that the arguments to \verb=@=, \texttt{!},
% ^^A    \texttt{<}, \texttt{>}, \texttt{p}, \texttt{m} or \texttt{b} have
% ^^A    been forgotten. So we report an error and ignore the last
% ^^A    \textsf{token}.
%    \begin{macrocode}
 %    \else  \@preamerr \@ne \fi
%    \end{macrocode}
% ^^A    Now that the build-up of the preamble is almost finished we can
% ^^A    insert the \textsf{token} registers and therefore redefine
% ^^A    \verb=\the@toks=. The actual insertion, though, is performed
% ^^A    later.
%    \begin{macrocode}
 %    \def\the@toks{\the\toks}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A
% ^^A  \subsubsection{The macros \texttt{\textbackslash @classz}
% ^^A           to \texttt{\textbackslash @classx}}
% ^^A
% ^^A The preamble is extended by the macros \verb=\@classz= to
% ^^A \verb=\@classx= which are called by \verb=\@mkpream=
% ^^A  depending on \verb=\@lastchclass=
% ^^A (i.e. the character class of the last \textsf{token}).
% ^^A \begin{macro}{\@classx}
% ^^A    First we define =\@classx= because of its important r\^ole.
% ^^A    When it is called we find that the current
% ^^A    \textsf{token} is \texttt{p}, \texttt{m} or \texttt{b}.
% ^^A    That means that a new column has to start.
%    \begin{macrocode}
 % \def\@classx{%
%    \end{macrocode}
% ^^A    Depending on the value of \verb=\@lastchclass= different actions
% ^^A    must take place:
%    \begin{macrocode}
 %   \ifcase \@lastchclass
%    \end{macrocode}
% ^^A    If the last character class was $0$ we separate the columns by
% ^^A    \verb=\hskip\col@sep= followed by \verb=&= and another
% ^^A    \verb=\hskip\col@sep=.
%    \begin{macrocode}
 %   \@acolampacol \or
%    \end{macrocode}
% ^^A    If the last class was class $1$ --- that means that a vertical
% ^^A    line was
% ^^A    drawn, --- before this line a \verb=\hskip\col@sep= was inserted.
% ^^A    Therefore there has to be only a \verb=&= followed by
% ^^A    \verb=\hskip\col@sep=. But this \verb=&= may be inserted only
% ^^A    if this is not the first column. This process is controlled
% ^^A    by \verb=\if@firstamp= in the macro \verb=\addamp=.
%    \begin{macrocode}
 %   \@addamp \@acol \or
%    \end{macrocode}
% ^^A    Class $2$ is treated like class $0$ because \verb=<{...}= can only
% ^^A    follow after class $0$.
%    \begin{macrocode}
 %   \@acolampacol \or
%    \end{macrocode}
% ^^A    Class $3$ requires no actions because all things necessary have
% ^^A    been done by the preamble \textsf{token} \texttt{>}.
%    \begin{macrocode}
 %   \or
%    \end{macrocode}
% ^^A    Class $4$ means that we are at the beginning of the preamble.
% ^^A    Therefore we start the preamble with \verb=\hskip\col@sep= and
% ^^A    then call \verb=\@firstampfalse=. This makes sure that a later
% ^^A    \verb=\@addamp= inserts the character
% ^^A    \verb=&= into the preamble.
%    \begin{macrocode}
 %   \@acol \@firstampfalse \or
%    \end{macrocode}
% ^^A    For class $5$ \textsf{tokens} only the character \verb=&= is inserted
% ^^A    as a column separator. Therefore we call \verb=\@addamp=.
%    \begin{macrocode}
 %   \@addamp
%    \end{macrocode}
% ^^A    Other cases are impossible. For an example
% ^^A    $\verb=\@lastchclass= = 6$---as it might appear in a
% ^^A    preamble of the form \verb=...!p...=---\texttt{p} would have
% ^^A    been taken as an  argument of \texttt{!}\ by \verb=\@testpach=.
%    \begin{macrocode}
 %   \fi}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A \begin{macro}{\@classz}
% ^^A    If the character class of the last \textsf{token} is $0$ we have
% ^^A    \texttt{c}, \texttt{l}, \texttt{r} or an argument of \texttt{m},
% ^^A    \texttt{b} or\ \texttt{p}. In the first three cases the preamble
% ^^A    must be extended the same way as if we had class $10$. The
% ^^A    remaining two cases do not require any action because the space
% ^^A    needed was generated by the last \textsf{token} (i.e.\
% ^^A    \texttt{m}, \texttt{b} or \texttt{p}). Since \verb=\@lastchclass= has
% ^^A    the value $10$ at this point nothing happens when \verb=\@classx= is
% ^^A    called. So the macro \verb=\@chlassz= may start like this:
%    \begin{macrocode}
 % \def\@classz{\@classx
%    \end{macrocode}
% ^^A    According to the definition of \verb=\insert@column= we must store
% ^^A    the number of the \textsf{token} register in which a preceding
% ^^A    \verb=>{..}= might have stored its argument into
% ^^A    \verb=\@tempcnta=.
%    \begin{macrocode}
 %    \@tempcnta \count@
%    \end{macrocode}
% ^^A    To have $\verb=\count@= = \verb=\@tmpcnta= + 1$ we prepare
% ^^A    the next \textsf{token} register.
%    \begin{macrocode}
 %    \prepnext@tok
%    \end{macrocode}
% ^^A    Now the preamble must be extended with the column whose format
% ^^A    can be determined by \verb=\@chnum=.
%    \begin{macrocode}
 %    \@addtopreamble{\ifcase \@chnum
%    \end{macrocode}
% ^^A    If \verb=\@chnum= has the value $0$ a centered column has to be
% ^^A    generated.
% ^^A    So we begin with stretchable space.
%    \begin{macrocode}
 %       \hfil
%    \end{macrocode}
% ^^A    The command \verb=\d@llarbegin= follows expanding into \verb=\begingroup=
% ^^A    (in the \textsf{tabular}--environment) or into \verb=$=.  Doing this
% ^^A    (provided an appropriate setting of \verb=\d@llarbegin=) we achieve
% ^^A    that the contents of the columns of an \textsf{array}--environment
% ^^A    are set in math mode while those of a \textsf{tabular}--environment
% ^^A    are set in LR mode.
%    \begin{macrocode}
 %       \d@llarbegin
%    \end{macrocode}
% ^^A    Now we insert the contents of the two \textsf{token} registers
% ^^A    and the symbol
% ^^A    for the column entry (i.e.\ \verb=#= or
% ^^A    more precise \verb=\@sharp=) using \verb=\insert@column=.
%    \begin{macrocode}
 %       \insert@column
%    \end{macrocode}
% ^^A    We end this case with \verb=\d@llarend= and \verb=\hfil= where \verb=\d@llarend=
% ^^A    again is either \verb=$= or \verb=\endgroup=.
%    \begin{macrocode}
 %       \d@llarend \hfil \or
%    \end{macrocode}
% ^^A    The templates for \texttt{l} and \texttt{r} (i.e.\ \verb=\@chnum= $1$
% ^^A    or $2$) are generated the same way. Since one  \verb=\hfil= is
% ^^A    missing the text is moved to the relevant side.
% ^^A    The \verb=\kern\z@= is needed in case of an empty column
% ^^A    entry. Otherwise
% ^^A    the \verb=\unskip= in \verb=\insert@column= removes the
% ^^A    \verb=\hfil=. Changed to \verb=\hskip1sp= so that it interacts better with
% ^^A    \verb=\@bsphack=.
%    \begin{macrocode}
 %       \hskip1sp\d@llarbegin \insert@column \d@llarend \hfil \or
 %       \hfil\hskip1sp\d@llarbegin \insert@column \d@llarend \or
%    \end{macrocode}
% ^^A    The templates for \texttt{p}, \texttt{m} and \texttt{b} mainly
% ^^A    consist of a \textsf{box}. In case of \texttt{m} it is generated
% ^^A    by \verb=\vcenter=.  This command is allowed only in math
% ^^A    mode. Therefore we start with a~\verb=$=.
%    \begin{macrocode}
 %    $\vcenter%$ emacs
%    \end{macrocode}
% ^^A    The part of the templates which is the same in all three cases
% ^^A    (\texttt{p}, \texttt{m} and \texttt{b})
% ^^A    is built by the macros \verb=\@startpbox= and
% ^^A    \verb=\@endpbox=. \verb=\@startpbox= has an argument:
% ^^A    the width of the column which is stored in the current
% ^^A    \textsf{token} (i.e.\ \verb=\@nextchar=).
% ^^A    Between these two macros we find the well known
% ^^A    \verb=\insert@column=.
%    \begin{macrocode}
 %    \@startpbox{\@nextchar}\insert@column \@endpbox $\or%$ emacs
%    \end{macrocode}
% ^^A    The templates for \texttt{p} and \texttt{b} are generated in the
% ^^A    same way though we do not need the \verb=$= characters because we use
% ^^A    \verb=\vtop= or \verb=\vbox=.
%    \begin{macrocode}
 %    \vtop \@startpbox{\@nextchar}\insert@column \@endpbox \or
 %    \vbox \@startpbox{\@nextchar}\insert@column \@endpbox
%    \end{macrocode}
% ^^A    Other values for \verb=\@chnum= are impossible. Therefore we
% ^^A    end the arguments to \verb=\@addtopreamble= and \verb=\ifcase=.
% ^^A    Before we come to the end of \verb=\@classz= we have to
% ^^A    prepare the next \textsf{token} register.
%    \begin{macrocode}
 %   \fi}\prepnext@tok}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A \begin{macro}{\@classix}
% ^^A    In case of class $9$ (\texttt{>}--\textsf{token}) we first check
% ^^A    if the character class of the last
% ^^A    \textsf{token} was $3$. In this case we have a
% ^^A    user preamble of the form \verb=..>{...}>{...}..= which
% ^^A    is not allowed. We only give an error message and continue.
% ^^A    So the declarations defined by the first  \verb=>{...}=
% ^^A    are ignored.
%    \begin{macrocode}
 % \def\@classix{\ifnum \@lastchclass = \thr@@
 %        \@preamerr \thr@@ \fi
%    \end{macrocode}
% ^^A    Furthermore, we call up \verb=\@class10= because afterwards always a
% ^^A    new column is started by \texttt{c}, \texttt{l}, \texttt{r},
% ^^A    \texttt{p}, \texttt{m} or \texttt{b}.
%    \begin{macrocode}
 %        \@classx}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A
% ^^A \begin{macro}{\@classviii}
% ^^A    If the current \textsf{token} is a \texttt{<} the last character
% ^^A    class must be $0$. In this case it is not necessary to extend the
% ^^A    preamble. Otherwise we output an error message, set \verb=\@chclass=
% ^^A    to $6$ and call \verb=\@classvi=.  By doing this we achieve that
% ^^A    \texttt{<} is treated like \texttt{!}.
%    \begin{macrocode}
 % \def\@classviii{\ifnum \@lastchclass >\z@
 %       \@preamerr 4\@chclass 6 \@classvi \fi}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\@arrayrule}
% ^^A    There is only one incompatibility with the original definition:
% ^^A    the definition of \verb=\@arrayrule=. In the original a line without
% ^^A    width\footnote{So the space between \texttt{cc} and \texttt{c|c}
% ^^A    is equal.}  is created by multiple insertions of
% ^^A \verb=\hskip .5\arrayrulewidth=.
% ^^A    We only insert a vertical line into the
% ^^A    preamble.  This is done to prevent problems with \TeX's main
% ^^A    memory when generating tables with many vertical lines in them
% ^^A    (especially in the case of \textsf{floats}).
%    \begin{macrocode}
 % \def\@arrayrule{\@addtopreamble \vline}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\@classvii}
% ^^A    As a consequence it follows that in case of class $7$
% ^^A    (\verb=@= \textsf{token})  the preamble need not to be extended.
% ^^A    In the original definition $\verb=\@lastchclass= = 1$
% ^^A    is treated by inserting \verb=\hskip .5\arrayrulewidth=.
% ^^A    We only check if the last \textsf{token} was of class $3$ which is
% ^^A    forbidden.
%    \begin{macrocode}
 % \def\@classvii{\ifnum \@lastchclass = \thr@@
%    \end{macrocode}
% ^^A    If this is true we output an error message and
% ^^A    ignore the declarations stored
% ^^A    by the last  \verb=>{...}=, because these are overwritten
% ^^A    by the argument of \texttt{@}.
%    \begin{macrocode}
 %    \@preamerr \thr@@ \fi}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A \begin{macro}{\@classvi}
% ^^A    If the current \textsf{token} is a regular \texttt{!}\ and the
% ^^A    last class was $0$ or $2$ we extend the preamble with
% ^^A    \verb=\hskip\col@sep=.  If the last \textsf{token} was of class $1$
% ^^A    (for instance \texttt{|}) we extend with \verb=\hskip \doublerulesep=
% ^^A    because the construction \verb=!{...}= has to be treated like
% ^^A    \texttt{|}.
%    \begin{macrocode}
 % \def\@classvi{\ifcase \@lastchclass
 %       \@acol \or
 %       \@addtopreamble{\hskip \doublerulesep}\or
 %       \@acol \or
%    \end{macrocode}
% ^^A    Now \verb=\@preamerr...= should follow because a
% ^^A    user preamble of the form \verb=..>{..}!.= is not allowed.
% ^^A    To save memory we call \verb=\@classvii= instead which also
% ^^A    does what we want.
%    \begin{macrocode}
 %       \@classvii
%    \end{macrocode}
% ^^A    If \verb=\@lastchclass= is $4$ or $5$ nothing has to be done.
% ^^A    Class $6$ to $10$ are not possible.
% ^^A    So we finish the macro.
%    \begin{macrocode}
 %       \fi}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\@classii}
% ^^A \begin{macro}{\@classiii}
% ^^A    In the case of character classes $2$ and $3$ (i.e.\ the argument
% ^^A    of \texttt{<} or \texttt{>}) we only have to store the current
% ^^A    \textsf{token} (\verb=\@nextchar=) into the corresponding
% ^^A    \textsf{token} register since the preparation and
% ^^A    insertion of these registers
% ^^A    are done by the macro \verb=\@classz=.
% ^^A    This is equivalent to calling \verb=\save@decl= in the case of
% ^^A    class $3$. To save command identifiers we do this call up
% ^^A     in the macro \verb=\@mkpream=.
% ^^A
% ^^A    Class $2$ exhibits a more complicated situation: the
% ^^A    \textsf{token} registers have already been inserted by
% ^^A    \verb=\@classz=. So the value of \verb=\count@= is too high
% ^^A    by one. Therefore we decrease \verb=\count@= by $1$.
%    \begin{macrocode}
 % \def\@classii{\advance \count@ \m@ne
%    \end{macrocode}
% ^^A    Next we store the current \textsf{token} into the correct
% ^^A    \textsf{token} register by calling \verb=\save@decl= and then
% ^^A    increase the value of \verb=\count@= again. At this point we
% ^^A    can save memory once more (at the cost of time) if we use the
% ^^A     macro \verb=\prepnext@tok=.
%    \begin{macrocode}
 %    \save@decl\prepnext@tok}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A \begin{macro}{\@classv}
% ^^A    If the current \textsf{token} is of class $5$ then it is an
% ^^A    argument of a \texttt{@} \textsf{token}. It must be stored into a
% ^^A    \textsf{token} register.
%    \begin{macrocode}
 % \def\@classv{\save@decl
%    \end{macrocode}
% ^^A    We extend the preamble with a command which inserts this
% ^^A    \textsf{token} register into the preamble when its construction
% ^^A    is finished. The user expects that this argument is worked out in
% ^^A    math mode if it was used in an
% ^^A    \textsf{array}--environment. Therefore we surround it with
% ^^A    \verb=\d@llar...='s.
%    \begin{macrocode}
 %    \@addtopreamble{\d@llarbegin\the@toks\the\count@\relax\d@llarend}%
%    \end{macrocode}
% ^^A    Finally we must prepare the next \textsf{token} register.
%    \begin{macrocode}
 %    \prepnext@tok}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\@classi}
% ^^A    In the case of class $0$ we were able to generate the necessary
% ^^A    space between columns by using the macro \verb=\@classx=.
% ^^A    Analogously the macro \verb=\@classvi= can be used for class $1$.
%    \begin{macrocode}
 % \def\@classi{\@classvi
%    \end{macrocode}
% ^^A    Depending on \verb=\@chnum= a vertical line
%    \begin{macrocode}
 %    \ifcase \@chnum \@arrayrule \or
%    \end{macrocode}
% ^^A    or (in case of \verb=!{...}=) the current \textsf{token} --- stored
% ^^A    in \verb=\@nextchar= --- has to be inserted into the preamble.
% ^^A    This corresponds to calling \verb=\@classv=.
%    \begin{macrocode}
 %       \@classv \fi}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A
% ^^A \begin{macro}{\@startpbox}
% ^^A    In \verb=\@classz=  the macro \verb=\@startpbox= is used.
% ^^A    The width of the \textsf{parbox} is passed as an argument.
% ^^A    \verb=\vcenter=, \verb=\vtop= or \verb=\vbox= are already in the
% ^^A    preamble. So we start with the braces for the wanted box.
%    \begin{macrocode}
 % \def\@startpbox#1{\bgroup
%    \end{macrocode}
% ^^A    The argument is the width of the box. This information has to be
% ^^A    assigned to \verb=\hsize=.
% ^^A    Then we assign default values to several parameters used in a
% ^^A    \textsf{parbox}.
%    \begin{macrocode}
 %   \setlength\hsize{#1}\@arrayparboxrestore
%    \end{macrocode}
% ^^A    Our main problem is to obtain the same distance between succeeding
% ^^A    lines of the \textsf{parbox}.
% ^^A    We have to remember that the distance between two \textsf{parboxes}
% ^^A    should be defined by \verb=\@arstrut=. That means that it can be
% ^^A    greater than the distance in a \textsf{parbox}.
% ^^A    Therefore it is not enough to set a \verb=\@arstrut= at the
% ^^A    beginning and at the end of the \textsf{parbox}. This would
% ^^A    dimension the distance
% ^^A    between first and second line and the distance between the two
% ^^A    last lines of the \textsf{parbox} wrongly.
% ^^A    To prevent this we set an invisible rule of height
% ^^A    \verb=\@arstrutbox=
% ^^A    at the beginning of the \textsf{parbox}. This has no effect on the
% ^^A    depth of the first line. At the end of the \textsf{parbox} we set
% ^^A    analogously another invisible rule which only affects the depth
% ^^A    of the last line. It is necessary to wait inserting this strut
% ^^A    until the paragraph actually starts to allow for things like
% ^^A    \verb=\parindent= changes via \verb=>{...}=.
%    \begin{macrocode}
 %    \everypar{%
 %       \vrule \@height \ht\@arstrutbox \@width \z@
 %       \everypar{}}%
 %    }
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\@endpbox}
% ^^A    If there are any declarations defined by \verb=>{...}=
% ^^A    and \verb=<{...}=
% ^^A    they now follow in the macro \verb=\@classz= --- the contents
% ^^A    of the column in between.
% ^^A    So the macro \verb=\@endpbox= must insert the \textsf{specialstrut}
% ^^A    mentioned earlier and then close the group opened by
% ^^A    \verb=\@startpbox=.
%    \begin{macrocode}
 % \def\@endpbox{\@finalstrut\@arstrutbox \egroup\hfil}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A \subsubsection{Building and calling \texttt{\textbackslash halign}}
% ^^A
% ^^A \begin{macro}{\@array}
% ^^A    After we have discussed the macros needed for the evaluation
% ^^A    of the user preamble we can define the macro \verb=\@array=
% ^^A    which uses these macros to create a \verb=\halign=.
% ^^A    It has two arguments. The first one is a position argument
% ^^A    which can be \texttt{t}, \texttt{b} or \texttt{c}; the
% ^^A    second one describes the wanted preamble,
% ^^A    e.g.\ it has the form \verb=|c|c|c|=.
%    \begin{macrocode}
 % \def\@array[#1]#2{%
%    \end{macrocode}
% ^^A    First we define a \textsf{strut} whose size basically corresponds
% ^^A     to a normal \textsf{strut} multiplied by the factor
% ^^A    \verb=\arraystretch=.
% ^^A    This \textsf{strut} is then  inserted into every row and enforces
% ^^A     a minimal distance between two rows.
% ^^A    Nevertheless, when using horizontal lines, large letters
% ^^A    (like accented capital letters) still collide with such lines.
% ^^A    Therefore at first we add to the height of a normal \textsf{strut}
% ^^A    the value of the parameter \verb=\extrarowheight=.
%    \begin{macrocode}
 %   \@tempdima \ht \strutbox
 %   \advance \@tempdima by\extrarowheight
 %   \setbox \@arstrutbox \hbox{\vrule
 %              \@height \arraystretch \@tempdima
 %              \@depth \arraystretch \dp \strutbox
 %              \@width \z@}%
%    \end{macrocode}
% ^^A    Then we open a group, in which the user preamble is evaluated by
% ^^A    the macro \verb=\@mkpream=. As we know this must happen locally.
% ^^A    This macro creates a preamble for a \verb=\halign= and saves
% ^^A    its result globally in the control sequence \verb=\@preamble=.
%    \begin{macrocode}
 %   \begingroup
 %   \@mkpream{#2}%
%    \end{macrocode}
% ^^A    We again redefine \verb=\@preamble= so that a call up of \verb=\@preamble=
% ^^A    now starts the \verb=\halign=. Thus also the arguments of \texttt{>},
% ^^A    \texttt{<}, \texttt{@} and \texttt{!}, saved in the
% ^^A    \textsf{token} registers are inserted into the preamble.  The
% ^^A    \verb=\tabskip= at the beginning and end of the preamble is set to
% ^^A    \textsf{0pt} (in the beginning by the use of \verb=\ialign=). Also the
% ^^A    command \verb=\@arstrut= is build in, which inserts the
% ^^A    \verb=\@arstrutbox=, defined above. Of course, the opening brace after
% ^^A    \verb=\ialign= has to be implicit as it will be closed in \verb=\endarray=
% ^^A    or another macro.
% ^^A
% ^^A    The \verb=\noexpand= in front of \verb=\ialign= does no harm in standard \LaTeX{}
% ^^A    and was added since some experimental support for using text glyphs in math
% ^^A    redefines \verb=\halign= with the result that is becomes expandable with
% ^^A    disastrous results in cases like this.
% ^^A    In the kernel definition for this macro the problem does
% ^^A    not surface because there \verb=\protect= is set (which is not necessary in this
% ^^A    implementation as there is no arbitrary user input that can get expanded) and
% ^^A    the experimental code made the redefinition robust. Whether this is the right
% ^^A    approach is open to question; consider the \verb=\noexpand= a courtesy to allow an
% ^^A    unsupported redefinition of a \TeX{} primitive for the moment (as people rely
% ^^A    on that experimental code).
%    \begin{macrocode}
 %   \xdef\@preamble{\noexpand \ialign \@halignto
 %                   \bgroup \@arstrut \@preamble
 %                           \tabskip \z@ \cr}%
%    \end{macrocode}
% ^^A    What we have not explained yet is the macro \verb=\@halignto=
% ^^A    that was just used. Depending on its replacement text the
% ^^A    \verb=\halign= becomes a \verb=\halign= \texttt{to} \meta{dimen}.
% ^^A    Now we close the group again. Thus
% ^^A    \verb=\@startpbox= and \verb=\@endpbox= as well as all
% ^^A    \textsf{token} registers get their former meaning back.
%    \begin{macrocode}
 %   \endgroup
%    \end{macrocode}
% ^^A     To support the \texttt{delarray.sty} package  we include a hook
% ^^A     into this part of the code which is a no-op in the main package.
%    \begin{macrocode}
 %   \@arrayleft
%    \end{macrocode}
% ^^A    Now we decide depending on the position argument in which
% ^^A    \textsf{box} the \verb=\halign= is to be put. (\verb=\vcenter= may be used
% ^^A    because we are in math mode.)
%    \begin{macrocode}
 %   \if #1t\vtop \else \if#1b\vbox \else \vcenter \fi \fi
%    \end{macrocode}
% ^^A    Now another implicit opening brace appears; then definitions
% ^^A    which shall stay local follow. While constructing the
% ^^A    \verb=\@preamble= in \verb=\@mkpream= the \verb=#= sign must be
% ^^A    hidden in the macro \verb=\@sharp= which is \verb=\let= to
% ^^A    \verb=\relax= at that moment (see definition of \verb=\@mkpream=
% ^^A    on page~\pageref{@mkpream}).
% ^^A    All these now get their actual meaning.
%    \begin{macrocode}
 %   \bgroup
 %   \let \@sharp ##\let \protect \relax
%    \end{macrocode}
% ^^A    With the above defined \textsf{struts} we fix down the distance
% ^^A    between rows by setting \verb=\lineskip= and \verb=\baselineskip=
% ^^A    to \textsf{0pt}. Since there have to be set \verb=$='s
% ^^A    around every column in the \textsf{array}--environment
% ^^A     the parameter \verb=\mathsurround= should
% ^^A    also be set to \textsf{0pt}. This prevents additional space between
% ^^A    the rows. The
% ^^A    \PlainTeX--macro \verb=\m@th= does this.
%    \begin{macrocode}
 %   \lineskip \z@
 %   \baselineskip \z@
 %   \m@th
%    \end{macrocode}
% ^^A    Beside, we have to assign a special meaning (which we still have
% ^^A    to specify) to the line separator \verb=\\=. We also have to
% ^^A    redefine the command \verb=\par= in such a way that empty lines in
% ^^A    \verb=\halign= cannot do any damage. We succeed in doing  so
% ^^A    by choosing something that will disappear when expanding.
% ^^A    After that we only have to call up \verb=\@preamble= to
% ^^A    start the wanted \verb=\halign=.
%    \begin{macrocode}
 %   \let\\\@arraycr \let\tabularnewline\\\let\par\@empty \@preamble}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\arraybackslash}
% ^^A Restore \verb=\\= for use in array and tabular environment (after
% ^^A \verb=\raggedright= etc.).
%    \begin{macrocode}
 % \def\arraybackslash{\let\\\tabularnewline}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\extrarowheight}
% ^^A    The \textsf{dimen} parameter used above also needs to be
% ^^A    allocated.  As a default value we use \textsf{0pt}, to ensure
% ^^A    compatibility with standard \LaTeX.
%    \begin{macrocode}
 % \newdimen \extrarowheight
 % \extrarowheight=0pt
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\@arstrut}
% ^^A    Now the insertion of \verb=\@arstrutbox= through \verb=\@arstut=
% ^^A    is easy since we know exactly in which mode \TeX\ is while working
% ^^A    on the \verb=\halign= preamble.
%    \begin{macrocode}
 % \def\@arstrut{\unhcopy\@arstrutbox}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A \subsubsection{The line separator \texttt{\textbackslash\textbackslash}}
% ^^A
% ^^A \begin{macro}{\@arraycr}
% ^^A    In the macro \verb=\@array= the line separator \verb=\\= is
% ^^A    \verb=\let= to the command \verb=\@arraycr=.
% ^^A    Its definition starts with a special brace which I have directly
% ^^A    copied from the original definition. It is
% ^^A    necessary, because the \verb=\futurlet= in \verb=\@ifnextchar=
% ^^A    might
% ^^A    expand a  following \verb=&= \textsf{token} in a construction like
% ^^A    \verb=\\ &=. This would otherwise end the alignment template at a
% ^^A    wrong time. On the other hand we have to be careful to avoid
% ^^A    producing a real group, i.e.\ \verb={}=, because the command will also
% ^^A    be used for the array environment, i.e.\ in math mode. In that
% ^^A    case an extra \verb={}= would produce an ord atom which could mess up
% ^^A    the spacing. For this reason we use a combination that does not
% ^^A    really produce a group at all but modifies the master counter so
% ^^A    that a \verb=&= will not be considered belonging to the current
% ^^A    \verb=\halign= while we are looking for a \verb=*= or \verb=[=.
% ^^A    For further information see
% ^^A    \cite[Appendix D]{bk:knuth}.
%    \begin{macrocode}
 % \def\@arraycr{\relax\iffalse{\fi\ifnum 0=`}\fi
%    \end{macrocode}
% ^^A    Then we test whether the user is using the star form and ignore
% ^^A    a possible star (I also disagree with this procedure, because a
% ^^A    star does not make any sense here).
%    \begin{macrocode}
 %   \@ifstar \@xarraycr \@xarraycr}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\@xarraycr}
% ^^A    In the command \verb=\@xarraycr= we test if an optional argument
% ^^A    exists.
%    \begin{macrocode}
 % \def\@xarraycr{\@ifnextchar [%
%    \end{macrocode}
% ^^A    If it does, we branch out into the macro \verb=\@argarraycr= if
% ^^A    not we close the special brace (mentioned above) and end the row
% ^^A    of the \verb=\halign= with a \verb=\cr=.
%    \begin{macrocode}
 %   \@argarraycr {\ifnum 0=`{}\fi\cr}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A \begin{macro}{\@argarraycr}
% ^^A    If additional space is requested by the user this case is treated
% ^^A    in the macro \verb=\@argarraycr=. First we close the special brace
% ^^A    and then we test if the additional space is positive.
%    \begin{macrocode}
 % \def\@argarraycr[#1]{\ifnum0=`{}\fi\ifdim #1>\z@
%    \end{macrocode}
% ^^A    If this is the case we create an invisible vertical rule with
% ^^A    depth \verb=\dp\@arstutbox=${}+{}$\meta{wanted\ space}.
% ^^A    Thus we achieve that all vertical lines specified
% ^^A    in the user preamble by a \texttt{|} are now
% ^^A    generally drawn.
% ^^A    Then the row ends with a \verb=\cr=.
% ^^A
% ^^A    If the space is negative we end the row at once with a \verb=\cr=
% ^^A    and move back up with a \verb=\vskip=.
% ^^A
% ^^A    While testing these macros I found out that the
% ^^A    \verb=\endtemplate=
% ^^A    created by \verb=\cr= and \verb=&= is something like an
% ^^A    \verb=\outer= primitive and therefore it should not appear in
% ^^A    incomplete \verb=\if= statements. Thus the following solution was
% ^^A    chosen which hides the \verb=\cr= in other macros when \TeX\
% ^^A    is skipping conditional text.
%    \begin{macrocode}
 %   \expandafter\@xargarraycr\else
 %   \expandafter\@yargarraycr\fi{#1}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\@xargarraycr}
% ^^A \begin{macro}{\@yargarraycr}
% ^^A    The following macros were already explained above.
%    \begin{macrocode}
 % \def\@xargarraycr#1{\unskip
 %   \@tempdima #1\advance\@tempdima \dp\@arstrutbox
 %   \vrule \@depth\@tempdima \@width\z@ \cr}
 % \def\@yargarraycr#1{\cr\noalign{\vskip #1}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A
% ^^A
% ^^A \subsubsection{Spanning several columns}
% ^^A
% ^^A \begin{macro}{\multicolumn}
% ^^A    If several columns should be held together with a special format
% ^^A    the command \verb=\multicolumn= must be used. It has three
% ^^A    arguments: the number of columns to be covered; the format for
% ^^A    the result column and the actual column entry.
%    \begin{macrocode}
 % \long\def\multicolumn#1#2#3{%
%    \end{macrocode}
% ^^A    First we combine the given number of columns into a single one;
% ^^A    then we start a new block so that the following definition is kept
% ^^A    local.
%    \begin{macrocode}
 %    \multispan{#1}\begingroup
%    \end{macrocode}
% ^^A    Since a \verb=\multicolumn= should only describe the format of a
% ^^A    result column, we redefine \verb=\@addamp= in such a way that one gets
% ^^A    an error message if one uses more than one \texttt{c},
% ^^A    \texttt{l}, \texttt{r}, \texttt{p}, \texttt{m} or \texttt{b} in
% ^^A    the second argument. One should consider that this definition is
% ^^A    local to the build-up of the preamble; an \textsf{array}-- or
% ^^A    \textsf{tabular}--environment in the third argument of the
% ^^A    \verb=\multicolumn= is therefore worked through correctly as well.
%    \begin{macrocode}
 %    \def\@addamp{\if@firstamp \@firstampfalse \else
 %                 \@preamerr 5\fi}%
%    \end{macrocode}
% ^^A    Then we evaluate the second argument with the help of
% ^^A    \verb=\@mkpream=.
% ^^A    Now we still have to insert the contents of the \textsf{token}
% ^^A    register into the \verb=\@preamble=, i.e.\ we have to say
% ^^A    \verb=\xdef\@preamble{\@preamble}=. This is achieved shorter by
% ^^A    writing:
%    \begin{macrocode}
 %    \@mkpream{#2}\@addtopreamble\@empty
%    \end{macrocode}
% ^^A    After the \verb=\@preamble= is created we forget all local
% ^^A    definitions and occupations of the \textsf{token} registers.
%    \begin{macrocode} 
 %    \endgroup
%    \end{macrocode}
% ^^A    In the special situation of  \verb=\multicolumn= \verb=\@preamble=
% ^^A    is not needed as preamble for a \verb=\halign= but it is directly
% ^^A    inserted into our table. Thus instead of \verb=\sharp=
% ^^A    there has to be the column entry (\verb=#3=) wanted by the user.
%    \begin{macrocode}
 %    \def\@sharp{#3}%
%    \end{macrocode}
% ^^A    Now we can pass the \verb=\@preamble= to \TeX\ . For safety
% ^^A    we start with an \verb=\@arstrut=. This should usually be in the
% ^^A    template for the first column however we do not know if this
% ^^A    template was overwritten by our \verb=\multicolumn=.
% ^^A    We also add a \verb=\null= at the right end to prevent any following
% ^^A    \verb=\unskip= (for example from \verb=\\[..]=) to remove the \verb=\tabcolsep=.
%    \begin{macrocode}
 %    \@arstrut \@preamble
 %    \null
 %    \ignorespaces}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A
% ^^A   \subsubsection{The Environment Definitions}
% ^^A
% ^^A After these preparations we are able to define the environments. They
% ^^A only differ in the initialisations of \verb=\d@llar...=, \verb=\col@sep=
% ^^A  and \verb=\@halignto=.
% ^^A
% ^^A \begin{macro}{\@halignto}
% ^^A \begin{macro}{\d@llarbegin}
% ^^A \begin{macro}{\d@llarend}
% ^^A    \verb=\d@llar= has to be
% ^^A    locally asigned since otherwise nested \textsf{tabular} and \textsf{array}
% ^^A    environments (via \verb=\multicolumn=) are impossible.
% ^^A    For 25 years or so \verb=\@halignto= was set globally (to save space on the
% ^^A    save stack, but that was a mistake: if there is a tabular in the
% ^^A    output routine (e.g., in the running header) then that tabular is 
% ^^A    able overwrite the \verb=\@halignto=
% ^^A    setting of a tabular in the main text resulting in a very weird error.
% ^^A    When the new font selection scheme is in force we have to
% ^^A    we surround all \verb=\halign= entries
% ^^A    with braces. See remarks in TUGboat 10\#2. Actually we are going
% ^^A    to use \verb=\begingroup= and \verb=\endgroup=. However, this is only
% ^^A    necessary when we are in text mode. In math the surrounding
% ^^A    dollar signs will already serve as the necessary extra grouping
% ^^A    level. Therefore we switch the settings of \verb=\d@llarbegin= and
% ^^A    \verb=\d@llarend= between groups and dollar signs.
%    \begin{macrocode}
 % \let\d@llarbegin\begingroup
 % \let\d@llarend\endgroup
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \end{macro}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A \begin{macro}{\array}
% ^^A    Our new definition of \verb=\array= then reads:
%    \begin{macrocode}
 % \def\array{\col@sep\arraycolsep
 %   \def\d@llarbegin{$}\let\d@llarend\d@llarbegin\def\@halignto{}%$ emacs
%    \end{macrocode}
% ^^A    Since there might be an optional argument we call another
% ^^A    macro which is also used by the other environments.
%    \begin{macrocode}
 %   \@tabarray}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\@tabarray}
% ^^A    This macro tests for a optional bracket and then calls up
% ^^A    \verb=\@array= or \verb=\@array[c]= (as default).
%    \begin{macrocode}
 % \def\@tabarray{\@ifnextchar[{\@array}{\@array[c]}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A \begin{macro}{\tabular}
% ^^A \begin{macro}{\tabular*}
% ^^A    The environments \textsf{tabular} and \textsf{tabular$*$} differ
% ^^A    only in the initialisation of the command \verb=\@halignto=. Therefore
% ^^A    we define
%    \begin{macrocode}
 % \def\tabular{\def\@halignto{}\@tabular}
%    \end{macrocode}
% ^^A     and analogously for the star form. We evaluate the argument first
% ^^A     using =\setlength= so that users of the \texttt{calc} package can
% ^^A     write code like\\ \verb=\begin{tabular*}{(\columnwidth-1cm)/2}...=
% ^^A     \begin{macrocode}
 % \expandafter\def\csname tabular*\endcsname#1{%
 %        \setlength\dimen@{#1}%
 %        \edef\@halignto{to\the\dimen@}\@tabular}
% ^^A    \end{macrocode}
% ^^A \end{macro}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\@tabular}
% ^^A    The rest of the job is carried out by the \verb=\@tabular= macro:
%    \begin{macrocode}
 % \def\@tabular{%
%    \end{macrocode}
% ^^A    First of all we have to make sure that we start out in
% ^^A    \textsf{hmode}.  Otherwise we might find our table dangling by
% ^^A    itself on a line.
%    \begin{macrocode}
 %   \leavevmode
%    \end{macrocode}
% ^^A    It should be taken into consideration that the macro \verb=\@array=
% ^^A    must be called in math mode. Therefore we open a \textsf{box},
% ^^A    insert a \verb=$= and then assign the correct values to \verb=\col@sep= and
% ^^A    \verb=\d@llar...=.
%    \begin{macrocode}
 %   \hbox \bgroup $\col@sep\tabcolsep \let\d@llarbegin\begingroup% $ emacs
 %                                     \let\d@llarend\endgroup
%    \end{macrocode}
% ^^A    Now everything \textsf{tabular} specific is done and we are able to
% ^^A    call the \verb=\@tabarray= macro.
%    \begin{macrocode}
 %   \@tabarray}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\endarray}
% ^^A    When the processing of \textsf{array} is finished we have to
% ^^A    close the \verb=\halign=
% ^^A    and afterwards the surrounding \textsf{box} selected by
% ^^A    \verb=\@array=. To save \textsf{token} space we then redefine
% ^^A    \verb=\@preamble=
% ^^A    because its replacement text isn't longer needed.
%    \begin{macrocode}
 % \def\endarray{\crcr \egroup \egroup \gdef\@preamble{}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\endtabular}
% ^^A \begin{macro}{\endtabular*}
% ^^A    To end a \textsf{tabular} or \textsf{tabular$*$} environment we
% ^^A    call up \verb=\endarray=, close the math mode and then the surrounding
% ^^A    \verb=\hbox=.
%    \begin{macrocode}
 % \def\endtabular{\endarray $\egroup}%$ emacs
 % \expandafter\let\csname endtabular*\endcsname=\endtabular
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A
% ^^A   \subsubsection{Last minute definitions}
% ^^A
% ^^A
% ^^A If this file is used as a package file we should \verb=\let= all macros
% ^^A to \verb=\relax= that were used in the original but are no longer
% ^^A  necessary.
%    \begin{macrocode}
 % \let\@ampacol=\relax        \let\@expast=\relax
 % \let\@arrayclassiv=\relax   \let\@arrayclassz=\relax
 % \let\@tabclassiv=\relax     \let\@tabclassz=\relax
 % \let\@arrayacol=\relax      \let\@tabacol=\relax
 % \let\@tabularcr=\relax      \let\@@endpbox=\relax
 % \let\@argtabularcr=\relax   \let\@xtabularcr=\relax
%    \end{macrocode}
% ^^A
% ^^A \begin{macro}{\@preamerr}
% ^^A    We also have to redefine the error routine \verb=\@preamerr= since
% ^^A    new kind of errors are possible.
% ^^A    The code for this macro is not perfect yet;
% ^^A    it still needs too much memory.
%    \begin{macrocode}
 % \def\@preamerr#1{\def\@tempd{{..} at wrong position: }%
 %    %\PackageError{array}{%
 %    \ClassError{memoir}{% changed in menoir
 %    \ifcase #1 Illegal pream-token (\@nextchar): `c' used\or %0
 %     Missing arg: token ignored\or                           %1
 %     Empty preamble: `l' used\or                             %2
 %     >\@tempd token ignored\or                               %3
 %     <\@tempd changed to !{..}\or                            %4
 %     Only one column-spec. allowed.\fi}\@ehc}                %5
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A
% ^^A \subsubsection
% ^^A   [Defining your own column specifiers]
% ^^A   {Defining your own column specifiers\footnotemark}
% ^^A
% ^^A \footnotetext{The code and the documentation in this section was
% ^^A   written by David. So far only the code from newarray was plugged
% ^^A   into array so that some parts of the documentation still claim
% ^^A   that this is newarray and even worse, some parts of the code are
% ^^A   unnecessarily doubled. This will go away in a future release. For
% ^^A   the moment we thought it would be more important to bring both
% ^^A   packages together.}
% ^^A
% ^^A  \begin{macro}{\newcolumn}
% ^^A    In \texttt{newarray.sty} the macro for specifying new columns was
% ^^A    named \verb"\newcolumn". When the functionality was added to
% ^^A    \texttt{array.sty} the command was renamed \verb"\newcolumntype".
% ^^A    Initially both names were supported, but now (In versions of this
% ^^A    package distributed for \LaTeXe) the old name is not defined.
% ^^A  \end{macro}
% ^^A
% ^^A \begin{macro}{\newcolumntype}
% ^^A  As
% ^^A described above, the \verb"\newcolumntype" macro gives users the chance
% ^^A to define letters, to be used in the same way as the primitive
% ^^A column specifiers, `c' `p' etc.
%    \begin{macrocode}
 % \def\newcolumntype#1{%
%    \end{macrocode}
% ^^A \verb"\NC@char" was added in V2.01 so that active characters, like "@" in
% ^^A AMS\LaTeX\ may be used. This trick was stolen from \texttt{array.sty}
% ^^A 2.0h. Note that we need to use the possibly active token,
% ^^A \verb"#1", in several places, as that is the token that actually
% ^^A appears in the preamble argument.
%    \begin{macrocode}
 %   \edef\NC@char{\string#1}%
%    \end{macrocode}
% ^^A First we check whether there is already a definition for this column.
% ^^A Unlike \verb"\newcommand" we give a warning rather than an error if it is
% ^^A defined. If it is a new column, add \verb"\NC@do" \meta{column} to
% ^^A the list \verb"\NC@list".
%    \begin{macrocode}
 %   \@ifundefined{NC@find@\NC@char}%
 %     {\@tfor\next:=<>clrmbp@!|\do{\if\noexpand\next\NC@char
 %         %\PackageWarning{array}%
 %           \@memwarn{Redefining primitive column \NC@char}\fi}% memoir change
 %      \NC@list\expandafter{\the\NC@list\NC@do#1}}%
 %    {%\PackageWarning{array}
 %       \@memwarn{Column \NC@char\space is already defined}}% memoir change
%    \end{macrocode}
% ^^A Now we define a macro with an argument delimited by the new column
% ^^A specifier, this is used to find occurrences of this specifier in the
% ^^A user preamble.
%    \begin{macrocode}
 %   \@namedef{NC@find@\NC@char}##1#1{\NC@{##1}}%
%    \end{macrocode}
% ^^A If an optional argument was not given, give a default argument of 0.
%    \begin{macrocode}
 %   \@ifnextchar[{\newcol@{\NC@char}}{\newcol@{\NC@char}[0]}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \begin{macro}{\newcol@}
% ^^A We can now define the macro which does the rewriting,
% ^^A \verb"\@reargdef" takes the same arguments as \verb"\newcommand", but
% ^^A does not check that the command is new. For a column, say `D' with
% ^^A one argument, define a command \verb"\NC@rewrite@D" with one
% ^^A argument, which recursively calls \verb"\NC@find" on the user preamble
% ^^A after replacing the first token or group with the replacement text
% ^^A specified in the \verb"\newcolumntype" command. \verb"\NC@find" will find the
% ^^A next occurrence of `D' as it will be \verb"\let" equal to
% ^^A \verb"\NC@find@D" by \verb"\NC@do".
%    \begin{macrocode}
 % \def\newcol@#1[#2]#3{\expandafter\@reargdef
 %      \csname NC@rewrite@#1\endcsname[#2]{\NC@find#3}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \begin{macro}{\NC@}
% ^^A Having found an occurrence of the new column, save the preamble
% ^^A before the column in \verb"\@temptokena", then check to see if we
% ^^A are at the end of the preamble. (A dummy occurrence of the column
% ^^A specifier will be placed at the end of the preamble by \verb"\NC@do".
%    \begin{macrocode}
 % \def\NC@#1{%
 %   \@temptokena\expandafter{\the\@temptokena#1}\futurelet\next\NC@ifend}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \begin{macro}{\NC@ifend}
% ^^A We can tell that we are at the end as \verb"\NC@do" will place a \verb"\relax"
% ^^A after the dummy column.
%    \begin{macrocode}
 % \def\NC@ifend{%
%    \end{macrocode}
% ^^A If we are at the end, do nothing. (The whole preamble will now be in
% ^^A \verb"\@temptokena".)
%    \begin{macrocode}
 %   \ifx\next\relax
%    \end{macrocode}
% ^^A Otherwise set the flag \verb"\if@tempswa", and rewrite the column.
% ^^A \verb"\expandafter" introduced 1n V2.01
%    \begin{macrocode}
 %     \else\@tempswatrue\expandafter\NC@rewrite\fi}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \begin{macro}{\NC@do}
% ^^A If the user has specified `C' and `L' as new columns, the list of
% ^^A rewrites (in the token register \verb"\NC@list") will look like
% ^^A \verb"\NC@do *" \verb"\NC@do C" \verb"\NC@do L".
% ^^A So we need to define \verb"\NC@do" as a one argument macro which
% ^^A initialises the rewriting of the specified column. Let us assume that
% ^^A `C' is the argument.
%    \begin{macrocode}
 % \def\NC@do#1{%
%    \end{macrocode}
% ^^A First we let \verb"\NC@rewrite" and \verb"\NC@find" be
% ^^A \verb"\NC@rewrite@C" and \verb"\NC@find@C" respectively.
%    \begin{macrocode}
 %   \expandafter\let\expandafter\NC@rewrite
 %     \csname NC@rewrite@\string#1\endcsname
 %   \expandafter\let\expandafter\NC@find
 %     \csname NC@find@\string#1\endcsname
%    \end{macrocode}
% ^^A Clear the token register \verb"\@temptokena" after putting the present
% ^^A contents of the register in front of the token \verb"\NC@find". At the
% ^^A end we place the tokens `\verb"C\relax"' which \verb"\NC@ifend" will use
% ^^A to detect the end of the user preamble.
%    \begin{macrocode}
 %   \expandafter\@temptokena\expandafter{\expandafter}%
 %         \expandafter\NC@find\the\@temptokena#1\relax}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\showcols}
% ^^A This macro is useful for debugging \verb"\newcolumntype" specifications,
% ^^A it is the equivalent of the primitive \verb"\show" command for macro
% ^^A definitions.  All we need to do is locally redefine \verb"\NC@do" to take
% ^^A its argument (say `C') and then \verb"\show" the (slightly modified)
% ^^A definition of \verb"\NC@rewrite@C". Actually as the the list always
% ^^A starts off with \verb"\NC@do *" and we do not want to print the
% ^^A definition of the $*$-form, define \verb"\NC@do" to throw away the first
% ^^A item in the list, and then redefine itself to print the rest of the
% ^^A definitions.
%    \begin{macrocode}
 % \def\showcols{{\def\NC@do##1{\let\NC@do\NC@show}\the\NC@list}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \begin{macro}{\NC@show}
% ^^A If the column `C' is defined as above, then
% ^^A \verb"\show\NC@rewrite@C" would output\\
% ^^A \verb"\long macro: ->\NC@find >{$}c<{$}".
% ^^A We want to strip the \verb"long macro: ->" and the \verb"\NC@find". So first we
% ^^A use \verb"\meaning" and then apply the macro \verb"\NC@strip" to the tokens so
% ^^A produced and then \verb"\typeout" the required string.
%    \begin{macrocode}
 % \def\NC@show#1{%
 %   \typeout{Column #1\expandafter\expandafter\expandafter\NC@strip
 %   \expandafter\meaning\csname NC@rewrite@#1\endcsname\@@}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \begin{macro}{\NC@strip}
% ^^A Delimit the arguments to \verb"\NC@strip" with `\texttt{:}', `\texttt{->}',
% ^^A a space, and \verb"\@@" to pull out the required parts of the output from
% ^^A \verb"\meaning".
%    \begin{macrocode}
 % \def\NC@strip#1:#2->#3 #4\@@{#2 -> #4}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \begin{macro}{\NC@list}
% ^^A Allocate the token register used for the rewrite list.
%    \begin{macrocode}
 % \newtoks\NC@list
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \subsubsection{The $*$--form}
% ^^A We view the $*$-form as a slight generalisation of the system
% ^^A described in the previous subsection. The idea is to define a $*$
% ^^A column by a command of the form:
% ^^A \begin{verbatim}
% ^^A \newcolumntype{*}[2]{%
% ^^A    \count@=#1\ifnum\count@>0
% ^^A       \advance\count@ by -1 #2*{\count@}{#2}\fi}
% ^^A \end{verbatim}
% ^^A \begin{macro}{\NC@rewrite@*}\label{NC@rewrite@*}
% ^^A This does not work however as \verb"\newcolumntype" takes great care not
% ^^A to expand anything in the preamble, and so the \verb"\if" is never
% ^^A expanded. \verb"\newcolumntype" sets up various other parts of the
% ^^A rewrite correctly though so we can define:
%    \begin{macrocode}
 % \newcolumntype{*}[2]{}
%    \end{macrocode}
% ^^A Now we must correct the definition of \verb"\NC@rewrite@*". The
% ^^A following is probably more efficient than a direct translation of
% ^^A the idea sketched above, we do not need to put a $*$ in the preamble
% ^^A and call the rewrite recursively, we can just put \verb"#1" copies of
% ^^A \verb"#2" into \verb"\@temptokena". (Nested $*$ forms will be expanded
% ^^A when the whole rewrite list is expanded again, see \verb"\@mkpream")
%    \begin{macrocode}
 % \long\@namedef{NC@rewrite@*}#1#2{%
%    \end{macrocode}
% ^^A Store the number.
%    \begin{macrocode}
 %   \count@#1\relax
%    \end{macrocode}
% ^^A Put \verb"#1" copies of \verb"#2" in the token register.
%    \begin{macrocode}
 %   \loop
 %   \ifnum\count@>\z@
 %   \advance\count@\m@ne
 %   \@temptokena\expandafter{\the\@temptokena#2}%
 %   \repeat
%    \end{macrocode}
% ^^A \verb"\NC@do" will ensure that \verb"\NC@find" is \verb"\let" equal
% ^^A to \verb"\NC@find@*".
%    \begin{macrocode}
 %   \NC@find}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \subsubsection{Modifications to internal macros of \texttt{array.sty}}
% ^^A
% ^^A \begin{macro}{\@xexpast}
% ^^A \begin{macro}{\@xexnoop}
% ^^A    These macros are used to expand $*$-forms in
% ^^A    \texttt{array.sty}. \verb"\let" them to \verb"\relax" to save space.
%    \begin{macrocode}
 % \let\@xexpast\relax
 % \let\@xexnoop\relax
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\save@decl}
% ^^A We do not assume that the token register is free, we add the new
% ^^A declarations to the front of the register. This is to allow user
% ^^A preambles of the form, \verb">{foo}>{bar}..". Users are not encouraged to
% ^^A enter such expressions directly, but they may result from the
% ^^A rewriting of \verb"\newcolumntype"'s.
%    \begin{macrocode}
 % \def\save@decl{\toks \count@ = \expandafter\expandafter\expandafter
 %                   {\expandafter\@nextchar\the\toks\count@}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \begin{macro}{\@mkpream}
% ^^A    The main modification to \verb"\@mkpream" is to replace the call to
% ^^A    \verb"\@xexpast" (which expanded $*$-forms) by a loop which expands
% ^^A    all \verb"\newcolumntype" specifiers.
%    \begin{macrocode}
 % \def\@mkpream#1{\gdef\@preamble{}\@lastchclass 4 \@firstamptrue
 %    \let\@sharp\relax \let\@startpbox\relax \let\@endpbox\relax
%    \end{macrocode}
% ^^A    Now we remove possible  $*$-forms and user-defined column
% ^^A    specifiers in the user preamble by repeatedly executing the list
% ^^A    \verb"\NC@list" until the re-writes have no more effect. The
% ^^A    expanded preamble will then be in the token register
% ^^A    \verb"\@temptokena". Actually we need to know at this point that
% ^^A    this is not \verb"\toks0".
%    \begin{macrocode}
 %    \@temptokena{#1}\@tempswatrue
 %    \@whilesw\if@tempswa\fi{\@tempswafalse\the\NC@list}%
%    \end{macrocode}
% ^^A    Afterwards we initialize all registers and macros, that we need
% ^^A    for the build-up of the preamble.
%    \begin{macrocode}
 %    \count@\m@ne
 %    \let\the@toks\relax
 %    \prepnext@tok
%    \end{macrocode}
% ^^A Having expanded all tokens defined using \verb"\newcolumntype" (including
% ^^A \verb"*"), we evaluate the remaining tokens, which are saved in
% ^^A \verb"\@temptokena".  We use the \LaTeX--macro \verb"\@tfor" to inspect each
% ^^A token in turn.
%    \begin{macrocode}
 %    \expandafter \@tfor \expandafter \@nextchar
 %     \expandafter :\expandafter =\the\@temptokena \do
%    \end{macrocode}
% ^^A \verb"\@testpatch" does not take an argument since \texttt{array.sty} 2.0h.
%    \begin{macrocode}
 %    {\@testpach
 %    \ifcase \@chclass \@classz \or \@classi \or \@classii
 %      \or \save@decl \or \or \@classv \or \@classvi
 %      \or \@classvii \or \@classviii
%    \end{macrocode}
% ^^A    In \texttt{newarray.sty} class 9 is equivalent to class 10.
%    \begin{macrocode}
 %      \or \@classx
 %      \or \@classx \fi
 %    \@lastchclass\@chclass}%
 %    \ifcase\@lastchclass
 %    \@acol \or
 %    \or
 %    \@acol \or
 %    \@preamerr \thr@@ \or
 %    \@preamerr \tw@ \@addtopreamble\@sharp \or
 %    \or
 %    \else  \@preamerr \@ne \fi
 %    \def\the@toks{\the\toks}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\@classix}
% ^^A    \texttt{array.sty} does not allow repeated \texttt{>}
% ^^A    declarations for the same column. This is allowed in
% ^^A    \texttt{newarray.sty} as documented in the introduction. Removing
% ^^A    the test for this case makes class 9 equivalent to class 10, and
% ^^A    so this macro is redundant. It is \verb"\let" to \verb"\relax" to save
% ^^A    space.
%    \begin{macrocode}
 % \let\@classix\relax
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\@classviii}
% ^^A    In \texttt{newarray.sty} explicitly allow class 2, as repeated
% ^^A    \texttt{<} expressions are accepted by this package.
%    \begin{macrocode}
 % \def\@classviii{\ifnum \@lastchclass >\z@\ifnum\@lastchclass=\tw@\else
 %       \@preamerr 4\@chclass 6 \@classvi \fi\fi}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\@classv}
% ^^A Class 5 is \texttt{@}-expressions (and is also called by class 1)
% ^^A This macro was incorrect in Version~1. Now we do not expand the
% ^^A \verb"@"-expression, but instead explicitly replace an
% ^^A \verb"\extracolsep" command by an assignment to \verb"\tabskip" by a
% ^^A method similar to the \verb"\newcolumntype" system described above.
% ^^A \verb"\d@llarbegin" \verb"\d@llarend" were introduced in V2.01 to match
% ^^A \texttt{array.sty} 2.0h.
%    \begin{macrocode}
 % \def\@classv{\save@decl
 %    \expandafter\NC@ecs\@nextchar\extracolsep{}\extracolsep\@@@
 %    \@addtopreamble{\d@llarbegin\the@toks\the\count@\relax\d@llarend}%
 %    \prepnext@tok}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\NC@ecs}
% ^^A Rewrite the first occurrence of \verb"\extracolsep{1in}" to
% ^^A \verb"\tabskip1in\relax". As a side effect discard any tokens after a
% ^^A second \verb"\extracolsep", there is no point in the user entering two of
% ^^A these commands anyway, so this is not really a restriction.
%    \begin{macrocode}
 % \def\NC@ecs#1\extracolsep#2#3\extracolsep#4\@@@{\def\@tempa{#2}%
 %   \ifx\@tempa\@empty\else\toks\count@={#1\tabskip#2\relax#3}\fi}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A \subsubsection{Support for the \texttt{delarray.sty}}
% ^^A
% ^^A The \texttt{delarray.sty} package  extends the array syntax by
% ^^A supporting the notation of delimiters. To this end we extend the
% ^^A array parsing mechanism to include a hook which can be used by this
% ^^A (or another) package to do some additional parsing.
% ^^A
% ^^A \begin{macro}{\@tabarray}
% ^^A    This macro tests for an optional bracket and then calls up
% ^^A    \verb"\@@array" or \verb"\@@array[c]" (as default).
%    \begin{macrocode}
 % \def\@tabarray{\@ifnextchar[{\@@array}{\@@array[c]}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \begin{macro}{\@@array}
% ^^A    This macro tests could then test an optional delimiter before the
% ^^A    left brace of the main preamble argument. Here in the main package
% ^^A    it simply is let to be \verb"\@array".
%    \begin{macrocode}
 % \let\@@array\@array
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\endarray}
% ^^A \begin{macro}{\@arrayright}
% ^^A    We have to declare the hook we put into \verb"\@array" above.
% ^^A    A similar hook `\verb"\@arrayright"' will be inserted into the
% ^^A    \verb"\endarray" to gain control. Both defaults to empty.
%    \begin{macrocode}
 % \def\endarray{\crcr \egroup \egroup \@arrayright \gdef\@preamble{}}
 % \let\@arrayleft\@empty
 % \let\@arrayright\@empty
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \end{macro}
% ^^A
% ^^A \subsubsection{Support for \texttt{\textbackslash firsthline} and
% ^^A             \texttt{\textbackslash lasthline}}
% ^^A
% ^^A The Companion~\cite[p.137]{GOOSSENS94} suggests two additional
% ^^A commands to control the alignments in case of tabulars with
% ^^A horizontal lines. They are now added to this package.
% ^^A
% ^^A  \begin{macro}{\extratabsurround}
% ^^A    The extra space around a table when \verb"\firsthline" or \verb"\lasthline"
% ^^A    are used.
%    \begin{macrocode}
 % \newlength{\extratabsurround}
 % \setlength{\extratabsurround}{2pt}
%    \end{macrocode}
% ^^A  \end{macro}
% ^^A
% ^^A \begin{macro}{\backup@length}
% ^^A    This register will be used internally by \verb"\firsthline" and
% ^^A    \verb"\lasthline".
%    \begin{macrocode}
 % \newlength{\backup@length}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\firsthline}
% ^^A    This code can probably be improved but for the moment it should
% ^^A    serve.
% ^^A
% ^^A    We start by producing a single tabular row without any visible
% ^^A    content that will produce the external reference point in case
% ^^A    \verb"[t]" is used.
%    \begin{macrocode}
 % \newcommand{\firsthline}{%}} emacs
 %   \multicolumn1c{% 
%    \end{macrocode}
% ^^A    Within this row we calculate \verb"\backup@length" to be the height
% ^^A    plus depth of a standard line. In addition we have to add the
% ^^A    width of the \verb"\hline", something that was forgotten in the
% ^^A    original definition.
%    \begin{macrocode}
 %     \global\backup@length\ht\@arstrutbox
 %     \global\advance\backup@length\dp\@arstrutbox
 %     \global\advance\backup@length\arrayrulewidth
%    \end{macrocode}
% ^^A    Finally we do want to make the height of this first line be a bit
% ^^A    larger than usual, for this we place the standard array strut
% ^^A    into it but raised by \verb"\extratabsurround"
%    \begin{macrocode}
 %      \raise\extratabsurround\copy\@arstrutbox
%    \end{macrocode}
% ^^A    Having done all this we end the line and back up by the value of
% ^^A    \verb"\backup@length" and then finally place our \verb"\hline". This should
% ^^A    place the line exactly at the right place but keep the reference
% ^^A    point of the whole tabular at the baseline of the first row.
%    \begin{macrocode}
 %     }\\[-\backup@length]\hline
 % }
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\lasthline}
% ^^A    For \verb"\lasthline" the situation is even worse and I got it
% ^^A    completely wrong initially.
% ^^A
% ^^A    The problem in this case is that if the optional argument \verb"[b]"
% ^^A    is used we do want the reference point of the tabular be at the
% ^^A    baseline of the last row but at the same time do want the the
% ^^A    depth of this last line increased by \verb"\extratabsurround" without
% ^^A    changing the placement \verb"\hline".
% ^^A
% ^^A    We start by placing the rule followed by an invisible row.
%    \begin{macrocode}
 % \newcommand{\lasthline}{\hline\multicolumn1c{%}} emacs
%    \end{macrocode}
% ^^A    We now calculate \verb"\backup@length" to be the height and depth of
% ^^A    two lines plus the width of the rule.
%    \begin{macrocode}
 %     \global\backup@length2\ht\@arstrutbox
 %     \global\advance\backup@length2\dp\@arstrutbox
 %     \global\advance\backup@length\arrayrulewidth
%    \end{macrocode}
% ^^A    This will bring us back to the baseline of the second last row:
%    \begin{macrocode}
 %     }\\[-\backup@length]%
%    \end{macrocode}
% ^^A    Thus if we now add another invisible row the reference point of
% ^^A    that row will be at the baseline of the last row (and will be the
% ^^A    reference for the whole tabular). Since this row is invisible we
% ^^A    can enlarge its depth by the desired amount.
%    \begin{macrocode}
 %     \multicolumn1c{%
 %        \lower\extratabsurround\copy\@arstrutbox
 %        }%
 % }
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A \subsubsection{Getting the spacing around rules right}
% ^^A
% ^^A    Beside a larger functionality \texttt{array.sty} has one
% ^^A    important difference to the standard \texttt{tabular} and
% ^^A    \texttt{array} environments: horizontal and vertical rules make a
% ^^A    table larger or wider, e.g., \verb=\doublerulesep= really denotes
% ^^A    the space between two rules and isn't measured from the middle of
% ^^A    the rules.
% ^^A
% ^^A  \begin{macro}{\@xhline}
% ^^A    For vertical rules this is implemented by the definitions above,
% ^^A    for horizontal rules we have to take out the backspace.
%    \begin{macrocode}
 % \CheckCommand*\@xhline{\ifx\reserved@a\hline
 %                \vskip\doublerulesep
 %                \vskip-\arrayrulewidth
 %              \fi
 %       \ifnum0=`{\fi}}
 % \renewcommand*\@xhline{\ifx\reserved@a\hline
 %                \vskip\doublerulesep
 %              \fi
 %       \ifnum0=`{\fi}}
%    \end{macrocode}
% ^^A  \end{macro}
% ^^A
% ^^A
%    \begin{macrocode}
 % %%%%%%%%%% end array.sty 2016/10/06 v2.4d %%%%%%%%% 
 % 
%    \end{macrocode}
% ^^A
% ^^A
%
% \subsubsection{Class additions to Array}
% 
% \begin{macro}{\m@mold@addamp}
% \begin{macro}{\m@m@addamp}
% \begin{macro}{\@addamp}
%
%    In the preamble a \verb?&? has to be inserted between any two columns;
%    before the first column there should not be a \verb?&?. As the user
%    preamble may start with a \verb?|? we have to remember somehow
%    if we have already inserted a \verb?#? (i.e.\ a column). This is done
%    with the boolean variable \cs{if@firstamp} that we test in
%    \cs{@addamp}, the macro that inserts the \verb?&?.
%
% \begin{PW}
%    PW: Later on, for horizontal lines in `continuous' tabulars,
% I need to know how many columns there are in a tabular. I need a modified
% kernel's \cs{@addamp} to do this and use the kernel's \cs{@curtab}
% (a counter used in tabbing) to store the number of columns.
%
% \cs{m@mold@addamp} stores the kernel's definition of \cs{@addamp}, and
% \cs{m@m@addamp} is the revised definition.
% \end{PW}
%
%    \begin{macrocode}
\newif \@iffirstamp
\let\m@mold@addamp\@addamp
\newcommand*{\m@m@addamp}{%
  \if@firstamp 
    \@firstampfalse
    \global\@curtab\@ne
  \else
    \@addtopreamble{&}
    \global\advance\@curtab\@ne  
  \fi}
\let\@addamp\m@m@addamp

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%



% \subsection{D column specifiers} \label{sec:dcolumns}
%
%
% Here ealier versions of the class had an embedded copy of the
% \Lpack{cdolumn} package. Now replaced by requiring the packge instead.
%    \begin{macrocode}
\RequirePackage{dcolumn}[2014/10/28]
%    \end{macrocode}
% The embeded copy is outcommented for now and will be removed in a
% later version.
%
% \changes{v3.7h}{2018/09/06}{Outcommented the embedded copy of
% \Lpack{dcolumn} and replaced it with requiring the \Lpack{dcolumn} package
% instead.}
%
% ^^A The description and code are essentially copied from the 
% ^^A \Lpack{dcolumn} package~\cite{DCOLUMN}.
% ^^A
%    \begin{macrocode}
 % %%%%%%%%%% Dcolumn package code %%%%%%%%%%%%%%%%%%%%%
 % %%%%%%%%%% With acknowledgements to David Carlisle %%%%%%%%%%%%%%%%%%%%%
 % 
%    \end{macrocode}
% ^^A
% ^^A
% ^^A The \Lpack{dcolumn} package~\cite{DCOLUMN} defines \texttt{D} 
% ^^A to be a column specifier
% ^^A with three arguments.\\
% ^^A \verb?D?\marg{sep.tex}\marg{sep.dvi}\marg{decimal places}
% ^^A for columns which are to be aligned on a `decimal point'.
% ^^A 
% ^^A
% ^^A The basic ideas behind these macros have been explained earlier.
% ^^A However they use three
% ^^A tricks which may be useful in other contexts.
% ^^A \begin{itemize}
% ^^A \item The separator is surrounded in extra \verb?{ }?, so that it is set
% ^^A with \cs{mathord} spacing, otherwise, for instance a `,' would have
% ^^A extra space after it.
% ^^A \item The separator is not given its special definition by making it
% ^^A active, as this would not work for an entry such as \verb?& .5 &?, as the
% ^^A first token of an alignment entry is read \emph{before} the preamble
% ^^A part, incase it is an \cs{omit}, in which case the preamble is to be
% ^^A omitted. Instead we switch the mathcode to (hex) 8000, which makes the
% ^^A token act as if it were active.
% ^^A \item Although \verb?\mathcode`.="8000?  makes \texttt{.} act as if it
% ^^A were active, it is still not allowed in constructions such as
% ^^A \verb?\def.{}?, even in math-mode, so we have to construct an active
% ^^A version of the separator, this is done by making it the uppercase of
% ^^A \verb?~?, and then using the construct\\
% ^^A \verb?\uppercase{\def~}?\marg{definition}.\\
% ^^A Note that the \meta{definition} is not uppercased, so the definition
% ^^A can refer to the standard, non-active use of the separator.
% ^^A \end{itemize}
% ^^A
% ^^A \begin{macro}{\DC@}
% ^^A Set up uppercase tables as required, and then grab the first part of
% ^^A the numerical argument into \cs{count@}.
%    \begin{macrocode}
 % \def\DC@#1#2#3{%
 %   \uccode`\~=`#1\relax
 %   \m@th
 %   \afterassignment\DC@x\count@#3\relax{#1}{#2}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\DC@x}
% ^^A If \cs{count@} is negative, centre on the decimal point. If it is
% ^^A positive either \verb?#1? will be empty in which case bad out decimal
% ^^A part to the number of digits specified by \cs{count@} or 
% ^^A it is none empty in which case \cs{count@} contains the
% ^^A number of digits to the left of the point, and \verb?#1? contains a junk
% ^^A token (probably \verb?.?) followed by the number of digits to the right
% ^^A of the point. In either of these latter cases, \cs{DC@right} is used.
%    \begin{macrocode}
 % \def\DC@x#1\relax#2#3{%
 %   \ifnum\z@>\count@
 %     \expandafter\DC@centre
 %   \else
 %     \expandafter\DC@right
 %   \fi
 %   {#2}{#3}{#1}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\DC@centre}
% ^^A If centering on the decimal point, just need to box up the two halves.
%    \begin{macrocode}
 % \def\DC@centre#1#2#3{%
 %   \let\DC@end\DC@endcentre
 %   \uppercase{\def~}{$\egroup\setbox\tw@=\hbox\bgroup${#2}}%$
 %   \setbox\tw@=\hbox{${\phantom{{#2}}}$}%
 %   \setbox\z@=\hbox\bgroup$\mathcode`#1="8000 }%$
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\DC@endcentre}
% ^^A and then pad out the smaller of the two boxes so there is the same
% ^^A amount of stuff either side of the point.
%    \begin{macrocode}
 % \def\DC@endcentre{$\egroup%$
 %     \ifdim \wd\z@>\wd\tw@
 %       \setbox\tw@=\hbox to\wd\z@{\unhbox\tw@\hfill}%
 %     \else
 %       \setbox\z@=\hbox to\wd\tw@{\hfill\unhbox\z@}\fi
 %     \box\z@\box\tw@}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\DC@right}
% ^^A This deals with both the cases where a specified number of decimal
% ^^A places is given.
%    \begin{macrocode}
 % \def\DC@right#1#2#3{%
 %   \ifx\relax#3\relax
%    \end{macrocode}
% ^^A If \verb?#3? is empty, add \cs{hfill} to right align the column, and 
% ^^A Just set \cs{DC@rl} to begin a group, so nothing fancy is done with
% ^^A the whole number part.
%    \begin{macrocode}
 %     \hfill
 %     \let\DC@rl\bgroup
 %   \else
%    \end{macrocode}
% ^^A Otherwise  set \cs{DC@rl} so that the whole number part is put in a
% ^^A box \cs{count@} times as wide as a digit.
% ^^A In order to share code with the other branch, then move \verb?#3? (the
% ^^A number of decimal places) into \cs{count@} throwing away the `.' from
% ^^A the user syntax.
%    \begin{macrocode}
 %     \edef\DC@rl{to\the\count@\dimen@ii\bgroup\hss\hfill}%
 %     \count@\@gobble#3\relax
 %   \fi
%    \end{macrocode}
% ^^A
%    \begin{macrocode}
 %   \let\DC@end\DC@endright
%    \end{macrocode}
% ^^A Box 2 contains the decimal part, set to \cs{dimen@} which is
% ^^A calculated below to be \cs{count@} times the width of a digit, plus
% ^^A the width of the `decimal point'.
%    \begin{macrocode}
 %   \uppercase{\def~}{$\egroup\setbox\tw@\hbox to\dimen@\bgroup${#2}}%
 %    \setbox\z@\hbox{$1$}\dimen@ii\wd\z@
 %    \dimen@\count@\dimen@ii
 %    \setbox\z@\hbox{${#2}$}\advance\dimen@\wd\z@
 %    \setbox\tw@\hbox to\dimen@{}%
%    \end{macrocode}
% ^^A Box 0 contains the whole number part, either just at its natural
% ^^A size for right aligned columns, or set to (the old value of)
% ^^A \cs{count@} times the width of a digit. \cs{DC@rl} defined above
% ^^A determines the two cases.
%    \begin{macrocode}
 %    \setbox\z@\hbox\DC@rl$\mathcode`#1="8000 }%$
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\DC@endright}
% ^^A Just finish off the second box, and then put out both boxes.
%    \begin{macrocode}
 % \def\DC@endright{$\hfil\egroup\box\z@\box\tw@}%$
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{D}
% ^^A The user interface, define the {\tt D} column to take three arguments.
% ^^A For special purposes, you may need to directly access \cs{DC@} rather
% ^^A than the \verb?D? column, eg to get a bold version you could use
% ^^A\begin{verbatim}
% ^^A \newcolumntype{E}[3]{>{\boldmath\DC@{#1}{#2}{#3}}c<{\DC@end}}
% ^^A\end{verbatim}
%    \begin{macrocode}
 % \newcolumntype{D}[3]{>{\DC@{#1}{#2}{#3}}c<{\DC@end}}
 % 
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
%    \begin{macrocode}
 % %%%%%%%%%% end Dcolumn package code %%%%%%%%%%%%%%%%%%%%%
 % 
%    \end{macrocode}
% ^^A
%
%
% \subsection{Support for delimeters}
%
% Here ealier versions of the class had an embedded copy of the
% \Lpack{dearray} package. Now replaced by requiring the packge instead.
%    \begin{macrocode}
\RequirePackage{delarray}[2014/10/28]
%    \end{macrocode}
% The embeded copy is outcommented for now and will be removed in a
% later version.
%
% \changes{v3.7h}{2018/09/06}{Outcommented the embedded copy of
% \Lpack{delarray} and replaced it with requiring the \Lpack{delarray} package
% instead.}
% ^^A
% ^^A The description and code are essentially from the 
% ^^A \Lpack{delarray} package~\cite{DELARRAY}, v1.01 1994/03/14.
% ^^A
%    \begin{macrocode}
 % %%%%%%%%%% Delarray package code %%%%%%%%%%%%%%%%%%%%%
 % %%%%%%%%%% With acknowledgements to David Carlisle %%%%%%%%%%%%%%%%%%%%%
 % 
%    \end{macrocode}
% ^^A
% ^^A
% ^^A The array syntax is extended by
% ^^A supporting the notation of delimiters. To this end we extend the
% ^^A array parsing mechanism to include a hook which can be used by this
% ^^A (or another) package to do some additional parsing.
% ^^A
% ^^A
% ^^A \begin{macro}{\@@array}
% ^^A    This macro tests for an optional delimiter before the left brace
% ^^A    of the main preamble argument. If there is no delimiter,
% ^^A    \cs{@arrayleft} and \cs{@arrayright} are made a no-ops, and
% ^^A    \cs{@array} is called with the positional argument. Otherwise
% ^^A    call \cs{@del@array}.
%    \begin{macrocode}
 % \def\@@array[#1]{\@ifnextchar\bgroup
 %   {\let\@arrayleft\relax\let\@arrayright\relax\@array[#1]}%
 %   {\@del@array[#1]}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \begin{macro}{\@del@array}
% ^^A    We now know that we have an {\tt array} (or {\tt tabular}) with
% ^^A    delimiters.
%    \begin{macrocode}
 % \def\@del@array[#1]#2#3#4{%
%    \end{macrocode}
% ^^A The following line is completely redundant but it does catch errors
% ^^A involving delimiters  before the processing of the alignment begins.
% ^^A A common error is likely to be omiting the `.' in a
% ^^A \cs{cases}-type construction. This causes the first token of the
% ^^A alignment to be gobbled, possibly causing lots of spurious errors
% ^^A before the cause of the error, the missing delimiter, is discovered as
% ^^A \cs{@arrayright} puts the alignment and the delimiters together.
%    \begin{macrocode}
 %   \setbox\z@\hbox{$\left#2\right#4$}%
%    \end{macrocode}
% ^^A In the case of a `c' argument we do not need to rebox the alignment,
% ^^A so we can define \cs{@arrayleft} and \cs{@arrayright} just to
% ^^A insert the delimiters.
%    \begin{macrocode}
 %   \if#1c\def\@arrayleft{\left#2}\def\@arrayright{\right#4}%
%    \end{macrocode}
% ^^A Otherwise we (should) have a {\tt[t]} or {\tt[b]} argument, so first we
% ^^A store the alignment, without delimiters in box0.
%    \begin{macrocode}
 %   \else\def\@arrayleft{\setbox\z@}%
%    \end{macrocode}
% ^^A Then after the alignment is finished:
%    \begin{macrocode}
 %   \def\@arrayright{%
%    \end{macrocode}
% ^^A Calculate the amount the box needs to be lowered (this will be
% ^^A negative in the case of \verb?[b]?). A little bit of arithmetic cf.\
% ^^A \theTeXbook, Appendix G, rule 8. We calculate the amount this
% ^^A way, rather than just taking the difference between the depth of box0
% ^^A and the depth of the box defined below, as the depth of that box may
% ^^A be affected by the delimiters if \cs{delimitershortfall} or
% ^^A \cs{delimiterfactor} have non-standard values.
%    \begin{macrocode}
 %      \dimen@=\dp\z@
 %      \advance\dimen@-\ht\z@
 %      \divide \dimen@ by \tw@
 %      \advance\dimen@ by\fontdimen22 \textfont\tw@
%    \end{macrocode}
% ^^A Now lower the alignment and the delimiters into place.
%    \begin{macrocode}
 %      \lower\dimen@\hbox{$\left#2\vcenter{\unvbox\z@}\right#4$}}%
%    \end{macrocode}
% ^^A End the \verb?\if#1c?
%    \begin{macrocode}
 %   \fi
%    \end{macrocode}
% ^^A Now that we have defined \cs{@arrayleft} and \cs{@arrayright}, call
% ^^A \cs{@array}.
%    \begin{macrocode}
 %   \@array[#1]{#3}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A
%    \begin{macrocode}
 % %%%%%%%%%% end Delarray package code %%%%%%%%%%%%%%%%%%%%%
 % 
%    \end{macrocode}
% ^^A
%
%
% \subsection{The tabularx environment}
%
% Here ealier versions of the class had an embedded copy of the
% \Lpack{tabularx} package. Now replaced by requiring the packge instead.
%    \begin{macrocode}
\RequirePackage{tabularx}[2016/02/03]
%    \end{macrocode}
% The embeded copy is outcommented for now and will be removed in a
% later version.
%
% \changes{v3.7h}{2018/09/06}{Outcommented the embedded copy of
% \Lpack{tabularx} and replaced it with requiring the \Lpack{tabularx} package
% instead.}

%
% ^^A The code and description are essentially from David Carlisle's  
% ^^A \Lpack{tabularx} package~\cite{TABULARX}, v2.07 1999/01/07.
% ^^A
%    \begin{macrocode}
 % %%%%%%%%%% Tabularx package code %%%%%%%%%%%%%%%%%%%%%
 % %%%%%%%%%% With acknowledgements to David Carlisle %%%%%%%%%%%%%%%%%%%%%
 % 
 % %%% This is a carbon copy of the tabularx dtx sources for v2.11,
 % %%% 2016/02/03 with two changes: error messages mention the class
 % %%% instead of tabularx. 
 % 
 % %%%%%%%%%% Tabularx package code v2.11 2016/02/03 %%%%%%%%%%%%%%%%%%%%%
 % 
%    \end{macrocode}
% ^^A
% ^^A
% ^^A
% ^^A The \Lpack{tabularx} package~\cite{TABULARX} implements a version of the \texttt{tabular}
% ^^A environment in which the widths of certain columns are calculated so
% ^^A that the table is is a specified width. The columns that may stretch are
% ^^A marked by an \texttt{X} in the preamble argument.
% ^^A
% ^^A What follows is a carbon copy of the contents of \texttt{tabularx.dtx} with small changes: (1) We make errors/warnings
% ^^A mention the class instead of \texttt{tabularx}, (2) we strip \texttt{tabularx} related \cs{changes} macros, (3) we
% ^^A remove loading the \Lpack{array} package, as we already come with a copy.
% ^^A
% ^^A First some registers etc.\ that we need.
%    \begin{macrocode}
 % \newdimen\TX@col@width
 % \newdimen\TX@old@table
 % \newdimen\TX@old@col
 % \newdimen\TX@target
 % \newdimen\TX@delta
 % \newcount\TX@cols
 % \newif\ifTX@
%    \end{macrocode}
% ^^A
% ^^A Now a trick to get the body of an environment into a token register, without doing any expansion. This does not do any
% ^^A real checking of nested environments, so if you should need to nest one {\ttfamily tabularx} inside another, the inner
% ^^A one must be surrounded by \verb+{ }+.
% ^^A
% ^^A \begin{macro}{\tabularx}
% ^^A Prior to (\texttt{tabularx}) v1.06, this macro took two arguments, which were saved in
% ^^A separate registers before the table body was saved by \verb+\TX@get@body+.
% ^^A Unfortunately this disables the \verb|[t]| optional argument. Now just save
% ^^A the width specification separately, then clear the token register
% ^^A \verb|\toks@|.
% ^^A Finally call \verb|\TX@get@body| to begin saving the body of the table.
% ^^A The \verb|{\ifnum0=`}\fi| was added at (tabularx) v1.03, to allow \Lenv{tabularx} to appear
% ^^A inside a \verb|\halign|.^^A
% ^^A \setbox0=\hbox{\footnotesize"\iffalse{\fi\ifnum0=`}\fi"}^^A
% ^^A \setbox2=\hbox{\footnotesize"\ifnum0=`{}\fi"}^^A
% ^^A \footnote{This adds an extra level of grouping,
% ^^A which is not really needed. Instead, I could use \box0\ here, and
% ^^A \box2\ below, however the code here would then have to be moved after
% ^^A the first line, because of the footnote to page 386 of the \TeX{}Book,
% ^^A and I do not think I should be writing code that is so obscure as to
% ^^A be documented in a footnote in an appendix called ``Dirty Tricks''!}
% ^^A
% ^^A This mechanism of grabbing an environment body does have the
% ^^A disadvantage (shared with the AMS alignment environments) that you
% ^^A can not make extension environments by code such as
% ^^A\begin{verbatim}
% ^^A\newenvironment{foo}{\begin{tabularx}{XX}}{\end{tabularx}}
% ^^A\end{verbatim}
% ^^A as the code is looking for a literal string \verb"\end{tabularx}" to stop
% ^^A scanning. Since version (tabularx) 2.02, one may avoid this problem by using
% ^^A \verb|\tabularx| and \verb|\endtabularx| directly in the definition:
% ^^A\begin{verbatim}
% ^^A\newenvironment{foo}{\tabularx{XX}}{\endtabularx}
% ^^A\end{verbatim}
% ^^A The scanner now looks for the end of the current environment (\verb|foo| in
% ^^A this example.) There are some restrictions on this usage, the
% ^^A principal one being that \verb|\endtabularx| must not be inside any \verb"{ }" pairs
% ^^A ao that the code before \verb"\endtabularx"  may be extracted and added to the table body
% ^^A (prior to version (tabularx) 2.09  \verb"\endtabularx" had to be
% ^^A the \emph{first} token of the `end code' of the environment).
%    \begin{macrocode}
 % \def\tabularx#1{%
%    \end{macrocode}
% ^^A Allow \verb"\tabularx" \verb"\endtabularx" (but not \verb"\begin{tabularx}"
% ^^A \verb"\end{tabularx}") to be used in \verb"\newenvironment" definitions.
%    \begin{macrocode}
 % \edef\TX@{\@currenvir}%
 %   {\ifnum0=`}\fi
%    \end{macrocode}
% ^^A \verb"\relax" added at v1.05 so that non-expandable length tokens, like
% ^^A \verb"\textwidth" do not generate an extra space, and an overfull box.
% ^^A \verb"\relax" removed again at v4.09 in favour of \verb"\setlength" so if you
% ^^A use the calc package you can use a width of \verb"(\textwidth-12pt)/2".
%    \begin{macrocode}
 %   \setlength\TX@target{#1}%
 %   \TX@typeout{Target width: #1 = \the\TX@target.}%
 %   \toks@{}\TX@get@body}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A 
% ^^A  \begin{macro}{\endtabularx}
% ^^A This does not do very much\ldots
%    \begin{macrocode}
 % \let\endtabularx\relax
%    \end{macrocode}
% ^^A  \end{macro}
% ^^A
% ^^A \begin{macro}{\TX@get@body}
% ^^A Place all tokens as far as the first \verb"\end" into a token register.
% ^^A Then call \verb"\TX@find@end" to see if we are at \verb"\end{tabularx}".
%    \begin{macrocode}
 % \long\def\TX@get@body#1\end
 %   {\toks@\expandafter{\the\toks@#1}\TX@find@end}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\TX@find@end}
% ^^A If we are at \verb"\end{tabularx}", call \verb"\TX@endtabularx", otherwise
% ^^A add \verb"\end{...}" to the register, and call \verb"\TX@get@body" again.
%    \begin{macrocode}
 % \def\TX@find@end#1{%
 %   \def\@tempa{#1}%
 %   \ifx\@tempa\TX@\expandafter\TX@endtabularx
 %   \else\toks@\expandafter
 %     {\the\toks@\end{#1}}\expandafter\TX@get@body\fi}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\TX@find@endtabularxa}
% ^^A split up the end code, and extract the part that lives in the table body.
%    \begin{macrocode}
 % \long\def\TX@find@endtabularxa
 %        #1\endtabularx#2\endtabularx#3\TX@find@endtabularxa{%
 %   \ifx\TX@#2\relax\else
 %   \toks@\expandafter{\the\toks@#1}%
 %   \fi}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \begin{macro}{\TX@find@endtabularxb}
% ^^A split up the end code, and extract the part that lives outside the table body.
%    \begin{macrocode}
 % \long\def\TX@find@endtabularxb
 %        #1\endtabularx#2\endtabularx#3\TX@find@endtabularxb{%
 %   \ifx\TX@#2%
 %     \expandafter\@firstoftwo
 %   \else
 %      \expandafter\@secondoftwo
 %   \fi
 %   {#1}{#2}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\TX@find@endtabularxbb}
% ^^A Helper to avoid needing 15 consecutive \verb"\expandafter"
%    \begin{macrocode}
 % \def\TX@find@endtabularxbb{%
 %   \expandafter\expandafter\expandafter
 %   \TX@find@endtabularxb
 % }
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\TX@}
% ^^A The string {\ttfamily tabularx} as a macro for testing with \verb"\ifx".
%    \begin{macrocode}
 % \def\TX@{tabularx}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A Now that all the parts of the table specification are stored in
% ^^A registers, we can begin the work of setting the table.
% ^^A
% ^^A The algorithm for finding the correct column widths is as follows.
% ^^A Firstly set the table with each {\ttfamily X} column the width of the
% ^^A final table. Assuming that there is at least one {\ttfamily X} column,
% ^^A this will produce a table that is too wide. Divide the excess width by
% ^^A the number of {\ttfamily X} columns, and reduce the column width by
% ^^A this amount. Reset the table. If the table is not now the correct
% ^^A width, a \verb"\multicolumn" entry must be `hiding' one of the {\ttfamily
% ^^A X} columns, and so there is one less {\ttfamily X} column affecting
% ^^A the width of the table. So we reduce by 1 the number of X columns and
% ^^A repeat the process.
% ^^A
% ^^A \begin{macro}{\TX@endtabularx}
% ^^A Although I have tried to make {\ttfamily tabularx} look like an
% ^^A environment, it is in fact a command, all the work is done by this
% ^^A macro.
%    \begin{macrocode}
 % \def\TX@endtabularx{%
 %    \expandafter\expandafter\expandafter
 %      \TX@find@endtabularxa\csname end\TX@\endcsname
 %      \endtabularx\TX@\endtabularx\TX@find@endtabularxa
%    \end{macrocode}
% ^^A Define the {\ttfamily X} column, with an internal version of the
% ^^A \verb"\newcolumntype" command. The \verb"\expandafter" commands enable
% ^^A \verb"\NC@newcol"  to get the {\em expansion} of\\
% ^^A \verb"\tabularxcolumn{\TX@col@width}" as its
% ^^A argument. This will be the definition of an {\ttfamily X} column, as
% ^^A discussed in section 4.
%    \begin{macrocode}
 %   \expandafter\TX@newcol\expandafter{\tabularxcolumn{\TX@col@width}}%
%    \end{macrocode}
% ^^A Initialise the column width, and the number of {\ttfamily X} columns.
% ^^A The number of {\ttfamily X} columns is set to one, which means that
% ^^A the initial count will be one too high, but this value is decremented
% ^^A before it is used in the main loop.
% ^^A
% ^^A Since v1.02, switch the definition of \verb"\verb".
%    \begin{macrocode}
 %   \let\verb\TX@verb
%    \end{macrocode}
% ^^A Since v1.05, save the values of all \LaTeX\ counters, the list
% ^^A \verb"\cl@@ckpt" contains the names of all the \LaTeX\ counters that have
% ^^A been defined so far. We expand \verb"\setcounter" at this point, as it
% ^^A results in fewer tokens being stored in \verb"\TX@ckpt", but the actual
% ^^A resetting of the counters occurs when \verb"\TX@ckpt" is expanded after
% ^^A each trial run.
% ^^A Actually since v1.07, use something equivalent to the expansion of the
% ^^A original definition of \verb"\setcounter", so that \verb"tabularx" works in
% ^^A conjunction with \verb"calc.sty".
%    \begin{macrocode}
 %   \def\@elt##1{\global\value{##1}\the\value{##1}\relax}%
 %   \edef\TX@ckpt{\cl@@ckpt}%
 %   \let\@elt\relax
 %   \TX@old@table\maxdimen
 %   \TX@col@width\TX@target
 %   \global\TX@cols\@ne
%    \end{macrocode}
% ^^A Typeout some headings (unless this is disabled).
%    \begin{macrocode}
 %   \TX@typeout@
 %     {\@spaces Table Width\@spaces Column Width\@spaces X Columns}%
%    \end{macrocode}%
% ^^A First attempt. Modify the {\ttfamily X} definition to count {\ttfamily
% ^^A X} columns.
%    \begin{macrocode}
 %   \TX@trial{\def\NC@rewrite@X{%
 %           \global\advance\TX@cols\@ne\NC@find p{\TX@col@width}}}%
%    \end{macrocode}
% ^^A Repeatedly decrease column width until table is the correct width,
% ^^A or stops shrinking, or the columns become two narrow.
% ^^A If there are no multicolumn entries, this will only take one attempt.
%    \begin{macrocode}
 %   \loop
 %     \TX@arith
 %     \ifTX@
 %     \TX@trial{}%
 %   \repeat
%    \end{macrocode}
% ^^A One last time, with warnings back on (see appendix D)
% ^^A use {\ttfamily tabular*} to put it in a box of the right size, in case
% ^^A the algorithm failed to find the correct size.
% ^^A
% ^^A Since v1.04, locally make \verb"\footnotetext" save its argument in a token
% ^^A register.
% ^^A Since v1.06, \verb"\toks@" contains the preamble specification,
% ^^A and possible optional argument, as well as the table body.
%    \begin{macrocode}
 %   {\let\@footnotetext\TX@ftntext\let\@xfootnotenext\TX@xftntext
 %     \csname tabular*\expandafter\endcsname\expandafter\TX@target
 %       \the\toks@
 %     \csname endtabular*\endcsname}%
%    \end{macrocode}
% ^^A Now the alignment is finished, and the \verb"}" has restored the original
% ^^A meaning of \verb"\@footnotetext" expand the register \verb"\TX@ftn" which will
% ^^A execute a series of\\
% ^^A \verb"\footnotetext["\meta{num}\verb"]{"\meta{note}\verb"}"\\
% ^^A commands. We need to be careful about clearing the register as we may
% ^^A be inside a nested {\ttfamily tabularx}.
%    \begin{macrocode}
 %   \global\TX@ftn\expandafter{\expandafter}\the\TX@ftn
%    \end{macrocode}
% ^^A Now finish off the {\ttfamily tabularx} environment. Note that we need
% ^^A \verb"\end{tabularx}" here as the \verb"\end{tabularx}" in the user's
% ^^A file is never expanded. Now use \verb"\TX@" rather than \verb"tabularx".
% ^^A
% ^^A We also need to finish off the group started by \verb"{\ifnum0=`}\fi" in
% ^^A the macro \verb"\tabularx".
%    \begin{macrocode}
 %   \ifnum0=`{\fi}%
 %    \expandafter\expandafter\expandafter
 %    \TX@find@endtabularxbb
 %     \expandafter\end\expandafter{\TX@}%
 %     \endtabularx\TX@\endtabularx\TX@find@endtabularxb
 % }
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A
% ^^A \begin{macro}{\TX@arith}
% ^^A Calculate the column width for the next try, setting the flag
% ^^A \verb"\ifTX@" to false if the loop should be aborted.
%    \begin{macrocode}
 % \def\TX@arith{%
 %   \TX@false
 %   \@tempdimb\maxdimen
 %   \divide\@tempdimb\TX@cols
 %   \ifdim\TX@col@width>\@tempdimb
 %     \TX@typeout@{Don't exceed \maxdimen}%
 %     \wd\@tempboxa\maxdimen
 %   \fi
 %   \ifdim\TX@old@table=\wd\@tempboxa
%    \end{macrocode}
% ^^A If we have reduced the column width, but the table width has not
% ^^A changed, we stop the loop, and output the table (which will cause an
% ^^A over-full alignment) with the previous value of \verb"\TX@col@width".
%    \begin{macrocode}
 %     \TX@col@width\TX@old@col
 %     \TX@typeout@{Reached minimum width, backing up.}%
 %   \else
%    \end{macrocode}
% ^^A Otherwise calculate the amount by which the current table is too wide.
%    \begin{macrocode}
 %     \dimen@\wd\@tempboxa
 %     \advance\dimen@ -\TX@target
 %     \ifdim\dimen@<\TX@delta
%    \end{macrocode}
% ^^A If this amount is less than \verb"\TX@delta", stop. (\verb"\TX@delta"
% ^^A should be non-zero otherwise we may miss the target due to rounding
% ^^A error.)
%    \begin{macrocode}
 %       \TX@typeout@{Reached target.}%
 %     \else
%    \end{macrocode}
% ^^A Reduce the number of effective {\ttfamily X} columns by one. (Checking
% ^^A that we do not get 0, as this would produce an error later.) Then
% ^^A divide excess width by the number of effective columns, and calculate
% ^^A the new column width. Temporarily store this value (times $-1$) in
% ^^A \verb"\dimen@".
%    \begin{macrocode}
 %       \ifnum\TX@cols>\@ne
 %         \advance\TX@cols\m@ne
 %       \fi
 %       \divide\dimen@\TX@cols
 %       \advance\dimen@ -\TX@col@width
 %       \ifdim \dimen@ >\z@
%    \end{macrocode}
% ^^A If the new width would be too narrow, abort the loop. At the moment
% ^^A too narrow, means less than 0\,pt!
% ^^A
% ^^A Prior to v2.03, if the loop was aborted here, the X columns were left
% ^^A with the width of the previous run, but this may make the table far
% ^^A too wide as initial guesses are always too big. Now force to
% ^^A \verb"\TX@error@width" which defaults to be 1em. If you want to
% ^^A get the old behaviour stick\\
% ^^A  \verb"\renewcommand\TX@error@width{\TX@col@width}"\\
% ^^A  in a package file loaded after \textsf{tabularx}.
%    \begin{macrocode}
 %         %\PackageWarning{tabularx}%
 %          \@memwarn{X Columns too narrow (table too wide)\MessageBreak}% <-- change here
 %         \TX@col@width\TX@error@width\relax
 %       \else
%    \end{macrocode}
% ^^A Otherwise save the old settings, and set the new column width. Set the
% ^^A flag to true so that the table will be set, and the loop will be
% ^^A executed again.
%    \begin{macrocode}
 %         \TX@old@col\TX@col@width
 %         \TX@old@table\wd\@tempboxa
 %         \TX@col@width-\dimen@
 %         \TX@true
 %       \fi
 %     \fi
 %   \fi}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\TX@error@width}
% ^^A If the calculated width is negative, use this instead.
%    \begin{macrocode}
 % \def\TX@error@width{1em}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\TX@delta}
% ^^A Accept a table that is within \verb"\hfuzz" of the correct width.
%    \begin{macrocode}
 % \TX@delta\hfuzz
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A Initialise the {\ttfamily X} column. The definition can be empty here,
% ^^A as it is set for each {\ttfamily tabularx} environment.
%    \begin{macrocode}
 % \newcolumntype{X}{}
%    \end{macrocode}
% ^^A
% ^^A \begin{macro}{\tabularxcolumn}
% ^^A The default definition of {\ttfamily X} is \verb"p{#1}".
%    \begin{macrocode}
 % \def\tabularxcolumn#1{p{#1}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\TX@newcol}
% ^^A A little macro just used to cut down the number of \verb"\expandafter"
% ^^A commands needed.
%    \begin{macrocode}
 % \def\TX@newcol{\newcol@{X}[0]}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\TX@trial}
% ^^A Make a test run.
%    \begin{macrocode}
 % \def\TX@trial#1{%
 %   \setbox\@tempboxa\hbox{%
%    \end{macrocode}
% ^^A Any extra commands. This is used on the first run to count the number
% ^^A of {\ttfamily X} columns.
%    \begin{macrocode}
 %     #1\relax
%    \end{macrocode}
% ^^A Since v1.04, make \verb"\footnotetext" gobble its arguments. Also locally
% ^^A clear \verb"\TX@vwarn" so that the warning is generated by the {\ttfamily
% ^^A final} run, and does not appear in the middle of the table if
% ^^A \verb"\tracingtabularx".
%    \begin{macrocode}
 %   \let\@footnotetext\TX@trial@ftn
 %   \let\TX@vwarn\@empty
%    \end{macrocode}
% ^^A Do not nest {\ttfamily tabularx} environments during trial runs. This
% ^^A would waste time, and the global setting of \verb"\TX@cols" would break the
% ^^A algorithm.
%    \begin{macrocode}
 %    \expandafter\let\expandafter\tabularx\csname tabular*\endcsname
 %    \expandafter\let\expandafter\endtabularx\csname endtabular*\endcsname
%    \end{macrocode}
% ^^A Added at v1.05: disable \verb"\write"s during a trial run. This trick is
% ^^A from the \TeX{}Book.\footnote{Actually the \TeX{}Book trick does
% ^^A not work correctly, so changed for v2.05.}
%    \begin{macrocode}
 %    \def\write{\begingroup
 %      \def\let{\afterassignment\endgroup\toks@}%
 %         \afterassignment\let\count@}%
%    \end{macrocode}
% ^^A Turn off warnings (see appendix D). Also prevent them being turned
% ^^A back on by setting the parameter names to be registers.
%    \begin{macrocode}
 %     \hbadness\@M
 %     \hfuzz\maxdimen
 %     \let\hbadness\@tempcnta
 %     \let\hfuzz\@tempdima
%    \end{macrocode}
% ^^A Make the table, and finish the hbox.
% ^^A Since v1.06, \verb"\toks@" contains the preamble specification,
% ^^A and possible optional argument, as well as the table body.
%    \begin{macrocode}
 %     \expandafter\tabular\the\toks@
 %     \endtabular}%
%    \end{macrocode}
% ^^A Since v1.05 reset all \LaTeX\ counters, by executing \verb"\TX@ckpt".
%    \begin{macrocode}
 %   \TX@ckpt
%    \end{macrocode}
% ^^A Print some statistics.
% ^^A Added \verb"\TX@align" in v1.05, to line up the columns.
%    \begin{macrocode}
 %   \TX@typeout@{\@spaces
 %      \expandafter\TX@align
 %         \the\wd\@tempboxa\space\space\space\space\space\@@
 %      \expandafter\TX@align
 %         \the\TX@col@width\space\space\space\space\space\@@
 %      \@spaces\the\TX@cols}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\TX@align}
% ^^A Macro added at v1.05, to improve the printing of the tracing info.
%    \begin{macrocode}
 % \def\TX@align#1.#2#3#4#5#6#7#8#9\@@{%
 %   \ifnum#1<10 \space\fi
 %   \ifnum#1<100 \space\fi
 %   \ifnum#1<\@m\space\fi
 %   \ifnum#1<\@M\space\fi
 %   #1.#2#3#4#5#6#7#8\space\space}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\arraybackslash}
% ^^A \verb"\\" hack.
%    \begin{macrocode}
 % \ifx\arraybackslash\@undefined
 % \def\arraybackslash{\let\\\tabularnewline}
 % \fi
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\tracingtabularx}
% ^^A Print statistics on column and table widths.
%    \begin{macrocode}
 % \def\tracingtabularx{%
 %   %\def\TX@typeout{\PackageWarningNoLine{tabularx}}%
 %   \def\TX@typeout{\ClassWarningNoLine{memoir}}% <--- changed
 %   \def\TX@typeout@##1{\typeout{(tabularx) ##1}}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\TX@typeout}
% ^^A The default is to be to be quiet
%    \begin{macrocode}
 % \let\TX@typeout\@gobble
 % \let\TX@typeout@\@gobble
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\TX@ftn}
% ^^A A token register for saving footnote texts.
%    \begin{macrocode}
 % \newtoks\TX@ftn
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\TX@ftntext}
% ^^A \begin{macro}{\TX@xftntext}
% ^^A Inside the alignment just save up the footnote text in a token
% ^^A register.
%    \begin{macrocode}
 % \long\def\TX@ftntext#1{%
 %   \edef\@tempa{\the\TX@ftn\noexpand\footnotetext
 %                     [\the\csname c@\@mpfn\endcsname]}%
 %   \global\TX@ftn\expandafter{\@tempa{#1}}}%
 % \long\def\TX@xftntext[#1]#2{%
 %   \global\TX@ftn\expandafter{\the\TX@ftn\footnotetext[#1]{#2}}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\TX@trial@ftn}
% ^^A On trial runs, gobble footnote texts.
%    \begin{macrocode}
 % \long\def\TX@trial@ftn#1{}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A This last section was added at Version 1.02. Previous versions
% ^^A documented the fact that \verb"\verb" did not work inside {\ttfamily
% ^^A tabularx}, but that did not stop people using it! This usually put
% ^^A \LaTeX\ into an irrecoverable error position, with error messages that
% ^^A did not mention the cause of the error. The `poor man's \verb"\verb"' (and
% ^^A \verb"\verb*") defined here is based on page 382 of the \TeX{}Book. As
% ^^A explained there, doing verbatim this way means that spaces are not
% ^^A treated correctly, and so \verb"\verb*" may well be useless, however I
% ^^A consider this section of code to be error-recovery, rather than a real
% ^^A implementation of verbatim.
% ^^A
% ^^A The mechanism is quite general, and any macro which wants to allow a
% ^^A form of \verb"\verb" to be used within its argument may
% ^^A \verb"\let\verb=\TX@verb". (Making sure to restore the real definition
% ^^A later!)
% ^^A
% ^^A \verb"\verb" and \verb"\verb*" are subject to the following restrictions:
% ^^A \begin{enumerate}
% ^^A \item Spaces in the argument are not read verbatim, but may be skipped
% ^^A       according to \TeX's usual rules.
% ^^A \item Spaces will be added to the output after control words, even if
% ^^A       they were not present in the input.
% ^^A \item Unless the argument is a single space, any trailing space,
% ^^A       whether in the original argument, or added as in (2),
% ^^A       will be omitted.
% ^^A \item The argument must not end with \verb"\", so \verb"\verb|\|" is not
% ^^A      allowed, however, because of (3), \verb"\verb|\ |" produces
% ^^A      \verb"\".
% ^^A \item The argument must be balanced with respect to \verb"{" and \verb"}". So
% ^^A      \verb"\verb|{|" is not allowed.
% ^^A \item A comment character like \verb"%" will not appear verbatim. It will
% ^^A       act as usual, commenting out the rest of the input line!
% ^^A \item The combinations \verb"?`" and \verb"!`" will appear as
% ^^A       {\ttfamily?`} and {\ttfamily!`} if the {\ttfamily cmtt} font is
% ^^A       being used.
% ^^A \end{enumerate}
% ^^A
% ^^A \begin{macro}{\TX@verb}
% ^^A The internal definition of \verb"\verb". Spaces will be replaced by \verb"~", so
% ^^A for the star-form, \verb"\let" \verb"~" be \verb*| |, which we obtain as
% ^^A \verb"\uppercase{*}". Use \verb"{\ifnum0=`}\fi" rather than \verb"\bgroup" to allow
% ^^A \verb"&" to appear in the argument.
%    \begin{macrocode}
 % {\uccode`\*=`\ %
 % \uppercase{\gdef\TX@verb{%
 %   \leavevmode\null\TX@vwarn
 %   {\ifnum0=`}\fi\ttfamily\let\\\ignorespaces
 %   \@ifstar{\let~*\TX@vb}{\TX@vb}}}}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\TX@vb}
% ^^A Get the `almost verbatim' text using \verb"\meaning". The `\verb"!"' is added to
% ^^A the front of the user supplied text, to ensure that the whole argument
% ^^A does not consist of a single \verb"{ }" group. \TeX\ would strip the outer
% ^^A braces from such a group. The `\verb"!"' will be removed later.
% ^^A
% ^^A Originally I followed Knuth, and had \verb"\def\@tempa{##1}", however this
% ^^A did not allow \verb"#" to appear in the argument. So in v1.04, I changed
% ^^A this to to use a token register, and \verb"\edef". This allows \verb"#" appear,
% ^^A but makes each one appear twice!, so later we loop through, replacing
% ^^A \verb"##" by \verb"#".
%    \begin{macrocode}
 % \def\TX@vb#1{\def\@tempa##1#1{\toks@{##1}\edef\@tempa{\the\toks@}%
 %     \expandafter\TX@v\meaning\@tempa\\ \\\ifnum0=`{\fi}}\@tempa!}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\TX@v}
% ^^A Strip the initial segment of the \verb"\meaning", including the `\verb"!"'
% ^^A added earlier.
%    \begin{macrocode}
 % \def\TX@v#1!{\afterassignment\TX@vfirst\let\@tempa= }
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A As explained above we are going to replace \verb"##" pairs by \verb"#". To do
% ^^A this we need non-special \verb"#" tokens.  Make \verb"*" into a parameter
% ^^A token so that we can define macros with arguments. The normal meanings
% ^^A will be restored by the \verb"\endgroup" later.
%    \begin{macrocode}
 % \begingroup
 % \catcode`\*=\catcode`\#
 % \catcode`\#=12
%    \end{macrocode}
% ^^A
% ^^A \begin{macro}{\TX@vfirst}
% ^^A As a special case, prevent the first character from being dropped.
% ^^A This makes \verb"\verb*| |" produce \verb*| |. Then call \verb"\TX@v@".
% ^^A This is slightly tricky since v1.04, as I have to ensure that an
% ^^A actual \verb"#" rather than a command \verb"\let" to \verb"#" is passed on if the
% ^^A first character is \verb"#".
%    \begin{macrocode}
 % \gdef\TX@vfirst{%
 %   \if\@tempa#%
 %     \def\@tempb{\TX@v@#}%
 %   \else
 %     \let\@tempb\TX@v@
 %     \if\@tempa\space~\else\@tempa\fi
 %   \fi
 %   \@tempb}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\TX@v@}
% ^^A Loop through the \verb"\meaning", replacing all spaces by \verb"~". If the last
% ^^A character is a space it is dropped, so that \verb"\verb*|\LaTeX|" produces
% ^^A \verb"\LaTeX" not \verb*|\LaTeX |. The rewritten tokens are then further
% ^^A processed to replace \verb"##" pairs.
%    \begin{macrocode}
 % \gdef\TX@v@*1 *2{%
 %   \TX@v@hash*1##\relax\if*2\\\else~\expandafter\TX@v@\fi*2}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A \begin{macro}{\TX@v@hash}
% ^^A The inner loop, replacing \verb"##" by \verb"#".
%    \begin{macrocode}
 % \gdef\TX@v@hash*1##*2{*1\ifx*2\relax\else#\expandafter\TX@v@hash\fi*2}
%    \end{macrocode}
% ^^A \end{macro}
% ^^A
% ^^A As promised, we now restore the normal meanings of \verb"#" and \verb"*".
%    \begin{macrocode}
 % \endgroup
%    \end{macrocode}
% ^^A
% ^^A \begin{macro}{\TX@vwarn}
% ^^A Warn the user the first time this \verb"\verb" is used.
%    \begin{macrocode}
 % \def\TX@vwarn{%
 %   \@warning{\noexpand\verb may be unreliable inside tabularx}%
 %   \global\let\TX@vwarn\@empty}
%    \end{macrocode}
% ^^A \end{macro}
%    \begin{macrocode}
 % 
 % %%%%%%%%%% end Tabularx package code v2.11 %%%%%%%%%%%%%%%%%%%%%
 % 
 % 
 % 
 % 
%    \end{macrocode}
% ^^A
% ^^A    At this point we had better stop anyone trying to load the several
% ^^A tabular-related packages (as effectively they are already loaded).
%    \begin{macrocode}
 % %%\@memfakeusepackage{array}
 % %%\@memfakeusepackage{dcolumn}
 % %%\@memfakeusepackage{delarray}
 % %%\@memfakeusepackage{tabularx}
 % 
%    \end{macrocode}
% ^^A
% ^^A
%  
% \subsection{Fear's rules}
%
%    Simon Fear disapproves of the default \LaTeX{} table rules and
% wrote the \Lpack{booktabs} package~\cite{BOOKTABS} to provide
% better horizontal rules. Like many typographers, he abhors vertical rules.
%
%
% \begin{macro}{\bktabrule}
% The rules in this section are based on \verb?\hrule \@height#1? but this 
% does not 
% work for continuous tabulars. Provide a version of this that
% can be \cs{let} when necessary.
%    \begin{macrocode}
\newcommand*{\bktabrule}[1]{%
  \hrule \@height#1}

%    \end{macrocode}
% \end{macro}
%
% The following is taken almost verbatim from the \Lpack{booktabs} package,
% version~1.618, March 2003.
%
%    \begin{macrocode}
%%%%%%%%%% Booktabs package code       %%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%% slightly modified by PRW    %%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%% by permission of Simon Fear %%%%%%%%%%%%%%%%%%%%%

%    \end{macrocode}
% Danie Els is now (2005) the official maintainer of the \Lpack{booktabs} package. He provided me with
% some updates to synchronize \Lpack{memoir}, \Lpack{booktabs} and support for \Lpack{colortbl} with \Lpack{booktabs}. I made the appropriate changes/extensions
% on 2005/09/03 as part of version 1.618 of \Lpack{memoir}.
%
% \begin{macro}{\CT@arc@}
% This supports the \Lpack{bookhands}/\Lpack{colortbl} package combination.
%    \begin{macrocode}
\AtBeginDocument{%
  \providecommand*{\CT@arc@}{}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\heavyrulewidth}
% \begin{macro}{\lightrulewidth}
% \begin{macro}{\cmidrulewidth}
% \begin{macro}{\belowrulesep}
% \begin{macro}{\belowbottomsep}
% \begin{macro}{\aboverulesep}
% \begin{macro}{\abovetopsep}
% \begin{macro}{\cmidrulesep}
% \begin{macro}{\cmidrulekern}
% \begin{macro}{\defaultaddspace}
% First we set up some new dimensions.
%    \begin{macrocode}
\newdimen\heavyrulewidth 
\newdimen\lightrulewidth 
\newdimen\cmidrulewidth  
\newdimen\belowrulesep   
\newdimen\belowbottomsep   
\newdimen\aboverulesep   
\newdimen\abovetopsep   
\newdimen\cmidrulesep    
\newdimen\cmidrulekern   
\newdimen\defaultaddspace
\heavyrulewidth=.08em
\lightrulewidth=.05em
\cmidrulewidth=.03em
\belowrulesep=.65ex
\belowbottomsep=\z@
\aboverulesep=.4ex
\abovetopsep=\z@
\cmidrulesep=\doublerulesep
\cmidrulekern=.5em
\defaultaddspace=.5em

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% 
% \begin{macro}{\@cmidla}
% \begin{macro}{\@cmidlb}
% \begin{macro}{\@aboverulesep}
% \begin{macro}{\@belowrulesep}
% \begin{macro}{\@thisruleclass}
% \begin{macro}{\@lastruleclass}
% \begin{macro}{\@thisrulewidth}
% And some internal counters and other things of no interest to the end user:
%    \begin{macrocode}
\newcount\@cmidla
\newcount\@cmidlb
\newdimen\@aboverulesep
\newdimen\@belowrulesep
\newcount\@thisruleclass
\newcount\@lastruleclass
\@lastruleclass=0
\newdimen\@thisrulewidth

%    \end{macrocode}
% which will be described as needed below.
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\futurenonspacelet}
% \begin{macro}{\@BTfnslone}
% \begin{macro}{\@BTfnsltwo}
% \begin{macro}{\@BTfnslthree}
% Next we define a very useful macro (more-or-less straight from the
% \theTeXbook's Dirty Tricks chapter; documented there). Use
% \cs{futurenonspacelet} instead of \cs{futurelet} when looking for the next
% (non-space) token after a macro that has an argument. (After a macro
% without an argument, space is ignored anyway, so \cs{futurenonspacelet}
% wouldn't be needed.) This hack allows users to type white
% space between successive rule commands.
%    \begin{macrocode}
\def\futurenonspacelet#1{\def\@BTcs{#1}%
 \afterassignment\@BTfnslone\let\nexttoken= }
\def\@BTfnslone{\expandafter\futurelet\@BTcs\@BTfnsltwo}
\def\@BTfnsltwo{\expandafter\ifx\@BTcs\@sptoken\let\next=\@BTfnslthree
 \else\let\next=\nexttoken\fi \next}
\def\@BTfnslthree{\afterassignment\@BTfnslone\let\next= }

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsubsection{Full width  rules}
%
% When we are not in a \texttt{longtable} environment, we can simply
% implement the full width rules as a \cs{hrule} in  a \verb?\noalign{}?
% group. But within a \texttt{longtable}, the rule has to be drawn like a
% \verb?\cmidrule{1-\LT@cols}? (the rationale for this is explained in the
% \texttt{longtable} documentation).

% In order to allow for both, all the rule macros have to
% open a \cs{noalign} group immediately, while they work out whether
% they have been called within a \texttt{longtable}; if you don't do this,
% \TeX's underlying \cs{halign} process gets hiccups.
% I use \LaTeX's
% dirty trick (\verb?\ifnum=0`}?) to fool the parser that the bracket
% count is OK. The bracket really gets closed after all the skipping
% at the end of the \cs{@BTendrule} macro.

% The class 1 rules, and \cs{specialrule}, really only differ in the
% defaults for space above and
% below, and the width, passed to a common routine, \cs{@BTrule},
% described below. The spaces, \cs{@aboverulesep} and \cs{@belowrulesep},
% are set within the \cs{noalign} group, so are inherited by
% \cs{@BTrule}. Similarly, \cs{@BTrule} knows as much as it needs to
% about the routine that called it by examining the inherited
% \cs{@thisruleclass}. The optional width argument is parsed by
% \cs{@BTrule} after being set to default if absent.

%
% \begin{macro}{\toprule}
% \begin{macro}{\midrule}
% \begin{macro}{\bottomrule}
% \begin{macro}{\specialrule}
%    \begin{macrocode}
\def\toprule{\noalign{\ifnum0=`}\fi
  \@aboverulesep=\abovetopsep
  \global\@belowrulesep=\belowrulesep
  \global\@thisruleclass=\@ne
  \@ifnextchar[{\@BTrule}{\@BTrule[\heavyrulewidth]}}

\def\midrule{\noalign{\ifnum0=`}\fi
  \@aboverulesep=\aboverulesep
  \global\@belowrulesep=\belowrulesep
  \global\@thisruleclass=\@ne
  \@ifnextchar[{\@BTrule}{\@BTrule[\lightrulewidth]}}

\def\bottomrule{\noalign{\ifnum0=`}\fi
  \@aboverulesep=\aboverulesep
  \global\@belowrulesep=\belowbottomsep
  \global\@thisruleclass=\@ne
  \@ifnextchar[{\@BTrule}{\@BTrule[\heavyrulewidth]}}

\def\specialrule#1#2#3{\noalign{\ifnum0=`}\fi
  \@aboverulesep=#2\global\@belowrulesep=#3\global\@thisruleclass=\tw@
  \@BTrule[#1]}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \begin{macro}{\addlinespace}
% An \cs{addlinespace} is essentially a zero-width rule with
% zero space above and argument (or default) space below. But because
%  the rule is not actually drawn, but is just a \cs{vskip}, there is no
%  need to check if we're in a longtable, so we don't need to call
%  \cs{@BTrule} as for `real' rules. But we do share the \cs{@BTendrule}
%  lookahead and flagsetting code (described below), and the \cs{vskip} is done there.
%    \begin{macrocode}
\def\addlinespace{\noalign{\ifnum0=`}\fi
  \@ifnextchar[{\@addspace}{\@addspace[\defaultaddspace]}}
\def\@addspace[#1]{\global\@belowrulesep=#1\global\@thisruleclass=\tw@
  \futurelet\@tempa\@BTendrule}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\@BTrule}
% All the rules (except \cs{addlinespace}) share this code.
%    \begin{macrocode}
\def\@BTrule[#1]{%
%    \end{macrocode}
% Note (2016/05/16): code rearranged a bit to come back into sync with
% \Lpack{booktabs} v1.618033.
%
% \changes{v3.7f}{2016/05/16}{changed the order so the \cs{ifx} lines
% come first. From booktabs 2016/04/27 v1.618033}
% Now we work out, by a very nasty hack, if we're within a
%  \texttt{longtable}. It's easy if \cs{longtable} isn't even defined: then we
%  can't be. But it is not enough just to check if \texttt{longtable} is
%  loaded --- we might be within an ordinary table rather than a
%  longtable. So we look to see if \cs{hline} has been re-defined
%  from its \LaTeX\ definition to be the same as
%  \cs{LT@hline}. (Longtable currently does this redefinition when it opens a
%  \texttt{longtable} environment, but not globally, so it is
%  cleared it when the environment closes.) Another
%  package could potentially do this! And \texttt{longtable} might change the
%  way it implements this! So, it is not entirely safe, but I have
%  found no better way so far.
%
%  We set up \cs{@BTswitch} to call \cs{@BTnormal} or \cs{@BLTrule}, as
%  appropriate, then call it.
%    \begin{macrocode}
  \ifx\longtable\undefined 
    \let\@BTswitch\@BTnormal
  \else\ifx\hline\LT@hline
    \let\@BTswitch\@BLTrule
  \else
    \let\@BTswitch\@BTnormal
  \fi\fi
%    \end{macrocode}
% On with the code
%    \begin{macrocode}
  \global\@thisrulewidth=#1\relax
%    \end{macrocode}
% Save the width argument (if the user didn't give one, then the
% calling routine will have called \cs{@BTrule} with the default) in a global
% variable for later use when drawing the rule.
%    \begin{macrocode}
  \ifnum\@thisruleclass=\tw@\vskip\@aboverulesep\else
%    \end{macrocode}
% Specialrules always insert specified space above. (Note: addlinespaces
% don't come here).
%    \begin{macrocode}
  \ifnum\@lastruleclass=\z@\vskip\@aboverulesep\else
  \ifnum\@lastruleclass=\@ne\vskip\doublerulesep\fi\fi\fi
%    \end{macrocode}
% After text (last rule class 0), precede the rule by \cs{aboverulesep};
% but if immediately after a
% previous rule, insert a \cs{doublerulesep}.
%
%    \begin{macrocode}
  \@BTswitch}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@BTnormal}
% This is when we're \emph{not} within a longtable. We are already in a
%  \cs{noalign} group, all we need do is draw an \cs{hrule} and gobble any
%  trailing spaces, then call the closing routine with \cs{@tempa} set
%  equal to the next token in the document.
%    \begin{macrocode}
% \def\@BTnormal{\hrule
%   \@height \@thisrulewidth\futurenonspacelet\@tempa\@BTendrule}
\def\@BTnormal{%
%%  \bktabrule{\@thisrulewidth}
  {\CT@arc@\bktabrule{\@thisrulewidth}}%
  \futurenonspacelet\@tempa\@BTendrule}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@BLTrule}
% This is for full width rule within a \texttt{longtable}. First we check if
%  a kerning argument has been used; if so let \cs{@@BLTrule} read it,
%  else call \cs{@@BLTrule} with an empty string:
%    \begin{macrocode}
\def\@BLTrule{\@ifnextchar({\@@BLTrule}{\@@BLTrule()}}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\@@BLTrule}
%    \begin{macrocode}
\def\@@BLTrule(#1){\@setrulekerning{#1}%
\global\@cmidlb\LT@cols
%    \end{macrocode}
% The \cs{@setrulekerning} routine parses the kerning argument tokens
% and sets global kerning widths accordingly (or to defaults, if user
% hasn't set them explicitly). The global assignment to \cs{@cmidlb}
% sets up the column count for the \cs{@cmidruleb} macro, which is
% shared with \verb?cmidrules?.
%    \begin{macrocode}
\ifnum0=`{\fi}%
%    \end{macrocode}
% Close the currently open \cs{noalign} group. Within a \texttt{longtable},
% rules are all to be drawn as leaders within a text box that is
% \cs{LT@cols} columns wide.
%    \begin{macrocode}
\@cmidruleb
%    \end{macrocode}
% Draw the rule. We share the \cs{@cmidruleb} code with ordinary \cs{cmidrule}s.
%    \begin{macrocode}
\noalign{\ifnum0=`}\fi
%    \end{macrocode}
% We have to open a new noalign immediately else \TeX{} will start a new
%    text box where we don't want one. Then, after gobbling any
%    unwanted white space, we call the closing routine.
%    \begin{macrocode}
\futurenonspacelet\@tempa\@BTendrule}

%    \end{macrocode}
% \end{macro}
% \begin{macro}{\@BTendrule}
% We look one step ahead (token is in \cs{@tempa}) to see if another
% rule follows (shame on user!). If so, we set \cs{@lastruleclass} equal
% to \cs{@thisruleclass} (thus setting it up for the following rule). If
% there isn't a following rule, we clear \cs{@lastruleclass} (ie set it
% to zero), which isn't technically true since we have just drawn a
% rule, but sets it up correctly for the next rule encountered, which
% must be following some intervening text.
%    \begin{macrocode}
\def\@BTendrule{%
  \ifx\@tempa\toprule\global\@lastruleclass=\@thisruleclass
  \else\ifx\@tempa\midrule\global\@lastruleclass=\@thisruleclass
  \else\ifx\@tempa\bottomrule\global\@lastruleclass=\@thisruleclass
  \else\ifx\@tempa\cmidrule\global\@lastruleclass=\@thisruleclass
  \else\ifx\@tempa\specialrule\global\@lastruleclass=\@thisruleclass
  \else\ifx\@tempa\addlinespace\global\@lastruleclass=\@thisruleclass
  \else\global\@lastruleclass=\z@\fi\fi\fi\fi\fi\fi
  \ifnum\@lastruleclass=\@ne\relax\else\vskip\@belowrulesep\fi
  \ifnum0=`{\fi}}
%    \end{macrocode}
% \end{macro}
%
%
% \subsubsection{Special subrules}
%
% \begin{macro}{\@setrulekerning}
% The following code parses the trimming arguments (if there are any)
%    for \cs{cmidrule} or a \cs{BLTrule}. The rule
%     will be trimmed left and right by \cs{cmrkern@l} and \cs{cmrkern@l},
%     which are zero by default, set to \cs{cmidrulekern} by the plain
%     \verb?(lr)? arguments, or user set as in \verb?(r{.5em})?. We parse token by
%     token through the arguments. The
%     tokens \verb?r? and \verb?l? cause \cs{cmrkern@r} or \cs{cmrkern@l} to be set to
%     \cs{cmidrulekern}. There is no lookahead to see if a width is the
%     next token; this strategy is efficient for the plain commands,
%     while inefficient for the qualified commands, but more importantly
%     it is much easier to program. Tokens \verb?r? and \verb?l? also set
%     \cs{cmrswitch} so that if the next token turns out to be
%     \marg{wd} then the kerning will be done on the side
%     currently specified. I have been too lazy to program an error
%     message should one encounter tokens other than \verb?r?, \verb?l? or
%     \marg{wd}.
% \changes{v1.618}{2005/09/03}{Fixed bug in booktabs trim command by improving character comparison code in \cs{@setrulekerning} (mempatch v3.8)}
%    \begin{macrocode}
\def\@setrulekerning#1{%
  \global\let\cmrkern@l\z@
  \global\let\cmrkern@r\z@
  \@tfor\@tempa :=#1\do
  {\def\@tempb{r}%
   \ifx\@tempa\@tempb
     \global\let\cmrkern@r\cmidrulekern
      \def\cmrsideswitch{\cmrkern@r}%
   \else
     \def\@tempb{l}%
     \ifx\@tempa\@tempb
       \global\let\cmrkern@l\cmidrulekern
       \def\cmrsideswitch{\cmrkern@l}%
     \else
       \global\expandafter\let\cmrsideswitch\@tempa
     \fi
   \fi}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cmidrule}
% \begin{macro}{\@cmidrule}
% \begin{macro}{\@@cmidrule}
% The \cs{cmidrule} re-uses \cs{@lastruleclass} in an entirely different
%  way from the full width rules. (Maybe I should have used a
%  different flag; it seemed efficient at the time \ldots). This
% is (left) set to one if you are in the middle of a row of
% \cs{cmidrules}, or starting a new one (with \cs{morecmidrules}).
% Otherwise, when \cs{@lastruleclass} is zero, we precede the
% rule with \cs{aboverulesep}.
%    \begin{macrocode}
\def\cmidrule{\noalign{\ifnum0=`}\fi
    \@ifnextchar[{\@cmidrule}{\@cmidrule[\cmidrulewidth]}}
\def\@cmidrule[#1]{\@ifnextchar({\@@cmidrule[#1]}{\@@cmidrule[#1]()}}
\def\@@cmidrule[#1](#2)#3{\@@@cmidrule[#3]{#1}{#2}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@@@cmidrule}
% The above is fiddling around to set defaults for missing optional
% arguments. We also pass to \cs{@@@cmidrule} in a different order,
% namely =[a-b]=\verb?{width required}= \verb?{kerning commands}= (this being
% the order in which the arguments are actually processed):
%    \begin{macrocode}
\def\@@@cmidrule[#1-#2]#3#4{\global\@cmidla#1\relax
    \global\advance\@cmidla\m@ne
    \ifnum\@cmidla>0\global\let\@gtempa\@cmidrulea\else
    \global\let\@gtempa\@cmidruleb\fi
    \global\@cmidlb#2\relax
    \global\advance\@cmidlb-\@cmidla
%    \end{macrocode}
% This has set up a switch (\cs{@gtempa}) to call the relevant routine,
% \cs{@cmidrulea} or \cs{@cmidruleb}, depending on whether we start
% from column one or not.
%    \begin{macrocode}
    \global\@thisrulewidth=#3
%    \end{macrocode}
% That is, set per default or given argument. Then parse any trimming
% arguments to set, globally, \cs{cmrkern@r} and \cs{cmrkern@l} accordingly:
%    \begin{macrocode}
    \@setrulekerning{#4}
%    \end{macrocode}
% Now insert space above if needed, close the \cs{noalign},
% then switch to appropriate rule drawing routine as determined
% above (\cs{let} to \cs{@gtempa}):
%    \begin{macrocode}
    \ifnum\@lastruleclass=\z@\vskip \aboverulesep\fi
    \ifnum0=`{\fi}\@gtempa
%    \end{macrocode}
% Having now drawn the rule,
% open another \cs{noalign}, and call the closing routine:
%    \begin{macrocode}
    \noalign{\ifnum0=`}\fi\futurenonspacelet\@tempa\@xcmidrule}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@xcmidrule}
% In this closing routine, see if another \cs{cmidrule} follows;
% if so, backspace
% vertical so it will line up with the one you just drew,
% and setting \cs{@lastruleclass} to 1 will suppress
% adding space above the next. If a \cs{morecimdrules} follows,
% we add (positive) \cs{cmidrulesep} (and again set \cs{@lastruleclass}
% to one). Otherwise this is the last rule of the current group
% and we can just add \cs{belowrulesep}. Finally, we close the \cs{noalign}.
%    \begin{macrocode}
\def\@xcmidrule{\ifx\@tempa\cmidrule\vskip-\@thisrulewidth
    \global\@lastruleclass=\@ne\else
    \ifx\@tempa\morecmidrules\vskip \cmidrulesep
    \global\@lastruleclass=\@ne\else
    \vskip \belowrulesep\global\@lastruleclass=\z@\fi\fi
    \ifnum0=`{\fi}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@cmidrulea}
% \begin{macro}{\@cmidruleb}
% This code (called below) actually draws the rules. They are drawn
% as boxes in text, rather than in a \cs{noalign} group, which permits
% the left and right kerning.
% \changes{v3.7f}{2016/05/16}{Added \cs{kern}\cs{z@} to comply to
% latest booktabs updates. In Booktabs they were added to protect
% against unskips.}
%    \begin{macrocode}
\def\@cmidrulea{%
  \multispan\@cmidla&\multispan\@cmidlb
%%    \unskip\hskip \cmrkern@l\leaders\bktabrule{\@thisrulewidth}\hfill
    \unskip\hskip \cmrkern@l{%
    \CT@arc@\leaders\bktabrule{\@thisrulewidth}\hfill\kern\z@}%
    \hskip \cmrkern@r\cr}
\def\@cmidruleb{%
  \multispan\@cmidlb
%%    \unskip\hskip \cmrkern@l\leaders\bktabrule{\@thisrulewidth}\hfill
  \unskip\hskip \cmrkern@l{%
    \CT@arc@\leaders\bktabrule{\@thisrulewidth}\hfill\kern\z@}%
    \hskip \cmrkern@r\cr}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\morecmidrules}
% This is really a dummy command; all the work is done above
% within the \cs{cmidrule} routine. We look one step ahead there
% to see if a \cs{morecmidrules} follows the current \cs{cmidrule},
% and if so set the flag. Otherwise,  \cs{morecmidrules} itself
% does nothing.
%    \begin{macrocode}
\def\morecmidrules{\noalign{\relax}}

%%%%%%%%%% end of Booktabs package code %%%%%%%%%%%%%%%%%%%%%

%    \end{macrocode}
% \end{macro}
%
% Ensure that the real \Lpack{booktabs} package can't get called.
% \changes{v1.618}{2005/09/03}{Killed use of real booktabs package (mempatch v3.12)}
%    \begin{macrocode}
%%\@memfakeusepackage{booktabs}

%    \end{macrocode}
%
%
% \subsection{Input files into tabulars, and etex}
%
%     M.J. Williams (CTT \textit{\cs{noalign} problem with \cs{input} and 
% tabular in memoir class}, 28 Aug 2007) reported that using \cs{input} in a 
% tabular resulted in errors. His example was:
% \begin{verbatim}
% ...
% \begin{tabular}{c|c} \hline
% 1 & 2 \\ \hline
% \input{data} \hline
% 5 & 6 \\ \hline
% \end{tabular}
% \end{verbatim}
% where \texttt{data.tex} contains the single line (and no newline) \\
% \verb?3 & 4 \\?
%
% Morten H{\o}gholm noted that the problem
% was caused by \Lpack{memoir}'s extension to \cs{input}
% and gave a solution that depends on processing via 
% \texttt{etex} rather than \texttt{tex}.
%
% Here's Morten's fix. Quoting, in part:
% \begin{quotation}
%     \Lpack{memoir} extends the file loading mechanism by providing 
% \cs{AtBeginFile} and \cs{AtEndFile} whose arguments are executed as 
% the names indicate. \ldots after inputting a file the storage bins are 
% emptied. The problem [in your case] is that this emptying is an
% assignment and so starts a new tabular cell and \cs{hline} is only
% allowed after \verb?\\? or other \cs{hline}s.
%
% \ldots the tabular environment wraps each tabular cell in additional
% groups so one can do an explicit test for which type of group we are in.
% If tested to be in an align group \emph{and} in vertical mode it means
% TeX hasn't found something to start a new cell and
% then \cs{noalign} can be used.
% \end{quotation}
%
%    \begin{macrocode}
\ifetex
  \renewcommand*{\killm@matf}[1]{%
    \ifnum 6=\currentgrouptype
      \ifvmode
        \expandafter\expandafter\expandafter\@firstoftwo
        \expandafter\expandafter\expandafter\noalign
      \fi
    \fi
    \@firstofone
    {\@namelet{#1-m@mfb}\relax
     \@namelet{#1-m@mfe}\relax
    }%
  }
\fi

%    \end{macrocode}
%
%
% \subsection{Continuous tabulars}
%
%    The standard \texttt{tabular} environment is wrapped inside a box
% (see \verb?\@tabular?),
% which means that it cannot break across pages. Equivalent environments
% are provided which are not boxed and so can continue across page 
% boundaries.
%
% \begin{macro}{\ctableftskip}
% \begin{macro}{\ctabrightskip}
% These skips are inserted at the left and right of continuous tabulars
% so that their horizontal location can be specified.
%    \begin{macrocode}
\newskip\ctableftskip \ctableftskip=\fill
\newskip\ctabrightskip \ctabrightskip=\fill

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\ctabular*}
% \begin{macro}{\@ctabularstar}
% This starts off the \texttt{ctabular*} continuous tabular environment.
% The default location is centered. NOTE: This is not for release.
%    \begin{macrocode}
\expandafter\def\csname ctabular*\endcsname{%
  \@ifnextchar[ {\@ctabularstar}{\@ctabularstar[c]}}
\def\@ctabularstar[#1]#2{\global\@curtab\@ne
  \ctableftskip\fill
  \ctabrightskip\fill
  \if l#1% left
    \ctableftskip\z@ 
  \else
    \if r#1% right
       \ctabrightskip\z@
    \fi
  \fi
  \setlength\dimen@{#2}%
  \xdef\@halignto{to\the\dimen@}\NC@tabular}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ctabular}
% \verb?\ctabular? is similar to \verb?\ctabular*? except that the
% width is known to be \verb?\hsize?.
%    \begin{macrocode}
\newcommand*{\ctabular}[1][c]{\global\@curtab\@ne
  \ctableftskip\fill
  \ctabrightskip\fill
  \if l#1% left
    \ctableftskip\z@ 
  \else
    \if r#1% right
      \ctabrightskip\z@
    \fi
  \fi
  \gdef\@halignto{to\hsize}\NC@tabular}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\NC@tabular}
% \verb?\NC@tabular?
%    \begin{macrocode}
\newcommand*{\NC@tabular}{%
  \par
  \addvspace{\topsep}
  \col@sep\tabcolsep
  \let\d@llarbegin\begingroup
  \let\d@llarend\endgroup
  \@NCtabarray}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@NCialign}
%    \begin{macrocode}
\newcommand*{\@NCialign}{\everycr{}\tabskip\ctableftskip\halign}

%    \end{macrocode}
% \end{macro}
%  
% \begin{macro}{\@NCtabarray}
% Effectively a modified version of \verb?\@array? 
%    \begin{macrocode}
\newcommand*{\@NCtabarray}[1]{%
  \@tempdima \ht\strutbox
  \advance\@tempdima\extrarowheight
  \setbox \@arstrutbox \hbox{\vrule
    \@height \arraystretch \@tempdima
    \@depth \arraystretch \dp\strutbox
    \@width\z@}%
  \begingroup
%%    \@mkpream{@{\hspace{\@totalleftmargin}}#1@{}}%
    \@mkpream{#1}%
    \xdef\@preamble{\@NCialign \@halignto
                    \bgroup & \tabskip\z@
                      \@arstrut
                      \@preamble
                      \tabskip\ctabrightskip
                      \cr}%
  \endgroup
  \let\@sharp ##\let\protect\relax
  \lineskip\z@
  \baselineskip\z@
  \let\\\@arraycr
  \let\tabularnewline\\%
  \let\par\@empty
  \ctabsetlines
  \@preamble
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\endctabular}
% \begin{macro}{\endctabular*}
% End the environments.
%    \begin{macrocode}
\def\endctabular{%
  \crcr \egroup
  \gdef\@preamble{}%
  \addvspace{\topsep}
  \noindent}
\expandafter\let\csname endctabular*\endcsname=\endctabular

%    \end{macrocode}
% \end{macro}
% \end{macro}
%  
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
% \subsubsection{Horizontal lines}
%
%   The standard \cs{hline} can produce odd results when used with
% continuous tabulars, but \cs{hhline} or \cs{cline} are OK. 
% I want a version of \cs{hline}
% that works with continuous tabulars and has an adjustable width
% (i.e., thickness). This will be based on a modified \cs{cline}
%
% For reference, here are the essentials of the kernel's definitions.
% \begin{verbatim}
% \def\hline{%
%    \noalign{\ifnum0=`}\fi\hrule \@height \arrayrulewidth \futurelet
%    \reserved@a\@xhline}
% \def\@xhline{%
%    \ifx\reserved@a\hline
%      \vskip\doublerulesep
%      \vskip-\arrayrulewidth
%    \fi
%    \ifnum0=`{\fi}}
% \def\cline#1{\@cline#1\@nil}
% \def\@cline#1-#2\@nil{%
%   \omit
%   \@multicnt#1%
%   \advance\@multispan\m@ne
%   \ifnum\@multicnt=\@ne\@firstofone{&\omit}\fi
%   \@multicnt#2%
%   \advance\@multicnt-#1%
%   \advance\@multispan\@ne
%   \leaders\hrule\@height\arrayrulewidth\hfill
%   \cr
%   \noalign{\vskip-\arrayrulewidth}}
% \end{verbatim}
%
% \begin{macro}{\memcline}
% \begin{macro}{\m@m@cline} 
% This is a version of the kernel \cs{cline} code that provides
% a variable width.
%    \begin{macrocode}
\newcommand*{\memcline}[2]{\m@m@cline[#1]#2\@nil}
\def\m@m@cline[#1]#2-#3\@nil{%
  \omit
  \@multicnt#2%
  \advance\@multispan\m@ne
  \ifnum\@multicnt=\@ne\@firstofone{&\omit}\fi
  \@multicnt#3%
  \advance\@multicnt-#2%
  \advance\@multispan\@ne
  \leaders\hrule\@height #1\hfill  % <- variable \@height value
  \cr
  \noalign{\vskip- #1}}            % <- variable \@height value

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memhline}
% \begin{macro}{\m@mhline}
% A version of \cs{hline}, based on \cs{memcline}, taking a 
% rule width as argument. It draws a \cs{memcline} from the
% first to the last (\cs{@curtab}) column.
%    \begin{macrocode}
\newcommand*{\memhline}[1][\arrayrulewidth]{\memcline{#1}{1-\@curtab}}
\newcommand*{\m@mhline}{\cline{1-\@curtab}}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%
% Fear's rules also do not play well within continuous tabulars.
%
% \begin{macro}{\m@m@BTnormal}
% Special version of \cs{@BTnormal}
%    \begin{macrocode}
\def\m@m@BTnormal{%
  \ifnum0=`{\fi}   % closes the \noalign
  \multispan{\@curtab} \leaders\bktabrule{\@thisrulewidth}\hfill\cr
  \noalign{\ifnum0=`}\fi
  \futurenonspacelet\@tempa\@BTendrule}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\ctabsetlines}
% Continuous tabulars cannot use the standard horizontal lines.
%    \begin{macrocode}
\def\ctabsetlines{%
  \let\hline\m@mhline
  \let\@BTnormal\m@m@BTnormal}

%    \end{macrocode}
% \end{macro}
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
% \subsection{Automated tabulations}
%
%
% It can be convenient, especially while drafting a document, to have
% a list of items put into a tabular without having to mark the ends
% of the rows. 
%
% The following is based on plain \TeX{} code given on pages 307--308 of
% \textit{TeX for the Impatient}~\cite{bk:Impatient}, which provides
% code for typesetting in columns.
%
% 
% \begin{macro}{\abovecolumnspenalty}
% \begin{macro}{\@linestogo}
% \begin{macro}{\@cellstogo}
% \begin{macro}{\@cellsincolumn}
% \begin{macro}{\crtok}
% Counters and such.
%    \begin{macrocode}
\newcount\abovecolumnspenalty
  \abovecolumnspenalty=10000
\newcount\@linestogo           % lines remaining to be procesed
\newcount\@cellstogo           % cells remaining in column or row
\newcount\@cellsincolumn         % number of lines per column
\newtoks\crtok
  \crtok = {\cr}%

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mincolumnwidth}
% \begin{macro}{\c@lleftskip}
% \begin{macro}{\c@lrightskip}
% More things
%   \begin{macrocode}
\newdimen\@mincolumnwidth
\let\c@lleftskip\hfil   % left skip within a column
\let\c@lrightskip\hfil % right skip within a column

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\preautotab}
% \begin{macro}{\postautotab}
% Hooks into the auto tabulations.
%    \begin{macrocode}
\let\preautotab\relax
\let\postautotab\relax

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\autocols}
% \cs{autocols}\oarg{width}\marg{pos}\marg{num}\marg{style}\marg{comma separated list}
% arranges the elements in the \meta{comma separated list} into \meta{num}
% columns, the elements filling each column before moving to the next.
% That is, the elements are ordered top to bottom and left to right.
%    \begin{macrocode}
\newcommand{\autocols}[5][0pt]{\par\begingroup
  \ctabsetlines
%    \end{macrocode}
% Set the table position
%    \begin{macrocode}
  \if l#2 
    \raggedright
  \else
    \if r#2
      \raggedleft
    \else
      \centering
    \fi
  \fi
%    \end{macrocode}
% Set the column position style
%    \begin{macrocode}
  \let\c@lleftskip\hfil
  \let\c@lrightskip\hfil
  \if l#4 
    \let\c@lleftskip\relax
  \else
    \if r#4
      \let\c@lrightskip\relax
    \fi
  \fi
%    \end{macrocode}
% Count the number of entries and the minimum width (max entry width)
% for the columns.
%    \begin{macrocode}
  \@mincolumnwidth\z@
  \TX@cols=#3
  \@curtab=#3
  \@linestogo\z@
  \@for\@tempa:=#5\do{
    \advance\@linestogo\@ne
    \settowidth{\@tempdima}{\@tempa}
    \ifdim\@tempdima>\@mincolumnwidth
      \@mincolumnwidth=\@tempdima
    \fi
  }
  \advance\@mincolumnwidth\tabcolsep
  \linespercol
%    \end{macrocode}
% Specify what is to be done after every entry
%    \begin{macrocode}
  \def\@endcolumnactions{%
    \global\advance\@linestogo\m@ne
    \ifnum\@cellstogo<\tw@
      \global\advance\TX@cols\m@ne
      \ifnum\TX@cols>\z@\linespercol\fi
      \the\crtok
    \else 
        &\global\advance\@cellstogo\m@ne
    \fi}%
%    \end{macrocode}
% Calculate the width of the columns
%    \begin{macrocode}
  \ifdim #1 > \z@
    \TX@col@width=#1
    \divide\TX@col@width \TX@cols
  \else
    \TX@col@width=\@mincolumnwidth
  \fi
  \penalty\abovecolumnspenalty
  \noindent% usually not a paragraph
%    \end{macrocode}
% Create most of the preamble by looping to add \cs{@cellsincolumn}-1 slots,
% then the last one which is different.
%    \begin{macrocode}
  \def\@preamble{}%
  \begingroup
    \let\@sharp\relax
    \ifnum\@cellsincolumn>\@ne
      \loop
        \g@addto@macro{\@preamble}{%
          \hb@xt@ \TX@col@width{%
               \c@lleftskip\strut\@sharp\c@lrightskip} &}%
        \advance\@cellsincolumn\m@ne
      \ifnum\@cellsincolumn>\@ne
      \repeat
    \fi
    \g@addto@macro{\@preamble}{%
      \hb@xt@ \TX@col@width{\c@lleftskip\strut\@sharp\c@lrightskip}}%
  \endgroup
  \let\@sharp ##
%    \end{macrocode}
% Start the \cs{valign}
%    \begin{macrocode}
  \tabskip\ctableftskip
%%  \tabskip\z@
  \valign \bgroup
    \tabskip\z@
    \@preamble
    \tabskip\ctabrightskip\cr
%    \end{macrocode}
% Add all the entries then finish off.
%    \begin{macrocode}
    \@for\@tempa:=#5\do{
      \@tempa\unskip\space\@endcolumnactions}%
    \the\crtok \egroup \par \endgroup}
  
%    \end{macrocode}
% \end{macro}
%  
%
% \begin{macro}{\linespercol}
% \cs{linespercol} calculates the maximum number of lines that go into
% a column, where there are \cs{TX@cols} columns and \cs{@linestogo}
% lines, so that the columns are balanced as well as possible. The result
% is \cs{@cellstogo}
%    \begin{macrocode}
\newcommand*{\linespercol}{%
  \@cellsincolumn=\@linestogo
  \divide\@cellsincolumn \TX@cols
  \@cellstogo=\@cellsincolumn
  \multiply\@cellstogo \TX@cols
  \@tempcnta=\@linestogo
  \advance\@tempcnta -\@cellstogo
  \ifnum \@tempcnta>\z@
    \advance\@cellsincolumn \@ne
  \fi
  \global\@cellstogo=\@cellsincolumn}

%    \end{macrocode}
% \end{macro}
%  
%
% \begin{macro}{\autorows}
% \cs{autorows}\oarg{width}\marg{pos}\marg{num}\marg{style}\marg{comma separated list}
% arranges the elements in the \meta{comma separated list} into \meta{num}
% columns, the elements filling each row before moving to the next.
% That is, the elements are ordered left to right and top to bottom.
% By default, each column is the same width, enough for the widest entry.
% If \meta{width} is a negative length (e.g., -1pt) the columns are set 
% to their natural 
% widths. If \meta{width} is positive (e.g., \cs{textwidth}), column widths 
% are equal widths so that the overal width is \meta{width}.
% The sideways location of thre tabular is \meta{pos} (l, c, or r), and
% the column style id \meta{style} (l, c, or r).
%    \begin{macrocode}
\newcommand{\autorows}[5][0pt]{\par\begingroup
 \ctabsetlines
%    \end{macrocode}
% Set the table position
%    \begin{macrocode}
  \ctableftskip\fill
  \ctabrightskip\fill
  \if l#2 
    \ctableftskip\z@
  \else
    \if r#2
      \ctabrightskip\z@
    \fi
  \fi
%    \end{macrocode}
% Set the column position style
%    \begin{macrocode}
  \let\c@lleftskip\hfil
  \let\c@lrightskip\hfil
  \if l#4 
    \let\c@lleftskip\relax
  \else
    \if r#4
      \let\c@lrightskip\relax
    \fi
  \fi
%    \end{macrocode}
% Count the number of entries and the minimum width (max entry width)
% for the columns.
%    \begin{macrocode}
  \TX@cols=#3\relax
  \@curtab=#3\relax
  \@cellstogo = \TX@cols
  \@mincolumnwidth\z@
  \@linestogo\z@
  \@for\@tempa:=#5\do{%
    \advance\@linestogo\@ne
    \settowidth{\@tempdima}{\@tempa}
    \ifdim\@tempdima>\@mincolumnwidth
      \@mincolumnwidth=\@tempdima
    \fi}%
  \advance\@mincolumnwidth\tabcolsep
%    \end{macrocode}
% Specify what is to be done after every entry
%    \begin{macrocode}
  \def\@endcolumnactions{%
    \global\advance\@linestogo\m@ne
    \global\advance\@cellstogo\m@ne
    \ifnum\@cellstogo<\@ne
      \global\@cellstogo=\TX@cols
      \the\crtok
    \else 
      & 
    \fi}%
%    \end{macrocode}
% Calculate the width of the columns
%    \begin{macrocode}
  \ifdim #1>\z@
    \TX@col@width=#1
  \else
    \TX@col@width=\hsize
  \fi
  \divide\TX@col@width \TX@cols
  \ifdim #1=\z@
    \TX@col@width=\@mincolumnwidth
  \fi
  \penalty\abovecolumnspenalty
  \noindent % usually not a paragraph
  \vskip -\z@ % don't know why we need this, but looks bad without it
%    \end{macrocode}
% Create most of the preamble by looping to add \cs{@cellsincolumn}-1 slots,
% then the last one which is different.
%    \begin{macrocode}
  \def\@preamble{}%
  \begingroup
    \let\@sharp\relax
    \ifnum\TX@cols>\@ne
      \loop
        \ifdim #1<\z@
          \g@addto@macro{\@preamble}{%
            \strut\c@lleftskip\@sharp\c@lrightskip &}%
        \else
          \g@addto@macro{\@preamble}{%
            \hb@xt@ \TX@col@width{%
                    \strut\c@lleftskip\@sharp\c@lrightskip} &}%
        \fi
        \advance\TX@cols\m@ne
      \ifnum\TX@cols>\@ne
      \repeat
    \fi
    \ifdim #1<\z@
      \g@addto@macro{\@preamble}{%
        \strut\c@lleftskip\@sharp\c@lrightskip}%
    \else
      \g@addto@macro{\@preamble}{%
        \hb@xt@ \TX@col@width{\strut\c@lleftskip\@sharp\c@lrightskip}}%
    \fi
  \endgroup
  \let\@sharp ##
%    \end{macrocode}
% Start the \verb?\halign?
%    \begin{macrocode}
  \tabskip\ctableftskip
  \halign to \hsize \bgroup
    \tabskip\z@
    \@preamble
%%    \tabskip\ctabrightskip\cr \preautotab
    \tabskip\ctabrightskip\cr 
%    \end{macrocode}
% Add all the entries then finish off.
%    \begin{macrocode}
    \@for\@tempa:=#5\do{%
      \@tempa\unskip\space\@endcolumnactions}%
%%    \the\crtok \postautotab \the\crtok \egroup \endgroup \par
    \the\crtok \egroup \endgroup \par}
  
%    \end{macrocode}
% \end{macro}
%  
%
%
%
% \section{Floating objects}
%
%    The file \file{latex.dtx} only defines a number of tools with
%    which floating objects can be defined. This is done in the
%    document class. It needs to define the following macros for each
%    floating object of type \texttt{TYPE} (e.g., \texttt{TYPE} =
%    figure).
%
%    \begin{description}
%    \item[\texttt{\bslash fps@TYPE}]
%        The default placement specifier for floats of type
%        \texttt{TYPE}.
%
%    \item[\texttt{\bslash ftype@TYPE}]
%        The type number for floats of type \texttt{TYPE}.  Each
%        \texttt{TYPE} has associated a unique positive \texttt
%        {TYPE} number, which is a power of two.  E.g., figures might
%        have type number 1, tables type number 2, programs type
%        number 4, etc.
%
%    \item[\texttt{\bslash ext@TYPE}]
%        The file extension indicating the file on which the contents
%        list for float type \texttt{TYPE} is stored.  For example,
%        \cs{ext@figure} = `lof'.
%
%    \item[\texttt{\bslash fnum@TYPE}]
%        A macro to generate the figure number for a caption. For
%        example, \cs{fnum@TYPE} == `Figure \cs{thefigure}'.
%
%    \item[\texttt{\bslash @makecaption}{\meta{num}}{\meta{text}}]
%        A macro to make a caption, with \meta{num} the value produced
%        by \cs{fnum@...} and \meta{text} the text of the caption. It
%        can assume it's in a \cs{parbox} of the appropriate width.
%        This will be used for \emph{all} floating objects.
%
%    \end{description}
%
%    The actual environment that implements a floating object such as
%    a figure is defined using the macros \cs{@float} and \cs{end@float},
%    which are defined in \file{latex.dtx}.
%
%    An environment that implements a single column floating object is
%    started with \verb?\@float{TYPE}?\oarg{placement} of type
%    \texttt{TYPE} with \meta{placement} as the placement specifier.
%    The default value of \meta{PLACEMENT} is defined by \cs{fps@TYPE}.
%
%    The environment is ended by \cs{end@float}.  E.g., \cs{figure} ==
%    \verb?\@float{figure}?, \cs{endfigure} == \cs{end@float}.
%
%
% \subsection{Floats}
%
% To define a float environment, say \Lenv{fenv}, the following macros must be defined:
% \begin{itemize}
% \item \cs{fps@fenv} The default placement specifier (normally \verb?tbp?). 
% \item \cs{ftype@fenv} The type number which is an integer and a power of 2.
% \item \cs{ext@fenv} The file extension for the contents list.
% \item \cs{c@fenv} A counter for the environment (for caption numbering).
% \item \cs{fnum@fenv} A macro to generate the caption `number'.
% \item \cs{l@fenv} A macro to produce an entry in a list of\ldots.
% \item \cs{flegtocfenv} A macro to write a \cs{namedlegend} title to a listof file.
% \item \cs{flegfenv} A macro to typeset the name of a \cs{namedlegend}.
% \item \cs{toclevel@fenv} Holding a bookmark level (required if the
%       \Lpack{hyperref} package will be used).
% \end{itemize}
%
% \begin{macro}{newflo@tctr}
% A counter for the type number of a new float. Normally
% figures are of type 1, tables type 2, and the next float type is then 4, and so
% on. 
%    \begin{macrocode}
\newcounter{newflo@tctr}
  \setcounter{newflo@tctr}{1}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\newfloat}
% \cs{newfloat}oarg{within}\marg{fenv}\marg{ext}\marg{capname}
% creates the commands for a new float environment, \meta{fenv} (aka \texttt{X}),
% using \meta{ext} (aka \texttt{Z}) as the
% file extension and \meta{capname} for the caption name.
% \changes{v1.61803}{2008/01/30}{Changed setting of \cs{ftype@X} in 
%        \cs{newfloat} to correctly assign float numbers, courtesy Flavian 
%        Lambert (mempatch v4.9)}
%    \begin{macrocode}
\newcommand{\newfloat}[4][\@empty]{%
%    \end{macrocode}
% \begin{macro}{\ftype@X}
%  Define the float type, set it to the float counter, and double
% the counter afterwards.
%    \begin{macrocode}
%%%  \@namedef{ftype@#2}{\value{newflo@tctr}}
%%%  \addtocounter{newflo@tctr}{\value{newflo@tctr}}
  \expandafter\edef\csname ftype@#2\endcsname{\the\c@newflo@tctr}%
  \advance\c@newflo@tctr \c@newflo@tctr
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\c@X}
% Create the counter for the caption, which must not have been previously
% defined.
%    \begin{macrocode}
  \@ifundefined{c@#2}{% counter is not defined
    \ifx \@empty#1\relax
      \newcounter{#2}
    \else
      \newcounter{#2}[#1]
      \expandafter\edef\csname the#2\endcsname{%
  \expandafter\noexpand\csname the#1\endcsname.\noexpand\arabic{#2}}
    \fi}{}
  \setcounter{#2}{0}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ext@X}
% \begin{macro}{\c@Zdepth}
% Define \cs{ext@X} for the file extension and set the new \verb?Zdepth? 
% depth counter to 1.
%    \begin{macrocode}
  \@namedef{ext@#2}{#3}%     file extension
  \@ifundefined{c@#3depth}{\newcounter{#3depth}}{}
  \setcounter{#3depth}{1}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\fps@X}
% \begin{macro}{\fnum@X}
% \begin{macro}{\flegX}
% \begin{macro}{\flegtocX}
% \cs{fps@X} is the default float placement specification, \cs{fnum@X}
% typesets the caption name and number, and \cs{flegX} and \cs{flegtocX} are for
% named legends.
%    \begin{macrocode}
  \@namedef{fps@#2}{tbp}                     % position
  \@namedef{fnum@#2}{#4~\@nameuse{the#2}}    % caption naming
  \@namedef{fleg#2}{#4}                      % legend naming
  \@namedef{flegtoc#2}##1{}                  % legend name in ToC

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{environment}{X}
% \begin{environment}{X*}
% Finally define the new float environment, in both normal and starred
% forms. We also al an internal macro that can be used to globally
% adjust floats, e.g. making all tables in small size.
% We would like to be able to insert adjustments inside the
% floats. But the manner in which \cs{@float} works makes it
% impossible for us to simple insert this into the definitions of the
% floats. 
%    \begin{macrocode}
  \newenvironment{#2}{\@float{#2}}{\end@float}
  \newenvironment{#2*}{\@dblfloat{#2}}{\end@dblfloat}
%    \end{macrocode}
% \end{environment}
% \end{environment}
%
% This ends the definition of \cs{newfloat}.
%    \begin{macrocode}
} % end \newfloat

%    \end{macrocode}
% \end{macro}
%
% \changes{v3.6i}{2011/02/18}{Added this instead of inserting the
% adjustment code directly into the environment definitions}
% \changes{v3.7g}{2017/05/08}{Moved into delayed \cs{@xfloat} redef as
% we need it to run after \cs{normalsize}}
% \begin{macro}{\@xfloat}
%   In order to inject adjustment code into the core of the floats we
%   will need to patch the code float macros a little.
%    \begin{macrocode}
  %\let\mem@old@xfloat\@xfloat
  %\def\@xfloat#1[#2]{\mem@old@xfloat{#1}[#2]\@nameuse{#1adjustment}}
%    \end{macrocode}
%   
% \end{macro}
%
% \begin{macro}{\setfloatlocations}
% \cs{setfloatlocations}\marg{float}\marg{locs} sets the defualt locations
% for the \meta{float} class of floats (e.g., \texttt{figure}) to \meta{locs}
% (initially \texttt{tbp}). For tables you might want to use: \\
% \verb?\setfloatlocations{table}{htbp}?
% \changes{v1.61803}{2008/01/30}{Added \cs{setfloatlocations} (mempatch v4.9)}
%    \begin{macrocode}
\newcommand*{\setfloatlocations}[2]{\@namedef{fps@#1}{#2}}

%    \end{macrocode}
% \end{macro}
% \changes{v3.6h}{2011/02/01}{Added \cs{setfloatadjustment}}
% \begin{macro}{\setfloatadjustment}
% \cs{setfloatadjustment}\marg{float}\marg{code} can be used to
% globally add internal adjustments to all floats of a certain
% type. For example to typeset the contents of all tables in
% \cs{small} use \verb|\setfloatadjustment{table}{\small}|.
%    \begin{macrocode}
\newcommand*\setfloatadjustment[2]{\@namedef{#1adjustment}{#2}}      

%    \end{macrocode}
% 
% \end{macro}
%
%
% To define subcaptions for use in a new float environment, say \texttt{fenv}, the
% following macros must be defined~\cite{SUBFIGURE}:
% \begin{itemize}
% \item A new counter \texttt{subfenv} for subcaption numbering.
% \item A new counter \texttt{extdepth}, where \texttt{ext} is the file extension
%       for the contents list of \texttt{fenv}, for setting the contents depth.
% \item \cs{thesubfenv} for the formatting of the subcaption number.
% \item \cs{@thesubfenv} for typesetting the number.
% \item \cs{@@thesubfenv} for alternative label reference.
% \item \cs{p@subfenv} for prepending to the subcaption number when it is referenced.
% \item \cs{ext@subfenv} the file extension for the contents list.
% \item \cs{l@subfenv} for formatting the contents list entry.
% \item \cs{@makesubfloatcaption} for typesetting the subcaption.
% \item \cs{toclevel@subfenv} for hyperref bookmarks
% \end{itemize}
%
% \begin{macro}{\newsubfloat}
% \cs{newsubfloat}\marg{fenv} creates the commands for a new
% subfloat for \meta{fenv} (aka \texttt{X}).
%    \begin{macrocode}
\newcommand{\newsubfloat}[1]{%
%    \end{macrocode}
% Call \verb?\newlistentry[X]{subX}{extX}{1}? to get most of the work done.
%    \begin{macrocode}
  \newlistentry[#1]{sub#1}{\@nameuse{ext@#1}}{1}
%    \end{macrocode}
%
% \begin{macro}{\ext@subX}
% \begin{macro}{\thesubX}
% \begin{macro}{\@thesubX}
% \begin{macro}{\@@thesubX}
% \begin{macro}{\p@subX}
% \begin{macro}{\toclevel@subX}
% And now for the rest of the commands for subcaptions.
% \changes{v1.1}{2002/03/10}{Added \cs{@namedef} of \cs{@@thesubenv}
%                to \cs{newsubfloat}}
% \changes{v1.1}{2002/03/10}{Added \cs{@namedef} of \cs{toclevel@subenv}
%                to \cs{newsubfloat}}
%    \begin{macrocode}
  \@namedef{ext@sub#1}{\csname ext@#1\endcsname}
  \@namedef{thesub#1}{(\alph{sub#1})}
  \@namedef{@thesub#1}{\@nameuse{thesub#1}%
            \if@tightsubcap\hskip\subfloatlabelskip\else\space\fi}
  \@namedef{@@thesub#1}{\@nameuse{thesub#1}}
  \@namedef{p@sub#1}{\csname the#1\endcsname}
  \@namedef{toclevel@sub#1}{1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% By permission of Steven Douglas Cochran the class provides similar 
% functionality as the \Lpack{subfigure} package~\cite{SUBFIGURE}.
% This requires some changes to be made to \cs{@float} and \cs{end@float}.
%
% \begin{macro}{\ifdonemaincaption}
% This is set TRUE after the \cs{(cont)caption} has been called in a float.
% \changes{v1.1}{2002/03/10}{Changed \cs{if@contmaincaption} to
%          \cs{ifdonemaincaption}}
%    \begin{macrocode}
\newif\ifdonemaincaption
  \donemaincaptionfalse

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@float}
% \begin{macro}{\@dbfloat}
% \begin{macro}{\@memresetsubcounter}
%   The kernel \cs{@float} and \cs{@dblfloat} macros are redefined to
%   set \cs{ifdonemaincaption} to FALSE, and also to zero the subfloat
%   counter, if it is defined.  Ignasi Furi\`{o}
%   reported\footnote{Private email from \texttt{ignasi.furio@uib.es},
%   2003/10/17} that floats embedded in text created an extra
%   space. This was caused by a missing \verb?%?.
%   \changes{v1.4}{2003/11/22}{Deleted spaces from \cs{@float} and
%   \cs{@dblfloat} (from patch v1.9)}
%  Axel Sommerfeldt\footnote{Private email, from axel.sommerfeldt@f-m.fm,
%  2013/05/10} asked for the subcounter reset to be factored out into
%  a macro and provided the code. 
%    \begin{macrocode}
\let\@memoldfloat\@float
\renewcommand{\@float}[1]{\donemaincaptionfalse
  \@memresetsubcounter{#1}%
  \@memoldfloat{#1}}
\let\@memolddblfloat\@dblfloat
\renewcommand{\@dblfloat}[1]{\donemaincaptionfalse
  \@memresetsubcounter{#1}%
  \@memolddblfloat{#1}}
\newcommand{\@memresetsubcounter}[1]{%
  \@ifundefined{c@sub#1}{}{\csname c@sub#1\endcsname = 0\relax}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\end@float}
% \begin{macro}{\end@dblfloat}
% The kernel \cs{end@float} and \cs{end@dblfloat} macros are redefined to 
% dump out any subcaptions that have not yet been processed.
%    \begin{macrocode}
\let\@memoldefloat\end@float
\def\end@float{%
  \@memlistsubcaptions{\@captype}\@memoldefloat}
\let\@memoldedblfloat\end@dblfloat
\def\end@dblfloat{%
  \@memlistsubcaptions{\@captype}\@memoldedblfloat}

%    \end{macrocode}
% Unfortunately the \Lpack{fixltx2e} package, version 1.1h (current as
% of 2005/09/03) makes assumptions about \cs{end@float} which do not
% hold for memoir. The code has to be reverted back to that in version
% 1.0b of \Lpack{fixltx2e}.
% \changes{v1.618}{2005/09/03}{Dealt with incompatibilities between
% fixltx2e and memoir's \cs{end@dblfloat} (mempatch v3.7)}
%
% \changes{v3.7c}{2015/03/05}{Note quite sure why this fix is needed,
% so we add a trick (\cs{MEMOIROVERRIDE}) so that it can be deleted by
% defining a macro before \cs{documentclass}, that makes it easier to
% test}
%
% Update 2015: The problematic code from \Lpack{fixltx2e} is no
% longer present from version 1.1s and on. This version is to be
% build into the LaTeX2e kernel for the TeX Live 2015 release. We
% change the code reversion so it only happens if older \Lpack{fixltx2e}
% versions are being used.
% \changes{v3.7d}{2015/03/17}{Adding check for older \Lpack{fixltx2e}
% and removing \cs{MEMOIROVERRIDE}}
%    \begin{macrocode}
\AtBeginDocument{%
  \@ifpackageloaded{fixltx2e}{%
    \@ifpackagelater{fixltx2e}{2014/01/01}{}{% package older than 2014/01/01
      \def\end@dblfloat{%
        \if@twocolumn
          \@endfloatbox
          \ifnum\@floatpenalty<\z@
            \@largefloatcheck
            \global\dp\@currbox1sp %
            \@cons\@deferlist\@currbox
          \fi
          \ifnum\@floatpenalty=-\@Mii \@Esphack\fi
        \else
          \end@float
        \fi}%
    }
  }{}
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \changes{v3.6h}{2011/02/01}{Added \cs{FloatBlock}}
% \subsubsection{Float blockage}
%
% This is basically a slightly modified copy of \cs{FloatBarrier} from
% the \Lpack{placeins} package by Donald Arseneau, renamed such that
% both can be used in the same document. We could have emulated the
% \Lpack{placeins} package, but people might use it with options, so,
% since the code is so short we just copy it. Kudos to Donald Arseneau.
% For more defaults see
% \cite{PLACEINS}. 
% \begin{macro}{\FloatBlock}
% \begin{macro}{\FloatBlockAllowAbove}
% \begin{macro}{\FloatBlockAllowBelow}
% The two \cs{XAllowY} macros is our way of supporting the
% \Lpack{placeins} package options.
%    \begin{macrocode}
\def\mem@fb@botlist{\@botlist}
\def\mem@fb@topblock{\suppressfloats[t]}
%    \end{macrocode}
% \changes{v3.7d}{2015/03/12}{\cs{\@dbldeferlist} may be removed in a
% comming LaTeX kernel update}
%    \begin{macrocode}
\def\FloatBlock{\par\begingroup \let\@elt\relax
 \edef\@tempa{\mem@fb@botlist\@deferlist\@dbldeferlist}%
 \ifx\@tempa\@empty 
 \else
    \ifx\@fltovf\relax % my indicator of recursion
       \if@firstcolumn 
         \clearpage 
       \else 
         \null\newpage\FloatBlock
       \fi
    \else 
       \newpage \let\@fltovf\relax 
       \FloatBlock % recurse once only
 \fi\fi \endgroup
 \mem@fb@topblock}
\newcommand*\FloatBlockAllowAbove{\def\mem@fb@topblock{}}
\newcommand*\FloatBlockAllowBelow{\def\mem@fb@botlist{}}
      
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \begin{macro}{\setFloatBlockFor}
%   This can be used to add \cs{FloatBLock} into various sectional
%   macros. Supported: \cs{chapter} (when in article mode) and all
%   sectional macros made using \cs{@startsection}.
%    \begin{macrocode}
\newcommand\setFloatBlockFor[1]{%
  \@namedef{#1block}{\FloatBlock}}
%    \end{macrocode}
%   
% \end{macro}
%
% \subsubsection{Margin floats}
%
% The next two constructions are inspired by \texttt{tufte-common.def}
% by Bil Kleb, Bill Wood, and Kevin Godby and provide a manner to
% insert figures or tables into the margin. Note that the
% \cs{setfloatadjustment} also applies here.
% \begin{macro}{\mem@margin@floatbox}
% Box to save the contents of a margin float in.
%    \begin{macrocode}
\newsavebox{\mem@margin@floatbox}
%    \end{macrocode}
% \end{macro}
%    % \begin{environment}{mem@margin@float}
% \begin{environment}{marginfigure}
% \begin{environment}{margintable}
% \begin{macro}{\marginfloatmarginmacro}
% Since the two environments only differ in `name' a constructor is used.
% Since these margin floats are wrapped inside another type of float
% (\cs{marginpar}) they may cause problems when used combined with
% regular floats (the float order may be wrong). For that reason the
% margin float throws a \cs{FloatBlock} before issuing the \cs{marginpar}.
%    \begin{macrocode}
\newcommand\marginfloatmarginmacro{\marginpar}
\newenvironment{mem@margin@float}[2][-1.2ex]%
  {\FloatBlock% 
  \begin{lrbox}{\mem@margin@floatbox}%
  \begin{minipage}{\marginparwidth}%
    \def\@captype{#2}%
    \hbox{}\vspace*{#1}%
    \@nameuse{margin#2adjustment}%
    \@nameuse{margin#2captionadjustment}%
    \noindent%
  }
  {\end{minipage}%
  \end{lrbox}%
  \marginfloatmarginmacro{\usebox{\mem@margin@floatbox}}%
  }
%    \end{macrocode}
% The  two environment is then just two applications of the
% constructor. The option can be used to move the margins float up and down. 
%    \begin{macrocode}
\newenvironment{marginfigure}[1][-1.2ex]{%
  \begin{mem@margin@float}[#1]{figure}}
  {\end{mem@margin@float}}
\newenvironment{margintable}[1][-1.2ex]{%
  \begin{mem@margin@float}[#1]{table}}
  {\end{mem@margin@float}}
\setfloatadjustment{marginfigure}{\centering}
\setfloatadjustment{margintable}{\centering}
      
%    \end{macrocode}
% \end{macro}
% \end{environment}
% \end{environment}
% \end{environment}
% \begin{macro}{\setmarginfloatcaptionadjustment}
% Because of the very narrow margin area, it may be fruitful to
% reconfigure the caption style when used in a margin float. This can
% be done globally for all captions (e.g. if all floats are margin
% floats, or just for margin floats.
%    \begin{macrocode}
\newcommand*\setmarginfloatcaptionadjustment[2]{%
  \@namedef{margin#1captionadjustment}{#2}}
      
%    \end{macrocode}
% \end{macro}
% \changes{v3.6h}{2011/02/06}{Added these two macros}
% \begin{macro}{\setmpjustification}
% \begin{macro}{\mpjustification}
%  Can be just to use and configure a specialized justification. It
%  follows the \verb?\marginpar? placement, and make use of the first
%  argument when at the left of the text block and the other when at
%  the right. It makes use of an internal setting from within
%  \verb?\marginparmargin?, thus that need to have been executed.
%    \begin{macrocode}
\newcommand\setmpjustification[2]{%
  \@namedef{mem@mp@justification}{%
    \ifm@msetmp\else\@memerror{In order to use
      \string\marginCmdAdjust,^^J%  
      please make sure to specify into which margin the^^J%
      \string\marginpar\space should go, using \string\marginparmargin}{}\fi
    \m@mwhich@margin{\m@mmpar@margin}% 
     \ifmemtortm #2 \else #1\fi}%
}
%    \end{macrocode}
% Default value
%    \begin{macrocode}
\newcommand\mpjustification{%
  \@nameuse{mem@mp@justification}}
\setmpjustification{\raggedleft}{\raggedright}
      
%    \end{macrocode}
%  
% \end{macro}
% \end{macro}
%
% \subsection{Captions}
%
%    The caption styling 
% is accomplished by redefining the \cs{@makecaption}
% command. First, though, define and initialise the user-level commands.
%
% \begin{macro}{\if@contcw}
% \begin{macro}{\if@conthang}
% \begin{macro}{\if@contindent}
% For use when checking caption width and captioning styles styles.
%    \begin{macrocode}
\newif\if@contcw
\newif\if@conthang
\newif\if@contindent

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\captiondelim}
% \begin{macro}{\@contdelim}
%  For the caption delimiter.
%    \begin{macrocode}
\newcommand{\captiondelim}[1]{\def\@contdelim{#1}}
\captiondelim{: }

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\captionnamefont}
% \begin{macro}{\@contnfont}
% The font for the caption name.
%    \begin{macrocode}
\newcommand{\captionnamefont}[1]{\def\@contnfont{#1}}
\captionnamefont{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\captiontitlefont}
% \begin{macro}{\@conttfont}
% The font for the caption title.
%    \begin{macrocode}
\newcommand{\captiontitlefont}[1]{\def\@conttfont{#1}}
\captiontitlefont{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\captionstyle}
% \begin{macro}{\@contcstyle}
% The paragraphing style for the caption.
%    \begin{macrocode}
\newcommand*{\captionstyle}[1]{\def\@contcstyle{#1}}
\captionstyle{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\captionstyle}
% \begin{macro}{\@memcshort}
% \begin{macro}{\@memcnom}
% \begin{macro}{\@contcshortstyle}
% \begin{macro}{\@contcstyle}
% The paragraphing style for the caption.
%
% I had email from J{\o}rgen Larsen (\url{jl@dirac.ruc.dk}), 2003/04/09,
% asking for separate controls for the short and long captions. \\
%  \cs{captionstyle}\oarg{short}\marg{normal}.
% \changes{v1.4}{2003/11/22}{Extended \cs{captionstyle} (from patch v1.5)}
% \changes{v3.6h}{2011/01/16}{Removed sporadic spaces}
%    \begin{macrocode}
\renewcommand{\captionstyle}{%
  \@ifnextchar[{\@memcshort}{\@memcnorm}}
\def\@memcshort[#1]#2{%
  \def\@contcshortstyle{#1}%
  \def\@contcstyle{#2}}
\def\@memcnorm#1{%
  \def\@contcshortstyle{#1}%
  \def\@contcstyle{#1}}
\captionstyle{}
  
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@contcwidth}
% \begin{macro}{\captionwidth}
% \begin{macro}{\changecaptionwidth}
% \begin{macro}{\normalcaptionwidth}
% The macros for dealing with the caption width.
%    \begin{macrocode}
\newlength{\@contcwidth}
\newcommand{\captionwidth}[1]{\setlength{\@contcwidth}{#1}}
\captionwidth{\linewidth}
\newcommand{\changecaptionwidth}{\@contcwtrue}
\newcommand{\normalcaptionwidth}{\@contcwfalse}
\normalcaptionwidth

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@contindw}
% \begin{macro}{\hangcaption}
% \begin{macro}{\indentcaption}
% \begin{macro}{\normalcaption}
% The macros for hanging and indented captions.
%    \begin{macrocode}
\newlength{\@contindw}
\newcommand{\hangcaption}{\@conthangtrue\@contindentfalse}
\newcommand{\indentcaption}[1]{\setlength{\@contindw}{#1}%
  \@conthangfalse\@contindenttrue}
\newcommand{\normalcaption}{\@conthangfalse\@contindentfalse}
\normalcaption

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\precaption}
% \begin{macro}{\@contpre}
% \begin{macro}{\postcaption}
% \begin{macro}{\@contpost}
% \begin{macro}{\midbicaption}
% \begin{macro}{\@contmidbi}
% The macros for the pre- and post-caption text/commands, and
% for the mid-caption command for bilingual captions.
%    \begin{macrocode}
\newcommand{\precaption}[1]{\def\@contpre{#1}}
\precaption{}
\newcommand{\postcaption}[1]{\def\@contpost{#1}}
\postcaption{}
\newcommand{\midbicaption}[1]{\def\@contmidbi{#1}}
\midbicaption{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\captiontitlefinal}
% \cs{captiontitlefinal}\marg{stuff} will put \meta{stuff} immediately
% at the end of a \cs{caption}'s title text but it will not appear
% in the LoF/LoT/etc. For example \\
% \verb?\captiontitlefinal{.}? \\
% The code was supplied by Frederic Connes.
% \changes{v1.61803}{2008/01/30}{Added \cs{captiontitlefinal} (mempatch v4.4)}
%    \begin{macrocode}
\newcommand*{\captiontitlefinal}[1]{\def\@contfinal{#1}}
  \captiontitlefinal{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\abovecaptionskip}
% \begin{macro}{\belowcaptionskip}
% Vertical space above and below a caption. Make them sum to an
% integral number of lines.
%    \begin{macrocode}
\newlength{\abovecaptionskip}
  \setlength{\abovecaptionskip}{0.5\onelineskip}
\newlength{\belowcaptionskip}
  \setlength{\belowcaptionskip}{0.5\onelineskip}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\caption}
% For subfloat support, the (kernel) \cs{caption} macro needs to note that it
% has been called.
%    \begin{macrocode}
\let\@memoldcaption\caption
\def\caption{\donemaincaptiontrue\@memoldcaption}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\memcaptioninfo}
% \verb?\memcaptioninfo{type}{\thetypenum}{short}{long}?
% \changes{v1.618}{2005/09/10}{Added \cs{memcaptioninfo}}
%    \begin{macrocode}
\newcommand{\memcaptioninfo}[4]{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@caption}
% For title referencing support, the (kernel) \cs{@caption} macro needs 
% to store the title.
% \changes{v1.618}{2005/09/03}{Added braces around second argument of \cs{@memold@caption} (per Dan Luecking, mempatch v3.0)}
%    \begin{macrocode}
\let\@memold@caption\@caption
\long\def\@caption#1[#2]#3{%
  \M@gettitle{#2}%
  \memcaptioninfo{#1}{\csname the#1\endcsname}{#2}{#3}%
  \@memold@caption{#1}[{#2}]{#3}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@makecaption}
%  This is a reimplementation of the kernel \cs{@makecaption} command.
% As well as including the caption typesetting commands it enables
% captions that include forced newlines (e.g., by \verb?\\?).
%
% The first part is due to 
% Donald Arseneau\footnote{Email: \texttt{asnd@triumf.ca}} from postings
% to the \ctt{} newsgroup and Email discussions. The \cs{topskip} strut is
% used whenever the caption is the first part of the float. This means,
% among other things, that if a caption comes at the
% top of a page, then the first line of the caption will be aligned with
% the normal first line of a page. The \cs{abovecaptionskip} is only used
% when there is something above the caption in the current float.
% \changes{v0.31}{2001/07/24}{Changed \cs{@tempa} to \cs{@memtempa} in \cs{@makecaption}}
% \changes{v1.0a}{2002/02/12}{Added extra centering code in \cs{@makecaption}}
% \changes{v1.4}{2003/11/22}{Added separate short/long styles in \cs{@makecaption}
%                             (from patch v1.5)}
% \changes{v1.61803}{2008/01/30}{Added \cs{@contfinal} to \cs{@makecaption}
%         (mempatch v4.4)}
%
% Axel Sommerfelt\footnote{Private email discussion} suggested to
% split \cs{@makecaption} into two macros, such that the caption
% formatting and the space above and below are separate. This enables
% us to use the formatting macro (\cs{@@makecaption}) to format, say,
% \Lpack{longtable} captions.
% \changes{v3.6k}{2013/05/13}{Split \cs{@makecaption} into
% \cs{@makecaption} and \cs{@@makecaption}} 
%    \begin{macrocode}
\long\def\@makecaption#1#2{\let\@memtempa\relax
  \ifdim\prevdepth>-99\p@ \vskip\abovecaptionskip
  \else \def\@memtempa{\vbox to\topskip{}}\fi
%    \end{macrocode}
% Inserting \cs{@@makecaption} to format the actual caption.
%    \begin{macrocode}
  \@@makecaption{#1}{#2}%
%    \end{macrocode}
% Then add the below caption spacing.
%    \begin{macrocode}
  \vskip\belowcaptionskip}

%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\@@makecaption}
% Next the rest of the caption code as \cs{@@makecaption}.
%    \begin{macrocode}
\long\def\@@makecaption#1#2{%
%    \end{macrocode}
% \begin{macro}{\@contfnote}
% \begin{macro}{\@contfmark}
% The caption title will be typeset twice, firstly to measure its width
% and secondly to actually typeset it. To avoid problems caused by
% a footnote in the caption getting processed twice, we temporarily
% disable the expected relevant commands.
% \changes{v3.6h}{2011/01/20}{Provided the same for \cs{pagentote}}
%    \begin{macrocode}
  \let\@contfnote\footnote \renewcommand{\footnote}[2][]{}
  \let\@contfmark\footnotemark \renewcommand{\footnotemark}[1][]{}
  \let\@contpnote\pagenote\renewcommand\pagenote[2][]{}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% Now measure the width of the total caption, not forgetting to take account
% of the font specifications, and then restore the footnoting. 
% \changes{v3.6k}{2013/05/13}{Font grouping, suggested by Axel Sommerfelt}
%    \begin{macrocode}
  \sbox\@tempboxa{{\@contnfont #1\@contdelim}\@conttfont #2\@contfinal}
  \let\footnote\@contfnote
  \let\footnotemark\@contfmark
  \let\pagenote\@contpnote
%    \end{macrocode}
% If the caption is less than one
% line, then the whole caption needs to be centered on the page (otherwise
% the short caption may be typeset flushleft).
%    \begin{macrocode}
  \ifdim\wd\@tempboxa<\linewidth \centering \fi
  \if@contcw
%    \end{macrocode}
% For typesetting at anything other than the normal width, put the caption
% into a \cs{parbox} of the specified width. This must be centered.
% \changes{v3.6h}{2010/12/06}{Align inner parbox at top
% line. Vertically centered parbox cause different spacing when
% \cs{changecaptionwidth} compared when it is not used.}
%    \begin{macrocode}
    \centering
    \parbox[t]{\@contcwidth}{%
%    \end{macrocode}
% Henrik Holm\footnote{Email from \texttt{henrik@tele.ntnu.no} on
% 2002/02/10.} proposed adding the next line to center short, narrow captions.
%    \begin{macrocode}
    \ifdim\wd\@tempboxa<\@contcwidth \centering \fi
  \fi
%    \end{macrocode}
% Hanging and indenting doesn't apply to short captions, so do these
% now.
% \changes{v1.6180339f}{2009/06/25}{Short captions no longer hang or indent}
%    \begin{macrocode}
  \ifdim\wd\@tempboxa<\linewidth
    \@contpre
    {\@contnfont #1\@contdelim}\@memtempa
    {\@contcshortstyle \@conttfont #2\@contfinal\par}
  \else
    \if@conthang
%    \end{macrocode}
% For a hanging caption we have to measure the width of the caption name,
% then typeset the whole caption in a hanging paragraph.
% \changes{v1.1}{2002/03/10}{Changed code for hangcaption in \cs{@makecaption}}
%    \begin{macrocode}
      \sbox\@tempboxa{\@contnfont #1\@contdelim}
      \@contpre%
      {\@contcstyle\hangindent=\wd\@tempboxa
       \noindent\box\@tempboxa\@memtempa \@conttfont #2\@contfinal\par}
    \else
      \if@contindent
%    \end{macrocode}
% An indented caption is similar, except the amount of indentation is
% kept in \cs{@contindw}.
%    \begin{macrocode}
        \@contpre%
        {\@contnfont #1\@contdelim}\@memtempa 
        {\@contcstyle\hangindent=\@contindw
                     \hangafter=\@ne\@conttfont #2\@contfinal\par}% <- v1.4 
      \else
%    \end{macrocode}
% For the normal style, just typeset the caption.
%    \begin{macrocode}
        \@contpre%
        {\@contnfont #1\@contdelim}\@memtempa 
        {\@contcstyle \@conttfont #2\@contfinal\par}
      \fi
    \fi
  \fi
%    \end{macrocode}
% Finish off the typesetting by processing the post-text,  and if not using
% the normal width then close off the \cs{parbox}, and lastly put in some
% vertical space. 
% \changes{v3.6k}{2013/05/13}{Removed the below vertical skip}
%    \begin{macrocode}
  \@contpost
  \if@contcw
    \par
    }  % end of the \parbox
  \fi
  }

%    \end{macrocode}
% \end{macro}
%
%
%
% \subsubsection{Continuation captions and legends}
%
% \begin{macro}{\contcaption}
%    \cs{contcaption}\marg{text} is a user-level command. 
%    It is a simplified
%    version of the normal \cs{caption} command as it doesn't have to deal
%    with numbering or list of \dots entries. 
%
% However,
% Brent Lievers\footnote{ (\texttt{lieversb@post.queensu.ca})
% in \ctt{} thread \textit{Figures}, 2003/11/14.} requested that \cs{label}
% should pick up the correct caption number after a \cs{contcaption}.
% \changes{v1.4}{2003/11/22}{Extended \cs{contcaption} (from patch v1.9)} 
%    \begin{macrocode}
\newcommand{\contcaption}{%
  \addtocounter{\@captype}{\m@ne}\refstepcounter{\@captype}%
  \@contcaption\@captype}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\@@contcaption}
% \begin{macro}{\@contcaption}
%    \cs{@contcaption} is the workhorse for the \cs{contcaption} command. In turn,
% it uses the \cs{@makecaption} command (defined in the usual classes)
% to do most of its work. It
% uses the number of the previous \cs{caption} command in the same
% type of float and its implementation includes much of the code
% used in the \LaTeX{} \cs{@caption} command.
% 
%    First specify \cs{@@contcaption}\marg{type}\marg{title}
% to save some repetitive code.
%    \begin{macrocode}
\long\def\@@contcaption#1#2{%
  \par
  \begingroup
     \@parboxrestore
     \if@minipage
       \@setminipage
     \fi
     \normalsize
     \@makecaption{\csname fnum@#1\endcsname}{\ignorespaces #2}\par
  \endgroup}

%    \end{macrocode}
% \end{macro}
%
% Now for \cs{@contcaption}\marg{type}\marg{title}. 
% It has to flush out any subcaptions at the 
% appropriate time, as well as typesetting the caption.
%    \begin{macrocode}
\long\def\@contcaption#1#2{%
  \if@contbotsub
    \@memlistsubcaptions{#1}%
    \@@contcaption{#1}{#2}%
  \else
    \@@contcaption{#1}{#2}%
    \@memlistsubcaptions{#1}%
  \fi}

%    \end{macrocode}
% \end{macro}    
%
%
% \begin{macro}{\memlegendinfo}
% \begin{macro}{\legend}
%    The macro \cs{legend}\marg{text}is intended
% to be used in a float environment for an `anonymous' caption, but can be
% used anywhere.
%
%    The implementation is similar to the \cs{caption} command but we have
% to eliminate printing of a delimeter.
% \changes{v1.4}{2003/11/16}{Added \cs{M@gettitle} to \cs{legend}}
% \changes{v1.618}{2005/09/10}{Added \cs{memlegendinfo}}
%    \begin{macrocode}
\newcommand{\memlegendinfo}[1]{}
\newcommand{\legend}[1]{%
  \M@gettitle{#1}%
  \memlegendinfo{#1}%
  \par
  \begingroup
     \@parboxrestore
     \if@minipage
       \@setminipage
     \fi
     \normalsize
     \captiondelim{\mbox{}}
     \@makecaption{}{\ignorespaces #1}\par
  \endgroup}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\namedlegend}
% \begin{macro}{\memnamedlegendinfo}
% \cs{namedlegend}\oarg{short-title}\marg{long-title} is like the
% \cs{caption} command except that it does not number the caption.
%
% \cs{memnamedlegendinfo}\marg{type}\marg{short-title}\marg{long-title}
% \changes{v1.618}{2005/09/10}{Added \cs{memnamedlegendinfo}}
%    \begin{macrocode}
\newcommand{\namedlegend}{\@dblarg{\@legend\@captype}}
\newcommand{\memnamedlegendinfo}[3]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@legend}
% \cs{@legend}\marg{type}\oarg{short-title}\marg{long-title}
% is the workhorse for the \cs{namedlegend} command. In turn, it calls
% \cs{@makelegend}. It requires two commands to have been defined, namely
% \cs{flegtoctype} and \cs{flegtype}. The command \cs{flegtoctype}\marg{text}
% is responsible for writing a title text to the appropriate listof file.
% \cs{flegtype} is responsible for typeseting the name of the legend.
% \changes{v1.4}{2003/11/16}{Added \cs{M@gettitle} to \cs{@legend}}
%    \begin{macrocode}
\long\def\@legend#1[#2]#3{%
  \M@gettitle{#2}%
  \memnamedlegendinfo{#1}{#2}{#3}%
  \par
  \csname flegtoc#1\endcsname{#2}%
  \begingroup
    \@parboxrestore
    \if@minipage
      \@setminipage
    \fi
    \normalsize
    \@makecaption{\csname fleg#1\endcsname}{\ignorespaces #3}\par
  \endgroup}

%    \end{macrocode}
% \end{macro}
%
%
% \subsubsection{Non-float captions}
%
% \begin{macro}{\newfixedcaption}
% \begin{macro}{\renewfixedcaption}
% \begin{macro}{\providefixedcaption}
% These commands are defined in terms of their \verb?\...command? counterparts.\\
% Call as \verb?\...fixedcaption?\oarg{capcommand}\marg{command}\marg{env}
%    \begin{macrocode}
\newcommand{\newfixedcaption}[3][\caption]{%
  \newcommand{#2}{\def\@captype{#3}#1}}
\newcommand{\renewfixedcaption}[3][\caption]{%
  \renewcommand{#2}{\def\@captype{#3}#1}}
\newcommand{\providefixedcaption}[3][\caption]{%
  \providecommand{#2}{\def\@captype{#3}#1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsubsection{Bilingual captions}
%
%    The bilingual caption commands all use internal grouping so
% that any changes are kept local. This has the unfortunate side-effect
% that any \cs{label} command must be within the grouping otherwise the
% wrong number is picked up. To make the coding, if not necessarily the 
% use, of the commands simpler, I have not used the traditional style
% of square brackets for optional caption text arguments. Instead, empty
% `required' arguments are used as the implementation means. 
%
% \begin{macro}{\membitwonumcaptioninfo}
% \begin{macro}{\membionenumcaptioninfo}
% \begin{macro}{\membicaptioninfo}
% \verb?\membitwonumcaptioninfo{type}{\thetypenum}?\marg{short1}\marg{long1}\\
%  \hspace*{2in} \marg{name2}\marg{short2}\marg{long2} \\
% \verb?\membionenumcaptioninfo{type}{\thetypenum}?\marg{short1}\marg{long1}\\
%  \hspace*{2in} \marg{name2}\marg{short2}\marg{long2} \\
% \verb?\membicaptioninfo{type}{\thetypenum}?\marg{short1}\marg{long1}\\
%  \hspace{2in} \marg{name2}\marg{long2} \\
% \changes{v1.618}{2005/09/10}{Added \cs{membitwonumcaptioninfo},
%   \cs{membitwonumcaptioninfo} and \cs{membicaptioninfo}}
%    \begin{macrocode}
\newcommand{\membitwonumcaptioninfo}[7]{}
\newcommand{\membionenumcaptioninfo}[7]{}
\newcommand{\membicaptioninfo}[6]{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\bitwonumcaption}
%  The 6 arguments are: optional label, short and long in language 1, 
% name in
% language 2, and short and long in language 2. Both texts are put
% into the List of as numbered entries.
%    \begin{macrocode}
\newcommand{\bitwonumcaption}[6][\@empty]{%
  \begingroup
  \let\memcaptioninfo\@gobblefour
%    \end{macrocode}
% Check if the first language argument is vacuous, then call
% the normal \cs{caption} for language 1.
%    \begin{macrocode}
  \@ifmtarg{#2}{\def\m@mscapi{#3}\caption{#3}}%
               {\def\m@mscapi{#2}\caption[#2]{#3}}%
%    \end{macrocode}
% Do the optional labeling.
%    \begin{macrocode}
  \ifx \@empty #1\else
    \label{#1}%
  \fi
%    \end{macrocode}
% Remove any extra spacing between the captions, and set the
% NAME for the second caption. Use a command to transfer
% the NAME to the renewal code to avoid circularity if
% for example, we are trying to redefine \cs{tablename} as
% \cs{tablename}. Decrement the caption counter.
%    \begin{macrocode}
  \setlength{\abovecaptionskip}{0pt}%
  \setlength{\belowcaptionskip}{0pt}%
  \edef\@memtempc{#4}%
  \expandafter\renewcommand\csname \@captype name\endcsname{\@memtempc}%
  \addtocounter{\@captype}{-1}%
%    \end{macrocode}
% Now repeat for the second language caption.
%    \begin{macrocode}
  \@contmidbi
  \@ifmtarg{#5}{\def\m@mscapii{#6}\caption{#6}}%
               {\def\m@mscapii{#5}\caption[#5]{#6}}%
  \membitwonumcaptioninfo{\@captype}{\@nameuse{the\@captype}}%
                         {\m@mscapi}{#3}{#4}{\m@mscapii}{#6}%
  \endgroup}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\bionenumcaption}
%  The 6 arguments are: optional labelling,
%  short and long in language 1, name in
% language 2, and short and long in language 2. Both texts are put
% into the List of, but only the first is numbered.
%    \begin{macrocode}
\newcommand{\bionenumcaption}[6][\@empty]{%
  \begingroup
  \let\memcaptioninfo\@gobblefour
%    \end{macrocode}
% Check if the first language argument is vacuous, then call
% the normal \cs{caption} for language 1.
%    \begin{macrocode}
  \@ifmtarg{#2}{\def\m@mscapi{#3}\caption{#3}}%
               {\def\m@mscapi{#2}\caption[#2]{#3}}%
%    \end{macrocode}
% Do the optional labeling.
%    \begin{macrocode}
  \ifx \@empty #1\else
    \label{#1}%
  \fi
%    \end{macrocode}
% Do the between captions code.
%    \begin{macrocode}
  \setlength{\abovecaptionskip}{0pt}%
  \setlength{\belowcaptionskip}{0pt}%
  \edef\@memtempc{#4}%
  \expandafter\renewcommand\csname \@captype name\endcsname{\@memtempc}
%    \end{macrocode}
% Use a continuation caption for the second language, not forgetting
% to add the appropriate unnumbered text to the List.
%    \begin{macrocode}
  \@contmidbi
  \contcaption{#6}%
  \@ifmtarg{#5}{%
    \def\m@mscapii{#6}%
    \addcontentsline{\csname ext@\@captype\endcsname}{\@captype}%
      {\protect\numberline{}{\ignorespaces #6}}}{%
    \def\m@mscapii{#5}%
    \addcontentsline{\csname ext@\@captype\endcsname}{\@captype}%
      {\protect\numberline{}{\ignorespaces #5}}}%
  \membionenumcaptioninfo{\@captype}{\@nameuse{the\@captype}}%
                         {\m@mscapi}{#3}{#4}{\m@mscapii}{#6}%
  \endgroup}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\bicaption}
%  The 5 arguments are: optional labelling, 
% short and long in language 1, name in
% language 2, and long in language 2. 
% Only the first text is put into the List.
%    \begin{macrocode}
\newcommand{\bicaption}[5][\@empty]{%
  \begingroup
  \let\memcaptioninfo\@gobblefour
%    \end{macrocode}
% Check if the first language argument is vacuous, then call
% the normal \cs{caption} for language 1.
%    \begin{macrocode}
  \@ifmtarg{#2}{\def\m@mscapi{#3}\caption{#3}}%
               {\def\m@mscapi{#2}\caption[#2]{#3}}%
%    \end{macrocode}
% Do the optional labeling.
%    \begin{macrocode}
  \ifx \@empty #1\else
    \label{#1}%
  \fi
%    \end{macrocode}
% Do the between captions code and 
% finally just use \cs{contcaption} for the
% second language.
%    \begin{macrocode}
  \setlength{\abovecaptionskip}{0pt}%
  \setlength{\belowcaptionskip}{0pt}%
  \edef\@memtempc{#4}
  \expandafter\renewcommand\csname \@captype name\endcsname{\@memtempc}%
  \@contmidbi
  \contcaption{#5}%
  \membicaptioninfo{\@captype}{\@nameuse{the\@captype}}%
                   {\m@mscapi}{#3}{#4}{#5}%
  \endgroup}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\bicontcaption}
%  The 3 arguments are long in language 1, name in
% language 2, and long in language 2.
%    \begin{macrocode}
\newcommand{\bicontcaption}[3]{%
  \begingroup
%    \end{macrocode}
% Call \cs{contcaption} for language 1.
%    \begin{macrocode}
  \contcaption{#1}%
%    \end{macrocode}
% Do the between captions code and use \cs{contcaption} for the second
% language.
%    \begin{macrocode}
  \setlength{\abovecaptionskip}{0pt}%
  \setlength{\belowcaptionskip}{0pt}%
  \edef\@memtempc{#2}%
  \expandafter\renewcommand\csname \@captype name\endcsname{\@memtempc}%
  \@contmidbi
  \contcaption{#3}%
  \endgroup}

%    \end{macrocode}
% \end{macro}
%
%
%
% \subsubsection{Support for the \Lopt{subfigure} package functionality}
%
% Much of the code in this section is based on the \Lpack{subfigure}
% package code, by kind permission of its author, Steven Douglas Cochran.
% To try and avoid clashes with the real \Lpack{subfigure} code I have
% used different macro names, especially when I have copied the code.
%
% \begin{macro}{\subcaptionstyle}
% \begin{macro}{\@contsubcstyle}
% The paragraphing style for subcaptions.
%    \begin{macrocode}
\newcommand{\subcaptionstyle}[1]{\def\@contsubcstyle{#1}}
\subcaptionstyle{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\if@shortsubcap}
% \begin{macro}{\if@hangsubcap}
% \begin{macro}{\shortsubcaption}
% \begin{macro}{\hangsubcaption}
% \begin{macro}{\normalsubcaption}
%  For dealing with short and hanging subcaptions. 
% Analagous to the \Lpack{subfigure} \texttt{nooneline} and \texttt{hang} options.
% The default is normal subcaptions.
%    \begin{macrocode}
\newif\if@shortsubcap
\newif\if@hangsubcap
\newcommand*{\shortsubcaption}{\@shortsubcaptrue}
\newcommand*{\hangsubcaption}{\@hangsubcaptrue}
\newcommand*{\normalsubcaption}{\@shortsubcapfalse\@hangsubcapfalse}
\normalsubcaption

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\subfloattopskip}
% \begin{macro}{\subfloatcapskip}
% \begin{macro}{\subfloatcaptopadj}
% \begin{macro}{\subfloatbottomskip}
% \begin{macro}{\subfloatlabelskip}
% \begin{macro}{\subfloatcapmargin}
% These \cs{subfloat...} lengths are analagous to the \Lpack{subfigure} 
% \cs{subfig...} lengths.
%    \begin{macrocode}
\newskip\subfloattopskip
\newskip\subfloatcapskip
\newskip\subfloatcaptopadj
\newskip\subfloatbottomskip
\newskip\subfloatlabelskip
\newdimen\subfloatcapmargin
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\if@tightsubcap}
% \begin{macro}{\loosesubcaptions}
% \begin{macro}{\tightsubcaptions}
% Unlike the \Lpack{subfigure} package the class provides no options for
% subcaptions. These macros provide the \Lpack{subfigure} loose/tight
% option functions. Set the default to tight.
%    \begin{macrocode}
\newif\if@tightsubcap
\newcommand{\loosesubcaptions}{%
  \subfloattopskip = 10\p@
  \subfloatcapskip  = 10\p@
  \subfloatcaptopadj = \z@
  \subfloatbottomskip = 10\p@
  \subfloatlabelskip = 0.33em
  \subfloatcapmargin = 10\p@
  \@tightsubcapfalse
}

\newcommand{\tightsubcaptions}{%
  \subfloattopskip = 5\p@
  \subfloatcapskip  = \z@
  \subfloatcaptopadj = 3\p@
  \subfloatbottomskip = 5\p@
  \subfloatlabelskip = 0.33em \@plus 0.07em \@minus 0.03em
  \subfloatcapmargin = \z@
  \@tightsubcaptrue
}
\tightsubcaptions

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\subcaptionsize}
% \begin{macro}{\@subcapsize}
% \begin{macro}{\subcaptionlabelfont}
% \begin{macro}{\@subcaplabelfont}
% \begin{macro}{\subcaptionfont}
% \begin{macro}{\@subcapfont}
% These macros set the size and fonts for the subcaptions. Set the defaults
% to \cs{footnotesize}, and the normal roman font.
%    \begin{macrocode}
\newcommand*{\subcaptionsize}[1]{\def\@subcapsize{#1}}
\newcommand*{\subcaptionlabelfont}[1]{\def\@subcaplabelfont{#1}}
\newcommand*{\subcaptionfont}[1]{\def\@subcapfont{#1}}
\subcaptionsize{\footnotesize}
\subcaptionlabelfont{\normalfont}
\subcaptionfont{\normalfont}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@contkeep}
% \begin{macro}{\@contset}
% \begin{macro}{\subconcluded}
% \cs{@contkeep} stores
% the current subfloat number in counter \verb?@contsubnum? and 
% \cs{@contset} sets the subfloat number to the value of \verb?@contsubnum?.
% \cs{subconcluded} sets the subfloat number to zero. 
%    \begin{macrocode}
  \newcounter{@contsubnum}
  \newcommand{\@contkeep}{%
    \setcounter{@contsubnum}{\value{sub\@captype}}}
  \newcommand{\@contset}{%
    \setcounter{sub\@captype}{\value{@contsubnum}}}
  \newcommand{\subconcluded}{%
    \setcounter{sub\@captype}{0}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%
% \begin{macro}{\if@contbotsub}
% A flag indicating whether the subcaption is to be at the bottom or
% top of the subfloat; TRUE for the subcaption at the bottom.
%    \begin{macrocode}
\newif\if@contbotsub
  \@contbotsubtrue

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\subcaption}
% \cs{subcaption}\oarg{list-entry}\marg{caption} is a generic
% subcaption. There is no \Lpack{subfigure} equivalent.
%    \begin{macrocode}
\newcommand{\subcaption}{%
  \bgroup
    \let\label=\memsub@label
    \ifdonemaincaption\else
      \advance\csname c@\@captype\endcsname\@ne
    \fi
    \refstepcounter{sub\@captype}\@contkeep
    \@ifnextchar [%
      {\@memsubcap{sub\@captype}}%
      {\@memsubcap{sub\@captype}[\@empty]}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@memsubcap}
% This handles the optional argument to \cs{subcaption}. It sets \cs{@tempdima}
% to \cs{hsize} as later on \cs{@makesubfloatcaption} uses this.
% \changes{v1.1a}{2002/04/28}{Added \cs{@tempdima} to \cs{@memsubcap}}
%    \begin{macrocode}
\long\def\@memsubcap#1[#2]#3{%
  \@tempdima=\hsize
  \vskip\subfloatcapskip
  \ifx \@empty #2
    \@memsubcaption{#1}{#3}{#3}%
  \else
    \@memsubcaption{#1}{#2}{#3}%
  \fi
  \vskip\subfloatcapskip
  \egroup}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\@memsubcaption}
% \cs{@memsubcaption}\marg{type}\marg{list-entry}\marg{caption}
% typesets a subcaption. This is a copy of the \Lpack{subfigure} 
% \cs{@subcaption} macro.
%    \begin{macrocode}
\newcommand{\@memsubcaption}[3]{%
  \ifx \relax#2\relax \else
    \bgroup
      \let\label\@gobble
      \let\protect\string
      \def\@memsubcaplabel{\@nameuse{@@the#1}}%
      \xdef\@memsubfigcaptionlist{%
        \@memsubfigcaptionlist,%
  {\protect\numberline{\@memsubcaplabel}\noexpand{\ignorespaces #2}}}%
    \egroup
  \fi
  \@makesubfloatcaption{\@nameuse{@the#1}}{#3}}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\contsubcaption}
% \cs{contsubcaption}\oarg{caption} is the continued version of
% \cs{subcaption}.
%    \begin{macrocode}
\newcommand{\contsubcaption}{%
  \bgroup
    \let\label=\memsub@label
    \@contset
    \refstepcounter{sub\@captype}\@contkeep
    \@ifnextchar [%
      {\@memsubcap{sub\@captype}}%
      {\@memsubcap{sub\@captype}[\@empty]}}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{environment}{subfloat}
% The \Lpack{subfigure} documentation suggests a way of defining a \Lenv{subfloat}
% environment. This is a trivial implementation because the \cs{subcaption}
% and \cs{contsubcaption} commands are provided by the class, and can be used
% within a \Lenv{subfloat}.
%    \begin{macrocode}
\newenvironment{subfloat}{}{}

%    \end{macrocode}
% \end{environment}
%
%
%
% \begin{macro}{\subbottom}
% \begin{macro}{\@memsubbody}
%    \cs{subbottom}\oarg{list-entry}\oarg{subcaption}\marg{text}
% typesets a subcaption below the \meta{text}. Most of the  work is
% performed by the \cs{@memsubbody} macro.
%    \begin{macrocode}
\newcommand{\subbottom}{%
  \@contbotsubtrue
  \@memsubbody}

\newcommand{\@memsubbody}{%
  \bgroup
  \let\label=\memsub@label
  \ifdonemaincaption\else
    \advance\csname c@\@captype\endcsname\@ne
  \fi
  \refstepcounter{sub\@captype}\@contkeep%
  \leavevmode
  \@ifnextchar [%
    {\@memsubfig}%
    {\@memsubfig[\@empty]}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\contsubbottom}
% \begin{macro}{\@memcontsubbody}
%     These are the continued versions of \cs{subbottom} and \cs{@memsubbody}.
% \begin{macrocode}
\newcommand{\contsubbottom}{%
  \@contbotsubtrue
  \@memcontsubbody}

\newcommand{\@memcontsubbody}{%
  \bgroup
  \let\label=\memsub@label
  \@contset
  \refstepcounter{sub\@captype}\@contkeep%
  \leavevmode
  \@ifnextchar [%
    {\@memsubfig}%
    {\@memsubfig[\@empty]}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\subtop}
% \begin{macro}{\contsubtop}
%  These are similar to \cs{subbottom} and \cs{contsubbottom} except that they
% put the subcaption on top of the \meta{text}.
%    \begin{macrocode}
\newcommand{\subtop}{%
  \@contbotsubfalse
  \@memsubbody}

\newcommand{\contsubtop}{%
  \@contbotsubfalse
  \@memcontsubbody}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \changes{v1.1a}{2002/04/28}{Deleted \cs{@contsubfloat} as it was not used}
%
% \begin{macro}{\@memsubfig}
% This is a revised version of the \Lpack{subfigure} \cs{@subfigure} command
% --- just the called macro names are changed.
%    \begin{macrocode}
\def\@memsubfig[#1]{%
  \@ifnextchar [%
    {\@memsubfloat{sub\@captype}[#1]}%
    {\@memsubfloat{sub\@captype}[\@empty #1][#1]}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@memsubfloat}
%    This is a modified version of the \Lpack{subfigure} \cs{@subfloat}
% command Essentially the \verb?\csname if#1topcap\endcsname? constructs are
% replaced by \cs{if@contbotsub}. 
% \changes{v3.6k}{2011/05/16}{This ought to be long}
%    \begin{macrocode}
\long\def\@memsubfloat#1[#2][#3]#4{%
  \@tempcnta=\@ne
  \if@tightsubcap
    \if@minipage
      \@tempcnta=\z@
    \else
      \ifdim\lastskip=\z@
        \@tempcnta=\@ne
      \else
        \@tempcnta=\tw@
      \fi
    \fi
  \fi
  \if@contbotsub
    \def\subfig@top{\subfloattopskip}%
    \def\subfig@bottom{\subfloatbottomskip}%
  \else
    \def\subfig@top{\subfloatbottomskip}%
    \def\subfig@bottom{\subfloattopskip}%
  \fi
  \setbox\@tempboxa \hbox{#4}%
  \@tempdima=\wd\@tempboxa
  \vtop\bgroup
    \vbox\bgroup
    \ifcase\@tempcnta
      \@minipagefalse
    \or
      \vspace{\subfig@top}
    \or
      \ifdim \lastskip=\z@ \else
        \@tempskipb\subfig@top\@xaddvskip
      \fi
    \fi
    \if@contbotsub
      \box\@tempboxa\egroup
      \ifx \@empty#3\relax \else
        \vskip\subfloatcapskip
        \@memsubcaption{#1}{#2}{#3}%
      \fi
    \else
      \ifx \@empty#3\relax \else
        \@memsubcaption{#1}{#2}{#3}%
        \vskip\subfloatcapskip
        \vskip\subfloatcaptopadj
      \fi\egroup
      \box\@tempboxa
    \fi
    \vspace{\subfig@bottom}
  \egroup
\egroup}
  
%    \end{macrocode}
% \end{macro}
%
%
% The following series of macros, from \Lpack{subfigure}, control the 
% typesetting of the subcaptions.
%
% \begin{macro}{\@memsubfigcaptionlist}
% A copy of \cs{@subfigcaptionlist}.
%    \begin{macrocode}
\newcommand*{\@memsubfigcaptionlist}{}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\memlistsubcaptions}
% A copy of \cs{listsubcaptions}.
%    \begin{macrocode}
\newcommand*{\memlistsubcaptions}{%
  \@ifstar
    {\gdef\@memsubfigcaptionlist{}}%
    {\@memlistsubcaptions{\@captype}}}

%    \end{macrocode}
% \end{macro}
% 
%
% \begin{macro}{\@memlistsubcaptions}
% A copy of \cs{@listsubcaptions}.
%    \begin{macrocode}
\newcommand*{\@memlistsubcaptions}[1]{%
  \@ifundefined{@captype}{}{%
    \@ifundefined{ext@sub#1}{}{%
      \@for \@tempa:=\@memsubfigcaptionlist \do {%
        \ifx \@empty\@tempa\relax \else
          \addcontentsline{\@nameuse{ext@sub#1}}{sub#1}{\@tempa}%
        \fi}}}%
  \gdef\@memsubfigcaptionlist{}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@makesubfloatcaption}
%  This is a copy of \cs{@makesubfigurecaption}.
% \changes{v3.6k}{2011/07/21}{Added a \cs{unskip} to remove a space if
% the text is empty}
%    \begin{macrocode}
\newcommand{\@makesubfloatcaption}[2]{%
  \setbox\@tempboxa\hbox{%
    \@subcapsize
    {\@subcaplabelfont #1}{\@subcapfont\ignorespaces #2}\unskip}%
  \@tempdimb=-\subfloatcapmargin
  \multiply\@tempdimb\tw@
  \advance\@tempdimb\@tempdima
  \hb@xt@\@tempdima{%
    \hss
    \ifdim \wd\@tempboxa >\@tempdimb
      \memsubfig@caption{#1}{#2}%
    \else
      \if@shortsubcap
        \memsubfig@caption{#1}{#2}%
      \else
        \box\@tempboxa
      \fi
    \fi
    \hss}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\memsubfig@caption}
% This is a copy of \cs{subfig@caption}.
% \changes{v3.6k}{2011/07/21}{Added a \cs{unskip} to remove a space if
% the text is empty}
%    \begin{macrocode}
\newcommand{\memsubfig@caption}[2]{%
  \if@hangsubcap
    \sbox{\@tempboxa}{\@subcapsize\@subcaplabelfont #1}%
    \addtolength{\@tempdimb}{-\wd\@tempboxa}%
    \usebox{\@tempboxa}%
    \memsubfig@captionpar{\@tempdimb}{%
      {\@subcapfont\ignorespaces #2}\unskip}%
  \else
    \memsubfig@captionpar{\@tempdimb}{{\@subcaplabelfont #1}%
      {\@subcapfont\ignorespaces #2}\unskip}%
  \fi}

%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\memsubfig@captionpar}
% This replaces \cs{subfig@captionpar}.
%    \begin{macrocode}
\newcommand{\memsubfig@captionpar}[2]{%
  \parbox[t]{#1}{\@subcapsize\@contsubcstyle #2}}

%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\memsub@label}
% These are copies of \cs{sub@label} and \cs{subref}.
%    \begin{macrocode}
\newcommand{\memsub@label}{%
  \@ifnextchar (%
    {\sf@memsub@label}%
    {\sf@memsub@label(Sub\@captype\space
                     \@nameuse{p@sub\@captype}%
                     \@nameuse{thesub\@captype})}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sf@memsub@label}
% This is a copy of \cs{sf@sub@label}.
%    \begin{macrocode}
\def\sf@memsub@label(#1)#2{%
  \protected@edef\mem@currentlabelname{#1}%
  \sf@@memsub@label{#2}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sf@@memsub@label}
% This is an expanded copy of \cs{sf@@sub@label} processed after any packages may
% have been loaded.
% An added complexity here is when \Lpack{showkeys} is used. It
% redefines \cs{label} to write it in the margins. But the
% \cs{sf@@memsub@label} writes the label to aux directly. So in order
% to support \Lpack{showkeys}, we add a hook, and define this hook if
% \Lpack{showkeys} is loaded.
% \changes{v3.7g}{2018/02/28}{Added hook into \cs{sf@@memsub@label},
% issue reported via \texttt{https://tex.stackexchange.com/q/374301/3929}}
%    \begin{macrocode}
\newcommand\sf@@memsub@label@hook[1]{}

\AtBeginDocument{%
  \@ifpackageloaded{nameref}{%
%    \end{macrocode}
% The \Lpack{nameref} package is loaded.
%    \begin{macrocode}
    \newcommand*{\sf@@memsub@label}[1]{%
      \@bsphack
      \sf@@memsub@label@hook{#1}%
      \protected@write\@auxout{}{%
        \string\newlabel{#1}%
          {{\@nameuse{p@sub\@captype}\@nameuse{@@thesub\@captype}}%
          {\thepage}%
          {\mem@currentlabelname\relax}%
          {\@currentHref}{}}}%
      \protected@write\@auxout{}{%
        \string\newlabel{sub@#1}%
          {{\@nameuse{@@thesub\@captype}}%
          {\thepage}%
          {\mem@currentlabelname\relax}%
          {\@currentHref}{}}}%
  \@esphack}
  }{% no nameref
    \@ifpackageloaded{hyperref}{%
%    \end{macrocode}
% The \Lpack{hyperref} package is loaded, but not \Lpack{nameref}.
%    \begin{macrocode}
      \newcommand*{\sf@@memsub@label}[1]{%
        \@bsphack
        \sf@@memsub@label@hook{#1}%
        \protected@write\@auxout{}{%
          \string\newlabel{#1}%
            {{\@nameuse{p@sub\@captype}\@nameuse{@@thesub\@captype}}%
            {\thepage}%
            {\mem@currentlabelname\relax}%
            {\@currentHref}{}}}%
        \protected@write\@auxout{}{%
          \string\newlabel{sub@#1}%
            {{\@nameuse{@@thesub\@captype}}%
            {\thepage}%
            {\mem@currentlabelname\relax}%
            {\@currentHref}{}}}%
    \@esphack}
    }{% no hyperref
%    \end{macrocode}
% Neither the \Lpack{hyperref} nor the \Lpack{nameref}
% package is loaded.
%    \begin{macrocode}
      \let\@memoldlabel\label
      \newcommand*{\sf@@memsub@label}[1]{%
        \@bsphack
        \sf@@memsub@label@hook{#1}%
        \@memoldlabel{#1}%
        \protected@write\@auxout{}{%
          \string\newlabel{sub@#1}%
            {{\@nameuse{@@thesub\@captype}}%
            {\thepage}}}%
    \@esphack}
    }{}%
  }% end no nameref
%    \end{macrocode}
% Next add the hook redefinition if \Lpack{showkeys} is loaded. Please
% note that the placement of the \Lpack{showkeys} label, might be a
% little strange.
% \changes{v3.7g}{2018/02/28}{added}
%    \begin{macrocode}
  \@ifpackageloaded{showkeys}{%
    \renewcommand\sf@@memsub@label@hook[1]{%
      \SK@\SK@@label{#1}%
    }
  }{}
} % end AtBeginDocument

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\subcaptionref}
% This is a copy of the \cs{subref} macro.
%    \begin{macrocode}
\DeclareRobustCommand{\subcaptionref}{%
  \@ifstar{\ssc@ref}{\sc@ref}}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\ssc@ref}
% \begin{macro}{\sc@ref}
% The implementation of the starred and unstarred forms of \cs{subcaptionref}.
%    \begin{macrocode}
\newcommand*{\ssc@ref}[1]{\ref{sub@#1}}
\newcommand*{\sc@ref}[1]{{\@subcaplabelfont\ref{sub@#1}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% 
% \subsubsection{Side captions}
% \changes{v1.61803}{2008/01/30}{Added all the code for side captions 
%         (mempatch v4.1)}
%
% \begin{macro}{\m@mscap@capbox}
% \begin{macro}{\m@mscap@fbox}
% We need two save boxes, one to hold the caption and the other
% for the float material.
%    \begin{macrocode}
\newsavebox{\m@mscap@capbox}
\newsavebox{\m@mscap@fbox}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\sidecapsep}
% \begin{macro}{\sidecapwidth}
% \cs{sidecapsep} is the space between the text and the caption, which
% is set in a box \cs{sidecapwidth} wide. These are initialized to
% the \cs{marginpar...} values.
%    \begin{macrocode}
\newdimen\sidecapsep
  \sidecapsep=\marginparsep
\newdimen\sidecapwidth
  \sidecapwidth=\marginparwidth
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setsidecaps}
% \cs{setsidecaps}\marg{sep}\marg{width} sets the \cs{sidecapsep} and
% \cs{sidecapwidth} (Ivars Finvers noted that the initial values don't change 
% if the \cs{marginpar...} values change, such as at \cs{checkandfixthelayout}).
% \changes{v1.61803}{2008/01/30}{Added \cs{setsidecaps} (mempatch v4.6)}
%    \begin{macrocode}
\newcommand*{\setsidecaps}[2]{%
  \setlength{\sidecapsep}{#1}\@memznegtest{\sidecapsep}%
  \setlength{\sidecapwidth}{#2}\@memznegtest{\sidecapwidth}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@m@tempdima}
% \begin{macro}{\m@mscapraise}
% Lengths for internal use. \cs{m@m@tempdima} is meant for general
% temporary use.
%    \begin{macrocode}
\newdimen\m@m@tempdima
\newdimen\m@mscapraise
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\sidecapraise}
% Length to make (small) adjustments to the position of the caption wrt the float.
%    \begin{macrocode}
\newdimen\sidecapraise
  \sidecapraise \z@

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setsidecappos}
% \begin{macro}{\m@mscappos}
% \cs{setsidecappos}\marg{pos}, where \meta{pos} is one of \texttt{t},
% \texttt{c}, or \texttt{b}, sets the vertical position of the caption
% in relation to the float and the result is saved as \cs{m@mscappos}.
% The default is \texttt{c}.
%    \begin{macrocode}
\newcommand*{\setsidecappos}[1]{%
  \def\m@mscappos{#1}\def\@tempb{t}%
  \ifx\@tempb\m@mscappos
  \else
    \def\@tempb{b}%
    \ifx\@tempb\m@mscappos
    \else
      \def\@tempb{c}%
      \ifx\@tempb\m@mscappos
      \else
        \@memerror{Argument to \string\setsidecappos\space is not t or c or b.
                   \MessageBreak Set to c}{\@ehc}%
        \def\m@mscappos{c}%
      \fi
    \fi
  \fi}     
\setsidecappos{c}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\sidecapmargin}
% \begin{macro}{\m@mscapmarg}
% \cs{sidecapmargin}\marg{margin}, where \meta{marg} is one of
% \texttt{left}, \texttt{right}, \texttt{inner}, or \texttt{outer}, 
% controls the margin where the caption will be put. The result
% is saved as \cs{m@mscapmarg} as a number. The default
% is \texttt{left}.
%    \begin{macrocode}
\newcommand{\sidecapmargin}[1]{%
  \def\@tempa{#1}\def\@tempb{left}%
    \ifx\@tempb\@tempa
      \def\m@mscapmarg{0}%   left
    \else
      \def\@tempb{right}%
      \ifx\@tempb\@tempa
        \def\m@mscapmarg{1}%  right
      \else
        \def\@tempb{outer}%
        \ifx\@tempb\@tempa
          \def\m@mscapmarg{2}%  outer
        \else
          \def\@tempb{inner}%
          \ifx\@tempb\@tempa
            \def\m@mscapmarg{3}%  inner
          \else
            \@memerror{Unrecognized argument for \string\sidecapmargin}%
                      {\@ehc}%
            \def\m@mscapmarg{-1}% error
          \fi
        \fi
      \fi
    \fi}
\sidecapmargin{left}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ifscapmargleft}
% \begin{macro}{\scapmarglefttrue}
% \begin{macro}{\scapmargleftfalse}
%  \cs{ifscapmargleft} is TRUE the caption should be in the left hand margin,
% otherwise in the right hand margin.
%    \begin{macrocode}
\newif\ifscapmargleft

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\sidecapfloatwidth}
% \begin{macro}{\m@mscapmainwidth}
% \cs{sidecapfloatwidth} is the width of the box holding the float. 
% Note that this is a macro,
% not a length, so must be changed using \cs{renewcommand*}.
% The default is \cs{linewidth}. Later, \cs{m@mscapmainwidth} will be set
% to the current length specification from \cs{sidecapfloatwidth}.
%    \begin{macrocode}
\def\sidecapfloatwidth{\linewidth}
\newdimen\m@mscapmainwidth

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mscaplkern}
% \begin{macro}{\setm@mscaplkern}
% \cs{setm@mscaplkern} is a utility macro to calculate the kern 
% (\cs{m@mscaplkern}) required when the caption is in the left margin.
%    \begin{macrocode}
\newdimen\m@mscaplkern
\newcommand*{\setm@mscaplkern}{%
  \m@mscaplkern=\sidecapwidth
  \advance\m@mscaplkern \sidecapsep
  \advance\m@mscaplkern \m@mscapmainwidth}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\sidecapstyle}
% \cs{sidecapstyle} is called just before the caption is set. It can
% be redefined to set different caption style parameters. The default
% is raggedleft for left margin captions and raggedright for right
% margin captions.
%    \begin{macrocode}
\newcommand*{\sidecapstyle}{%
%%%  \captionnamefont{\bfseries}%
  \ifscapmargleft
    \captionstyle{\raggedleft}%
  \else
    \captionstyle{\raggedright}%
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sidecaption}
% The whole shebang is in the \texttt{sidecaption} environment but
% it is more convenient to specify this via macros rather than 
% directly as an environment.
%
% \cs{sidecaption}\oarg{fortoc}\marg{title}\oarg{label} is what it
% looks like to the user, but internally further macros handle
% all the arguments.
%    \begin{macrocode}
\newcommand*{\sidecaption}{%
  \@ifnextchar [{\@sidecaption}{\@sidecaption[]}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@sidecaption}
% \cs{@sidecaption}\oarg{fortoc}\marg{title} grabs the first
% two arguments.
%    \begin{macrocode}
\def\@sidecaption[#1]#2{%
  \@ifnextchar [{\@@sidecaption{#1}{#2}}{\@@sidecaption{#1}{#2}[]}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@mem@scap@beforehook}
% \begin{macro}{\@mem@scap@afterhook}
% Two hooks into the 'scap' internals. By default they do nothing, but
% can be used make say sidecaption align towards the spine in twosided
% documents. This is done by redefining \emph{before} to
% \verb+\checkoddpage\ifoddpage\else\raggedleft\fi+ and redefining
% \emph{after} to \verb+\par+. Note that since 'sidecontcaption',
% 'sidenamedlegend' and 'sidelegend' all share the same basic
% internals redefining the two hooks will affect those as well. The
% user might want to create their own special environment, say, like this:
% \begin{verbatim}
% \makeatletter
% \newenvironment{sidecaption*}{
%   \renewcommand\@mem@scap@beforehook{\checkoddpage\ifoddpage\else\raggedleft\fi}
%   \renewcommand\@mem@scap@afterhook{\par}
%   \begin{sidecaption}}
%   {\end{sidecaption}}
% \makeatother
% \end{verbatim}
% \changes{v1.6180339c}{2009/01/21}{Added 'before' and 'after' hooks
% to shared sidecaption internals}
%    \begin{macrocode}
\newcommand\@mem@scap@beforehook{}
\newcommand\@mem@scap@afterhook{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@@sidecaption}
% \cs{@@sidecaption}\marg{fortoc}\marg{title}\oarg{label} is the
% last macro in the chain and handles all three arguments.
% This does all the work for \verb?\begin{sidecaption}?
% \begin{macro}{\m@mscap@fortoc}
% \begin{macro}{\m@mscap@forcap}
% \begin{macro}{\m@mscaplabel}
% First, save all the arguments as macros.
%    \begin{macrocode}
\def\@@sidecaption#1#2[#3]{%
  \ifx\@empty#1\@empty
    \def\m@mscap@fortoc{#2}%
  \else
    \def\m@mscap@fortoc{#1}%
  \fi
  \def\m@mscap@forcap{#2}%
  \ifx\@empty#3\@empty
    \def\m@mscaplabel{}%
  \else
    \def\m@mscaplabel{\@bsphack\label{#3}\@esphack}%
  \fi
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% Set the float width, calculate the left margin kern, and start
% a \texttt{minipage} to hold the float, saving it in box
% \cs{m@mscap@fbox}.
%    \begin{macrocode}
  \m@mscapstart@fbox}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mscapstart@fbox}
% \begin{macro}{\m@mscapend@fbox}
% \cs{m@mscapstart@fbox} is the macro that actually sets the float width, 
% calculates the left margin kern, and starts the float's \texttt{minipage}.
% The macro \cs{m@mscapend@fbox} ends the box.
%    \begin{macrocode}
\newcommand*{\m@mscapstart@fbox}{%
%    \end{macrocode}
% \changes{v1.6180339c}{2009/01/21}{Added \cs{@mem@scap@beforehook}}
%    \begin{macrocode}
  \@mem@scap@beforehook%
  \setlength{\m@mscapmainwidth}{\sidecapfloatwidth}%
  \setm@mscaplkern
  \begin{lrbox}{\m@mscap@fbox}%
    \begin{minipage}[c]{\m@mscapmainwidth}}
\newcommand*{\m@mscapend@fbox}{%
    \end{minipage}%
  \end{lrbox}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\endsidecaption}
% \cs{endsidecaption} does the work for \verb?\end{sidecaption}?.
%
% Finish the float minipage, then increment the caption counter and
% call \cs{label} via \cs{m@mscaplabel}.
%    \begin{macrocode}
\def\endsidecaption{%
  \m@mscapend@fbox
  \refstepcounter\@captype
  \m@mscaplabel
%    \end{macrocode}
% \changes{v3.6k}{2012/08/19}{We need to move \cs{m@mscapcheckside}
% here or the \cs{sidecapstyle} inside the box, will never work correctly.}
%    \begin{macrocode}
  \m@mscapcheckside %<--- added 2012/08/19
%    \end{macrocode}
% Set the caption inside a minipage, saving it in box \cs{m@mscap@capbox}.
%    \begin{macrocode}
  \begin{lrbox}{\m@mscap@capbox}%
    \begin{minipage}[c]{\sidecapwidth}%
      \sidecapstyle
      \@caption\@captype[\m@mscap@fortoc]{\m@mscap@forcap}
    \end{minipage}%
  \end{lrbox}%
%    \end{macrocode}
% Output the float and caption.
%    \begin{macrocode}
  \m@mscapopboxes}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mscapopboxes}
% Having determined how high the caption box must be raised with
% respect to the float box, output the boxes. 
%    \begin{macrocode}
\newcommand*{\m@mscapopboxes}{%
  \m@mcalcscapraise
%    \end{macrocode}
% Set the float (from box \cs{m@mscap@fbox}) then the caption (from
% box \cs{m@mscap@capbox}) kerning it to the left or right as
% appropriate.
% \changes{v3.6k}{2012/08/19}{Moved \cs{m@mscapcheckside} into
% \cs{endsidecaption}, otherwise \cs{sidecapstyle} never see the side check}
%    \begin{macrocode}
  \usebox{\m@mscap@fbox}%\m@mscapcheckside
  \ifscapmargleft%
    \rlap{\kern-\m@mscaplkern
          \raisebox{\m@mscapraise}{\usebox{\m@mscap@capbox}}}%
  \else%
    \rlap{\kern\sidecapsep 
          \raisebox{\m@mscapraise}{\usebox{\m@mscap@capbox}}}%
  \fi
%    \end{macrocode}
% Finally, make \cs{m@mscapthisside} a no-op.
%    \begin{macrocode}
  \gdef\m@mscapthisside{}%
%    \end{macrocode}
% \changes{v1.6180339c}{2009/01/21}{Added \cs{@mem@scap@afterhook}}
%    \begin{macrocode}
  \@mem@scap@afterhook%
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mcalcscapraise}
% Calculate the amount the caption might have to be raised wrt the
% float. This depends on the position: \\
% \texttt{t:} raise by the difference in heights \\
% \texttt{c:} shouldn't have to do anything as the minipages are meant
%             to center aligned \\
% \texttt{b:} lower by the difference in depths \\
%
%    However, experiments showed that a little bit of tweaking might
% help. The final adjustment, \cs{sidecapraise} is controlled by
% the user.
%    \begin{macrocode}
\newcommand*{\m@mcalcscapraise}{%
  \def\@tempb{t}%
  \ifx\m@mscappos\@tempb
    \settoheight{\m@m@tempdima}{\strut\usebox{\m@mscap@capbox}}%
    \settoheight{\m@mscapraise}{\usebox{\m@mscap@fbox}}%
    \advance\m@mscapraise -\m@m@tempdima
    \advance\m@mscapraise  0.5ex
  \else
    \def\@tempb{b}%
    \ifx\m@mscappos\@tempb
      \settodepth{\m@m@tempdima}{\usebox{\m@mscap@fbox}}%
      \settodepth{\m@mscapraise}{\strut\usebox{\m@mscap@capbox}}%
      \advance\m@mscapraise -\m@m@tempdima
    \else
      \m@mscapraise=\z@
      \advance\m@mscapraise 0.25ex
    \fi
  \fi
  \advance\m@mscapraise  \sidecapraise}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mscapcheckside}
% This macro determines whether the caption should be set in the
% left or right margin. In twocolumn documents the caption for a single
% column float is always set in the adjacent margin. Starred floats
% are treated as regular floats as in a onecolumn document.
%    \begin{macrocode}
\newcommand*{\m@mscapcheckside}{%
  \if@twocolumn
    \ifdim\hsize=\textwidth%  float*
      \m@mscapcheckregside
    \else
      \if@firstcolumn
        \scapmarglefttrue
      \else
        \scapmargleftfalse
      \fi
    \fi
  \else
    \m@mscapcheckregside
  \fi
%    \end{macrocode}
% Finally apply any user's override.
%    \begin{macrocode}
  \m@mscapthisside}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mscapcheckregside}
% This performs the margin calculation for onecolumn documents.
%    \begin{macrocode}
\newcommand*{\m@mscapcheckregside}{%
    \if@twoside
      \checkoddpage
      \ifnum\m@mscapmarg<\@ne%      % left
        \scapmarglefttrue
      \else
        \ifnum\m@mscapmarg=\@ne%    % right
          \scapmargleftfalse
        \else  
          \ifnum\m@mscapmarg=\tw@%  % outer
            \scapmarglefttrue
            \ifoddpage
              \scapmargleftfalse
            \fi
          \else%                  % inner
            \scapmargleftfalse
            \ifoddpage
              \scapmarglefttrue
            \fi
          \fi
        \fi
      \fi
    \else%     oneside
%    \end{macrocode}
% In oneside documents, inner and outer is the same as left and right.
% \changes{v3.7f}{2015/08/10}{Side caption placement bugfix for
% onesided docs. Related to \protect\url{http://tex.stackexchange.com/q/259324/3929}.
% }
%    \begin{macrocode}
      % \scapmarglefttrue% 0 and 3
      % \ifnum\m@mscapmarg>\@ne
      %   \ifnum\m@mscapmarg<\thr@@
      %     \scapmargleftfalse
      %   \fi
      % \fi
      \ifcase\m@mscapmarg\relax% 0
        \scapmarglefttrue%
      \or% 1
        \scapmargleftfalse%
      \or% 2
        \scapmargleftfalse%
      \or% 3
        \scapmarglefttrue%
      \fi%
    \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\overridescapmargin}
% \begin{macro}{\m@mscapthisside}
% User macro to override the calculated caption margin. Call as either:\\
% \verb?\overridescapmargin{left}? or \verb?\overridescapmargin{right}?  \\
%    \begin{macrocode}
\newcommand*{\overridescapmargin}[1]{%
  \def\@tempb{#1}\def\@tempa{left}%
  \ifx\@tempa\@tempb
    \def\m@mscapthisside{\scapmarglefttrue}%
  \else
    \def\@tempa{right}%
    \ifx\@tempa\@tempb
      \def\m@mscapthisside{\scapmargleftfalse}%
    \else
      \@memerror{Argument to \string\overridescapmargin\space neither 
                 left nor right}{\@ehc}%
      \def\m@mscapthisside{}%
    \fi
  \fi}
\newcommand*{\m@mscapthisside}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%    Now for the other kinds of captions.
%
% \begin{macro}{\sidecontcaption}
% \cs{sidecontcaption}\marg{title}\oarg{label} is for
% a continuation sidecaption.
%    \begin{macrocode}
\newcommand*{\sidecontcaption}{%
  \@sidecontcaption}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@sidecontcaption}
% \cs{@sidecontcaption}\marg{title} grabs the first
% argument.
%    \begin{macrocode}
\def\@sidecontcaption#1{%
  \@ifnextchar [{\@@sidecontcaption{#1}}{\@@sidecontcaption{#1}[]}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@@sidecontcaption}
% \cs{@@sidecontcaption}\marg{title}\oarg{label} is the
% last macro in the chain and handles all two arguments.
% This does all the work for \verb?\begin{sidecontcaption}?
%    \begin{macrocode}
\def\@@sidecontcaption#1[#2]{%
  \def\m@mscap@forcap{#1}%
  \ifx\@empty#2\@empty
    \def\m@mscaplabel{}%
  \else
    \def\m@mscaplabel{\@bsphack\label{#2}\@esphack}%
  \fi
  \m@mscapstart@fbox}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\endsidecontcaption}
% \cs{endsidecontcaption} does the work for \verb?\end{sidecontcaption}?.
%
%    \begin{macrocode}
\def\endsidecontcaption{%
  \m@mscapend@fbox
  \addtocounter{\@captype}{\m@ne}\refstepcounter\@captype
  \m@mscaplabel
%    \end{macrocode}
% \changes{v3.7b}{2013/05/30}{Forgot the side check}
%    \begin{macrocode}
  \m@mscapcheckside %<--- added 2013/05/30
  \begin{lrbox}{\m@mscap@capbox}%
    \begin{minipage}[c]{\sidecapwidth}%
      \sidecapstyle
      \@contcaption\@captype{\m@mscap@forcap}
    \end{minipage}%
  \end{lrbox}%
  \m@mscapopboxes}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sidenamedlegend}
% \begin{macro}{\@sidenamedlegend}
% \cs{sidenamedlegend}\oarg{fortoc}\marg{title} is for
% a namedlegend sidecaption.
%    \begin{macrocode}
\newcommand*{\sidenamedlegend}{%
  \@ifnextchar [{\@sidenamedlegend}{\@sidenamedlegend[]}}
\def\@sidenamedlegend[#1]#2{%
  \@@sidenamedlegend{#1}{#2}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@@sidenamedlegend}
% \cs{@@sidenamedlegend}\marg{fortoc}\marg{title} is the
% last macro in the chain and handles all arguments.
% This does all the work for \verb?\begin{sidenamedlegend}?
%    \begin{macrocode}
\def\@@sidenamedlegend#1#2{%
  \ifx\@empty#1\@empty
    \def\m@mscap@fortoc{#2}%
  \else
    \def\m@mscap@fortoc{#1}%
  \fi
  \def\m@mscap@forcap{#2}%
  \def\m@mscaplabel{}%
  \m@mscapstart@fbox}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\endsidenamedlegend}
% \cs{endsidenamedlegend} does the work for \verb?\end{sidenamedlegend}?.
%    \begin{macrocode}
\def\endsidenamedlegend{%
  \m@mscapend@fbox
  \begin{lrbox}{\m@mscap@capbox}%
    \begin{minipage}[c]{\sidecapwidth}%
      \sidecapstyle
      \@legend\@captype[\m@mscap@fortoc]{\m@mscap@forcap}
    \end{minipage}%
  \end{lrbox}%
  \m@mscapopboxes}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sidelegend}
% \cs{sidelegend}\marg{title} is for
% a legend sidecaption.
%    \begin{macrocode}
\newcommand*{\sidelegend}{%
  \@@sidelegend}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@@sidelegend}
% \cs{@@sidelegend}\marg{title} is the
% last macro in the chain and handles all arguments.
% This does all the work for \verb?\begin{sidelegend}?
%    \begin{macrocode}
\def\@@sidelegend#1{%
  \def\m@mscap@forcap{#1}%
  \m@mscapstart@fbox}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\endsidelegend}
% \cs{endsidelegend} does the work for \verb?\end{sidelegend}?.
%    \begin{macrocode}
\def\endsidelegend{%
  \m@mscapend@fbox
  \begin{lrbox}{\m@mscap@capbox}%
    \begin{minipage}[c]{\sidecapwidth}%
      \sidecapstyle
      \legend{\m@mscap@forcap}
    \end{minipage}%
  \end{lrbox}%
  \m@mscapopboxes}

%    \end{macrocode}
% \end{macro}
%
% \changes{v3.6k}{2013/015/13}{Added \Lpack{longtable} caption
% support}
% 
% \subsubsection{Handling \Lpack{longtable} captions}
% 
% In \Lpack{longtable} the caption ends up as a special row in the
% table. In order to use our caption formatting we need to redefine
% \cs{LT@makecaption} to use our formatting macro plus
% \cs{belowcaptionskip}. It needs to be
% done after \Lpack{longtable} is loaded, and \emph{not} if the
% \Lpack{ltcaption} package is loaded. The later is used by the
% \Lpack{caption} package to aid caption formatting i
% \Lpack{longtable}. Special thanks to Axel Sommerfelt.
% \begin{macro}{\LT@makecaption}
%    \begin{macrocode}
\AtBeginDocument{
  \@ifpackageloaded{longtable}{
    \@ifpackageloaded{ltcaption}{}{%
      \def\LT@makecaption#1#2#3{%
        \LT@mcol\LT@cols c{\hbox to\z@{\hss\parbox[t]\LTcapwidth{%
           \let\@memtempa\relax%   
           % starred form -> #1 = \@gobble
           \ifx#1\@gobble%
             \let\@contnfont\@empty%
             \let\@contdelim\@empty%
             \@@makecaption{}{#3}%
           \else%
             \@@makecaption{#2}{#3}%
           \fi%
           \endgraf\vskip\belowcaptionskip}%
         \hss}}}
    }
  }{}
}
%    \end{macrocode}
% At a later point, we will supplement with a \cs{legend} for
% \Lpack{longtable} as well.
% \end{macro}
%
% \section{Epigraphs}
%
% This code comes from the \Lpack{epigraph} package~\cite{EPIGRAPH}.
%
% \begin{macro}{\beforeepigraphskip}
% \begin{macro}{\afterepigraphskip}
% \begin{macro}{\epigraphwidth}
% \begin{macro}{\epigraphrule}
%    The several length commands, which can be changed by the user with
% \cs{setlength}.
%    \begin{macrocode}
\newlength{\beforeepigraphskip}
  \setlength{\beforeepigraphskip}{.5\baselineskip}
\newlength{\afterepigraphskip}
  \setlength{\afterepigraphskip}{.5\baselineskip}
\newlength{\epigraphwidth}
  \setlength{\epigraphwidth}{.4\textwidth}
\newlength{\epigraphrule}
  \setlength{\epigraphrule}{.4\p@}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\epigraphsize}
%    The size of the font to be used.
%    \begin{macrocode}
\newcommand{\epigraphsize}{\small}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\epigraphflush}
% \begin{macro}{\textflush}
% \begin{macro}{\sourceflush}
%  The three commands to position epigraphs in the textblock and to position
%  the components of the epigraph.
%    \begin{macrocode}
\newcommand{\epigraphflush}{flushright}
\newcommand{\textflush}{flushleft}
\newcommand{\sourceflush}{flushright}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\epigraphfontsize}
% \begin{macro}{\epigraphposition}
% \begin{macro}{\epigraphtextposition}
% \begin{macro}{\epigraphsourceposition}
% These are declarative forms of the above. It's a bit late now, but
% the previous macros should have been internal.
% \changes{v1.2}{2002/08/10}{Added some declarations for epigraphs.}
%    \begin{macrocode}
\newcommand{\epigraphfontsize}[1]{\def\epigraphsize{#1}}
\newcommand{\epigraphposition}[1]{\long\def\epigraphflush{#1}}
\newcommand{\epigraphtextposition}[1]{\def\textflush{#1}}
\newcommand{\epigraphsourceposition}[1]{\def\sourceflush{#1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%
%
% \begin{macro}{\@epirule}
%  The internal command to draw a rule between text and source.
%    \begin{macrocode}
\newcommand{\@epirule}{\rule[.5ex]{\epigraphwidth}{\epigraphrule}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@epitext}
% The internal command to typeset the \meta{text}. Put it into a minipage of the
% right size and typeset per \cs{textflush}.
% \changes{v1.61803}{2008/01/30}{Added \cs{par} to \cs{@epitext} and 
%         \cs{@episource} (mempatch v4.7)}
%    \begin{macrocode}
\newcommand{\@epitext}[1]{%
  \begin{minipage}{\epigraphwidth}\begin{\textflush} #1\par
%    \end{macrocode}
%  Draw a rule if it will be visible, otherwise add some extra vertical space.
%    \begin{macrocode}
    \ifdim\epigraphrule>\z@ \@epirule \else \vspace*{1ex} \fi
  \end{\textflush}\end{minipage}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@episource}
%    The internal command for typesetting the \meta{source}, which is put 
% into a minipage and typeset according to \cs{sourceflush}.
%    \begin{macrocode}
\newcommand{\@episource}[1]{%
  \begin{minipage}{\epigraphwidth}
    \begin{\sourceflush} #1\par
  \end{\sourceflush}\end{minipage}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\epigraph}
%    Having got the preliminaries out of the way, here's the user command
% for a single epigraph. This is set in a minipage to prevent breaking
% across a page. Position it according to \cs{epigraphflush}.
%    \begin{macrocode}
\newcommand{\epigraph}[2]{\vspace{\beforeepigraphskip}
  {\epigraphsize\begin{\epigraphflush}\begin{minipage}{\epigraphwidth}
    \@epitext{#1}\\ \@episource{#2}
    \end{minipage}\end{\epigraphflush}
    \vspace{\afterepigraphskip}}}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\qitem}
% \begin{macro}{\qitemlabel}
%    \cs{qitem} is the epigraph list version of \cs{item}. 
% Set everything inside a minipage.
%    \begin{macrocode}
\newcommand{\qitem}[2]{{%
  \raggedright\item \begin{minipage}{\epigraphwidth}
    \@epitext{#1}\\ \@episource{#2}
  \end{minipage}}}
%    \end{macrocode}
%  \cs{qitemlabel} is needed for a list as well. It is not going to 
% typeset anything.
%    \begin{macrocode}
\newcommand{\qitemlabel}[1]{\hfill}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{environment}{epigraphs}
%  Now for the epigraph list. This is defined in terms of a \Lenv{list}
% environment. 
%    \begin{macrocode}
\newenvironment{epigraphs}{%
%    \end{macrocode}
% Do the vertical space, set the font size, position according to 
% \cs{epigraphflush}, and put everything into a minipage.
%    \begin{macrocode}
  \vspace{\beforeepigraphskip}\begin{\epigraphflush}
  \epigraphsize
  \begin{minipage}{\epigraphwidth}
   \list{}%
%    \end{macrocode}
%  Make the list just fit the minipage (i.e., no indents).
%    \begin{macrocode}
    {\itemindent\z@ \labelwidth\z@ \labelsep\z@
     \leftmargin\z@ \rightmargin\z@
     \let\makelabel\qitemlabel}}%
  {\endlist\end{minipage}\end{\epigraphflush}
   \vspace{\afterepigraphskip}}
%    \end{macrocode}
% \end{environment}
%
% \subsection{Epigraphs before a chapter title}
%
%
% \begin{macro}{\@epichapapp}
% \begin{macro}{\dropchapter}
% \begin{macro}{\undodrop}
%    Commands to drop and restore positions of chapter titles. Dropping is
% accomplished by inserting vertical space before the \cs{@chapapp} command.
%    \begin{macrocode}
\newcommand{\dropchapter}[1]{%
  \let\@epichapapp\@chapapp
  \renewcommand{\@chapapp}{\vspace*{#1}\@epichapapp}}
\newcommand{\undodrop}{\let\@chapapp\@epichapapp}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% Placing an epigraph before a chapter title uses the scheme outlined
% by Piet van Oostrum~\cite{FANCYHDR}. This is to put a zero sized
% picture into the page header. 
%
% \begin{macro}{\if@epirhs}
% \begin{macro}{\if@epicenter}
%  Two booleans for testing whether an epigraph is to be at the RH margin,
% centered, or at the LH margin. The default is RH margin.
%    \begin{macrocode}
\newif\if@epirhs     \@epirhstrue
\newif\if@epicenter  \@epicentertrue
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@epipos}
%    This routine sets the \cs{if@epi...} booleans according to the value of
% \cs{epigraphflush}. If \cs{epigraphflush} is neither \texttt{center} nor 
% \texttt{flushleft}
% then it defaults to \texttt{flushright}. We have to use this to be upward 
% compatible with \cs{epigraphflush} being set by the user with \cs{renewcommand}.
%    \begin{macrocode}
\newcommand{\@epipos}{
  \long\def\@ept{flushleft}
  \ifx\epigraphflush\@ept
    \@epirhsfalse \@epicenterfalse
  \else
    \long\def\@ept{center}
    \ifx\epigraphflush\@ept
      \@epirhsfalse \@epicentertrue
    \else
      \@epirhstrue  \@epicenterfalse
    \fi
  \fi}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\epigraphhead}
% \cs{epigraphhead}\oarg{distance}\marg{text} puts \meta{text} at
% \meta{distance} (a number, not a length) below the header at the 
% page position specified by \cs{epigraphflush}.
%    \begin{macrocode}
\newcommand{\epigraphhead}[2][95]{%
%    \end{macrocode}
% We have to use \cs{def} instead of the normal \LaTeX{} definition commands
% as we will keep on
% (re)defining things. For reasons that are not fully clear to me \LaTeX{}
% doesn't seem to like me using a \cs{savebox} for storing the epigraph text,
% so I'll use a command instead.
%    \begin{macrocode}
  \def\@epitemp{\begin{minipage}{\epigraphwidth}#2\end{minipage}}
%    \end{macrocode}
% Define an \texttt{epigraph} page style.
%    \begin{macrocode}
  \def\ps@epigraph{\let\@mkboth\@gobbletwo
%    \end{macrocode}
% There are three possible definitions for \cs{@oddhead} depending on the
% value of \cs{epigraphflush}. We call \cs{@epipos} to decide which one to do.
%    \begin{macrocode}
    \@epipos
    \if@epirhs
      \def\@oddhead{\hfil\begin{picture}(0,0)
                         \put(0,-#1){\makebox(0,0)[r]{\@epitemp}}
                         \end{picture}}
    \else
      \if@epicenter
        \def\@oddhead{\hfil\begin{picture}(0,0)
                           \put(0,-#1){\makebox(0,0)[b]{\@epitemp}}
                           \end{picture}\hfil}
      \else
        \def\@oddhead{\begin{picture}(0,0)
                           \put(0,-#1){\makebox(0,0)[l]{\@epitemp}}
                           \end{picture}\hfil}
      \fi
    \fi
    \let\@evenhead\@oddhead
    \def\@oddfoot{\reset@font\hfil\thepage\hfil}
    \let\@evenfoot\@oddfoot}
%    \end{macrocode}
% Make \texttt{epigraph} be the page style for this page.
%    \begin{macrocode}
  \thispagestyle{epigraph}}

%    \end{macrocode}
% \end{macro}
%
%    The above produces a \texttt{plain} pagestyle with the epigraph. Life is
% more complex if someone wants a fancy style with the epigraph. They
% will have to do some work, though.
%
% \begin{macro}{\the@epigraph}
% \begin{macro}{\@epidrop}
% \begin{macro}{\epigraphforheader}
% \cs{the@pigraph} is a macro to store the contents of an epigraph, and \cs{@pidrop}
% stores the \meta{distance} number.
% \cs{epigraphforheader}\oarg{distance}\marg{text} defines the internal macros
% appropriately.
% \changes{v1.2}{2002/08/10}{Added \cs{the@epigraph}, \cs{@epidrop}}
% \changes{v1.2}{2002/08/10}{Added \cs{epigraphforheader}}
%    \begin{macrocode}
\newcommand{\the@epigraph}{}
\newcommand{\@epidrop}{95}
\newcommand{\epigraphforheader}[2][95]{%
  \def\@epidrop{#1}\long\def\the@epigraph{#2}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\epigraphpicture}
% \cs{epigraphpicture} puts \cs{the@epigraph} into a zero-sized picture at location
% \verb?(0,-\@epidrop)?. This can then be used as part of a fancy chapter header.
% The coding is similar to \cs{epigraphhead}.
% \changes{v1.2}{2002/08/10}{Added \cs{epigraphpicture}}
%    \begin{macrocode}
\newcommand{\epigraphpicture}{%
  \def\@epitemp{%
    \begin{minipage}{\epigraphwidth}\the@epigraph\end{minipage}}%
  \@epipos
  \if@epirhs
    \begin{picture}(0,0)%
      \put(0,-\@epidrop){\makebox(0,0)[r]{\@epitemp}}%
    \end{picture}%
  \else
    \if@epicenter
      \begin{picture}(0,0)%
        \put(0,-\@epidrop){\makebox(0,0)[b]{\@epitemp}}%
      \end{picture}%
    \else
      \begin{picture}(0,0)%
        \put(0,-\@epidrop){\makebox(0,0)[l]{\@epitemp}}%
      \end{picture}%
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
%
% \section{The deprecated font commands}
%
% The class does not support the old font changing commands unless the
% \Lopt{oldfontcommands} option is used.
%
% \begin{macro}{\@memoldfonterr}
% \begin{macro}{\@memoldfontwarn}
% Macros for old font class error and warning. E.g., \\
% \verb?\@memoldfonterr{\tt}{\ttfamily}{\texttt}?
% \changes{v1.4}{2003/02/27}{Added \cs{@memoldfonterr} and \cs{@memoldfontwarn}}
% \changes{v1.618}{2005/09/03}{Fiddled with the braces in \cs{@memoldfontwarn} (mempatch v3.0)}
%    \begin{macrocode}
\newcommand*{\@memoldfonterr}[3]{%
  \@memerror{Font command \protect#1\space is not supported}{%
    Use \protect#2, or \protect#3{...}, or the oldfontcommands option}}
\newcommand*{\@memoldfontwarn}[3]{%
  \@memwarn{The \protect#1\space font command is deprecated.
    \MessageBreak Use \protect#2{...} or {\protect#3... } instead}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%  Just give a single warning when an old font command is used following the
% \Lopt{oldfontcommands} option.
% \changes{v1.4}{2003/11/22}{Just issue a single warning for an old font
%                            (from patch v1.9)}
%
% \begin{macro}{\@mem@rmwarn}
% \begin{macro}{\rm}
% The old command for roman font.
% \changes{v1.0a}{2002/01/29}{Changed definition of \cs{rm}}
% \changes{v1.4}{2003/02/27}{More efficient coding of all the old font commands}
%    \begin{macrocode}
\if@memoldfont
  \def\@mem@rmwarn{\@memoldfontwarn{\rm}{\textrm}{\rmfamily}}
  \DeclareOldFontCommand{\rm}{\@mem@rmwarn\gdef\@mem@rmwarn{}%
    \normalfont\rmfamily}{\mathrm}
\else
  \def\rm{\@memoldfonterr{\rm}{\textrm}{\rmfamily}}
\fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mem@sfwarn}
% \begin{macro}{\sf}
% The old sans font command.
% \changes{v1.0a}{2002/01/29}{Changed definition of \cs{sf}}
%    \begin{macrocode}
\if@memoldfont
  \def\@mem@sfwarn{\@memoldfontwarn{\sf}{\textsf}{\sffamily}}
  \DeclareOldFontCommand{\sf}{\@mem@sfwarn\gdef\@mem@sfwarn{}%
    \normalfont\sffamily}{\mathsf}
\else
  \def\sf{\@memoldfonterr{\sf}{\textsf}{\sffamily}}
\fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mem@ttwarn}
% \begin{macro}{\tt}
% The old typewriter font command.
% \changes{v1.0a}{2002/01/29}{Changed definition of \cs{tt}}
%    \begin{macrocode}
\if@memoldfont
  \def\@mem@ttwarn{\@memoldfontwarn{\tt}{\texttt}{\ttfamily}}
  \DeclareOldFontCommand{\tt}{\@mem@ttwarn\gdef\@mem@ttwarn{}%
    \normalfont\ttfamily}{\mathtt}
\else
  \def\tt{\@memoldfonterr{\tt}{\texttt}{\ttfamily}}
\fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mem@bfwarn}
% \begin{macro}{\bf}
% The old bold font command.
% \changes{v1.0a}{2002/01/29}{Changed definition of \cs{bf}}
%    \begin{macrocode}
\if@memoldfont
  \def\@mem@bfwarn{\@memoldfontwarn{\bf}{\textbf}{\bfseries}}
  \DeclareOldFontCommand{\bf}{\@mem@bfwarn\gdef\@mem@bfwarn{}%
    \normalfont\bfseries}{\mathbf}
\else
  \def\bf{\@memoldfonterr{\bf}{\textbf}{\bfseries}}
\fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mem@itwarn}
% \begin{macro}{\it}
% The old italic font command.
% \changes{v1.0a}{2002/01/29}{Changed definition of \cs{it}}
%    \begin{macrocode}
\if@memoldfont
  \def\@mem@itwarn{\@memoldfontwarn{\it}{\textit}{\itshape}}
  \DeclareOldFontCommand{\it}{\@mem@itwarn\gdef\@mem@itwarn{}%
    \normalfont\itshape}{\mathit}
\else
  \def\it{\@memoldfonterr{\it}{\textit}{\itshape}}
\fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mem@slwarn}
% \begin{macro}{\sl}
% The old slanted font command.
% \changes{v1.0a}{2002/01/29}{Changed definition of \cs{sl}}
%    \begin{macrocode}
\if@memoldfont
  \def\@mem@slwarn{\@memoldfontwarn{\sl}{\textsl}{\slshape}}
  \DeclareOldFontCommand{\sl}{\@mem@slwarn\gdef\@mem@slwarn{}%
    \normalfont\slshape}{\@nomath\sl}
\else
  \def\sl{\@memoldfonterr{\sl}{\textsl}{\slshape}}
\fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mem@scwarn}
% \begin{macro}{\sc}
% The old small caps font command.
% \changes{v1.0a}{2002/01/29}{Changed definition of \cs{sc}}
%    \begin{macrocode}
\if@memoldfont
  \def\@mem@scwarn{\@memoldfontwarn{\sc}{\textsc}{\scshape}}
  \DeclareOldFontCommand{\sc}{\@mem@scwarn\gdef\@mem@scwarn{}%
    \normalfont\scshape}{\@nomath\sc}
\else
  \def\sc{\@memoldfonterr{\sc}{\textsc}{\scshape}}
\fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mem@calwarn}
% \begin{macro}{\cal}
% The old calligraphic font command.
% \changes{v1.0a}{2002/01/29}{Added definition of \cs{cal}}
%    \begin{macrocode}
\if@memoldfont
  \def\@mem@calwarn{%
    \@memwarn{The \protect\cal\space font command is deprecated.
    \MessageBreak Try to use \protect\mathcal\space instead}}
  \DeclareRobustCommand*\cal{\@mem@calwarn\gdef\@mem@calwarn{}%
    \@fontswitch\relax\mathcal}
\else
  \def\cal{%
    \@memerror{Font command \protect\cal\space is not supported}{%
    Use \protect\mathcal, or the oldfontcommands option}}
\fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mem@mitwarn}
% \begin{macro}{\mit}
% The old math italic font command.
% \changes{v1.0a}{2002/01/29}{Added definition of \cs{mit}}
%    \begin{macrocode}
\if@memoldfont
  \def\@mem@mitwarn{%
    \@memwarn{The \protect\mit\space font command is deprecated.
    \MessageBreak Try to use \protect\mathnormal\space instead}}
  \DeclareRobustCommand*\mit{\@mem@mitwarn\gdef\@mem@mitwarn{}%
    \@fontswitch\relax\mathnormal}
\else
  \def\mit{%
  \@memerror{Font command \protect\mit\space is not supported}{%
             Use \protect\mathnormal, or the oldfontcommands option}}
\fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\em}
% \begin{macro}{\eminnershape}
% \begin{macro}{\emph}
% The old emphasis font command (the original \cs{em} is defined in the
% kernel file \file{ltfssini.dtx}, coded here as \cs{@m@m@m}).
% \changes{v0.2}{2001/06/03}{Redid coding for \cs{emph} and \cs{em}}
% \changes{v1.618}{2005/09/03}{Dont' deprecate \cs{em} and deleted \cs{@mem@emwarn} (mempatch v3.0)}
% \changes{v1.618}{2005/09/03}{Completely redid \cs{em} and \cs{emph}, matching latest fixltx2e package (mempatch v3.3)}
%    \begin{macrocode}
\DeclareRobustCommand{\em}{%
  \@nomath\em
  \ifdim\fontdimen\@ne\font > \z@
    \eminnershape
  \else
    \itshape
  \fi}
\providecommand{\eminnershape}{\upshape}
\DeclareTextFontCommand{\emph}{\em}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%
%
% \section{Cross Referencing} \label{sec:xref}
%
% \subsection{Label referencing}
%
% \begin{macro}{\fref}
% \begin{macro}{\tref}
% \begin{macro}{\pref}
%   These are named references to labeled figures, tables and pages. 
% I find these
% useful to ensure consistency throughout the document --- I don't have
% to remember whether it is `see Figure ...' or `figure' or `Fig.' or \ldots.
%    \begin{macrocode}
\newcommand*{\fref}[1]{\figurerefname~\ref{#1}}
\newcommand*{\tref}[1]{\tablerefname~\ref{#1}}
\newcommand*{\pref}[1]{\pagerefname~\pageref{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\Aref}
% \begin{macro}{\Bref}
% \begin{macro}{\Pref}
% \begin{macro}{\Cref}
% \begin{macro}{\Sref}
%   These are named references to labeled Part, Chapter and Sectional
% divisions.
% \changes{v1.2}{2002/07/27}{Added \cs{Pref}, \cs{Cref} and \cs{Sref}}
% \changes{v1.61803}{2008/01/30}{Added \cs{Bref} (mempatch v4.9+)}
% \changes{v1.61803}{2008/05/17}{Added \cs{Aref}}
%    \begin{macrocode}
\newcommand*{\Aref}[1]{\appendixrefname\ref{#1}}
\newcommand*{\Bref}[1]{\bookrefname\ref{#1}}
\newcommand*{\Pref}[1]{\partrefname\ref{#1}}
\newcommand*{\Cref}[1]{\chapterrefname\ref{#1}}
\newcommand*{\Sref}[1]{\sectionrefname\ref{#1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsection{Title referencing}
%
% This is based on DA's \Lpack{titleref} package~\cite{TITLEREF}. 
% The following 
% remarks are taken from that package.
%
%
%  Titles for numbered sectioning units and for floats with captions are
%  the same as the respective TOC, LOF, or LOT entry (even when no TOC is
%  printed).  When a short title is provided (\verb?\section[short]{long}?)
%  it will be used for the \cs{titleref}.  This is especially useful for
%  figure captions.  Unnumbered sections take their title reference from
%  the printed title.  Beware!  This turns the title into a moving argument
%  when it normally is not, and will cause weird errors if there are
%  `fragile' commands present.
%
%  Enumerated lists do not have titles and simply inherit the title of
%  their section.
%
%  The format of the title reference is controlled by the command
%  \cs{theTitleReference}, which can be redefined with \cs{renewcommand}.
%  It takes two parameters: the number and the title. The number is
%  just the regular \cs{ref} and it is WRONG in unnumbered sections.
%  Beware!  The default definition is the unadorned title.  You could
%  do, for example, \\
%  \verb?\renewcommand{\theTitleReference}[2]{#1\ \emph{#2}}?.
%
%  The title of the current section is also available without \cs{label}:
%  Use the command \cs{currenttitle} to generate a \cs{titleref} to the current
%  section.  If you have redefined \cs{theTitleReference} to print the number
%  with the title, be aware that the two may not correspond:  In a numbered
%  list the number will show the current item but the title will show the
%  current section, but in an unnumbered section the number will show
%  some previous section number.
%
%  The big problem with the \verb?[usetoc]? method is that \cs{titleref} will
%  not refer to a \cs{label} which was given in the title or caption itself;
%  the label must be placed after the sectioning command or the caption.
%  If you make a title-reference to a label given in a title, you will get
%  a warning message.
%
% \changes{v1.4}{2003/11/16}{Added title referencing (from patch v1.4)}
%
% \begin{macro}{\ifheadnameref}
% \begin{macro}{\headnameref}
% \begin{macro}{\tocnameref}
% \cs{ifheadnameref}: FALSE use ToC entry, TRUE use header entry
% \changes{v1.61803}{2008/01/30}{Added \cs{headnameref} and \cs{tocnameref}}
%    \begin{macrocode}
\newif\ifheadnameref
\newcommand*{\headnameref}{\headnamereftrue}
\newcommand*{\tocnameref}{\headnamereffalse}
  \tocnameref
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\theTitleReference}
% \cs{theTitleReference}\marg{num}\marg{title} is the style for typesetting
%  a referenced (number and) title.
%    \begin{macrocode}
\newcommand{\theTitleReference}[2]{#2}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\label}
% This redefinition of \cs{label} is intended to work with other redirections
% of \cs{label}, if they record extra information in a similar way.
%    \begin{macrocode}
\let\@mem@old@label\label
\def\label#1{\@bsphack\begingroup
  \protected@edef\@currentlabel{\protect\M@TitleReference
      {\@currentlabel}{\M@currentTitle}}%
  \@mem@old@label{#1}%
  \endgroup \@esphack}%

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@mem@@gettitle}
% \cs{@mem@@gettitle}\marg{title} grabs a title text.
%    \begin{macrocode}
\def\@mem@@gettitle#1{\begingroup \let\protect\@unexpandable@protect
    \let\label\@mem@nestwarn 
    \let\index\@gobble \let\glossary\@gobble
    \let\markboth\@gobbletwo \let\@mkboth\@gobbletwo 
    \let\markright\@gobble
    \edef\@tempa{\noexpand\def\noexpand\M@currentTitle{#1}}%
  \expandafter\endgroup\@tempa}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@mem@nestwarn}
% \begin{macro}{\M@TitleReference}
%    \begin{macrocode}
\let\@mem@nestwarn\@gobble
\let\M@TitleReference\@firstoftwo

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\titleref}
% \begin{macro}{\currenttitle}
% \begin{macro}{\@mem@titleref}
% \begin{macro}{\@mem@titlerefnolink}
%   \cs{titleref}\marg{key} prints the title corresponding to
%   \verb?\label{key}?.  \cs{currenttitle} prints the latest title.
% \cs{titleref} extended to support a starred version that will not
% provide hyperlinks when using  \Lpack{hyperref}. The
% \Lpack{hyperref} definition of \cs{@mem@titlerefnolink} is found
% in \Lpack{memhfixc}.
% \changes{v1.6180339c}{2009/01/18}{Extended \cs{titleref}, suggestion
% on ctt by martin@helios.de}
%    \begin{macrocode}
\newcommand*\@mem@titleref[1]{\begingroup 
  \let\numberline\@gobble
  \let\M@TitleReference\@mem@theTR % interrupt recursion of \ref
  \ref{#1}\endgroup}
\let\@mem@titlerefnolink\@mem@titleref

\DeclareRobustCommand\titleref{\@ifstar{\@mem@titlerefnolink}{\@mem@titleref}}

\DeclareRobustCommand{\currenttitle}{\begingroup
  \let\numberline\@gobble
  \theTitleReference\@currentlabel\M@currentTitle\endgroup}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{verbatim}
% % \DeclareRobustCommand\@mem@nestwarn[1]{\@memwarn%
% %  {Label \string"#1\string" was put in a title,\MessageBreak
% %   so the \noexpand\titleref is incorrect}}
% \end{verbatim}
%
% \begin{macro}{\M@currentTitle}
%    \begin{macrocode}
\let\M@currentTitle\@empty

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@mem@theTR}
% proper definition:
%    \begin{macrocode}
\def\@mem@theTR{\let\M@TitleReference\@firstoftwo \theTitleReference}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\namerefon}
% \begin{macro}{\namerefoff}
% Named references has turned some arguments (e.g., \verb?\legend{text}?) into
%  moving ones (Sven.Hartrumpf@FernUni-Hagen.de reported a problem but 
%  not a cause, March 2003). Not everyone needs named references.
%    \begin{macrocode}
\newcommand*{\namerefon}{\let\M@gettitle\@mem@@gettitle}
\newcommand*{\namerefoff}{\let\M@gettitle\@gobble}
  \namerefon
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \section{Table of Contents, etc.}
%
%     A \cs{section} command writes a
%     \verb?\contentsline{section}?\marg{title}\marg{page} command
%     on the \file{.toc} file, where \meta{title} contains the
%     contents of the entry and \meta{page} is the page number. If
%     sections are being numbered, then \meta{title} will be of the
%     form \cs{numberline}\marg{num}\marg{heading} where
%     \meta{num} is the number produced by \cs{thesection}.  Other
%     sectioning commands work similarly.
%
%     A \cs{caption} command in a `figure' environment writes \\
% \verb?\contentsline{figure}{?\cs{numberline}\marg{num}\marg{caption}\verb?}?\marg{page} \\
%     on the \file{.lof} file, where \meta{num} is the number produced
%     by \cs{thefigure} and \meta{caption} is the figure caption.  It
%     works similarly for a `table' environment.
%
%    The command \cs{contentsline}\marg{name} expands to
%    \cs{l@}\meta{name}.  So, to specify the table of contents, we must
%    define \cs{l@chapter}, \cs{l@section}, \cs{l@subsection}, \ldots ; to
%    specify the list of figures, we must define \cs{l@figure}; and so
%    on.  Most of these can be defined with the \cs{@dottedtocline}
%    command, which works as follows. \\
% \cs{@dottedtocline}\marg{level}\marg{indent}\marg{numwidth}\marg{title}\marg{page}
%
%    \begin{description}
%    \item[\meta{level}] An entry is produced only if\meta{level}
%        $<=$ value of the \Lcount{tocdepth} counter.  Note,
%        \cs{chapter} is level 0, \cs{section} is level 1, etc.
%    \item[\meta{indent}] The indentation from the outer left margin
%        of the start of the contents line.
%    \item[\meta{numwidth}] The width of a box in which the section
%        number is to go, if \meta{title} includes a \cs{numberline}
%        command.
%    \end{description}
%
% \begin{macro}{\@pnumwidth}
% \begin{macro}{\@tocrmarg}
% \begin{macro}{\@dotsep}
%    This command uses the following three parameters, which are set
%    with a \cs{newcommand} (so em's can be used to make them depend upon
%    the font).
%    \begin{description}
%    \item[\texttt{\bslash @pnumwidth}] The width of a box in which the
%        page number is put.
%    \item[\texttt{\bslash @tocrmarg}] The right margin for multiple
%        line entries.  One wants \cs{@tocrmarg} $\ge$ \cs{@pnumwidth}
%    \item[\texttt{\bslash @dotsep}] Separation between dots, in mu
%        units. Should be defined as a number like 2 or 1.7
%    \end{description}
%
%    \begin{macrocode}
\newcommand{\@pnumwidth}{1.55em}
\newcommand{\@tocrmarg} {2.55em}
\newcommand{\@dotsep}{4.5}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\tocentryskip}
% \begin{macro}{\tocbaseline}
% \begin{macro}{\tocskip}
%    We define two lengths and a utility command.
%    \begin{macrocode}
\newlength{\tocentryskip} \setlength{\tocentryskip}{1em}
\newlength{\tocbaseline} \setlength{\tocbaseline}{20pt}
\newcommand{\tocskip}[1]{%
    \addtocontents{toc}{\protect\vspace{#1}}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsection{New List of \ldots}
%
% It is apparent that users want to do at least two things that are not
% readily provided by the standard classes: (a) change the appearance
% of the Table of Contents, etc., headings, and (b) create new List of\ldots.
% This class provides a means of creating new Lists whose headings are
% parameterized, thereby killing two birds with one stone.
%
% In the standard classes the tables of contents, figures etc. are always 
% set in single-column style. In this class you can choose one- or two-column
% ToCs, etc.
% The titles are added to the ToC, unless the starred versions of the 
% commands are used.
% \changes{v1.6180339f}{2009/03/16}{Enabled two-column ToC, etc}
%
% \begin{macro}{\ensureonecol}
% \begin{macro}{\restorefromonecol}
%  These two
% macros cooperate to switch from two-columns to one column, and back again.
% \changes{v1.0a}{2002/01/24}{Deleted \cs{ensuretwocol} and 
%   \cs{restorefromtwocol} as they were unused. BUT later reinstated them.}
% \begin{macro}{\onecoltocetc}
% \begin{macro}{\twocoltocetc}
% \begin{macro}{\doccoltocetc}
% These macros define \cs{ensureonecol} and \cs{restorefromonecol} such that
% \begin{itemize}
% \item \cs{onecoltocetc} ToCs, etc., will be set in one column (the default)
% \item \cs{twocoltocetc} ToCs, etc., will be set in two columns
% \item \cs{doccoltocetc} ToCs, etc., will be set in column(s) corresponding
%        to the document's (onecolumn/twocolumn) option.
% \end{itemize}
% \changes{v1.6180339f}{2009/03/16}{Added \cs{onecoltocetc}, \cs{twocoltocetc}
%                                   and \cs{doccoltocetc}}
%    \begin{macrocode}
\newcommand*{\onecoltocetc}{%
  \def\ensureonecol{%
    \if@twocolumn
      \@restonecoltrue\onecolumn
    \else
      \@restonecolfalse
    \fi}%
  \def\restorefromonecol{\if@restonecol\twocolumn\fi}}
\newcommand*{\twocoltocetc}{%
  \def\ensureonecol{%
    \if@twocolumn
      \@restonecoltrue
    \else
      \@restonecolfalse\twocolumn
    \fi}%
  \def\restorefromonecol{\if@restonecol\else\onecolumn\fi}}
\newcommand*{\doccoltocetc}{%
  \let\ensureonecol\relax
  \let\restorefromonecol\relax}
%    \end{macrocode}
% Set the default
%    \begin{macrocode}
\onecoltocetc

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% 
% \begin{macro}{\cftparskip}
% The \cs{parskip} local to the ToC, etc, is set to the length \cs{cftparskip}.
%    \begin{macrocode}
\newlength{\cftparskip}
\setlength{\cftparskip}{0pt}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\newlistof}
% \cs{newlistof}\marg{listofcmmd}\marg{ext}\marg{listofname}
% creates the command \cs{listofcmmd} to typeset a new List of, where the
% external file has the extension \file{.ext} and the heading title is
% \meta{listofname}. The code for this is a heavily modified part
% of the \Lpack{tocloft} package.
%
%    \begin{macrocode}
\newcommand{\newlistof}[3]{%
%    \end{macrocode}
%
% In the following, \texttt{X} stands for the value of \meta{listofcmmd} and
% \texttt{Z} stands for the value of \meta{ext}.
%
% \begin{macro}{\ext@Z}
% \begin{macro}{\Zdepth}
% The file extension and listing depth, which is set to level~1.
%    \begin{macrocode}
  \@namedef{ext@#2}{#2}
  \@ifundefined{c@#2depth}{\newcounter{#2depth}}{}
  \setcounter{#2depth}{1}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\Zmark}
% The heading marks for the listing.
% \changes{v1.1}{2002/03/10}{Changed \cs{@mkboth} to \cs{markboth} in \cs{Zmark}}
%    \begin{macrocode}
  \@namedef{#2mark}{\markboth{#3}{#3}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\X}
% Typeset the listing title and entries, 
% with both a normal and starred version.
% \changes{v1.61803398}{2009/08/08}{changed such that it only use one
% internal macro}
% \changes{v1.61803398}{2009/08/09}{chose a better name for the
% internal macro}
%    \begin{macrocode}
   \@namedef{#1}{\@ifstar{\@nameuse{mem@#1}{01}}{\@nameuse{mem@#1}{00}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@X}
% \begin{macro}{\cftZbeforelisthook}
% \begin{macro}{\cftZafterlisthook}
% \changes{v1.61803398}{2009/08/08}{introduced \cs{mem@X} to replace
% \cs{@starZ} and \cs{@plainZ}}
%   In earlier version of the class, we used two macros \cs{@starZ}
%   and \cs{@plainZ}, to reduce code we now only use one, the argument
%   of it takes care of differentiating between the stuff that are
%   different. Two hooks is added just before and after importing the
%   list file contents.
% \changes{v1.61803398d}{2010/02/14}{added the before and after hooks}
%    \begin{macrocode}
  \@namedef{cft#2beforelisthook}{}%
  \@namedef{cft#2afterlisthook}{}%
  \@namedef{mem@#1}##1{%
    \ensureonecol
    \par
    \begingroup
      \@nameuse{@#2maketitle}
      \if##1
        \ifmem@em@starred@listof\else
          \phantomsection
          \addcontentsline{toc}{chapter}{#3}
        \fi
      \fi
      \parskip\cftparskip
      \@nameuse{cft#2beforelisthook}%
      \@starttoc{#2}%
      \@nameuse{cft#2afterlisthook}%
    \endgroup
    \restorefromonecol}
%    \end{macrocode}
%   
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@Zmaketitle}
% This macro typesets the title.
% \changes{v1.3}{2002/10/10}{Added \cs{printZnonum} to \cs{@Zmaketitle}}
% \changes{v1.61803}{2008/01/30}{Slight changes to \cs{@Zmaketitle}
%         (mempatch v4.6)}
% \changes{v3.6j}{2011/03/01}{Made sure \cs{parskip} is zero in the
% title, otherwise a non-zero \cs{parskip} might cause it to be placed
% incorrectly}
%    \begin{macrocode}
  \@namedef{@#2maketitle}{%
    \@nameuse{#2headstart}
   {\parindent\z@ 
    \parskip\z@
%%%%  \parskip\cftparskip
    \interlinepenalty\@M
%    \end{macrocode}
% \changes{v1.3}{2002/11/14}{Added printZnonum to \cs{newlistof}}
%    \begin{macrocode}
    \@nameuse{print#2nonum}%
    \@nameuse{print#2title}{#3}%
    \@nameuse{#2mark}%
    \thispagestyle{chapter}%
    \@nameuse{after#2title}
   }
    \@afterheading}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\Zheadstart}
% \begin{macro}{\afterZtitle}
% The macros \cs{Zheadstart} and \cs{afterZtitle}
% control what goes before and after the title. They
% default to the corresponding macros for chapters.
%    \begin{macrocode}
  \@namedef{#2headstart}{\chapterheadstart}
  \@namedef{after#2title}{\afterchaptertitle}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\printZnonum}
% This typesets something before the title and defaults
% to \cs{printchapternonum}.
% \changes{v1.3}{2002/10/10}{Added \cs{printZnonum} macro}
%    \begin{macrocode}
  \@namedef{print#2nonum}{\printchapternonum}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\printZtitle}
% The title is typeset by the macro \cs{printZtitle}\marg{title}
% which defaults to \cs{printchaptertitle}.
%    \begin{macrocode}
  \@namedef{print#2title}##1{\printchaptertitle{##1}}
%    \end{macrocode}
% \end{macro}
%
% This is the end of the definition of \cs{newlistof}.
%    \begin{macrocode}
} % end \newlistof

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifmem@em@starred@listof}
% \begin{macro}{\KeepFromToc}
%   The class handles the created `new lists' a little different than
%   other classes. We automatically add it to the main table of
%   contents. This us usually what one wants. If not, one can always
%   use the starred version. But in some cases other packages will use
%   \cs{tableofcontents} to typeset their own `list of\dots', in which
%   case it becomes a little hard to add a star. Therefore we add a
%   switch that can be used to emulate the starred list of. After the
%   macro \cs{KeepFromToc} the memoir created (non-starred) `list of'
%   will behave as their starred counterpart.
% \changes{v1.61803398}{2009/08/08}{LM: added \cs{KeepFromToc}}
%    \begin{macrocode}
\newif\ifmem@em@starred@listof
\newcommand\KeepFromToc{\mem@em@starred@listoftrue}
%    \end{macrocode}
% Tip: use \cs{KeepFromToc} as an environment, i.e.
% \begin{verbatim}
% \begin{KeepFromToc}
%  \listoffigures 
% \end{KeepFromToc}
% \end{verbatim}
% to locally remove a list from the TOC.
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@starttoc}
% A list of macro calls \cs{@starttoc} to read the appropriate file. I have
% changed the kernel definition to allow a file to be read multiple times
% by delaying killing the file until the end of the document.
% \changes{v1.3}{2002/11/14}{Changed \cs{@starttoc}}
% \changes{v1.61803398d}{2009/11/23}{Removed infelicity in \cs{@starttoc}}
%    \begin{macrocode}
\renewcommand{\@starttoc}[1]{%
  \begingroup\makeatletter
    \@input{\jobname.#1}%
    \if@filesw
      \AtEndDocument{%
%    \end{macrocode}
% If a ToC, or other ListOf, is called more than once then we have to stop
% opening yet another, redundant, output file. The check against \cs{relax}
% seems to meet the requirement.
%    \begin{macrocode}
        \expandafter\ifx\csname tf@#1\endcsname\relax
          \expandafter\newwrite\csname tf@#1\endcsname
          \immediate\openout \csname tf@#1\endcsname \jobname.#1\relax
        \fi
      }%
    \fi
  \@nobreakfalse
  \endgroup}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Table of Contents}
%
% \begin{macro}{\tableofcontents}
% \begin{macro}{\tableofcontents*}
%    These macros request that \LaTeX{} produces a table of
%    contents. The ToC heading is added to the ToC unless the starred
% version is used.
%
%    \begin{macrocode}
\newlistof{tableofcontents}{toc}{\contentsname}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%    The List of Figures and List of Tables are defined later.
%
%
%
% \subsection{List entries}
%
%    Each command in the body of the text that makes an entry in the ToC,
% or LoF or LoT needs an addtional macro to format the entry, as described
% above. Users often want to change the formatting of the entries but
% it is not immediately obvious how to do that.
%
%    I have borrowed and modified more of the code from the \Lpack{tocloft}
% package to enable easy creation and modification the formatting of the
% entries.
%
%
% \begin{macro}{\setpnumwidth}
% \begin{macro}{\setrmarg}
%  User commands for setting \cs{@pnumwidth} and \cs{@tocrmarg}.
%    \begin{macrocode}
\newcommand*{\setpnumwidth}[1]{\renewcommand{\@pnumwidth}{#1}}
\newcommand*{\setrmarg}[1]{\renewcommand{\@tocrmarg}{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\cftdot}
% \begin{macro}{\cftdotfill}
% In the default ToC, a dotted line can be used to provide a leader between
% a title and the page number. The definition of this leader is buried
% in the \cs{@dottedtocline} command. The \cs{cftdotfill}\marg{sep}
% command provides a parameterised version of the leader code, where
% \meta{sep} is the separation between the dots in mu units.
% The symbol used for the `dots' in the leader is given by the value
% of \cs{cftdot}. 
%    \begin{macrocode}
\providecommand{\cftdot}{.}
\providecommand{\cftdotfill}[1]{%
  \leaders\hbox{$\m@th\mkern #1 mu\hbox{\cftdot}\mkern #1 mu$}\hfill}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\cftdotsep}
% \begin{macro}{\cftnodots}
% \cs{cftdotsep} holds the default dot separation. 
% If the kerns in \cs{cftdotfill} are large enough, then no dots will
% be printed. \cs{cftnodots} should be `large enough'.
% \changes{v1.2}{2002/07/07}{Changed \cs{cftnodots} from 10,000 to 2,000 for 
%                17pt option and pdflatex}
%    \begin{macrocode}
\providecommand{\cftdotsep}{4.5}
\newcommand{\cftnodots}{2000}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%     Now for the trickier bits regarding the typesetting of the ToC
% entries.
%
%     A \file{.toc} (also \file{.lof} and \file{.lot}) file consists
% of a list of \\
% \cs{contentsline}\marg{kind}\marg{title}\marg{page} \\
% commands, where \meta{kind} is the kind of heading (e.g., \texttt{part} or
% \texttt{section} or \texttt{figure}), \meta{title} is the title text 
% (including the number),
% and \meta{page} is the page number. The entries are inserted into the
% file by calling the \\
% \cs{addcontentsline}\marg{file}\marg{kind}\marg{title} \\
% command, where \meta{file} is the file extension (e.g., \texttt{toc}, \texttt{lot})
% and the other arguments are the same as for the \cs{contentsline}
% command. (Arbitrary stuff may also be put into the file via the
% \cs{addtocontents}\marg{file}\marg{text} command).
% The typesetting of the \cs{contentsline} entries is performed by 
% commands of the form \cs{l@kind}. The sectioning and captioning commands
% call \cs{addcontentsline} to insert their titles into the \file{.toc}
% etc., files.
%
%     For the purposes at hand it is generally impossible to treat 
% the typesetting
% of a title and its number separately, as both are bundled into the
% \meta{title} argument within \cs{contentsline}. They could be handled
% separately if the \cs{contentsline} command was suitably modified. If
% this was done, then the \cs{addtocontentsline} command would also need
% to be changed which would then require the sectioning and captioning
% commands to be modified as well. This is certainly possible, but would
% cause problems if any other package also modified the sectioning or
% captioning commands, and there are several packages which do this.
%
%  I provide modified versions of the \cs{l@kind} commands. 
% Essentially, my new definitions
% consist of inlined versions of the code for \cs{@dottedtocline}.
%
%
% \begin{macro}{\cftparfillskip}
% The \cs{l@kind} commands modify (locally) the value of \cs{parfillskip}.
% \cs{cftparfillskip} is a copy of the default \theTeXbook{}
% \cs{parfillskip} definition.
%    \begin{macrocode}
\newcommand*{\cftparfillskip}{\parfillskip=0pt plus1fil}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@cftn@me}
% Lars Madsen suggested that macros like \cs{cftfigurename} be added
% to entries in the LoF, and so on.
% \changes{v1.61803}{2008/01/30}{Added \cs{@cftn@me} (Lars Madsen mempatch v4.5)}
%    \begin{macrocode}
\newcommand*{\@cftn@me}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@cft@hb@xt@}
% \begin{macro}{\numberlinebox}
% \begin{macro}{\partnumberlinebox}
% \begin{macro}{\chapternumberlinebox}
% \begin{macro}{\booknumberlinebox}
% \changes{v3.6k}{2012/07/22}{Added four \cs{Xnumberlinebox} macros}
% Each of the four \cs{Xnumberline} macros (part, chapter, book and
% regular) typeset their contents inside a box of a certain width. In
% order to make this a little more flexible we provide a default box
% macro. Note that the box left aligned by default. The default
% \cs{Xnumberlinebox} macros are then let equal to this default.
%    \begin{macrocode}
\newcommand\mem@cft@hb@xt@[2]{\hb@xt@#1{#2\hfil}}
\let\numberlinebox\mem@cft@hb@xt@
\let\partnumberlinebox\mem@cft@hb@xt@
\let\chapternumberlinebox\mem@cft@hb@xt@
\let\booknumberlinebox\mem@cft@hb@xt@

%    \end{macrocode}
% 
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\numberline}
% \begin{macro}{\numberlinehook}
% The purpose of the \cs{numberline}\marg{secnum} command is to typeset
% \meta{secnum} left justified in a box of width \cs{@tempdima}. I redefine
% it to add three additional parameters, namely \cs{@cftbsnum}, 
% \cs{@cftasnum} and \cs{@cftasnumb} 
% (see \file{ltsect.dtx} for the original
% definition). 
% \changes{v1.61803398d}{2010/02/13}{added \cs{numberlinehook}}
% We also add a hook, that initially does nothing, but
% might be redefined to record say withs of \meta{secnum}s. In order
% to tell the owner of the \cs{numberline}'s apart, check the value of
% \cs{cftwhatismyname}. 
% \changes{v3.6k}{2012/07/22}{Factored out the box part into a
% separate macro}
%    \begin{macrocode}
\newcommand*\numberlinehook[1]{}
\renewcommand*{\numberline}[1]{%
  \numberlinehook{#1}%
  %\hb@xt@\@tempdima{\@cftn@me\@cftbsnum #1\@cftasnum\hfil}\@cftasnumb}
  \numberlinebox\@tempdima{\@cftn@me\@cftbsnum #1\@cftasnum}\@cftasnumb}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@cftbsnum}
% \begin{macro}{\@cftasnum}
% \begin{macro}{\@cftasnumb}
%    \begin{macrocode}
\newcommand{\@cftbsnum}{}
\newcommand{\@cftasnum}{}
\newcommand{\@cftasnumb}{}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% 
%
% \begin{macro}{\newlistentry}
% \cs{newlistentry}\oarg{within}\marg{counter}\marg{ext}\marg{level-1}
% creates a set of commands for typesetting a new kind of entry in a List of.
% \meta{counter} is the name of the counter for the entry and must be 
% the same as the name
% of the entry (e.g., \texttt{subsection}). The optional \meta{within} is the
% name of a counter within which \texttt{counter} is defined. The file extension
% for the List of is \meta{ext} and \meta{level-1} is one less than the 
% level of the entry in the List of.
% \changes{v1.61803}{2008/01/30}{Added \cs{cftXname} to \cs{newlistentry}
%                (mempatch v4.5)}
% \changes{v1.61803398}{2009/07/17}{Added bidi support to \cs{newlistentry}}
%    \begin{macrocode}
\newcommand{\newlistentry}[4][\@empty]{%
%    \end{macrocode}
%
%    In the following, \texttt{X} is used as the value of \meta{counter} and
% \texttt{Z} as the value of \meta{ext}.
%
% \begin{macro}{\c@X}
% \begin{macro}{\theX}
% Check if \meta{within} and \meta{counter} have been defined. It is
% an error if \meta{within} has not been defined. \meta{counter}
% will be created if it has not been previously defined.
% Set the default counter values.
%    \begin{macrocode}
  \@ifundefined{c@#2}{%    check & set the counter
    \ifx \@empty#1\relax
      \newcounter{#2}
    \else
      \newcounter{#2}[#1]%
      \expandafter\edef\csname the#2\endcsname{%
  \expandafter\noexpand\csname the#1\endcsname.\noexpand\arabic{#2}}
    \fi}{}
  \setcounter{#2}{0}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% That finishes off the error checking. No matter what the result, the
% rest of the new commands are defined.
%
% \begin{macro}{\l@X}
% \cs{l@X}\marg{title}\marg{page} typesets the entry.
%    \begin{macrocode}
  \@namedef{l@#2}##1##2{%
%    \end{macrocode}
% Only typeset if the \cs{Zdepth} is greater than \meta{level-1}.
%    \begin{macrocode}
    \ifnum \@nameuse{c@#3depth} > #4\relax
%    \end{macrocode}
% Add some vertical space.
%    \begin{macrocode}
      \vskip \@nameuse{cftbefore#2skip}
%    \end{macrocode}
% Start a group to keep paragraphing changes local. Set the \cs{leftskip}
% to the entry's indentation.
% \begin{macro}{\cftwhatismyname}
% \changes{v1.61803398d}{2010/02/13}{added \cs{cftwhatismyname}}
% \cs{cftwhatismyname} locally stores the type of toc entry. Useful
% for hooks into general macros like \verb?\numberline?.
%    \begin{macrocode}
      {%\leftskip \@nameuse{cft#2indent}\relax
       \newcommand*\cftwhatismyname{#2}% 
       \memRTLleftskip \@nameuse{cft#2indent}\relax
%    \end{macrocode}
% \end{macro}
% Set the \cs{rightskip} to \cs{@tocrmarg} to leave room for the page number.
%    \begin{macrocode}
%%%       \rightskip \@tocrmarg
       \memRTLrightskip \@tocrmarg
%    \end{macrocode}
% Ensure that the last line of an entry will be filled. Setting \cs{parfillskip}
% to a negative value prevents `overfull box' messages.
%    \begin{macrocode}
%%%       \parfillskip -\rightskip
       \parfillskip -\memRTLrightskip
%    \end{macrocode}
% Set the paragraph's indentation to the entry's indentation.
%    \begin{macrocode}
       \parindent \@nameuse{cft#2indent}\relax\@afterindenttrue
%    \end{macrocode}
% Try and prevent breaks between lines in a multiline entry.
%    \begin{macrocode}
       \interlinepenalty\@M
%    \end{macrocode}
% Make sure we have left vertical mode.
%    \begin{macrocode}
       \leavevmode
%    \end{macrocode}
% Our version of \cs{numberline} expects that the width of the number box
% is in \cs{@tempdima}, and that the three macros \cs{@cftbsnum}, 
% \cs{@cftaqsnum}, and \cs{@cftasnumb} are defined. We set all these to 
% the values for this entry.
% \changes{v3.6k}{2012/07/30}{Added brace pair around 
% \cs{nameuse\{cft#2name\}}, then
% \cs{cftXfont} can end with say \cs{MakeUppercase}}
%    \begin{macrocode}
       \settowidth{\@tempdima}{\@nameuse{cft#2font}{\@nameuse{cft#2name}}}%
       \addtolength{\@tempdima}{\@nameuse{cft#2numwidth}}%
 \expandafter\let\expandafter\@cftbsnum\csname cft#2presnum\endcsname
 \expandafter\let\expandafter\@cftasnum\csname cft#2aftersnum\endcsname
 \expandafter\let\expandafter\@cftasnumb\csname cft#2aftersnumb\endcsname
 \expandafter\let\expandafter\@cftn@me\csname cft#2name\endcsname
%    \end{macrocode}
% Arrange that the (entry number and) first line of the title is set at
% the current indent, and that any subsequent lines will be further
% indented.
%    \begin{macrocode}
%%%       \advance\leftskip\@tempdima \null\nobreak\hskip -\leftskip
       \advance\memRTLleftskip\@tempdima \null\nobreak\hskip -\memRTLleftskip
%    \end{macrocode}
% Print the (number and) title, prohibiting any breaking.
% \changes{v3.6k}{2012/07/29}{Added brace pair around \#\#1, then
% \cs{cftXfont} can end with say \cs{MakeUppercase}}
%    \begin{macrocode}
       {\@nameuse{cft#2font}{##1}}\nobreak
%    \end{macrocode}
% Print the leader and the page number, and then close the group.
%    \begin{macrocode}
       \@nameuse{cft#2fillnum}{##2}}
    \fi
  }% end of \l@#2

%    \end{macrocode}
% \end{macro}
%
% Now define all the layout commands used by \cs{l@X}. The default
% values of these print the entry in a normal font with a dotted
% line between the title and the page number.
% \begin{macro}{\cftbeforeXskip}
% The skip before the title.
%    \begin{macrocode}
  \expandafter\newlength\csname cftbefore#2skip\endcsname
    \setlength{\@nameuse{cftbefore#2skip}}{\z@ \@plus .2\p@}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\cftXindent}
% \begin{macro}{\cftXnumwidth}
% The indent and width for the number.
%    \begin{macrocode}
  \expandafter\newlength\csname cft#2indent\endcsname
  \expandafter\newlength\csname cft#2numwidth\endcsname
%    \end{macrocode}
% Set the default values for the indent and numwidth depending on
% the entry's level. A level of 1 corresponds to a figure entry
% (no indent, and space for a number like N.N).
%    \begin{macrocode}
  \ifcase #4\relax  % 0   (level 1)
    \setlength{\@nameuse{cft#2indent}}{0em}
    \setlength{\@nameuse{cft#2numwidth}}{2.3em}
  \or               % 1   (level 2)
    \setlength{\@nameuse{cft#2indent}}{2.3em}
    \setlength{\@nameuse{cft#2numwidth}}{3.2em}
  \or               % 2   (level 3)
    \setlength{\@nameuse{cft#2indent}}{5.5em}
    \setlength{\@nameuse{cft#2numwidth}}{4.1em}
  \or               % 3   (level 4)
    \setlength{\@nameuse{cft#2indent}}{8.5em}
    \setlength{\@nameuse{cft#2numwidth}}{5.0em}
  \else             % anything else
    \setlength{\@nameuse{cft#2indent}}{10.5em}
    \setlength{\@nameuse{cft#2numwidth}}{6.0em}
  \fi
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \begin{macro}{\cftXfont}
% \begin{macro}{\cftXname}
% \begin{macro}{\cftXpresnum}
% \begin{macro}{\cftXaftersnum}
% \begin{macro}{\cftXaftersnumb}
% \begin{macro}{\cftXdotsep}
% \begin{macro}{\cftXleader}
% \begin{macro}{\cftXpagefont}
% \begin{macro}{\cftXafterpnum}
% And the remaining commands; the only ones that are not null are for the
% dotsep, the font and the leader
%    \begin{macrocode}
  \@namedef{cft#2font}{\normalfont}
  \@namedef{cft#2name}{}
  \@namedef{cft#2presnum}{}
  \@namedef{cft#2aftersnum}{}
  \@namedef{cft#2aftersnumb}{}
  \@namedef{cft#2dotsep}{\cftdotsep}
  \@namedef{cft#2leader}{\normalfont\cftdotfill{\@nameuse{cft#2dotsep}}}
  \@namedef{cft#2pagefont}{\normalfont}
  \@namedef{cft#2afterpnum}{}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\toclevel@X}
% The hyperref package needs a command \cs{toclevel@X}, holding
% the \meta{level-1} value.
%    \begin{macrocode}
  \@namedef{toclevel@#2}{#4}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cftXformatpnum}
% \begin{macro}{\cftXformatpnumhook}
% \begin{macro}{\cftXfillnum}
% Typeset the leader and page number. We add a hook into the formating
% of the page number. This might later be used to record the widths of
% the numbers used. It will be given the page number as its
% argument. Does nothing by default.
% \changes{v1.61803}{2008/01/30}{Added \cs{cftXformatpnum} (Dan Leucking
%                   mempatch v4.9)}
% \changes{v1.61803398d}{2010/02/13}{added hook into page number formatter}
%    \begin{macrocode}
  \@namedef{cft#2formatpnumhook}##1{}
  \@namedef{cft#2formatpnum}##1{%
    \@nameuse{cft#2formatpnumhook}{##1}%
    \hb@xt@\@pnumwidth{\hfil\@nameuse{cft#2pagefont}##1}}
  \@namedef{cft#2fillnum}##1{%
    {\@nameuse{cft#2leader}}\nobreak
%%%    \hb@xt@\@pnumwidth{%
%%%      \hfil\@nameuse{cft#2pagefont}##1}
       \@nameuse{cft#2formatpnum}{##1}%
       \@nameuse{cft#2afterpnum}\par}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% This ends the definition of \cs{newlistentry}.
%    \begin{macrocode}
} % end \newlistentry

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\cftsetindents}
% \cs{cftsetindents}\marg{entry}\marg{indent}\marg{numwidth} sets
% the \textit{indent} and \textit{numwidth} for entry \meta{entry}. 
%    \begin{macrocode}
\newcommand*{\cftsetindents}[3]{%
  \setlength{\@nameuse{cft#1indent}}{#2}
  \setlength{\@nameuse{cft#1numwidth}}{#3}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cftbookname}
% If you want a book entry in the ToC like: \\
% BOOK I Title ... \\
% then \verb?\renewcommand*{\cftbookname}{BOOK~}? \\
%    \begin{macrocode}
\newcommand*{\cftbookname}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cftbookbreak}
% \begin{macro}{\l@book}
% \begin{macro}{\booknumberline}
% \begin{macro}{\booknumberlinehook}
% Now for the ToC entry.
% \changes{v1.61803}{2008/01/30}{Added \cs{l@book} and supports (mempatch v4.4)}
% \changes{v1.6180339}{2008/07/23}{Deleted \cs{space} from \cs{booknumberline}
%                      and \cs{partnumberline}
%                      (per Lars Henrik Gam Madsen mempatch v5.1)}
% \changes{v1.61803398}{2009/07/18}{Added bidi support to \cs{l@book}}
% \changes{v1.61803398d}{2010/02/13}{added hook into the book numberline}
% \changes{v3.6k}{2012/07/22}{Factored the general box out of \cs{booknumberline}}
%    \begin{macrocode}
\newcommand*{\cftbookbreak}{\addpenalty{-\@highpenalty}%
  \addvspace{\cftbeforebookskip}}
\newcommand*{\l@book}[2]{%
  \ifnum\c@tocdepth >-3\relax
    \cftbookbreak
    \begingroup
      {%\leftskip \cftbookindent\relax
       \memRTLleftskip \cftbookindent\relax
%%%       \rightskip \@tocrmarg
       \memRTLrightskip \@tocrmarg
%%%       \parfillskip -\rightskip
       \parfillskip -\memRTLrightskip
       \parindent \cftbookindent\relax\@afterindenttrue
       \interlinepenalty\@M
       \leavevmode
       \settowidth{\@tempdima}{\cftbookfont\cftbookname}%
       \addtolength{\@tempdima}{\cftbooknumwidth}%
       \let\@cftbsnum \cftbookpresnum
       \let\@cftasnum \cftbookaftersnum
       \let\@cftasnumb \cftbookaftersnumb
%%%       \advance\leftskip \@tempdima \null\nobreak\hskip -\leftskip
       \advance\memRTLleftskip \@tempdima \null\nobreak\hskip -\memRTLleftskip
%    \end{macrocode}
% \changes{v3.6k}{2012/07/29}{Added brace pair around \#1, then
% \cs{cftbookfont} can end with say \cs{MakeUppercase}}
%    \begin{macrocode}
       {\cftbookfont {#1}}%
       \cftbookfillnum{#2}}
      \nobreak
      \global\@nobreaktrue
      \everypar{\global\@nobreakfalse\everypar{}}%
    \endgroup
  \fi}
\newcommand*\booknumberlinehook[1]{}
\newcommand{\booknumberline}[1]{%
  \booknumberlinehook{#1}%
  % \hb@xt@\@tempdima{%
  %   \cftbookname\@cftbsnum #1\@cftasnum\hfil}\@cftasnumb}%%\space}
  \booknumberlinebox\@tempdima{%
    \cftbookname\@cftbsnum #1\@cftasnum}\@cftasnumb}%%\space}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\cftbeforebookskip}
% \begin{macro}{\cftbookindent}
% \begin{macro}{\cftbooknumwidth}
% \begin{macro}{\cftbookfont}
% \begin{macro}{\cftbookpresnum}
% \begin{macro}{\cftbookaftersnum}
% \begin{macro}{\cftbookaftersnumb}
% \begin{macro}{\cftbookleader}
% \begin{macro}{\cftbookdotsep}
% \begin{macro}{\cftbookpagefont}
% \begin{macro}{\cftbookafterpnum}
% \begin{macro}{\cftbookfillnum}
% \begin{macro}{\cftbookformatpnum}
% \begin{macro}{\cftbookformatpnumhook}
% \changes{v1.61803398d}{2010/02/13}{added hook into \cs{cftbookformatpnum}}
%    \begin{macrocode}
\newlength{\cftbeforebookskip}
  \setlength{\cftbeforebookskip}{2.25em \@plus\p@}
\newdimen\cftbookindent
  \setlength{\cftbookindent}{0em}
\newdimen\cftbooknumwidth
  \setlength{\cftbooknumwidth}{1.5em}
\newcommand*{\cftbookfont}{\large\bfseries}
\newcommand*{\cftbookpresnum}{}
\newcommand*{\cftbookaftersnum}{}
\newcommand*{\cftbookaftersnumb}{}
\newcommand*{\cftbookleader}{%
  \large\bfseries\cftdotfill{\cftbookdotsep}}
\newcommand*{\cftbookdotsep}{\cftnodots}
\newcommand*{\cftbookpagefont}{\large\bfseries}
\newcommand{\cftbookafterpnum}{}
\newcommand{\cftbookfillnum}[1]{%
  {\cftbookleader}%
%%%%  {\hb@xt@\@pnumwidth{\hss {\cftbookpagefont #1}}}%
  \cftbookformatpnum{#1}%
  \cftbookafterpnum\par}
\newcommand{\cftbookformatpnumhook}[1]{}
\newcommand{\cftbookformatpnum}[1]{%
  \cftbookformatpnumhook{#1}%
  \hb@xt@\@pnumwidth{\hss {\cftbookpagefont #1}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%
% \begin{macro}{\cftpartname}
% If you want a part entry in the ToC like: \\
% PART I Title ... \\
% then \verb?\renewcommand*{\cftpartname}{PART~}? \\
% \changes{v1.618}{2005/09/03}{Added \cs{cftpartname}, courtesy Danie Els (mempatch v3.12)}
%    \begin{macrocode}
\newcommand*{\cftpartname}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cftpartbreak}
% \begin{macro}{\l@part}
% Can't use \cs{newlistentry} for \cs{l@part} because of the initial penalty
% and the final \cs{nobreak} code.
% \changes{v1.61803}{2008/01/30}{Added \cs{cftpartbreak}}
% \changes{v1.61803398}{2009/07/18}{Added bidi support to \cs{l@part}}
%    \begin{macrocode}
\newcommand*{\cftpartbreak}{\addpenalty{-\@highpenalty}%
  \addvspace{\cftbeforepartskip}}
\newcommand*{\l@part}[2]{%
  \ifnum \c@tocdepth >-2\relax
    \cftpartbreak
    \begingroup
      {%\leftskip \cftpartindent\relax
       \memRTLleftskip \cftpartindent\relax
%%%       \rightskip \@tocrmarg
       \memRTLrightskip \@tocrmarg
%%%       \parfillskip -\rightskip
       \parfillskip -\memRTLrightskip
       \parindent \cftpartindent\relax\@afterindenttrue
       \interlinepenalty\@M
       \leavevmode    
       \settowidth{\@tempdima}{\cftpartfont\cftpartname}%
       \addtolength{\@tempdima}{\cftpartnumwidth}%
       \let\@cftbsnum \cftpartpresnum
       \let\@cftasnum \cftpartaftersnum
       \let\@cftasnumb \cftpartaftersnumb
%%%       \advance\leftskip \@tempdima \null\nobreak\hskip -\leftskip
       \advance\memRTLleftskip \@tempdima \null\nobreak\hskip -\memRTLleftskip
%    \end{macrocode}
% \changes{v3.6k}{2012/07/29}{Added brace pair around \#1, then
% \cs{cftpartkfont} can end with say \cs{MakeUppercase}}
%    \begin{macrocode}
       {\cftpartfont {#1}}%
       \cftpartfillnum{#2}}
      \nobreak
        \global\@nobreaktrue
        \everypar{\global\@nobreakfalse\everypar{}}%
    \endgroup
  \fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\toclevel@part}
% Needed if the \Lpack{hyperref} package is used.
% \changes{v1.61803}{2008/01/30}{Added \cs{toclevel@part} (mempatch v4.9)}
%    \begin{macrocode}
\newcommand*{\toclevel@part}{-1}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\partnumberline}
% \begin{macro}{\partnumberlinehook}
% \cs{partnumberline} is a special version of \cs{numberline} output by \cs{part}.
% Its default definition is identical to \cs{numberline}.
% \changes{v1.3}{2002/11/14}{Added \cs{partnumberline}}
% \changes{v1.61803}{2008/01/30}{Added a space after the number in 
%         \cs{partnumberline} (mempatch v4.4)}
% \changes{v1.61803398d}{2010/02/13}{added hook into part numberline}
% \changes{v3.6k}{2012/07/22}{Factored out the box command}
%    \begin{macrocode}
\newcommand*\partnumberlinehook[1]{}
\newcommand{\partnumberline}[1]{%
  \partnumberlinehook{#1}%
  % \hb@xt@\@tempdima{%
  %   \cftpartname\@cftbsnum #1\@cftasnum\hfil}\@cftasnumb}%%\space}
  \partnumberlinebox\@tempdima{%
    \cftpartname\@cftbsnum #1\@cftasnum}\@cftasnumb}%%\space}


%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\cftbeforepartskip}
% \begin{macro}{\cftpartnumwidth}
% \begin{macro}{\cftpartfont}
% \begin{macro}{\cftpartpresnum}
% \begin{macro}{\cftpartaftersnum}
% \begin{macro}{\cftpartaftersnumb}
% \begin{macro}{\cftpartleader}
% \begin{macro}{\cftpartdotsep}
% \begin{macro}{\cftpartpagefont}
% \begin{macro}{\cftpartafterpnum}
% \begin{macro}{\cftpartindent}
% \begin{macro}{\cftpartformatpnum}
% \begin{macro}{\cftpartformatpnumhook}
% \begin{macro}{\cftpartfillnum}
%  These are the user commands to control the typesetting of Part entries.
%  They are initialised to give the standard appearance.
% \changes{v1.3}{2002/10/10}{Changed \cs{cftpartnumwidth} to cater for
%                            use of \cs{numberline} in the ToC}
% \changes{v1.61803}{2008/01/30}{Added \cs{cftpartformatpnum} (mempatch v4.9)}
% \changes{v1.61803398d}{2010/02/13}{added hook into \cs{cftpartformatpnum}}
%    \begin{macrocode}
  \newlength{\cftbeforepartskip}
    \setlength{\cftbeforepartskip}{2.25em \@plus\p@}
  \newlength{\cftpartindent}
    \setlength{\cftpartindent}{0em}
  \newlength{\cftpartnumwidth}
    \setlength{\cftpartnumwidth}{1.5em}
  \newcommand{\cftpartfont}{\large\bfseries}
  \newcommand{\cftpartpresnum}{}
  \newcommand{\cftpartaftersnum}{}
  \newcommand{\cftpartaftersnumb}{}
  \newcommand{\cftpartleader}{%
              \large\bfseries\cftdotfill{\cftpartdotsep}}
  \newcommand{\cftpartdotsep}{\cftnodots}
  \newcommand{\cftpartpagefont}{\large\bfseries}
  \newcommand{\cftpartafterpnum}{}
  \newcommand{\cftpartformatpnumhook}[1]{}
  \newcommand*{\cftpartformatpnum}[1]{%
    \cftpartformatpnumhook{#1}%
    \hb@xt@\@pnumwidth{\hss {\cftpartpagefont #1}}}
  \newcommand{\cftpartfillnum}[1]{%
    {\cftpartleader}%
    {\cftpartformatpnum{#1}}%
     \cftpartafterpnum\par}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\cftchaptername}
% If you want a chapter entry in the ToC like: \\
% Chapter 1. A title ... \\
% then \verb?\renewcommand*{\cftchaptername}{\chaptername~}? \\
% \verb?\renewcommand*{\cftchapteraftersnum}{.}? \\
% 
% \changes{v1.618}{2005/09/03}{Added \cs{cftchaptername}, courtesy Danie Els (mempatch v3.12)}
%    \begin{macrocode}
\newcommand*{\cftchaptername}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\l@chapapp}
% Generic chapter/appendix ToC entry typesetting.
% \changes{v1.618}{2005/09/03}{Added \cs{l@chapapp}, courtesy Danie Els (mempatch v3.12)}
% \changes{v1.61803398}{2009/07/18}{ADded bidi support to \cs{l@chapapp}}
%    \begin{macrocode}
\newcommand*{\l@chapapp}[3]{%
  \ifnum \c@tocdepth >\m@ne
    \cftchapterbreak
    \vskip \cftbeforechapterskip
    {%\leftskip \cftchapterindent\relax
     \memRTLleftskip \cftchapterindent\relax
%%%     \rightskip \@tocrmarg
     \memRTLrightskip \@tocrmarg
%%%     \parfillskip -\rightskip
     \parfillskip -\memRTLrightskip
     \parindent \cftchapterindent\relax
     \@afterindenttrue
     \interlinepenalty\@M
     \leavevmode
     \let\@cftbsnum \cftchapterpresnum
     \let\@cftasnum \cftchapteraftersnum
     \let\@cftasnumb \cftchapteraftersnumb
     \def\@chapapp@head{#3}%
     \settowidth{\@tempdima}{\cftchapterfont\@chapapp@head}%
     \addtolength{\@tempdima}{\cftchapternumwidth}%
%%%     \advance\leftskip \@tempdima \null\nobreak\hskip -\leftskip
     \advance\memRTLleftskip \@tempdima \null\nobreak\hskip -\memRTLleftskip
%    \end{macrocode}
% \changes{v3.6k}{2012/07/29}{Added brace pair around \#1, then
% \cs{cftchapterfont} can end with say \cs{MakeUppercase}}
%    \begin{macrocode}
     {\cftchapterfont {#1}}\nobreak
     \cftchapterfillnum{#2}}
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\l@chapter}
%  \cs{l@chapter}\marg{title}\marg{page} typesets the ToC entry for
% a \texttt{chapter} heading. It is a parameterised copy of the default 
% \cs{l@chapter}
% (see \file{classes.dtx} for the original definition). Can't use
% \cs{newlistentry} for this because of the intial penalty.
% \changes{v1.3}{2002/11/14}{Added \cs{cftchapterbreak} to \cs{l@chapter}}
% \changes{v1.618}{2005/09/03}{Defined \cs{l@chapter} in terms of \cs{l@chapapp} (mempatch v3.12)}
%    \begin{macrocode}
\newcommand*{\l@chapter}[2]{%
  \l@chapapp{#1}{#2}{\cftchaptername}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\toclevel@chapter}
% Needed if the \Lpack{hyperref} package is used.
% \changes{v1.61803}{2008/01/30}{Added \cs{toclevel@chapter} (mempatch v4.9)}
%    \begin{macrocode}
\newcommand*{\toclevel@chapter}{0}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cftappendixname}
% If you want a appendixed chapter entry in the ToC like: \\
% Appendix A A title ... \\
% then \verb?\renewcommand*{\cftappendixname}{\appendixname~}? \\
% 
% \changes{v1.618}{2005/09/03}{Added \cs{cftappendixname}, courtesy Danie Els (mempatch v3.12)}
%    \begin{macrocode}
\newcommand*{\cftappendixname}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\l@appendix}
% \begin{macro}{\toclevel@appendix}
% Similar to \cs{l@chapter} but for an appendix.
% \changes{v1.618}{2005/09/03}{Added \cs{l@apendix} (mempatch v3.12)}
%    \begin{macrocode}
\newcommand*{\l@appendix}[2]{%
  \l@chapapp{#1}{#2}{\cftappendixname}}
\newcommand{\toclevel@appendix}{0}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\chapternumberline}
% \begin{macro}{\chapternumberlinehook}
% \cs{chapternumberline} is a special version of \cs{numberline} output by 
% \cs{chapter}.
% It's default definition is identical to \cs{numberline}.
% \changes{v1.3}{2002/11/14}{Added \cs{chapternumberline}}
% \changes{v1.618}{2005/09/03}{Added \cs{@chapapp@head} to \cs{chapternumberline} (mempatch v3.12)}
% \changes{v1.61803398d}{2010/02/13}{added hook into chapter numberline}
% changes{v3.6k}{2012/07/22}{Factored out the box command}
%    \begin{macrocode}
\newcommand*\chapternumberlinehook[1]{}
\newcommand{\chapternumberline}[1]{%
  \chapternumberlinehook{#1}%
  % \hb@xt@\@tempdima{\@chapapp@head\@cftbsnum #1\@cftasnum\hfil}%
  % \@cftasnumb}
  \chapternumberlinebox\@tempdima{\@chapapp@head\@cftbsnum #1\@cftasnum}%
  \@cftasnumb}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\cftbeforechapterskip}
% \begin{macro}{\cftchapterindent}
% \begin{macro}{\cftchapternumwidth}
% \begin{macro}{\cftchapterfont}
% \begin{macro}{\cftchapterpresnum}
% \begin{macro}{\cftchapteraftersnum}
% \begin{macro}{\cftchapteraftersnumb}
% \begin{macro}{\cftchapterleader}
% \begin{macro}{\cftchapterdotsep}
% \begin{macro}{\cftchapterpagefont}
% \begin{macro}{\cftchapterafterpnum}
% \begin{macro}{\cftchapterformatpnum}
% \begin{macro}{\cftchapterformatpnumhook}
% \begin{macro}{\cftchapterfillnum}
%  These are the user commands to control the typesetting of Chapter entries.
%  They are initialised to give the standard appearance.
% \changes{v1.61803}{2008/01/30}{Added \cs{cftchapterformatpnum} (mempatch v4.9)}
% \changes{v1.61803398d}{2010/02/13}{added hook into \cs{cftchapterformatpnum}}
%    \begin{macrocode}
  \newlength{\cftbeforechapterskip}
    \setlength{\cftbeforechapterskip}{1.0em \@plus\p@}
  \newlength{\cftchapterindent}
    \setlength{\cftchapterindent}{0em}
  \newlength{\cftchapternumwidth}
    \setlength{\cftchapternumwidth}{1.5em}
  \newcommand{\cftchapterfont}{\bfseries}
  \newcommand{\cftchapterpresnum}{}
  \newcommand{\cftchapteraftersnum}{}
  \newcommand{\cftchapteraftersnumb}{}
  \newcommand{\cftchapterleader}{%
              \bfseries\cftdotfill{\cftchapterdotsep}}
  \newcommand{\cftchapterdotsep}{\cftnodots}
  \newcommand{\cftchapterpagefont}{\bfseries}
  \newcommand{\cftchapterafterpnum}{}
  \newcommand{\cftchapterformatpnumhook}[1]{}
  \newcommand*{\cftchapterformatpnum}[1]{%
    \cftchapterformatpnumhook{#1}%
    \hb@xt@\@pnumwidth{\hfil\cftchapterpagefont #1}}
  \newcommand*{\cftchapterfillnum}[1]{%
    {\cftchapterleader}\nobreak
    \cftchapterformatpnum{#1}%
    \cftchapterafterpnum\par}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\cftchapterbreak}
% Another parameter for \cs{l@chapter}.
% \changes{v1.3}{2002/11/14}{Added \cs{cftchapterbreak}}
%    \begin{macrocode}
  \newcommand{\cftchapterbreak}{\addpenalty{-\@highpenalty}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\l@section}
% \begin{macro}{\l@subsection}
% \begin{macro}{\l@subsubsection}
% \begin{macro}{\l@paragraph}
% \begin{macro}{\l@subparagraph}
%  \cs{l@section}\marg{title}\marg{page} typesets the ToC entry for
% a \cs{section} heading. Similarly \cs{l@subsection} and \cs{l@subsubsection}
% for \cs{subsection} and \cs{subsubsection} entries, and so on.
% \changes{v1.4}{2003/11/22}{Used \cs{newlistentry} for pararaph and 
%                             subparagraph (from patch v1.7)}
% \changes{v1.618}{2005/09/02}{Corrected (sub)paragraph ToC indents (mempatch v2.3)}
%    \begin{macrocode}
\newlistentry[chapter]{section}{toc}{0}
  \cftsetindents{section}{1.5em}{2.3em}
\newlistentry[section]{subsection}{toc}{1}
  \cftsetindents{subsection}{3.8em}{3.2em}
\newlistentry[subsection]{subsubsection}{toc}{2}
  \cftsetindents{subsubsection}{7.0em}{4.1em}
\newlistentry[subsubsection]{paragraph}{toc}{3}
  \cftsetindents{paragraph}{10.0em}{5.0em}
\newlistentry[paragraph]{subparagraph}{toc}{4}
  \cftsetindents{subparagraph}{12.0em}{6.0em}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%   The typesetting for Figures and Tables is defined later.
%
%
%
% \subsection{Support for the \Lpack{subfigure} package}
%
%  The code for supporting the \Lpack{subfigure} package is, in all 
% essentials, the same as that for the figure and table captions; only the
% names are changed. However, the code need only be executed if the
% \Lpack{subfigure} package is actually loaded. 
%
% \begin{macro}{\@cftl@subfigtab}
%    This command redefines the \cs{l@subfigure} and \cs{l@subtable} commands. 
% \changes{v1.61803}{2008/01/30}{Made \cs{@cftl@subfigtab} a no-op (mempatch v4.6)}
%    \begin{macrocode}
\newcommand*{\@cftl@subfigtab}{
%    \end{macrocode}
% \begin{macro}{\l@subfigure}
% \begin{macro}{\l@subtable}
%  \cs{l@subfigure}\marg{title}\marg{page} typesets the LoF entry for
% a subfigure caption heading, and \cs{l@subtable} does the same for subtables.
%    \begin{macrocode}
\newlistentry[figure]{subfigure}{lof}{1}
  \cftsetindents{subfigure}{2.3em}{2.5em}
\newlistentry[table]{subtable}{lot}{1}
  \cftsetindents{subtable}{2.3em}{2.5em}}
\renewcommand*{\@cftl@subfigtab}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%    Call the \Lpack{subfigure} package setup code only if the 
% \Lopt{subfigure} package has been used.
%    \begin{macrocode}
\AtBeginDocument{\@ifpackageloaded{subfigure}{\@cftl@subfigtab}{}}

%    \end{macrocode}
%
%
% \subsection{Switching page numbering}
%
%    It can, at times, be useful to be able to have ToC entries that have
% no printed page numbers.
%
% \begin{macro}{\cftpagenumbersoff}
% The user level command for switching off page numbers is 
% \cs{cftpagenumbersoff}\marg{entry} where \meta{entry} is the 
% name of the entry. 
% The macro redefines the \cs{cftXfillnum} command so that there is no leader
% and the page number is ignored.
%    \begin{macrocode}
\DeclareRobustCommand{\cftpagenumbersoff}[1]{%
  \@namedef{cft#1fillnum}##1{%
    \cftparfillskip\@nameuse{cft#1afterpnum}\par}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cftpagenumberson}
% \cs{cftpagenumberson}\marg{entry} is the user level command for 
% reversing the corresponding \cs{cftpagenumbersoff}.
% The macro defines the \cs{cftXfillnum} command to correspond to 
% the default definition.
% \changes{v1.61803}{2008/01/30}{Modified \cs{cftpagenumberson} to use \cs{cftXformatpnum} 
%                   (mempatch v4.9)}
%    \begin{macrocode}
\DeclareRobustCommand{\cftpagenumberson}[1]{%
  \@namedef{cft#1fillnum}##1{%
    \@nameuse{cft#1leader}\nobreak
    \@nameuse{cft#1formatpnum}{##1}%
    \@nameuse{cft#1afterpnum}\par}}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Chapter precis}
%
% \begin{macro}{\chapterprecis}
% The command \cs{chapterprecis}\marg{text} typesets
% \meta{text} at the point where it is called, and also adds \meta{text}
% to the \file{.toc} file. It is expects to be called immediately after
% a \cs{chapter} command.
%    \begin{macrocode}
\newcommand{\chapterprecis}[1]{%
  \chapterprecishere{#1}
  \chapterprecistoc{#1}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chapterprecishere}
% \cs{chapterprecishere}\marg{text} typesets \meta{text}. It expects
% to be called immediately after a \cs{chapter} command. 
% \changes{v1.3}{2002/11/14}{Parameterised \cs{chapterprecishere}}
%    \begin{macrocode}
\newcommand{\chapterprecishere}[1]{%
  \prechapterprecis #1\postchapterprecis}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\prechapterprecis}
% \begin{macro}{\prechapterprecisshift}
% \begin{macro}{\precisfont}
% \begin{macro}{\postchapterprecis}
% The \cs{pre...} and \cs{post...} macros put code before and after 
% \cs{chapterprecishere} text. By
% default \cs{prechapterprecis} adds some (negative) space (defined by
% \cs{prechapterprecisshift} whose value depends on whether or not the
% \Lopt{article} option is used, as discovered by Lars Madsen) and starts a
% quote environment using the \cs{precisfont}. \cs{postchapterprecis} ends
% the quote environment.
% \changes{v1.3}{2002/11/14}{Added \cs{prechapterprecis} and 
%                            \cs{postchapterprecis}}
% \changes{v1.61803}{2008/01/30}{Added \cs{prechapterprecisshift} and
%          \cs{precisfont} (mempatch v4.9)}
%    \begin{macrocode}
\newdimen\prechapterprecisshift
\ifartopt
  \prechapterprecisshift=0pt
\else
  \prechapterprecisshift=-2\baselineskip
\fi
\newcommand*{\precisfont}{\normalfont\itshape}
\newcommand{\prechapterprecis}{%
  \vspace*{\prechapterprecisshift}%
  \begin{quote}\precisfont}
%    \end{macrocode}
% \changes{v3.6k}{2013/04/24}{We are missing the after heading
% stuff. Otherwise text will indent after \cs{chapterprecis}}
%    \begin{macrocode}
\newcommand*{\postchapterprecis}{%
  \end{quote}%
  \par\m@mindentafterchapter%
  \@afterheading}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\precistocfont}
% Font for typesetting chapter precis in the ToC.
% \changes{v1.3}{2002/11/14}{Added \cs{precistocfont}}
%    \begin{macrocode}
\newcommand{\precistocfont}{\normalfont\itshape}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\precistocformat}
% Macro for adding extra formatting to the precis toc text, formatting
% that has nothiing to do with font. The default is \cs{noindent}.
% \changes{v3.6d}{2010/06/09}{Added \cs{precistocformat}}
%    \begin{macrocode}
\newcommand{\precistocformat}{\noindent}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\chapterprecistoc}
% \begin{macro}{\precistoctext}
% \cs{chapterprecistoc}\marg{text} effectively adds \meta{text} to 
% the \file{.toc}
% file. The \meta{text} will be typeset within the same margins as the
% the title text of a \cs{chapter} heading, using the \cs{precistocfont} font.
% \changes{v1.3}{2002/11/14}{Added \cs{precistoctext}}
% \changes{v1.61803398}{2009/07/18}{Added bidi support to \cs{precistoctext}}
%    \begin{macrocode}
\newcommand{\chapterprecistoc}[1]{%
  \addtocontents{toc}{\precistoctext{#1}}}
\DeclareRobustCommand{\precistoctext}[1]{%
%    \end{macrocode}
% Start a group to localize changes to the paragraphing. Set the 
% left margin to the chapter indent plus the chapter number width.
% \changes{v1.6180339c}{2009/01/20}{Added a \cs{nopagebreak}, though
% this only disencourage a page break}
%    \begin{macrocode}
  {%\nopagebreak\leftskip \cftchapterindent\relax
   \nopagebreak\memRTLleftskip \cftchapterindent\relax
%%%   \advance\leftskip \cftchapternumwidth\relax
   \advance\memRTLleftskip \cftchapternumwidth\relax
%    \end{macrocode}
% Set the right hand margin to \cs{@tocrmarg}.
%    \begin{macrocode}
%%%   \rightskip \@tocrmarg\relax
   \memRTLrightskip \@tocrmarg\relax
%    \end{macrocode}
% Typeset \meta{text} using an italic font, then ensure that the paragraph
% is finished (to use the local skips). Finally close the group and we 
% are done.
% \changes{v3.6d}{2010/06/09}{Added \cs{precistocformat}}
%    \begin{macrocode}
   \precistocformat\precistocfont #1\par}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \subsection{Adding things to the ToC}
%
% \begin{macro}{\cftlocalchange}
% \cs{cftmakelocalchange}\marg{file}\marg{pnumwidth}\marg{tocrmarg}
% makes an entry into \meta{file} to change the \cs{@pnumwidth} and
% the \cs{@tocrmarg} values.
%    \begin{macrocode}
\newcommand{\cftlocalchange}[3]{%
  \addtocontents{#1}{\protect\setpnumwidth{#2} \protect\setrmarg{#3}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cftaddtitleline}
% \cs{cftaddtitleline}\marg{file}\marg{kind}\marg{title}\marg{page}
% adds a \cs{contentsline} entry to \meta{file} with the given information.
%    \begin{macrocode}
\newcommand{\cftaddtitleline}[4]{%
  \addtocontents{#1}{\protect\contentsline{#2}{#3}{#4}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cftaddnumtitleline}
% \cs{cftaddnumtitleline}\marg{file}\marg{kind}\marg{num}\marg{title}\marg{page}
% adds a \cs{contentsline} entry to \meta{file} with the given information.
%    \begin{macrocode}
\newcommand{\cftaddnumtitleline}[5]{%
  \addtocontents{#1}%
    {\protect\contentsline{#2}{\protect\numberline{#3}%
                              {\protect\ignorespaces #4}}{#5}}}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\cftinsertcode}
% \begin{macro}{\cftinserthook}
% \begin{macro}{\cftinsert}
%  This is a generalisation of a suggestion by Lars Madsen (private email,
% 2007/12/14).
%
% \cs{cftinsertcode}\marg{id}\marg{code} creates a hook to be executed in 
% a `List of'. Since we use \cs{@nameuse} it does not matter if the hook 
% does not exist
%
% \cs{cftinserthook}\marg{list}\marg{id} inserts the hook \meta{id} into the 
% \meta{list} `List of' file (in the form of \cs{cftinsert}\marg{id}).
%
% Use like this:
% \begin{verbatim}
% \cftinsertcode{A}{%
%    \renewcommand*{\cftchapterfont}{\normalfont\scshape}
%    ...
%    }
% \cftinsertcode{F}{...}
% \cftinsertcode{G}{...}
%    ...
% \frontmatter
% \tableofcontents
% \cftinserthook{lof}{G}
% \listoffigures
% \chapter{...}
% ...
% \mainmatter
% \cftinserthook{lof}{F}
% \cftinserthook{toc}{A}
% \chapter{...}
% ...
% \end{verbatim}
%
% \changes{v1.61803}{2008/01/30}{Added \cs{cftinsert} and friends (mempatch v4.9)}
%    \begin{macrocode}
\newcommand*{\cftinsert}[1]{\@nameuse{cftinsert#1}}
\newcommand{\cftinsertcode}[2]{\@namedef{cftinsert#1}{#2}}
\newcommand*{\cftinserthook}[2]{%
  \addtocontents{#1}{\protect\cftinsert\protect{#2\protect}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsection{ToC and divisional numbering}
%
%  Commands are provided, based on the \Lpack{tocvsec2} package, for changing
% the section numbering level and the ToC entry level.
%
% \begin{macro}{\@setclcnt}
% Helper macro to set a sectioning-related counter. Use as
% \cs{@setclcnt}\marg{sec}\marg{counter} to set \Lcount{counter}
% to the level of \meta{sec}.
% \changes{v1.61803}{2008/01/30}{Added book to \cs{@setclcnt} and friends
%                   (mempatch v4.4)}
% \changes{v1.61803398}{2009/07/29}{PW: Replaced \cs{if@tempswa} with 
%   \cs{@setclcntok} in \cs{@setclcnt} to avoid bad clashes with other uses}
%    \begin{macrocode}
\newcommand*{\@setclcnt}[2]{%
  \def\@setclcntok{0}% = false
  \nametest{#1}{none}%
  \ifsamename
    \setcounter{#2}{-10}%
    \def\@setclcntok{1}% = true
  \fi
  \nametest{#1}{book}%
  \ifsamename
    \setcounter{#2}{-2}%
    \def\@setclcntok{1}%
  \fi
  \nametest{#1}{part}%
  \ifsamename
    \setcounter{#2}{-1}%
    \def\@setclcntok{1}%
  \fi
  \nametest{#1}{chapter}%
  \ifsamename
    \setcounter{#2}{0}%
    \def\@setclcntok{1}%
  \fi
  \nametest{#1}{section}%
  \ifsamename
    \setcounter{#2}{1}%
    \def\@setclcntok{1}%
  \fi
  \nametest{#1}{subsection}%
  \ifsamename
    \setcounter{#2}{2}%
    \def\@setclcntok{1}%
  \fi
  \nametest{#1}{subsubsection}%
  \ifsamename
    \setcounter{#2}{3}%
    \def\@setclcntok{1}%
  \fi
  \nametest{#1}{paragraph}%
  \ifsamename
    \setcounter{#2}{4}%
    \def\@setclcntok{1}%
  \fi
  \nametest{#1}{subparagraph}%
  \ifsamename
    \setcounter{#2}{5}%
    \def\@setclcntok{1}%
  \fi
  \nametest{#1}{all}%
  \ifsamename
    \setcounter{#2}{50}%
    \def\@setclcntok{1}%
  \fi
%%  \if@tempswa\else
    \ifnum \@setclcntok = 0\relax
    \@memerror{%
      Unknown document division name (#1)
    }{%
     I'll ignore it.
     Type \space <return> and I'll continue.\MessageBreak
     If you haven't mistyped the name then use
     \protect\setcounter\space instead.}%
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\settocdepth}
% \cs{settocdepth}\marg{sec} is the user command for setting 
% \Lcount{tocdepth} in the \file{.toc} file to the value corresponding to
% \meta{sec}. 
% \changes{v1.3}{2002/11/14}{Changed \cs{settocdepth} to use \cs{changetocdepth}}
% \changes{v1.61803}{2008/01/30}{Added book to ToC depth setting (mempatch v4.4)}.
% \changes{v1.61803398}{2009/07/29}{PW: Replaced \cs{if@tempswa} with 
%   \cs{@chtocdok} in \cs{settocdepth} to avoid bad clashes with other uses}
%    \begin{macrocode}
\newcommand*{\settocdepth}[1]{%
  \def\@chtodok{0}%   false
  \nametest{#1}{none}%
  \ifsamename
    \addtocontents{toc}{\changetocdepth{-10}}%
    \def\@chtodok{1}%   true
  \fi
  \nametest{#1}{book}%
  \ifsamename
    \addtocontents{toc}{\changetocdepth{-2}}%
    \def\@chtodok{1}%
  \fi
  \nametest{#1}{part}%
  \ifsamename
    \addtocontents{toc}{\changetocdepth{-1}}%
    \def\@chtocdok{1}%
  \fi
  \nametest{#1}{chapter}%
  \ifsamename
    \addtocontents{toc}{\changetocdepth{0}}%
    \def\@chtocdok{1}%
  \fi
  \nametest{#1}{section}%
  \ifsamename
    \addtocontents{toc}{\changetocdepth{1}}%
    \def\@chtocdok{1}%
  \fi
  \nametest{#1}{subsection}%
  \ifsamename
    \addtocontents{toc}{\changetocdepth{2}}%
    \def\@chtocdok{1}%
  \fi
  \nametest{#1}{subsubsection}%
  \ifsamename
    \addtocontents{toc}{\changetocdepth{3}}%
    \def\@chtocdok{1}%
  \fi
  \nametest{#1}{paragraph}%
  \ifsamename
    \addtocontents{toc}{\changetocdepth{4}}%
    \def\@chtocdok{1}%
  \fi
  \nametest{#1}{subparagraph}%
  \ifsamename
    \addtocontents{toc}{\changetocdepth{5}}%
    \def\@chtocdok{1}%
  \fi
  \nametest{#1}{all}%
  \ifsamename
    \addtocontents{toc}{\changetocdepth{50}}%
    \def\@chtocdok{1}%
  \fi
%  \if@tempswa
  \ifnum\@chtocdok=1\relax
%    \end{macrocode}
% The next bit is from Heiko Oberdiek (CTT {\itshape Re: Memoir, \verb?\settocdepth?
% and pdflatex \verb?=>? problem with PDF bookmarks}, 2006/07/21) as 
% \Lpack{hyperref} needs \verb?\tocdepth? set in the body not just in the ToC.
%    \begin{macrocode}
    \@ifundefined{toclevel@#1}{%
      \@memwarn{Unknown toclevel for #1}%
    }{%
      \setcounter{tocdepth}{\@nameuse{toclevel@#1}}%
    }
  \else
    \@memerror{%
      Unknown document division name (#1)
    }{%
     I'll ignore it.
     Type \space <return> and I'll continue.}%
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\toclevel@none}
% \begin{macro}{\toclevel@all}
% Couple of extras for hypperef to cater for \texttt{all} and \texttt{none}
% as `division levels'.
% \changes{v1.61803}{2008/01/30}{Added \cs{toclevel@none} and \cs{toclevel@all}
%         (mempatch v4.4)}
%    \begin{macrocode}
\newcommand*{\toclevel@none}{-10}
\newcommand*{\toclevel@all}{50}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\changetocdepth}
% Changes the \texttt{tocdepth} counter. Make it robust as it will be written
% to the *.toc file.
% \changes{v1.3}{2002/11/14}{Added \cs{changetocdepth}}
%    \begin{macrocode}
\DeclareRobustCommand{\changetocdepth}[1]{\setcounter{tocdepth}{#1}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\maxtocdepth}
% \cs{maxtocdepth}\marg{sec} can be used to initialise \Lcount{tocdepth}
% to the value corresponding to \meta{sec}. This can only be used
% between the end of the preamble and the \cs{tableofcontents} command.
%    \begin{macrocode}
\newcommand{\maxtocdepth}[1]{%
  \@setclcnt{#1}{tocdepth}}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\maxsecnumdepth}
% \cs{maxsecnumdepth}\marg{sec} can be used to initialise 
% \Lcount{secnumdepth}
% to the value corresponding to \meta{sec}.
% \changes{v1.1}{2002/03/10}{Added maxsecnumdepth counter and modified \cs{maxsecnumdepth}}
%    \begin{macrocode}
\newcounter{maxsecnumdepth}
\newcommand{\maxsecnumdepth}[1]{%
  \@setclcnt{#1}{secnumdepth}\@setclcnt{#1}{maxsecnumdepth}}

%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\setsecnumdepth}
% \cs{setsecnumdepth}\marg{sec} is the user command for setting
% \Lcount{secnumdepth} to the value for \meta{sec}. In the preamble it sets
% both the \Lcount{secnumdepth} and \Lcount{maxsecnumdepth} to \meta{sec}
% while in the body it only sets \Lcount{secnumdepth}.
% \changes{v1.61803}{2008/01/30}{Extended \cs{setsecnumdepth} to make it more
%           intuitive (mempatch v4.9)}
%    \begin{macrocode}
\newcommand{\setsecnumdepth}[1]{%
  \ifx\@nodocument\relax%      after the preamble
    \@setclcnt{#1}{secnumdepth}%
  \else
    \@setclcnt{#1}{secnumdepth}%
    \@setclcnt{#1}{maxsecnumdepth}%
  \fi}
\setsecnumdepth{section}

%    \end{macrocode}
% \end{macro}
% 
% 
%
%
% \section{Bibliography}
%
%
% \begin{macro}{\bibindent}
% The \Lopt{open} bibliography uses an indentation of \cs{bibindent}.
%    \begin{macrocode}
\newdimen\bibindent
  \setlength\bibindent{1.5em}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\bibitemsep}
% The vertical separation between items in the bibliography list.
% \changes{v1.4}{2003/11/22}{Added \cs{bibitemsep} (from patch v1.7)}
%    \begin{macrocode}
\newlength{\bibitemsep}
  \setlength{\bibitemsep}{\itemsep}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\biblistextra}
% A hook into the \texttt{bibitemlist}.
% \changes{v1.4}{2003/11/22}{Added \cs{biblistextra} (from patch v1.7)}
%    \begin{macrocode}
\newcommand{\biblistextra}{\itemsep=\bibitemsep}

%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{bibitemlist}
%  The \texttt{thebibliography} environment starts a new document division. 
% Internally it tweaks some typesetting aspects; principally it
% uses \cs{sloppy} because good linebreaking is hard in a bibliography,
% and \verb?\sfcode`\.=1000\relax? causes a full stop not to produce an
% end-of-sentence space. The implementation of the environment is
% based on the generic \texttt{list} environment, and uses the \cs{c@enumiv}
% count for the labels. The following code is extracted from the
% \Lpack{book} class, plus some additions.
% \changes{v1.4}{2003/11/22}{Added \cs{biblistextra} to bibitemlist (from patch v1.7)}
%    \begin{macrocode}
\newenvironment{bibitemlist}[1]{%
  \typeout{bibitemlist}
  \list{\@biblabel{\@arabic\c@enumiv}}%
       {\settowidth\labelwidth{\@biblabel{#1}}%
        \leftmargin\labelwidth
        \advance\leftmargin\labelsep
        \@openbib@code
        \usecounter{enumiv}%
        \let\p@enumiv\@empty
        \renewcommand\theenumiv{\@arabic\c@enumiv}%
        \biblistextra}%
  \sloppy
  \clubpenalty4000
  \@clubpenalty \clubpenalty
  \widowpenalty4000%
  \sfcode`\.\@m}%
  {\def\@noitemerr
    {\@latex@warning{Empty `thebibliography' environment}}%
    \endlist}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\newblock}
% The default is for \cs{newblock} to provide a small space.
%    \begin{macrocode}
\newcommand{\newblock}{\hskip .11em\@plus.33em\@minus.07em}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@openbib@code}
% This a an empty hook. It will be modified if the \Lopt{openbib}
% option is used.
%    \begin{macrocode}
\let\@openbib@code\@empty
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setbiblabel}
% \begin{macro}{\@biblabel}
% This is the user command for setting the label for a \cs{bibitem}. 
% The following sets the default definition.
%    \begin{macrocode}
\newcommand*{\setbiblabel}[1]{%
  \renewcommand*{\@biblabel}[1]{#1}}
\setbiblabel{[#1]\hfill}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@memb@bchap}
% \begin{macro}{\@memb@bsec}
%  In a \ctt{} thread \textit{memoir, natbib, and chapterbib} in January 2003
% there was a discussion on how to get all three to work together.
% Donald Arseneau suggested that \cs{bibsection} be used as a `standard'
% way of controlling the sectioning command of a bibliography. Here is
% an implementation of that idea.
%
% \cs{@memb@bchap} is a copy of memoir's original code for the start
% of the \texttt{thebibliography} environment which used a \cs{chapter*}
% title. \cs{@memb@bsec} is the much simpler version for a \cs{section} title.
% \changes{v1.4}{2003/02/27}{Added support code for implementing \cs{bibsection}
%                            (patch 1.3)}
% \changes{v3.7g}{2018/02/28}{Removeded \cs{phantomsection} before
% \cs{addcontentsline} as it is no longer needed, and causes the
% hyperlink target to the bibligraphy to be below the title, reported
% via \texttt{https://tex.stackexchange.com/a/396303/3929}}
%    \begin{macrocode}
\newcommand{\@memb@bchap}{%
  \chapter*{\bibname}%
  \bibmark
  \ifnobibintoc\else
    % \phantomsection
    \addcontentsline{toc}{chapter}{\bibname}%
  \fi
  \prebibhook}
\newcommand{\@memb@bsec}{\section{\bibname}\prebibhook}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\bibsection}
% Normally treat the bibliography heading as a chapter.
% \changes{v1.4}{2003/02/27}{Added \cs{bibsection} to replace memoir's
%                            original code for the bibliography (patch 1.3)}
%    \begin{macrocode}
\newcommand{\bibsection}{\@memb@bchap}

%    \end{macrocode}
% \end{macro}
% 
% \begin{environment}{thebibliography}
% The definition of the \texttt{thebibliography} environment in this class is not
% quite the same as in the standard classes!
%
% \changes{v0.2}{2001/06/03}{Deleted starred version of thebibliography}
% \changes{v1.4}{2003/02/27}{Replaced initial code in the bibliography
%                            environment by \cs{bibsection} (patch 1.3)}
%    \begin{macrocode}
\newenvironment{thebibliography}[1]{%
  \bibsection
  \begin{bibitemlist}{#1}}{\end{bibitemlist}\postbibhook}
%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\ifnobibintoc}
% \begin{macro}{\bibintoc}
% \begin{macro}{\nobibintoc}
% Flag to control whether or not to add the bibliography title to the ToC,
% and declarations to set the flag.
% Default is to put the title into the ToC.
% \changes{v0.2}{2001/06/03}{Added \cs{ifnobibintoc}, etc.}
%    \begin{macrocode}
\newif\ifnobibintoc
\newcommand*{\bibintoc}{\nobibintocfalse}
\newcommand*{\nobibintoc}{\nobibintoctrue}
\bibintoc

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\prebibhook}
% \begin{macro}{\postbibhook}
% These two macros are called just before starting the bib items and just
% after finishing them. By default they do nothing but can be changed
% by the user to give, say, some introductory information.
%    \begin{macrocode}
\newcommand{\prebibhook}{}
\newcommand{\postbibhook}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@cite}
% The output of the \cs{cite} command is produced by this macro. The default
% is used. The \Lpack{cite} package is a good way of changing this.
%    \begin{macrocode}
% \renewcommand*{\@cite}[1]{[#1]}
%    \end{macrocode}
% \end{macro}
%
% \subsection{Use with the \Lpack{natbib} and \Lpack{chapterbib} packages}
%
% The \Lpack{natbib} package~\cite{NATBIB} uses its own definition for
% the \texttt{thebibliography} environment, which knows nothing about adding
% the Bibliography to the ToC. The following makes appropriate changes
% to \Lpack{natbib} code to support the class.
%
% The \Lpack{chapterbib} package by Donald Arseneau also may make changes
% to the \texttt{thebibliography} environment --- perhaps memoir's version
% or natbib's version.
%
%    As packages get loaded after classes, I have to try and patch any
% non-memoir modifications at begin document time. 
% The fixes have to be firstly for \Lpack{natbib}
% and only after those can \Lpack{chapterbib} be considered.
%
% \changes{v1.1}{2002/03/10}{Added internal support for the natbib package}
% \changes{v1.4}{2003/02/27}{Changed code supporting natbib (patch 1.3)}
% \changes{v1.4}{2003/02/27}{Added code supporting chapterbib (patch 1.3)}
% \begin{macro}{\bibsection}
% \begin{macro}{\endthebibliography}
% Natbib provides \cs{bibsection} for titling the bibliography. I also have
% to extend the end of the \texttt{thebibliography} environment to cater for
% \cs{postbibhook}.
%    \begin{macrocode}
\AtBeginDocument{%
  \@ifpackageloaded{natbib}{% natbib is loaded
%    \end{macrocode}
% As \Lpack{natbib} is used, change \cs{endthebibliography} to the class
% definition.
%    \begin{macrocode}
    \addtodef{\endthebibliography}{}{\vskip-\lastskip\postbibhook}
    \@ifpackagewith{natbib}{sectionbib}{% with sectionbib option
%    \end{macrocode}
% \Lpack{natbib}'s \Lopt{sectionbib} option is used,
%    \begin{macrocode}
      \renewcommand{\bibsection}{\@memb@bsec}}%
%    \end{macrocode}
% The \Lopt{sectionbib} option is not used, so we have a chapter title.
%    \begin{macrocode}
      {\renewcommand{\bibsection}{\@memb@bchap}}}%
%    \end{macrocode}
% Finished with any \Lpack{natbib} related changes.
%    \begin{macrocode}
  {}
%    \end{macrocode}
%
% Now deal with \Lpack{chapterbib} if necessary.
%    \begin{macrocode}
  \@ifpackagewith{chapterbib}{sectionbib}{%
%    \end{macrocode}
% \Lpack{chapterbib} is used with its \Lopt{sectionbib} option. This is the
% only case to worry about. Kill \Lpack{chapterbib}'s \cs{sectionbib} macro
% which it calls at begin document to do its patch, then make sure
% the class definition is used.
%    \begin{macrocode}
    \renewcommand{\sectionbib}[2]{}
    \renewcommand{\bibsection}{\@memb@bsec}}{}
%    \end{macrocode}
% And we've finished with this bunch of \cs{AtBeginDocument} code.
%    \begin{macrocode}
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
%
%  \section{The index}
%
% I allow for a single column index as well as the default double column.
%
% \begin{macro}{\ifonecolindex}
% TRUE for a one column index.
% \changes{v1.3}{2002/10/10}{Added one column index}
%    \begin{macrocode}
\newif\ifonecolindex
  \onecolindexfalse

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\onecolindex}
% \begin{macro}{\twocolindex}
% \changes{v1.61803}{2008/01/30}{Added \cs{onecolindex} and \cs{twocolindex}}
%    \begin{macrocode}
\newcommand*{\onecolindex}{\onecolindextrue}
\newcommand*{\twocolindex}{\onecolindexfalse}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{environment}{theindex}
%    The environment \texttt{theindex} can be used for indices. It makes an
%    index with two columns, with each entry a separate paragraph. At
%    the user level the commands \cs{item}, \cs{subitem} and \cs{subsubitem}
%    are used to produce index entries of various levels. When a new
%    letter of the alphabet is encountered an amount of \cs{indexspace}
%    white space can be added.
%
%
% \changes{v0.2}{2001/06/03}{Deleted starred version of theindex}
% \changes{v0.2}{2001/06/03}{Changed Index pagestyle to chapter}
% \changes{v1.618}{2005/09/03}{Make \cs{indexcolsep} work, courtesy of hazydirk (mempatch v3.11)}
% \changes{v1.61803}{2008/01/30}{Added \cs{clearforchapter} to theindex
%         environment (Erik Quaeghebeur, mempatch v4.4)}
% \changes{v1.61803}{2008/01/30}{Added an indextitlepagestyle (Lars Madsen
%                    mempatch v4.6)}
%    \begin{macrocode}
\newenvironment{theindex}{%
  \clearforchapter
  \if@twocolumn
    \@restonecolfalse
  \else
    \@restonecoltrue
  \fi
  \ifonecolindex
    \onecolumn
    \chapter*{\indexname}
    \preindexhook
  \else
    \setlength{\columnseprule}{\indexrule}%
    \setlength{\columnsep}{\indexcolsep}%
    \twocolumn[\@makeschapterhead{\indexname}
               \preindexhook]%
  \fi
  \indexmark
  \ifnoindexintoc\else
    \phantomsection
    \addcontentsline{toc}{chapter}{\indexname}%
  \fi
  \thispagestyle{indextitlepagestyle}\parindent\z@
  \parskip\z@ \@plus .3\p@\relax
  \let\item\@idxitem}%
  {\if@restonecol\onecolumn\else\twocolumn\fi}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\ps@indextitlepagestyle}
%    \begin{macrocode}
\aliaspagestyle{indextitlepagestyle}{chapter}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifnoindexintoc}
% \begin{macro}{\indexintoc}
% \begin{macro}{\noindexintoc}
% Flag to control whether or not to add the index title to the ToC,
% and declarations to set the flag.
% Default is to put the title into the ToC.
% \changes{v0.2}{2001/06/03}{Added \cs{ifnoindexintoc}, etc.}
%    \begin{macrocode}
\newif\ifnoindexintoc
\newcommand*{\indexintoc}{\noindexintocfalse}
\newcommand*{\noindexintoc}{\noindexintoctrue}
\indexintoc

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\indexcolsep}
% \begin{macro}{\indexrule}
% These two lengths control the column separation and the thickness
% of the inter-column rule.
% \changes{v0.2}{2001/06/03}{Added \cs{indexcolsep} and \cs{indexrule}}
%    \begin{macrocode}
\newlength{\indexcolsep} \setlength{\indexcolsep}{35pt}
\newlength{\indexrule}   \setlength{\indexrule}{0pt}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\preindexhook}
% A macro that is called between the index heading and the start of the
% two columns. The user can modify it to add something.
%    \begin{macrocode}
\newcommand{\preindexhook}{}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\l@index}
%   Format the index entry in the table of contents.
%    \begin{macrocode}
\newcommand{\l@index}{\@dottedtocline{1}{0em}{0pt}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@idxitem}
% \begin{macro}{\subitem}
% \begin{macro}{\subsubitem}
%    Thsee macros are used to format the entries in the index. 
%    \begin{macrocode}
\newcommand{\@idxitem}  {\par\hangindent 40\p@}
\newcommand{\subitem}   {\par\hangindent 40\p@ \hspace*{20\p@}}
\newcommand{\subsubitem}{\par\hangindent 40\p@ \hspace*{30\p@}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\indexspace}
%    The amount of white space that is inserted between `letter
%    blocks' in the index.
%    \begin{macrocode}
\newcommand{\indexspace}{\par \vskip 10\p@ \@plus5\p@ \@minus3\p@\relax}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makeindex}
% \begin{macro}{\index}
% \begin{macro}{\specialindex}
% \begin{macro}{\makememindexhook}
% This is a modified version of the kernel \cs{makeindex} to allow for
% multiple indexes. It also defines \cs{index} (which is a modified version
% of the standard \cs{index}) and \cs{specialindex}.
%
% \cs{makememindexhook} is a null op but can be redefined to add extra code
% into \cs{makeindex}. For example, to incorporate \Lpack{ledmac}'s
% \cs{edindex} into the scheme:
% \begin{verbatim}
% \renewcommand*{\makememindexhook}{%
%    \def\edindex{\@bsphack%
%      \@ifnextchar [{\l@d@index}{\l@d@index[\jobname]}}}
% \end{verbatim}
% \changes{v1.3}{2002/11/14}{Indexing macros completely redone and extended}
% \changes{v1.61}{2004/03/12}{Added the \cs{makememindexhook} to \cs{makeindex}}
% \changes{v1.618}{2005/09/02}{Modified \cs{makeindex} for \cs{nofiles}}
%    \begin{macrocode}
\newcommand*{\makememindexhook}{}
%    \end{macrocode}
%    \begin{macrocode}
\providecommand*{\makeindex}{}
\renewcommand*{\makeindex}[1][\jobname]{%
  \if@filesw
    \def\index{\@bsphack%
      \@ifnextchar [{\@index}{\@index[\jobname]}}
    \def\specialindex{\@bsphack\@spindex}%
    \makememindexhook
    \expandafter\newwrite\csname #1@idxfile\endcsname
    \expandafter\immediate\openout \csname #1@idxfile\endcsname #1.idx\relax
    \typeout{Writing index file #1.idx }%
  \fi}

%    \end{macrocode}
% Initially define, but emasculate, \cs{index} and \cs{specialindex} which are
% defined properly by the user calling \cs{makeindex}.
%    \begin{macrocode}
\renewcommand{\index}[2][\jobname]{\@bsphack\@esphack}
\newcommand{\specialindex}[3]{\@bsphack\@esphack}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\printindex}
% The command to read an \file{ind} file.
%    \begin{macrocode}
\newcommand{\printindex}[1][\jobname]{\@input@{#1.ind}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifreportnoidxfile}
% \begin{macro}{\reportnoidxfile}
% \begin{macro}{\ignorenoidxfile}
% \begin{macro}{\ifshowindexmark}
% \begin{macro}{\showindexmarks}
% \begin{macro}{\hideindexmarks}
% Two booleans to control reporting on unknown \file{idx} files and
% displaying indexed items in the margin.
%    \begin{macrocode}
\newif\ifreportnoidxfile
\newcommand*{\reportnoidxfile}{\reportnoidxfiletrue}
\newcommand*{\ignorenoidxfile}{\reportnoidxfilefalse}
  \ignorenoidxfile
\newif\ifshowindexmark
\newcommand*{\showindexmarks}{\showindexmarktrue}
\newcommand*{\hideindexmarks}{\showindexmarkfalse}
  \hideindexmarks

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@index}
% \verb?\@index[file]? is first stage of \cs{index}, handling the \file{idx} file.
%    \begin{macrocode}
\def\@index[#1]{%
  \@ifundefined{#1@idxfile}%
  {\ifreportnoidxfile
     \@memwarn{Undefined index file #1}%
    \fi
    \begingroup
    \@sanitize
    \@nowrindex}%
  {\def\@idxfile{#1}%
   \begingroup
   \@sanitize
   \@wrindexm@m}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@nowrindex}
% Called when there is no \file{idx} file to throw away the indexed item.
%    \begin{macrocode}
\newcommand{\@nowrindex}[1]{%
  \ifshowindexmark\@showidx{#1}\fi\endgroup\@esphack}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@wrindexm@m}
% \begin{macro}{\@@wrindexhyp}
% The next stage in index processing is \verb?\@wrindexm@m{item}?, 
% which writes the \file{idx} file name
% and indexed item to the \file{aux} file. The \cs{@@wrindexhyp} macro
% provides hyperlinks in case the \Lpack{hyperref} package is used.
%    \begin{macrocode}
\newcommand{\@wrindexm@m}[1]{\@@wrindexhyp#1||\\}
\def\@@wrindexhyp#1|#2|#3\\{%
  \ifshowindexmark\@showidx{#1}\fi
  \ifx\\#2\\%
    \protected@write\@auxout{}%
      {\string\@@wrindexm@m{\@idxfile}{#1|hyperpage}{\thepage}}%
  \else
    \def\Hy@temp@A{#2}%
    \ifx\Hy@temp@A\HyInd@ParenLeft
      \protected@write\@auxout{}%
        {\string\@@wrindexm@m{\@idxfile}{#1|#2hyperpage}{\thepage}}%
    \else
%    \end{macrocode}
% Add a corresponding test on \verb+|)+ to add \verb|hyperpage|. This
% is needed by the \verb|xindy| indexing programme. The standard
% \verb|makeindex| programme does not seem to mind.
% \changes{v3.7g}{2018/04/04}{Added test for \texttt{|)} and adding
% \texttt{hyperpage} accordingly.}
%    \begin{macrocode}
      \ifx\Hy@temp@A\HyInd@ParenRight
        \protected@write\@auxout{}%
          {\string\@@wrindexm@m{\@idxfile}{#1|#2hyperpage}{\thepage}}%
      \else
        \protected@write\@auxout{}%
          {\string\@@wrindexm@m{\@idxfile}{#1|#2}{\thepage}}%
      \fi        
    \fi
  \fi
  \endgroup
  \@esphack}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\hyperpage}
% \begin{macro}{\hyperlink}
% These are defined in the \Lpack{hyperref} package but we need them.
% Other hyperstuff is only used if the package itself is used.
%    \begin{macrocode}
\newcommand{\hyperpage}[1]{#1}
\newcommand{\hyperlink}[2]{#2}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@@wrindexm@m}
% The macro \verb?\@@wrindexm@m{file}{item}{page}? has been written into
% the \file{aux} file. It is normally defined so that it calls
% \verb?\@@@wrindexm@m{item}{page}? to finally write to the \file{idx} file.
%    \begin{macrocode}
\newcommand{\@@wrindexm@m}[1]{\begingroup
  \def\@idxfile{\@nameuse{#1@idxfile}}
  \@sanitize
  \@@@wrindexm@m}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@@@wrindexm@m}
% \cs{@@@wrindexm@m}\marg{item}\marg{page} writes the \cs{indexentry} to 
% the \file{idx} file. This file is read both at the beginning and end of 
% a document so \cs{@@@wrindexm@m} must be disabled for one of these reads
% otherwise the index entries will be doubled up. Initially I disabled it
% after the first read. It eventually dawned on me that this meant two
% LaTeX runs to update the \file{idx}. Enabling it for the second read
% means that the \file{idx} file is updated at the end of each run.
% \changes{v1.618}{2005/09/02}{Made \cs{@@@wrindexm@m} obey \cs{nofiles}}
% \changes{v1.618}{2005/09/25}{\cs{@@@wrindexm@m} now reads the aux
%                  file at the end of the document}
%    \begin{macrocode}
\newcommand{\@@@wrindexm@m}[2]{\endgroup}
\AtBeginDocument{%
  \def\@@@wrindexm@m#1#2{%
    \if@filesw
      \immediate\write \@idxfile{\string\indexentry{#1}{#2}}%
    \fi
    \endgroup}%
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@spindex}
% Now do similar things for \cs{specialindex}.
%    \begin{macrocode}
\newcommand{\@spindex}[2]{%
  \@ifundefined{#1@idxfile}%
  {\ifreportnoidxfile
     \@memwarn{Undefined index file #1}%
    \fi
    \begingroup
    \@sanitize
    \@nowrindex}%
  {\def\@idxfile{#1}%
   \def\@sptheidx{#2}%
   \begingroup
   \@sanitize
   \@wrspindex}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@wrspindex}
% \begin{macro}{\@@wrspindexhyp}
%    \begin{macrocode}
\newcommand{\@wrspindex}[1]{\@@wrspindexhyp#1||\\}
\def\@@wrspindexhyp#1|#2|#3\\{%
  \ifshowindexmark\@showidx{#1}\fi
  \ifx\\#2\\%
    \protected@write\@auxout{}%
      {\string\@@wrindexm@m{\@idxfile}%
        {#1|hyperspindexpage(\thepage)}%
      {\@nameuse{the\@sptheidx}}}%
  \else
    \def\Hy@temp@A{#2}%
    \ifx\Hy@temp@A\HyInd@ParenLeft
      \protected@write\@auxout{}%
        {\string\@@wrindexm@m{\@idxfile}%
         {#1|#2hyperspindexpage(\thepage)}%
         {\@nameuse{the\@sptheidx}}}%
    \else
      \protected@write\@auxout{}%
        {\string\@@wrindexm@m{\@idxfile}{#1|#2}%
        {\@nameuse{the\@sptheidx}}}%
    \fi
  \fi
  \endgroup
  \@esphack}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\hyperspindexpage}
%    \begin{macrocode}
\def\hyperspindexpage(#1)#2{\hyperlink{page.#1}{#2}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifmemhyperindex}
% \begin{macro}{\memhyperindextrue}
% \begin{macro}{\memhyperindexfalse}
% Flag to turn off \cs{hyperindexfalse} hyperrefing the index (apparently
% \Lpack{xindy} can't cope with this. Email from Frederic Connes, 2005/07/13:
% \begin{verbatim}
%  ...You use |hyperspindex(\thepage) which xindy doesn't 
% recognise as a valid markup-locref. And I don't know how 
% to add it because xindy only accepts one argument in 
% markup-locref (if the number is not a page number, it will 
% still point to a page with that number) so replacing it 
% with |hyperpage won't work. ...
% \end{verbatim}
% 
%
% The default is \cs{memhyperindextrue}. Setting \cs{memhyperindexfalse}
% prohibits a hyper index --- setting whatever option in \Lpack{hyperref}
% to disable hyper indexing will (probably) not work as far as \Lpack{xindy}
% is concerned.
% \changes{v1.618}{2005/09/04}{Added \cs{ifmemhyperindex}}
%    \begin{macrocode}
\newif\ifmemhyperindex
  \memhyperindextrue

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ifm@mxindy}
% \begin{macro}{\m@mxindytrue}
% \begin{macro}{\m@mxindyfalse}
% \begin{macro}{\xindyindex}
% \begin{macro}{\@@wrspindexhyp}
% Use \cs{xindyindex} when you are going to use the xindy program rather
% than makeindex. hyperrefed entries won't work with xindy.
% The code was supplied by Frederic 
% Connes\footnote{\texttt{frederic@connes.org}} in an email to me on 
% 2006/01/08.
% \changes{v1.61803}{2008/01/30}{Added \cs{xindyindex} (Frederic Connes
%                  mempatch v4.4)}
%    \begin{macrocode}
\newif\ifm@mxindy
\m@mxindyfalse
\newcommand*{\xindyindex}{\m@mxindytrue}
\def\@@wrspindexhyp#1|#2|#3\\{%
  \ifshowindexmark\@showidx{#1}\fi
  \ifx\\#2\\%
    \protected@write\@auxout{}%
      {\string\@@wrindexm@m{\@idxfile}%
        \ifm@mxindy{#1}\else{#1|hyperspindexpage(\thepage)}\fi
      {\@nameuse{the\@sptheidx}}}%
  \else
    \def\Hy@temp@A{#2}%
    \ifx\Hy@temp@A\HyInd@ParenLeft
      \protected@write\@auxout{}%
        {\string\@@wrindexm@m{\@idxfile}%
         \ifm@mxindy{#1|#2}\else{#1|#2hyperspindexpage(\thepage)}\fi
      {\@nameuse{the\@sptheidx}}}%
    \else
      \protected@write\@auxout{}%
        {\string\@@wrindexm@m{\@idxfile}{#1|#2}%
      {\@nameuse{the\@sptheidx}}}%
    \fi
  \fi
  \endgroup
  \@esphack}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
%
% \begin{macro}{\@@wrindexhyp}
% \begin{macro}{\@@wrspindexhyp}
% If the \Lpack{hyperref} package is not being used, or \cs{ifmemhyperindex}
% is false, there is no need
% to clutter up the index files. 
% \changes{v1.61}{2004/03/28}{Declutter index files if hyperref is not used}
% \changes{v1.618}{2005/09/02}{Fixed spaces in non-hyperref index files (mempatch v2.3).
% Reported by Michael W. Daniels.}
%    \begin{macrocode}
\AtBeginDocument{%
  \@ifpackageloaded{hyperref}{}{\memhyperindexfalse}%
%    \end{macrocode}
% If the \Lpack{hyperref} package is not being used, or a hyperindex
% is not required, simplify!
%    \begin{macrocode}
  \ifmemhyperindex\else
    \def\@@wrindexhyp#1||\\{%
      \ifshowindexmark\@showidx{#1}\fi
      \protected@write\@auxout{}%
        {\string\@@wrindexm@m{\@idxfile}{#1}{\thepage}}%
      \endgroup
      \@esphack}%
    \def\@@wrspindexhyp#1||\\{%
      \ifshowindexmark\@showidx{#1}\fi
      \protected@write\@auxout{}%
        {\string\@@wrindexm@m{\@idxfile}{#1}{\@nameuse{the\@sptheidx}}}%
      \endgroup
      \@esphack}%
  \fi
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\see}
% \begin{macro}{\seename}
% \begin{macro}{\seealso}
% \begin{macro}{\alsoname}
% These definitions are taken from the \Lpack{makeidx} package.
%    \begin{macrocode}
\newcommand*{\see}[2]{\emph{\seename} #1}
\newcommand*{\seename}{see}
\newcommand*{\seealso}[2]{\emph{\alsoname} #1}
\newcommand*{\alsoname}{see also}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\citeindexfile}
% For the \Lpack{natbib} package, and possibly other packages that do 
% some special indexing.
%    \begin{macrocode}
\newcommand{\citeindexfile}{\jobname}
\AtBeginDocument{\@ifpackageloaded{natbib}{%
  \def\NAT@index{\index[\citeindexfile]{\NAT@idxtxt}}}{}}

%    \end{macrocode}
% \end{macro}
%
% The next part of the code is essentially the \Lpack{showidx} package.
% I tried putting index entries into marginpars but too many on a page
% led to the `too many floats' problem.
%
% \begin{macro}{\indexmarkstyle}
% \begin{macro}{\@indexbox}
%    \begin{macrocode}
\newtoks\indexmarkstyle
  \indexmarkstyle{\normalfont\footnotesize\ttfamily}
\newinsert\@indexbox
  \dimen\@indexbox\maxdimen

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%    \begin{macrocode}
\begingroup
  \catcode`\@\active
  \expandafter\gdef\csname\string @sanitizeat\endcsname
  {\def @{\char`\@}}
\endgroup

%    \end{macrocode}
%
% \begin{macro}{\@showidx}
%    \begin{macrocode}
\newcommand{\@showidx}[1]{%
  \insert\@indexbox{%
    \@sanitizeat
    \the\indexmarkstyle
    \hsize\marginparwidth
    \hangindent\marginparsep \parindent\z@
    \everypar{}\let\par\@@par \parfillskip\@flushglue
    \lineskip\normallineskip
    \baselineskip .8\normalbaselineskip\sloppy
    \raggedright \leavevmode
    \vrule \@height .7\normalbaselineskip \@width \z@\relax
      #1\relax
    \vrule \@height \z@ \@depth .3\normalbaselineskip \@width \z@\relax
  }%
  \ifhmode\penalty\@M \hskip\z@skip\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@leftidx}
% \begin{macro}{\@rightidx}
%    \begin{macrocode}
\newcommand{\@leftidx}{\hskip-\marginparsep \hskip-\marginparwidth}
\newcommand{\@rightidx}{\hskip\columnwidth \hskip\marginparsep}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@mkidx}
%    \begin{macrocode}
\newcommand{\@mkidx}{\vbox to \z@{%
  \rlap{%
    \if@twocolumn
      \if@firstcolumn \@leftidx \else \@rightidx \fi
    \else
      \if@twoside
        \ifodd\c@page \@rightidx \else \@leftidx \fi
      \else
        \@rightidx
      \fi
    \fi
    \box\@indexbox
  }%
  \vss}}

%    \end{macrocode}
% \end{macro}
%
% \section{Page bottom}
%
% \begin{macro}{\raggedbottom}
% \begin{macro}{\flushbottom}
% \begin{macro}{\@texttop}
% \begin{macro}{\mem@flshbot}
% These kernel macros need changing because of the new \cs{@indexbox} 
% marginal insert.
% \changes{v3.7d}{2015/04/21}{It makes more sense to explicitly call
% \cs{flushbottom} than just let \cs{@texttop}. We also add a switch
% macro to see if \cs{flushbottom} is active. \cs{raggedbottom} and
% \cs{sloppybottom} sets the switch to false}
%    \begin{macrocode}
\renewcommand{\raggedbottom}{%
  \def\mem@flshbot{01}%
  \def\@textbottom{\vskip\z@ plus.0001fil}%
  \let\@texttop\@mkidx}
\renewcommand{\flushbottom}{%
  \def\mem@flshbot{00}%
  \let\@textbottom\relax
  \let\@texttop\@mkidx}
\let\@texttop\@mkidx
\flushbottom

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsection{Widows and sloppybottom}
%
%    There was a discussion \textit{widow handling?} on CTT in 
% May 2006. \texttt{ivowel@gmail.com} wrote
% \begin{quote}
% in experimenting with raggedbottom, widowpenalty, and clubpenalty,
% I think that I have not found a solution that strikes me as 
% particularly desirable. I think what I would really like is that
% widows (i.e., left-over single lines that begin on the following
% page) are resolved not by pushing one extra line from the same
% paragraph also onto the next page, but by stretching the
% \cs{textheight} to allow this one extra at the bottom of the
% same page.
% \end{quote}
% Donald Arseneau, as he so often does, came up with a solution he
% termed \cs{sloppybottom}. Here is a generalised version.
%
% \begin{macro}{\sloppybottom}
% \cs{sloppybottom} allows an extra line on a page to save a widow.
% You must increase the \cs{topskip} (by 60 percent is reasonable) and this
% will push the text lower on the page. Run \cs{checkandfixthelayout}
% after the change. For example:
% \begin{verbatim}
% \setlength{\topskip}{1.6\topskip}
% \checkandfixthelayout
% \sloppybottom
% ...
% \end{verbatim}
% \changes{v1.61803}{2008/01/30}{Added \cs{sloppybottom} (mempatch v4.6)}
% \changes{v3.7d}{2015/04/21}{Added flush bottom switch}
%    \begin{macrocode}
\newcommand*{\sloppybottom}{%
  \def\mem@flshbot{01}%
  \def\@textbottom{\vskip \z@ \@plus.0001fil \@minus .95\topskip}%
  \topskip=1\topskip \@plus 0.625\topskip \@minus .95\topskip
  \def\@texttop{\vskip \z@ \@plus -0.625\topskip \@minus -0.95\topskip}}

%    \end{macrocode}
% \end{macro}
%
%
%
%
% \section{Glossaries}
%
% Standard LaTeX provides little and insufficient support for
% glossaries, just a \cs{makeglossary} and \cs{glossary} commands.
% This class does somewhat better. The code follows along the lines
% of that for indexes.
% \changes{v1.618}{2005/09/25}{Added glossary code}
%
%
% \begin{macro}{\ifonecolglossary}
% \begin{macro}{\onecolglossarytrue}
% \begin{macro}{\onecolglossaryfalse}
% TRUE for a one column glossary, otherwise its two column.
%    \begin{macrocode}
\newif\ifonecolglossary
  \onecolglossarytrue
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\onecolglossary}
% \begin{macro}{\twocolglossary}
% \changes{v1.61803}{2008/01/30}{Added \cs{onecolglossary} and \cs{twocolglossary}}
%    \begin{macrocode}
\newcommand*{\onecolglossary}{\onecolglossarytrue}
\newcommand*{\twocolglossary}{\onecolglossaryfalse}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{environment}{theglossary}
% The environment \texttt{theglossary} is used for glossaries.
% It makes a glossary with one or two columns, headed by a chapter-like
% title.
%    \begin{macrocode}
\newenvironment{theglossary}{%
  \if@twocolumn
    \@restonecolfalse
  \else
    \@restonecoltrue
  \fi
  \ifonecolglossary
    \onecolumn
    \chapter*{\glossaryname}
    \preglossaryhook
  \else
    \setlength{\columnseprule}{\glossaryrule}
    \setlength{\columnsep}{\glossarycolsep}
    \twocolumn[\@makeschapterhead{\glossaryname}
               \preglossaryhook]%
  \fi
  \glossarymark
  \ifnoglossaryintoc\else
    \phantomsection
    \addcontentsline{toc}{chapter}{\glossaryname}
  \fi
  \thispagestyle{chapter}\parindent\z@
  \parskip\z@ \@plus .3\p@\relax
  \begintheglossaryhook}%
  {\atendtheglossaryhook\if@restonecol\onecolumn\else\twocolumn\fi}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\begintheglossaryhook}
% \begin{macro}{\atendtheglossaryhook}
% Two vacuous macros called as the last thing by \verb?\begin{theglossary}?
% and the first thing by \verb?\end{theglossary}? These could be used,
% for example, to insert another kind of environment.
%    \begin{macrocode}
\newcommand*{\begintheglossaryhook}{}
\newcommand*{\atendtheglossaryhook}{}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\preglossaryhook}
% A vacuous macro called after the title is set and before the listing
% starts. The user can modify it to, for example, add some explanatory
% text.
%    \begin{macrocode}
\newcommand*{\preglossaryhook}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifnoglossaryintoc}
% \begin{macro}{\glossaryintoc}
% \begin{macro}{\noglossaryintoc}
% Flag and declarations to control whether or not the glossary
% title is added to the ToC. Default is to put the title
% in the ToC.
%    \begin{macrocode}
\newif\ifnoglossaryintoc
\newcommand*{\glossaryintoc}{\noglossaryintocfalse}
\newcommand*{\noglossaryintoc}{\noglossaryintoctrue}
  \glossaryintoc

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\glossarycolsep}
% \begin{macro}{\glossaryrule}
% When the glossary is two column these lengths control the
% column separation and the width of a rule between the columns.
%    \begin{macrocode}
\newdimen\glossarycolsep \glossarycolsep=35\p@
\newdimen\glossaryrule \glossaryrule=0\p@
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\glossaryspace}
% Vertical space between `letter blocks' in the glossary.
% Note that this is a macro, not a length.
%    \begin{macrocode}
\newcommand*{\glossaryspace}{%
    \par \vskip 1.0\onelineskip \@plus 5\p@ \@minus3\p@\relax}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\makeglossary}
% The preamble command to set up a glossary. Output is to the
% \file{\#1.glo} file. We need the \cs{providecommand} in case \cs{nofiles}
% has been called before the class. \cs{makeglossary} sets up several 
% file-specific macros.
%    \begin{macrocode}
\providecommand*{\makeglossary}{}
\renewcommand*{\makeglossary}[1][\jobname]{%
  \makememglossaryhook
  \@namedef{memglsact#1}{@}%           actual
  \@namedef{memglsnx#1}{}%             no ref
  \@namedef{memglsn#1}{\thepage}%      num  by page
  \@namedef{memglsnf#1}{|memjustarg}%  no special number format | emacs
  \if@filesw \expandafter\newwrite\csname #1memglofile\endcsname
    \expandafter\immediate\openout \csname #1memglofile\endcsname #1.glo\relax
    \typeout{Writing glossary file #1.glo }%
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makememglossaryhook}
% A vacuous macro called at the start of the \cs{makeglossary} code.
% It is redefinable to do something useful.
%    \begin{macrocode}
\newcommand*{\makememglossaryhook}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\glossary}
% The user command for a raw glossary item. The full calling
% sequence looks like: \\
% \cs{glossary}\oarg{file}\parg{key}\marg{term}\marg{desc} \\
% but most is accomplished by lower level macros. It calls
% \cs{@glossary} to handle the first optional argument.
%    \begin{macrocode}
  \def\glossary{\@bsphack%
    \@ifnextchar [{\@glossary}{\@glossary[\jobname]}}%
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@glossary}
% \cs{@glossary}\oarg{file} handles the first of the \cs{glossary} optional
% arguments, even though the calling sequence looks like: \\
% \cs{@glossary}\oarg{file}\parg{key}\marg{term}\marg{desc}. \\
% It calls \cs{@@glossary} to handle the second optional argument
% and the rest.
%    \begin{macrocode}
\def\@glossary[#1]{%
  \@ifnextchar ({\@@glossary[#1]}{\@@glossary[#1]()}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@@glossary}
% The base macro for \cs{glossary}. Its real calling sequence is: \\
% \cs{@@glossary}\oarg{file}\parg{key}\marg{term}\marg{desc}. \\
% Provided the glossary output file has been set up it calls
% \cs{@wrglom@m} to write the data, otherwise it throws away its
% arguments.
%    \begin{macrocode}
\def\@@glossary[#1](#2)#3#4{%
  \@ifundefined{#1memglofile}{%
    \begingroup
    \@sanitize
    \endgroup
    \@esphack%
   }{%
    \def\memglofile{#1}%
    \begingroup
    \@sanitize
%    \end{macrocode}
% Use the correct key, \meta{key} if given, otherwise \meta{term}.
%    \begin{macrocode}
    \ifx\@empty#2\@empty
      \@wrglom@m{#3}{#3}{#4}%
    \else
      \@wrglom@m{#2}{#3}{#4}%
    \fi}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@wrglom@m}
% \cs{@wrglom@m}\marg{key}\marg{term}\marg{desc} writes its three arguments,
% plus the \meta{ref} and the \meta{num} to the \file{aux} file as the
% arguments to the \cs{@@wrglom@m} macro.
%    \begin{macrocode}
\newcommand{\@wrglom@m}[3]{%
  \protected@write\@auxout{}%
    {\string\@@wrglom@m{\memglofile}{#1}{#2}{#3}{\@nameuse{memglsnx\memglofile}}{\@nameuse{memglsn\memglofile}}}%
  \endgroup
  \@esphack}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@@wrglom@m}
% The calling sequence looks like: \\
% \cs{@@wrglom@m}\marg{file}\marg{key}\marg{term}\marg{desc}\marg{ref}\marg{num} \\
% but is actually really only \\
% \cs{@@wrglom@m}\marg{file} \\
% It saves the output file identifier in \cs{memglofile} and 
% \meta{file} as \cs{m@mgf}, then calls \cs{memwritetoglo}
% to handle the remaining `arguments'.
%    \begin{macrocode}
\newcommand{\@@wrglom@m}[1]{\begingroup
  \def\memglofile{\@nameuse{#1memglofile}}%
  \def\m@mgf{#1}%
  \@sanitize
  \memwritetoglo}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\memwritetoglo}
% \begin{macro}{\@ctualm@mwritetoglo}
% \cs{memwritetoglo}\marg{key}\marg{name}\marg{desc}\marg{ref}\marg{num}
% will, at an appropriate time write the raw glossary data to the
% appropriate \file{glo} file.
%
%    The \file{aux} file is read twice, once as one of the initial
% actions at the start of the \texttt{document} environment, and again
% at the end of the \texttt{document} environment. The raw glossary
% data must only be written once from the \file{aux} to the \file{glo} file.
% Initially \cs{memwritetoglo} is defined to do nothing, then, after the
% \file{aux} file has been read at the beginning is redefined to do
% its writing. 
%
% The Makeindex program expects its input to be like: \\
% \verb?\glosaryentry{key@data}{num}?
% Very cunningly the raw data is fed to the \file{glo}
% file looking like: \\
% \verb?\glossaryentry{key@{\memgloterm{term} \memglodesc{desc} \memgloref{ref}}{num}? \\
% which as far as Makeindex is concerned is simply: \\
% \verb?\glosaryentry{key@{data}}{num}? \\
% (note where all the braces are).
%
%    \begin{macrocode}
\newcommand{\memwritetoglo}[5]{\endgroup}
\newcommand{\@ctualm@mwritetoglo}[5]{%
  \immediate\write \memglofile{\string\glossaryentry{#1\@nameuse{memglsact\m@mgf}
                    {\string\memgloterm{#2}}{\string\memglodesc{#3}}
                    {\string\memgloref{#4}}\@nameuse{memglsnf\m@mgf}}{#5}}%
  \endgroup}
\AtBeginDocument{%
  \let\memwritetoglo\@ctualm@mwritetoglo}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\changeglossactual}
% \begin{macro}{\changeglossref}
% \begin{macro}{\changeglossnum}
% \begin{macro}{\changeglossnumformat}
% There are internal macros that are file-dependant, their names
% being constructed from the file name plus a fixed name. The
% \cs{makeglossary} command initializes these but the user may well need
% to change them. In the macros below, \texttt{...actual} refers to the
% actual character in a Makeindex configuration file (default \texttt{@}),
% \texttt{...ref} to the \meta{ref} glossary argument, \texttt{...num}
% to the meta{num} argument (default \cs{thepage}) and \texttt{...numformat}
% to the Makeindex encapsulating command. Example uses are:
% \begin{verbatim}
% \changeglossactual[file]{?}
% \changeglossref[file]{\thepage}
% \changeglossnum[file]{\thesection}
% \changeglossnumref[file]{|textbf}
% \end{verbatim}
%    \begin{macrocode}
\newcommand*{\changeglossactual}[2][\jobname]{%
  \@namedef{memglsact#1}{#2}}
\newcommand*{\changeglossref}[2][\jobname]{%
  \@namedef{memglsnx#1}{#2}}
\newcommand*{\changeglossnum}[2][\jobname]{%
  \@namedef{memglsn#1}{#2}}
\newcommand*{\changeglossnumformat}[2][\jobname]{%
  \@namedef{memglsnf#1}{#2}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\glossitem}
% The final sorted glossary data is in the form: \\
% \cs{glossitem}\marg{term}\marg{desc}\marg{ref}\marg{num} \\
% The definition here does little.
%    \begin{macrocode}
\newcommand{\glossitem}[4]{#1 #2 #3 #4\par}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\memgloterm}
% \begin{macro}{\memglodesc}
% \begin{macro}{\memgloref}
% \begin{macro}{\memglonum}
% These are wrappers round the \meta{term}, \meta{desc}, \meta{ref} and
% \meta{num} elements in the final data. They are vacuous to start with.
%    \begin{macrocode}
\newcommand*{\memgloterm}[1]{#1}
\newcommand*{\memglodesc}[1]{#1}
\newcommand*{\memgloref}[1]{#1}
\newcommand*{\memglonum}[1]{#1}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\printglossary}
% \cs{printglossary}\oarg{file} inputs the glossary \file{gst} file.
%    \begin{macrocode}
\newcommand*{\printglossary}[1][\jobname]{\@input@{#1.gls}}

%    \end{macrocode}
% \end{macro}
%
%
%
%      
% \section{Notes/Marginalia}
%
%
% \subsection{A simple interface for specifying locations}
%
% \changes{v1.61803398d}{2010/01/25}{added}
%
% The \Lpack{memoir} class as of December 2009 supports \cs{marginpar},
% \cs{sidepar}, and \cs{sidebar} for placing information in a margin.
% The means of specifying in which margin the information should be put
% is different for each of these. Here a consistent location interface 
% is provided for all marginalia.
%
%
% \begin{macro}{\m@msetm@argin}
% \begin{macro}{\m@mm@argin}
% A workhorse macro for setting a margin placement code. The argument
% may be one of: left, right, outer, or inner, with \cs{m@mm@argin} defined
% as the corresponding codes of 0, 1, 2, or 3. An unkown argument is coded
% as a negative number.
%    \begin{macrocode}
\newcommand*{\m@msetm@argin}[1]{%
  \def\@tempa{#1}\def\@tempb{left}%
  \ifx\@tempa\@tempb
    \def\m@mm@argin{0}%
  \else
    \def\@tempb{right}%
    \ifx\@tempa\@tempb
      \def\m@mm@argin{1}%
    \else
      \def\@tempb{outer}%
      \ifx\@tempa\@tempb
        \def\m@mm@argin{2}%
      \else
        \def\@tempb{inner}%
        \ifx\@tempa\@tempb
          \def\m@mm@argin{3}%
        \else
          \def\m@mm@argin{-1}%
        \fi
      \fi
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ifmemtortm}
% \begin{macro}{\memtortmtrue}
% \begin{macro}{\memtortmfalse}
% A flag set TRUE if the marginalia is to be moved to the right of the text
% and FALSE if it is to be moved to the left of the text. 
%    \begin{macrocode}
% MEM-TO-RighT-Margin
\newif\ifmemtortm
  \memtortmtrue
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mwhich@margin}
% \cs{m@mwhich@margin}\marg{code} sets \cs{ifmemtortm} TRUE or FALSE depending
% on the value of \meta{code} (0 to 3), and other factors.
% \begin{description}
% \item[Two column document] If the first column, to the left, otherwise
%                            to the right, irrespective the document being
%                            one- or two-side.
% \item[One sided document] If code = 0 (left), to the left, otherwise 
%  (code = 1 (right), 2 (outer), 3 (inner)) to the right.
% \item[Two sided document] depends on whether a recto or verso page:
%    \begin{description}
%    \item[Recto (odd) page] right if code = 1 (right) or 2 (outer), otherwise
%                            left.
%    \item[Verso (even) page] left if code = 0 (left) or 2 (outer), otherwise
%                             right.
%    \end{description}
% \end{description}
%
% 
%    \begin{macrocode}
\newcommand*{\m@mwhich@margin}[1]{%
  \memtortmtrue
  \if@twocolumn
    \if@firstcolumn% left
      \memtortmfalse
    \else%           right
      \memtortmtrue
    \fi
  \else
    \if@twoside
      \checkoddpage
      \ifcase #1\relax% 0 left
        \memtortmfalse
      \or%                   1 right
        \memtortmtrue
      \or%                   2 outer
        \ifoddpage
          \memtortmtrue
        \else
          \memtortmfalse
        \fi
      \or%                 3 inner
        \ifoddpage
          \memtortmfalse
        \else
          \memtortmtrue
        \fi
      \fi% end ifcase
    \else%           oneside
      \ifnum #1=\z@% 0   left, all else right       
        \memtortmfalse
      \else
        \memtortmtrue
      \fi
    \fi% end if@twoside
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
%    
% \subsection{Marginpars}
%
% A \cs{marginpar} is a kind of floating object --- you can't control
% exactly where it will go. There is one problem with the kernel
% definition of \cs{marginpar} in that sometimes a \cs{marginpar} may
% end up on the wrong side of the page. The following is an attempt
% to fix that using the odd/even page check provided as part of
% the class.
% 
% \begin{macro}{\@addmarginpar}
% The part of the code for \cs{marginpar} that deals with deciding which
% side of the page it should be printed on is \cs{@addmarginpar}, buried
% away in the kernel's \texttt{output} routine. A couple of minor changes are made
% to the kernel code. The first is at the beginning where I have added
% the \cs{checkoddpage} page checking code.
% \changes{v1.618033988d}{2010/02/26}{fixed twoside -> left marrgin
% bug, reported by Frank Wikstr\"om, on private email}
% In the new margin placement syntax, there is a new syntax: always
% left, in twoside mode. This cannot be implemented using the normal
% marginpar placement controls, so we have to add our own.
%    \begin{macrocode}
\def\@addmarginpar{%
    \checkoddpage
%    \end{macrocode}
% Continue with the kernel code. The twocolumn stuff in the new syntax
% scheme is the same as in the kernel.
%    \begin{macrocode}
    \@next\@marbox\@currlist{\@cons\@freelist\@marbox
    \@cons\@freelist\@currbox}\@latexbug\@tempcnta\@ne
    \if@twocolumn
        \if@firstcolumn \@tempcnta\m@ne \fi
    \else
%    \end{macrocode}
% \changes{v1.618033988d}{2010/02/26}{added as a part of the above
% mentioned fix}
% Here we add the new stuff. We make use of the fact that we have
% hidden all the page checking in \verb?\m@mwhich@margin?, and we only
% fire it of if we know \verb?\marginparmargin? have been used (via
% \verb?\ifm@msetmp?). 
%    \begin{macrocode}
      \ifm@msetmp%
        % \@tempcnta > 0 => right side of page
        % \@tempcnta < 0 => left side of page
        \m@mwhich@margin{\m@mmpar@margin}% set left or right margin
        \ifmemtortm%
          \@tempcnta\@ne\relax%
         \else% 
          \@tempcnta\m@ne\relax%
        \fi%
      \else%
        \if@mparswitch
%    \end{macrocode}
% The next line, reading \\
% \verb?\ifodd\c@page \else\@tempcnta\m@ne \fi? \\
% is where the odd/even page checking is done in the kernel code. I
% replace it with my code, and then continue with the kernel.
%    \begin{macrocode}
          \ifoddpage \else \@tempcnta\m@ne \fi%
        \fi%
        \if@reversemargin \@tempcnta -\@tempcnta \fi%
      \fi%
    \fi%
    \ifnum\@tempcnta <\z@  \global\setbox\@marbox\box\@currbox \fi
    \@tempdima\@mparbottom
    \advance\@tempdima -\@pageht
    \advance\@tempdima\ht\@marbox
    \ifdim\@tempdima >\z@
%    \end{macrocode}
% The next line in the kernel reads: \\
% \verb?\@latex@warning@no@line {Marginpar on page \thepage\space moved}? \\
% I have changed the warning message to give the user an indication
% of the severity of the move. Then follow the kernel on to the end.
%    \begin{macrocode}
      \@latex@warning@no@line {Marginpar on page 
                               \thepage\space moved by \the\@tempdima}%
    \else
      \@tempdima\z@
    \fi
    \global\@mparbottom\@pageht
    \global\advance\@mparbottom\@tempdima
    \global\advance\@mparbottom\dp\@marbox
    \global\advance\@mparbottom\marginparpush
    \advance\@tempdima -\ht\@marbox
    \global\setbox \@marbox
                   \vbox {\vskip \@tempdima
                          \box \@marbox}%
    \global \ht\@marbox \z@
    \global \dp\@marbox \z@
    \kern -\@pagedp
    \nointerlineskip
    \hb@xt@\columnwidth
      {\ifnum \@tempcnta >\z@
          \hskip\columnwidth \hskip\marginparsep
       \else
          \hskip -\marginparsep \hskip -\marginparwidth
       \fi
       \box\@marbox \hss}%
    \nointerlineskip
    \hbox{\vrule \@height\z@ \@width\z@ \@depth\@pagedp}%
}

%    \end{macrocode}
% \end{macro}
%
% \subsubsection{Marginpar -- margin interface}
%
% The `standard' method of specifying the desired margin for a \cs{marginpar}
% consists of the two macros \cs{normalmarginpar} and \cs{reversemarginpar}, 
% whose effects depend on whether the document is one- or two-sided, whether
% the page is recto or verso, and if it is set in one- or two-columns.
%
% \begin{macro}{\ifm@msetmp}
% \begin{macro}{m@msetmptrue}
% \begin{macro}{m@msetmpfalse}
% TRUE if the macro \cs{marginparmargin} has been called.
%    \begin{macrocode}
\newif\ifm@msetmp
  \m@msetmpfalse
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\marginparmargin}
% \begin{macro}{\m@mmpar@margin}
% The user command for specifying the desired margin for \cs{marginpar}s.
% The code is stored as \cs{m@mmpar@margin}, and \cs{setmpbools} is called to
% convert to the regular \cs{marginpar} booleans.
%    \begin{macrocode}
\newcommand*{\marginparmargin}[1]{%
  \m@msetmptrue
  \m@msetm@argin{#1}%
  \ifnum\m@mm@argin<\z@
    \@memwarn{Bad \string\marginparmargin\space argument `#1'\MessageBreak
              set to `outer'}%
    \gdef\m@mmpar@margin{2}%   set as outer
  \else
    \global\let\m@mmpar@margin\m@mm@argin
  \fi
  \setmpbools}

%    \end{macrocode}
% \changes{v3.6k}{2013/05/14}{Added default \cs{m@mmpar@margin}}
%    \begin{macrocode}
\if@twocolumn\else
  \if@twoside
    \def\m@mmpar@margin{2}
  \else
    \def\m@mmpar@margin{1}
  \fi
\fi

%    \end{macrocode}
% 
%
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setmpbools}
% Given \cs{m@mmpar@margin}, \cs{setmpbools} sets the corresponding 
% \cs{marginpar} location booleans.
%    \begin{macrocode}
\newcommand*{\setmpbools}{%
  \if@twoside
    \@mparswitchtrue
  \else
    \@mparswitchfalse
  \fi
  \ifcase\m@mmpar@margin\relax% 0 left
    \@reversemargintrue%  \sideparswitchfalse \reversesidepartrue
  \or%                    1 right
    \@reversemarginfalse% \sideparswitchfalse \reversesideparfalse
  \or%                    2 outer
    \@reversemarginfalse% \sideparswitchtrue \reversesideparfalse
  \or%                    3 inner
    \@reversemargintrue% \sideparswitchtrue \reversesidepartrue
  \fi}

%    \end{macrocode}
% \end{macro}
%
%    \begin{macrocode}
\newcommand*{\m@msetmpcodes}{%
  \if@mparswitch%  2 sided
    \if@reversemargin% inner
      \def\m@mmpar@margin{3}%
    \else% outer
      \def\m@mmpar@margin{2}%
    \fi
  \else% 1 sided
    \if@reversemargin% left
      \def\m@mmpar@margin{0}%
    \else% right
      \def\m@mmpar@margin{1}%
    \fi
  \fi}

%    \end{macrocode}
%
% \subsection{A fixed marginpar}
%
%
% Introduce a non-floating marginpar.
% \changes{v1.4}{2003/11/22}{Added \cs{sidepar} and supports for a fixed 
%                            marginpar (from patch v1.8)}
%
% \begin{macro}{\parnopar}
% From \theTeXbook{} Exercise 14.15. It creates an `invisible' end/start paragraph,
% and may be used for getting \TeX{} to try a pagebreak.
% 
% Roman Eisle (email 2008/09/05) found a problem with the original
% definition as its effects continued on: \\
% \verb?\newcommand{\parnopar}{\parfillskip=0pt\par\parskip=0pt\noindent}? \\
% and he supplied the fix used below.
%
% \changes{v1.6180339c}{2008/12/24}{Changed \cs{parnopar} to limit its effect
% to a single instance}
% \changes{v3.6e}{2010/08/17}{made \cs{parnopar} sit inside a group}
%    \begin{macrocode}
\newcommand*{\parnopar}{{\parfillskip=0pt\par\parskip=0pt\noindent}} 

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\ifreversesidepar}
% \begin{macro}{\ifsideparswitch}
% \changes{v1.61803398d}{2010/01/25}{Added footnote explaining the default}
% Analogues of \cs{marginpar} controls.\footnote{Note that for some
% now forgotten reason the default placement of the \cs{sidepar} is
% reversed in comparison to say \cs{marginpar}. As not to change
% existing documents, we have left the default like this.}
%    \begin{macrocode}
\newif\ifreversesidepar
%  \reversesideparfalse
  \reversesidepartrue
\newif\ifsideparswitch
  \sideparswitchfalse
\if@twoside \sideparswitchtrue \fi

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \changes{v1.61803398d}{2010/01/25}{Added}
% \begin{macro}{\ifm@msetsp}
% \begin{macro}{\m@msetsptrue}
% \begin{macro}{\m@msetspfalse}
%    \begin{macrocode}
%% true if \sideparmargin used
\newif\ifm@msetsp
  \m@msetspfalse
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \changes{v1.61803398d}{2010/01/25}{Added}
% \begin{macro}{\sideparmargin}
% \begin{macro}{\m@mspar@margin}
% User command for specifing the margin for \cs{sidepar}s.
% The numeric code is stored in \cs{m@mspar@margin}.
%    \begin{macrocode}
\newcommand*{\sideparmargin}[1]{%
  \m@msetsptrue
  \m@msetm@argin{#1}%
  \ifnum\m@mm@argin<\z@
    \@memwarn{Bad \string\sideparmargin\space argument `#1'\MessageBreak
              set to `outer'}%
    \gdef\m@mspar@margin{2}%   set as outer
  \else
    \global\let\m@mspar@margin\m@mm@argin
  \fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \changes{v1.61803398d}{2010/01/25}{Added}
% \begin{macro}{\m@msidepar@left}
% \begin{macro}{\m@msidepar@right}
% Move a \cs{sidepar} into the left/right margin.
%    \begin{macrocode}
\newcommand*{\m@msidepar@left}{%
  \@tempdimc\marginparwidth
  \advance\@tempdimc\marginparsep
  \kern-\@tempdimc}
\newcommand*{\m@msidepar@right}{%
  \@tempdimc\columnwidth
  \advance\@tempdimc\marginparsep
  \kern\@tempdimc}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \changes{v1.61803398d}{2010/01/25}{Added}
% \begin{macro}{\setspbools}
% Given the \cs{m@mspar@margin} code, calculates the corresponding
% \cs{sidepar} location booleans.
%    \begin{macrocode}
\newcommand*{\setspbools}{%
    \ifcase\m@mspar@margin\relax% 0 left
      \sideparswitchfalse \reversesidepartrue
    \or%                    1 right
      \sideparswitchfalse \reversesideparfalse
    \or%                    2 outer
      \sideparswitchtrue \reversesideparfalse
    \or%                    3 inner
      \sideparswitchtrue \reversesidepartrue
    \fi}

%    \end{macrocode}
% \end{macro}
% \changes{v1.61803398d}{2010/01/25}{Added}
% \begin{macro}{\setspcode}
% Given the \cs{sidepar} location booleans, sets up the corresponding
% \cs{m@mspar@margin} numeric codes.
%    \begin{macrocode}
\newcommand*{\setspcode}{%
  \ifsideparswitch
    \ifreversesidepar
      \def\m@mspar@margin{3}% inner
    \else
      \def\m@mspar@margin{2}% outer
    \fi
  \else
    \ifreversesidepar
      \def\m@mspar@margin{0}% left
    \else
      \def\m@mspar@margin{1}% right
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
% \changes{v1.61803398d}{2010/01/25}{Added}
% \begin{macro}{\sideparfont}
% \begin{macro}{\sideparform}
% The font to be used for \cs{sidepar}s and the alignment for it.
% \changes{v1.61803398d}{2010/02/04}{Changed default font}
% \changes{v1.61803398d}{2010/02/05}{added \cs{sideparform}} 
% The \cs{sideparform} holds code that will set the text flush against
% the edge of the text.\footnote{One might consider redefining this
% using the \cs{RaggedRight} and \cs{RaggedLeft} macros from the
% ragged2e package.}
%    \begin{macrocode}
\newcommand*{\sideparfont}{\normalfont\normalsize}
\newcommand*{\sideparform}{\ifmemtortm\raggedright\else\raggedleft\fi}
%    \end{macrocode}
% \end{macro}
% \end{macro}

%
% \begin{macro}{\sidepar}
% \begin{macro}{\@sidepar}
% \begin{macro}{\sideparvshift}
% \cs{sidepar}\oarg{left}\marg{right} (per \cs{marginpar}).
% Sidepars had a nasty habit of moving up or down depending on whether 
% characters in the sidepar and the main text line have ascenders and/or 
% descenders. The length \cs{sideparvshift} was provided to
% enable adjustments. This is Dan Luecking's modified version of my
% original code  
% (CTT \textit{Re: sidepars drift up a point}, 2006/04/11) which does a much
% better job,
% and the default for \cs{sideparvshift} is now 0pt.
% \changes{v1.61803}{2008/01/30}{Fixed \cs{sidepars} from moving up and down
%     (mempatch v4.5)}
% \changes{v1.61803}{2008/01/30}{Normalised font in \cs{@sidepar} 
%          (mempatch v4.9)}
% \changes{v1.61803398d}{2010/01/25}{\cs{@sidepar} changed to fit the
% interface just added}
% \changes{v1.61803398d}{2010/02/05}{added \cs{sideparform}}
% \changes{v3.6h}{2010/10/29}{The inserted text should have the same
% baseline stretch as the rest of the page notes.}
%    \begin{macrocode}
\newcommand{\sidepar}{\@dblarg{\@sidepar}}
\long\def\@sidepar[#1]#2{\leavevmode\@bsphack\strut\vadjust{%
  \checkoddpage
  \ifm@msetsp% \sideparmargin used
%%%%    \setspbools
  \else% \sideparmargin not used, set the \m@mspar@margin code
    \setspcode
  \fi
  \rlap{\kern-\parindent
    \m@mwhich@margin{\m@mspar@margin}% set left or right margin
    \ifmemtortm
      \m@msidepar@right
    \else
      \m@msidepar@left
    \fi
  \setbox0=\vtop to 0pt{%
    \begin{minipage}[t]{\marginparwidth}%
      \def\baselinestretch{\m@m@footnote@spacing}%
      \sideparform\sideparfont%
      \ifmemtortm #2\else #1\fi
    \end{minipage}%
    \vss}%
  \vtop to 0pt{\kern\sideparvshift% default should be 0pt
    \kern-\dp\strutbox
    \kern-\ht0
    \box0 \vss}}}%
  \@esphack}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% Vertical shift for sidepar to align with text line
%    \begin{macrocode}
\newlength{\sideparvshift}
\setlength{\sideparvshift}{0pt}
%%%%  \setlength{\sideparvshift}{-2.08ex}% seems to work for all font sizes

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Sidebars}
%
% \changes{v1.1}{2002/03/19}{Added experimental code for sidebars}
%
% On 2002/10/22 Donald Arseneau posted the following code to \ctt{} for adding
% sidebars to plain TeX.
% \begin{verbatim}
% \newinsert\sideins
% \skip\sideins=0pt
% \count\sideins=0
% \dimen\sideins=2in
% 
% \def\sidebarvsep{25pt}
% \def\sidebarhsep{15pt}
% 
% \let\mainpagecontents\pagecontents
% 
% \def\sidecontents{%
%   \ifvoid\sideins\else
%       {\advance\hsize\sidebarhsep
%        \moveright\hsize \vtop to0pt{%
%        \vskip-\sidebarvsep \vskip\topskip % offset by difference
%        \unvbox\sideins \vss}%
%     }\fi}
% \def\pagecontents{\sidecontents\mainpagecontents}
% \long\def\sidebar#1{
%   \insert\sideins{%
%     \splittopskip\sidebarvsep\relax
%     \hsize 1.5in \rightskip=0pt plus 20pt \it
%     \noindent \vbox to \sidebarvsep{}\ignorespaces #1%
%     \ifhmode \unskip\strut\fi \par
%    }%
% }
% 
% \end{verbatim}
%
% The following started off (2002/03/19) as my attempt to rewrite the above 
% into a form suitable for LaTeX, and this class in particular.
%
% Donald Arseneau came up with some improvements to my sidebar code. 
% The impetus
% for this came from a CTT thread, \textit{whitespace after my command}, 
% 2006/11/30 and earlier. In email to me on 2006/11/30 he said:
% \begin{quotation}
%    For \Lpack{memoir} \cs{sidebar}, it seems the rules are expanding
% to fill the space for the sidebar, so here is my suggested change
% to \cs{sidecontents}.
%
%    It occurs to me that a separate \cs{sidetsep} (or \cs{sidetopsep})
% would be more valuable than having an explicit 1\cs{onelineskip}.
%
%   I grouped common code into two macros, and altered \cs{sidebarform} too.
% \end{quotation}
%
% Since then we have been going back and forth, with the result that
% practically all the complex code is Donald's.
% \changes{v1.61803}{2008/01/30}{Major rewrite of \cs{sidebar} code
%                 (mempatch v4.6 and v4.9)}
%
%
% \begin{macro}{\sideins}
% Create a new insert called \cs{sideins}, which also creates a corresponding
% skip, count, dimen, and box. \\
% \verb?\skip\sideins? is the extra vertical space to allow on the page for 
% the insert, \\
% \verb?\count\sideins? is the magnification factor for page breaking, \\
% \verb?\dimen\sideins? is the maximum insertion size (height) per page, \\
% and the inserted material will be in \verb?\box\sideins? when a page is output.
%    \begin{macrocode}
\newinsert\sideins
  \skip\sideins=0pt
  \count\sideins=0

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sidebartopsep}
% Separation at the top of a sidebar.
%    \begin{macrocode}
\newlength{\sidebartopsep}
  \setlength{\sidebartopsep}{0pt}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\setsidebarheight}
% The macro \cs{setsidebarheight}\marg{length} sets the total
% height of sidebars on a page to \meta{length}.
% This is an interface for controlling \verb?\dimen\sideins? properly,
% taking account of \cs{topskip} and the sidebar font size (and therefore
% should be invoked \emph{after} declaring \cs{sidebarfont}).
%
%    Note that \cs{sidebartopsep} is \emph{not} included as part of the
% allocated height.
%    \begin{macrocode}
\newcommand{\setsidebarheight}[1]{%
  \setlength{\dimen\sideins}{#1}%
  \advance\dimen\sideins-\topskip
  \advance\dimen\sideins\ht\strutbox}

%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\sidebarhsep}
% \begin{macro}{\sidebarvsep}
% \begin{macro}{\sidebarwidth}
% The length \cs{sidebarhsep} is the gap between the typeblock and the sidebar.
% \cs{sidebarvsep} is the vertical gap between sidebars on a page.
% The maximum number of sidebar lines on a page is 
% \verb?1 + (\dimen\sideins - \sidebarvsep)?, assuming \verb?\dimen\sideins?
% is defined in terms of \cs{onelineskip}.
% The width of the sidebar is \cs{sidebarwidth}.
%    \begin{macrocode}
\newlength{\sidebarhsep}
\newlength{\sidebarvsep}
\newlength{\sidebarwidth}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\sidebarfont}
% The font for typesetting the contents of a sidebar.
% \changes{v1.61803398d}{2010/02/05}{Added a default for \cs{sidebarfont}}
%    \begin{macrocode}
\newcommand{\sidebarfont}{\normalfont\normalsize}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setsidebars}
% \cs{setsidebars}\marg{hsep}\marg{width}\marg{vsep}\marg{topsep}\marg{font}\marg{height}
% sets the main \cs{sidebar} parameters. A \verb?*? argument means leave the
% setting as is.
% \changes{v1.61803}{2008/01/30}{Added \cs{setsidebars} (mempatch v4.6)}
%    \begin{macrocode}
\newcommand*{\setsidebars}[6]{%
  \nametest{#1}{*}\ifsamename\else
    \setlength{\sidebarhsep}{#1}\@memznegtest{\sidebarhsep}%
  \fi
  \nametest{#2}{*}\ifsamename\else
    \setlength{\sidebarwidth}{#2}\@memznegtest{\sidebarwidth}%
  \fi
  \nametest{#3}{*}\ifsamename\else
    \setlength{\sidebarvsep}{#3}\@memnegtest{\sidebarvsep}%
  \fi
  \nametest{#4}{*}\ifsamename\else
    \setlength{\sidebartopsep}{#4}%
  \fi
  \nametest{#5}{*}\ifsamename\else
    \def\sidebarfont{#5}%
  \fi
  \nametest{#6}{*}\ifsamename\else
    \setsidebarheight{#6}%
    \ifdim\dimen\sideins>\z@\else
%%%%      \@memerror{\protect\sidebarheight\space is zero or negative}{\@ehd}%
      \@memwarn{\protect\sidebarheight\space is zero or negative}%
    \fi
  \fi}
\setsidebars{\marginparsep}%          sidebarhsep
            {\marginparwidth}%        sidebarwidth
            {\onelineskip}%           sidebarvsep
            {0pt}%                    sidebartopsep
            {\normalsize\normalfont}% sidebarfont
            {\textheight}%            sidebarheight

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sidebarform}
% \cs{sidebarform} sets the `raggedness' in a sidebar. The current definition
% is less ragged than \cs{raggedright}. Examples: 
% \begin{verbatim}
%  for flushleftright \renewcommand{\sidebarform}{}
%  for raggedleft     \renewcommand{\sidebarform}{\raggedleft}
% \end{verbatim}
% \changes{v1.4}{2003/11/22}{Added \cs{sidebarform} (from patch v1.5)}
% \changes{v1.61803398}{2009/07/18}{Added bidi support to \cs{sidebarform}}
% \changes{v1.61803398d}{2010/02/05}{changed to make the text flush
% against the text}
%    \begin{macrocode}
\newcommand{\sidebarform}{%\rightskip=\z@ \@plus 2em}
  %\memRTLrightskip=\z@ \@plus 2em
  \ifmemtortm\raggedright\else\raggedleft\fi%
  % \ifmemtortm\memRTLrightskip=\z@ \@plus 2em\else\memRTLleftskip=\z@ \@plus 2em\fi
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifsidebaroneside}
% Flag for oneside.
% \changes{v1.61}{2004/04/05}{Added \cs{ifsidebaroneside}}
% \changes{v1.61803398d}{2010/02/07}{flaged as deprecated, the macro
% is not used at all, kept just to ensure that documents does not
% crash, TO BE DELETED}
%    \begin{macrocode}
\newif\ifsidebaroneside
  \if@twoside\sidebaronesidefalse\else\sidebaronesidetrue\fi

%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\sidebarmargin}
% \begin{macro}{\m@msidebar@margin}
% \changes{v1.61803398d}{2010/02/07}{removed the mention of
% \cs{sidebaroneside}, as it is deprecated}
% \cs{sidebarmargin}\marg{side} sets the side where sidebars will be printed.
% Valid arguments are: left, right, outer, or inner.
%
% \changes{v1.618}{2005/09/03}{Added \cs{sidebarmargin} (mempatch v3.2)}
% \changes{v1.61803398d}{2010/01/25}{Changed to match new general interface}
%    \begin{macrocode}
\newcommand*{\sidebarmargin}[1]{%
  \m@msetm@argin{#1}%
  \ifnum\m@mm@argin<\z@
    \@memwarn{Bad \string\sidebarmargin\space argument `#1'\MessageBreak
              set to `outer'}%
    \gdef\m@msidebar@margin{2}%   set as outer
  \else
    \global\let\m@msidebar@margin\m@mm@argin
  \fi}
%%%% default outer
\gdef\m@msidebar@margin{2}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@sideb@left}
% \begin{macro}{\m@sideb@right}
% Code used later to put sidebars into the desired margin.
% \changes{v1.61803}{2008/01/30}{Added \cs{m@sideb@left} and \cs{m@sideb@right}
%                    (mempatch v4.6)}
%    \begin{macrocode}
\newcommand*{\m@sideb@left}{%
  \@tempdimc \sidebarwidth
  \advance\@tempdimc\sidebarhsep
  \kern-\@tempdimc}
\newcommand*{\m@sideb@right}{%
  \@tempdimc \columnwidth%  or \hsize
  \advance\@tempdimc\sidebarhsep
  \kern\@tempdimc}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\sidecontents}
% This locates the horizontal position of a sidebar. On two column
% pages it is put in the margin next to the column where \cs{sidebar}
% is called, otherwise it is put in the outer (foredge) margin, except
% for the oneside option when it is put into the right hand margin.
% This can be separately controlled via \cs{ifsidebaroneside}.
% Emanuele Vicentini\footnote{\texttt{emanuelevicentini@yahoo.it},
% private email, 2004/04/05}
% suggested to code for the oneside option.
% \changes{v1.61}{2004/04/05}{Changed \cs{sidecontents} for oneside option} 
% \changes{v1.618}{2005/09/03}{Changed \cs{sidecontents} for \cs{sidebarmargin}}
% \changes{v1.61803}{2008/01/30}{Modified \cs{sidecontents} (mempatch v4.6)}
% \changes{v1.61803398d}{2010/01/15}{changed to use
% \cs{m@mwhich@margin} for determining wheter to move right ot left}
%    \begin{macrocode}
\newcommand{\sidecontents}{\hbox to \z@{%
  \m@mwhich@margin{\m@msidebar@margin}%
  \ifmemtortm
    \m@sideb@right
  \else
    \m@sideb@left
  \fi
%    \end{macrocode}
% DA and I have gone to and fro on the next bit of code trying to get
% the top alignment correct. 
% \begin{verbatim}
% \vtop to0pt{%
%    \vskip\onelineskip
%    \unvbox\sideins \vss}%
% \end{verbatim}
% DA has the last word.
%    \begin{macrocode}
  \vtop to0pt{%
    \normalsize\normalfont\sidebarfont% select font so we know the strut size
    \vskip\topskip \vskip-\ht\strutbox
    \vskip\sidebartopsep% extra vertical shift
    \unvbox\sideins \vss}%
  \hss}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sidebar}
% \cs{sidebar}\marg{text} puts \meta{text} into a sidebar.
%
% Florence Henry (\texttt{florence.henry@obspm.fr}) in the thread 
% \textit{Of memoir, sidebar, and justification}, 2003/04/02, pointed
% out that \texttt{itemize} in a \cs{sidebar} could overflow. DA gave the
% solution hint.
%
% DA says that having stacked insertions position properly is difficult.
% Here he uses the size of the strut to regulate both the height and the
% depth of each insertion (much as for footnotes). The following is his
% code and commentary.
% \changes{v1.4}{2003/11/22}{Revised \cs{sidebar}}
% \changes{v1.61803}{2008/01/30}{DA's rewrite of \cs{sidebar} (mempatch v4.6)}
%    \begin{macrocode}
\newcommand{\sidebar}[1]{%
  \insert\sideins{%
%    \end{macrocode}
% Begin the insertion with settings. The height of the strut box
% (dependant on the font) will determine the top alignment both initially
% and after a page break. The setting for maximum depth does not control
% anything; see the code further on instead.
% \changes{v1.61803398d}{2010/02/05}{removed
% \cs{normalfont}\cs{normalsize}, as these are now in the \cs{sidebarfont}}
% \changes{v3.6h}{2010/10/29}{the text should have the same baseline
% stretch as the rest of the page notes.}
%    \begin{macrocode}
    \hsize\sidebarwidth
    \@parboxrestore
    \def\baselinestretch{\m@m@footnote@spacing}%
%    \end{macrocode}
% \changes{v1.61803398d}{2010/02/05}{Added margin placement check
% inside \cs{sidebar}}
% Even though the margin placement is handled inside
% \cs{sidecontents}, there are some timming issues such that
% \cs{ifmemtortm} is executed too late for \cs{sidebar}s internals to
% make use of it. Fixed by adding the margin check to \cs{sidebar} as well.
%    \begin{macrocode}
    \m@mwhich@margin{\m@msidebar@margin}%    
    \sidebarform\sidebarfont
    \splittopskip=\ht\strutbox
    \splitmaxdepth=\dp\strutbox % doesn't do anything useful
%    \end{macrocode}
% Allow a free split at the top (so this whole insertion moves
% to the next page if it does not fit).
%    \begin{macrocode}
    \allowbreak
%    \end{macrocode}
% Control the (vertical) positioning of non-split entries. Footnotes (and
% previous versions of \cs{sidebar}) us a strut at the beginning of the text,
% but we will allow a baseline-skip to perform the same function. This
% method also introduces a \cs{parskip} when the paragraph begins, so we
% counteract that. (The problem with an initial strut is that it messes'
% up entries that begin with vertical space.)
%    \begin{macrocode}
    \prevdepth=\dp\strutbox    % supersedes a "top-strut"
    \vskip-\parskip
%    \end{macrocode}
% Now the user's sidebar entry:
%    \begin{macrocode}
    #1%
%    \end{macrocode}
% If the entry ended still in a paragraph, take the chance to insert a
% final strut; then end the paragraph.
%    \begin{macrocode}
    \ifvmode\else
      \unskip\@finalstrut\strutbox
    \fi\par
%    \end{macrocode}
% Explicitly force the effect of \cs{maxdepth} (\cs{splitmaxdepth}),
% but using the depth of the strut in the r\^{o}le of \cs{maxdepth}.
%    \begin{macrocode}
    \ifdim\prevdepth>\dp\strutbox \prevdepth=\dp\strutbox \fi
%    \end{macrocode}
% Now control how adjacent entries abut (whether or not a final strut got 
% inserted) and how an entry fits at the bottom of the page. Use \cs{vskip}s
% to move from the text bottom to where a strut would bottom out,
% but insert an allowed breakpoint at the baseline position
% (so that the entry baseline may match the page's baseline). Finally
% insert the extra separation between entries.
%    \begin{macrocode}
    \ifdim\prevdepth>99\p@
      \nobreak
      \vskip-\prevdepth
      \allowbreak
      \vskip\dp\strutbox
    \fi
    \vskip\sidebarvsep}}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{Footnotes}
%
%    For my reference, in case I want to fiddle with it even more
% than I have already done so, here is the kernel code (from \file{ltfloat.dtx}) 
% for footnotes.
% \DescribeMacro{\footins}
% The insert for footnotes.
% \begin{verbatim}
% \newinsert\footins
%   \skip\footins=\bigskipamount
%   \count\footins=1000
%   \dimen\footins=8in
% \end{verbatim}
%
% \DescribeMacro{\footnoterule}
% Draws the rule separating footnotes from the main text. It is executed
% after a \cs{vspace} of \verb?\skip\footins? and should take no vertical
% space.
% \begin{verbatim}
% \def\footnoterule{\kern-3\p@ \hrule \@width 2in \kern 2.6\p@}
%
% \@definecounter{footnote}
%   \def\thefootnote{\@arabic\c@footnote}
% \@definecounter{mpfootnote}
%   \def\thempfootnote{\itshape\@alph\c@mpfootnote}
% \end{verbatim}
%
% \DescribeMacro{\@makefnmark}
% Generates the footnote marker from \cs{@thefnmark}.
% \begin{verbatim}
% \def\@makefnmark{\hbox{\@textsuperscript{\normalfont\@thefnmark}}}
%
% \DeclareRobustCommand*\textsuperscript[1]{%
%    \@textsuperscript{\selectfont#1}}
% \def\@textsuperscript#1{%
%    {\m@th\ensuremath{^{\mbox{\fontsize\sf@size\z@#1}}}}}
%
% \newdimen\footnotesep
% \end{verbatim}
%
% \DescribeMacro{\footnote}
% \cs{footnote}\oarg{num}\marg{text} is what the user uses for footnoting.
% It defines \cs{@thefnmark} and calls \cs{@footnotemark} and 
% \cs{@footnotetext} to do the work.
% \begin{verbatim}
% \def\footnote{\@ifnextchar[\@xfootnote{\stepcounter\@mpfn
%   \protected@xdef\@thefnmark{\thempfn}%
%   \@footnotemark\@footnotetext}}
% \end{verbatim}
%
% \DescribeMacro{\@xfootnote}
% Handles the optional \meta{num} argument to \cs{footnote}.
% It defines \cs{@thefnmark} and calls \cs{@footnotemark} and 
% \cs{@footnotetext} to do the work.
% \begin{verbatim}
% \def\@xfootnote[#1]{%
%   \begingroup
%     \csname c@\@mpfn\endcsname #1\relax
%     \unrestored@protected@xdef\@thefnmark{\thempfn}%
%   \endgroup
%   \@footnotemark\@footnotetext}
% \end{verbatim}
%
% \DescribeMacro{\@footnotetext}
% \cs{@footnotetext}\marg{text} sets up for typeseting the footnote 
% (at the bottom of the page). It calls \cs{@makefntext}\marg{text}
% to actually do the typesetting (\cs{@makefntext} has to be supplied
% by a class or package).
% \begin{verbatim}
% \long\def\@footnotetext#1{%
%   \insert\footins{%
%     \reset@font\footnotesize
%     \interlinepenalty\interfootnotelinepenalty
%     \splittopskip\footnotesep
%     \splitmaxdepth \dp\strutbox \floatingpenalty \@MM
%     \hsize\columnwidth \@parboxrestore
%     \protected@edef\@currentlabel{%
%       \csname p@footnote\endcsname\@thefnmark}%
%     \color@begingroup
%       \@makefntext{%
%         \rule\z@\footnotesep\ignorespaces#1\@finalstrut\strutbox}%
%     \color@endgroup}}
% \end{verbatim}
%
% \DescribeMacro{\footnotemark}
% \cs{footnotemark}\oarg{num} the user uses this to produce just a 
% footnote mark in the text.
% \begin{verbatim}
% \def\footnotemark{%
%    \@ifnextchar[\@xfootnotemark
%      {\stepcounter{footnote}%
%       \protected@xdef\@thefnmark{\thefootnote}%
%       \@footnotemark}}
% \end{verbatim}
%
% \DescribeMacro{\@xfootnotemark}
% Handles the optional \meta{num} argument to \cs{footnotemark}.
% \begin{verbatim}
% \def\@xfootnotemark[#1]{%
%    \begingroup
%      \c@footnote #1\relax
%      \unrestored@protected@xdef\@thefnmark{\thefootnote}%
%    \endgroup
%    \@footnotemark}
% \end{verbatim}
%
% \DescribeMacro{\@footnotemark}
% Typesets the mark in the main text, via \cs{@makefnmark}.
% \begin{verbatim}
% \def\@footnotemark{%
%    \leavevmode
%    \ifhmode\edef\@x@sf{\the\spacefactor}\nobreak\fi
%    \@makefnmark
%    \ifhmode\spacefactor\@x@sf\fi
%    \relax}
% \end{verbatim}
%
% \DescribeMacro{\footnotetext}
% \cs{footnotetext}\oarg{num}\marg{text} is user view for creating a footnote
% without a marker in the main text.
% \begin{verbatim}
% \def\footnotetext{%
%    \@ifnextchar [\@xfootnotenext
%       {\protected@xdef\@thefnmark{\thempfn}%
%       \@footnotetext}}
% \end{verbatim}
%
% \DescribeMacro{\@xfootnotetext}
% Handles the optional \meta{num} argument to \cs{footnotetext}.
% \begin{verbatim}
% \def\@xfootnotenext[#1]{%
%   \begingroup
%     \csname c@\@mpfn\endcsname #1\relax
%     \unrestored@protected@xdef\@thefnmark{\thempfn}%
%   \endgroup
%   \@footnotetext}
% \end{verbatim}
%
% \DescribeMacro{\@mpfn}
% \DescribeMacro{\thempfn}
% \begin{verbatim}
% \def\@mpfn{footnote}
% \def\thempfn{\thefootnote}
% \end{verbatim}
%
% And from \file{ltboxes.dtx} for the \texttt{minipage} environment. 
%
% \DescribeMacro{\@mpfn}
% \DescribeMacro{\thempfn}
% \DescribeMacro{\@footnotetext}
% When setting up
% the environment, it includes:
% \begin{verbatim}
% \def\@mpfn{mpfootnote}\def\thempfn{\thempfootnote}\c@mpfootnote\z@
% \let\@footnotetext\@mpfootnotetext
% \end{verbatim}
%
% \DescribeMacro{\@mpfootnotetext}
% Later it defines \cs{@mpfootnotetext}\marg{text} as the minipage version
% of \cs{@footnotetext}.
% \begin{verbatim}
% \long\def\@mpfootnotetext#1{%
%   \global\setbox\@mpfootins\vbox{%
%     \unvbox\@mpfootins
%     \reset@font\footnotesize
%     \hsize\columnwidth
%     \@parboxrestore
%     \protected@edef\@currentlabel{%
%       \csname p@mpfootnote\endcsname\@thefnmark}%
%     \color@begingroup
%       \@makefntext{%
%         \rule\z@\footnotesep\ignorespaces#1\@finalstrut\strutbox}%
%     \color@endgroup}}
% \end{verbatim}
%
% That completes the kernel extracts.
%
% \begin{macro}{\footnoterule}
%    Usually, footnotes are separated from the main body of the text
%    by a small rule. This rule is drawn by the macro \cs{footnoterule}.
%    We have to make sure that the rule takes no vertical space (see
%    \file{plain.tex}) so we compensate for the natural heigth of the
%    rule of 0.4pt by adding the right amount of vertical skip.
%
%    To prevent the rule from colliding with the footnote we first add
%    a little negative vertical skip, then we put the rule and make
%    sure we end up at the same point where we begun this operation.
%  \changes{v3.6k}{2013/05/08}{Added \cs{normalcolor}, this seems to
%  fix a color leak into paragraph footnotes.}
%    \begin{macrocode}
\renewcommand{\footnoterule}{%
  \kern-3\p@
  \normalcolor% added 2013/05/08
  \hrule width .4\columnwidth
  \kern 2.6\p@}
%    \end{macrocode}
% And just to make sure that we are using memoir's font-dependent
% skips:
%    \begin{macrocode}
\skip\footins=\bigskipamount
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\c@footnote}
%    Footnotes are numbered per chapter. The counter is predefined.
%    \begin{macrocode}
\@addtoreset{footnote}{chapter}
%    \end{macrocode}
% \end{macro}
%
%    The footnote mechanism of \LaTeX{} calls the macro \cs{@makefntext}
%    to produce the actual footnote. The macro gets the text of the
%    footnote as its argument and should use \cs{@thefnmark} as the mark
%    of the footnote. The macro \cs{@makefntext} is called when
%    effectively inside a \cs{parbox} of width \cs{columnwidth} (i.e.,
%    with \cs{hsize} = \cs{columnwidth}).
%
%   An example of what can be achieved is given by the following piece
%   of \TeX{} code.
% \begin{verbatim}
%          \long\def\@makefntext#1{%
%             \@setpar{\@@par
%                      \@tempdima = \hsize
%                      \advance\@tempdima-10pt
%                      \parshape \@ne 10pt \@tempdima}%
%             \par
%             \parindent 1em\noindent
%             \hbox to \z@{\hss\@makefnmark}#1}
% \end{verbatim}
%    The effect of this definition is that all lines of the footnote
%    are indented by 10pt, while the first line of a new paragraph is
%    indented by 1em. To change these dimensions, just substitute the
%    desired value for `10pt' (in both places) or `1em'.  The mark is
%    flushright against the footnote.
%
%    The standard classes use a simpler macro, in which the
%    footnote text is set like an ordinary text paragraph, with no
%    indentation except on the first line of a paragraph, and the
%    first line of the footnote. Thus, all the macro must do is set
%    \cs{parindent} to the appropriate value for succeeding paragraphs
%    and put the proper indentation before the mark.
% \begin{verbatim}
% \newcommand{\@makefntext}[1]{%
%     \parindent 1em%
%     \noindent
%     \hb@xt@1.8em{\hss\@makefnmark}#1}
% \end{verbatim}
%
% This class provides a configurable specification.
%
% Normally, if two or more footnotes are sequentially applied: \\
% \verb?...text\footnote{first}\footnote{second}...? \\
% the markers in the text run together 
% (e.g., \ldots text\textsuperscript{12}). 
% The class provides a separator between the markers
% (e.g., \ldots text\textsuperscript{1,2}).
% The underlying ideas for this are from the \Lpack{ledmac} 
% package~\cite{LEDMAC},
% which in turn got them from the \Lpack{footmisc} package~\cite{FOOTMISC}.
% \changes{v1.4}{2003/11/22}{Added footnote separator (from patch v1.5)}
%
% \begin{macro}{\multfootsep}
% The separator between multiple footnote markers.
%    \begin{macrocode}
\newcommand*{\multfootsep}{\textsuperscript{\normalfont,}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\multiplefootnotemarker}
% \begin{macro}{\m@mmf@prepare}
% \cs{m@mmf@prepare} is a pair of self-cancelling kerns.
%    \begin{macrocode}
\newcommand*{\multiplefootnotemarker}{3sp}
\newcommand*{\m@mmf@prepare}{%
  \kern-\multiplefootnotemarker
  \kern\multiplefootnotemarker\relax}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mmf@check}
% If \cs{m@mmf@check} recognises the last kern as \cs{multiplefootnotemarker}
% it typesets \cs{multfootsep}.
%    \begin{macrocode}
\newcommand*{\m@mmf@check}{%
  \ifdim\lastkern=\multiplefootnotemarker\relax
    \edef\@x@sf{\the\spacefactor}%
    \unkern
    \multfootsep
    \spacefactor\@x@sf\relax
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@footnotemark}
% We have to modify the kernel's % \cs{@footnotetext} and 
% \cs{@footnotemark} 
% to implement the separator.
% \changes{v1.618}{2005/09/03}{Stop body font changes leaking into footnotes (mempatch v3.7)}
% \changes{v1.61803}{2008/01/30}{Keep single spacing in footnotes (mempatch v4.6)}
% \changes{v3.6g}{2010/09/19}{Made the 'single spacing' configurable.}
% \changes{v3.6h}{2010/20/22}{\cs{@footnotetext} is redefined later
% on, so the \cs{m@mold@footnotetext} needs to be moved, we also
% remove this version of \cs{@footnotetext} such that people do
% not mistake this for the `real' \cs{@footnotetext}}.
%    \begin{macrocode}
\renewcommand*{\@footnotemark}{%
  \leavevmode
  \ifhmode
    \edef\@x@sf{\the\spacefactor}%
    \m@mmf@check
    \nobreak
  \fi
  \@makefnmark
  \m@mmf@prepare
  \ifhmode\spacefactor\@x@sf\fi
  \relax}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@pn@multiple@marker}
%  This controls the multiple marker handling for successive page
%  notes, i.e., adding a comma between them. 
% \changes{v3.6k}{2013/05/16}{Added hooks, they are not intended for users}
%    \begin{macrocode}
\newcommand{\mem@pn@multiple@marker}[1]{%
  \leavevmode
  \ifhmode
    \edef\@x@sf{\the\spacefactor}%
    \m@mmf@check
    \nobreak
  \fi
  \@nameuse{mem@pnmm@start@hook}%
  #1%
  \@nameuse{mem@pnmm@end@hook}%
  \m@mmf@prepare
  \ifhmode\spacefactor\@x@sf\fi
  \relax}
      
%    \end{macrocode}
%   
% \end{macro}
% %
% \begin{macro}{\footmarkwidth}
% \begin{macro}{\footmarksep}
% \begin{macro}{\footparindent}
% The mark is typset right justified in a box with width \cs{footmarkwidth}.
% Second and later lines of the text are offset \cs{footmarksep} from the
% end of the box. Paragraphs in footnotes are indented by \cs{parindent}.
%    \begin{macrocode}
\newlength{\footmarkwidth}
\newlength{\footmarksep}
\newlength{\footparindent}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\footmarkstyle}
% \begin{macro}{\footscript}
% The marker is typeset according to \cs{footscript}\marg{marker}. This
% can be specified by the user via \cs{footmarkstyle}.
%    \begin{macrocode}
\newcommand*{\footmarkstyle}[1]{\def\footscript##1{#1}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\makefootmarkhook}
% A vacuous macro that the user can redefine to do something useful?
%    \begin{macrocode}
\newcommand{\makefootmarkhook}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\footfootmark}
% This macro typesets the footnote marker.
%    \begin{macrocode}
\newcommand{\footfootmark}{%
  \ifdim\footmarkwidth < \z@
%    \end{macrocode}
% Negative width, mark is in the margin.
%    \begin{macrocode}
    \llap{\hb@xt@ -\footmarkwidth{%
            \hss\normalfont\footscript{\@thefnmark}}%
          \hspace*{-\footmarkwidth}}%
  \else
    \ifdim\footmarkwidth = \z@
%    \end{macrocode}
% Zero width, mark is at (inside) the margin.
%    \begin{macrocode}
      {\normalfont\footscript{\@thefnmark}}%
    \else
%    \end{macrocode}
% Positive width.
%    \begin{macrocode}
      \hb@xt@\footmarkwidth{\hss\normalfont\footscript{\@thefnmark}}%
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makefootmark}
% \begin{macro}{\@makefntext}
% The class version of \cs{@makefntext}.
%    \begin{macrocode}
\newcommand{\makefootmark}[1]{%
  \leavevmode
  \parindent \footparindent\noindent
  \leftskip\footmarksep\relax
  \advance\leftskip \footmarkwidth \null\nobreak\hskip -\leftskip\relax
  \makefootmarkhook\relax
  \footfootmark #1}
%    \end{macrocode}
% In the thread \textit{memoir and footnote.sty trouble}, 2003/04/02,
% Patrik Nyman (\texttt{patrik.nyman@orient.su.se}) noted that in order
% to stop \file{footnote.sty} (from \texttt{mdwtools}) barfing my original \\
% \verb?\newcommand{\@makefntext}[1]{\makefootmark{#1}}? \\
% had to be changed.
% \changes{v1.4}{2004/11/22}{Revised \cs{@makefntext}}
%    \begin{macrocode}
\newcommand{\@makefntext}[1]{\makefootmark #1}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% All that now remains for the footer part is to set the defaults.
%    \begin{macrocode}
\footmarkstyle{\textsuperscript{#1}}
\setlength{\footmarkwidth}{1.8em}
\setlength{\footmarksep}{-1.8em}
\setlength{\footparindent}{1em}

%    \end{macrocode}
%
% \begin{macro}{\@makefnmark}
%    The footnote markers that are printed in the text to point to the
%    footnotes should be produced by the macro \cs{@makefnmark}. We use
%    the default definition for it.
%    \begin{macrocode}
%\renewcommand\@makefnmark{\hbox{\@textsuperscript{%
%                                \normalfont\@thefnmark}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\footref}
%    Sometimes it is desireable to reference a footnote more than
% once.
%    If a footnote is labelled (e.g., \verb?\footnote{text\label{fn}}?) then
% the macro \cs{footref}\marg{fn} will print the footnote marker.
% The code is essentially a much simplified version of \cs{footnotemark}
% from \file{ltfloat.dtx}.
% \changes{v1.0}{2001/10/30}{Added \cs{footref}}
%    \begin{macrocode}
\newcommand{\footref}[1]{%
  \begingroup
    \unrestored@protected@xdef\@thefnmark{\ref{#1}}%
  \endgroup
  \@footnotemark}

%    \end{macrocode}
% \end{macro}
%
% The following code for footnotes that can include verbatims is based
% on Jeremy Gibbons \textit{`Footnotes with verbatim material'}
% in the column \textit{`Hey --- it works'} (edited by Jeremy Gibbons), 
% TeX and TUG NEWS, vol 2 no. 4, p 9, October 1993. I have updated
% the basic code so that it works for LaTeX2e.
%
% \begin{macro}{\verbfootnote}
% \begin{macro}{\@xverbfootnote}
% \cs{verbfootnote} is just like \cs{footnote} except that it can contain
% verbatim material.
%    \begin{macrocode}
\def\verbfootnote{\@ifnextchar[\@xverbfootnote{\stepcounter\@mpfn
  \protected@xdef\@thefnmark{\thempfn}%
  \@footnotemark\@verbfootnotetext}}

\def\@xverbfootnote[#1]{%
  \begingroup
    \csname c@\@mpfn\endcsname #1\relax
    \unrestored@protected@xdef\@thefnmark{\thempfn}%
  \endgroup
  \@footnotemark\@verbfootnotetext}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@verbfootnotetext}
% This is the secret ingredient. It is based on the \cs{footnote} macro
% in \theTeXbook{} page 363, which somehow manages to read an argument 
% with verbatims. As Knuth says that it is subtle and involves trickery,
% don't expect me to even try to explain anything. 
%
% I'm not at all sure about the color bits, though!
% \changes{v1.618}{2005/09/02}{Fixed colors in \cs{verbfootnote} (mempatch v2.3)}
%    \begin{macrocode}
\long\def\@verbfootnotetext{%
  \insert\footins\bgroup
    \footnotesize
    \interlinepenalty\interfootnotelinepenalty
    \splittopskip\footnotesep
    \splitmaxdepth \dp\strutbox \floatingpenalty \@MM
    \hsize\columnwidth \@parboxrestore
    \edef\@currentlabel{\csname p@footnote\endcsname\@thefnmark}%
%%%%    \color@begingroup    
    \@makefntext{\rule{\z@}{\footnotesep}\ignorespaces}%
    \futurelet\next\fo@t
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\fo@t}
% \begin{macro}{\f@@t}
% \begin{macro}{\f@t}
% \begin{macro}{\@foot}
% Guess what these do.
% \changes{v1.61803}{2008/01/30}{Added \cs{m@mmf@prepare} to \cs{@foot} to 
%       implement the multifootnotemark separator (noted by zarko, CTT 2005/01/15)}
%    \begin{macrocode}
\def\fo@t{\ifcat\bgroup\noexpand\next \let\next\f@@t
          \else \let\next\f@t\fi \next}
\def\f@@t{\bgroup\aftergroup\@foot\let\next}
\def\f@t#1{%
  \color@begingroup
  #1\@foot
  \color@endgroup}
\def\@foot{%
  \strut\egroup
%%%%  \color@endgroup
  \m@mmf@prepare
  }

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@verbmpfootnotetext}
%    Footnotes in minipages are a little different, so another
% version of \cs{...footnotetext}. 
%    \begin{macrocode}
\long\def\@verbmpfootnotetext{%
  \global\setbox\@mpfootins\vbox{%
    \reset@font\footnotesize
    \unvbox\@mpfootins
    \bgroup
    \hsize\columnwidth
    \@parboxrestore
    \edef\@currentlabel{\csname p@mpfootnote\endcsname\@thefnmark}%
    \color@begingroup
    \@makefntext{\rule{\z@}{\footnotesep}\ignorespaces}%
    }
    \futurelet\next\fo@t
} 

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@minipagerestore}
% To get the \cs{verbfootnote} to work in a \texttt{minipage} we have to use
% \cs{@verbmpfootnotetext} instead of \cs{@verbfootnotetext}. There is
% a nice hook in the kernel \texttt{minipage} code for this. 
%
% As of version 1.61803 the following code is placed earlier. \\
% \verb?\def\@minipagerestore{\let\@verbfootnotetext\@verbmpfootnotetext}?
% \end{macro}
%
%
% \subsection{Major extensions for footnotes}
%
%    \begin{macrocode}
%%%%%%%%%%%%%% major extension to footnoting 

%    \end{macrocode}
%
% This all requires modifications to the output routine's \cs{@makecol},
% which will be done later. 
%
% \begin{macro}{\setfootnoterule}
% Per Starb\"{a}ck found (CTT \textit{feetbelowfloat in memoir}, 2006/11/24)
% that \cs{feetbelowfloat} did not affect anything when \cs{raggedbottom}
% is in effect.
%
% \cs{setfootnoterule}\oarg{vfill}\marg{uplift}\marg{width}\marg{thickness}
% defines the \cs{footnoterule}. Memoir's default setting is \\
% \verb?\setfootnoterule{3pt}{0.4\columnwidth}{\normalrulethickness}? \\
% To force footnotes to the bottom after a \cs{raggedbottom} use \\
% \verb?\setfootnoterule[\vfill]{3pt}{0.4\columnwidth}{\normalrulethickness}?
% \changes{v1.61803}{2008/01/30}{Added \cs{setfootnoterule} (memptatch v4.6)}
%  \changes{v3.6k}{2013/05/08}{Added \cs{normalcolor}, this seems to
%  fix a color leak into paragraph footnotes.}
%    \begin{macrocode}
\newcommand*{\setfootnoterule}[4][]{%
  \def\footnoterule{\kern -#2\relax #1\relax
    \normalcolor% added 2013/05/08
    \hrule width #3\relax
    \kern #2\kern-#4}}
\setfootnoterule{3pt}{0.4\columnwidth}{\normalrulethickness}

%    \end{macrocode}
% \end{macro}
%
% All sorts of extra kinds of footnotes.
%
% \begin{macro}{\m@mdoextrafeet}
% \begin{macro}{\extrafeetins}
% \begin{macro}{\extrafeetinshook}
% These macros are hooks into \cs{@makecol}.
% \changes{v1.618}{2005/09/02}{Fixed memoir/listings spacing problem (from Cartsten Heinz, mempatch v2.3)}
% \changes{v1.618}{2005/09/03}{Set \cs{boxmaxdepth} in \cs{extrafeetins} (mmempatch v3.1)}
%    \begin{macrocode}
\newcommand{\m@mdoextrafeet}{\extrafeetins}
\newcommand*{\extrafeetins}{%
  \setbox\@outputbox \vbox{%
    \boxmaxdepth \@maxdepth
    \unvbox\@outputbox
    \ifvoid\footinsv@r\else\@footstartv@r\@footgroupv@r\fi
    \extrafeetinshook}}
\newcommand{\extrafeetinshook}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mdodoreinextrafeet}
% \begin{macro}{\extrafeetreinshook}
% Hooks into \cs{@reinserts} for multiple footnote kinds.
%    \begin{macrocode}
\newcommand{\m@mdodoreinextrafeet}{%
  \ifvoid\footinsv@r\else\insert\footinsv@r{\unvbox\footinsv@r}\fi
  \extrafeetreinshook}
\newcommand{\extrafeetreinshook}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
%
% \begin{macro}{\foottextfont}
% \begin{macro}{\footinsdim}
% \begin{macro}{\@preamfntext}
% General macros.
%    \begin{macrocode}
\newcommand{\foottextfont}{\footnotesize}
\newlength{\footinsdim}
  \setlength{\footinsdim}{8in}   % standard for \dimen\footins
\newcommand{\@preamfntext}{%
  \interlinepenalty\interfootnotelinepenalty
  \floatingpenalty \@MM
  \splittopskip=\footnotesep
  \splitmaxdepth=\dp\strutbox
  \@parboxrestore}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% We are going to change some of the kernel footnote macros
%
% \begin{macro}{\@mpfootnotetext}
% \begin{macro}{\@plainmpfootnotetext}
% \changes{v1.6180}{2006/06/12}{Stop font changes leaking into footnotes.
%                  The v1.618 change was too early}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable'}
%    \begin{macrocode}
\renewcommand{\@mpfootnotetext}[1]{%
  \global\setbox\@mpfootins\vbox{%
    \unvbox\@mpfootins
    \def\baselinestretch{\m@m@footnote@spacing}%
    \foottextfont \hsize\columnwidth \@parboxrestore
    \protected@edef\@currentlabel{%
      \csname p@mpfootnote\endcsname\@thefnmark}%
  \color@begingroup
  \reset@font%        
    \@makefntext{%
      \rule\z@\footnotesep\ignorespaces{\foottextfont #1}%
      \@finalstrut\strutbox}%
  \color@endgroup}}

%    \end{macrocode}
% Save our revised version of \cs{@mpfootnotetext}
% \changes{v3.6h}{2010/10/22}{\cs{m@mold@mpfootnotetext} renamed to \cs{@plainmpfootnotetext}}
%    \begin{macrocode}
\let\@plainmpfootnotetext\@mpfootnotetext

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% We also to patch the minipage environment. We can use 
% \cs{@minipagerestore} for the \texttt{begin} part (done earlier), 
% but have to 
% modify \cs{endminipage}
%
% \begin{macro}{\m@mdoextrafeetmini}
% \begin{macro}{\extrafeetminihook}
% \begin{macro}{\@minipagerestore}
%    \begin{macrocode}
\newcommand{\m@mdoextrafeetmini}{%
  \extrafeetminihook}
\newcommand{\extrafeetminihook}{}
%%%%\renewcommand{\@minipagerestore}{\m@mdoextrafeetmini}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\extrafeetendmini}
% \begin{macro}{\extrafeetendminihook}
%    \begin{macrocode}
\newcommand{\extrafeetendmini}{%
  \ifvoid\@mpfootinsv@r\else
    \vskip\skip\@mpfootins
    \normalcolor\footnoterule\mp@footgroupv@r
  \fi
  \extrafeetendminihook}
\newcommand{\extrafeetendminihook}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mdoextrafeetendmini}
% \begin{macro}{\endminipage}
% This is our patched version of \cs{endminipage}.
%    \begin{macrocode}
\newcommand{\m@mdoextrafeetendmini}{\extrafeetendmini}
\def\endminipage{%
  \par
  \unskip
  \ifvoid\@mpfootins\else
    \vskip\skip\@mpfootins
    \normalcolor
    \footnoterule
    \unvbox\@mpfootins
  \fi
  \m@mdoextrafeetendmini
  \@minipagefalse
  \color@endgroup
  \egroup
  \expandafter\@iiiparbox\@mpargs{\unvbox\@tempboxa}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\plainfootnotes}
% The declaration for standard footnotes; easy, just use the saved
% versions of \cs{@footnotetext} and \cs{@mpfootnotetext}.
% \changes{v3.6h}{2010/10/22}{\cs{m@mold@footnotetext} renamed
% \cs{@plainfootnotetext} and \cs{m@mold@mpfootnotetext} as \cs{@plainmpfootnotetext}}
%    \begin{macrocode}
\newcommand{\plainfootnotes}{%
  \let\@footnotetext\@plainfootnotetext
  \let\@mpfootnotetext\@plainmpfootnotetext}

%    \end{macrocode}
% \end{macro}
%
% Now for lots of somewhat tedious code, interspersed with complex
% `Dirty Tricks' type things.
%
%     Robert Schlicht~\footnote{Private email, 2004/03/12, 
% (\texttt{w.m.l@gmx.net})} [RS] has provided valuable help in tuning
% up the code.
% 
%
% \begin{macro}{\newfootnoteseries}
% \cs{newfootnoteseries}\marg{series} creates the set of macros required
% for footnote code (see the kernel code presented earlier).
% The created macros have \meta{series} appended to their name.
% \changes{v1.61}{2004/03/14}{Added skip setup to \cs{newfootnoteseries}}
% \changes{v1.61}{2004/03/24}{Use \cs{newcounter} instead of \cs{newcount}
%                 in \cs{newfootnoteseries}}
%    \begin{macrocode}
\newcommand{\newfootnoteseries}[1]{%
  \expandafter\newinsert\csname footins#1\endcsname%  -> \footins#1
  \expandafter\skip\csname footins#1\endcsname \bigskipamount%
%%%                                      - > \skip\footins#1 % [RS]
  \newcounter{footnote#1}%                       -> \c@footnote#1
  \@nameuse{c@footnote#1} \z@%                   -> \c@footnote#1=0
  \global\@namelet{p@footnote#1} \@empty%        -> \p@footnote#1 
  \@namedef{thefootnote#1}{\arabic{footnote#1}}% -> \thefootnote#1
  \@namedef{foottextfont#1}{\foottextfont}%      -> \foottextfont#1
  \m@makefootnote{#1}%                           -> \footnote#1
  \m@make@xfootnote{#1}%                         -> \@xfootnote#1
  \m@make@footnotetext{#1}%                      -> \@footnotetext#1
  \m@makefootnotemark{#1}%                       -> \footnotemark#1
  \m@make@xfootnotemark{#1}%                     -> \@xfootnotemark#1
  \m@make@footnotemark{#1}%                      -> \@footnotemark#1
  \m@makefootnotetext{#1}%                       -> \footnotetext#1
  \m@make@xfootnotenext{#1}%                     -> \@xfootnotenext#1
  \m@make@mpfn{#1}%                              -> \@mpfn#1
  \m@makethempfn{#1}%                            -> \thempfn#1
  \m@make@makefnmark{#1}%                        -> \@makefnmark#1
  \m@makefootref{#1}%                            -> \footref#1
  \m@makefootfootmark{#1}%                       -> \footfootmark#1
  \m@makemakefootmark{#1}%                       -> \makefootmark#1
  \m@makefootmarkstyle{#1}%                      -> \footmarkstyle#1
  \@namedef{@makefntext#1}##1{\@nameuse{makefootmark#1} ##1}%
  \m@make@footstart{#1}%                         -> \@footstart#1
  \m@make@footgroup{#1}%                         -> \@footgroup#1
  \expandafter\newinsert\csname @mpfootins#1\endcsname% -> \@mpfootins#1
  \newcounter{mpfootnote#1}%                     -> \c@mpfootnote#1
  \global\@namelet{p@mpfootnote#1}\@empty
  \@namedef{thempfootnote#1}{\itshape\alph{mpfootnote#1}}%
  \m@make@mpfootnotetext{#1}%                    -> \@mpfootnotetext#1
%    \end{macrocode}
% Reset the counter per chapter, except for articles.
% \changes{v1.6}{2004/03/14}{Added chapter reset for footnote series [RS]}
%    \begin{macrocode}
  \ifartopt\else%  [RS]
    \expandafter\@cons\csname cl@chapter\endcsname {{footnote#1}}%
  \fi
%    \end{macrocode}
% Add the footnote to the (re)insert hooks.
%    \begin{macrocode}
  \g@addto@macro{\extrafeetinshook}{%
    \ifvoid\@nameuse{footins#1}\else
      \@nameuse{@footstart#1}\@nameuse{@footgroup#1}\fi}
  \g@addto@macro{\extrafeetreinshook}{%
    \ifvoid\@nameuse{footins#1}\else
      \insert\@nameuse{footins#1}{\unvbox\@nameuse{footins#1}}\fi}
  \g@addto@macro{\extrafeetendminihook}{%
    \ifvoid\@nameuse{@mpfootins#1}\else
      \vskip\skip\@mpfootins
      \normalcolor\footnoterule\@nameuse{mp@footgroup#1}\fi}
  \g@addto@macro{\extrafeetminihook}{%
    \@namedef{@mpfn#1}{mpfootnote#1}
    \@namedef{thempfn#1}{\@nameuse{thempfootnote#1}}
    \csname c@mpfootnote#1\endcsname\z@
     \expandafter\let\expandafter\@t@mp \csname @mpfootnotetext#1\endcsname
     \expandafter\let \csname @footnotetext#1\endcsname \@t@mp}
  \g@addto@macro{\@mem@extranofeet}{%  % [RS]
    \ifvoid\@nameuse{footins#1}\else\@mem@nofootfalse\fi}
  \plainfootstyle{#1}%
}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@makefootnote}
% \cs{m@makefootnote}\marg{series} creates  \cs{footnote<series>}
% \changes{v1.4}{2004/01/21}{In \cs{m@makefootnote} changed \cs{advance}
% to \cs{stepcounter} to make change global}
%    \begin{macrocode}
\newcommand{\m@makefootnote}[1]{
  \@namedef{footnote#1}{\@ifnextchar[
    {\@nameuse{@xfootnote#1}}{%\advance \@nameuse{c@\@mpfn#1} by \@ne
                              \stepcounter{\@mpfn#1}%
      \@name@p@xdef{@thefnmark#1}{\@nameuse{thempfn#1}}%
      \@nameuse{@footnotemark#1}\@nameuse{@footnotetext#1}}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@xfootnote}
% \cs{m@make@xfootnote}\marg{series} creates \cs{@xfootnote<series>}
%    \begin{macrocode}
\newcommand{\m@make@xfootnote}[1]{
  \@namedef{@xfootnote#1}[##1]{%
  \begingroup
    \csname c@\@mpfn#1\endcsname ##1\relax
    \@name@unresp@xdef{@thefnmark#1}{\@nameuse{thempfn#1}}%
  \endgroup
  \@nameuse{@footnotemark#1}\@nameuse{@footnotetext#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@footnotetext}
% \cs{m@make@footnotetext}\marg{series} creates \cs{@footnotetext<series>}
% \changes{v1.6180339a}{2008/08/07}{Removed a space from 
%     \cs{m@make@footnotetext} and \cs{m@make@mpfootnotetext} 
%     (courtesy David Wilson)}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
%    \begin{macrocode}
\newcommand{\m@make@footnotetext}[1]{%
  \@namelongdef{@footnotetext#1}##1{%
  \insert\@nameuse{footins#1}{%
  \def\baselinestretch{\m@m@footnote@spacing}% 
  \reset@font\@nameuse{foottextfont#1}%
  \@preamfntext
  \hsize\columnwidth
  \protected@edef\@currentlabel{%
    \csname p@footnote#1\endcsname\@nameuse{@thefnmark#1}}% 
  \color@begingroup
    \@nameuse{@makefntext#1}{%
      \rule\z@\footnotesep\ignorespaces{\@nameuse{foottextfont#1}##1}% <- v1.6180339a
      \@finalstrut\strutbox}%
  \color@endgroup}%
  \m@mmf@prepare}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@mpfootnotetext}
% \cs{m@make@mpfootnotetext}\marg{series} creates \cs{@mpfootnotetext<series>}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
%    \begin{macrocode}
\newcommand{\m@make@mpfootnotetext}[1]{%
  \@namelongdef{@mpfootnotetext#1}##1{%
    \global\setbox\@nameuse{@mpfootins#1}\vbox{%
      \unvbox\@nameuse{@mpfootins#1}%
      \def\baselinestretch{\m@m@footnote@spacing}%  
      \reset@font\@nameuse{foottextfont#1}%
      \hsize\columnwidth \@parboxrestore
      \protected@edef\@currentlabel{%
        \csname p@mpfootnote#1\endcsname\@nameuse{@thefnmark#1}}%
    \color@begingroup
      \@nameuse{@makefntext#1}{%
        \rule\z@\footnotesep\ignorespaces{\@nameuse{foottextfont#1}##1}% <- v1.6180339a
        \@finalstrut\strutbox}%
    \color@endgroup}%
    \m@mmf@prepare}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@makefootnotemark}
% \changes{v1.61}{2004/03/24}{Changed \cs{advance} to \cs{stepcounter}
%                 in \cs{m@makefootnotemark}}
% \cs{m@makefootnotemark}\marg{series} creates \cs{footnotemark<series>}
%    \begin{macrocode}
\newcommand{\m@makefootnotemark}[1]{
\@namedef{footnotemark#1}{%
  \@ifnextchar[ {\@nameuse{@xfootnotemark#1}}
    {%\advance\@nameuse{c@footnote#1} by \@ne%
     \stepcounter{footnote#1}%
     \@name@p@xdef{@thefnmark#1}{\@nameuse{thefootnote#1}}%
     \@nameuse{@footnotemark#1}}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@xfootnotemark}
% \cs{m@make@xfootnotemark}\marg{series} creates \cs{@xfootnotemark<series>}
%    \begin{macrocode}
\newcommand{\m@make@xfootnotemark}[1]{%
  \@namedef{@xfootnotemark#1}[##1]{%
  \begingroup
    \@nameuse{c@footnote#1} ##1\relax
    \@name@unresp@xdef{@thefnmark#1}{\@nameuse{thefootnote#1}}%
  \endgroup
  \@nameuse{@footnotemark#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@footnotemark}
% \cs{m@make@footnotemark}\marg{series} creates \cs{@footnotemark<series>}
%    \begin{macrocode}
\newcommand{\m@make@footnotemark}[1]{%
\@namedef{@footnotemark#1}{%
  \leavevmode
  \ifhmode
    \edef\@x@sf{\the\spacefactor}%
    \m@mmf@check
    \nobreak
  \fi
  \@nameuse{@makefnmark#1}%
  \m@mmf@prepare
  \ifhmode\spacefactor\@x@sf\fi
  \relax}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@makefootmarkstyle}
% \cs{m@makefootmarkstyle}\marg{series} creates \cs{footmarkstyle<series>}
%    \begin{macrocode}
\newcommand{\m@makefootmarkstyle}[1]{%
 \@namedef{footmarkstyle#1}##1{%
    \@namedef{footscript#1}####1{##1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@makefootnotetext}
% \cs{m@makefootnotetext}\marg{series} creates \cs{footnotetext<series>}
%    \begin{macrocode}
\newcommand{\m@makefootnotetext}[1]{%
\@namedef{footnotetext#1}{%
  \@ifnextchar[  {\@nameuse{@xfootnotenext#1}}%
  {\@name@p@xdef{@thefnmark#1}{\@nameuse{thempfn#1}}%
  \@nameuse{@footnotetext#1}}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@xfootnotenext}
% \cs{m@make@xfootnotenext}\marg{series} creates \cs{@xfootnotenext<series>}
%    \begin{macrocode}
\newcommand{\m@make@xfootnotenext}[1]{
\@namedef{@xfootnotenext#1}[##1]{%
  \begingroup
    \csname c@\@mpfn#1\endcsname ##1\relax
    \@name@unresp@xdef{@thefnmark#1}{\@nameuse{thempfn#1}}%
  \endgroup
  \@nameuse{@footnotetext#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@mpfn}
% \cs{m@make@mpfn}\marg{series} creates \cs{@mpfn<series>}
%    \begin{macrocode}
\newcommand{\m@make@mpfn}[1]{%
  \@namedef{@mpfn#1}{\@nameuse{footnote#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@makethempfn}
% \cs{m@makethempfn}\marg{series} creates \cs{thempfn<series>}
%    \begin{macrocode}
\newcommand{\m@makethempfn}[1]{%
  \@namedef{thempfn#1}{\@nameuse{thefootnote#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@makefnmark}
% \cs{m@make@makefnmark}\marg{series} creates \cs{@makefnmark<series>}
%    \begin{macrocode}
\newcommand{\m@make@makefnmark}[1]{%
  \@namedef{@makefnmark#1}{%
    \hbox{\@textsuperscript{\normalfont\@nameuse{@thefnmark#1}}}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@makefootref}
% \cs{m@makefootref}\marg{series} creates \cs{footref<series>}
%    \begin{macrocode}
\newcommand{\m@makefootref}[1]{%
  \@namedef{footref#1}##1{%
    \begingroup
      \@name@unresp@xdef{@thefnmark#1}{\ref{##1}}%
    \endgroup
    \@nameuse{@footnotemark#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@makefootfootmark}
% \cs{m@makefootfootmark}\marg{series} creates \cs{footfootmark<series>}
%    \begin{macrocode}
\newcommand{\m@makefootfootmark}[1]{%
  \@namedef{footfootmark#1}{%
    \ifdim\footmarkwidth < \z@
      \llap{\hb@xt@ -\footmarkwidth{%
            \hss\normalfont\@nameuse{footscript#1}%
            {\@nameuse{@thefnmark#1}}}%
            \hspace*{-\footmarkwidth}}%
    \else
      \ifdim\footmarkwidth = \z@
        {\normalfont\@nameuse{footscript#1}{\@nameuse{@thefnmark#1}}}%
      \else
        \hb@xt@\footmarkwidth{%
            \hss\normalfont\@nameuse{footscript#1}%
            {\@nameuse{@thefnmark#1}}}%
      \fi
    \fi}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@makemakefootmark}
% \changes{v1.61}{2004/03/23}{Removed extraneous space from \cs{m@makemakefootmark}}
% \cs{m@makemakefootmark}\marg{series} creates \cs{makefootmark<series>}
%    \begin{macrocode}
\newcommand{\m@makemakefootmark}[1]{%
  \@namedef{makefootmark#1}##1{%
    \leavevmode
    \parindent \footparindent\noindent
    \leftskip\footmarksep\relax
    \advance\leftskip \footmarkwidth 
    \null\nobreak\hskip -\leftskip\relax
    \makefootmarkhook\relax
    \@nameuse{footfootmark#1}##1}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@footgroup}
% \cs{m@make@footgroup}\marg{series} creates \cs{@footgroup<series>}
%    \begin{macrocode}
\newcommand{\m@make@footgroup}[1]{%
  \@namedef{@footgroup#1}{\unvbox\@nameuse{footins#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@makemp@footgroup}
% \cs{m@makemp@footgroup}\marg{series} creates \cs{mp@footgroup<series>}
%    \begin{macrocode}
\newcommand{\m@makemp@footgroup}[1]{%
  \@namedef{mp@footgroup#1}{\unvbox\@nameuse{@mpfootins#1}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@footstart}
% \cs{m@make@footstart}\marg{series} creates \cs{@footstart<series>}.
%
% The footnote series should of course use
% the skip associated with that series not just
% \cs{vskip}\cs{bigskipamount}. 
% \changes{v3.7d}{2015/04/22}{Changed the \cs{vskip}}
% \changes{v3.7d}{2015/04/22}{Added the feet at bottom part}
%    \begin{macrocode}
\newcommand{\m@make@footstart}[1]{%
  \@namedef{@footstart#1}{%
    %\vskip\bigskipamount
    \mem@if@flushbottomF\m@mopfn@bottom
    \vskip\skip\csname footins#1\endcsname
    \leftskip=\z@
    \rightskip=\z@
    \footnoterule}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\plainfootstyle}
% \cs{plainfootstyle}\marg{series} specifies a plain (normal) footnote
% style for \meta{series}.
%    \begin{macrocode}
\newcommand{\plainfootstyle}[1]{%
  \m@make@footnotetext{#1}%
  \m@make@footgroup{#1}%
  \m@make@footstart{#1}%
  \m@make@mpfootnotetext{#1}%
  \m@makemp@footgroup{#1}%
  \@nameuse{footmarkstyle#1}{\textsuperscript{##1}}
  \expandafter\dimen\csname footins#1\endcsname=\footinsdim
  \expandafter\count\csname footins#1\endcsname=1000\relax}

%    \end{macrocode}
% \end{macro}
%
% Now the basic code for footnote declarations (we will be
% using \texttt{footnotev@r} instead of the regular \texttt{footnote}).
%
% \begin{macro}{\footinsv@r}
% Define the new \cs{footinsv@r} insert. 
%    \begin{macrocode}
\newinsert\footinsv@r
  \skip\footinsv@r\bigskipamount
  \count\footinsv@r=1000 % no magnifcation
  \dimen\footinsv@r=\footinsdim
%    \end{macrocode}
% \end{macro}
% Create a new \verb?v@r? footnote series.
%    \begin{macrocode}
\m@make@footstart{v@r}
%    \end{macrocode}
% 
% \begin{macro}{\@footgroupv@r}
% Initialise the \texttt{footgroup} for the series to do nothing.
%    \begin{macrocode}
\newcommand{\@footgroupv@r}{}

%    \end{macrocode}
% \end{macro}
%
% And also for minipages:
% \begin{macro}{\@mpfootinsv@r}
% \begin{macro}{\mp@footgroupv@r}
%    \begin{macrocode}
\newinsert\@mpfootinsv@r
\newcommand{\mp@footgroupv@r}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \Lpack{ledmac} package style footnotes (see \file{ledmac.dtx} for 
% more detailed explanations).
%
% The two- and three-column notes use a macro \cs{m@mrigidbalance}
% to split text into a number of columns. This is based on \theTeXbook,
% page 397.
% \begin{macro}{\m@m@k}
% \begin{macro}{\m@m@h}
%    \begin{macrocode}
\newcount\m@m@k \newdimen\m@m@h
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mrigidbalance}
% \begin{macro}{\m@mdosplits}
% \begin{macro}{\m@msplitoff}
% \cs{m@mrigidbalance}\marg{box}\marg{num}\marg{length} splits a
% \meta{box} (of text) into \meta{num} columns with \meta{length}
% space between the top baseline and the top of the \cs{vbox}.
%    \begin{macrocode}
\newcommand*{\m@mrigidbalance}[3]{\setbox0=\box#1 \m@m@k=#2 \m@m@h=#3
  \@@line{\splittopskip=\m@m@h \vbadness=\@M \hfilneg
  \valign{##\vfill\cr\m@mdosplits}}}
\newcommand*{\m@mdosplits}{\ifnum\m@m@k>0 \noalign{\hfil}\m@msplitoff
  \global\advance\m@m@k-1\cr\m@mdosplits\fi}
\newcommand*{\m@msplitoff}{\dimen0=\ht0
  \divide\dimen0 by\m@m@k \advance\dimen0 by\m@m@h
  \setbox2 \vsplit0 to \dimen0
  \unvbox2 }

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \subsubsection{Two column footnotes}
%
% \begin{macro}{\twocolumnfootnotes}
% Declaration for two column footnotes. This causes the standard
% \cs{footnote} and friends to internally use the \verb?v@r? series,
% which here produces two column footnotes.
% \changes{v1.61}{2004/03/14}{Made [RS] change to \cs{twocolumnfootnotes}}
%    \begin{macrocode}
\newcommand{\twocolumnfootnotes}{%
  \@namedef{foottextfontv@r}{\foottextfont}%  % [RS]
  \let\@footnotetext\@twocolfootnotetext
  \dimen\footinsv@r=2\footinsdim
  \count\footinsv@r=500\relax
  \m@make@twocol@footgroup{v@r}%
  \let\@footgroupv@r\@twocol@footgroupv@r
  \let\@mpfootnotetext\@mptwocolfootnotetext 
  \m@make@mptwocol@footgroup{v@r}%
  \let\mp@footgroupv@r\@mptwocol@footgroupv@r}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@twocolfootnotetext}
% \cs{@twocolfootnotetext}\marg{text} is the two column version of
% \cs{@footnotetext} for the \verb?v@r? series.
% \changes{v1.618}{2005/09/03}{Added missing percent to \cs{@twocolfootnotetext} (mempatch v3.1)}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
%    \begin{macrocode}
\newcommand{\@twocolfootnotetext}[1]{\insert\footinsv@r{%
  \def\baselinestretch{\m@m@footnote@spacing}%   
  \reset@font\foottextfont
  \@preamfntext
  \protected@edef\@currentlabel{%
    \csname p@footnote\endcsname\@thefnmark}%
  \color@begingroup
    \@twocolfootfmt{#1}%
  \color@endgroup}%
  \m@mmf@prepare}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@preamtwofmt}
% Give each column 0.45 of the textwidth.
%    \begin{macrocode}
\newcommand{\@preamtwofmt}{%
  \hsize .45\hsize
  \parindent=\z@
  \tolerance=5000\relax
  \raggedright
  \leavevmode}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@twocolfootfmt}
% \cs{@twocolfootfmt}
%    \begin{macrocode}
\newcommand{\@twocolfootfmt}[1]{%
  \@preamtwofmt
  {\footfootmark\strut {\foottextfont #1}\strut\par}\allowbreak}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@mptwocolfootnotetext}
% \cs{@mptwocolfootnotetext}\marg{text} is the two column version
% of \cs{@mpfootnotetext} for the \verb?v@r? series for minipages.
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
%    \begin{macrocode}
\newcommand{\@mptwocolfootnotetext}[1]{%
  \global\setbox\@mpfootinsv@r\vbox{%
    \unvbox\@mpfootinsv@r
    \def\baselinestretch{\m@m@footnote@spacing}%   
    \reset@font\foottextfont 
    \hsize\columnwidth \@parboxrestore
    \protected@edef\@currentlabel{%
      \csname p@mpfootnote\endcsname\@thefnmark}%
  \color@begingroup
    \@twocolfootfmt{#1}%
  \color@endgroup}%
  \m@mmf@prepare}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\twocolumnfootstyle}
% \cs{twocolumnfootstyle}\marg{series} specifies a two column footnote 
% style for \meta{series}.
%    \begin{macrocode}
\newcommand{\twocolumnfootstyle}[1]{%
  \m@make@twocolfootnotetext{#1}%
  \m@make@mptwocolfootnotetext{#1}%
  \m@make@twocolfootfmt{#1}%
  \m@make@twocol@footgroup{#1}%
  \m@make@mptwocol@footgroup{#1}%
  \m@make@footstart{#1}%
  \@namelongdef{@footnotetext#1}##1{%
     \@nameuse{@twocolfootnotetext#1}{##1}}%
  \@namelongdef{@mpfootnotetext#1}##1{%
     \@nameuse{@mptwocolfootnotetext#1}{##1}}%
  \@namedef{@footgroup#1}{\@nameuse{@twocol@footgroup#1}}%
  \@namedef{mp@footgroup#1}{\@nameuse{@mptwocol@footgroup#1}}%
  \expandafter\dimen\csname footins#1\endcsname=2\footinsdim
  \expandafter\count\csname footins#1\endcsname=500\relax}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@twocolfootnotetext}
% \cs{m@make@twocolfootnotetext}\marg{series} creates 
% \cs{@twocolfootnotetext}\meta{series}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
%    \begin{macrocode}
\newcommand{\m@make@twocolfootnotetext}[1]{%
  \@namelongdef{@twocolfootnotetext#1}##1{%
    \insert\@nameuse{footins#1}{%
    \def\baselinestretch{\m@m@footnote@spacing}%   
    \reset@font\@nameuse{foottextfont#1}%
    \@preamfntext
    \protected@edef\@currentlabel{%
      \csname p@footnote#1\endcsname \@nameuse{@thefnmark#1}}%
    \color@begingroup
      \@nameuse{@twocolfootfmt#1}{##1}%
    \color@endgroup}%
    \m@mmf@prepare}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@mptwocolfootnotetext}
% \cs{m@make@mptwocolfootnotetext}\marg{series} creates
% \cs{@mptwocolfootnotetext}\meta{series}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
%    \begin{macrocode}
\newcommand{\m@make@mptwocolfootnotetext}[1]{%
\@namelongdef{@mptwocolfootnotetext#1}##1{%
  \global\setbox\@nameuse{@mpfootins#1}\vbox{%
    \unvbox\@nameuse{@mpfootins#1}
    \def\baselinestretch{\m@m@footnote@spacing}%   
    \reset@font\@nameuse{foottextfont#1}%
    \hsize\columnwidth \@parboxrestore
    \protected@edef\@currentlabel{%
      \csname p@mpfootnote#1\endcsname\@nameuse{@thefnmark#1}}%
  \color@begingroup
    \@nameuse{@twocolfootfmt#1}{##1}%
  \color@endgroup}\m@mmf@prepare}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@twocolfootfmt}
% \cs{m@make@twocolfootfmt}\marg{series} creates
% \cs{@twocolfootfmt}\meta{series} 
% \changes{v1.61}{2004/03/14}{Removed space from \cs{m@make@twocolfootfmt} [RS]}
%    \begin{macrocode}
\newcommand{\m@make@twocolfootfmt}[1]{%
  \@namedef{@twocolfootfmt#1}##1{%
    \@preamtwofmt
    {\@nameuse{footfootmark#1}\strut
     {\@nameuse{foottextfont#1}##1}\strut\par}\allowbreak}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@twocol@footgroup}
% \cs{m@make@twocol@footgroup}\marg{series} creates
% \cs{@twocol@footgroup}\meta{series} 
%    \begin{macrocode}
\newcommand{\m@make@twocol@footgroup}[1]{%
  \@namedef{@twocol@footgroup#1}{{%
    \@nameuse{foottextfont#1} \splittopskip=\ht\strutbox
     \m@mrigidbalance{\@nameuse{footins#1}}{\tw@}{\splittopskip}}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@mptwocol@footgroup}
% \cs{m@make@mptwocol@footgroup}\marg{series} creates
% \cs{@mptwocol@footgroup}\meta{series}
%    \begin{macrocode}
\newcommand{\m@make@mptwocol@footgroup}[1]{%
\@namedef{@mptwocol@footgroup#1}{{%
  \@nameuse{foottextfont#1} \splittopskip=\ht\strutbox
  \m@mrigidbalance{\@nameuse{@mpfootins#1}}{\tw@}{\splittopskip}}}}

%    \end{macrocode}
% \end{macro}
%
%
% \subsubsection{Three column footnotes}
%
% \begin{macro}{\threecolumnfootnotes}
% Declaration for three column footnotres.
% \changes{v1.61}{2004/03/14}{Made [RS] change to \cs{threecolumnfootnotes}}
%    \begin{macrocode}
\newcommand{\threecolumnfootnotes}{%
  \@namedef{foottextfontv@r}{\foottextfont}%  % [RS]
  \let\@footnotetext\@threecolfootnotetext
  \dimen\footinsv@r=3\footinsdim
  \count\footinsv@r=333\relax
  \m@make@threecol@footgroup{v@r}%
  \let\@footgroupv@r\@threecol@footgroupv@r
  \let\@mpfootnotetext\@mpthreecolfootnotetext 
  \m@make@mpthreecol@footgroup{v@r}%
  \let\mp@footgroupv@r\@mpthreecol@footgroupv@r}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@threecolfootnotetext}
% \cs{@threecolfootnotetext}\marg{text} is the three column version of
% \cs{@footnotetext}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
%    \begin{macrocode}
\newcommand{\@threecolfootnotetext}[1]{\insert\footinsv@r{%
  \def\baselinestretch{\m@m@footnote@spacing}%   
  \reset@font\foottextfont
  \@preamfntext
  \protected@edef\@currentlabel{%
    \csname p@footnote\endcsname\@thefnmark}%
  \color@begingroup
    \@threecolfootfmt{#1}%
  \color@endgroup}\m@mmf@prepare}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@preamthreefmt}
% Give each column 0.3 of the text width.
%    \begin{macrocode}
\newcommand{\@preamthreefmt}{%
  \hsize .3\hsize
  \parindent=\z@
  \tolerance=5000\relax
  \raggedright
  \leavevmode}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@threecolfootfmt}
%
%    \begin{macrocode}
\newcommand{\@threecolfootfmt}[1]{%
  \@preamthreefmt
  {\footfootmark\strut {\foottextfont #1}\strut\par}\allowbreak}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@mpthreecolfootnotetext}
% \cs{@mpthreecolfootnotetext}\marg{text} is the three column version of
% \cs{@mpfootnotetext}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
%    \begin{macrocode}
\newcommand{\@mpthreecolfootnotetext}[1]{%
  \global\setbox\@mpfootinsv@r\vbox{%
    \unvbox\@mpfootinsv@r
    \def\baselinestretch{\m@m@footnote@spacing}%  
    \reset@font\foottextfont 
    \hsize\columnwidth \@parboxrestore
    \protected@edef\@currentlabel{%
      \csname p@mpfootnote\endcsname\@thefnmark}%
  \color@begingroup
    \@threecolfootfmt{#1}%
  \color@endgroup}\m@mmf@prepare}

%    \end{macrocode}
% \end{macro}
%
%
%
% \begin{macro}{\threecolumnfootstyle}
% \cs{threecolumnfootstyle}\marg{series} specifies three column footnote style
% for \meta{series}
%    \begin{macrocode}
\newcommand{\threecolumnfootstyle}[1]{%
  \m@make@threecolfootnotetext{#1}%
  \m@make@mpthreecolfootnotetext{#1}%
  \m@make@threecolfootfmt{#1}%
  \m@make@threecol@footgroup{#1}%
  \m@make@mpthreecol@footgroup{#1}%
  \m@make@footstart{#1}%
  \@namelongdef{@footnotetext#1}##1{%
    \@nameuse{@threecolfootnotetext#1}{##1}}%
  \@namelongdef{@mpfootnotetext#1}##1{%
    \@nameuse{@mpthreecolfootnotetext#1}{##1}}%
  \@namedef{@footgroup#1}{\@nameuse{@threecol@footgroup#1}}%
  \@namedef{mp@footgroup#1}{\@nameuse{@mpthreecol@footgroup#1}}%
  \expandafter\dimen\csname footins#1\endcsname=3\footinsdim
  \expandafter\count\csname footins#1\endcsname=333\relax}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@threecolfootnotetext}
% \cs{m@make@threecolfootnotetext}\marg{series} creates
% \cs{@threecolfootnotetext}\meta{series}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
%    \begin{macrocode}
\newcommand{\m@make@threecolfootnotetext}[1]{%
\@namelongdef{@threecolfootnotetext#1}##1{%
  \insert\@nameuse{footins#1}{%
  \def\baselinestretch{\m@m@footnote@spacing}%  
  \reset@font\@nameuse{foottextfont#1}%
  \@preamfntext
  \protected@edef\@currentlabel{%
    \csname p@footnote#1\endcsname \@nameuse{@thefnmark#1}}%
  \color@begingroup
    \@nameuse{@threecolfootfmt#1}{##1}%
  \color@endgroup}\m@mmf@prepare}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@mpthreecolfootnotetext}
% \cs{m@make@mpthreecolfootnotetext}\marg{series} creates
% \cs{@mpthreecolfootnotetext}\meta{series}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
%    \begin{macrocode}
\newcommand{\m@make@mpthreecolfootnotetext}[1]{%
\@namelongdef{@mpthreecolfootnotetext#1}##1{%
  \global\setbox\@nameuse{@mpfootins#1}\vbox{%
    \unvbox\@nameuse{@mpfootins#1}
    \def\baselinestretch{\m@m@footnote@spacing}%   
    \reset@font\@nameuse{foottextfont#1}%
    \hsize\columnwidth \@parboxrestore
    \protected@edef\@currentlabel{%
      \csname p@mpfootnote#1\endcsname\@nameuse{@thefnmark#1}}%
  \color@begingroup
    \@nameuse{@threecolfootfmt#1}{##1}%
  \color@endgroup}\m@mmf@prepare}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@threecolfootfmt}
% \cs{m@make@threecolfootfmt}\marg{series} creates
% \cs{@threecolfootfmt}\meta{series}
% \changes{v1.61}{2004/03/14}{Removed space from \cs{m@make@threecolfootfmt} [RS]}
%    \begin{macrocode}
\newcommand{\m@make@threecolfootfmt}[1]{%
\@namelongdef{@threecolfootfmt#1}##1{%
  \@preamthreefmt
  {\@nameuse{footfootmark#1}\strut 
   {\@nameuse{foottextfont#1}##1}\strut\par}\allowbreak}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@threecol@footgroup}
% \cs{m@make@threecol@footgroup}\marg{series} creates
% \cs{@threecol@footgroup}\meta{series} 
%    \begin{macrocode}
\newcommand{\m@make@threecol@footgroup}[1]{%
\@namedef{@threecol@footgroup#1}{{%
  \@nameuse{foottextfont#1} \splittopskip=\ht\strutbox
  \m@mrigidbalance{\@nameuse{footins#1}}{\thr@@}{\splittopskip}}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@mpthreecol@footgroup}
% \cs{m@make@mpthreecol@footgroup}\marg{series} creates
% \cs{@mpthreecol@footgroup}\meta{series} 
%    \begin{macrocode}
\newcommand{\m@make@mpthreecol@footgroup}[1]{%
\@namedef{@mpthreecol@footgroup#1}{{%
  \@nameuse{foottextfont#1} \splittopskip=\ht\strutbox
  \m@mrigidbalance{\@nameuse{@mpfootins#1}}{\thr@@}{\splittopskip}}}}

%    \end{macrocode}
% \end{macro}
%
%
% \subsubsection{Paragraphed footnotes}
%
% Paragraphed footnotes are based on \theTeXbook, page 398ff, in the 
% Dirty Tricks appendix. It does a lot of box manipulations.
%
% \begin{macro}{\m@munvxh}
% \cs{m@munvxh}\marg{vbox}: unvbox, extract the last line, and unhbox it.
%    \begin{macrocode}
\newcommand{\m@munvxh}[1]{%
  \setbox0=\vbox{\unvbox#1%
    \global\setbox1=\lastbox}%
  \unhbox1
  \unskip
  \unskip
  \unpenalty
  \hskip\m@mipn@skip}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mungebox}
%
%    \begin{macrocode}
\newcommand{\m@mungebox}{%
  \setbox0=\hbox{\m@munvxh0}%
  \dp0=\z@
  \ht0=\footfudgefactor\wd0
  \box0
  \penalty0}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mipn@skip}
% \begin{macro}{\m@minterparanoteglue}
% These are `inter-para-note-skip' and `inter-parafootnote' glue, for 
% paragraphed footnotes.
%    \begin{macrocode}
\newskip\m@mipn@skip
\newcommand*{\m@minterparanoteglue}[1]{%
  {\foottextfont\global\m@mipn@skip=#1\relax}}
\m@minterparanoteglue{1em plus.4em minus.4em}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mmakehboxofhboxes}
% Make an hbox of hboxes.
%    \begin{macrocode}
\newcommand*{\m@mmakehboxofhboxes}{\setbox0=\hbox{}%
  \loop
    \unpenalty
    \setbox2=\lastbox
  \ifhbox2
    \setbox0=\hbox{\box2\unhbox0}
  \repeat}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mremovehboxes}
%    \begin{macrocode}
\newcommand*{\m@mremovehboxes}{\setbox0=\lastbox
  \ifhbox0{\m@mremovehboxes}\unhbox0 \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\footfudgefiddle}
% TeX uses \verb?\footfufgefactor? to estimate the space required for
% paragraphed footnotes. If it underestimates then the notes approach,
% or cover, the footer. \verb?\footfudgefiddle? can be changed (upward) from
% its default to improve matters.
%    \begin{macrocode}
\newcommand*{\footfudgefiddle}{64}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\paragraphfootnotes}
% Declaration for paragraphed footnotes.
% \changes{v1.61}{2004/03/14}{Made [RS] change to \cs{paragraphfootnotes}}
%    \begin{macrocode}
\newcommand{\paragraphfootnotes}{%
  \@namedef{foottextfontv@r}{\foottextfont}%  % [RS]
  \let\@footnotetext\@parafootnotetext
  \dimen\footinsv@r=\footinsdim
  \count\footinsv@r=1000\relax
  \m@make@para@footgroup{v@r}%
  \let\@footgroupv@r\@para@footgroupv@r
  \let\@mpfootnotetext\@mpparafootnotetext 
  \m@make@mppara@footgroup{v@r}%
  \let\mp@footgroupv@r\@mppara@footgroupv@r
  {\foottextfont
   \dimen0=\baselineskip
   \multiply\dimen0 by 1024
   \divide\dimen0 by \hsize \multiply\dimen0 by \footfudgefiddle
   \xdef\footfudgefactor{\expandafter\strip@pt\dimen0 }}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@parafootnotetext}
% \cs{@parafootnotetext}\marg{text} is a paragraph version of
% \cs{@footnotetext}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
%    \begin{macrocode}
\newcommand{\@parafootnotetext}[1]{\insert\footinsv@r{
  \def\baselinestretch{\m@m@footnote@spacing}%  
  \reset@font\foottextfont
  \@preamfntext
  \protected@edef\@currentlabel{%
    \csname p@footnote\endcsname\@thefnmark}%
  \setbox0=\vbox{\hsize=\maxdimen
    \color@begingroup
      \noindent \@parafootfmt{#1}%
    \color@endgroup}%
  \m@mungebox}\m@mmf@prepare}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@parafootfmt}
% \cs{@parafootfmt}\marg{text} is a paragraph version of
% \cs{@footfmt}
%    \begin{macrocode}
\newcommand{\@parafootfmt}[1]{%
  \parindent=\z@
  \parfillskip=0pt \@plus 1fil
  {\footfootmark\strut {\foottextfont #1}\penalty-10}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@mpparafootnotetext}
% \cs{@mpparafootnotetext}\marg{text} is a paragraph version of
% \cs{@mpfootnotetext}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
%    \begin{macrocode}
\newcommand{\@mpparafootnotetext}[1]{%
  \global\setbox\@mpfootinsv@r\vbox{%
    \unvbox\@mpfootinsv@r
    \def\baselinestretch{\m@m@footnote@spacing}%   
    \reset@font\foottextfont 
    \hsize\columnwidth \@parboxrestore
    \protected@edef\@currentlabel{%
      \csname p@mpfootnote\endcsname\@thefnmark}%
    \setbox0=\vbox{\hsize=\maxdimen
      \color@begingroup
      \noindent \@parafootfmt{#1}%
      \color@endgroup}%
  \m@mungebox}\m@mmf@prepare}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\paragraphfootstyle}
% \cs{paragraphfootstyle}\marg{series} specifies paragraphed footnote style
% for \meta{series}.
%    \begin{macrocode}
\newcommand{\paragraphfootstyle}[1]{%
  \m@make@parafootnotetext{#1}%
  \m@make@mpparafootnotetext{#1}%
  \m@make@parafootfmt{#1}%
  \m@make@para@footgroup{#1}%
  \m@make@mppara@footgroup{#1}%
  \m@make@para@footstart{#1}%
  \@namelongdef{@footnotetext#1}##1{%
    \@nameuse{@parafootnotetext#1}{##1}}%
  \@namelongdef{@mpfootnotetext#1}##1{%
    \@nameuse{@mpparafootnotetext#1}{##1}}%
  \@namedef{@footgroup#1}{\@nameuse{@para@footgroup#1}}%
  \@namedef{mp@footgroup#1}{\@nameuse{@mppara@footgroup#1}}%
  \@namedef{@footstart#1}{\@nameuse{@para@footstart#1}}%
  \expandafter\dimen\csname footins#1\endcsname=\footinsdim
  \expandafter\count\csname footins#1\endcsname=1000\relax
  {\@nameuse{foottextfont#1}%
   \dimen0=\baselineskip
   \multiply\dimen0 by 1024
   \divide\dimen0 by \hsize \multiply\dimen0 by 64
   \xdef\footfudgefactor{\expandafter\strip@pt\dimen0 }}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@parafootnotetext}
% \cs{m@make@parafootnotetext}\marg{series} creates
% \cs{@parafootnotetext}\meta{series} 
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
%    \begin{macrocode}
\newcommand{\m@make@parafootnotetext}[1]{%
\@namelongdef{@parafootnotetext#1}##1{%
  \insert\@nameuse{footins#1}{
  \def\baselinestretch{\m@m@footnote@spacing}%   
  \reset@font\@nameuse{foottextfont#1}%
  \@preamfntext
  \protected@edef\@currentlabel{%
    \csname p@footnote#1\endcsname \@nameuse{@thefnmark#1}}%
  \setbox0=\vbox{\hsize=\maxdimen
    \color@begingroup
      \noindent \@nameuse{@parafootfmt#1}{##1}%
    \color@endgroup}%
  \m@mungebox}\m@mmf@prepare}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@mpparafootnotetext}
% \cs{m@make@mpparafootnotetext}\marg{series} creates
% \cs{@mpparafootnotetext}\meta{series} 
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
%    \begin{macrocode}
\newcommand{\m@make@mpparafootnotetext}[1]{%
\@namelongdef{@mpparafootnotetext#1}##1{%
  \global\setbox\@nameuse{@mpfootins#1}\vbox{%
    \unvbox\@nameuse{@mpfootins#1}
    \def\baselinestretch{\m@m@footnote@spacing}%   
    \reset@font\@nameuse{foottextfont#1}%
    \hsize\columnwidth \@parboxrestore
    \protected@edef\@currentlabel{%
      \csname p@mpfootnote#1\endcsname\@nameuse{@thefnmark#1}}%
    \setbox0=\vbox{\hsize=\maxdimen
      \color@begingroup
        \noindent \@nameuse{@parafootfmt#1}{##1}%
      \color@endgroup}%
    \m@mungebox}\m@mmf@prepare}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@parafootfmt}
% \cs{m@make@parafootfmt}\marg{series} creates
% \cs{@parafootfmt}\meta{series} 
% \changes{v1.61}{2004/03/14}{Removed space from \cs{m@make@parafootfmt} [RS]}
%    \begin{macrocode}
\newcommand{\m@make@parafootfmt}[1]{%
\@namelongdef{@parafootfmt#1}##1{%
  \parindent=\z@
  \parfillskip=0pt \@plus 1fil
  {\@nameuse{footfootmark#1}\strut 
   {\@nameuse{foottextfont#1}##1}\penalty-10}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@para@footgroup}\marg{series} creates
% \cs{@para@footgroup}\meta{series}
%    \begin{macrocode}
\newcommand{\m@make@para@footgroup}[1]{%
\@namedef{@para@footgroup#1}{%
  \unvbox\@nameuse{footins#1}
  \m@mmakehboxofhboxes
  \setbox0=\hbox{\unhbox0 \m@mremovehboxes}%
  \@nameuse{foottextfont#1}%
  \noindent\unhbox0\par}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@mppara@footgroup}
% \cs{m@make@mppara@footgroup}\marg{series} creates
% \cs{@mppara@footgroup}\meta{series} 
%    \begin{macrocode}
\newcommand{\m@make@mppara@footgroup}[1]{%
\@namedef{@mppara@footgroup#1}{%
  \unvbox\@nameuse{@mpfootins#1}
  \m@mmakehboxofhboxes
  \setbox0=\hbox{\unhbox0 \m@mremovehboxes}%
  \@nameuse{foottextfont#1}%
  \noindent\unhbox0\par}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@make@para@footstart}
% \cs{m@make@para@footstart}\marg{series} creates
% \cs{@para@footstart}\meta{series} 
%    \begin{macrocode}
\newcommand{\m@make@para@footstart}[1]{%
\@namedef{@para@footstart#1}{%
  \vskip\bigskipamount
  \leftskip=\z@
  \rightskip=\z@
  \parindent=\z@
  \vskip\skip\@nameuse{footins#1}%
  \footnoterule}}

%    \end{macrocode}
% \end{macro}
%
% \subsection{Nasty insert bits}
% \changes{v1.61803}{2008/01/30}{Put \cs{@makecol} and associated code
%           into new section `Nasty insert bits' (mempatch various)}
%
% \cs{sidebar} is implemented as a new kind of \cs{insert} and the 
% extended footnotes are also implemented via new kinds of \cs{insert}s.
% New \cs{insert}s mean that the kernel's \cs{@makecol} must be revised
% to cater for them. As this is part of the output process it is nasty to
% do.
%
% Before v1.61803 \cs{@makecol} got (re)defined at several points in the 
% code. Here is what I hope is the final version od \cs{@makecol} and
% associated code after having resolved and combined all the changes.
%
%
% \begin{macro}{\if@mem@nofoot}
% \begin{macro}{\@mem@testifnofoot}
% \begin{macro}{\@mem@extranofoot}
% These are from [RS] as \cs{@doclearpage} should check for more than
% just \cs{footins} being void. Note that this covers all current
% class defined inserts, including sidebars.
% \changes{v1.61}{2004/03/14}{Added \cs{if@mem@nofoot}, 
%                              \cs{@mem@testifnofoot}, and
%                              \cs{@mem@extranofoot}}
%    \begin{macrocode}
\newif\if@mem@nofoot
\newcommand*{\@mem@testifnofoot}{%
  \@mem@nofoottrue
  \ifvoid\footins\else\@mem@nofootfalse\fi
  \ifvoid\footinsv@r\else\@mem@nofootfalse\fi
  \ifvoid\sideins\else\@mem@nofootfalse\fi
  \@mem@extranofeet}
\newcommand*{\@mem@extranofeet}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\memold@doclearpage}
% \begin{macro}{\mem@doclearpage}
% \begin{macro}{\@doclearpage}
% I thought that I could get away with using the kernel's 
% \cs{@doclearpage} but [RS] discovered that I couldn't.
% \changes{v1.62}{2004/03/14}{Redid \cs{@doclearpage} using [RS] code}
% \changes{v3.7d}{2015/04/23}{Opdated \cs{mem@doclearpage} to match
% \Lpack{fixltx2e} v1.1s (which will be the base of the ltx kernel for
% TL15)}
%    \begin{macrocode}
\let\memold@doclearpage\@doclearpage
\newcommand{\mem@doclearpage}{%
  \@mem@testifnofoot
  \if@mem@nofoot
    \setbox\@tempboxa\vsplit\@cclv to\z@ \unvbox\@tempboxa
    \setbox\@tempboxa\box\@cclv
    \xdef\@deferlist{\@toplist\@botlist\@deferlist}%
    \global \let \@toplist \@empty
    \global \let \@botlist \@empty
    \global \@colroom \@colht
    \ifx \@currlist\@empty
    \else
       \@latexerr{Float(s) lost}\@ehb
       \global \let \@currlist \@empty
    \fi
    \@makefcolumn\@deferlist
    \@whilesw\if@fcolmade \fi{\@opcol\@makefcolumn\@deferlist}%
    \if@twocolumn
      \if@firstcolumn
        \xdef\@deferlist{\@dbltoplist\@deferlist}%
        \global \let \@dbltoplist \@empty
        \global \@colht \textheight
        \begingroup
           \@dblfloatplacement
           \@makefcolumn\@deferlist
           \@whilesw\if@fcolmade \fi{\@outputpage
                                     \@makefcolumn\@deferlist}%
         \endgroup
       \else
        \vbox{}\clearpage
      \fi
    \fi
    \ifx\@deferlist\@empty \else\clearpage \fi
  \else
    \setbox\@cclv\vbox{\box\@cclv\vfil}%
    \@makecol\@opcol
    \clearpage
  \fi
  % older version
  %   \setbox\@tempboxa\vsplit\@cclv to\z@ \unvbox\@tempboxa
  %   \setbox\@tempboxa\box\@cclv
  %   \xdef\@deferlist{\@toplist\@botlist\@deferlist}%
  %   \global\let\@toplist\@empty
  %   \global\let\@botlist\@empty
  %   \global\@colroom\@colht
  %   \ifx \@currlist\@empty
  %   \else
  %     \@latexerr{Float(s) lost}\@ehb
  %     \global\let\@currlist\@empty
  %   \fi
  %   \@makefcolumn\@deferlist
  %   \@whilesw\if@fcolmade \fi{\@opcol\@makefcolumn\@deferlist}%
  %   \if@twocolumn
  %     \if@firstcolumn
  %       \xdef\@dbldeferlist{\@dbltoplist\@dbldeferlist}%
  %       \global\let\@dbltoplist\@empty
  %       \global\@colht\textheight
  %       \begingroup
  %         \@dblfloatplacement
  %         \@makefcolumn\@dbldeferlist
  %         \@whilesw\if@fcolmade \fi{\@outputpage
  %                                   \@makefcolumn\@dbldeferlist}%
  %       \endgroup
  %     \else
  %       \vbox{}\clearpage
  %     \fi
  %   \fi
  % \else
  %   \setbox\@cclv\vbox{\box\@cclv\vfil}%
  %   \@makecol\@opcol
  %   \clearpage
  % \fi
}
%    \end{macrocode}
% Replace the kernel's \cs{@doclearpage}.
%    \begin{macrocode}
\gdef\@doclearpage{\mem@doclearpage}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\m@m@makecolfloats}
% \begin{macro}{\m@m@makecoltext}
% These two macros contain code common to versions of \cs{@makecol}
%    \begin{macrocode}
\newcommand*{\m@m@makecolfloats}{%
  \xdef\@freelist{\@freelist\@midlist}%
  \global\let\@midlist\@empty
  \@combinefloats}
\newcommand*{\m@m@makecoltext}{%
  \ifvbox\@kludgeins
    \@makespecialcolbox
  \else
    \setbox\@outputbox \vbox to\@colht{%
      \@texttop
      \dimen@ \dp\@outputbox
      \unvbox \@outputbox
      \vskip -\dimen@
      \@textbottom}%
  \fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@m@makecolintro}
% A hook into the revised \cs{@makecol}
%    \begin{macrocode}
\newcommand*{\m@m@makecolintro}{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mopfootnote}
% (footnote) code for possible use in \cs{@makecol}.
% \changes{v3.7d}{2015/04/21}{Added feature to force footnotes to the
% bottom of the page in a ragged context}
%    \begin{macrocode}
\newcommand*{\m@mopfootnote}{\setbox\@outputbox \vbox{%
  \boxmaxdepth\@maxdepth
  \@tempdima\dp\@cclv
  \unvbox\@cclv
  \vskip-\@tempdima
%    \end{macrocode}
% We then add a macro call that is only activated if we are not using
% \cs{flushbottom}. If \cs{feetatbottom} is active, then a
% \cs{vfill} is added. Solution inspired by \Lpack{footmisc}.
%    \begin{macrocode}
  \mem@if@flushbottomF\m@mopfn@bottom
  \vskip \skip\footins
  \color@begingroup
    \normalcolor
    \footnoterule
    \unvbox \footins
  \color@endgroup}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mopfootnotebf}
% (footnote) code in support of footnotes below floats.
% Problem with original code noted by J{\o}rgen Larsen (\url{jl@ruc.dk})
% on 2008/05/24. Updated 2015.
% \changes{v1.618033}{2008/06/02}{Added \cs{m@mopfootnotebf}}
% \changes{v3.7d}{2015/04/21}{Added feature to force footnotes to the
% bottom of the page in a ragged context}
%    \begin{macrocode}
\newcommand*{\m@mopfootnotebf}{%
  \setbox\@outputbox \vbox{%
  \boxmaxdepth\@maxdepth
  \unvbox\@outputbox
%    \end{macrocode}
% We then add a macro call as above.
%    \begin{macrocode}
  \mem@if@flushbottomF\m@mopfn@bottom
  \vskip\skip\footins
  \color@begingroup
    \normalcolor
    \footnoterule
    \unvbox \footins
  \color@endgroup}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mopsidebar}
% (sidebar) code for possible use in \cs{@makecol}.
% From DA's latest sidebar fixes.
%    \begin{macrocode}
\newcommand*{\m@mopsidebar}{%
  \ifvoid\sideins\else
    \setbox\@outputbox \vbox{%
      \sidecontents
      \unvbox\@outputbox}
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@makecol}
% DA's latest version of \cs{@makecol} (giving the standard 
% footnote order (bottom floats after footnotes)) putting the sidebar
% insert after the others (from mempatch v4.9). The code is renewed on
% page~\pageref{makecol} onwards.
%    \begin{macrocode}
 % \gdef\mem@makecol{%
 %   \m@m@makecolintro
 %   \ifvoid\footins
 %     \setbox\@outputbox \box\@cclv
 %   \else
 %     \m@mopfootnote
 %   \fi
 %   \m@mdoextrafeet
 %   \m@m@makecolfloats
 %   \m@mopsidebar
 %   \m@m@makecoltext
 %   \global \maxdepth \@maxdepth}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@makecolbf}
% A version of \cs{@makecol} which puts footnotes at the bottom of the page
% (after any bottom floats). The code is renewed on
% page~\pageref{makecol} onwards.
% \changes{v1.618033}{2008/06/02}{Used \cs{m@mopfootnotebf} instead of
%                     \cs{m@mopfootnote} in \cs{mem@makecolbf}}
%    \begin{macrocode}
 % \gdef\mem@makecolbf{%
 %   \m@m@makecolintro
 %   \setbox\@outputbox \box\@cclv
 %   \m@m@makecolfloats
 %   \ifvoid\footins\else
 %     \m@mopfootnotebf
 %   \fi
 %   \m@mdoextrafeet
 %   \m@mopsidebar
 %   \m@m@makecoltext
 %   \global\maxdepth \@maxdepth}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@makecoldblf}
% A version of \cs{@makecol} which is a placeholder to fix the doublefloat
% problem. 
%
%    \begin{macrocode}
\gdef\mem@makecoldblf{%
  \m@m@makecolintro
  \setbox\@outputbox \box\@cclv
  \m@m@makecolfloats
  \m@mopsidebar%    <- added
  \ifvoid\footins
  \else
    \m@mopfootnote
  \fi
  \m@mdoextrafeet
  \m@m@makecoltext
  \global \maxdepth \@maxdepth}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\feetabovefloat}
% \begin{macro}{\feetbelowfloat}
% \begin{macro}{\@makecol}
% declarations to put footnotes above bottom floats (standard \LaTeX)
% or at the bottom of the page
%    \begin{macrocode}
\newcommand{\feetabovefloat}{\gdef\@makecol{\mem@makecol}}
\newcommand{\feetbelowfloat}{\gdef\@makecol{\mem@makecolbf}}
\feetabovefloat

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\feetatbottom}
% \begin{macro}{\feetbelowragged}
% \begin{macro}{\m@mopfn@bottom}
% \begin{macro}{\mem@if@flushbottomF}
%   If a page is typeset with a ragged bottom then any footnotes are
%   added directly under the text. It may look better if the footnotes
%   are added to the text block from the bottom up.
%    \begin{macrocode}
\newcommand\feetatbottom{\def\m@mopfn@bottom{\vfill\relax}}
\newcommand\feetbelowragged{\let\m@mopfn@bottom\relax}
\feetbelowragged
%    \end{macrocode}
% Next we add a test to see if \cs{flushbottom} is active. This macro
% is used within \cs{m@mopfootnote} and \cs{m@mopfootnotebf} to
% force the footnotes to the bottom \emph{only} when \cs{flushbottom}
% is \emph{not} active, hince the \texttt{F} in the name.
%    \begin{macrocode}
\newcommand\mem@if@flushbottomF[1]{%
  \if\mem@flshbot\else#1\fi%
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@reinserts}
% DA's final version from last patch.
% \changes{v3.6d}{2010/06/30}{THere is a newer version further down
% the code}
%    \begin{macrocode}
 % \gdef\@reinserts{%
 % \ifvoid\footins\else\insert\footins{\unvbox\footins}\fi
 % \m@mdodoreinextrafeet
 % \ifvbox\@kludgeins\insert\@kludgeins{\unvbox\@kludgeins}\fi
 %  \ifvoid\sideins\else\insert\sideins{\unvbox\sideins}\fi}

%    \end{macrocode}
% \end{macro}
%
% \changes{v1.61803398d}{2010/01/25}{Added section about side footnotes}
% \subsection{Side footnotes} \label{sec:sidefootnotes}
%
%
% \subsubsection{Extension to the regular footnote}
%
%  The code here enables the regular \cs{footnote} to be set in the
% margin. It is based on Robin Fairbairns' \Lpack{footmisc} package.
%
% \begin{macro}{\ifm@mfnmargin}
% \begin{macro}{\footnotesatfoot}
% \begin{macro}{\footnotesinmargin}
% Declarations for regular footnotes to be set as normal at the foot
% of the page, or in the margin.
%    \begin{macrocode}
\newif\ifm@mfnmargin
\newcommand*{\footnotesatfoot}{\m@mfnmarginfalse}
\newcommand*{\footnotesinmargin}{\m@mfnmargintrue}
\footnotesatfoot

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \changes{v1.61803398d}{2010/01/25}{Remember that we actually have
% several \cs{@footnotetext} in memoir, might be an idea to clean this
% up at some point/daleif}
% \begin{macro}{\@footnotetext}
% \begin{macro}{\m@mold@footnotetext}
% Change \cs{@footnotetext} to enable footnotes to be put into the margin
% by using \cs{marginpar}.
%    \begin{macrocode}
\renewcommand{\@footnotetext}[1]{%
  \ifm@mfnmargin%   use marginpar
%    \end{macrocode}
% Use \cs{marginpar} for placing the footnote.
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
%    \begin{macrocode}
    \marginpar{%
    \def\baselinestretch{\m@m@footnote@spacing}%
    \reset@font
    \foottextfont
    \protected@edef\@currentlabel{%
      \csname p@footnote\endcsname\@thefnmark}%
    \color@begingroup
      \@makefntext{\ignorespaces#1}%
    \color@endgroup}%
  \else% regular feet
%    \end{macrocode}
% This is the original code for \cs{@footnotetext}.
% \changes{v1.618033988c}{2010/02/20}{sporadic spaces removed, error
% reported on texlive mailinglist}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
%    \begin{macrocode}
    \insert\footins{%
    \def\baselinestretch{\m@m@footnote@spacing}%
    \reset@font
    \foottextfont
    \@preamfntext
    \hsize\columnwidth
    \protected@edef\@currentlabel{%
      \csname p@footnote\endcsname\@thefnmark}%
    \color@begingroup
      \@makefntext{%
        \rule\z@\footnotesep\ignorespaces{\foottextfont #1}%
        \@finalstrut\strutbox}%
    \color@endgroup}%
  \fi%
  \m@mmf@prepare}
%    \end{macrocode}
% Need to save this version of \cs{@footnotetext}, it is
% used within \cs{plainfootnotes}.
% \changes{v3.6h}{2010/10/22}{Moved \cs{m@mold@footnotetext} to this
% location, and renamed it to \cs{@plainfootnotetext}}
%    \begin{macrocode}
\let\@plainfootnotetext\@footnotetext

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \subsection{Bottom aligned side footnotes}
%
% The code for the bottom aligned marginal footnotes is based partly on
% the \cs{sidebar} code and code from David Salomon, 'Output Routines:
% Examples and Techniques. Part III: Insertions', \textit{TUGboat}, 
% 11, 4, pp 588--605, Nov 1990.
%
% \begin{macro}{\sidefootmargin}
% \begin{macro}{\m@msidefoot@margin}
% \cs{sidefootmargin} is the user command for setting the side for
% side footnotes (stored as \cs{m@msidefoot@margin}). The default
% is \texttt{outer}.
%    \begin{macrocode}
\newcommand*{\sidefootmargin}[1]{%
  \m@msetm@argin{#1}%
  \ifnum\m@mm@argin<\z@
    \@memwarn{Bad \string\sidefootmargin\space argument `#1'\MessageBreak
              set to `outer'}%
    \gdef\m@msidefoot@margin{2}%   set as outer
  \else
    \global\let\m@msidefoot@margin\m@mm@argin
  \fi}
\sidefootmargin{outer}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\sidefootins}
% As for any non-main text matter we need an insert.
%    \begin{macrocode}
\newinsert\sidefootins
  \skip\sidefootins=0pt
  \count\sidefootins=0\relax

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sidefootadjust}
% \begin{macro}{\sidefootheight}
% \begin{macro}{\setsidefootheight}
% The length \cs{sidefootadjust} can be used for fine control over the
% vertivcal position of the base of the column of side footnotes. 
% The length \cs{sidefootheight}
% is the height of the column and is best set by the \cs{setsidefootheight}
% macro, which takes the desired height as its argument and sets the height
% of the \cs{sidefootins} \cs{insert}. The height is
% initially set to the \cs{textheight}.
%    \begin{macrocode}
\newlength{\sidefootadjust}
  \setlength{\sidefootadjust}{0pt}
\newlength{\sidefootheight}
\newcommand*{\setsidefootheight}[1]{%
  \setlength{\dimen\sidefootins}{#1}%
  \advance\dimen\sidefootins -\topskip
  \advance\dimen\sidefootins \ht\strutbox
  \setlength{\sidefootheight}{\dimen\sidefootins}}
\setsidefootheight{\textheight}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\sidefoothsep}
% \begin{macro}{\sidefootwidth}
% \begin{macro}{\sidefootvsep}
% The horizontal space between the text block and side footnotes 
% (\cs{sidefoothsep}), 
% the width of the column of notes (\cs{sidefootwidth}),
% and the vertical space between consecutive side footnotes
% (\cs{sidefootvsep}). 
% \changes{v1.61803398d}{2010/02/05}{removed \cs{sidefootfont}}
%    \begin{macrocode}
\newlength{\sidefoothsep}
\newlength{\sidefootvsep}
\newlength{\sidefootwidth}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setsidefeet}
% The macro \cs{setsidefeet}\marg{hsep}\marg{width}\marg{vsep}\marg{adj}\marg{font}\marg{height}
% sets the specifications for the side footnotes. An `*' means `use
% the current 
% value'.
% \changes{v1.61803398d}{2010/02/05}{changed \cs{sidefootfont} to 
% \cs{sidefoottextfont}}
%
%    \begin{macrocode}
\newcommand*{\setsidefeet}[6]{%
  \nametest{#1}{*}\ifsamename\else
    \setlength{\sidefoothsep}{#1}\@memznegtest{\sidefoothsep}%
  \fi
  \nametest{#2}{*}\ifsamename\else
    \setlength{\sidefootwidth}{#2}\@memznegtest{\sidefootwidth}%
  \fi
  \nametest{#3}{*}\ifsamename\else
    \setlength{\sidefootvsep}{#3}\@memznegtest{\sidefootvsep}%
  \fi
  \nametest{#4}{*}\ifsamename\else
    \setlength{\sidefootadjust}{#4}%
  \fi
  \nametest{#5}{*}\ifsamename\else
    \def\sidefoottextfont{#5}%
  \fi
  \nametest{#6}{*}\ifsamename\else
    \setsidefootheight{#6}%
    \ifdim\dimen\sidefootins>\z@\else
      \@memerror{\protect\sidefootheight\space is zero or negative}{\@ehd}%
    \fi
  \fi}
\setsidefeet{\marginparsep}{\marginparwidth}%
            {\onelineskip}{0pt}%
            {\normalfont\footnotesize}{\textheight}%

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\sidefootform}
% Set the sidefootnotes raggedy right
%    \begin{macrocode}
\newcommand*{\sidefootform}{\rightskip=\z@ \@plus 2em}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\m@sideft@left}
% \begin{macro}{\m@sideft@right}
% Macros placing the sidefootnotes at the left and the right respectively.
%    \begin{macrocode}
\newcommand*{\m@sideft@left}{%
  \@tempdimc \sidefootwidth
  \advance\@tempdimc\sidefoothsep
  \kern-\@tempdimc}
\newcommand*{\m@sideft@right}{%
  \@tempdimc \columnwidth% or \hsize
  \advance\@tempdimc\sidefoothsep
  \kern\@tempdimc}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mdownsf}
% A length used in the vertical positioning of sidefootnotes.
% (Perhaps one of the \cs{@tempdim} lengths could be used instead?)
%    \begin{macrocode}
\newlength{\m@mdownsf}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sidefootcontents}
% The essence of the sidefootnote task. This first positions the column 
% to the left or the right and then tries to make the bottom of the 
% column align with the bottom of the textblock.
%    \begin{macrocode}
\newcommand*{\sidefootcontents}{\hbox to \z@{%
  \m@mwhich@margin{\m@msidefoot@margin}%
  \ifmemtortm
    \m@sideft@right
  \else
    \m@sideft@left
  \fi
%    \end{macrocode}
% Now the fun part. The general idea is to measure the height of the insert's 
% contents, subtract this from the specified height of the insert, 
% and move the contents down by that amount.
% The code below seems to work except when sidefootnotes
% spill over to the following page; also, like \cs{sidebar}, 
% they are out of vertical alignment when on a \cs{chapter} page. 
% I haven't found a way to automatically
% adjust for these, which is why the \cs{sidefootadjust} length is
% there to enable manual adjustment.
% \changes{v1.61803398d}{2010/02/05}{changed \cs{sidefootfont} 
% to \cs{sidefoottextfont}}
%    \begin{macrocode}
  \vtop to 0pt{%    original
    \normalsize\normalfont\sidefoottextfont
    \vskip\topskip \vskip-\ht\strutbox
    \vskip\sidefootadjust%    use this for minor vertical adjustment
    \m@mdownsf=\dimen\sidefootins
    \advance\m@mdownsf-\ht\sidefootins
    \advance\m@mdownsf-\dp\sidefootins
%    \end{macrocode}
% Here's where the fiddling occurs, arrived at by a mixture of theory and 
% experiment.
%    \begin{macrocode}
    \ifdim\m@mdownsf>\sidefootvsep
      \advance\m@mdownsf\sidefootvsep
      \advance\m@mdownsf 0.5\ht\strutbox
    \fi
    \vskip\m@mdownsf%     --- basically works
    \unvbox\sidefootins%
    \vss}%
  \hss}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mopsidefoot}
% If there are any sidefeet then add them to the output.
%    \begin{macrocode}
\newcommand*{\m@mopsidefoot}{%
  \ifvoid\sidefootins\else
    \setbox\@outputbox \vbox{%
      \sidefootcontents
      \unvbox\@outputbox}
  \fi}  

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@makecol}
% \begin{macro}{\mem@makecolbf}
% \begin{macro}{\@reinserts}
% \begin{macro}{\@mem@extranofeet}
% \begin{macro}{@mem@testifnofoot}
% Revise these to cater for the new sidefoot insert.\label{makecol}
% \changes{v3.7c}{2013/11/28}{Spurious space}
%    \begin{macrocode}
\gdef\mem@makecol{%
  \m@m@makecolintro
  \ifvoid\footins
    \setbox\@outputbox \box\@cclv
  \else
    \m@mopfootnote
  \fi
  \m@mdoextrafeet
  \m@m@makecolfloats
  \m@mopsidebar
  \m@mopsidefoot
  \m@m@makecoltext
  \global \maxdepth \@maxdepth}

%    \end{macrocode}
%
% \changes{v1.618033988b}{2010/02/17}{a bf was missing in \cs{m@mopfootnotebf}}
% \changes{v3.7c}{2013/11/28}{Spurious space}
%    \begin{macrocode}
\gdef\mem@makecolbf{%
  \m@m@makecolintro
  \setbox\@outputbox \box\@cclv
  \m@m@makecolfloats
  \ifvoid\footins
  \else
    \m@mopfootnotebf
  \fi
  \m@mdoextrafeet
  \m@mopsidebar
  \m@mopsidefoot
  \m@m@makecoltext
  \global \maxdepth \@maxdepth}

%    \end{macrocode}
% \changes{v3.6d}{2010/06/30}{There should not be an \cs{else} on the
% kludge line}
% \changes{v3.6f}{2010/08/22}{There should not be an \cs{else} on the
% kludge line, then remember to remove it}
%    \begin{macrocode}
\gdef\@reinserts{%
  \ifvoid\footins\else\insert\footins{\unvbox\footins}\fi
  \m@mdodoreinextrafeet
  \ifvbox\@kludgeins\insert\@kludgeins{\unvbox\@kludgeins}\fi
  \ifvoid\sideins\else\insert\sideins{\unvbox\sideins}\fi
  \ifvoid\sidefootins\else\insert\sidefootins{\unvbox\sidefootins}\fi}

%    \end{macrocode}
%
% The easy way of extending the \cs{clearpage} code is by:
% \begin{verbatim}
% \renewcommand*{\@mem@extranofeet}{%
%  \ifvoid\sidefootins\else\@mem@nofootfalse\fi}
% \end{verbatim}
% but as so many other changes have to be made it's probably better to
% leave that alone and change \cs{@mem@testifnofoot} directly.
%    \begin{macrocode}
\renewcommand*{\@mem@testifnofoot}{%
  \@mem@nofoottrue
  \ifvoid\footins\else\@mem@nofootfalse\fi
  \ifvoid\footinsv@r\else\@mem@nofootfalse\fi
  \ifvoid\sideins\else\@mem@nofootfalse\fi
  \ifvoid\sidefootins\else\@mem@nofootfalse\fi
  \@mem@extranofeet}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsubsection{The sidefootnote macros}
%
% The macros here are essentially a copy of the ones for \cs{footnote}.
% I have not done anything about sidefootnotes in minipages, as I can't
% imagine a use for them while simultaneously making the final appearance
% looking good.
%
% The usual counter.
%    \begin{macrocode}
\newcounter{sidefootnote}
  \renewcommand{\thesidefootnote}{\@arabic\c@sidefootnote}
\@addtoreset{sidefootnote}{chapter}

%    \end{macrocode}
%
% By using: \\
% \verb?\letcountercounter{sidefootnote}{footnote}? \\
% the same counter will be used for both footnotes and sidefootnotes.
% This can be reverted to separate counters by; \\
% \verb?\unletcounter{sidefootnote}?
%
% \begin{macro}{\sidefoottextfont}
% The font for the sidefootnotes.
% \changes{v1.61803398d}{2010/02/06}{\cs{sidefoottextfont} is already
% defined by the initial issuing of \cs{setsidefeet}}
%    \begin{macrocode}
%\newcommand*{\sidefoottextfont}{\normalfont\footnotesize}

%    \end{macrocode}
% \end{macro}
%
% The remainder of the code is a copied from that for \cs{footnote}
% but with the appropriate variables for \cs{sidefootnote}s
%
% \begin{macro}{\@sidempfn}
% \begin{macro}{\thesidempfn}
%    \begin{macrocode}
\newcommand*{\@sidempfn}{sidefootnote}
\newcommand*{\thesidempfn}{\thesidefootnote}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@makesidefnmark}
%    \begin{macrocode}
\newcommand*{\@makesidefnmark}{\hbox{\@textsuperscript{%
  \normalfont\@thesidefnmark}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@preamsidefntext}
%    \begin{macrocode}
\newcommand{\@preamsidefntext}{%
  \interlinepenalty\interfootnotelinepenalty
  \floatingpenalty \@MM
  \splittopskip=\footnotesep
  \splitmaxdepth=\dp\strutbox
  \@parboxrestore}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@sidefootnotetext}
% \changes{v1.61803398d}{2010/02/05}{changed \cs{sidefootfont} 
% to \cs{sidefoottextfont}}
% \changes{v3.6g}{2010/09/19}{made 'single spacing' configurable}
%    \begin{macrocode}
\newcommand{\@sidefootnotetext}[1]{\insert\sidefootins{%
  \hsize\sidefootwidth
  \@parboxrestore
    \def\baselinestretch{\m@m@footnote@spacing}%
  \sidefootform \normalsize\normalfont\sidefoottextfont
  \splittopskip=\ht\strutbox
  \splitmaxdepth=\dp\strutbox
  \allowbreak
  \prevdepth=\dp\strutbox
  \vskip-\parskip
  \protected@edef\@currentlabel{%
    \csname p@sidefootnote\endcsname\@thesidefnmark}%
\color@begingroup
\@makesidefntext{{\sidefoottextfont #1}}%
\color@endgroup
  \ifvmode\else
    \unskip\@finalstrut\strutbox
  \fi
  \par
  \ifdim\prevdepth>\dp\strutbox \prevdepth=\dp\strutbox\fi
  \ifdim\prevdepth>99\p@
    \nobreak
    \vskip-\prevdepth
    \allowbreak
    \vskip\dp\strutbox
  \fi
  \vskip\sidefootvsep}%
  \m@mmf@prepare}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@sidefootnotemark}
%    \begin{macrocode}
\newcommand*{\@sidefootnotemark}{%
  \leavevmode
  \ifhmode
    \edef\@x@sf{\the\spacefactor}%
    \m@mmf@check
    \nobreak
  \fi
  \@makesidefnmark
  \m@mmf@prepare
  \ifhmode\spacefactor\@x@sf\fi
  \relax}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sidefootnote}
%    \begin{macrocode}
\newcommand*{\sidefootnote}{\@ifnextchar[ 
  \@xsidefootnote{\stepcounter\@sidempfn
  \protected@xdef\@thesidefnmark{\thesidempfn}%
  \@sidefootnotemark\@sidefootnotetext}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@xsidefootnote}
%    \begin{macrocode}
\def\@xsidefootnote[#1]{%
  \begingroup
    \csname c@\@sidempfn\endcsname #1\relax
    \unrestored@protected@xdef\@thesidefnmark{\thesidempfn}%
  \endgroup
  \@sidefootnotemark\@sidefootnotetext}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sidefootnotemark}
%    \begin{macrocode}
\newcommand{\sidefootnotemark}{%
  \@ifnextchar[
    \@xsidefootnotemark
      {\stepcounter{sidefootnote}%
       \protected@xdef\@thesidefnmark{\thesidefootnote}%
       \@sidefootnotemark}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@xsidefootnotemark}
%    \begin{macrocode}
\def\@xsidefootnotemark[#1]{%
  \begingroup
    \c@sidefootnote #1\relax
    \unrestored@protected@xdef\@thesidefnmark{\thesidefootnote}%
  \endgroup
  \@sidefootnotemark}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sidefootnotetext}
%    \begin{macrocode}
\newcommand*{\sidefootnotetext}{%
  \@ifnextchar[
    \@xsidefootnotetext
      {\protected@xdef\@thesidefnmark{\thesidempfn}%
       \@sidefootnotetext}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@xsidefootnotetext}
%    \begin{macrocode}
\def\@xsidefootnotetext[#1]{%
  \begingroup
    \csname c@\@sidempfn\endcsname #1\relax
    \unrestored@protected@xdef\@thesidefnmark{\thesidempfn}%
  \endgroup
  \@sidefootnotetext}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sidefootmarkstyle}
% \begin{macro}{\sidefootscript}
% \begin{macro}{\makesidefootmarkhook}
% \begin{macro}{\sidefootfootmark}
%    \begin{macrocode}
\newcommand*{\sidefootmarkstyle}[1]{\def\sidefootscript##1{#1}}
\newcommand*{\makesidefootmarkhook}{}
\newcommand*{\sidefootfootmark}{%
  \ifdim\sidefootmarkwidth < \z@
    \llap{\hb@xt@ -\sidefootmarkwidth{%
          \hss\normalfont\sidefootscript{\@thesidefnmark}}%
         \hspace*{-\sidefootmarkwidth}}%
  \else
    \ifdim\sidefootmarkwidth = \z@
      {\normalfont\sidefootscript{\@thesidefnmark}}%
    \else
      \hb@xt@\sidefootmarkwidth{\hss\normalfont\sidefootscript{\@thesidefnmark}}%
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\makesidefootmark}
% \changes{v1.61803398d}{2010/02/04}{Made \cs{makesidefootmark} long
% as the similar \cs{footnote} command, otherwise one cannot make side
% footnotes containign several paragraphs}
%    \begin{macrocode}
\newcommand{\makesidefootmark}[1]{%
  \leavevmode
  \parindent \sidefootparindent\noindent
  \leftskip\sidefootmarksep\relax
  \advance\leftskip \sidefootmarkwidth \null\nobreak\hskip -\leftskip\relax
  \makesidefootmarkhook\relax
  \sidefootfootmark #1}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@makesidefntext}
%    \begin{macrocode}
\newcommand{\@makesidefntext}[1]{\makesidefootmark #1}

%    \end{macrocode}
% \end{macro}
%
% Final layout.
% \begin{macro}{\sidefootmarkwidth}
% \begin{macro}{\sidefootmarksep}
% \begin{macro}{\sidefootparindent}
% \changes{v1.61803398d}{2010/02/04}{changed the defaults for
% \cs{sidefootmarkwidth} and \cs{sidefootmarksep} to zero, from 1em
% and -1em, looks better with the narrow margins}
%    \begin{macrocode}
\newlength{\sidefootmarkwidth}
  \setlength{\sidefootmarkwidth}{0em}
\newlength{\sidefootmarksep}
  \setlength{\sidefootmarksep}{0em}
\newlength{\sidefootparindent}
  \setlength{\sidefootparindent}{1em}
\sidefootmarkstyle{\textsuperscript{#1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \subsection{End notes}
%
% \changes{v3.6h}{2011/01/19+}{Reimplemented page notes}
% This used to be a copy of the \Lpack{pagenote} package, with minor
% amendments. But it turned out that the implementation used by
% \Lpack{pagenote} at that time, had a few serious flaws. In this
% implementation we will instead turn to the trick used by the
% \Lpack{endnotes} package to overcome the same problem.
% For the sake of history, let us summarise what the actual problem
% was. Basically the command \cs{pagenote}\marg{text} would write an
% entry to an external file in the following format
% \begin{verbatim}
% \noteentry{nom}{id}{text}{pagenum}
% \end{verbatim}
% and when typesetting the page notes, this file would be read into
% the document and \cs{noteentry} would typeset each page note. The
% main problem here is \verb|{text}| which is written verbatimly to
% the external file, but it is written on a single line!, thus an
% input like this
% \begin{verbatim}
% \pagenote{Test%
% test}
% \end{verbatim}
% would give us the entry
% \begin{verbatim}
% \noteentry{num}{id}{Test%test}{pagenum}
% \end{verbatim}
% oops! This is what we will solve using inspiration from
% \Lpack{endnotes}, kudos to  John Lavagnino.
%
%
% \begin{macro}{\ifm@mpnpageopt}
% \begin{macro}{\ifm@mpncontopt}
% We need two flags for the options.
% \cs{m@mpnpageoptfalse} means that page numbers are not available and
% \cs{m@mpncontopt} means that note numbers are reset at each \cs{chapter}.
%    \begin{macrocode}
\newif\ifm@mpnpageopt
  \m@mpnpageoptfalse
\newif\ifm@mpncontopt
  \m@mpncontoptfalse
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\c@pagenote}
% \begin{macro}{\thepagenote}
% We need a counter for the notes. This is the default definition.
%    \begin{macrocode}
\newcounter{pagenote}[chapter]
\renewcommand{\thepagenote}{\arabic{pagenote}}
\setcounter{pagenote}{0}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\notepageref}
% \begin{macro}{\continuousnotenums}
% \changes{v3.6h}{2011/01/19}{Removed references to pagenote package}
%   Let the user change the default options.  \cs{notepageref} makes
%   page numbers available in the typeset list of page note and
%   \cs{continuousnotenums} means that notes will be numbered
%   continuously throughout the document.
%    \begin{macrocode}
\newcommand*{\notepageref}{\m@mpnpageopttrue}
\@onlypreamble\notepageref
\newcommand*{\continuousnotenums}{%
  \counterwithout{pagenote}{chapter}
  \renewcommand{\thepagenote}{\arabic{pagenote}}}
\@onlypreamble\continuousnotenums

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\ifmempagenotes}
% Need to check if notes are required.
%    \begin{macrocode}
\newif\ifmempagenotes
  \mempagenotesfalse

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\makepagenote}
% This sets up the note file. At the end it emasculates itself so it can only
% be used once.
%    \begin{macrocode}
\newcommand*{\makepagenote}{%
  \newwrite\@notefile
  \immediate\openout\@notefile=\jobname.ent
  \mempagenotestrue
%    \end{macrocode}
% \begin{macro}{\pagenote}
% Make sure that this has a useful definition. 
% \changes{v3.6h}{2011/01/19}{Made \cs{pagenote} robust}
% \changes{v3.6j}{2011/03/01}{Removed \cs{@sanitize}}
% \changes{v3.6k}{2011/03/08}{Actually need \cs{@sanitize} for the
% optional argument. But we need to remove spaces from this}
%    \begin{macrocode}
  \DeclareRobustCommand\pagenote{\@bsphack\begingroup
    \rem@special{\ }% <--- added 
    \@sanitize
    \m@m@wrpnote}%
%    \end{macrocode}
% \end{macro}
% \changes{v3.6h}{2011/01/19}{Added the redefinition of \cs{mem@footto@pagenote}}
% \begin{macro}{\mem@footto@pagenote}
% The same as for \cs{pagenote} but here we use a special version of
% the writing macro that will ignore the optional argument. This will
% internally be used when the user ask for foot notes to be turned
% into page notes.
% \changes{v3.6j}{2011/03/01}{Removed \cs{@sanitize}}
% \changes{v3.6k}{2011/03/08}{Actually need \cs{@sanitize} for the
% optional argument. But we need to remove spaces from this}
%    \begin{macrocode}
  \DeclareRobustCommand\mem@footto@pagenote{\@bsphack\begingroup
    \rem@special{\ }% <--- added 
    \@sanitize
    \def\mem@pn@step{01}%
    \m@m@wrpnote}%
%    \end{macrocode}
% \end{macro}
% At the end we make sure \cs{makepagenote} can only do something once.
% \begin{macrocode}
  \typeout{Writing note file \jobname.ent}%
  \let\makepagenote\@empty}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\immediate@protected@write}
% We might have to do some immediate writes. This is an immediate
% version of the kernel \cs{protected@write}.
%    \begin{macrocode}
\newcommand{\immediate@protected@write}[3]{%
  \begingroup
  #2%
  \let\protect\@unexpandable@protect
  \edef\reserved@a{\immediate\write#1{#3}}%
  \reserved@a
  \endgroup
  \if@nobreak\ifvmode\nobreak\fi\fi}

%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\m@m@pnwrite} 
% \begin{macro}{\m@m@pnwrited} 
% In the old implementation we used \cs{immediate@protected@write}
% unless the user asked for page numbers in the notes, the new
% implementation use the same writing method for all cases, for easy
% of notation we collect it in a macro. Seems UTF8 is an interesting
% beast, \cs{immediate@protected@write} can write it to disk, but
% \cs{m@m@pnwrite} cannot. To get past this we also include a version
% that has an embedded \cs{detokenize} (thanks to Heiko Oberdiek for
% that hint).
% \changes{v3.6k}{2011/04/06}{Added the version with \cs{detokenize}}
%    \begin{macrocode}
\newcommand{\m@m@pnwrite}[3]{\immediate\write#1{#3}}
\newcommand{\m@m@pnwrited}[3]{\immediate\write#1{\detokenize{#3}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\pnchap}
% \begin{macro}{\pnschap}
% Redefine these for different subheadings in the notes list.
%    \begin{macrocode}
\newcommand*{\pnchap}{\f@rtoc}
\newcommand*{\pnschap}{\f@rbdy}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \begin{macro}{\c@pagenoteshadow}
% \begin{macro}{\mem@pn@step}
% \begin{macro}{\mem@pn@lastkern}
% Utilities, a counter to provide us with a unique name for each page
% note, a toggle macro and a length to hold a lastkern (because
% someone may hide it from us).
%    \begin{macrocode}
\newcounter{pagenoteshadow}
  \setcounter{pagenoteshadow}{0}
\newcommand\mem@pn@step{00} % i.e. true
\newlength\mem@pn@lastkern
%    \end{macrocode}
%  
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@m@wrpnote}
% This writes the note information to the note file. If the optional argument
% is empty it increments the
% note counter and calls \cs{notenumintext} to handle its appearance in 
% the body text. We write an entry of the following design
% \begin{verbatim}
% \startnoteentry{notenumber}{id}{auto label key}{hyperref}
% macro:->text
% \endnoteentry
% \end{verbatim}
% 
% \begin{macro}{\m@m@pnwrite@fourtharg}
% \begin{macro}{\m@m@pnwrite@fourtharg@hyperref}
% In order for us to add \Lpack{hyperref} support we will need to
% record the hyperref anchor label into the page note data. We do this
% though \verb|\m@m@pnwrite@fourtharg|, which by default just adds
% \verb|{}| to the page note data. \Lpack{memhfixc} makes it point
% toward \verb|\m@m@pnwrite@fourtharg@hyperref| instead. We make sure
% to pass it the optional argument from \verb?\pagenote?, if this is
% precent a hyper anchor is not passed on.
% \changes{v3.6k}{2013/05/17}{Macro needs to test an argument}
%    \begin{macrocode}
\newcommand\m@m@pnwrite@fourtharg[1]{\m@m@pnwrited\@notefile{}{{}}}
\newcommand\m@m@pnwrite@fourtharg@hyperref[1]{%
  \@ifmtarg{#1}{%
    \m@m@pnwrite\@notefile{}{{\Hy@pagenote@currentHref}}%
  }{%
    \m@m@pnwrited\@notefile{}{{}}%
  }}

%    \end{macrocode}
% \end{macro}
%   % \end{macro}
% 
% \changes{v1.61803}{2008/05/25}{Made \cs{m@m@wrpnote} match the effect 
%                    described in memman regarding the optional argument.}
% \changes{v3.6h}{2011/01/19}{Changed the internal implementation}
%    \begin{macrocode}
\newcommand{\m@m@wrpnote}[2][]{%
%    \end{macrocode}
% If \Lpack{hyperref} is loaded it issues a whatisit and thus
% hide/reset the last kern, which is needed for the algorithm used for
% the multiple notes in a row feature (adding commas). So we start by
% storing the last kern, and refstep a shadow counter such that we
% can generate more or less unique label keys.
%    \begin{macrocode}
  \mem@pn@lastkern=\lastkern% 
  \refstepcounter{pagenoteshadow}% 
%    \end{macrocode}
% If the user asks for it enable page back refs, we use labels and
% references for this (bonus: automatic support for hyperlinks if
% \Lpack{hyperref} is available).
%    \begin{macrocode}
  \ifm@mpnpageopt%
    \phantomsection%
    \label{pagenote\thepagenoteshadow-\thesheetsequence}%
  \fi%
%    \end{macrocode}
% Next we want to be able to reuse this macro just for writing the
% entry to disk, no writing a marker in the text (think replacement
% for \cs{footnotetext}), we use the toggle for this and also remember
% to re-insert the code needed for comma separated multiple markers
%    \begin{macrocode}
  \if\mem@pn@step%
    \@ifmtarg{#1}{\refstepcounter{pagenote}%
      % this enables the ^{1,2} feature
      \ifdim\mem@pn@lastkern=\multiplefootnotemarker%
        \m@mmf@prepare% rerun
      \fi%
      \mem@pn@multiple@marker{\notenumintext{\thepagenote}}% 
    }{}%
  \fi%
%    \end{macrocode}
% Check if this is the first note in a division, and if so indicate this 
% in the file.
% \changes{v3.6h}{2011/01/25}{Added \cs{pagenotesubheadstarred}}
%    \begin{macrocode}
  \ifm@mpn@new@chap%
    \global\m@mpn@new@chapfalse%
    \addtonotes{\string\pagenotesubhead{\@chapapp}{\thechapter}{\pnchap}}%
  \fi%
  \ifm@mpn@new@schap%
    \global\m@mpn@new@schapfalse%
    \addtonotes{\string\pagenotesubheadstarred{\@chapapp}{}{\pnschap}}%
  \fi%
%    \end{macrocode}
% Next we write to the notes file. Instead of writing everything as a
% macro with arguments, we will use three writes. One to start a new
% entry with a few (non-text) arguments, then the text itself, and
% finally an end of entry marker macro. There is a slight complication
% here. The \verb|#1| may be UTF8 so it has to be written unexpanded
% to disk, but macros like \verb|\thepagenote| need to be
% expanded. Luckily \TeX\ eats up spaces when reading arguments, so we
% simply writte several lines using two different writing methods.
% \changes{v3.6k}{2011/04/06}{Rewritten to use a different writing method}
%    \begin{macrocode}
  \m@m@pnwrite\@notefile{}%
    {\string\startnoteentry{\thepagenote}}%
  \m@m@pnwrited\@notefile{}{{#1}}%
  \m@m@pnwrite\@notefile{}%
    {{pagenote\thepagenoteshadow-\thesheetsequence}}%
%    \end{macrocode}
% Add the fourth argument.
% \changes{v3.6k}{2013/05/16}{Added fourth argument for the note data}
% \changes{v3.6k}{2013/05/17}{Fourth arg, should depend on \#1}
%    \begin{macrocode}
  \m@m@pnwrite@fourtharg{#1}%
%    \end{macrocode}
% Getting the newline stuff to work require
% \verb|\immediate\write| which we defined earlier. We then write the
% text `verbatimly' using the detokenized macro.
% \changes{v3.6k}{2011/04/06}{No longer any need for the \cs{meaning} construction.}
%    \begin{macrocode}
  \begingroup%
    \newlinechar='40%
    \m@m@pnwrited\@notefile{}{#2}%
  \endgroup%
%    \end{macrocode}
% Remember to also write a marker that ends the entry.
%    \begin{macrocode}
  \m@m@pnwrite\@notefile{}%
  {\string\endnoteentry}%
  \endgroup%
  \@esphack}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pagenote}
% \begin{macro}{\mem@footto@pagenote}
% The user command to generate a note. It is given substance 
% by \cs{makepagenote}. Supplied with a special version used if the
% user asks for all footnotes to be turned into page notes.
% \changes{v3.6h}{2011/01/19}{Added \cs{mem@footto@pagenote}}
%    \begin{macrocode}
\def\pagenote{\@bsphack\begingroup \@sanitize\m@m@pagenote}
\let\mem@footto@pagenote\pagenote
%    \end{macrocode}
% \end{macro}
% \end{macro}
% 
% \begin{macro}{\m@m@pagenote}
%    \begin{macrocode}
\newcommand{\m@m@pagenote}[2][]{\endgroup\@esphack}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pagetofootnote}
% \begin{macro}{\foottopagenote}
% \begin{macro}{\memsavefootnote}
% \begin{macro}{\memsavepagenote}
%  Let the user change pagenotes to footnotes, or vice-versa. In either
% case the optional argument is ignored.
% \changes{v3.6h}{2010/12/07}{\cs{footnote} should be long}
% \changes{v3.6h}{2010/12/09}{because of the way
% \cs{pagenote} is defined, we cannot redefine \cs{footnote} to have
% any arguments, we need to go another route}
% \changes{v3.6h}{2010/12/09}{Added a check for the race condition}
% We have a race condition, if both \cs{pagetofootnote} and
% \cs{makepagenote} is issued in the same  document,
% \cs{pagetofootnote} need to come last. 
%    \begin{macrocode}
\newcommand*{\pagetofootnote}{%
  \let\memsavepagenote\pagenote
  \renewcommand{\pagenote}[2][]{\footnote{##2}}
%    \end{macrocode}
% Basic idea is, if pagenotes mode is on when \cs{pagetofootnote} is
% issued, everything is fine. Else we test at end document (because
% \cs{makepagenote} can go anywhere).
%    \begin{macrocode}
  \ifmempagenotes\else% 
    \AtEndDocument{%
      \ifmempagenotes% 
      \@memerror{The use of \string\pagetofootnote\space before
        \string\makepagenote\space^^Jdoes not make
        sense. \string\makepagenote\space make some redefinitions that
        are not picked up if \string\pagetofootnote\space is issued
        before \string\makepagenote
      }{}
    \fi
   }
   \fi
}
%    \end{macrocode}
% Next the more challenging one. We make the footnote counter act as
% the page note counter, this ensure that \cs{footnotemark} still work
% when the user ask to have footnotes converted into page
% notes. \cs{footnotetext} is the same as the page note writer macro,
% but without writing the marker, here we use the special page note macro.
%    \begin{macrocode}
\newcommand*{\foottopagenote}{%
  \let\memsavefootnote\footnote
%    \end{macrocode}
% \changes{v3.6k}{2013/05/02}{Remember to remove footnote counter from
% chapter reset}
% Since we alias the footnote counter to the pagenote counter, we need
% to rewmove the footnote counter from the chapter reset, otherwise
% \cs{continuousnotenums} will be wrong.
%    \begin{macrocode}
  \counterwithout{footnote}{chapter}
  \letcountercounter{footnote}{pagenote}
  \renewcommand\footnotetext[2][]{\mem@footto@pagenote{##2}}
  \renewcommand{\footnote}[2][]{\pagenote{##2}}
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\addtonotes}
% \cs{addtonotes}\marg{text} puts \meta{text} into the notes file.
% \changes{v3.6i}{2011/02/18}{\cs{addtonotes} need \cs{immediate@protected@write}}
%    \begin{macrocode}
\newcommand{\addtonotes}[1]{\ifmempagenotes
 \IfFileExists{\jobname.ent}{\immediate@protected@write\@notefile{}{#1}}{\mempnofilewarn}%
\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\notenumintext}
% \begin{macro}{\notenuminnotes}
% \cs{notenumintext}\marg{notenum} typesets \meta{notenum} (in the
% body text). 
%    \begin{macrocode}
\newcommand{\notenumintext}[1]{%
  \textsuperscript{#1}}
%    \end{macrocode}
% \cs{notenuminnotes}\marg{notenum} typesets \meta{notenum} (i.e. the
% very first item when typesetting a note). 
%    \begin{macrocode}
\newcommand{\notenuminnotes}[1]{%
  {\normalfont #1.}\space}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\noteentry}
% \changes{v3.6}{2010/12/14}{explanation was wrong}
% \changes{v3.6h}{2011/01/19}{removed}
% \cs{noteentry}\marg{notenum}\marg{id}\marg{text}\marg{pagenum}
% typesets a note. This macro is not used anymore.
%    \begin{macrocode}
 %\newcommand{\noteentry}[4]{} % not used any more!

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\idtextinnotes}
% \cs{idtextinnotes}\marg{id text} typesets the note's \meta{id text}.
%    \begin{macrocode}
\newcommand{\idtextinnotes}[1]{%
  [#1]\space}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\noteidinnotes}
% \cs{noteidinnotes}\marg{notenum}\marg{id} is used to typeset the note 
% identification (in the note listing). It is set so that it typesets the 
% \meta{id} if it is not empty, otherwise it sets the \meta{notenum}.
%    \begin{macrocode}
\newcommand{\noteidinnotes}[2]{%
  \@ifmtarg{#2}{%
    \notenuminnotes{#1}}{\idtextinnotes{#2}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pageinnotes}
% \begin{macro}{\printpageinnotes}
% \begin{macro}{\printpageinnoteshyperref}
% \changes{v3.6h}{2011/01/19}{Changed to match new implementation}
% \cs{pageinnotes}\marg{key} calls 
% \cs{printpageinnotes}\marg{key} to typeset the originating 
% page number (in the note), but only if the \cs{notepageref} declaration
% has been used. Remember we provide an automatically generated label
% key, thus we use \cs{pageref} to get the page number. We provide a
% \Lpack{hyperref} version which is automatically used whenever
% \Lpack{hyperref} is loaded.
%    \begin{macrocode}
\newcommand{\pageinnotes}[1]{%
  \ifm@mpnpageopt \printpageinnotes{#1}\fi}
\newcommand*{\printpageinnotes}[1]{%
  (\pagerefname\ \pageref{#1})\space}
\newcommand\printpageinnoteshyperref[1]{%
(\hyperref[#1]{\pagerefname\ \pageref*{#1}})\space}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\noteinnotes}
% \cs{noteinnotes}\marg{text} is used to typeset the note's text 
% (in the note list). This macro is not used any more, but doesn't do
% any harm to leave it here.
%    \begin{macrocode}
\newcommand{\noteinnotes}[1]{#1} % not used anymore!

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\prenoteinnotes}
% \begin{macro}{\postnoteinnotes}
% These are called immediately before and after the note information is 
% typeset.
%    \begin{macrocode}
\newcommand{\prenoteinnotes}{\par\noindent}
\newcommand{\postnoteinnotes}{\par}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\prenotetext}
% \begin{macro}{\postnotetext}
% Thise two macros are executed just before and just after the note
% text. Does nothing by default.
%    \begin{macrocode}
\newcommand\prenotetext{}
\newcommand\postnotetext{}

%    \end{macrocode}
% 
% \end{macro}
% \end{macro}
%
% \begin{macro}{\notesname}
% \begin{macro}{\notedivision}
% Heading for note list.
%    \begin{macrocode}
\providecommand*{\notesname}{Notes}
\newcommand*{\notedivision}{\chapter{\notesname}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \changes{v3.6h}{2010/12/14}{typo}
% \changes{v3.6h}{2011/01/19}{There is no reason to use two macros to
% implement a starred and non starred version in this case.}
% \begin{macro}{\printpagenotes}
% \begin{macro}{\printpagenotes*}
% User commands to print the note file.
%    \begin{macrocode}
\newcommand*{\printpagenotes}{\@ifstar{\mem@printpagenotes{00}}{\mem@printpagenotes{01}}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\mempnofilewarn}
% Warning when the notes file does not exist.
%    \begin{macrocode}
\newcommand*{\mempnofilewarn}{%
  \ClassWarning{memoir}{There is no .ent file}}

%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\startnoteentrystart}
% \begin{macro}{\endnoteentryend}
% \begin{macro}{\pagenoteanchor}
% \begin{macro}{\pagenotebyanchor}
%   Utility macros to handle page note formating and hyperlinks.
%   \changes{v3.6k}{2013/05/16}{altered to use four arguments instead of three}
%   \changes{v3.6k}{2013/05/16}{Added page note anchor}
%   \changes{v3.6k}{2013/05/17}{Forgot about labels in the note text.}
%   \changes{v3.7g}{2018/01/03}{Added \cs{phantomsection}, otherwise
%   \cs{label} does not work correctly. Reported in \texttt{https://tex.stackexchange.com/q/408448/3929}}
%    \begin{macrocode}
\newcommand\startnoteentrystart[4]{%
  \prenoteinnotes%
  \noteidinnotes{#1}{#2}%
  \@ifmtarg{#2}{\phantomsection\def\@currentlabel{#1}}{}%
  \pagenoteanchor{#4}%
  \pageinnotes{#3}%
  \prenotetext%
}
\def\endnoteentryend{\postnotetext\postnoteinnotes}
\let\pagenoteanchor\@gobble
%    \end{macrocode}
% The page note hyper anchor should of course only be added when there
% is an anchor.
% \changes{v3.6k}{2013/05/17}{Forgot to test the argument}
%    \begin{macrocode}
\newcommand\pagenotehyperanchor[1]{%
  \expandafter\@ifmtarg\expandafter{#1}{}{%
    \Hy@raisedlink{\hyper@@anchor{#1}{\relax}}}}%

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\mem@printpagenotes}
% \begin{macro}{\startnoteentry}
% \begin{macro}{\ednoteentry}
%   The internal macro for printing the list of page notes. The two
%   macros \cs{startnoteentry} and \cs{endnoteentry} are also defined here.
% \changes{v3.6k}{2011/03/09}{Start and end entry better be long}
% \changes{v3.6k}{2011/04/06}{We no longer use \cs{meaning} when
% writing the data to disk, so no need to remove \texttt{>} any
% more. Also removed the safe GT stuff}
%    \begin{macrocode}
% \changes{v3.6k}{2013/05/16}{\cs{startnoteentry} should expect four args}
\newcommand\mem@printpagenotes[1]{%
  \ifmempagenotes
    \notedivision
    \IfFileExists{\jobname.ent}{%
      \begingroup
      \long\def\startnoteentry####1####2####3####4{%
        \begingroup
        \startnoteentrystart{####1}{####2}{####3}{####4}%
      }
      \long\def\endnoteentry{\endnoteentryend\endgroup}
      \immediate\closeout\@notefile
      \input{\jobname.ent}%
      \if#1\immediate\openout\@notefile=\jobname.ent\fi%
      \endgroup
    }{%
      \mempnofilewarn
    }%
  \fi%
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@sprintpagenotes}
% Macro implementing \cs{printpagenotes*}. Removed
% \changes{v3.6h}{2011/01/20}{Removed}
%    \begin{macrocode}
 % \newcommand*{\@sprintpagenotes}{%
 %   \ifmempagenotes
 %   \notedivision
 % \IfFileExists{\jobname.ent}{%
 %   \immediate\closeout\@notefile
 %   \input{\jobname.ent}%
 %   \immediate\openout\@notefile=\jobname.ent%
 %   }{%
 %   \mempnofilewarn
 % }%
 % \fi}
  
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@printpagenotes}
% Macro implementing \cs{printpagenotes}. Removed
% \changes{v3.6h}{2011/01/20}{Removed}
%    \begin{macrocode}
 % \newcommand*{\@printpagenotes}{%
 %   \ifmempagenotes
 %     \notedivision
 %     \IfFileExists{\jobname.ent}{%
 %       \immediate\closeout\@notefile
 %       \input{\jobname.ent}%
 %      }{%
 %        \mempnofilewarn
 %      }
 %   \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pagenotesubhead}
% \begin{macro}{\pagenotesubheadstarred}
% \changes{v3.6h}{2011/01/25}{Added \cs{pagenotesubheadstarred}}
% The section heading before each set of notes. \\
% \cs{pagenotesubhead}\marg{chaptername}\marg{number}\marg{title}
% The \cs{pagenotesubheadstarred} macro is used for unnumbered
% devisions. By default it is the same as \cs{pagenotesubhead}, but
% the user can change this. For example it may look odd with an title
% like this: >>Chapter Title<< when there is no number.
%    \begin{macrocode}
\newcommand*{\pagenotesubhead}[3]{%
  \section*{#1 #2 #3}}
\newcommand\pagenotesubheadstarred{\pagenotesubhead}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \section{Change marks} \label{sec:vct}
%
%    When preparing a manuscript it normally goes through
%    several iterations. The commands provided may be used to identify
%    changes made to a document during its life cycle.
%
% The code for this part of the class is based on the version
% controls in the \Lpack{iso} class~\cite{ISOCLASS}.
%
% \subsection{Print control}
%
%    Members of the development group often need to see the changes
%    between document versions, while the general public does not.
% \begin{macro}{\ifchangemarks}
%    This controls the appearence of the version controls defined
%    below.
%    \begin{macrocode}
\newif\ifchangemarks\changemarksfalse
%    \end{macrocode}
%   The marks only work properly when the \Lopt{draft} option
%   is in effect. Also, the command \cs{changemarkstrue} must be
%   put in the document preamble.
% \end{macro}
%
% \begin{macro}{\changemarks}
% \begin{macro}{\nochangemarks}
% More user friendly version of \cs{changemarks(true/false)}.
% \changes{v1.61803}{2008/01/30}{Added \cs{changemarks} and \cs{nochangemarks}}
%    \begin{macrocode}
\newcommand*{\changemarks}{\changemarkstrue}
\newcommand*{\nochangemarks}{\changemarksfalse}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\v@rid}
%    This acts as an alias for \cs{marginpar} when both \cs{ifchangemarks} is
%    true and the \Lopt{draft} option is in effect, otherwise it throws
%    away its two arguments.
% \changes{v1.2}{2002/07/27}{Added \cs{@bsphack} and \cs{@esphack} to \cs{v@rid}}
%    \begin{macrocode}
\newcommand{\v@rid}[2]{%
  \@bsphack
  \ifchangemarks
     \ifdraftdoc
       \marginpar[#1]{#2}%
  \fi\fi
  \@esphack}

%    \end{macrocode}
% \end{macro}
%
% \subsection{Change marking}
%
%    The following commands flag changes in the typeset document. Each of
%    the commands takes one parameter which is intended to be a 
%    `change number' or comment for tracking purposes. A symbol and
% the \meta{change-id} is put into the margin near where the command 
% is given. The marking commands should be attached to some word or 
% punctuation mark in the text otherwise extraneous spaces may creep
% into the final document.
% \changes{v1.2}{2002/07/27}{Added \cs{@bsphack} and \cs{@esphack} to changemarks}
% \begin{macro}{\added}
%    \cs{added}\marg{change-id}
%    Flags, with the symbol $\oplus$, that something has been added 
% to the manuscript.
%    \begin{macrocode}
\newcommand{\added}[1]{%
  \@bsphack
  \ifchangemarks
    \v@rid{\small$\oplus$ #1}{\small$\oplus$ #1}%
  \fi
  \@esphack}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\deleted}
%    \cs{deleted}\marg{change-id}
%    Flags, with the symbol $\neq$, that something has been deleted 
% from the manuscript.
%    \begin{macrocode}
\newcommand{\deleted}[1]{%
  \@bsphack
  \ifchangemarks
    \v@rid{\small$\neq$ #1}{\small$\neq$ #1}%
  \fi
  \@esphack}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\changed}
%    \cs{changed}\marg{change-id}
%    Flags, with the symbol $\Leftrightarrow$,  that something
% has been changed in the text.
%    \begin{macrocode}
\newcommand{\changed}[1]{%
  \@bsphack
  \ifchangemarks
    \v@rid{\small$\Leftrightarrow$ #1}{\small$\Leftrightarrow$ #1}%
  \fi
  \@esphack}

%    \end{macrocode}
% \end{macro}
%
% \section{Trimming marks}
%
% The \Lopt{showtrims} options prints trimming marks at the corners
% of the logical page. The code for this comes from ideas gleaned
% from Martin Schr\"{o}der's \Lpack{everyshi} package~\cite{EVERYSHI}
% and Melchior Franz's \Lpack{crop} package~\cite{CROP}. 
% The implementation and any errors are mine.
%
%    The implementation up to October 2002 was limited to putting a cross
% at the page corners. The manual directed users to the \Lpack{crop}
% packge if they wanted anything more. In October 2002 the implementation
% was substantially extended. The background to this is below.
%
%    Before the release of version 1.7 of \Lpack{crop} in May 2002 its
% author asked me to make some changes to \Lpack{memoir} that would be
% helpful to him, and I did so. Later he told me that the changes were
% unnecessary and I reverted to the original \Lpack{memoir} code.
%
%    On 2002/10/06 Peter Heslin (\url{peter.heslin@ucd.ie}) started a
% thread on \url{comp.text.tex} titled `Incompatibility of memoir.cls 
% and crop.sty' in which he said that \Lpack{memoir} and \Lpack{crop}
% did not seem to work together. The following are some snippets from
% that thread, identified by the various proponents.
% \begin{description}
% \item[crop] Ah, yes. It cannot work with all those \cs{settrims} etc.
%             crop.sty does only respect \verb?\stock{width,height}?,
%             but none of the other memoir specific trim marks stuff \ldots
%
% \item[crop] \ldots I'm not a memoir expert. crop.sty respects all the
%  usual LaTeX paper dimensions and simply puts the marks around the
% page. It works with all standard classes and the KOMA classes. memoir
% seems to do things completely differently \ldots
%
%    Sorry, but I'm afraid I have to pass the problem to the memoir
% author. \ldots
%
% \item[memoir] I will try and take a look at the problem but I'm
%  not a crop expert --- I've never used it. However it seems odd to
% me that crop doesn't work with memoir. Memoir provides a different
% interface for specifying the page layout but then translates everything
% to the standard length variables. \ldots
%
% \item[crop] You've just taken code from it \verb?...:->?
%
%    crop doesn't have its own idea at all. It just uses that of DEK
% and LaTeX, which says, that the reference point of the output box
% in the output routine is assumed 1 inch to the left [later corrected 
% to right] and 1 inch down
% from the upper left (virtual) paper corner.
%
% \item[crop] With other words: crop changes \cs{hoffset} and \cs{voffset},
% in order to center the logical (virtual) page on the physical sheet
% of paper, in the middle of the crop marks. The length macros 
% \cs{evensidemargin} and \cs{oddsidemargin} are unchanged and refer still 
% to the logical page (modulo 1 inch).
%
%    The memoir class, in contrast (mis)uses the LaTeX margins
% \cs{even(odd)sidemargin} for that purpose.
%
%    Thus, the meaning of \cs{even(odd)sidemargin} is different
% in both packages.
% \end{description}
%
%     Given all the above I concluded that \Lpack{crop} would remain
% as it was, and that in order to satisfy Peter Heslin I would have
% to extend the trimming marks. The following was originally limited to 
% extensions
% asked for by Peter Heslin.
%
% \begin{macro}{\showtrimsoff}
% \begin{macro}{\showtrimson}
% Switch trimming marksoff and on. Requested by James Hunt on CTT
% \textit{Are crop marks needed on every page?}, February 2006.
% \changes{v1.61803}{2008/01/30}{Added \cs{showtrimsoff} and \cs{showtrimson} 
%                (mempatch v4.5)}
%    \begin{macrocode}
\newcommand*{\showtrimsoff}{\showtrimsfalse}
\newcommand*{\showtrimson}{\showtrimstrue}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% 
% \begin{macro}{\trimmark}
% This is a cross 
% in a zero sized picture for marking the corner of a logical page. Up to 
% version 1.0 the macro used \cs{setlength} for adjusting the \cs{unitlength}
% but Henrik Holm\footnote{Message to \ctt{} on 2002/01/04 
% (\texttt{h.holm@spray.no})} discovered that if the \Lpack{calc} package
% is used then LaTeX complains about a missing number.
% \changes{v1.0a}{2002/01/04}{Removed \cs{setlength} from \cs{trimmark}. Stops
%                 problem with the calc package.}
%    \begin{macrocode}
\newcommand*{\trimmark}{%
  \begin{picture}(0,0)
    \unitlength 1cm
    \thinlines
    \put(-2,0){\line(1,0){4}}
    \put(0,-2){\line(0,1){4}}
  \end{picture}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\Ltrimpictl}
% \begin{macro}{\Ltrimpictr}
% \begin{macro}{\Ltrimpicbl}
% \begin{macro}{\Ltrimpicbr}
%  `L' shaped trim marks for four corners.
% \changes{v1.3}{2002/10/10}{Added \cs{Ltrimpictl}, \cs{Ltrimpictr}, \cs{Ltrimpicbl}
%                            and \cs{Ltrimpicbr}}
%    \begin{macrocode}
\newcommand*{\Ltrimpictl}{%
  \begin{picture}(0,0)
    \unitlength 1mm
    \thinlines
    \put(-2,0){\line(-1,0){18}}
    \put(0,2){\line(0,1){18}}
  \end{picture}}
\newcommand*{\Ltrimpictr}{%
  \begin{picture}(0,0)
    \unitlength 1mm
    \thinlines
    \put(2,0){\line(1,0){18}}
    \put(0,2){\line(0,1){18}}
  \end{picture}}
\newcommand*{\Ltrimpicbl}{%
  \begin{picture}(0,0)
    \unitlength 1mm
    \thinlines
    \put(-2,0){\line(-1,0){18}}
    \put(0,-2){\line(0,-1){18}}
  \end{picture}}
\newcommand*{\Ltrimpicbr}{%
  \begin{picture}(0,0)
    \unitlength 1mm
    \thinlines
    \put(2,0){\line(1,0){18}}
    \put(0,-2){\line(0,-1){18}}
  \end{picture}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\Ftrimpicbl}
%    Frame the page.
% \changes{v1.3}{2002/10/10}{Added \cs{Ftrimpictl}}
%    \begin{macrocode}
\newcommand*{\Ftrimpicbl}{%
  \begin{picture}(0,0)
    \unitlength 1pt
    \thinlines
    \put(0,0){\framebox(\strip@pt\paperwidth,\strip@pt\paperheight){}}
  \end{picture}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\tmarktl}
% \begin{macro}{\tmarktr}
% \begin{macro}{\tmarkbl}
% \begin{macro}{\tmarkbr}
% The trimming marks used for corner display.
% \changes{v1.3}{2002/10/10}{Added \cs{tmarktl}, \cs{tmarktr}, \cs{tmarkbl}
%                            and \cs{tmarkbr}}
%    \begin{macrocode}
\newcommand*{\tmarktl}{\trimmark} 
\newcommand*{\tmarktr}{\trimmark} 
\newcommand*{\tmarkbl}{\trimmark} 
\newcommand*{\tmarkbr}{\trimmark} 

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\tmarktm}
% \begin{macro}{\tmarkml}
% \begin{macro}{\tmarkmr}
% \begin{macro}{\tmarkbm}
% The trimming marks used for mid-side display.
% \changes{v1.3}{2002/10/10}{Added \cs{tmarktm}, \cs{tmarkml}, \cs{tmarkmr}
%                            and \cs{tmarkbm}}
% \changes{v1.6180339c}{2009/11/13}{Fill in these four macros. Easier
% for users to define them to do nothing, than coming up with the code}
%    \begin{macrocode}
\newcommand*{\tmarktm}{%
  \begin{picture}(0,0)%
    \unitlength 1mm
    \thinlines
    \put(0,2){\line(0,1){10}}
  \end{picture}}
\newcommand*{\tmarkml}{%
  \begin{picture}(0,0)%
    \unitlength 1mm
    \thinlines
    \put(-2,0){\line(-1,0){10}}
  \end{picture}}
\newcommand*{\tmarkmr}{%
  \begin{picture}(0,0)%
    \unitlength 1mm
    \thinlines
    \put(2,0){\line(1,0){10}}
  \end{picture}}
\newcommand*{\tmarkbm}{%
  \begin{picture}(0,0)%
    \unitlength 1mm
    \thinlines
    \put(0,-12){\line(0,1){10}}
  \end{picture}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\trimXmarks}
% \begin{macro}{\trimLmarks}
% \begin{macro}{\trimFrame}
% \begin{macro}{\trimNone}
% These are declarations for the different kinds of trimming marks.
% \changes{v1.3}{2002/10/10}{Added \cs{trimXmarks}, \cs{trimLmarks}, 
%                            \cs{trimFrame} and \cs{trimNone}} 
%    \begin{macrocode}
\newcommand*{\trimXmarks}{%
  \let\tmarktl\trimmark
  \let\tmarktr\trimmark
  \let\tmarkbl\trimmark
  \let\tmarkbr\trimmark}
\newcommand*{\trimLmarks}{%
  \let\tmarktl\Ltrimpictl
  \let\tmarktr\Ltrimpictr
  \let\tmarkbl\Ltrimpicbl
  \let\tmarkbr\Ltrimpicbr}
\newcommand*{\trimFrame}{%
  \let\tmarktl\null
  \let\tmarktr\null
  \let\tmarkbl\Ftrimpicbl
  \let\tmarkbr\null}
\newcommand*{\trimNone}{%
  \let\tmarktl\relax
  \let\tmarktr\relax
  \let\tmarkbl\relax
  \let\tmarkbr\relax
  \let\tmarktm\relax
  \let\tmarkml\relax
  \let\tmarkmr\relax
  \let\tmarkbm\relax}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\trimmarks}
% \begin{macro}{\trimmarkscolor}
%    This positions four marks (\cs{trimmark}) at the corners of a
% logical page. It is basically a \cs{vbox} with zero height and width.
%
% Bastiaan Niels Veelo reported (2003/07/11) odd things (e.g., some
% macros ignored) when changing trim marks. Turns out to be related
% to the use of \cs{protect}. The macro \cs{trimmarkscolor} can be
% used to change the color of the trimmarks. Despite its name, it is
% not a color but just an empty macro.
% \changes{v1.1}{2002/03/10}{Changed \cs{trimmarks} to work properly with the oneside option}
% \changes{v1.3}{2002/10/10}{Changed \cs{trimmarks} to use \cs{tmarktl}, etc.,
%                            instead of four \cs{trimmark}s}
% \changes{v1.4}{2003/11/22}{Fiddled \cs{protect} in \cs{trimmaks}
%                            (from patch v1.7)}              
% \changes{v3.6h}{2010/12/05}{Added \cs{trimmarkscolor}}
%    \begin{macrocode}
\newcommand*\trimmarkscolor{}
\newcommand*{\trimmarks}{%   
  \vbox to \z@{\vskip-1in \vskip\trimtop % top of logical page
    \hb@xt@\z@{\hskip-1in
      \ifodd\c@page 
        \hskip\stockwidth \hskip-\trimedge \hskip-\paperwidth
      \else 
        \if@twoside
          \hskip\trimedge  % left of logical page
        \else
          \hskip\stockwidth \hskip-\trimedge \hskip-\paperwidth
        \fi
      \fi
      \vbox to \paperheight{%
        \let\protect\relax        % <- v1.4 addition
        \hb@xt@\paperwidth{\trimmarkscolor\tmarktl\hfil\tmarktm\hfil\tmarktr}%
        \vfil
        \hb@xt@\paperwidth{\trimmarkscolor\tmarkml\hfil\tmarkmr}%
        \vfil
        \hb@xt@\paperwidth{\trimmarkscolor\tmarkbl\hfil\tmarkbm\hfil\tmarkbr}}%
    \hss}%
  \vss}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \subsection{Quark marks}
%
% William Adams (2006/08/28) supplied the following code to use trim marks 
% along the style of Quark Xpress. 
%
% \begin{macro}{\registrationColour}
% \begin{macro}{\quarkmarks}
% Trim marks on the style of Quark Express.
% \changes{v1.61803}{2008/01/30}{Added \cs{quarkmarks} (mempatch v4.6)}
% \changes{v3.6h}{2010/12/05}{Added \cs{normalfont} such that font
% changes going over a page break does not effect the quarks
% text. Reported by Rasmus Villemoes.}
% \changes{v3.6j}{2011/02/28}{Typo hsip -> hskip, reported by Alex Ball}
%    \begin{macrocode}
\newcommand*{\registrationColour}[1]{#1}
\newcommand*{\quarkmarks}{%
\renewcommand*{\tmarktl}{\registrationColour{%
  \begin{picture}(0,0)
    \setlength{\unitlength}{1bp}\thicklines
    \put(-36,0){\line(1,0){24}}
    \put(0,12){\line(0,1){24}}
    \put(3,27){\normalfont\ttfamily\fontsize{8bp}{10bp}\selectfont\jobname\ \
      \today\ \ \printtime\ \ Page \thepage}
  \end{picture}}}
\renewcommand*{\tmarktm}{\registrationColour{%
  \begin{picture}(0,0)
    \setlength{\unitlength}{1bp}\thicklines
    \put(-24,24){\line(1,0){48}}
    \put(0,12){\line(0,1){24}}
    \put(0,24){\oval(12,12)}
  \end{picture}}}
\renewcommand*{\tmarktr}{\registrationColour{%
  \begin{picture}(0,0)
    \setlength{\unitlength}{1bp}\thicklines
    \put(12,0){\line(1,0){24}}
    \put(0,12){\line(0,1){24}}
  \end{picture}}}
\renewcommand*{\tmarkmr}{\registrationColour{%
  \begin{picture}(0,0)
    \setlength{\unitlength}{1bp}\thicklines
    \put(12,0){\line(1,0){24}}
    \put(24,-24){\line(0,1){48}}
    \put(24,0){\oval(12,12)}
  \end{picture}}}
\renewcommand*{\tmarkbr}{\registrationColour{%
  \begin{picture}(0,0)
    \setlength{\unitlength}{1bp}\thicklines
    \put(12,0){\line(1,0){24}}
    \put(0,-36){\line(0,1){24}}
  \end{picture}}}
\renewcommand*{\tmarkbm}{\registrationColour{%
  \begin{picture}(0,0)
    \setlength{\unitlength}{1bp}\thicklines
    \put(-24,-24){\line(1,0){48}}
    \put(0,-36){\line(0,1){24}}
    \put(0,-24){\oval(12,12)}
  \end{picture}}}
\renewcommand*{\tmarkbl}{\registrationColour{%
  \begin{picture}(0,0)
    \setlength{\unitlength}{1bp}\thicklines
    \put(-36,0){\line(1,0){24}}
    \put(0,-36){\line(0,1){24}}
  \end{picture}}}
\renewcommand*{\tmarkml}{\registrationColour{%
  \begin{picture}(0,0)
    \setlength{\unitlength}{1bp}\thicklines
    \put(-36,0){\line(1,0){24}}
    \put(-24,-24){\line(0,1){48}}
    \put(-24,0){\oval(12,12)}
  \end{picture}}}
\renewcommand*{\trimmarks}{%
%%  \special{papersize=\the\stockwidth,\the\stockheight}
  {%
  \vbox to \z@{\vskip-1in \vskip\trimtop % top of logical page
    \hb@xt@\z@{\hskip-1in
      \ifodd\c@page
        \hskip\stockwidth \hskip-\trimedge \hskip-\paperwidth
      \else
        \if@twoside
          \hskip\trimedge % left of logical page
        \else
          \hskip\stockwidth \hskip-\trimedge \hskip-\paperwidth
        \fi
      \fi
      \vbox to \paperheight{%
        \let\protect\relax %      <- v1.4 addition
%    \end{macrocode}
% We remember to add \cs{trimmarkscolor}
% \changes{v3.6h}{2010/12.05}{added \cs{trimmarkscolor}}
%    \begin{macrocode}
        \hb@xt@\paperwidth{\trimmarkscolor\tmarktl\hfil\tmarktm\hfil\tmarktr}%
        \vfil
        \hb@xt@\paperwidth{\trimmarkscolor\tmarkml\hfil\tmarkmr}%
        \vfil
        \hb@xt@\paperwidth{\trimmarkscolor\tmarkbl\hfil\tmarkbm\hfil\tmarkbr}}%
      \hss}%
    \vss}}%
}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
%    Any marks are put onto the pages by adding to the \cs{shipout}
% routine.
%
% \begin{macro}{\mem@oldshipout}
% Keep a copy of the current version of \cs{shipout} in \cs{mem@oldshipout}.
%    \begin{macrocode}
\let\mem@oldshipout\shipout
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\mem@shipi}
% \begin{macro}{\mem@shipii}
% Effectively these will add the \cs{trimmarks} to the box holding
% the contents of the page. Note that any \cs{makeindex} must come 
% \emph{before} \Lpack{pagesel} (and \Lpack{selectp}) package.
% \changes{v1.618}{2005/09/03}{Changed \cs{mem@shipii} for the pagesel package,
%              courtesy James Szinger (mempatch v311)}
% \changes{v1.61803}{2008/01/30}{Added \cs{ifshowtrims} to \cs{mem@shipii}
%                    (mempatch v4.5)}
% \changes{v1.6180339f}{2009/06/24}{Added Dan Luecking's fix to 
% \cs{mem@shippii} to cater for another merry hyperref change!}
% \changes{v1.6180339c}{2009/11/13}{Replaced Dans fix with a fix from
% Heiko Oberdiek}
%    \begin{macrocode}
\newcommand*{\mem@shipi}{%
  \ifvoid\@cclv\expandafter\aftergroup\fi\mem@shipii}
\newcommand*\mem@shipii{%
  \ifvoid\@cclv
    \mem@oldshipout\box\@cclv
  \else
    \ifshowtrims
%    \end{macrocode}
% Heiko Oberdiek responded to a problem reported by Rolf
% Niepraschk. The earlier implementation might cause the output box to
% be shifted. Heikos explanation (in response to the line 
%  \verb?\mem@oldshipout\vbox{\trimmarks\ifvbox\@cclv\unvbox\else\box\fi\@cclv}?) :
% \begin{verbatim}
%   In vertical mode (\mem@oldshipout\vbox{...}) TeX puts
%   interline skip between two boxes (\trimmarks and \@cclv),
%   here \linekskip (1pt) is put inbetween causing the
%   shift downwards.
% \end{verbatim}
% Heiko also provided the fix used below. Actually Heikos fix also
% fixes a problem that might cause glue settings to disappear.
%    \begin{macrocode}
    \mem@oldshipout\vbox{%
        \trimmarks
        \nointerlineskip
        \box\@cclv
     }%
    \else
      \mem@oldshipout\box\@cclv
    \fi
  \fi}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\shipout}
% Our new version of \cs{shipout}, which is only needed for the 
% \Lopt{showtrims} option. This adds \cs{mem@shipi} to the page box
% which then calls the original version of \cs{shipout}.
%    \begin{macrocode}
\ifshowtrims
  \renewcommand*{\shipout}{\afterassignment\mem@shipi\setbox\@cclv=}
\fi

%    \end{macrocode}
% \end{macro}
%
%
% \section{Verbatims, boxes, and files}
%
% All the code in this section was added for version 1.2 of the class.
% \changes{v1.2}{2002/07/27}{Section `Verbatims, boxes and files' added}
%
% \subsection{Modified version of the verbatim package}
%
% Much of this is from the \Lpack{verbatim} package code~\cite{VERBATIM}.
% Unless indicated otherwise, the code and commentary is from that
% package.
%
%
% \subsubsection{Preliminaries}
%
% \begin{macro}{\every@verbatim}
% \begin{macro}{\afterevery@verbatim}
%    The hook (i.e., token register) \cs{every@verbatim}
%    is initialized to \meta{empty}.
%
% PW added the \cs{afterevery@verbatim} hook.
%    \begin{macrocode}
\newtoks\every@verbatim
  \every@verbatim={}
\newtoks\afterevery@verbatim
  \afterevery@verbatim={}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@makeother}
%    \cs{@makeother} takes as argument a character and changes
%    its category code to $12$ (other).
%    \begin{macrocode}
\def\@makeother#1{\catcode`#112\relax}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\@vobeyspaces}
%    The macro \cs{@vobeyspaces} causes spaces in the input
%    to be printed as spaces in the output.
%    \begin{macrocode}
\begingroup
 \catcode`\ =\active%
 \def\x{\def\@vobeyspaces{\catcode`\ \active\let \@xobeysp}}
 \expandafter\endgroup\x
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\@xobeysp}
%    The macro \cs{@xobeysp} produces exactly one space in
%    the output, protected against breaking just before it.
%    (\cs{@M} is an abbreviation for the number $10000$.)
%    \begin{macrocode}
\def\@xobeysp{\leavevmode\penalty\@M\ }
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\verbatim@line}
%    We use a newly defined token register called \cs{verbatim@line}
%    that will be used as the character buffer.
%    \begin{macrocode}
\newtoks\verbatim@line
%    \end{macrocode}
% \end{macro}
%
% PW. I have extended the original \Lpack{verbatim} package code to handle
% TABs within verbatims. Normally TeX replaces a TAB by either a single space or
% ignores it altogether. For this purpose I have bits of code from the \Lpack{moreverb}
% package~\cite{MOREVERB} for handling TABs.
%
% \textit{Code and commentary from moreverb.}
%
% We define a few auxiliary macros and counters for expanding tabs.
%    \begin{macrocode}
\newcount\tab@position 
%    \end{macrocode}
%
% \begin{macro}{\@xobeytab}
% \cs{@xobeytab} puts enough spaces in to get to the next nominal
% tab stop
%    \begin{macrocode}
\def\@xobeytab{%
  \loop
    \toks@\expandafter{\the\toks@\@xobeysp}%
    \advance\tab@position-1
  \ifnum\tab@position>0 \repeat
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@vobeytabs}
% \cs{@vobeytabs} initialises use of \cs{@xobeytab}.  Needs to be
% executed within a group, as mustn't be allowed to leak out into the
% wide world.
%
%    \begin{macrocode}
\begingroup
  \catcode`\^^I=\active
  \gdef\@vobeytabs{\catcode`\^^I\active\let^^I\@xobeytab}%
\endgroup
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\verbatim@tabexpand}
% \cs{verbatim@tabexpand}\marg{body of line}\cs{@nil} processes every
% character of a line by tail recursion, counting the characters and
% juggling things when a tab is encountered.
%    \begin{macrocode}
\def\verbatim@tabexpand#1{%
  \ifx#1\@nil
    \the\toks@
    \expandafter\par
  \else
    \ifx#1\@xobeytab
      \@xobeytab
    \else
%    \end{macrocode}
%
% We can safely put \cs{@xobeysp} into the token register, since it
% does precisely what we need
%    \begin{macrocode}
      \toks@\expandafter{\the\toks@#1}%
      \advance\tab@position\m@ne
    \fi
    \ifnum\tab@position=0 \tab@position\tab@size \fi
    \expandafter\verbatim@tabexpand
  \fi
}

%    \end{macrocode}
% \end{macro}
%
% \textit{End of code and commentary from moreverb.}
%
% PW. Some macros for turning tabbing on and off.
%
% \begin{macro}{\tabson}
% \begin{macro}{\tabsoff}
% \begin{macro}{\@maybeobeytabs}
% \cs{tabson} turns tabbing on, and \cs{tabsoff} turns it off. Default
% is no tabbing.
%    \begin{macrocode}
\newif\ift@bs
\newcommand{\tabson}[1][4]{%
  \ifnum\@ne > #1\relax
    \tabsoff
  \else
    \t@bstrue
    \def\tab@size{#1\relax}%
    \def\@maybeobeytabs{\@vobeytabs}%
  \fi
}
\newcommand{\tabsoff}{%
  \t@bsfalse
  \def\tab@size{\z@}%
  \def\@maybeobeytabs{}%
}
\tabsoff

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\tabverbatim@processline}
% Process a line with TABs (extracted from \Lpack{moreverb}).
%    \begin{macrocode}
\def\tabverbatim@processline{\tab@position\tab@size
  \toks@{}%
  \expandafter\verbatim@tabexpand\the\verbatim@line\@nil}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\notabverbatim@processline}
% Processes a line ignoring TABs (this is the original \Lpack{verbatim}
% package definition of \cs{verbatim@processline}).
%    \begin{macrocode}
\def\notabverbatim@processline{\the\verbatim@line\par}

%    \end{macrocode}
% \end{macro}
%
% \textit{We are now back to the \Lpack{verbatim} code.}
%
% The following four macros are defined globally in a way suitable for
% the \texttt{verbatim} and \texttt{verbatim*} environments.
% \begin{macro}{\verbatim@startline}
% \begin{macro}{\verbatim@addtoline}
% \begin{macro}{\verbatim@processline}
%    \cs{verbatim@startline} initializes processing of a line
%    by emptying the character buffer (\cs{verbatim@line}).
%    \begin{macrocode}
\def\verbatim@startline{\verbatim@line{}}
%    \end{macrocode}
%    \cs{verbatim@addtoline} adds the tokens in its argument
%    to our buffer register \cs{verbatim@line} without expanding
%    them.
%    \begin{macrocode}
\def\verbatim@addtoline#1{%
  \verbatim@line\expandafter{\the\verbatim@line#1}}
%    \end{macrocode}
%    Processing a line inside a \texttt{verbatim} or \texttt{verbatim*}
%    environment means printing it.
%    Ending the line means that we have to begin a new paragraph.
%    We use \cs{par} for this purpose.  Note that \cs{par}
%    is redefined in \cs{@verbatim} to force \TeX{} into horizontal
%    mode and to insert an empty box so that empty lines in the input
%    do appear in the output.
% (PW changed next line from \\
% \verb?\def\verbatim@processline{\the\verbatim@line\par}?
%    \begin{macrocode}
\def\verbatim@processline{\notabverbatim@processline}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\verbatim@finish}
%    As a default, \cs{verbatim@finish} processes the remaining
%    characters.
%    When this macro is called we are facing the following problem:
%    when the \verb?\end{verbatim}?
%    command is encountered \cs{verbatim@processline} is called
%    to process the characters preceding the command on the same
%    line.  If there are none, an empty line would be output if we
%    did not check for this case.
%
%    If the line is empty \verb?\the\verbatim@line? expands to
%    nothing.  To test this we use a trick similar to that on p.\ 376
%    of the \TeX{}book, but with \verb?$?\ldots\verb?|$? instead of
%    the \verb?!? tokens.  These \verb?$? tokens can never have the same
%    category code as a \verb?$? token that might possibly appear in the
%    token register \cs{verbatim@line}, as such a token will always have
%    been read with category code $12$ (other).
%    Note that \cs{ifcat} expands the following tokens so that
%    \verb?\the\verbatim@line? is replaced by the accumulated
%    characters
%    \begin{macrocode}
\def\verbatim@finish{\ifcat$\the\verbatim@line$\else
  \verbatim@processline\fi}
%    \end{macrocode}
% \end{macro}
%
%
% \subsubsection{The \texttt{verbatim} and \texttt{verbatim*} environments}
%
% \begin{macro}{\verbatim@font}
%    We start by defining the macro \cs{verbatim@font} that is
%    to select the font and to set font-dependent parameters.
%    Then we go through \cs{verbatim@nolig@list} to avoid
%    certain ligatures.
%    \cs{verbatim@nolig@list} is a macro defined in the \LaTeXe{} kernel
%    to expand to
% \begin{verbatim}
%    \do\`\do\<\do\>\do\,\do\'\do\-
% \end{verbatim}
%    All the characters in this list can be part of a ligature in some
%    font or other.
% 
% PW. This is the original version which I'm going to replace.
% \begin{verbatim}
% \def\verbatim@font{\normalfont\ttfamily
%                    \hyphenchar\font\m@ne
%                    \let\do\do@noligs
%                    \verbatim@nolig@list}
% \end{verbatim}
% Actually the kernel defines the macro \verb+\@noligs+ which just
% runs the last two lines of the \verb+\verbatim@font+ above. As other
% package may add stuff to \verb+\@noligs+, we will use that instead.
% \end{macro}
%
% \begin{macro}{\setverbatimfont}
% \begin{macro}{\m@mverbfont}
% \begin{macro}{\verbatim@font}
% User level handle for changing the font used for verbatim text.
% \changes{v1.61803398}{2009/09/10}{Changed the last two lines of
% \cs{verbatim@font} into using \cs{@noligs} instead. This fixes
% problem with upquote.}
%    \begin{macrocode}
\newcommand{\setverbatimfont}[1]{\def\m@mverbfont{#1}}
\setverbatimfont{\normalfont\ttfamily}

\def\verbatim@font{\m@mverbfont
                   \hyphenchar\font\m@ne
                   \@noligs}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\@verbatim}
%    The macro \cs{@verbatim} sets up things properly.
%    First of all, the tokens of the \cs{every@verbatim} hook
%    are inserted.
%    Then a \texttt{trivlist} environment is started and its first
%    \cs{item} command inserted.
%    Each line of the \texttt{verbatim} or \texttt{verbatim*}
%    environment will be treated as a separate paragraph.
% \changes{v1.61803398}{2009/07/18}{Added bidi support to \cs{@verbatim}}
%    \begin{macrocode}
\def\@verbatim{\the\every@verbatim
  \trivlist \item \relax
%    \end{macrocode}
%    The following extra vertical space is for compatibility with the
%    \LaTeX kernel: otherwise, using the \Lpack{verbatim} package changes
%    the vertical spacing of a \texttt{verbatim} environment nested within a
%    \texttt{quote} environment.
%    \begin{macrocode}
  \if@minipage\else\vskip\parskip\fi
%    \end{macrocode}
%    The paragraph parameters are set appropriately:
%    the penalty at the beginning of the environment,
%    left and right margins, paragraph indentation, the glue to
%    fill the last line, and the vertical space between paragraphs.
%    The latter space has to be zero since we do not want to add
%    extra space between lines.
%    \begin{macrocode}
  \@beginparpenalty \predisplaypenalty 
%%%  \leftskip\@totalleftmargin\rightskip\z@
  \memRTLleftskip\@totalleftmargin\memRTLrightskip\z@
  \parindent\z@\parfillskip\@flushglue\parskip\z@
%    \end{macrocode}
%    There's one point to make here:
%    the \texttt{list} environment uses \TeX's \cs{parshape}
%    primitive to get a special indentation for the first line
%    of the  list.
%    If the list begins with a \texttt{verbatim} environment
%    this \cs{parshape} is still in effect.
%    Therefore we have to reset this internal parameter explicitly.
%    We could do this by assigning $0$ to \cs{parshape}.
%    However, there is a simpler way to achieve this:
%    we simply tell \TeX{} to start a new paragraph.
%    As is explained on p.~103 of the \TeX{}book, this resets
%    \cs{parshape} to zero.
%    \begin{macrocode}
  \@@par
%    \end{macrocode}
%    We now ensure that \cs{par} has the correct definition,
%    namely to force \TeX{} into horizontal mode
%    and to include an empty box.
%    This is to ensure that empty lines do appear in the output.
%    Afterwards, we insert the \cs{interlinepenalty} since \TeX{}
%    does not add a penalty between paragraphs (here: lines)
%    by its own initiative. Otherwise a \texttt{verbatim} environment
%    could be broken across pages even if a \cs{samepage}
%    declaration were present.
%
%    However, in a top-aligned minipage, this will result in an extra
%    empty line added at the top. Therefore, a slightly more
%    complicated construct is necessary.
%    One of the important things here is the inclusion of
%    \cs{leavevmode} as the first macro in the first line, for example,
%    a blank verbatim line is the first thing in a list item.
%    \begin{macrocode}
  \def\par{%
    \if@tempswa
      \leavevmode\null\@@par\penalty\interlinepenalty
    \else
      \@tempswatrue
      \ifhmode\@@par\penalty\interlinepenalty\fi
    \fi}%
%    \end{macrocode}
%    But to avoid an error message when the environment
%    doesn't contain any text, we redefine \cs{@noitemerr}
%    which will in this case be called by \cs{endtrivlist}.
%    \begin{macrocode}
  \def\@noitemerr{\@warning{No verbatim text}}%
%    \end{macrocode}
%    Now we call \cs{obeylines} to make the end of line character
%    active,
%    \begin{macrocode}
  \obeylines
%    \end{macrocode}
%    change the category code of all special characters,
%    to $12$ (other).
%    \begin{macrocode}
  \let\do\@makeother \dospecials
%    \end{macrocode}
%    and switch to the font to be used.
%    \begin{macrocode}
  \verbatim@font
%    \end{macrocode}
%    To avoid a breakpoint after the labels box, we remove the penalty
%    put there by the list macros: another use of \cs{unpenalty}!
%    \begin{macrocode}
  \everypar \expandafter{\the\everypar \unpenalty}%
%    \end{macrocode}
% PW added next code at end of \cs{@verbatim}.
%    \begin{macrocode}
  \wrapright\the\afterevery@verbatim}
%    \end{macrocode}   
% \end{macro}
%
%
% \begin{macro}{\verbatim}
% \begin{macro}{\verbatim*}
%    Now we define the toplevel macros.
%    \cs{verbatim} is slightly changed:
%    after setting up things properly it calls
%    \cs{verbatim@start}.
%    This is done inside a group, so that \cs{verbatim} can be used
%    directly, without \cs{begin}.
%
% PW. The following is the original code, but I want a version of
% \texttt{verbatim} that recognises TABs.
% \begin{verbatim}
%    \begin{macrocode}
% \def\verbatim{%
%    \begingroup\@verbatim \frenchspacing\@vobeyspaces 
%    \verbatim@start}
%    \end{macrocode}
%    \cs{verbatim*} is defined accordingly.
%    \begin{macrocode}
% \@namedef{verbatim*}{\begingroup\@verbatim\verbatim@start}
% \def\endverbatim{\endtrivlist\endgroup}
% \expandafter\let\csname endverbatim*\endcsname=\endverbatim
%    \end{macrocode}
% \end{verbatim}
%
% PW. My code for these is a modified version of the original \Lpack{verbatim}
% code.
%    \begin{macrocode}
\def\verbatim{\begingroup
  \ift@bs
    \def\verbatim@processline{\tabverbatim@processline}%
  \fi
  \@verbatim \frenchspacing\@vobeyspaces\@maybeobeytabs\verbatim@start}
\@namedef{verbatim*}{\begingroup
  \ift@bs
    \def\verbatim@processline{\tabverbatim@processline}%
  \fi
  \@verbatim\@maybeobeytabs\verbatim@start}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\endverbatim}
% \begin{macro}{\endverbatim*}
%    To end the \texttt{verbatim} and \texttt{verbatim*}
%    environments it is only necessary to finish the
%    \texttt{trivlist} environment started in \cs{@verbatim} and
%    close the corresponding group, and handle\footnote{Noted by
% Zarko Cucej (\url{zarko.cucej@uni-mb.si}).} following (non-) paragraph,
% by using \cs{@doendpe}.
% \changes{v1.4}{2003/11/22}{Added \cs{@doendpe} to \cs{endverbatim} 
%                            (from patch v1.8)}
% \changes{v2.0a}{2004/03/01}{Refixed \cs{endverbatim}}
%    \begin{macrocode}
\def\endverbatim{\endtrivlist\endgroup\@doendpe}
\@namelet{endverbatim*}\endverbatim

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% For abnormal \cs{parskip}s the NTG class included the following, but I'm
% not sure if it is relevant here, but if it is just how it should be included.
% \begin{verbatim}
% From NTG, where it is a \cs{def}
% \providecommand*{\verbatim}{%
%   \topsep=-0.5\parskip
%   \@verbatim
%   \frenchspacing\@vobeyspaces \@xverbatim}
% \end{verbatim}
%
%
% \subsubsection{The \texttt{comment} environment}
%
%    The \cs{comment} macro is similar to \cs{verbatim*}.
%    However, we do not need to switch fonts or set special
%    formatting parameters such as \cs{parindent} or \cs{parskip}.
%    We need only set the category code of all special characters
%    to $12$ (other) and that of \verb?^^M? (the end of line character)
%    to $13$ (active).
%    The latter is needed for macro parameter delimiter matching in
%    the internal macros defined below.
%    In contrast to the default definitions used by the
%    \cs{verbatim} and \cs{verbatim*} macros,
%    we define \cs{verbatim@addtoline} to throw away its argument
%    and \cs{verbatim@processline}, \cs{verbatim@startline},
%    and \cs{verbatim@finish} to act as no-ops.
%    Then we call \cs{verbatim@}.
%    But the first thing we do is to call \cs{@bsphack} so that
%    this environment has no influence whatsoever upon the spacing.
%
% PW: This is the original code for the \texttt{comment} environment, 
% which I'm going to change.
% \begin{verbatim}
% \def\comment{\@bsphack
%              \let\do\@makeother\dospecials\catcode`\^^M\active
%              \let\verbatim@startline\relax
%              \let\verbatim@addtoline\@gobble
%              \let\verbatim@processline\relax
%              \let\verbatim@finish\relax
%              \verbatim@}
% \end{verbatim}
%    \cs{endcomment} is very simple: it only calls
%    \cs{@esphack} to take care of the spacing.
%    The \cs{end} macro closes the group and therefore takes care
%    of restoring everything we changed.
% \begin{verbatim}
% \let\endcomment=\@esphack
% \end{verbatim}
%
% PW: The remainder of this section is my code.
%
% \begin{macro}{\setupcomment}
% \cs{setupcomment} does all the \cs{let}s in the original \cs{comment} code.
%    \begin{macrocode}
\newcommand{\setupcomment}{%
  \let\do\@makeother\dospecials\catcode`\^^M\active
  \let\verbatim@startline\relax
  \let\verbatim@addtoline\@gobble
  \let\verbatim@processline\relax
  \let\verbatim@finish\relax}
%    \end{macrocode}
% \end{macro}
%
% The macros below do no checking to see if something has (not) been defined
% previously. It's `user beware' time.
%
% \begin{macro}{\newcomment}
% \cs{newcomment}\marg{name} creates a new comment environment called 
% \meta{name}. This is a generalisation of the original comment code.
%    \begin{macrocode}
\newcommand{\newcomment}[1]{%
  \expandafter\def\csname #1\endcsname{\@bsphack\setupcomment\verbatim@}%
  \expandafter\let\csname end#1\endcsname=\@esphack}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\commentsoff}
% \cs{commentsoff}\marg{name} switches off the \meta{name} comment 
% environment by defining the relevent macros to do nothing.
%    \begin{macrocode}
\newcommand{\commentsoff}[1]{%
  \expandafter\def\csname #1\endcsname{}%
  \expandafter\def\csname end#1\endcsname{}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\commentson}
% \cs{commentson}\marg{name} switches on the \meta{name} comment 
% environment. It has to do the same things as \cs{newcomment} does,
% so let \cs{newcomment} do the work.
%    \begin{macrocode}
\newcommand{\commentson}[1]{\newcomment{#1}}

%    \end{macrocode}
% \end{macro}
%
% We had better supply the \texttt{comment} environment, as promised.
%    \begin{macrocode}
\newcomment{comment}

%    \end{macrocode}
%
% PW: That is the end of my changes and extensions to the original 
% \texttt{comment} environment code.
%
%
% \subsubsection{The main loop}
%
% Here comes the tricky part:
% During the definition of the macros we need to use the special
% characters \verb?\?, \verb?{?, and \verb?}? not only with their
% normal category codes,
% but also with category code $12$ (other).
% We achieve this by the following trick:
% first we tell \TeX{} that \verb?\?, \verb?{?, and \verb?}?
% are the lowercase versions of \verb?!?, \verb?[?, and \verb?]?.
% Then we replace every occurrence of \verb?\?, \verb?{?, and \verb?}?
% that should be read with category code $12$ by \verb?!?, \verb?[?,
% and \verb?]?, respectively,
% and give the whole list of tokens to \cs{lowercase},
% knowing that category codes are not altered by this primitive!
%
% But first we have ensure that
% \verb?!?, \verb?[?, and \verb?]? themselves have
% the correct category code!
% To allow special settings of these codes we hide their setting in
% the macro \cs{vrb@catcodes}.  If it is already defined our new
% definition is skipped.
%    \begin{macrocode}
\@ifundefined{vrb@catcodes}%
  {\def\vrb@catcodes{%
     \catcode`\!12\catcode`\[12\catcode`\]12}}{}
%    \end{macrocode}
% This trick allows us to use this code for applications where other
% category codes are in effect.
%
% We start a group to keep the category code changes local.
%    \begin{macrocode}
\begingroup
 \vrb@catcodes
 \lccode`\!=`\\ \lccode`\[=`\{ \lccode`\]=`\}
%    \end{macrocode}
%    We also need the end-of-line character \verb?^^M?,
%    as an active character.
%    If we were to simply write \verb?\catcode`\^^M=\active?
%    then we would get an unwanted active end of line character
%    at the end of every line of the following macro definitions.
%    Therefore we use the same trick as above:
%    we write a tilde \verb?~? instead of \verb?^^M? and
%    pretend that the
%    latter is the lowercase variant of the former.
%    Thus we have to ensure now that the tilde character has
%    category code $13$ (active).
%    \begin{macrocode}
 \catcode`\~=\active \lccode`\~=`\^^M
%    \end{macrocode}
%    The use of the \cs{lowercase} primitive leads to one problem:
%    the uppercase character `\texttt{C}' needs to be used in the
%    code below and its case must be preserved.
%    So we add the command:
%    \begin{macrocode}
 \lccode`\C=`\C
%    \end{macrocode}
%    Now we start the token list passed to \cs{lowercase}.
%    We use the following little trick (proposed by Bernd Raichle):
%    The very first token in the token list we give to \cs{lowercase} is
%    the \cs{endgroup} primitive. This means that it is processed by
%    \TeX{} immediately after \cs{lowercase} has finished its operation,
%    thus ending the group started by \cs{begingroup} above. This avoids
%    the global definition of all macros.
%    \begin{macrocode}
 \lowercase{\endgroup
%    \end{macrocode}
% \begin{macro}{\verbatim@start}
%    The purpose of \cs{verbatim@start} is to check whether there
%    are any characters on the same line as the \verb?\begin{verbatim}?
%    and to pretend that they were on a line by themselves.
%    On the other hand, if there are no characters remaining
%    on the current line we shall just find an end of line character.
%    \cs{verbatim@start} performs its task by first grabbing the
%    following character (its argument).
%    This argument is then compared to an active \verb?^^M?,
%    the end of line character.
%    \begin{macrocode}
    \def\verbatim@start#1{%
      \verbatim@startline
      \if\noexpand#1\noexpand~%
%    \end{macrocode}
%    If this is true we transfer control to \cs{verbatim@}
%    to process the next line.  We use
%    \cs{next} as the macro which will continue the work.
%    \begin{macrocode}
        \let\next\verbatim@
%    \end{macrocode}
%    Otherwise, we define \cs{next} to expand to a call
%    to \cs{verbatim@} followed by the character just
%    read so that it is reinserted into the text.
%    This means that those characters remaining on this line
%    are handled as if they formed a line by themselves.
%    \begin{macrocode}
      \else \def\next{\verbatim@#1}\fi
%    \end{macrocode}
%    Finally we call \cs{next}.
%    \begin{macrocode}
      \next}%
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\verbatim@}
%    The three macros \cs{verbatim@}, \cs{verbatim@@},
%    and \cs{verbatim@@@} form the ``main loop'' of the
%    \texttt{verbatim} environment.
%    The purpose of \cs{verbatim@} is to read exactly one line
%    of input.
%    \cs{verbatim@@} and \cs{verbatim@@@} work together to
%    find out whether the four characters
%    \cs{end} (all with category code $12$ (other)) occur in that
%    line.
%    If so, \cs{verbatim@@@} will call
%    \cs{verbatim@test} to check whether this \cs{end} is
%    part of \verb?\end{verbatim}? and will terminate the environment
%    if this is the case.
%    Otherwise we continue as if nothing had happened.
%    So let's have a look at the definition of \cs{verbatim@}:
%    \begin{macrocode}
    \def\verbatim@#1~{\verbatim@@#1!end\@nil}%
%    \end{macrocode}
%    Note that the \verb?!? character will have been replaced by a
%    \verb?\? with category code $12$ (other) by the \cs{lowercase}
%    primitive governing this code before the definition of this
%    macro actually takes place.
%    That means that
%    it takes the line, puts \cs{end} (four character tokens)
%    and \cs{@nil} (one control sequence token) as a
%    delimiter behind it, and
%    then calls \cs{verbatim@@}.
% \end{macro}
%
% \begin{macro}{\verbatim@@}
%    \cs{verbatim@@} takes everything up to the next occurrence of
%    the four characters \cs{end} as its argument.
%    \begin{macrocode}
    \def\verbatim@@#1!end{%
%    \end{macrocode}
%    That means: if they do not occur in the original line, then
%    argument \verb?#1? is the
%    whole input line, and \cs{@nil} is the next token
%    to be processed.
%    However, if the four characters \cs{end} are part of the
%    original line, then
%    \verb?#1? consists of the characters in front of \cs{end},
%    and the next token is the following character (always remember
%    that the line was lengthened by five tokens).
%    Whatever \verb?#1? may be, it is verbatim text,
%    so \verb?#1? is added to the line currently built.
%    \begin{macrocode}
       \verbatim@addtoline{#1}%
%    \end{macrocode}
%    The next token in the input stream
%    is of special interest to us.
%    Therefore \cs{futurelet} defines \cs{next} to be equal
%    to it before calling \cs{verbatim@@@}.
%    \begin{macrocode}
       \futurelet\next\verbatim@@@}%
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\verbatim@@@}
%    \cs{verbatim@@@} will now read the rest of the tokens on
%    the current line,
%    up to the final \cs{@nil} token.
%    \begin{macrocode}
    \def\verbatim@@@#1\@nil{%
%    \end{macrocode}
%    If the first of the above two cases occurred, i.e.\ no
%    \cs{end} characters were on that line, \verb?#1? is empty
%    and \cs{next} is equal to \cs{@nil}.
%    This is easily checked.
%    \begin{macrocode}
       \ifx\next\@nil
%    \end{macrocode}
%    If so, this was a simple line.
%    We finish it by processing the line we accumulated so far.
%    Then we prepare to read the next line.
%    \begin{macrocode}
         \verbatim@processline
         \verbatim@startline
         \let\next\verbatim@
%    \end{macrocode}
%    Otherwise we have to check what follows these \cs{end}
%    tokens.
%    \begin{macrocode}
       \else
%    \end{macrocode}
%    Before we continue, it's a good idea to stop for a moment
%    and remember where we are:
%    We have just read the four character tokens \cs{end}
%    and must now check whether the name of the environment (surrounded
%    by braces) follows.
%    To this end we define a macro called \cs{@tempa}
%    that reads exactly one character and decides what to do next.
%    This macro should do the following: skip spaces until
%    it encounters either a left brace or the end of the line.
%    But it is important to remember which characters are skipped.
%    The \cs{end}\meta{optional spaces}\verb?{? characters
%    may be part of the verbatim text, i.e.\ these characters
%    must be printed.
%
%    Assume for example that the current line contains
%    \begin{verbatim*}
%      \end {AVeryLongEnvironmentName}
%\end{verbatim*}
%    As we shall soon see, the scanning mechanism implemented here
%    will not find out that this is text to be printed until
%    it has read the right brace.
%    Therefore we need a way to accumulate the characters read
%    so that we can reinsert them if necessary.
%    The token register \cs{@temptokena} is used for this purpose.
%
%    Before we do this we have to get rid of the superfluous
%    \cs{end} tokens at the end of the line.
%    To this end we define a temporary macro whose argument
%    is delimited by \verb?\end\@nil? (four character tokens
%    and one control sequence token) to be used below
%    on the rest of the line, after appending a \cs{@nil} token to it.
%    (Note that this token can never appear in \verb?#1?.)
%    We use the following definition of
%    \cs{@tempa} to get the rest of the line (after the first
%    \cs{end}).
%    \begin{macrocode}
         \def\@tempa##1!end\@nil{##1}%
%    \end{macrocode}
%    We mentioned already that we use token register
%    \cs{@temptokena}
%    to remember the characters we skip, in case we need them again.
%    We initialize this with the \cs{end} we have thrown away
%    in the call to \cs{@tempa}.
%    \begin{macrocode}
         \@temptokena{!end}%
%    \end{macrocode}
%    We shall now call \cs{verbatim@test}
%    to process the characters
%    remaining on the current line.
%    But wait a moment: we cannot simply call this macro
%    since we have already read the whole line.
%    Therefore we have to first expand the macro \cs{@tempa} to insert
%    them again after the \cs{verbatim@test} token.
%    A \verb?^^M? character is appended to denote the end of the line.
%    (Remember that this character comes disguised as a tilde.)
%    \begin{macrocode}
         \def\next{\expandafter\verbatim@test\@tempa#1\@nil~}%
%    \end{macrocode}
%    That's almost all, but we still have to
%    now call \cs{next} to do the work.
%    \begin{macrocode}
       \fi \next}%
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\verbatim@test}
%    We define \cs{verbatim@test} to investigate every token
%    in turn.
%    \begin{macrocode}
    \def\verbatim@test#1{%
%    \end{macrocode}
%    First of all we set \cs{next} equal to \cs{verbatim@test}
%    in case this macro must call itself recursively in order to
%    skip spaces.
%    \begin{macrocode}
           \let\next\verbatim@test
%    \end{macrocode}
%    We have to distinguish four cases:
%    \begin{enumerate}
%      \item The next token is a \verb?^^M?, i.e.\ we reached
%            the end of the line.  That means that nothing
%            special was found.
%            Note that we use \cs{if} for the following
%            comparisons so that the category code of the
%            characters is irrelevant.
%    \begin{macrocode}
           \if\noexpand#1\noexpand~%
%    \end{macrocode}
%            We add the characters accumulated in token register
%            \cs{@temptokena} to the current line.  Since
%            \cs{verbatim@addtoline} does not expand its argument,
%            we have to do the expansion at this point.  Then we
%            \cs{let} \cs{next} equal to \cs{verbatim@}
%            to prepare to read the next line.
%    \begin{macrocode}
             \expandafter\verbatim@addtoline
               \expandafter{\the\@temptokena}%
             \verbatim@processline
             \verbatim@startline
             \let\next\verbatim@
%    \end{macrocode}
%      \item A space character follows.
%            This is allowed, so we add it to \cs{@temptokena}
%            and continue.
%    \begin{macrocode}
           \else \if\noexpand#1
             \@temptokena\expandafter{\the\@temptokena#1}%
%    \end{macrocode}
%      \item An open brace follows.
%            This is the most interesting case.
%            We must now collect characters until we read the closing
%            brace and check whether they form the environment name.
%            This will be done by \cs{verbatim@testend}, so here
%            we let \cs{next} equal this macro.
%            Again we will process the rest of the line, character
%            by character.
%            The characters forming the name of the environment will
%            be accumulated in \cs{@tempc}.
%            We initialize this macro to expand to nothing.
%    \begin{macrocode}
           \else \if\noexpand#1\noexpand[%
             \let\@tempc\@empty
             \let\next\verbatim@testend
%    \end{macrocode}
%            Note that the \verb?[? character will be a \verb?{? when
%            this macro is defined.
%      \item Any other character means that the \cs{end} was part
%            of the verbatim text.
%            Add the characters to the current line and prepare to call
%            \cs{verbatim@} to process the rest of the line.
%    \begin{macrocode}
           \else
             \expandafter\verbatim@addtoline
               \expandafter{\the\@temptokena}%
             \def\next{\verbatim@#1}%
           \fi\fi\fi
%    \end{macrocode}
%    \end{enumerate}
%    The last thing this macro does is to call \cs{next}
%    to continue processing.
%    \begin{macrocode}
           \next}%
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\verbatim@testend}
%    \cs{verbatim@testend} is called when
%    \cs{end}\meta{optional spaces}\verb?{? was seen.
%    Its task is to scan everything up to the next \verb?}?
%    and to call \cs{verbatim@@testend}.
%    If no \verb?}? is found it must reinsert the characters it read
%    and return to \cs{verbatim@}.
%    The following definition is similar to that of
%    \cs{verbatim@test}:
%    it takes the next character and decides what to do.
%    \begin{macrocode}
    \def\verbatim@testend#1{%
%    \end{macrocode}
%    Again, we have four cases:
%    \begin{enumerate}
%      \item \verb?^^M?: As no \verb?}? is found in the current line,
%            add the characters to the buffer.  To avoid a
%            complicated construction for expanding
%            \cs{@temptokena}
%            and \cs{@tempc} we do it in two steps.  Then we
%            continue with \cs{verbatim@} to process the
%            next line.
%    \begin{macrocode}
         \if\noexpand#1\noexpand~%
           \expandafter\verbatim@addtoline
             \expandafter{\the\@temptokena[}%
           \expandafter\verbatim@addtoline
             \expandafter{\@tempc}%
           \verbatim@processline
           \verbatim@startline
           \let\next\verbatim@
%    \end{macrocode}
%      \item \verb?}?: Call \cs{verbatim@@testend} to check
%            if this is the right environment name.
%    \begin{macrocode}
         \else\if\noexpand#1\noexpand]%
           \let\next\verbatim@@testend
%    \end{macrocode}
%      \item \verb?\?: This character must not occur in the name of
%            an environment.  Thus we stop collecting characters.
%            In principle, the same argument would apply to other
%            characters as well, e.g., \verb?{?.
%            However, \verb?\? is a special case, since it may be
%            the first character of \cs{end}.  This means that
%            we have to look again for
%            \cs{end}\marg{environment name}
%            Note that we prefixed the \verb?!? by a \cs{noexpand}
%            primitive, to protect ourselves against it being an
%            active character.
%    \begin{macrocode}
         \else\if\noexpand#1\noexpand!%
           \expandafter\verbatim@addtoline
             \expandafter{\the\@temptokena[}%
           \expandafter\verbatim@addtoline
             \expandafter{\@tempc}%
           \def\next{\verbatim@!}%
%    \end{macrocode}
%      \item Any other character: collect it and continue.
%            We cannot use \cs{edef} to define \cs{@tempc}
%            since its replacement text might contain active
%            character tokens.
%    \begin{macrocode}
         \else \expandafter\def\expandafter\@tempc\expandafter
           {\@tempc#1}\fi\fi\fi
%    \end{macrocode}
%    \end{enumerate}
%    As before, the macro ends by calling itself, to
%    process the next character if appropriate.
%    \begin{macrocode}
         \next}%
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\verbatim@@testend}
%    Unlike the previous macros \cs{verbatim@@testend} is simple:
%    it has only to check if the \cs{end}\marg{...}
%    matches the corresponding \cs{begin}\marg{...}
%    \begin{macrocode}
    \def\verbatim@@testend{%
%    \end{macrocode}
%    We use \cs{next} again to define the things that are
%    to be done.
%    Remember that the name of the current environment is
%    held in \cs{@currenvir}, the characters accumulated
%    by \cs{verbatim@testend} are in \cs{@tempc}.
%    So we simply compare these and prepare to execute
%    \cs{end}\marg{current environment}
%    macro if they match.
%    Before we do this we call \cs{verbatim@finish} to process
%    the last line.
%    We define \cs{next} via \cs{edef} so that
%    \cs{@currenvir} is replaced by its expansion.
%    Therefore we need \cs{noexpand} to inhibit the expansion
%    of \cs{end} at this point.
%    \begin{macrocode}
       \ifx\@tempc\@currenvir
         \verbatim@finish
         \edef\next{\noexpand\end{\@currenvir}%
%    \end{macrocode}
%    Without this trick the \cs{end} command would not be able
%    to correctly check whether its argument matches the name of
%    the current environment and you'd get an
%    interesting \LaTeX{} error message such as:
%    \begin{verbatim}
%! \begin{verbatim*} ended by \end{verbatim*}.
%\end{verbatim}
%    But what do we do with the rest of the characters, those
%    that remain on that line?
%    We call \cs{verbatim@rescan} to take care of that.
%    Its first argument is the name of the environment just
%    ended, in case we need it again.
%    \cs{verbatim@rescan} takes the list of characters to be
%    reprocessed as its second argument.
%    (This token list was inserted after the current macro
%    by \cs{verbatim@@@}.)
%    Since we are still in an \cs{edef} we protect it
%    by means of\cs{noexpand}.
%    \begin{macrocode}
                    \noexpand\verbatim@rescan{\@currenvir}}%
%    \end{macrocode}
%    If the names do not match, we reinsert everything read up
%    to now and prepare to call \cs{verbatim@} to process
%    the rest of the line.
%    \begin{macrocode}
       \else
         \expandafter\verbatim@addtoline
           \expandafter{\the\@temptokena[}%
           \expandafter\verbatim@addtoline
             \expandafter{\@tempc]}%
         \let\next\verbatim@
       \fi
%    \end{macrocode}
%    Finally we call \cs{next}.
%    \begin{macrocode}
       \next}%
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\verbatim@rescan}
%    In principle \cs{verbatim@rescan} could be used to
%    analyse the characters remaining after the \verb?\end{...}?
%    command and pretend that these were read
%    ``properly'', assuming ``standard'' category codes are in
%    force.\footnote{Remember that they were all read with
%          category codes $11$ (letter) and $12$ (other) so
%          that control sequences are not recognized as such.}
%    But this is not always possible (when there are unmatched
%    curly braces in the rest of the line).
%    Besides, we think that this is not worth the effort:
%    After a \texttt{verbatim} or \texttt{verbatim*} environment
%    a new line in the output is begun anyway,
%    and an \verb?\end{comment}? can easily be put on a line by itself.
%    So there is no reason why there should be any text here.
%    For the benefit of the user who did put something there
%    (a comment, perhaps)
%    we simply issue a warning and drop them.
%    The method of testing is explained in Appendix~D, p.\ 376 of
%    the \TeX{}book. We use \verb?^^M? instead of the \verb?!?
%    character used there
%    since this is a character that cannot appear in \verb?#1?.
%    The two \cs{noexpand} primitives are necessary to avoid
%    expansion of active characters and macros.
%
%    One extra subtlety should be noted here: remember that
%    the token list we are currently building will first be
%    processed by the \cs{lowercase} primitive before \TeX{}
%    carries out the definitions.
%    This means that the `\texttt{C}' character in the
%    argument to the \cs{@warning} macro must be protected against
%    being changed to `\texttt{c}'.  That's the reason why we added the
%    \verb?\lccode`\C=`\C? assignment above.
%    We can now finish the argument to \cs{lowercase} as well as the
%    group in which the category codes were changed.
%    \begin{macrocode}
    \def\verbatim@rescan#1#2~{\if\noexpand~\noexpand#2~\else
        \@warning{Characters dropped after `\string\end{#1}'}\fi}}
%    \end{macrocode}
% \end{macro}
%
% \subsubsection{The \cs{verbatiminput} command}
%
% \begin{macro}{\verbatim@in@stream}
%    We begin by allocating an input stream (out of the 16 available
%    input streams).
%    \begin{macrocode}
\newread\verbatim@in@stream
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\verbatim@readfile}
%    The macro \cs{verbatim@readfile} encloses the main loop by calls to
%    the macros \cs{verbatim@startline} and \cs{verbatim@finish},
%    respectively.  This makes sure
%    that the user can initialize and finish the command when the file
%    is empty or doesn't exist.  The \texttt{verbatim} environment has a
%    similar behaviour when called with an empty text.
%    \begin{macrocode}
\def\verbatim@readfile#1{%
  \verbatim@startline
%    \end{macrocode}
%    When the file is not found we issue a warning.
%    \begin{macrocode}
  \openin\verbatim@in@stream #1\relax
  \ifeof\verbatim@in@stream
    \typeout{No file #1.}%
  \else
%    \end{macrocode}
%    At this point we pass the name of the file to \cs{@addtofilelist}
%    so that its appears appears in the output of a \cs{listfiles}
%    command.
%    In addition, we use \cs{ProvidesFile} to make a log entry in the
%    transcript file and to distinguish files read in via
%    \cs{verbatiminput} from others.
%    \begin{macrocode}
    \@addtofilelist{#1}%
    \ProvidesFile{#1}[(verbatim)]%
%    \end{macrocode}
%    While reading from the file it is useful to switch off the
%    recognition of the end-of-line character.  This saves us stripping
%    off spaces from the contents of the line.
%    \begin{macrocode}
    \expandafter\endlinechar\expandafter\m@ne
    \expandafter\verbatim@read@file
    \expandafter\endlinechar\the\endlinechar\relax
    \closein\verbatim@in@stream
  \fi
  \verbatim@finish
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\verbatim@read@file}
%    All the work is done in \cs{verbatim@read@file}.  It reads the input
%    file line by line and recursively calls itself until the end of
%    the file.
%    \begin{macrocode}
\def\verbatim@read@file{%
  \read\verbatim@in@stream to\next
  \ifeof\verbatim@in@stream
  \else
%    \end{macrocode}
%    For each line we call \cs{verbatim@addtoline} with the contents of
%    the line. \hskip0pt plus 3cm\penalty0\hskip0pt plus -3cm
%    \cs{verbatim@processline} is called next.
%    \begin{macrocode}
    \expandafter\verbatim@addtoline\expandafter{\next}%
    \verbatim@processline
%    \end{macrocode}
%    After processing the line we call \cs{verbatim@startline} to
%    initialize all before we read the next line.
%    \begin{macrocode}
    \verbatim@startline
%    \end{macrocode}
%    Without \cs{expandafter} each call of \cs{verbatim@read@file} uses
%    space in \TeX's input stack.\footnote{A standard \TeX\ would
%    report an overflow error if you try to read a file with more than
%    ca.\ 200~lines.  The same error occurs if the first line of code
%    in \S 390 of \textsl{``TeX: The Program''\/} is missing.}
%    \begin{macrocode}
    \expandafter\verbatim@read@file
  \fi
}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\verbatiminput}
%    \cs{verbatiminput} first starts a group to keep font and category
%    changes local.
%    Then it calls the macro \cs{verbatim@input} with additional
%    arguments, depending on whether an asterisk follows.
%
% PW. I added the TAB checking code.
%    \begin{macrocode}
\def\verbatiminput{\begingroup
  \ift@bs
    \def\verbatim@processline{\tabverbatim@processline}%
  \fi
  \@ifstar{\verbatim@input{\@maybeobeytabs}}%
          {\verbatim@input{\frenchspacing\@vobeyspaces\@maybeobeytabs}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\verbatim@input}
%    \cs{verbatim@input} first checks whether the file exists, using
%    the standard macro cs{IfFileExists} which leaves the name of the
%    file found in \cs{@filef@und}.
%    Then everything is set up as in the \cs{verbatim} macro.
%    \begin{macrocode}
\def\verbatim@input#1#2{%
   \IfFileExists {#2}{\@verbatim #1\relax
%    \end{macrocode}
%    Then it reads in the file, finishes off the \texttt{trivlist}
%    environment started by \cs{@verbatim} and closes the group.
%    This restores everything to its normal settings.
%    \begin{macrocode}
    \verbatim@readfile{\@filef@und}\endtrivlist\endgroup\@doendpe}%
%    \end{macrocode}
%   If the file is not found a more or less helpful message is
%    printed. The final \cs{endgroup} is  needed to close the group
%    started in \cs{verbatiminput} above.
%    \begin{macrocode}
   {\typeout {No file #2.}\endgroup}}
%    \end{macrocode}
% \end{macro}
%
% \textit{That completes my borrowings from \Lpack{verbatim}.}
%
% The next bunch of code implements wrapping verbatim lines so they, hopefully,
% stay within the typeblock.
%
% \begin{macro}{\verbatimindent}
% \begin{macro}{\verbatimbreakchar}
% \begin{macro}{\setverbatimbreak}
% The length \cs{verbatimindent} is the distance continuation lines are indented
% from the left margin. \cs{verbatimbreakchar} is the character to indicate
% a wrapped line.
%    \begin{macrocode}
\newlength{\verbatimindent}
  \setlength{\verbatimindent}{3em}
\newcommand*{\verbatimbreakchar}{\char`\%}
\newcommand*{\setverbatimbreak}{%
  \vspace*{-\baselineskip}%
  \def\@xobeysp{~\discretionary{\verbatimbreakchar}%
    {\kern\verbatimindent}{}}%
}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\raggedwrap}
% \begin{macro}{\wrappingon}
% \begin{macro}{\wrapright}
% \begin{macro}{\wrappingoff}
% \cs{wrappingon} and \cs{wrappingoff} enable/prohibit wrapping. The
% default is \cs{wrappingoff}.
%
% The macro
% \cs{wrapright}  is used to set paragraph skips; without raggedright the 
% lines
% may break at the first space \emph{outside} the text area. However,
% Paul (\url{paulaugust2003@yahoo.com}) found that wrapped verbatims
% in a list (e.g., \texttt{itemize}) were not indented although regular
% verbatims were indented. \cs{raggedwrap} is a variation on \cs{raggedright}
% (\cs{leftskip} is set to \cs{@totalleftmargin} instead of 0pt), and seems
% to have fixed the problem with the original code which used 
% \cs{raggedright}. 
% \changes{v1.61803}{2008/01/30}{Added \cs{raggedwrap} (mempatch v4.4)}
% \changes{v1.61803398}{2009/07/18}{Added bidi support to \cs{raggedwrap}}
%    \begin{macrocode}
\newcommand*{\raggedwrap}{%
  \@rightskip\@flushglue
%%%  \rightskip\@rightskip
  \memRTLrightskip\@rightskip
%%%  \leftskip\@totalleftmargin
  \memRTLleftskip\@totalleftmargin
  \parindent\ragrparindent}
\newcommand*{\wrappingon}{%
  \def\@xobeysp{~\discretionary{\verbatimbreakchar}%
    {\kern\verbatimindent}{}}%
  \def\wrapright{\raggedwrap}}
\newcommand*{\wrappingoff}{%
  \def\@xobeysp{\leavevmode\penalty\@M\ }%
  \def\wrapright{}}
\wrappingoff

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \subsection{Writing and boxing verbatim}
%
%    This bunch of code is from the \Lpack{moreverb} package.
%
% \begin{environment}{verbatimoutput}
% \verb?\begin{verbatimoutput}?\marg{filename} writes all text in its body to a
% file, the name of which it is given as an argument. (The code was
% written by Rainer Sch\"opf but the environment was called 
% \verb?verbatimwrite?). In the code below, uncommenting \\
% \verb?\catcode`\^^I=12? \\
% will result in TABs being written as \verb?^^I?.
% \changes{v1.3}{2002/09/27}{Changed name verbatimwrite to 
%               verbatimoutput (but neither were mentioned in the manual)}
%    \begin{macrocode}
\newwrite \verbatim@out
\def\verbatimoutput#1{%
  \@bsphack
  \immediate\openout \verbatim@out #1
  \let\do\@makeother\dospecials
  \catcode`\^^M\active %% \catcode`\^^I=12  
  \def\verbatim@processline{%
    \immediate\write\verbatim@out
      {\the\verbatim@line}}%
  \verbatim@start}
%    \end{macrocode}
%    \begin{macrocode}
\def\endverbatimoutput{%
  \immediate\closeout\verbatim@out
  \@esphack}
%    \end{macrocode}
% \end{environment}
%
%
%
% \begin{environment}{fboxverbatim}
% \texttt{fboxverbatim} puts the contents of a verbatim environment
% in a framing box. (PW: This was originally called \texttt{boxedverbatim}).
%
% (Written by Victor Eijkhout.)
%
% Bug fix (supplied by David Carlisle) 1995/12/28, marked
% \verb+%%%DPC%%%+
%
% First, redefine `processline' to produce only a line as wide
% as the natural width of the line
%
%    \begin{macrocode}
\def\fboxverbatim{\begingroup%
  \tabsoff %% PW otherwise box fills the width
  \def\verbatim@processline{%
    {\setbox0=\hbox{\the\verbatim@line}%
    \hsize=\wd0 \the\verbatim@line\par}}%
%    \end{macrocode}
%
% Now save the verbatim code in a box
%
%    \begin{macrocode}
  \@minipagetrue%%%DPC%%%
  \@tempswatrue%%%DPC%%%
  \setbox0=\vbox\bgroup \verbatim
}
%    \end{macrocode}
%
% At the end of the environment, we (umm) simply have to stick the
% results into a frame.
%
%    \begin{macrocode}
\def\endfboxverbatim{%
  \endverbatim
  \unskip\setbox0=\lastbox %%%DPC%%%
%    \end{macrocode}
%
% Now everything's in the box, so we can close it\dots
%
%    \begin{macrocode}
  \egroup
%    \end{macrocode}
%
% To change the code for centering, the next line needs a spot of
% hacking.
%
%    \begin{macrocode}
  \fbox{\box0}% <<<=== change here for centering,...
\endgroup}
%    \end{macrocode}
% \end{environment}
%
%
%
% \subsection{The shortvrb package}
%
% The following is the \Lpack{shortvrb} package code (from \texttt{doc.dtx}
% by Frank Mittelbach). It has been so useful to me that I wanted
% to include it in the class.
%
% CODE AND COMMENTARY IS BY FRANK MITTELBACH
%
% \begin{macro}{\MakeShortVerb}
%    \begin{macrocode}
\def\MakeShortVerb#1{%
  \expandafter\ifx\csname cc\string#1\endcsname\relax
%    \end{macrocode}
%    \begin{macrocode}
    \@shortvrbinfo{Made }{#1}%
    \add@special{#1}%
%    \end{macrocode}
% Then the character's current catcode is stored in \verb?\cc\?\meta{c}.
%    \begin{macrocode}
    \expandafter
    \xdef\csname cc\string#1\endcsname{\the\catcode`#1}%
%    \end{macrocode}
% The character is spliced into the definition using the same trick as
% used in \cs{verb} (for instance), having activated \verb?~? in a group.
%    \begin{macrocode}
    \begingroup
      \catcode`\~\active  \lccode`\~`#1%
      \lowercase{%
%    \end{macrocode}
% The character's old meaning is recorded in \verb?\ac\?\meta{c} prior to
% assigning it a new one.
%    \begin{macrocode}
      \global\expandafter\let
         \csname ac\string#1\endcsname~%
      \gdef~{\verb~}}%
    \endgroup
%    \end{macrocode}
% Finally the character is made active.
%    \begin{macrocode}
    \global\catcode`#1\active
%    \end{macrocode}
% If we suspect that \meta{c} is already a short reference, we tell
% the user. Now he or she is responsible if anything goes wrong\,\dots
%    \begin{macrocode}
  \else
%    \end{macrocode}
%    \begin{macrocode}
    \@shortvrbinfo\@empty{#1 already}%
  \fi}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\DeleteShortVerb}
% Here's the means of undoing a \cs{MakeShortVerb}, for instance in a
% region where you need to use the character outside a verbatim
% environment.  It arranges for \cs{dospecials} and \cs{@sanitize} to be
% altered appropriately, restores the saved catcode and, if necessary,
% the character's meaning (as stored by 
% \cs{MakeShortVerb}).  If the catcode wasn't stored in
% \verb?\cc\?\meta{c} (by \cs{MakeShortVerb}) the command is silently
% ignored. 
%    \begin{macrocode}
\def\DeleteShortVerb#1{%
  \expandafter\ifx\csname cc\string#1\endcsname\relax
  \else
%    \end{macrocode}
%    \begin{macrocode}
    \@shortvrbinfo{Deleted }{#1 as}%
    \rem@special{#1}%
    \global\catcode`#1\csname cc\string#1\endcsname
%    \end{macrocode}
% We must not forget to reset \verb?\cc\?\meta{c}, otherwise the check in
% \cs{MakeShortVerb} for a repeated definition will not work.
%    \begin{macrocode}
    \global \expandafter\let \csname cc\string#1\endcsname \relax
    \ifnum\catcode`#1=\active
      \begingroup
        \catcode`\~\active   \lccode`\~`#1%
        \lowercase{%
          \global\expandafter\let\expandafter~%
          \csname ac\string#1\endcsname}%
      \endgroup \fi \fi}
%    \end{macrocode}
% \end{macro}
%
%  \begin{macro}{\@shortvrbinfo}
% Helper function for info messages.
%    \begin{macrocode}
\def\@shortvrbinfo#1#2{%
  \ClassInfo{memoir}{%
     #1\expandafter\@gobble\string#2 a short reference
                                          for \string\verb}}
%    \end{macrocode}
%  \end{macro}
%
% \begin{macro}{\add@special}
% This helper macro adds its argument to the
% \cs{dospecials} macro which is conventionally used by verbatim macros
% to alter the catcodes of the currently active characters.  We need
% to add \verb?\do\?\meta{c} to the expansion of \cs{dospecials} after
% removing the character if it was already there to avoid multiple
% copies building up should \cs{MakeShortVerb} not be balanced by
% \cs{DeleteShortVerb} (in case anything that uses \cs{dospecials} cares
% about repetitions).
%    \begin{macrocode}
\def\add@special#1{%
  \rem@special{#1}%
  \expandafter\gdef\expandafter\dospecials\expandafter
    {\dospecials \do #1}%
%    \end{macrocode}
% Similarly we have to add \verb?\@makeother\?\meta{c} to \cs{@sanitize}
% (which is used in things like \cs{index} to re-catcode all special
% characters except braces).
%    \begin{macrocode}
  \expandafter\gdef\expandafter\@sanitize\expandafter
    {\@sanitize \@makeother #1}}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\rem@special}
% The inverse of cs{add@special} is slightly trickier.  \cs{do} is
% re-defined to expand to nothing if its argument is the character of
% interest, otherwise to expand simply to the argument.  We can then
% re-define \cs{dospecials} to be the expansion of itself.  The space
% after \verb?=`##1? prevents an expansion to \cs{relax}!
%    \begin{macrocode}
\def\rem@special#1{%
  \def\do##1{%
    \ifnum`#1=`##1 \else \noexpand\do\noexpand##1\fi}%
  \xdef\dospecials{\dospecials}%
%    \end{macrocode}
% Fixing \cs{@sanitize} is the same except that we need to re-define
% \cs{@makeother} which obviously needs to be done in a group. 
%    \begin{macrocode}
  \begingroup
    \def\@makeother##1{%
      \ifnum`#1=`##1 \else \noexpand\@makeother\noexpand##1\fi}%
    \xdef\@sanitize{\@sanitize}%
  \endgroup}
%    \end{macrocode}
% \end{macro}
%
% END OF MITTELBACH CODE AND COMMENTARY.
%
% \subsection{General verbatim boxing and line numbering}
%
%    A while ago I wrote a package that I never released. Here it is
% now, updated and improved. The package was based on code originally
% posted to \ctt{}  by Donald Arseneau on 13 July 2000.
%
% This is DA's posted code.
% \begin{verbatim}
% \RequirePackage{verbatim}
% \def\boxverbflag{14 }
%
% \def\boxedverbatim{%
%    \fboxsep=1em
%    \def\verbatim@processline{\leavevmode
%      \vrule\vbox{\advance\hsize-.8p@ \@@line
%        {\strut\kern\fboxsep\the\verbatim@line\hss}%
%         \kern\fbozsep}\vrule\par}%
%    \@verbatim % but make some replacement settings
% %   \ifdim\@totalleftmargin>\fboxsep \fboxsep\@totalleftmargin \fi
%    \leftskip\x@skip \rightskip\z@skip
%    \interlinepenalty\boxverbflag
%    \parfillskip\z@ plus\p@ minus\p@
%    \lineskip-\fboxsep \baselineskip\z@skip
%    \frenchspacing\@vobeyspaces
%    \boxverb@toprule
%    \verbatim@start}
%
% \def\endboxedverbatim{\hrule\endtrivlist}
%
% \@namefdef{boxedverbatim*}{\let\frenchspacing\@gobble \boxedverbatim}
% \@namefdef{endboxedverbatim*}{\hrule\endtrivlist}
%
% \output=\expandafter{\expandafter\boxverb@split \the\output}
%
% \def\boxverb@toprule{\hrule \nobreak \vskip-.1\p@
%    \@@line{\vrule height2\fboxsep \hss \vrule}}
%
% \def\boxverb@split{\ifnum\outputpenalty=\boxverbflag
%    \ifdim\dp\@cclv=\z@
%    \setbox\@cclv\vbox{\unvbox\@cclv\hrule\kern-.4pt}%
%    \null \kern-.7\topskip \boxverb@toprule
%    \fi\fi}
% \end{verbatim}
% That's the end of DA's posted code
%
% I have extended this to provide:
% \begin{itemize}
%  \item A (multipage) boxed verbatim
%  \item A (multipage) boxed verbatim input
%  \item Normally each `page' is boxed, but start/end rules can be switched off
%    at page boundaries
%  \item A heading can be put at the start of `continuation' pages
%  \item Lines of verbatim text can be numbered
%  \item Can be `downgraded' to normal verbatim environment
%  \end{itemize}
%
%    OK, on to the main code.
%
% \begin{macro}{\boxverbflag}
% \begin{macro}{\bvboxsep}
%    \begin{macrocode}
\def\boxverbflag{14 }
\newlength{\bvboxsep}      % user can change this
\setlength{\bvboxsep}{1em}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%    \begin{macrocode}
\newif\ifbvperpage % start/end lines on every page of multipage verbatim
\bvperpagetrue

%    \end{macrocode}
%
% \begin{macro}{\bvtopofpage}
% \begin{macro}{\b@vtop}
% Can use \cs{bvtopofpage} to put a heading above continued verbatims.
% For example \\
% \verb?\bvtopofpage{\begin{center}\normalfont (Continued)\end{center}}? \\
% It only works for \cs{bvperpagetrue}.
%    \begin{macrocode}
\newcommand{\bvtopofpage}[1]{%
  \long\def\b@vtop{#1}}
\def\b@vtop{}  % used in \boxverb@split for heading 

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\c@memfbvline}
% \begin{macro}{\c@bvlinectr}
% Counter for adjusting the starting line number for boxed verbatims
% and for the line number itself..
%    \begin{macrocode}
\newcounter{memfbvline}
  \c@memfbvline=\z@
\newcounter{bvlinectr}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\setbvlinenums}
% \cs{setbvlinenums}\marg{firstline}\marg{startnumsat} sets the first line
% number to \meta{firstline} and the first line number to be printed is
% \meta{startnumsat}. 
% \changes{v1.61803}{2008/01/30}{Added \cs{setbvlinenums} (mempatch v4.9)}
%    \begin{macrocode}
\newcommand*{\setbvlinenums}[2]{%
  \c@bvlinectr #1\relax \advance\c@bvlinectr \m@ne
  \ifnum\z@<\linemodnum%   we are printing line numbers
    \@tempcnta #2\relax
    \divide\@tempcnta\linemodnum
    \multiply\@tempcnta\linemodnum
    \c@memfbvline #2\relax
    \advance\c@memfbvline-\@tempcnta
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\theb@vlinenumber}
% \begin{macro}{\resetbvlinenumber}
% \cs{resetbvlinenumber} reinitializes the line numbering.
% \changes{v1.61803}{2008/01/30}{Changed \cs{theb@vlinenumber} (mempatch v4.9)}
%    \begin{macrocode}
\def\theb@vlinenumber{\getthelinenumber{bvlinectr}{memfbvline}}
\newcommand*{\resetbvlinenumber}{\setcounter{bvlinectr}{0}}
 
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\b@vdocount}
% \begin{macro}{\bvnumlength}
% Increment line number if counting. A line number is printed in
% a space width \cs{bvnumlength}, which is given a temporary value here.
%    \begin{macrocode}
\def\b@vdocount{\ifbvcountlines\stepcounter{bvlinectr}\fi}
\newlength{\bvnumlength}       
%% \settowidth{\bvnumlength}{\vlvnumfont 9999}
\settowidth{\bvnumlength}{\normalfont 999}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ifbvcountinside}
% \begin{macro}{\bvnumbersinside}
% \begin{macro}{\bvnumbersoutside}
% Flag and commands for positioning the numbers. Default is to print
% them inside the box.
%    \begin{macrocode}
\newif\ifbvcountinside  % TRUE if line numbers inside box
  \bvcountinsidetrue
\newcommand*{\bvnumbersinside}{\bvcountinsidetrue}
\newcommand*{\bvnumbersoutside}{\bvcountinsidefalse}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\b@vdoinside}
% \begin{macro}{\b@vdooutside}
% Print numbers inside (outside) the box.
%    \begin{macrocode}
\def\b@vdoinside{%
  \ifbvcountlines\ifbvcountinside%
    \makebox[\bvnumlength][r]{%
      \vlvnumfont \theb@vlinenumber\space}%
  \fi\fi}

\def\b@vdooutside{%
  \ifbvcountlines\ifbvcountinside\else%
    \llap{\makebox[\bvnumlength][r]{%
      \vlvnumfont \theb@vlinenumber\space}}%
  \fi\fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@@m@mline}
% \cs{@@line} is defined as \verb?\def\@@line{\hb@xt@\hsize}? and I need
% an equivalent for \cs{linewidth} instead of \cs{hsize} for use in
% \cs{setupboxverb@line}.
% \changes{v1.61803}{2008/01/30}{Added \cs{@@m@mline} (mempatch v4.9)}
%    \begin{macrocode}
\newcommand*{\@@m@mline}{\hb@xt@\linewidth}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\setupboxverb@line}
% Use a macro for the first main part of DA's code for \cs{boxedverbatim}, 
% adding lots of hooks.
%
% Per Starb\"{a}ck had problems with the combination of \texttt{adjustwidth} 
% with \texttt{boxedverbatim} (see CTT \textit{Re: [memoir] adjustwidth + 
% boxedverbatim}, 2007/02/10) and Lars Madsen came up with a suggestion to
% use \cs{linewidth} instead of \cs{hsize}.
% \changes{v1.61803}{2008/01/30}{Changed \cs{hsize} to \cs{linewidth} in
%         \cs{setupboxverb@line} (mempatch v4.9)}
%    \begin{macrocode}
\newcommand{\setupboxverb@line}{%
  \par
  \ifbvperpage
    \output=\expandafter{\expandafter\boxverb@split \the\output}
  \fi
%    \end{macrocode}
% \begin{macro}{\verbatim@processline}
%    \begin{macrocode}
  \def\verbatim@processline{\leavevmode
    \b@vdocount%
    \bvleftsidehook\vbox{\advance% \hsize-.8\p@ \@@line % changed to \linewidth
                                 \linewidth-.8\p@ \@@line
      {\b@vdooutside\strut\kern\bvboxsep%
       \b@vdoinside%
       \ift@bs
         \tabverbatim@processline
       \else
         \the\verbatim@line
       \fi
       \hss}%
     \kern\bvboxsep}\bvrightsidehook\par}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\setupbox@verb}
% Use a macro for the second main part of DA's code, and integrate it
% with the other verbatim codes (e.g., include \cs{@maybeobeytags}).
%    \begin{macrocode}
\newcommand{\setupbox@verb}{%
  \leftskip\z@skip \rightskip\z@skip
  \interlinepenalty\boxverbflag
  \parfillskip\z@ plus\p@ minus\p@
  \lineskip-\bvboxsep \baselineskip\z@skip
  \frenchspacing\@vobeyspaces\@maybeobeytabs
  \boxverb@toprule}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\boxedverbatim}
% \begin{macro}{\endboxedverbatim}
% \begin{macro}{\boxedverbatim*}
% \begin{macro}{\endboxedverbatim*}
% Given the two macros above, we can write a briefer version of DA's 
% \cs{boxedverbatim(*)}. 
% As noted by Zarko Cucej\footnote{\url{zarko.cucej@uni-mb.si}}, have to handle
% a following (no-) paragraph.
% \changes{v1.4}{2003/11/22}{Added \cs{@doendpe} to \cs{endboxedverbatim}
%                            (from patch v1.8)}
%    \begin{macrocode}
\def\boxedverbatim{\begingroup
  \let\@@line\@@m@mline%    new from mempatch v4.9
  \setupboxverb@line
  \@verbatim
  \setupbox@verb
  \verbatim@start}
\def\endboxedverbatim{\bvendrulehook\endtrivlist\endgroup\@doendpe}
\@namedef{boxedverbatim*}{\let\frenchspacing\@gobble \boxedverbatim}
\@namelet{endboxedverbatim*}\endboxverbatim

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%    \begin{macrocode}
\def\boxverb@toprule{\bvtoprulehook
  \@@line{\bvleftsidehook \bvtopmidhook \bvrightsidehook}}

%    \end{macrocode}
%
% \begin{macro}{\bvendofpage}
% \cs{bvendofpage}\marg{spec} sets the boxed verbatim `end of page' to \meta{spec}.
% \changes{v1.618}{2005/09/02}{Added \cs{bvendofpage} (mempatch v2.3d)}
% \changes{v1.61803}{2008/01/30}{Changed \cs{bvendofpage} to include width}
%    \begin{macrocode}
\newcommand*{\bvendofpage}[1]{%
  \def\boxverb@botpage{#1}}
%%%%\bvendofpage{\hrule\kern-.4pt}
\bvendofpage{\hrule width\linewidth\kern-.4pt}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\boxverb@split}
%    \begin{macrocode}
\def\boxverb@split{\ifnum\outputpenalty=\boxverbflag
  \ifdim\dp\@cclv=\z@
%%%%    \setbox\@cclv\vbox{\unvbox\@cclv\hrule\kern-.4pt}%
    \setbox\@cclv\vbox{\unvbox\@cclv\boxverb@botpage}%
    \null \kern-.7\topskip \b@vtop \boxverb@toprule
  \fi
\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\bvtoprulehook}
% \begin{macro}{\bvendrulehook}
% \begin{macro}{\bvleftsidehook}
% \begin{macro}{\bvrightsidehook}
% \begin{macro}{\bvtopmidhook}
% The new hooks, for the top, bottom, left and right of the box.
% \changes{v1.61803}{2008/01/30}{Added \cs{linewidth} to \cs{bvtoprulehook} and
%                 \cs{bvendrulehook} (mempatch v4.9)}
%    \begin{macrocode}
\def\bvtoprulehook{\hrule width\linewidth \nobreak\vskip-.1\p@}
\def\bvendrulehook{\hrule width\linewidth}
\def\bvleftsidehook{\vrule}
\def\bvrightsidehook{\vrule}
\def\bvtopmidhook{\rule{0\p@}{2\bvboxsep} \hss}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\boxedverbatiminput}
% \begin{macro}{\boxedverbatim@input}
% \cs{boxedverbatiminput}\marg{filename} read in filename contents as verbatim
%    \begin{macrocode}
\newcommand{\boxedverbatiminput}{\begingroup
  \@ifstar{\let\frenchspacing\@gobble 
           \boxedverbatim@input\relax}%
          {\boxedverbatim@input{\frenchspacing\@vobeyspaces}}}

%    \end{macrocode}
%
%    \begin{macrocode}
\def\boxedverbatim@input#1#2{%
  \setupboxverb@line
  \IfFileExists{#2}{\@verbatim #1\relax
  \setupbox@verb
    \verbatim@readfile{\@filef@und}%
      \bvendrulehook\endtrivlist\endgroup\@doendpe}%
  {\typeout {No file #2.}\endgroup}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% Some prepackaged boxing styles.
%
% \begin{macro}{\bvbox}
% Original (default) boxing.
%    \begin{macrocode}
\newcommand{\bvbox}{%
  \bvperpagetrue%
  \renewcommand{\bvtoprulehook}{\hrule \nobreak \vskip-.1\p@}%
  \renewcommand{\bvleftsidehook}{\vrule}%
  \renewcommand{\bvrightsidehook}{\vrule}%
  \renewcommand{\bvendrulehook}{\hrule}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\nobvbox}
% No boxing
%    \begin{macrocode}
\newcommand{\nobvbox}{%
  \bvperpagefalse%
  \renewcommand{\bvtoprulehook}{}%
  \renewcommand{\bvleftsidehook}{}%
  \renewcommand{\bvrightsidehook}{}%
  \renewcommand{\bvendrulehook}{}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\bvtopandtail}
% Head and foot horizontal lines only
%    \begin{macrocode}
\newcommand{\bvtopandtail}{%
  \bvperpagefalse%
  \renewcommand{\bvtoprulehook}{\hrule \nobreak \vskip-.1\p@}%
  \renewcommand{\bvleftsidehook}{}%
  \renewcommand{\bvrightsidehook}{}%
  \renewcommand{\bvendrulehook}{\hrule}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\bvsides}
% Side vertical lines only
%    \begin{macrocode}
\newcommand{\bvsides}{%
  \bvperpagefalse%
  \renewcommand{\bvtoprulehook}{\vskip 3ex}%
  \renewcommand{\bvleftsidehook}{\vrule}%
  \renewcommand{\bvrightsidehook}{\vrule}%
  \renewcommand{\bvendrulehook}{}}

%    \end{macrocode}
% \end{macro}
%
%
%
% \subsection{The framed package}
%
% The following code is the \Lpack{framed} package~\cite{FRAMED}
% by Donald Arseneau.
% \changes{v1.4}{2003/11/22}{Updated framed code to v0.8a of the package}
% \changes{v1.61803}{2008/01/30}{Updated framed code to v0.95 of the package}
%
% \begin{macro}{\framed}
% \begin{macro}{\endframed}
% \begin{macro}{\shaded}
% \begin{macro}{\endshaded}
%    \begin{macrocode}
\let\framed\relax \let\endframed\relax
\let\shaded\relax \let\endshaded\relax

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% Way back when DA sent me a pre-release copy of v0.6 of his \Lpack{framed} 
% package~\cite{FRAMED}.
% We also discussed good ways of embedding it into the class. One result
% being that I defined some some items \cs{AtBeginDocument}, but this is
% no longer required as DA has changed \Lpack{framed} to cooperate
% with memoir. We continue to have sporadic email conversations about the
% interaction of \Lpack{memoir} and \Lpack{framed}.
%
% Here is a modified version of \file{framed.sty}. In particular
% I moved some of DA's description of the code into the general commentary
% instead of comments within the code.
%
% \begin{verbatim}
% framed.sty   v 0.95    2007/10/04
% Copyright (C) 1992-2007 by Donald Arseneau  (asnd@triumf.ca)
% These macros may be freely transmitted, reproduced, or modified
% provided that this notice is left intact.
% 
%====================== Begin Instructions =======================
%
%                       framed.sty
%                       ~~~~~~~~~~
% Create framed, shaded, or differently highlighted regions that can 
% break across pages.  The environments defined are 
%   framed    -- ordinary frame box (\fbox) with edge at margin
%   shaded    -- shaded background (\colorbox) bleeding into margin
%   snugshade -- similar
%   leftbar   -- thick vertical line in left margin
% to be used like
% \begin{framed}
%  copious text
% \end{framed}
%
% But the more general purpose of this package is to facilitate the
% creation of environments that enable page breaking
% within arbitrary decorations using a simple new-environment definition
% incorporating \FrameCommand and
% \begin{MakeFramed}{settings} ... \end{MakeFramed}
%
% The "framed" environment uses "\fbox" as its "\FrameCommand" with 
% the additional settings \fboxrule=\FrameRule and \fboxsep=\FrameSep.
% You can change these lengths (using \setlength) and you can change 
% the definition of \FrameCommand to use much fancier boxes.
%
% In fact, the "shaded" environment just redefines \FrameCommand to be
% \colorbox{shadecolor} (and you have to define the color "shadecolor":
% \definecolor{shadecolor}...).
%
% A page break is allowed, and even encouraged, before the framed
% environment.  If you want to attach some text (a box title) to the
% frame, then the text should be inserted by \FrameCommand.
%
% The contents of the framed regions are restricted: 
% Floats, footnotes, marginpars and head-line entries will be lost.
% (Some of these may be handled in a later version.)
% This package will not work with the page breaking of multicol.sty,
% or other systems that perform column-balancing.
%
% The MakeFramed environment does the work.  Its "settings" argument
% should contain any adjustments to the text width (applied to \hsize,
% and using the "\width" of the frame itself) as well as a "restore" 
% command -- \@parboxrestore or \FrameRestore or something similar;
% as an example, the snugshade environment shows how to suppress excess
% spacing within the box, copying the code from minipage.
%
% Expert commands:
% \MakeFramed, \endMakeFramed: the "MakeFramed" environment
% \FrameCommand: command to draw the frame around its argument
% \FrameRestore: restore some text settings, but fewer than \@parboxrestore
% \FrameRule: length register; \fboxrule for default "framed".
% \FrameSep: length register; \fboxsep for default "framed".
% \FrameHeightAdjust: macro; height of frame above baseline at top of page
% 
% This is still a `pre-production' version because I can think of many
% features/improvements that should be made.  Nevertheless, starting 
% with version 0.5 it should be bug-free.
%
% ToDo: 
% Test more varieties of list 
% Improve and correct documentation
% Propagation of \marks
% Handle footnotes (how??) floats (?) and marginpars.
% Stretchability modification.
%======================== End Instructions ========================
%
% \ProvidesPackage{framed}[2007/10/04 v 0.95: 
%    framed or shaded text with page breaks]
%
% \newenvironment{framed}% using default \FrameCommand
%   {\MakeFramed {\advance\hsize-\width \FrameRestore}}%
%   {\endMakeFramed}
%
% \newenvironment{shaded}{%
%   \def\FrameCommand{\fboxsep=\FrameSep \colorbox{shadecolor}}%
%   \MakeFramed {\FrameRestore}}%
%   {\endMakeFramed}
%
% \newenvironment{leftbar}{%
%   \def\FrameCommand{\vrule width 3pt \hspace{10pt}}%
%   \MakeFramed {\advance\hsize-\width \FrameRestore}}%
%  {\endMakeFramed}
%
% \newenvironment{snugshade}{%
%   \def\FrameCommand{\colorbox{shadecolor}}%
%   \MakeFramed {\FrameRestore\@setminipage}}%
%  {\par\unskip\endMakeFramed}
% 
% \end{verbatim}
%
% Now for the package code.
%
%    \begin{macrocode}
\chardef\FrameRestore=\catcode`\| % for debug
\catcode`\|=\catcode`\% % (debug: insert space after backslash)

%    \end{macrocode}
%
% \begin{macro}{\MakeFramed}
%    \begin{macrocode}
\def\MakeFramed#1{\par
%    \end{macrocode}
% measure added width and height; call result \cs{width} and \cs{height}
%    \begin{macrocode}
 \fb@sizeofframe\FrameCommand
 \let\width\fb@frw \let\height\fb@frh
%    \end{macrocode}
% insert pre-penalties and skips
%    \begin{macrocode}
 \begingroup
 \skip@\lastskip
 \if@nobreak\else 
    \penalty9999 % updates \page parameters
    \ifdim\pagefilstretch=\z@ \ifdim\pagefillstretch=\z@
%    \end{macrocode}
% not infinitely stretchable, so encourage a page break here
%    \begin{macrocode}
       \edef\@tempa{\the\skip@}%
       \ifx\@tempa\zero@glue \penalty-30
       \else \vskip-\skip@ \penalty-30 \vskip\skip@
    \fi\fi\fi
    \penalty\z@
%    \end{macrocode}
% Give a stretchy breakpoint that will always be taken in preference
% to the \cs{penalty} 9999 used to update page parameters.  The cube root
% of 10000/100 indicates a multiplier of 0.21545, but the maximum 
% calculated badness is really 8192, not 10000, so the multiplier
% is 0.2301. 
%    \begin{macrocode}
    \advance\skip@ \z@ plus-.5\baselineskip
    \advance\skip@ \z@ plus-.231\height
    \advance\skip@ \z@ plus-.231\skip@
    \advance\skip@ \z@ plus-.231\topsep
    \vskip-\skip@ \penalty 1800 \vskip\skip@
 \fi
 \addvspace{\topsep}%
 \endgroup
%    \end{macrocode}
% clear out pending page break
%    \begin{macrocode}
 \penalty\@M \vskip 2\baselineskip \vskip\height
 \penalty9999 \vskip -2\baselineskip \vskip-\height
 \penalty9999 % updates \pagetotal
|\message{After clearout, \pagetotal=\the\pagetotal, 
|         \pagegoal=\the\pagegoal. }%
 \fb@adjheight 
 \setbox\@tempboxa\vbox\bgroup
   #1% Modifications to \hsize (can use \width and \height)
   \textwidth\hsize \columnwidth\hsize}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\endMakeFramed}
%    \begin{macrocode}
\def\endMakeFramed{\par
     \kern\z@
     \hrule\@width\hsize\@height\z@
     \penalty-100 % put depth into height
 \egroup
  % {\showoutput\showbox\@tempboxa}%
 \begingroup 
   \fb@put@frame\FrameCommand\FirstFrameCommand
 \endgroup}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\fb@put@frame}
% \cs{fb@put@frame}\marg{nosplit}\marg{split} 
% takes the contents of \cs{@tempboxa} and puts all, 
% or a piece,
% of it on the page with a frame (\cs{FrameCommand}, \cs{FirstFrameCommand},
% \cs{MidFrameCommand}, or \cs{LastFrameCommand}).  It recurses until all of 
% \cs{@tempboxa} has been used up. (\cs{@tempboxa} must have zero depth.) \\
% \meta{nosplit} = attempted framing command, if no split \\
% \meta{split} = framing command if split.
%
% First iteration: Try to fit with \cs{FrameCommand}. If it does not fit,
% split for \cs{FirstFrameCommand}.
%
% Later iteration: Try to fit with \cs{LastFrameCommand}. If it does not
% fit, split for \cs{MidFrameCommand}.
%    \begin{macrocode}
\def\fb@put@frame#1#2{\relax
 \ifdim\pagegoal=\maxdimen \pagegoal\vsize \fi
 \ifinner
   \fb@putboxa#1%
   \fb@afterframe
 \else
  \dimen@\pagegoal \advance\dimen@-\pagetotal % natural space left on page
  \ifdim\dimen@<2\baselineskip % Too little room on page
|   \message{Page has only \the\dimen@\space room left; eject. }%
    \eject \fb@adjheight \fb@put@frame#1#2%
  \else % there's appreciable room left on the page
     \fb@sizeofframe#1%
|    \message{\string\pagetotal=\the\pagetotal,
|        \string\pagegoal=\the\pagegoal,
|        \string\pagestretch=\the\pagestretch,
|        \string\pageshrink=\the\pageshrink,
|        \string\fb@frh=\fb@frh. \space}
|    \message{Box of size \the\ht\@tempboxa\space + \fb@frh}%
     \begingroup % temporarily set \dimen@ to be...
     \advance\dimen@.8\pageshrink  % maximum space available on page
     \advance\dimen@-\fb@frh\relax % space available for frame's contents
     \expandafter\endgroup
%    \end{macrocode}
% expand \cs{ifdim}, then restore \cs{dimen@} to real room left on page
%    \begin{macrocode}
     \ifdim\dimen@>\ht\@tempboxa % whole box does fit
|       \message{fits in \the\dimen@. }%
%    \end{macrocode}
% Use vsplit anyway to capture the marks \\
% !!!???!!! MERGE THIS WITH THE else CLAUSE!!!
%    \begin{macrocode}
        \fb@putboxa#1%
        \fb@afterframe
     \else % box must be split
|       \message{must be split to fit in \the\dimen@. }%
%    \end{macrocode}
% update frame measurement to use \cs{FirstFrameCommand} 
% or \cs{MidFrameCommand}
%    \begin{macrocode}
        \fb@sizeofframe#2%
        \setbox\@tempboxa\vbox{% simulate frame and flexiblity of the page:
           \vskip \fb@frh \@plus\pagestretch \@minus.8\pageshrink
           \kern137sp\kern-137sp\penalty-30
           \unvbox\@tempboxa}%
        \edef\fb@resto@set{\boxmaxdepth\the\boxmaxdepth 
                           \splittopskip\the\splittopskip}%
        \boxmaxdepth\z@ \splittopskip\z@
|       \message{Padded box of size \the\ht\@tempboxa\space split 
|                to \the\dimen@}%
%    \end{macrocode}
% Split box here
%    \begin{macrocode}
        \setbox\tw@\vsplit\@tempboxa to\dimen@
|       \toks99\expandafter{\splitfirstmark}%
|       \toks98\expandafter{\splitbotmark}%
|       \message{Marks are: \the\toks99, \the\toks98. }%
        \setbox\tw@\vbox{\unvbox\tw@}% natural-sized
|       \message{Natural height of split box is \the\ht\tw@, leaving 
|          \the\ht\@tempboxa\space remainder. }%
%    \end{macrocode}
% If the split-to size $>$ (\cs{vsize}-\cs{topskip}), then set box to full size
%    \begin{macrocode}
        \begingroup
        \advance\dimen@\topskip
        \expandafter\endgroup
        \ifdim\dimen@>\pagegoal
|         \message{Frame is big -- Use up the full column. }%
          \dimen@ii\pagegoal
          \advance\dimen@ii -\topskip
          \advance\dimen@ii \FrameHeightAdjust\relax
        \else  % suspect this is wrong:
%    \end{macrocode}
% If the split-to size $>$ feasible room-on-page, rebox it smaller.
%    \begin{macrocode}
          \advance\dimen@.8\pageshrink
          \ifdim\ht\tw@>\dimen@
|           \message{Box too tall; rebox it to \the\dimen@. }%
            \dimen@ii\dimen@
          \else % use natural size
            \dimen@ii\ht\tw@
          \fi
        \fi
%    \end{macrocode}
% Re-box contents to desired size \cs{dimen@ii}
%    \begin{macrocode}
        \advance\dimen@ii -\fb@frh
        \setbox\tw@\vbox to\dimen@ii \bgroup
%    \end{macrocode}
% remove simulated frame and page flexibility:
%    \begin{macrocode}
        \vskip -\fb@frh \@plus-\pagestretch \@minus-.8\pageshrink
        \unvbox\tw@ \unpenalty\unpenalty
        \ifdim\lastkern=-137sp % whole box went to next page
|          \message{box split at beginning! }%
           % need work here???
           \egroup \fb@resto@set \eject % (\vskip for frame size was discarded) 
           \fb@adjheight
           \fb@put@frame#1#2% INSERTED ???
        \else % Got material split off at the head
           \egroup \fb@resto@set
           \ifvoid\@tempboxa % it all fit after all
|             \message{box split at end! }%
              \setbox\@tempboxa\box\tw@
              \fb@putboxa#1%
              \fb@afterframe
           \else % it really did split
|             \message{box split as expected. Its reboxed height 
|                      is \the\ht\tw@. }%
              \ifdim\wd\tw@>\z@
                \wd\tw@\wd\@tempboxa
%    \end{macrocode}
% PW: the next line was: \\
% \verb!\centerline{#2{\box\tw@}}%  ??? \centerline bad idea?! \\
% but I have changed it as follows so that \cs{centerline} can be changed
% from elsewhere if useful.
%    \begin{macrocode}
                \memfblineboxtwo{#2{\box\tw@}}%  ??? \centerline bad idea? \\
              \else
|               \message{Zero width means likely blank. 
|                        Don't frame it (guess)}%
                \box\tw@
              \fi
              \hrule \@height\z@ \@width\hsize
              \eject
              \fb@adjheight
              \fb@put@frame\LastFrameCommand\MidFrameCommand
  \fi\fi\fi\fi\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\memfblineboxtwo}
% \begin{macro}{\memfblineboxa}
% PW: this is an addition of mine. There is a question mark against the
% use of \cs{centerline} within the \Lenv{framed} code. I have
% created these two macros which are used in the code instead of 
% \cs{centerline}, so that those parts of the code can be easily altered.
% are used instead
%    \begin{macrocode}
\newcommand{\memfblineboxtwo}[1]{\centerline{#1}}
\newcommand{\memfblineboxa}[1]{\centerline{#1}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\fb@putboxa}
%    \begin{macrocode}
\def\fb@putboxa#1{%
  \ifvoid\@tempboxa
%%%%    PackageWarning{framed}{Boxa is void -- discard it. }% 
    \@memwarn{Boxa is void -- discard it. }%
  \else
|   \message{Frame and place boxa. }%
|   %{\showoutput\showbox\@tempboxa}%
%%%%%%%    \centerline{#1{\box\@tempboxa}}%
    \memfblineboxa{#1{\box\@tempboxa}}%
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\fb@afterframe}
%    \begin{macrocode}
\def\fb@afterframe{%
    \nointerlineskip \null %{\showoutput \showlists}
    \penalty-30 \vskip\topsep \relax}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\fb@frw}
% \begin{macro}{\fb@frh}
% \begin{macro}{\fb@sizeofframe}
% \cs{fb@sizeofframe}\marg{framecommand} measures width and height added by 
% frame (\meta{framecommand}) and call the results \cs{fb@frw} and \cs{fb@frh}.
%    \begin{macrocode}
\newdimen\fb@frw
\newdimen\fb@frh
\def\fb@sizeofframe#1{\begingroup
 \setbox\z@\vbox{\vskip-5in \hbox{\hskip-5in 
   #1{\hbox{\vrule \@height 4.7in \@depth.3in \@width 5in}}}%
   \vskip\z@skip}%
|  \message{Measuring frame addition for \string#1 in \@currenvir\space 
|    gives ht \the\ht\z@\space and wd \the\wd\z@. }%
%{\showoutput\showbox\z@}%
 \global\fb@frw\wd\z@ \global\fb@frh\ht\z@
 \endgroup}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\fb@adjheight}
%    \begin{macrocode}
\def\fb@adjheight{%
  \vbox to\FrameHeightAdjust{}% get proper baseline skip from above.
  \penalty\@M \nointerlineskip
  \vskip-\FrameHeightAdjust
  \penalty\@M} % useful for tops of pages

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\zero@glue}
%    \begin{macrocode}
\edef\zero@glue{\the\z@skip}

\catcode`\|=\FrameRestore

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\FrameCommand}
% \begin{macro}{\FrameRule}
% \begin{macro}{\FrameSep}
% \begin{macro}{\FirstFrameCommand}
% \begin{macro}{\MidFrameCommand}
% \begin{macro}{\LastFrameCommand}
% Provide configuration commands:
%    \begin{macrocode}
\providecommand\FrameCommand{%
 \setlength\fboxrule{\FrameRule}\setlength\fboxsep{\FrameSep}%
 \fbox}
\@ifundefined{FrameRule}{\newdimen\FrameRule \FrameRule=\fboxrule}{}
\@ifundefined{FrameSep} {\newdimen\FrameSep  \FrameSep =3\fboxsep}{}
\providecommand\FirstFrameCommand{\FrameCommand}
\providecommand\MidFrameCommand{\FrameCommand}
\providecommand\LastFrameCommand{\FrameCommand}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\FrameHeightAdjust}
% Height of frame above first baseline when frame starts a page:
%    \begin{macrocode}
\providecommand\FrameHeightAdjust{6pt}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\FrameRestore}
% \cs{FrameRestore} has parts of \cs{@parboxrestore}, performing a similar but 
% less complete restoration of a default layout.  See how it is used in the 
% "settings" argument of \cs{MakeFrame}.  Though not a parameter, \cs{hsize} 
% should be set to the desired total line width available inside the
% frame before invoking \cs{FrameRestore}.  
%    \begin{macrocode}
\def\FrameRestore{%
   \let\if@nobreak\iffalse
   \let\if@noskipsec\iffalse
   \let\-\@dischyph
   \let\'\@acci\let\`\@accii\let\=\@acciii
   %  \message{FrameRestore:
   %    \@totalleftmargin=\the \@totalleftmargin,
   %    \rightmargin=\the\rightmargin, 
   %    \@listdepth=\the\@listdepth.  }%
%    \end{macrocode}
%  Test if we are in a list (or list-like paragraph)
%    \begin{macrocode}
   \ifnum \ifdim\@totalleftmargin>\z@ 1\fi  
          \ifdim\rightmargin>\z@ 1\fi
          \ifnum\@listdepth>0 1\fi 0>\z@
     %     \message{In a list: \linewidth=\the\linewidth, 
     %       \@totalleftmargin=\the\@totalleftmargin,
     %       \parshape=\the\parshape, \columnwidth=\the\columnwidth, 
     %       \hsize=\the\hsize, 
     %       \labelwidth=\the\labelwidth. }%
%    \end{macrocode}
% Now try to propagate changes of width from \cs{hsize} to list parameters.
% This is deficient, but a more advanced way to indicate modification to text 
% dimensions is not (yet) provided; in particular, no separate left/right
% adjustment. (PW. I have provided a macro for the next few lines as I think
% that I may have a reason to allow them to be easily changed).
%    \begin{macrocode}  
%%%     \@setminipage % snug fit around the item
%%%     \advance\linewidth-\columnwidth \advance\linewidth\hsize
%%%     \parshape\@ne \@totalleftmargin \linewidth
     \memfblistfixparams
   \else % Not in list
     \linewidth=\hsize
     %\message{No list, set \string\linewidth=\the\hsize. }%
   \fi
   \sloppy}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\memfblistfixparams}
% An extract of some code from \cs{FrameRestore}.
% Try to propagate changes of width from \cs{hsize} to list parameters.
% This is deficient, but a more advanced way to indicate modification to text 
% dimensions is not (yet) provided; in particular, no separate left/right
% adjustment. 
%    \begin{macrocode}
\newcommand*{\memfblistfixparams}{%
  \@setminipage % snug fit around the item
  \advance\linewidth-\columnwidth \advance\linewidth\hsize
  \parshape\@ne \@totalleftmargin \linewidth}

%    \end{macrocode}
% \end{macro}
%
%    I have moved the following from the start of the \Lpack{framed}
% package to here. 
%
% \begin{environment}{framed}
% \begin{environment}{shaded}
% \begin{environment}{leftbar}
% \begin{environment}{snugshade}
%    \begin{macrocode}
\newenvironment{framed}% using default \FrameCommand
  {\MakeFramed {\advance\hsize-\width \FrameRestore}}%
  {\endMakeFramed}

\newenvironment{shaded}{%
  \def\FrameCommand{\fboxsep=\FrameSep \colorbox{shadecolor}}%
  \MakeFramed {\FrameRestore}}%
  {\endMakeFramed}

\newenvironment{leftbar}{%
  \def\FrameCommand{\vrule width 3pt \hspace{10pt}}%
  \MakeFramed {\advance\hsize-\width \FrameRestore}}%
 {\endMakeFramed}

\newenvironment{snugshade}{%
  \def\FrameCommand{\colorbox{shadecolor}}%
  \MakeFramed {\FrameRestore\@setminipage}}%
 {\par\unskip\endMakeFramed}

%    \end{macrocode}
% \end{environment}
% \end{environment}
% \end{environment}
% \end{environment}
%
% As the package used \cs{newenvironment} it will
% burp if it is used with the class. There are two options: either
% prevent \Lpack{framed} from being loaded, or kill the environments
% if it is loaded. I'm going for the latter as Donald will be updating
% his package at some point and author's may want to use it before it's
% updated here.
%
%    \begin{macrocode}
\AtBeginPackage{framed}{%
  \let\framed\relax \let\endframed\relax
  \let\shaded\relax \let\endshaded\relax
  \let\leftbar\relax \let\endleftbar\relax
  \let\snugshade\relax \let\endsnugshade\relax}

%    \end{macrocode}
%
%
% \begin{environment}{qframe}
% This is from an email to me from DA shortly after he released \Lpack{framed}
% v 0.95.
% \begin{quote}
% A frame more like a simple parbox. 
% Notably useful for use
% inside a single list item --- the frame matches the text of the other
% items. 
% \end{quote}
% He actually called it \Lenv{pframe} and said that something similar
% could be in a later version of \Lpack{framed}.
%
% I have found it useful for framing \Lenv{quote} or \Lenv{adjustwidth}
% environments, or similar. Hence the name, from 
% `\textit{q}uote \textit{frame}'.
% \changes{v1.61803}{2008/01/30}{Added the qframe environment}
%    \begin{macrocode}
\newenvironment{qframe}{%
  \def\FrameCommand##1{\fboxrule=\FrameRule\fboxsep=\FrameSep
    \hskip\@totalleftmargin\fbox{##1}% There is no \@totalrightmargin, so...
      \hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
  \MakeFramed{\advance\hsize-\width 
              \advance\hsize \FrameSep
              \@totalleftmargin\z@ \linewidth=\hsize}}%
 {\endMakeFramed}

%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{qshade}
% And here is my corresponding version for \Lenv{shaded}.
% \changes{v1.61803}{2008/01/30}{Added the qshade environment}
%    \begin{macrocode}
\newenvironment{qshade}{%
  \def\FrameCommand##1{\fboxsep=\FrameSep
    \hskip\@totalleftmargin
    \hskip -1\FrameSep
    \colorbox{shadecolor}{##1}% 
      \hskip-\linewidth \hskip-\@totalleftmargin 
      \hskip -1\FrameSep
      \hskip\columnwidth}%
  \MakeFramed{\advance\hsize-\width 
              \advance\hsize 3\FrameSep
              \@totalleftmargin\z@ \linewidth=\hsize}}%
 {\endMakeFramed}

%    \end{macrocode}
% \end{environment}
%
%
% \subsection{The newfile package}
%
% The following code is from the \Lpack{newfile} package.
% To try and avoid name clashes with other packages, each internal macro
% in this package includes the character string `\verb?stre@m?'.
%
% \begin{macro}{\newoutputstream}
% \cs{newoutputstream}\marg{stream} creates a new output stream called \meta{stream}.
% Different files may be associated with the \meta{stream}. Note that
% TeX permits no more than 16 output streams.
%    \begin{macrocode}
\newcommand*{\newoutputstream}[1]{%
  \@ifundefined{#1outstre@m}%
    {\expandafter\newwrite\csname #1outstre@m\endcsname
     \csname newif\expandafter\endcsname
       \csname ifstre@m#1open\endcsname
     \global\csname stre@m#1openfalse\endcsname
     \expandafter\ifx\csname atstreamopen#1\endcsname\relax
       \global\@namedef{atstreamopen#1}{}%
     \fi
     \expandafter\ifx\csname atstreamclose#1\endcsname\relax
       \global\@namedef{atstreamclose#1}{}%
     \fi
    }%
    {\@memwarn{Output stream #1\space is already defined}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\newinputstream}
% \cs{newinputstream}\marg{stream} creates a new input stream called \meta{stream}.
% Different files may be associated with the \meta{stream}. Note that
% TeX permits no more than 16 input streams.
%    \begin{macrocode}
\newcommand*{\newinputstream}[1]{%
  \@ifundefined{#1instre@m}%
    {\expandafter\newread\csname #1instre@m\endcsname
     \csname newif\expandafter\endcsname
       \csname ifstre@m#1open\endcsname
     \global\csname stre@m#1openfalse\endcsname
     \expandafter\ifx\csname atstreamopen#1\endcsname\relax
       \global\@namedef{atstreamopen#1}{}%
     \fi
     \expandafter\ifx\csname atstreamclose#1\endcsname\relax
       \global\@namedef{atstreamclose#1}{}%
     \fi
    }%
    {\@memwarn{Input stream #1\space is already defined}}}

%    \end{macrocode}
% \end{macro}
%
%    Some checking macros will be useful as some of the checks occur in
% multiple places.
%
% \begin{macro}{\IfStreamOpen}
% \cs{IfStreamOpen}\marg{stream}\marg{TRUE code}\marg{FALSE code}
% checks if stream \meta{stream} is currently open.
%    \begin{macrocode}
\newcommand{\IfStreamOpen}[3]{%
  \csname ifstre@m#1open\endcsname#2\else#3\fi}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\instre@mandopen}
% \cs{instre@mandopen}\marg{stream}\marg{TRUE code} checks if \meta{stream}
% is an input stream and is open. If so, it executes \meta{TRUE code}.
%    \begin{macrocode}
\newcommand{\instre@mandopen}[2]{%
  \@ifundefined{#1instre@m}{%
    \@memwarn{#1\space is not an input stream}}%
  {\IfStreamOpen{#1}{#2}{%
    \@memwarn{Input stream #1\space is not open}}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\instre@mandclosed}
% \cs{instre@mandclosed}\marg{stream}\marg{TRUE code} checks if \meta{stream}
% is an input stream and is closed (not open). 
% If so, it executes \meta{TRUE code}.
%    \begin{macrocode}
\newcommand{\instre@mandclosed}[2]{%
  \@ifundefined{#1instre@m}{%
    \@memwarn{#1\space is not an input stream}}%
  {\IfStreamOpen{#1}{%
    \@memwarn{Input stream #1\space is open}}{#2}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\outstre@mandopen}
% \cs{outstre@mandopen}\marg{stream}\marg{TRUE code} checks if \meta{stream}
% is an output stream and is open. If so, it executes \meta{TRUE code}.
%    \begin{macrocode}
\newcommand{\outstre@mandopen}[2]{%
  \@ifundefined{#1outstre@m}{%
    \@memwarn{#1\space is not an output stream}}%
  {\IfStreamOpen{#1}{#2}{%
    \@memwarn{Output stream #1\space is not open}}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\outstre@mandclosed}
% \cs{outstre@mandclosed}\marg{stream}\marg{TRUE code} checks if \meta{stream}
% is an output stream and is closed (not open). 
% If so, it executes \meta{TRUE code}.
%    \begin{macrocode}
\newcommand{\outstre@mandclosed}[2]{%
  \@ifundefined{#1outstre@m}{%
    \@memwarn{#1\space is not an output stream}}%
  {\IfStreamOpen{#1}{%
    \@memwarn{Output stream #1\space is open}}{#2}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\openoutputfile}
% \cs{openoutputfile}\marg{filename}\marg{stream} opens the file called 
% \meta{filename} and attaches it to the stream \meta{stream} for
% writing. However, if the \cs{nofiles} command has been given the
% file is \emph{not} attached to the stream. No more than one file can be 
% attached to a stream at any given time.
%    \begin{macrocode}
\newcommand*{\openoutputfile}[2]{%
  \outstre@mandclosed{#2}{%
    \global\@namedef{#1@filename}{#1}%
    \if@filesw 
      \immediate\openout\@nameuse{#2outstre@m}=\@nameuse{#1@filename}%
    \fi
    \global\csname stre@m#2opentrue\endcsname%
    \@nameuse{atstreamopen#2}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\closeoutputstream}
% \cs{closeoutputstream}\marg{stream} closes the stream \meta{stream}.
%    \begin{macrocode}
\newcommand*{\closeoutputstream}[1]{%
  \outstre@mandopen{#1}{%
    \@nameuse{atstreamclose#1}%
    \immediate\closeout\@nameuse{#1outstre@m}%
    \global\csname stre@m#1openfalse\endcsname}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\openinputfile}
% \cs{openinputfile}\marg{filename}\marg{stream} opens the file called 
% \meta{filename} and attaches it to the stream \meta{stream} for
% reading. The file is added to the list of files. 
% No more than one file can be attached to a stream at
% any given time.
%    \begin{macrocode}
\newcommand{\openinputfile}[2]{%
  \IfFileExists{#1}{%                   file exists
    \instre@mandclosed{#2}{% 
      \@addtofilelist{#1}%
      \global\@namedef{#1@filename}{#1}%
      \immediate\openin\@nameuse{#2instre@m}=\@nameuse{#1@filename}%
      \global\csname stre@m#2opentrue\endcsname%
      \@nameuse{atstreamopen#2}}}%
  {%                                    file not found
    \typeout{No file #1.}
  }}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\closeinputstream}
% \cs{closeinputstream}\marg{stream} closes the stream \meta{stream}.
%    \begin{macrocode}
\newcommand{\closeinputstream}[1]{%
  \instre@mandopen{#1}{%
     \@nameuse{atstreamclose#1}%
     \immediate\closein\@nameuse{#1instre@m}%
     \global\csname stre@m#1openfalse\endcsname}}

%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{writeverbatim}
% \verb?\begin{writeverbatim}?\marg{stream} writes the contents of
% the environment as verbatim text to the given \meta{stream}.
%    \begin{macrocode}
\def\writeverbatim#1{%
  \@bsphack
  \let\do\@makeother\dospecials
  \catcode`\^^M\active
  \def\verbatim@processline{%
    \immediate\write\@nameuse{#1outstre@m}{\the\verbatim@line}}%
  \verbatim@start}
\def\endwriteverbatim{\@esphack}

%    \end{macrocode}
% \end{environment}
%
% \begin{macro}{\addtostream}
% \cs{addtostream}\marg{stream}\marg{text} writes \meta{text} to the
% given \meta{stream}.
%    \begin{macrocode}
\newcommand{\addtostream}[2]{%
  \@bsphack
  \outstre@mandopen{#1}{%
    {\let\protect\string
     \immediate\write\@nameuse{#1outstre@m}{#2}%
    }}%
  \@esphack}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifstre@mnoteof}
% \begin{macro}{\checkstre@mnoteof}
% \cs{checkstre@mnoteof}\marg{stream} sets \cs{ifstre@mnoteof} to TRUE if
% \meta{stream} is not at the end of the file (i.e., it is the opposite
% of \cs{ifeof}).
%    \begin{macrocode}
\newif\ifstre@mnoteof
\newcommand{\checkstre@meof}[1]{%
  \stre@mnoteoftrue\ifeof\@nameuse{#1instre@m}\stre@mnoteoffalse\fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\readstream}
% \cs{readstream}\marg{stream} reads the contents of
% the given \meta{stream} as \cs{input} text.
%    \begin{macrocode}
\def\readstream#1{
  \instre@mandopen{#1}{%
    \loop \checkstre@meof{#1} \ifstre@mnoteof
      \read\@nameuse{#1instre@m} to\temptokstre@m
     \temptokstre@m
    \repeat
    }}
  
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\readaline}
% \cs{readaline}\marg{stream} reads what TeX considers to be one line
% from the given \meta{stream} as \cs{input} text.
%    \begin{macrocode}
\def\readaline#1{
  \instre@mandopen{#1}{%
    \ifeof\@nameuse{#1instre@m}
      \@memwarn{No more to read from stream #1}
    \else
      \read\@nameuse{#1instre@m} to\temptokstre@m
      \temptokstre@m
    \fi}}
  
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\readverbatim}
% \cs{readverbatim}\marg{stream} reads the contents of
% the given \meta{stream} as verbatim text.
%
% The read verbatim code is a slight variation on code from the
% \Lpack{verbatim} package. Most of the setup is done by the macros
% \cs{stre@mverb@input}\marg{setup}\marg{stream} and
% \cs{verbatim@readstre@m}\marg{stream}. Finally, \cs{verbatim@read@file}
% is a \Lpack{verbatim} package macro.
%    \begin{macrocode}
\def\readverbatim{\begingroup
  \ift@bs
    \def\verbatim@processline{\tabverbatim@processline}%
  \fi
  \@ifstar{\stre@mverb@input{\@maybeobeytabs}}%
     {\stre@mverb@input{\frenchspacing\@vobeyspaces\@maybeobeytabs}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\stre@mverb@input}
% \begin{macro}{\@verbinstre@m}
% \cs{stre@mverb@input}\marg{setup}\marg{stream} is a stream
% version of \cs{verbatim@input}. It defines \cs{@verbinstre@m}
% to be \meta{stream}.
%
%    \begin{macrocode}
\newcommand{\stre@mverb@input}[2]{%
  \IfStreamOpen{#2}%
    {\@verbatim #1\relax
     \def\@verbinstre@m{\@nameuse{#2instre@m}}
     \verb@readstre@m\endtrivlist\endgroup\@doendpe}%
    {\@memwarn{Stream #2\space is not open}\endgroup}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\verb@readstre@m}
% \cs{verb@readstre@m} is the stream analogue to \cs{verbatim@readfile}.
%    \begin{macrocode}
\newcommand{\verb@readstre@m}{%
  \verbatim@startline
  \expandafter\endlinechar\expandafter\m@ne
  \expandafter\verbatim@read@stre@m
  \expandafter\endlinechar\the\endlinechar\relax
  \verbatim@finish}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\verbatim@read@stre@m}
% \cs{verbatim@read@stre@m} is the analogue to \cs{verbatim@readfile}.
% It gets its input from the stream \cs{@verbinstre@m}, which is defined
% in the \cs{stre@mverb@input} macro.
%    \begin{macrocode}
\newcommand{\verbatim@read@stre@m}{%
  \read\@verbinstre@m to\next
  \ifeof\@verbinstre@m
  \else
    \expandafter\verbatim@addtoline\expandafter{\next}%
    \verbatim@processline
    \verbatim@startline
    \expandafter\verbatim@read@stre@m
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\readboxedverbatim}
% \cs{readboxedverbatim}\marg{stream} is the equivalent of
% \cs{readverbtim} except that it generates a boxed verbatim.
%    \begin{macrocode}
\newcommand{\readboxedverbatim}{\begingroup
  \@ifstar{\stre@mbvin\relax}%
          {\stre@mbvin{\frenchspacing\@vobeyspaces}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\stre@mbvin}
% \cs{stre@mbvin}\marg{setup}\marg{stream} is the workhorse for
% \cs{readboxedverbatim}, and in its turn it uses \cs{verb@readstre@m}.
%    \begin{macrocode}
\newcommand{\stre@mbvin}[2]{%
  \IfStreamOpen{#2}%
    {\setupboxverb@line
     \@verbatim #1\relax
     \def\@verbinstre@m{\@nameuse{#2instre@m}}%
     \setupbox@verb
     \verb@readstre@m\bvendrulehook\endtrivlist\endgroup\@doendpe}%
    {\@memwarn{Stream #2\space is not open}\endgroup}}

%    \end{macrocode}
% \end{macro}
%
%
%
% \section{Utilities}
%
%
% \subsection{Extra `provide' commands}
%
% \begin{macro}{\provideenvironment}
% Works like \cs{providecommand} but for environments.
% \changes{v1.2}{2002/08/04}{Added \cs{provideenvironment} and supports}
%    \begin{macrocode}
\newcommand{\provideenvironment}{\@star@or@long\m@mprovenv}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mprovenv}
% This checks if the environment has been defined. If not it calls
% the kernel code for \cs{newenvironment} otherwise it calls code to
% discard arguments.
%    \begin{macrocode}
\newcommand{\m@mprovenv}[1]{\@ifundefined{#1}%
  {\new@environment{#1}}%       % create new environment
  {\@memwarn{Environment `#1' already defined}%
   \m@mgobbleoptsandtwo}}
%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\m@mgobbleoptsandtwo}
% \begin{macro}{\m@mgobbleoptandtwo}
% \cs{m@mgobbleoptsandtwo} gobbles the \verb?[opt][opt]{begin}{end}? arguments to 
% \cs{provideenvironment}. It is actually more general than that as it will 
% gobble any sequence of any number of optional arguments followed by
% two required arguments. If there are no optional arguments it disposes
% of the two required ones, otherwise it calls a recursive procedure to
% discard any number of optionals, then two required ones.
%
% \cs{m@mgobbleoptandtwo} recursively discards optional arguments, then finally
% two required arguments.
%    \begin{macrocode}
\newcommand{\m@mgobbleoptsandtwo}{%
  \@ifnextchar [{\m@mgobbleoptandtwo}{\@gobbletwo}}
\def\m@mgobbleoptandtwo[#1]{%
  \@ifnextchar [{\m@mgobbleoptandtwo}{\@gobbletwo}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\providecounter}
% Works like the other \cs{provide...} commands, but for counters.
% Code is based on \cs{newcounter} in \file{ltcounts.dtx}.
% \changes{v1.2}{2002/07/17}{Added \cs{providecounter}}
%    \begin{macrocode}
\newcommand*{\providecounter}[1]{%
  \@ifundefined{c@#1}%
    {\newcounter{#1}}%
    {\@memwarn{Counter `#1' already defined}%
      \@ifnextchar[{\m@mgobbleopt}{}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mgobbleopt}
% Gobble an optional argument.
% \changes{v1.2}{2002/07/07}{Added \cs{m@mgobbleopt}}
%    \begin{macrocode}
\def\m@mgobbleopt[#1]{}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\providelength}
% Works like the other \cs{provide...} commands, but for lengths.
% Code is based on \cs{provide@command} in \file{ltdefns.dtx}.
% \changes{v1.2}{2002/07/17}{Added \cs{providelength}}
%    \begin{macrocode}
\newcommand*{\providelength}[1]{%
  \begingroup
    \escapechar\m@ne\xdef\@gtempa{{\string#1}}%
  \endgroup
  \expandafter\@ifundefined\@gtempa
    {\newlength{#1}}%
    {\@memwarn{Length #1 already defined}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\newloglike}
% \begin{macro}{\m@mnewlog}
% \begin{macro}{\m@mnewlogs}
% For defining a new log-like math function.
% \verb?\newloglike{\fun}{string}? or \verb?\newloglike*{\fun}{string}?.
% The starred version is for functions with limits (like an integral sign).
% \changes{v1.6}{2004/01/28}{Added \cs{newloglike}}
%    \begin{macrocode}
\newcommand*{\newloglike}{\@ifstar{\m@mnewlogs}{\m@mnewlog}}
\newcommand*{\m@mnewlogs}[2]{%
  \newcommand*{#1}{\mathop{\operator@font #2}}}
\newcommand*{\m@mnewlog}[2]{%
  \newcommand*{#1}{\mathop{\operator@font #2}\nolimits}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% 
% \begin{macro}{\provideloglike}
% \begin{macro}{\m@mprovlogs}
% \begin{macro}{\m@mprovlog}
%  The provide version of \cs{newloglike}.
% \changes{v1.6}{2004/01/28}{Added \cs{provideloglike}}
%    \begin{macrocode}
\newcommand*{\provideloglike}{\@ifstar{\m@mprovlogs}{\m@mprovlog}}
\newcommand*{\m@mprovlogs}[2]{%
  \providecommand*{#1}{\mathop{\operator@font #2}}}
\newcommand*{\m@mprovlog}[2]{%
  \providecommand*{#1}{\mathop{\operator@font #2}\nolimits}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% 
%
% \subsection{Changing counters}
%
%     In LaTeX, a new counter called, say `ctr', is created by the command
% \verb?\newcounter{ctr}[within]?. If the optional within argument is given
% the the counter `ctr' is reset to zero each time the counter `within'
% changes. The command \cs{thectr} typesets the value of the counter ctr.
% This is automatically defined by \cs{newcounter} and is initialised
% to typeset arabic numerals. Sometimes it may be desireable to change
% the counter definitions.
%
% The following code is based on the \Lpack{chngcntr} package~\cite{CHNGCNTR}.
%
% \begin{macro}{\@removefromreset}
% This code uses David Carlisle's \cs{@removefromreset} command as
% specified in the remreset package~\cite{REMRESET}.
% It is provided here as a convenience to the user, and with
% David Carlisle's permission.
%
% START OF DAVID CARLISLE'S CODE
%    \begin{macrocode}
\providecommand{\@removefromreset}[2]{{%
  \expandafter\let\csname c@#1\endcsname\@removefromreset
  \def\@elt##1{%
    \expandafter\ifx\csname c@##1\endcsname\@removefromreset
    \else
      \noexpand\@elt{##1}%
    \fi}%
  \expandafter\xdef\csname cl@#2\endcsname{%
    \csname cl@#2\endcsname}}}

%    \end{macrocode}
% END OF DAVID CARLISLE'S CODE
% \end{macro}
%
% \begin{macro}{\@ifbothcntrs}
% This is called as \\
% \cs{@ifbothcntrs}\marg{cntr}\marg{within}\marg{code when both are counters}. 
% This tests if both \meta{cntr} and \meta{within} are counters.
%    \begin{macrocode} 
\newcommand{\@ifbothcntrs}[3]{%
  \@ifundefined{c@#1}{% counter undefined
    \@memerror{#1 is not a counter}{\@eha}}%
  {% else counter is defined
    \@ifundefined{c@#2}{% within undefined
      \@memerror{#2 is not a counter}{\@eha}}%
    {% else both counter and within  are defined
     #3}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\counterwithin}
% \begin{macro}{\counterwithin*}
% \begin{macro}{\@csinstar}
% \begin{macro}{\@csin}
%    It is sometimes desireable to change a counter that has been defined
% by \verb?\newcounter{ctr}? to act as though it had been defined as 
% \verb?\newcounter{ctr}[within]?. The command
% \verb?\counterwithin{ctr}{within}? accomplishes this. By default,
% it also redefines the \cs{thectr} command so that it typesets values
% in the style \verb?\thewithin.\arabic{ctr}?. The starred version of the
% command suppresses the redefinition of \cs{thectr}. 
% \changes{v3.7g}{2018/03/09}{As of TeXLive 2018 \cs{counterwithin}
% and \cs{counterwithout} will be moved into the kernel. We therefore
% change to using \cs{providecommand} instead of \cs{newcommand} to
% avoid colisions}
%    \begin{macrocode}
\providecommand{\counterwithin}{\@ifstar{\@csinstar}{\@csin}}
\providecommand{\@csinstar}[2]{%
  \@ifbothcntrs{#1}{#2}{\@addtoreset{#1}{#2}}}
\providecommand{\@csin}[2]{%
  \@ifbothcntrs{#1}{#2}{\@addtoreset{#1}{#2}%
                        \@namedef{the#1}{\@nameuse{the#2}.\arabic{#1}}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\counterwithout}
% \begin{macro}{\counterwithout*}
% \begin{macro}{\@csoutstar}
% \begin{macro}{\@csout}
%    Likewise, the command \verb?\counterwithout{ctr}{within}? changes a
% counter that has been created by \verb?\newcounter{ctr}[within]? to act
% as though it had been created by \verb?\newcounter{ctr}?. By default it
% also redefines the \cs{thectr} command so that it just typesets an arabic
% numeral. The starred version of the command suppresses the redefinition
% of \cs{thectr}.
% \changes{v1.618}{2005/09/03}{Deleted chngctr from \cs{@csoutstar} (mempatch v3.4)}
% \changes{v3.7g}{2018/03/09}{As of TeXLive 2018 \cs{counterwithin}
% and \cs{counterwithout} will be moved into the kernel. We therefore
% change to using \cs{providecommand} instead of \cs{newcommand} to
% avoid colisions}
%    \begin{macrocode}
\providecommand{\counterwithout}{\@ifstar{\@csoutstar}{\@csout}}
\providecommand{\@csoutstar}[2]{%
  \@ifbothcntrs{#1}{#2}{\@removefromreset{#1}{#2}}}
\providecommand{\@csout}[2]{%
  \@ifbothcntrs{#1}{#2}{\@removefromreset{#1}{#2}%
                        \@namedef{the#1}{\arabic{#1}}}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%    Any number of \verb?\counterwithin{ctr}{...}? and \verb?\counterwithout{ctr}{...}?
% commands can be issued for a given counter, ctr, if you wish to toggle
% between the two styles. The current value of ctr is unaffected by
% \cs{counterwithin} and \cs{counterwithout}. If you want to change the value
% after one of these commands, use \verb?\setcounter{ctr}{...}?, and to change
% the typeseting style use \verb?\renewcommand{\thectr}{...}?.
%
% 
% \begin{macro}{\letcountercounter}
% \begin{macro}{\c@m@morig@ctr}
% \begin{macro}{\unletcounter}
% At times it is handy to `let' one counter act as if it was a
% different counter. Say you have two constructions, each with their
% own counter A and B, now you want them to cooperate, counting in
% unison. This can be done using the \verb?\letcountercounter?.
%
% \medskip
%
% \cs{letcountercounter}\marg{counterA}\marg{counterB} \cs{let}s 
% (make the same) \meta{counterA} to \meta{counterB}. The
% original of \meta{counterA} is kept in \cs{c@m@morig@ctr}\meta{counterA}.
%
% \cs{unletcounter}\marg{counterA} restores \meta{counterA} to its un\cs{let}
% condition.
%
% The code is based on Donald Arseneau's `Re: \cs{let}, \cs{csname} and 
% \cs{endcsname}', CTT, 2004/12/08. The long version, where \cs{xp}
% is actually \cs{expandafter} is along the lines of:
% \begin{verbatim}
% \xp\xp\xp\let\xp\csname\xp c@#1\xp\endcsname\csname c@#2\endcsname
% \end{verbatim}
% which employs 6 \cs{expandafter}s. DA's version uses only 2. The technique
% can be applied to other kinds of \cs{let}s.
%
%    \begin{macrocode}
\newcommand*{\letcountercounter}[2]{%
  \expandafter\let\csname c@m@morig@ctr#1\expandafter\endcsname%
                   \csname c@#1\endcsname
  \expandafter\let\csname c@#1\expandafter\endcsname%
                  \csname c@#2\endcsname}
\newcommand*{\unletcounter}[1]{%
 \expandafter\let\csname c@#1\expandafter\endcsname%
                 \csname c@m@morig@ctr#1\endcsname}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \subsection{Odd/even page checking}
%
% It is difficult to check robustly if the current page is odd or even.
% This code, which is based on the \Lpack{chngpage} package~\cite{CHNGPAGE}, 
% provides a method that has proved (so far) to be robust.
%    It works by writing out a label and on the next LaTeX run checks
% the page reference for the label.
%
% \begin{macro}{\ifoddpage}
% \begin{macro}{\oddpagetrue}
% \begin{macro}{\oddpagefalse}
% \begin{macro}{\ifstrictpagecheck}
% \begin{macro}{\strictpagechecktrue}
% \begin{macro}{\strictpagecheckfalse}
% \begin{macro}{\strictpagecheck}
% \begin{macro}{\easypagecheck}
% The boolean \cs{ifoddpage} is TRUE if the checked page is odd. The
% boolean \cs{ifstrictpagecheck} is for turning on (TRUE) and off (FALSE)
% the strictest method of page checking. 
% \changes{v1.61803}{2008/01/30}{Added \cs{strictpagecheck} and \cs{easypagecheck}}
%    \begin{macrocode}
\newif\ifoddpage
\newif\ifstrictpagecheck
  \strictpagecheckfalse
\newcommand*{\strictpagecheck}{\strictpagechecktrue}
\newcommand*{\easypagecheck}{\strictpagecheckfalse}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\c@cp@cntr}
% \begin{macro}{\cplabel}
% The counter \verb?cp@cntr? is used to make unique labels, which start 
% with \cs{cplabel}.
%    \begin{macrocode}
\newcounter{cp@cntr}
\newcommand{\cplabel}{^_}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \begin{macro}{\checkoddpage}
% This is the user level command to check for odd/even page. It does
% a robust check for \cs{strictpagecheck} otherwise the simple minded
% check. It sets \cs{ifoddpage} to TRUE if the page is odd, otherwise
% it sets it to FALSE.
%
%    This is now fixed so that it should work for non-arabic page numbering.
% It uses a new label/pageref variant based on the page counter value, not
% its printed representation. This also gets rid of worrying about hyperref!!
% The problem was discovered by Bastiaan Niels Veelo
%
% \changes{v1.4}{2003/11/22}{Complete rewrite of odd page checking 
%                            (from patch v1.6)}
%    \begin{macrocode}
\DeclareRobustCommand{\checkoddpage}{%
  \oddpagefalse%
  \ifstrictpagecheck%
    \stepcounter{cp@cntr}\pmemlabel{\cplabel\thecp@cntr}%
    \@memcnta=\pmemlabelref{\cplabel\thecp@cntr}\relax
    \ifodd\@memcnta\oddpagetrue\fi
  \else
    \ifodd\c@page\oddpagetrue\fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{macro}{\thepmemc@@page}
% The value of the page counter.
%    \begin{macrocode}
\gdef\thepmemc@@page{\the\c@page}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pmemprotected@write}
% \cs{pmemprotected@write} is a modified version of the kernel's
% \cs{protected@write}.
%
%  This version of the macro was provided by Romano Giannetti
% (\url{romano@dea.icai.upco.es}) on 15 July 2003. 
%    \begin{macrocode}
\long\def\pmemprotected@write#1#2#3{%
  \begingroup
  \let\thepmemc@@page\relax
  #2%
  \let\protect\@unexpandable@protect
  \edef\reserved@a{\write#1{#3}}%
  \reserved@a
  \endgroup
  \if@nobreak\ifvmode\nobreak\fi\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\pmemlabel}
% A version of \cs{label} that uses \cs{pmemprotected@write}.
%    \begin{macrocode}
\newcommand{\pmemlabel}[1]{\@bsphack
  \pmemprotected@write\@auxout{}%
    {\string\newpmemlabel{#1}{\thepmemc@@page}}%
  \@esphack}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\newpmemlabel}
% \begin{macro}{\pmemlabelref}
% We have to be able to cope with a particular label
% not (yet) being in the the \file{.aux} file when we come to check 
% the page number.
%    \begin{macrocode}
\newcommand{\newpmemlabel}[2]{{\global\@namedef{m@#1}{#2}}}
\newcommand{\pmemlabelref}[1]{%
  \expandafter\ifx\csname m@#1\endcsname\relax
    0%
  \else
    \csname m@#1\endcsname
  \fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%  \subsection{Checking for empty arguments}
%
%  Like page checking, testing for an empty macro argument is more
% difficult than it might appear at first sight.
%
%    The following code is from the \Lpack{ifmtarg} package~\cite{IFMTARG}.
%
% \begin{macro}{\@ifmtarg}
% \begin{macro}{\@ifnotmtarg}
% \cs{@ifmtarg}\marg{arg}\marg{code when empty}\marg{code when arg not empty} \\
% \cs{@ifnotmtarg}\marg{arg}\marg{code when arg not empty} \\
%    \begin{macrocode}
\begingroup
\catcode`\Q=3
\long\gdef\@ifmtarg#1{\@xifmtarg#1QQ\@secondoftwo\@firstoftwo\@nil}
\long\gdef\@xifmtarg#1#2Q#3#4#5\@nil{#4}
\long\gdef\@ifnotmtarg#1{\@xifmtarg#1QQ\@firstofone\@gobble\@nil}
\endgroup

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%    Some example uses:
% \begin{verbatim}
% \newcommand{\isempty}[1]{%
%    \@ifmtarg{#1}{\typeout{YES}}{\typeout{NO}}}
% \newcommand{\isnotempty}[1]{%
%    \@ifnotmtarg{#1}{\typeout{YES}}}
%
% \isempty{}    -> YES  \isnotempty{}    -> 
% \isempty{   } -> YES  \isnotempty{   } -> 
% \isempty{A}   -> NO   \isnotempty{A}   -> YES 
% \isempty{ A } -> NO   \isnotempty{ A } -> YES 
% \end{verbatim}
%
%
% \subsection{Changing the page layout in the document}
%
%  You should not do this, but\ldots
%
% The following code is essentially from the \Lpack{chngpage} 
% package~\cite{CHNGPAGE}.
%
% \begin{macro}{\ch@ngetext}
% This macro sets the page output parameters.
%    \begin{macrocode}
\DeclareRobustCommand{\ch@ngetext}{%
  \setlength{\@colht}{\textheight}\setlength{\@colroom}{\textheight}%
  \setlength{\vsize}{\textheight}\setlength{\columnwidth}{\textwidth}%
  \if@twocolumn%
    \advance\columnwidth-\columnsep \divide\columnwidth\tw@%
    \@firstcolumntrue%
  \fi%
  \setlength{\hsize}{\columnwidth}%
  \setlength{\linewidth}{\hsize}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\changetext}
% \cs{changetext}\marg{H}\marg{W}\marg{E}\marg{O}\marg{G}
% adds the given lengths to 5 main bits of the page layout. An empty
% argument means `no change'.
%    \begin{macrocode}
\DeclareRobustCommand{\changetext}[5]{%
  \@ifmtarg{#1}{}{\addtolength{\textheight}{#1}}%
  \@ifmtarg{#2}{}{\addtolength{\textwidth}{#2}}%
  \@ifmtarg{#3}{}{\addtolength{\evensidemargin}{#3}}%
  \@ifmtarg{#4}{}{\addtolength{\oddsidemargin}{#4}}%
  \@ifmtarg{#5}{}{\addtolength{\columnsep}{#5}}%
  \ch@ngetext}

%    \end{macrocode}
% \end{macro}
%
% Any given change lasts until another \cs{changetext} command is given.
% A \cs{changetext} command should only be issued between two paragraphs.
%
% \cs{changetext} should not be used by anyone unless they really
% know what they are doing. If you really know what you are doing
% then you should know enough not to use it.
%
% \begin{macro}{\changepage}
% Change the page layout, but DON'T.
% \changes{v1.61803}{2008/01/30}{Added \cs{changepage} to match chngpage.sty}
%    \begin{macrocode}
\DeclareRobustCommand{\changepage}[9]{%
  \@ifmtarg{#1}{}{\addtolength{\textheight}{#1}}%
  \@ifmtarg{#2}{}{\addtolength{\textwidth}{#2}}%
  \@ifmtarg{#3}{}{\addtolength{\evensidemargin}{#3}}%
  \@ifmtarg{#4}{}{\addtolength{\oddsidemargin}{#4}}%
  \@ifmtarg{#5}{}{\addtolength{\columnsep}{#5}}%
  \ch@ngetext
  \@ifmtarg{#6}{}{\addtolength{\topmargin}{#6}}%  
  \@ifmtarg{#7}{}{\addtolength{\headheight}{#7}}%  
  \@ifmtarg{#8}{}{\addtolength{\headsep}{#8}}%  
  \@ifmtarg{#9}{}{\addtolength{\footskip}{#9}}}  

%    \end{macrocode}
% \end{macro}
%
% \subsection{Temporarily changing the text width}
%
%
% \begin{environment}{adjustwidth}
% \begin{environment}{adjustwidth*}
% \verb?\begin{adjustwidth}?\marg{left}\marg{right}
% adds the given lengths to the left and right hand margins. A positive
% value will shorten the text and a negative value will widen it. The
% starred version of the environment will cause the
% margin changes to switch between odd and even pages.
%
% This code is based on the \Lpack{chngpage} package.
% \changes{v0.2}{2001/06/03}{Replaced optional arg of adjustwidth by adjustwidth*}
%    \begin{macrocode}
\newenvironment{adjustwidth}[2]{%
  \begin{list}{}{%
    \topsep\z@%
    \listparindent\parindent%
    \parsep\parskip%
    \@ifmtarg{#1}{\setlength{\leftmargin}{\z@}}%
                 {\setlength{\leftmargin}{#1}}%
    \@ifmtarg{#2}{\setlength{\rightmargin}{\z@}}%
                 {\setlength{\rightmargin}{#2}}%
    }
    \item[]}{\end{list}}

%    \end{macrocode}
%
%    \begin{macrocode}
\newenvironment{adjustwidth*}[2]{%
  \begin{list}{}{%
    \topsep\z@%
    \listparindent\parindent%
    \parsep\parskip%
    \checkoddpage
    \ifoddpage  % odd numbered page
      \@ifmtarg{#1}{\setlength{\leftmargin}{\z@}}%
                   {\setlength{\leftmargin}{#1}}%
      \@ifmtarg{#2}{\setlength{\rightmargin}{\z@}}%
                   {\setlength{\rightmargin}{#2}}%
    \else       % even numbered page
      \@ifmtarg{#2}{\setlength{\leftmargin}{\z@}}%
                   {\setlength{\leftmargin}{#2}}%
      \@ifmtarg{#1}{\setlength{\rightmargin}{\z@}}%
                   {\setlength{\rightmargin}{#1}}%
    \fi
    }
    \item[]}{\end{list}}

%    \end{macrocode}
% \end{environment}
% \end{environment}
%
%  The environments only work for complete paragraphs.
%
% \subsection{Centering text}
%
% \begin{macro}{\calccentering}
% This macro calculates the amount to be added to the spine margin
% (and subtracted from the foredge margin) 
% in order to center the textblock. Call as \\
% \verb?\calccentering{\length}? and it sets \cs{length}
% to the required value. Then use as \\
% \verb?\begin{adjustwidth*}{\length}{-\length}...?
%    \begin{macrocode}
\newcommand{\calccentering}[1]{
  #1 = \paperwidth
  \advance #1 by -\textwidth
  \divide #1 by \tw@
  \advance #1 by -\spinemargin}

%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{vplace}
% \verb?\begin{vplace}?\oarg{decimal number} centers its body vertically. The
% optional argument \meta{decimal number} increases ($>1.0$) or decreases
% ($<1.0$) the space above the body with respect to the space below.
% This is more robust than the method proposed in the manual.
% \changes{v1.61803}{2008/01/30}{Added vplace environment (mempatch v4.4)}
% \changes{v3.6g}{2010/08/27}{Both should be \cs{vspace*}}
%    \begin{macrocode}
\newenvironment{vplace}[1][1]{%
  \par\vspace*{\stretch{#1}}%
}{%
  \vspace*{\stretch{1}}%
  \par}

%    \end{macrocode}
% \end{environment}
%
%
% \subsection{Moving from the current page}
%
% Much of this code is taken from the \Lpack{nextpage} package~\cite{NEXTPAGE}.
%
% Clear to next page is \cs{clearpage}.
%
% \begin{macro}{\cleartoevenpage}
%  \cs{cleartoevenpage}\oarg{text} clears to the next even 
% numbered page, 
%  putting the optional \meta{text} on the skipped page, if any.
%    \begin{macrocode}
\newcommand{\cleartoevenpage}[1][\@empty]{%
  \clearpage%
  \ifodd\c@page\hbox{}#1\clearpage\fi}

%    \end{macrocode}
% \end{macro}
%
% Move to the next page without flushing floats is \cs{newpage}.
%
% \begin{macro}{\movetoevenpage}
%  \cs{movetoevenpage}\oarg{text} moves to the next even 
% numbered page without flushing floats, 
%  putting the optional \meta{text} on the skipped page, if any.
%    \begin{macrocode}
\newcommand{\movetoevenpage}[1][\@empty]{%
  \newpage%
  \ifodd\c@page\hbox{}#1\newpage\fi}

%    \end{macrocode}
% \end{macro}
%
% Clear to next odd numbered page is \cs{cleardoublepage}.
%
% \begin{macro}{\cleartooddpage}
%  \cs{cleartooddpage}\oarg{text} clears to the next odd
% numbered page, 
%  putting the optional \meta{text} on the skipped page, if any.
%    \begin{macrocode}
\newcommand{\cleartooddpage}[1][\@empty]{%
  \clearpage%
  \ifodd\c@page\else\hbox{}#1\clearpage\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\movetooddpage}
%  \cs{movetooddpage}\oarg{text} moves to the next odd
% numbered page without flushing floats, 
%  putting the optional \meta{text} on the skipped page, if any.
%    \begin{macrocode}
\newcommand{\movetooddpage}[1][\@empty]{%
  \newpage%
  \ifodd\c@page\else\hbox{}#1\newpage\fi}

%    \end{macrocode}
% \end{macro}
%
% Example uses: \\
% \begin{verbatim}
% \cleartooddpage                         % same as \cleardouble page
% \cleartooddpage[\thispagestyle{empty}]  % No headings on the skipped page
% \cleartoevenpage                        % go to next even numbered page
% Next example puts text on a skipped page
% \cleartoevenpage[\vspace*{\hfill}THIS PAGE LEFT BLANK\vspace*{\hfill}]
% \end{verbatim}
%
%
%
% \subsection{Needing space at the bottom of a page}
%
% \begin{macro}{\needspace}
% \cs{needspace}\marg{length} checks if the is \meta{length} amount
% of vertical space left on the page. If there is not it will start
% a new page. The code is a variant of code thought of for the 
% \Lpack{needspace} package~\cite{NEEDSPACE}.
% \changes{v1.4}{2003/11/16}{Added patch v1.4 versions of needspace macros}
% \changes{v3.6g}{2010/09/09}{Added a \cs{vskip0pt} at the end to make
% it work better with \cs{section} and friends}
%    \begin{macrocode}
\newcommand{\needspace}[1]{\begingroup\setlength{\dimen@}{#1}%
  \vskip\z@\@plus\dimen@\penalty -100\vskip\z@\@plus-\dimen@
  \vskip\dimen@\penalty 9999\vskip-\dimen@\vskip\z@skip\endgroup}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\Needspace}
% \begin{macro}{\Needspace*}
% \cs{Needspace} and \cs{Needspace*} are more robust versions of \cs{needspace},
% which depends on penalties. If either \cs{needspace} or \cs{Needspace}
% produce a short page it will be ragged bottom, even if \cs{flushbottom}
% is in effect. The \cs{Needspace*} version honours the \cs{...bottom}
% declaration.
%    \begin{macrocode}    
\newcommand{\Needspace}{\@ifstar{\M@sneedsp@}{\M@needsp@}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\M@sneedsp@}
% \begin{macro}{\M@needsp@}
% These implement \cs{Needspace*} and \cs{needspace} respectively.
%    \begin{macrocode}    
\newcommand{\M@sneedsp@}[1]{\par \penalty-100\begingroup
  \setlength{\dimen@}{#1}%
  \dimen@ii\pagegoal \advance\dimen@ii-\pagetotal
  \ifdim \dimen@>\dimen@ii
    \break
  \fi\endgroup}
\newcommand{\M@needsp@}[1]{\par \penalty-100\begingroup
  \setlength{\dimen@}{#1}%
  \dimen@ii\pagegoal \advance\dimen@ii-\pagetotal
  \ifdim \dimen@>\dimen@ii
    \ifdim \dimen@ii>\z@
      \vfil
    \fi
    \break
  \fi\endgroup}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
% \subsection{Overlong lines}
%
% LaTeX provides \cs{fussy} and \cs{sloppy} to control the amount of slack
% in a line while trying to make justified lines. Their definitions are:
% \begin{verbatim}
% \def\fussy{%
%   \emergencystretch\z@
%   \tolerance 200%
%   \hfuzz .1\p@
%   \vfuzz\hfuzz}
% \def\sloppy{%
%   \tolerance 9999%
%   \emergencystretch 3em%
%   \hfuzz .5\p@
%   \vfuzz\hfuzz}
% \end{verbatim}
%
% \begin{macro}{\midsloppy}
% Somewhere between \cs{fussy} and \cs{sloppy}.
% \changes{v1.61803}{2008/01/30}{Added \cs{midsloppy} and midsloppypar
%                   (mempatch v4.5)}
%    \begin{macrocode}
\newcommand*{\midsloppy}{%
  \tolerance 5000%
  \hbadness 4000%
  \emergencystretch 1.5em%
  \hfuzz .1\p@
  \vfuzz\hfuzz}
%    \end{macrocode}
% \end{macro}
%
% \begin{environment}{midsloppypar}
% A paragraph form of \cs{midsloppy}; equivalent to \verb?\par \midsloppy ... \par}?
%    \begin{macrocode}
\newenvironment{midsloppypar}{\par\midsloppy}{\par}

%    \end{macrocode}
% \end{environment}
%
% \subsection{Text spacing commands}
%
% While we're at it, new text spacing commands to supplement
% the kernel's \\
% \verb?\, (\thinspace) = 3/18 em?
% \changes{v1.4}{2003/11/16}{Extra text spacing macros from patch v1.4}
% \begin{macro}{\medspace}
% \begin{macro}{\:}
% Medium space \verb?\: (\medspace) = 4/18 em?
%    \begin{macrocode}    
\newcommand{\medspace}{\kern .22222em }
\DeclareRobustCommand{\:}{%
  \relax\ifmmode\mskip\medmuskip\else\medspace\fi}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\!}
% Negative thin space (- 3/18 em).
% Patrik Nyman (private email 2003/10/06) pointed out I had missed
% the final \verb?\fi? !!!!. 
%    \begin{macrocode}
\DeclareRobustCommand{\!}{%
  \relax\ifmmode\mskip-\thinmuskip\else\negthinspace\fi}

%    \end{macrocode}
% \end{macro}
%
% \subsection{Fractions and subscripts}
%
%
% Styles for fractions like 3/4.
%
% \begin{macro}{\slashfracstyle}
% \cs{slashfracstyle} based on the kernel \cs{textsuperscript} macro
% \changes{v1.4}{2003/11/16}{Added \cs{slashfrac} and supports (from patch v1.4)}
%    \begin{macrocode}    
\DeclareRobustCommand*{\slashfracstyle}[1]{%
  {\m@th\ensuremath{\mbox{\fontsize\sf@size\z@\selectfont #1}}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\slashfrac}
% \cs{slashfrac} based on TeXbook exercise 11.6
%    \begin{macrocode}    
\DeclareRobustCommand*{\slashfrac}[2]{\leavevmode
  \raise.5ex\hbox{\slashfracstyle{#1}}\kern-.13em/%
  \kern-.15em\lower.25ex\hbox{\slashfracstyle{#2}}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\textsubscript}
% \begin{macro}{\@textsubscript}
% \cs{textsubscript}, for text subscripts, based on the kernel 
% \cs{textsuperscript} macro.
% \changes{v1.4}{2003/11/16}{Added \cs{textsubscript} and supports 
%                (from patch v1.5)}
% \changes{v3.7d}{2014/07/28}{\cs{@textsubscript} should be provided,
% not newcommaded, otherwise one cannot load \Lpack{fixltx2e} before
% \cs{documentclass}, reported by Ulrike Fischer}
% \changes{v3.7d}{2015/03/05}{Requested by the LTX3 team as they are
% updating the LaTeX kernel with the \Lpack{fixltx2e} fixes. Added
% \cs{@ifundefined} wapper}
%    \begin{macrocode}    
\@ifundefined{textsubscript}{%
  \DeclareRobustCommand*{\textsubscript}[1]{%
    \@textsubscript{\selectfont#1}}
  \providecommand*{\@textsubscript}[1]{%
    {\m@th\ensuremath{_{\mbox{\fontsize\sf@size\z@#1}}}}}
}{}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
%  \subsection{Numbers to names}
%
%    \begin{macrocode}
%%%%%%%%%%%%%%%%%%%% number formatting

%    \end{macrocode}
%
% The macros here convert an integer number in the range 0--2147483647
% (TeX's maximum) into
% the natural language name of the number.
% \changes{v1.4}{2003/11/16}{Much extended numbers to names (patch v1.2)}
%
% \begin{macro}{\iflowernumtoname}
% A flag for lowercasing the initial letters.
%    \begin{macrocode}
\newif\iflowernumtoname
  \lowernumtonamefalse
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ifpriornum}
% \begin{macro}{\ifminusnumber}
% \begin{macro}{\ifnotnumtonameallcaps}
% \begin{macro}{\ifmakeordinal}
% Some new booleans
%    \begin{macrocode}
\newif\ifpriornum
\newif\ifminusnumber
\newif\ifnotnumtonameallcaps
\newif\ifmakeordinal

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\namenumberand}
% \begin{macro}{\namenumbercomma}
% \begin{macro}{\lcminusname}
% \begin{macro}{\ucminusname}
% \begin{macro}{\minusname}
% Some macros representing characters/words for number formatting.
%    \begin{macrocode}
\newcommand*{\namenumberand}{ and }
\newcommand*{\namenumbercomma}{, }
\newcommand*{\lcminusname}{minus }
\newcommand*{\ucminusname}{Minus }
\let\minusname\lcminusname
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\fnumbersep}
% \begin{macro}{\tensunitsep}
% \begin{macro}{\nthstring}
% \begin{macro}{\iststring}
% \begin{macro}{\iindstring}
% \begin{macro}{\iiirdstring}
% \begin{macro}{\tiethstring}
% \begin{macro}{\teenstring}
% More characters/words for formatting
%    \begin{macrocode}
\newcommand*{\fnumbersep}{,}
\newcommand*\tensunitsep{-}
\newcommand*{\nthstring}{th}      % nth
\newcommand*{\iststring}{st}      % 1st
\newcommand*{\iindstring}{nd}     % 2nd
\newcommand*{\iiirdstring}{rd}    % 3rd
\newcommand*{\tiethstring}{tieth} % tieth
\newcommand*{\teenstring}{teen}   % teen
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\ordscript}
% How to format the ordinal string
%    \begin{macrocode}
\newcommand{\ordscript}[1]{#1}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\m@mten}
% An internal shorthand for 10
%    \begin{macrocode}
\chardef\m@mten=10 % shorthand for 10

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\c@ism@mctr}
% \begin{macro}{\c@xsm@mctr}
% \begin{macro}{\c@csm@mctr}
% \begin{macro}{\c@ksm@mctr}
% \begin{macro}{\c@xksm@mctr}
% Counters for digits (units to ten thousands) in a number
%    \begin{macrocode}
\newcounter{ism@mctr}  % units
\newcounter{xsm@mctr}  % tens
\newcounter{csm@mctr}  % hundreds
\newcounter{ksm@mctr}  % thousands
\newcounter{xksm@mctr} % ten thousands
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\c@cksm@mctr}
% \begin{macro}{\c@msm@mctr}
% \begin{macro}{\c@xmsm@mctr}
% \begin{macro}{\c@cmsm@mctr}
% \begin{macro}{\c@bsm@mctr}
% Counters for digits (hundred thousands to billions) in a number
%    \begin{macrocode}
\newcounter{cksm@mctr} % hundred thousands
\newcounter{msm@mctr}  % millions
\newcounter{xmsm@mctr} % ten millions
\newcounter{cmsm@mctr} % hundred millions
\newcounter{bsm@mctr}  % billions
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\c@workm@mctr}
% A `work' counter.
%    \begin{macrocode}
\newcounter{workm@mctr}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\numdigits}
% \cs{numdigits}\marg{number} splits the \meta{number} into individual digits.
% It sets \cs{minusnumbertrue} if the number is negative, otherwise it is false.
%    \begin{macrocode}
\newcommand*{\numdigits}[1]{%
  \setcounter{ism@mctr}{0}%
  \setcounter{xsm@mctr}{0}%
  \setcounter{csm@mctr}{0}%
  \setcounter{ksm@mctr}{0}%
  \setcounter{xksm@mctr}{0}%
  \setcounter{cksm@mctr}{0}%
  \setcounter{msm@mctr}{0}%
  \setcounter{xmsm@mctr}{0}%
  \setcounter{cmsm@mctr}{0}%
  \setcounter{bsm@mctr}{0}%
  \setcounter{workm@mctr}{#1}%
  \minusnumberfalse
  \ifnum \c@workm@mctr < \z@  % negative
    \minusnumbertrue
    \c@workm@mctr = -\c@workm@mctr
  \fi
  \ifnum \c@workm@mctr > \m@ne     % units
    \c@ism@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@ism@mctr by -\c@workm@mctr
    \divide \c@workm@mctr by \m@mten
  \fi
  \ifnum \c@workm@mctr > \z@    % tens
    \c@xsm@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@xsm@mctr by -\c@workm@mctr
    \divide \c@workm@mctr by \m@mten
  \fi
  \ifnum \c@workm@mctr > \z@   % hundreds
    \c@csm@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@csm@mctr by -\c@workm@mctr
    \divide \c@workm@mctr by \m@mten
  \fi
  \ifnum \c@workm@mctr > \z@   % thousands
    \c@ksm@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@ksm@mctr by -\c@workm@mctr
    \divide \c@workm@mctr by \m@mten
  \fi
  \ifnum \c@workm@mctr > \z@   % ten thousands
    \c@xksm@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@xksm@mctr by -\c@workm@mctr
    \divide \c@workm@mctr by \m@mten
  \fi
  \ifnum \c@workm@mctr > \z@   % hundred thousands
    \c@cksm@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@cksm@mctr by -\c@workm@mctr
    \divide \c@workm@mctr by \m@mten
  \fi
  \ifnum \c@workm@mctr > \z@   % millions
    \c@msm@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@msm@mctr by -\c@workm@mctr
    \divide \c@workm@mctr by \m@mten
  \fi
  \ifnum \c@workm@mctr > \z@  % ten millions
    \c@xmsm@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@xmsm@mctr by -\c@workm@mctr
    \divide \c@workm@mctr by \m@mten
  \fi
  \ifnum \c@workm@mctr > \z@  % hundred millions
    \c@cmsm@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@cmsm@mctr by -\c@workm@mctr
    \divide \c@workm@mctr by \m@mten
  \fi
  \ifnum \c@workm@mctr > \z@% billions
    \c@bsm@mctr = \c@workm@mctr
    \divide \c@workm@mctr by \m@mten
    \multiply \c@workm@mctr by \m@mten
    \advance \c@bsm@mctr by -\c@workm@mctr
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\form@tnumber}
% \cs{form@tnumber}\marg{number} formats \meta{number} as digits.
%    \begin{macrocode}
\newcommand*{\form@tnumber}[1]{%
  \numdigits{#1}%
  \ifminusnumber-\fi
  \priornumfalse
  \ifnum \c@bsm@mctr > \z@ % billions
    \priornumtrue
    \thebsm@mctr\fnumbersep
  \fi
  \ifpriornum                 % hundred millions
    \thecmsm@mctr
  \else
    \ifnum \c@cmsm@mctr > \z@
      \priornumtrue
      \thecmsm@mctr
    \fi
  \fi
  \ifpriornum                 % ten millions
    \thexmsm@mctr
  \else
    \ifnum \c@xmsm@mctr > \z@
      \priornumtrue
      \thexmsm@mctr
    \fi
  \fi
  \ifpriornum                 % millions
    \themsm@mctr\fnumbersep
  \else
    \ifnum \c@msm@mctr > \z@
      \priornumtrue
      \themsm@mctr\fnumbersep
    \fi
  \fi
  \ifpriornum                % hundred thousands
    \thecksm@mctr
  \else
    \ifnum \c@cksm@mctr > \z@
      \priornumtrue
      \thecksm@mctr
    \fi
  \fi
  \ifpriornum                % ten thousands
    \thexksm@mctr
  \else
    \ifnum \c@xksm@mctr > \z@
      \priornumtrue
      \thexksm@mctr
    \fi
  \fi
  \ifpriornum                % thousands
    \theksm@mctr\fnumbersep
  \else
    \ifnum \c@ksm@mctr > \z@
      \priornumtrue
      \theksm@mctr\fnumbersep
    \fi
  \fi
  \ifpriornum                % hundreds
    \thecsm@mctr
  \else
    \ifnum \c@csm@mctr > \z@
      \priornumtrue
      \thecsm@mctr
    \fi
  \fi
  \ifpriornum                % tens
    \thexsm@mctr
  \else
    \ifnum \c@xsm@mctr > \z@
      \priornumtrue
      \thexsm@mctr
    \fi
  \fi
  \theism@mctr}              % units

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\cardinal}
% \cs{cardinal}\marg{number} prints \meta{number} unformatted.
%    \begin{macrocode}
\newcommand*{\cardinal}[1]{%
  \begingroup
  \let\fnumbersep\relax
  \form@tnumber{#1}%
  \endgroup}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\fcardinal}
% \cs{fcardinal}\marg{number} prints \meta{number} formatted.
%    \begin{macrocode}
\newcommand*{\fcardinal}[1]{%
  \begingroup
  \form@tnumber{#1}%
  \endgroup}
  
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ordinal}
% \cs{ordinal}\marg{number} prints \meta{number} as an unformatted ordinal.
%    \begin{macrocode}
\newcommand*{\ordinal}[1]{%
  \begingroup
  \let\fnumbersep\relax
  \form@tnumber{#1}%
  \let\ordstring\nthstring
  \ifnum \c@xsm@mctr=\@ne\else
    \ifcase \c@ism@mctr
      \or \let\ordstring\iststring%    1st
      \or \let\ordstring\iindstring%   2nd
      \or \let\ordstring\iiirdstring%  3rd
    \fi
  \fi
  \ordscript{\ordstring}%
  \endgroup
}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\fordinal}
% \cs{fordinal}\marg{number} prints \meta{number} as a formatted ordinal.
%    \begin{macrocode}
\newcommand*{\fordinal}[1]{%
  \begingroup
  \form@tnumber{#1}%
  \let\ordstring\nthstring
  \ifnum \c@xsm@mctr=\@ne\else
    \ifcase \c@ism@mctr
      \or \let\ordstring\iststring%    1st
      \or \let\ordstring\iindstring%   2nd
      \or \let\ordstring\iiirdstring%  3rd
    \fi
  \fi
  \ordscript{\ordstring}%
  \endgroup
}

%    \end{macrocode}
% \end{macro}
%
% The next, tedious, code is for translating numbers into names.
%
% \begin{macro}{\nNameo}
% \begin{macro}{\nNamec}
% \begin{macro}{\nNamem}
% \begin{macro}{\nNamemm}
% \begin{macro}{\nNamemmm}
% Names of major numbers: $0$, $10^{2}$, $10^{3}$, $10^{6}$, and $10^{9}$.
%    \begin{macrocode}
\newcommand*\nNameo{\iflowernumtoname z\else Z\fi ero}
\newcommand*\nNamec{\iflowernumtoname h\else H\fi undred}
\newcommand*\nNamem{\iflowernumtoname t\else T\fi housand}
\newcommand*\nNamemm{\iflowernumtoname m\else M\fi illion}
\newcommand*\nNamemmm{\iflowernumtoname b\else B\fi illion}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\nNamei}
% \begin{macro}{\nNameii}
% \begin{macro}{\nNameiii}
% \begin{macro}{\nNameiv}
% \begin{macro}{\nNamev}
%    These are the names for numbers 1 to 5.
%    \begin{macrocode}
\newcommand*\nNamei{\iflowernumtoname o\else O\fi ne}
\newcommand*\nNameii{\iflowernumtoname t\else T\fi wo}
\newcommand*\nNameiii{\iflowernumtoname t\else T\fi hree}
\newcommand*\nNameiv{\iflowernumtoname f\else F\fi our}
\newcommand*\nNamev{\iflowernumtoname f\else F\fi ive}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\nNamevi}
% \begin{macro}{\nNamevii}
% \begin{macro}{\nNameviii}
% \begin{macro}{\nNameix}
% \begin{macro}{\nNamex}
%    These are the names for numbers 6 to 10.
%    \begin{macrocode}
\newcommand*\nNamevi{\iflowernumtoname s\else S\fi ix}
\newcommand*\nNamevii{\iflowernumtoname s\else S\fi even}
\newcommand*\nNameviii{\iflowernumtoname e\else E\fi ight}
\newcommand*\nNameix{\iflowernumtoname n\else N\fi ine}
\newcommand*\nNamex{\iflowernumtoname t\else T\fi en}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\nNamexi}
% \begin{macro}{\nNamexii}
% \begin{macro}{\nNamexiii}
% \begin{macro}{\nNamexiv}
% \begin{macro}{\nNamexv}
%    These are the names for numbers 11 to 15.
%    \begin{macrocode}
\newcommand*\nNamexi{\iflowernumtoname e\else E\fi leven}
\newcommand*\nNamexii{\iflowernumtoname t\else T\fi welve}
\newcommand*\nNamexiii{\iflowernumtoname t\else T\fi hir\teenstring}
\newcommand*\nNamexiv{\iflowernumtoname f\else F\fi our\teenstring}
\newcommand*\nNamexv{\iflowernumtoname f\else F\fi if\teenstring}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\nNamexvi}
% \begin{macro}{\nNamexvii}
% \begin{macro}{\nNamexviii}
% \begin{macro}{\nNamexix}
% \begin{macro}{\nNamexx}
%    These are the names for numbers 16 to 20.
%    \begin{macrocode}
\newcommand*\nNamexvi{\iflowernumtoname s\else S\fi ix\teenstring}
\newcommand*\nNamexvii{\iflowernumtoname s\else S\fi even\teenstring}
\newcommand*\nNamexviii{\iflowernumtoname e\else E\fi igh\teenstring}
\newcommand*\nNamexix{\iflowernumtoname n\else N\fi ine\teenstring}
\newcommand*\nNamexx{\iflowernumtoname t\else T\fi wenty}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\nNamexxx}
% \begin{macro}{\nNamexl}
% \begin{macro}{\nNamel}
% \begin{macro}{\nNamelx}
% \begin{macro}{\nNamelxx}
%    These are the names for numbers 30 to 70.
%    \begin{macrocode}
\newcommand*\nNamexxx{\iflowernumtoname t\else T\fi hirty}
\newcommand*\nNamexl{\iflowernumtoname f\else F\fi orty}
\newcommand*\nNamel{\iflowernumtoname f\else F\fi ifty}
\newcommand*\nNamelx{\iflowernumtoname s\else S\fi ixty}
\newcommand*\nNamelxx{\iflowernumtoname s\else S\fi eventy}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\nNamelxxx}
% \begin{macro}{\nNamexc}
%    These are the names for numbers 80 to 90.
%    \begin{macrocode}
\newcommand*\nNamelxxx{\iflowernumtoname e\else E\fi ighty}
\newcommand*\nNamexc{\iflowernumtoname n\else N\fi inety}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%
%
% \begin{macro}{\unitnumbername}
% Get the name of a unit (0 -- 9).
%    \begin{macrocode}
\newcommand*{\unitnumbername}[1]{%
  \ifcase #1 \nNameo\or
   \nNamei\or
   \nNameii\or
   \nNameiii\or
   \nNameiv\or
   \nNamev\or
   \nNamevi\or
   \nNamevii\or
   \nNameviii\or
   \nNameix\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\teennumbername}
% Get the name of a 'teen number (10 -- 19)
%    \begin{macrocode}
\newcommand*{\teennumbername}[1]{%
  \ifcase #1 \nNamex\or
   \nNamexi\or
   \nNamexii\or
   \nNamexiii\or
   \nNamexiv\or
   \nNamexv\or
   \nNamexvi\or
   \nNamexvii\or
   \nNamexviii\or
   \nNamexix\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\tensnumbername}
% Get the name of a tens number (20 -- 90)
%    \begin{macrocode}
\newcommand*{\tensnumbername}[2]{%
  \ifnum #1=\@ne
    \teennumbername{#2}\ifnotnumtonameallcaps\lowernumtonametrue\fi
  \else
    \ifcase #1
    \or
    \or \nNamexx
    \or \nNamexxx
    \or \nNamexl
    \or \nNamel
    \or \nNamelx
    \or \nNamelxx
    \or \nNamelxxx
    \or \nNamexc
    \fi
    \ifnotnumtonameallcaps\lowernumtonametrue\fi
    \ifnum #2 > \z@ \tensunitsep\unitnumbername{#2}\fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% Names of small ordinals. The use of \cs{nthstring} instead of `th' saves
% some tokens.
%    \begin{macrocode}
\newcommand*\nthNameo{\nNameo\nthstring}
\newcommand*\nthNamei{\iflowernumtoname f\else F\fi irst}
\newcommand*\nthNameii{\iflowernumtoname s\else S\fi econd}
\newcommand*\nthNameiii{\iflowernumtoname t\else T\fi hird}
\newcommand*\nthNameiv{\nNameiv\nthstring}
\newcommand*\nthNamev{\iflowernumtoname f\else F\fi if\nthstring}
\newcommand*\nthNamevi{\nNamevi\nthstring}
\newcommand*\nthNamevii{\nNamevii\nthstring}
\newcommand*\nthNameviii{\iflowernumtoname e\else E\fi igh\nthstring}
\newcommand*\nthNameix{\iflowernumtoname n\else N\fi in\nthstring}
\newcommand*\nthNamexii{\iflowernumtoname t\else T\fi welf\nthstring}

%    \end{macrocode}
%
% \begin{macro}{\unitordinalname}
% Get the ordinal name of a unit (0 -- 9)
%    \begin{macrocode}
\newcommand*{\unitordinalname}[1]{%
  \ifcase #1 \nthNameo\or
  \nthNamei\or
  \nthNameii\or
  \nthNameiii\or
  \nthNameiv\or
  \nthNamev\or
  \nthNamevi\or
  \nthNamevii\or
  \nthNameviii\or
  \nthNameix\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\teenordinalname}
% Get the ordinal name of a 'teen number (10 -- 19). Using \cs{nthstring}
% instead of `th' to save some tokens.
%    \begin{macrocode}
\newcommand*{\teenordinalname}[1]{%
  \ifcase #1 \nNamex\nthstring\or
  \nNamexi\nthstring\or
  \nthNamexii\or
  \nNamexiii\nthstring\or
  \nNamexiv\nthstring\or
  \nNamexv\nthstring\or
  \nNamexvi\nthstring\or
  \nNamexvii\nthstring\or
  \nNamexviii\nthstring\or
  \nNamexix\nthstring\fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\tensordinalname}
% Get the ordinal name of a tens number (20 -- 90)
% (Mathew Dafilis (\texttt{mpd@swin.edu.au}) sent Email on 2003/11/14
% saying that \cs{ordinaltoname} didn't work for 20, 30, etc. He was
% correct. It is now fixed.
%    \begin{macrocode}
\newcommand*{\tensordinalname}[2]{%
  \ifnum #1=\@ne
    \teenordinalname{#2}\ifnotnumtonameallcaps\lowernumtonametrue\fi
  \else
    \ifnum #2> \z@
      \ifcase #1
      \or 
      \or \nNamexx
      \or \nNamexxx
      \or \nNamexl
      \or \nNamel
      \or \nNamelx
      \or \nNamelxx
      \or \nNamelxxx
      \or \nNamexc
      \fi
      \ifnotnumtonameallcaps\lowernumtonametrue\fi
      \tensunitsep\unitordinalname{#2}
    \else
      \ifcase #1
      \or 
      \or \nthNamexx
      \or \nthNamexxx
      \or \nthNamexl
      \or \nthNamel
      \or \nthNamelx
      \or \nthNamelxx
      \or \nthNamelxxx
      \or \nthNamexc
      \fi
      \ifnotnumtonameallcaps\lowernumtonametrue\fi
    \fi
  \fi}
  
%    \end{macrocode}
% \end{macro}
%
%    The names of tens ordinals. The use of \cs{tiethstring} instead
% of `tieth' saves somes tokens.
%    \begin{macrocode}
\newcommand*\nthNamexx{\iflowernumtoname t\else T\fi wen\tiethstring}
\newcommand*\nthNamexxx{\iflowernumtoname t\else T\fi hir\tiethstring}
\newcommand*\nthNamexl{\iflowernumtoname f\else F\fi or\tiethstring}
\newcommand*\nthNamel{\iflowernumtoname f\else F\fi if\tiethstring}
\newcommand*\nthNamelx{\iflowernumtoname s\else S\fi ix\tiethstring}
\newcommand*\nthNamelxx{\iflowernumtoname s\else S\fi even\tiethstring}
\newcommand*\nthNamelxxx{\iflowernumtoname e\else E\fi igh\tiethstring}
\newcommand*\nthNamexc{\iflowernumtoname n\else N\fi ine\tiethstring}

%    \end{macrocode}
%
% \begin{macro}{\n@me@number}
% \cs{n@me@number}\marg{number} is an internal macro to convert a 
% \meta{number} to names.
%    \begin{macrocode}
\newcommand*{\n@me@number}[1]{%
\begingroup
    \numdigits{#1}%
    \ifminusnumber\minusname\fi
    \priornumfalse
%% billions
    \ifnum \c@bsm@mctr > \z@
      \unitnumbername{\thebsm@mctr}\space
      \ifnotnumtonameallcaps\lowernumtonametrue\fi\nNamemmm
      \priornumtrue
    \fi
%% hundred millions
    \ifnum \c@cmsm@mctr > \z@
      \ifpriornum\namenumbercomma\fi
      \unitnumbername{\thecmsm@mctr}\space
      \ifnotnumtonameallcaps\lowernumtonametrue\fi\nNamec
      \priornumtrue
    \fi
%% tens/units millions
    \ifnum \c@xmsm@mctr > \z@
      \ifpriornum
        \ifnum\c@cmsm@mctr>\z@\namenumberand\else\namenumbercomma\fi
      \fi
      \tensnumbername{\thexmsm@mctr}{\themsm@mctr}%
      \priornumtrue
    \else
      \ifnum \c@msm@mctr > \z@
        \ifpriornum
          \ifnum\c@cmsm@mctr>\z@\namenumberand\else\namenumbercomma\fi
        \fi
        \unitnumbername{\themsm@mctr}%
        \ifnotnumtonameallcaps\lowernumtonametrue\fi
        \priornumtrue
      \fi
    \fi
    \ifnum \c@cmsm@mctr > \z@
      \ifpriornum\space\fi
      \nNamemm
    \else
      \ifnum \c@xmsm@mctr > \z@
        \ifpriornum\space\fi
        \nNamemm
      \else
        \ifnum \c@msm@mctr > \z@
          \ifpriornum\space\fi
          \nNamemm
        \fi
      \fi
    \fi
%% hundred thousands
    \ifnum \c@cksm@mctr > \z@
      \ifpriornum\namenumbercomma\fi
      \unitnumbername{\thecksm@mctr}\space
        \ifnotnumtonameallcaps\lowernumtonametrue\fi\nNamec
      \priornumtrue
    \fi
%% tens/units thousands
    \ifnum \c@xksm@mctr > \z@
      \ifpriornum
        \ifnum\c@cksm@mctr>\z@\namenumberand\else\namenumbercomma\fi
      \fi
      \tensnumbername{\thexksm@mctr}{\theksm@mctr}%
      \priornumtrue
    \else
      \ifnum \c@ksm@mctr > \z@
        \ifpriornum
          \ifnum\c@cksm@mctr>\z@\namenumberand\else\namenumbercomma\fi
        \fi
        \unitnumbername{\theksm@mctr}%
        \ifnotnumtonameallcaps\lowernumtonametrue\fi
        \priornumtrue
      \fi
    \fi
    \ifnum \c@cksm@mctr > \z@
      \ifpriornum\space\fi
      \nNamem
    \else
      \ifnum \c@xksm@mctr > \z@
        \ifpriornum\space\fi
        \nNamem
      \else
        \ifnum \c@ksm@mctr > \z@
          \ifpriornum\space\fi
          \nNamem
        \fi
      \fi
    \fi
%% hundreds
    \ifnum \c@csm@mctr > \z@
      \ifpriornum\namenumbercomma\fi
      \unitnumbername{\thecsm@mctr}\space
        \ifnotnumtonameallcaps\lowernumtonametrue\fi\nNamec
      \priornumtrue
    \fi
%% tens/units
  \ifmakeordinal
    \ifnum \c@xsm@mctr > \z@
      \ifpriornum\namenumberand\fi
      \tensordinalname{\thexsm@mctr}{\theism@mctr}%
    \else
      \ifnum \c@ism@mctr > \z@
        \ifpriornum\namenumberand\fi
        \unitordinalname{\theism@mctr}%
      \else
        \ifpriornum\nthstring\else\unitordinalname{\theism@mctr}\fi
      \fi
    \fi
  \else  % not ordinal
    \ifnum \c@xsm@mctr > \z@
      \ifpriornum\namenumberand\fi
      \tensnumbername{\thexsm@mctr}{\theism@mctr}%
    \else
      \ifnum \c@ism@mctr > \z@
        \ifpriornum\namenumberand\fi
        \unitnumbername{\theism@mctr}%
      \else
        \ifpriornum\else\unitnumbername{\theism@mctr}\fi
      \fi
    \fi
  \fi % end ifmakeordinal
\endgroup}

%    \end{macrocode}
% \end{macro}
%
% \changes{v1.61803}{2008/01/30}{Made all \cs{(num/ordinal)toname} robust}
% \begin{macro}{\numtoname}
% Lowercase all names
%    \begin{macrocode}
\DeclareRobustCommand{\numtoname}[1]{%
  \makeordinalfalse
  \notnumtonameallcapstrue%
  \lowernumtonametrue%
  \n@me@number{#1}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\numtoName}
% Uppercase first letter of first name (all else lowercase).
%    \begin{macrocode}
\DeclareRobustCommand{\numtoName}[1]{%
  \makeordinalfalse
  \notnumtonameallcapstrue%
  \lowernumtonamefalse%
  \n@me@number{#1}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\NumToName}
% Uppercase first letter of all names (all else lowercase).
%    \begin{macrocode}
\DeclareRobustCommand{\NumToName}[1]{%
  \makeordinalfalse
  \notnumtonameallcapsfalse%
  \lowernumtonamefalse%
  \n@me@number{#1}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ordinaltoname}
% Lowercase all ordinal names
%    \begin{macrocode}
\DeclareRobustCommand{\ordinaltoname}[1]{%
  \makeordinaltrue
  \notnumtonameallcapstrue%
  \lowernumtonametrue%
  \n@me@number{#1}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\ordinaltoName}
% Uppercase first letter of first ordinal name (all else lowercase).
%    \begin{macrocode}
\DeclareRobustCommand{\ordinaltoName}[1]{%
  \makeordinaltrue
  \notnumtonameallcapstrue%
  \lowernumtonamefalse%
  \n@me@number{#1}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\OrdinalToName}
% Uppercase first letter of all ordinal names (all else lowercase).
%    \begin{macrocode}
\DeclareRobustCommand{\OrdinalToName}[1]{%
  \makeordinaltrue
  \notnumtonameallcapsfalse%
  \lowernumtonamefalse%
  \n@me@number{#1}}

%    \end{macrocode}
% \end{macro}
%
%
% \subsection{A fix for two column headings}
%
%
% This is from a posting by Donald Arseneau to \ctt{} on 23 April 2001 to fix
% a problem --- `When I use \verb?\onecolumn\chapter...? its headline
% is printed lower on the page than for two-column chapters'
%
% DA and I had previously discussed this in relation to the Index
% and I had put a hack into the \Lpack{tocbibind} package to fix the Index.
%
% Donald posted the following.
%
% \cs{vspace*} gives bad spacing after a pagebreak and \cs{@makechapterhead}
% starts with \cs{vspace*}.
% The biggest problem is the definition of \cs{@topnewpage}, which is used
% for the two-column spanning text. Here is a redefinition:
% \changes{v0.2}{2001/06/03}{Added DA's redefinition of \cs{@topnewpage}}
% \begin{macro}{\@topnewpage}
%    \begin{macrocode}
\long\def \@topnewpage [#1]{%
  \@nodocument
  \@next\@currbox\@freelist{}{}%
  \global \setbox\@currbox
    \vbox {%
      \break
      \prevdepth\z@
      \begingroup
      \normalcolor
      \hsize\textwidth
      \@parboxrestore
      \col@number \@ne
      #1%
      \vskip -\dbltextfloatsep
      \endgroup
      \null % ordinary \baselineskip
      \vskip -\topskip
  }%
  \begingroup %% \showbox\@currbox
    \splitmaxdepth\maxdepth \splittopskip\topskip
    \setbox\@tempboxa \vsplit\@currbox to \z@
  \endgroup %% \showbox\@currbox
  \ifdim \ht\@currbox>\textheight
    \ht\@currbox \textheight
  \fi
  \global \count\@currbox \tw@
  \@tempdima -\ht\@currbox
  \advance \@tempdima -\dbltextfloatsep
  \global \advance \@colht \@tempdima
  \ifx \@dbltoplist \@empty
  \else
    \@latexerr{Float(s) lost}\@ehb
    \let \@dbltoplist \@empty
  \fi
  \@cons \@dbltoplist \@currbox
  \global \@dbltopnum \m@ne
  \ifdim \@colht<2.5\baselineskip
    \@latex@warning@no@line {Optional argument of \noexpand\twocolumn
        too tall on page \thepage}%
    \@emptycol
    \if@firstcolumn
    \else
      \@emptycol
    \fi
  \else
    \global \vsize \@colht
    \global \@colroom \@colht
    \@floatplacement
  \fi}

%    \end{macrocode}
% \end{macro}
%
% The original version of \cs{@topnewpage} is in \file{ltouput.dtx}, line 159.
%
% \subsection{Time of day}
%
% William Adams (2006/08/28) supplied a basis for 
% \cs{printime}, which he needed for \cs{quarkmarks} but I have used one 
% from \textit{TeX for the Impatient} 
% as it saves some counters.
% \changes{v1.61803}{2008/01/30}{Added \cs{printime} and friends (mempatch v4.6)}
% \begin{macro}{\m@mcalchm}
% Calculate the hours and minutes from \cs{time}.
%    \begin{macrocode}
\newcommand*{\m@mcalchm}{%
  \count0 = \time \divide \count0 by 60\relax
  \count2 = \count0\relax%    the hour
  \count4 = \time \multiply\count0 by 60\relax
  \advance\count4 by -\count0\relax% the minute
  \ifnum\count4<10 \toks1 = {0}%  make a leading zero
  \else \toks1 = {}%
  \fi}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\hmpunct}
% \begin{macro}{\amname}
% \begin{macro}{\pmname}
% User format controls for \cs{printtime}
%    \begin{macrocode}
%%% punctuation, am and pm for \printtime
\newcommand*{\hmpunct}{:}% hours minutes separator
\newcommand*{\amname}{am}% ante meridiem
\newcommand*{\pmname}{pm}% post meridiem

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\printtime}
% \begin{macro}{\printtime*}
% Print the time of day as 24 hour clock or 12 hour clock
% \cs{printtime} prints the time par 24 hour clock and \cs{printtime*}
% per 12 hour clock.
%    \begin{macrocode}
\newcommand*{\printtime}{%
  \@ifstar{\m@msprtime}{\m@mprtime}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\m@mprtime}
% \begin{macro}{\m@msprtime}
% These implement time printing: \cs{m@mprtime} as 24 hour clock and
% \cs{m@msprtime} as 12 hour clock
%    \begin{macrocode}
\newcommand*{\m@mprtime}{\begingroup
  \m@mcalchm
  \number\count2\hmpunct\the\toks1 \number\count4
  \endgroup}
\newcommand*{\m@msprtime}{\begingroup
  \m@mcalchm
  \def\@mpm{\pmname}%
  \ifnum\count2<1\relax% early in the morning
    \count2=12\relax
    \ifnum\count4>0\relax% not midnight
      \def\@mpm{\amname}%
    \fi
  \else
    \ifnum\time<721\relax% noon or earlier
      \def\@mpm{\amname}%
    \else
      \ifnum\time>779\relax% 1300 hrs or later
        \advance\count2 by -12\relax
      \fi
    \fi
  \fi
  \number\count2\hmpunct\the\toks1 \number\count4\ \@mpm
  \endgroup}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \subsection{Sequential sheet (page) numbers}
%
% \begin{macro}{\c@sheetsequence}
% Peter Heslin asked for the ability to add a sequential page number
% (1 for the first page, N for the last page, no matter what value
% the page counter has) to the trimming marks.
%
%    \cs{c@sheetsequence} is a new counter for pages starting at the 
% beginning and independent
% of the standard page counter. This should not be reset by anything.
% The counter increment has to be added to the output routine.
%
%     This may also be useful for page N of M numbering.
% \changes{v1.3}{2002/10/10}{Added sheetsequence counter.}
%    \begin{macrocode}
\newcounter{sheetsequence}
  \setcounter{sheetsequence}{1}
  \renewcommand{\thesheetsequence}{\@arabic\c@sheetsequence}
\g@addto@macro{\@outputpage}{\stepcounter{sheetsequence}}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\c@lastsheet}
% \begin{macro}{\c@lastpage}
% While we're at it, might as well provide for lastpage and lastsheet counters
% \changes{v1.3}{2002/11/14}{Added lastsheet and lastpage functions.}
%    \begin{macrocode}
\newcounter{lastsheet}
  \setcounter{lastsheet}{0}
\newcounter{lastpage}
  \setcounter{lastpage}{0}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\dol@stsheet}
% \begin{macro}{\dol@stpage}
% These two macros write the values of lastsheet and lastpage to the
% \file{aux} file. They have to be called at the end of the document
% after a \cs{clearpage} to flush out any floats.
% \changes{v1.4}{2003/02/27}{In \cs{dol@stpage} use the page counter value,
%                            not \cs{thepage} otherwise problems with
%                            non-arabic page numbers (patch 1.1)}
% \changes{v1.61}{2004/03/21}{In \cs{dol@stpage} use the sheet counter value,
%                              not \cs{thesheetsequence} otherwise problems
%                              if (e.g., hangul.sty) \cs{@arabic} is redefined}
% \changes{v1.618}{2005/09/02}{Made \cs{dol@stsheet} and \cs{dol@stpage}
%  obey \cs{nofiles}}
% \changes{v1.61803}{2008/01/30}{Made \cs{dol@stsheet} and \cs{dolastpage}
%                    use \cs{memsetcounter} instead of \cs{setcounter}}

%    \begin{macrocode}
\newcommand{\dol@stsheet}{%
  \if@filesw
    \addtocounter{sheetsequence}{-1}%
    \immediate\write\@auxout%
      {\string\memsetcounter{lastsheet}{\the\c@sheetsequence}}%
    \stepcounter{sheetsequence}%
  \fi}
\newcommand{\dol@stpage}{%
  \if@filesw
    \addtocounter{page}{-1}%
    \immediate\write\@auxout%
      {\string\memsetcounter{lastpage}{\the\c@page}}%
    \stepcounter{page}%
  \fi}
%    \end{macrocode}
% I originally used this: \\
% \verb?\AtEndDocument{\clearpage\dol@stsheet\dol@stpage}?
% but following the CTT thread \textit{AtEndDocument produces unwanted page
% break}, 2004/03/11, and in particular Dan Luecking's response I now
% try as hard as possible to do it right at the end, but even this is not
% 100\% reliable. The only way to ensure reliability is to modify the kernel
% \verb?\enddocument? which doesn't seem to be a particularly wise thing
% to do.
% \changes{v1.61}{2004/03/14}{Changed location of calls to \cs{dol@stsheet}
%                             and \cs{dol@stpage}}
%    \begin{macrocode}
\AtBeginDocument{\AtEndDocument{\clearpage\dol@stsheet\dol@stpage}}

%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \subsection{Leaves per gathering}
%
%     Traditionally books are assembled in terms of gatherings, or signatures, 
% with perhaps 8 or 16 pages (or leaves) per grouping (a leaf has two pages, 
% recto and one verso). At the request of Alan Ristow code for this has
% been included in the class.
%
% \begin{macro}{\ifcntrmod}
% \begin{macro}{\ifnotcntrmod}
% \begin{macro}{\iscntrmod}
% \cs{iscntrmod}\marg{counter}\marg{number} returns \cs{cntrmod(true|false)}
% and \cs{notcntrmod(false|true)} if \meta{counter} is a multiple of 
% \meta{number}.
% \changes{v1.61803}{2008/01/30}{Added \cs{iscntrmod}}
%    \begin{macrocode}
\newif\ifcntrmod
\newif\ifnotcntrmod
\newcommand*{\iscntrmod}[2]{
  \@tempcnta=\@nameuse{c@#1}%
  \@tempcntb=\@tempcnta
  \divide\@tempcnta #2\relax
  \multiply\@tempcnta #2\relax
  \advance\@tempcntb-\@tempcnta
  \ifnum\@tempcntb=0\relax
    \cntrmodtrue
    \notcntrmodfalse
  \else
    \cntrmodfalse
    \notcntrmodtrue
  \fi}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@memensuresigpages}
% Ouput enough (empty) pages to make up a complete final signature.
% \changes{v1.61803}{2008/01/30}{Added \cs{@memensuresigpages}}
%    \begin{macrocode}
\newcommand*{\@memensuresigpages}{%
  \ifnum\@mempagespersig<\@ne
  \else
    \iscntrmod{sheetsequence}{\@mempagespersig}
    \ifcntrmod
    \else
        \clearpage
        \pagestyle{empty}
        \mbox{}
      \loop
        \iscntrmod{sheetsequence}{\@mempagespersig}
        \ifnotcntrmod
        \clearpage
        \pagestyle{empty}
        \mbox{}
      \repeat
    \fi
  \fi}

%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\leavespergathering}
% \cs{leavespergathering}\marg{num} is the user command for specifying that
% there must be \meta{num} leaves per gathering (2\meta{num} pages per 
% gathering). For \meta{num} more than one the total number of pages output
% is exactly divisible by 2\meta{num}. \meta{num} less than two (the default)
% has no effect.
% \changes{v1.61803}{2008/01/30}{Added \cs{leavespergathering}}
%    \begin{macrocode}
\newcommand*{\leavespergathering}[1]{\@memcnta=#1\relax
                                     \ifnum\@memcnta<\tw@
                                       \def\@mempagespersig{-1}%
                                     \else
                                       \multiply\@memcnta \tw@
                                       \edef\@mempagespersig{\@memcnta}%
                                     \fi}
\leavespergathering{0}

%    \end{macrocode}
% \end{macro}
%
% Finally, make sure that the requested number of pages is output.
%    \begin{macrocode}
\AtEndDocument{\@memensuresigpages}

%    \end{macrocode}
%
% \subsection{Text case}
% \changes{v3.6k}{2012/09/13}{Included a copy of the \texttt{textcase}
% package.} 
%
% Since, say, \cs{MakeUppercase} does too much, i.e.\ also upper case
% math and arguments to, say, \cs{ref}, we provide a version that does
% not. David Carlisle wrote the simple package ---
% \Lpack{textcase}~\cite{TEXTCASE} which we simply present as a carbon
% copy including Davids explanations. We do \emph{not} mark this
% package as have been emulated. Loading \texttt{textcase} just
% overwrites the macros if they exist.
%
% \MakeShortVerb{\|}
%    \begin{macrocode}
%%%% Nearly a carbon copy from textcase.dtx by David Carlisle
%    \end{macrocode}
% \begin{macro}{\@uclcnotmath}
% This is the main macro from \texttt{textcase}. It is basically
% a copy of |\MakeUppercase| and |\MakeLowercase|
% from the \LaTeX\ kernel, modified slightly so that they
% can share code (that modification could be done to the
% standard versions as well) and then further changed to
% skip certain features like math mode and |\label| arguments.
%
% The arguments are:\\
% |#1|: Extra commands to apply for case changing.
%       Used to locally redefine |\i| and |\j| for uppercasing.\\
% |#2|: Either |##1##2| or |##2##1| to control the order
%       in which |\let| is applied to the pairs of control
%       sequences in |\@uclclist|.\\
% |#3|:  |\uppercase| or |\lowercase|.\\
% |#4|: The text to be upper (or lower) cased.
%    \begin{macrocode}
\def\@uclcnotmath#1#2#3#4{\begingroup
%    \end{macrocode}
% Run extra commands (currently just to redefine |\i| and |\j|).
%    \begin{macrocode}
      #1%
%    \end{macrocode}
%
% Locally set |\( \)| to be just |$ $|, so that the math skipping
% code can be simplified, just to look for |$|.
%    \begin{macrocode}
      \def\({$}\let\)\(% $ for emacs :-)
%    \end{macrocode}
%
% Set up the `non-math' things that also have to be skipped.
%    \begin{macrocode}
      \def\NoCaseChange##1{\noexpand\NoCaseChange{\noexpand##1}}%
      \@nonchangecase\label
      \@nonchangecase\ref
      \@nonchangecase\ensuremath
%    \end{macrocode}
%
% |\cite| a bit trickier, as we want to uppercase any optional argument.
% This will fail if the optional argument contains a brace group, but
% should catch most cases.
%
% |text \cite[page 1]{foo} more text| ends up as
%\begin{verbatim}
% \uppercase{text \toks@{\cite[page1]}%
% \the\toks@{foo}%
% \uppercase{ more text}
%\end{verbatim}
%    \begin{macrocode}
      \def\cite##1##{\toks@{\noexpand\cite##1}\@citex}%
      \def\@citex##1{\NoCaseChange{\the\toks@{##1}}}%
%    \end{macrocode}
% (|\@citex| is a scratch macro here, not a redefinition of the existing
% |\@citex|.)
%
% The following is essentially taken from |\MakeUppercase|.
% Recursively execute |\reserved@a| to |\let| the pairs in |\@uclclist|.
% The strange construction with |\@gobble| at the end just gobbles the
% final recursive call.
%
% Incidentally, packages should not use the |\reserved@|\ldots\ scratch
% macros, which are `reserved' for use within the \LaTeX\ kernel, but
% (a) this code is essentially a copy from the kernel, and 
% (b) I'm allowed to break the rules, so there.
%    \begin{macrocode}
      \def\reserved@a##1##2{\let#2\reserved@a}%
      \expandafter\reserved@a\@uclclist\reserved@b{\reserved@b\@gobble}%
%    \end{macrocode}
%
% Expand everything first so that the `skipping' code can see what to
% skip and so that tokens are revealed to |\uppercase|.
% This makes the argument `moving'.
% The |$\valign$| is just a fake math expression used to terminate
% the parsing done by |\@skipmath|.
%    \begin{macrocode}
      \protected@edef\reserved@a{\endgroup
          \noexpand\@skipmath#3#4$\valign$}%
%    \end{macrocode}
%
%    \begin{macrocode}
      \reserved@a}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@nonchangecase}
%    \begin{macrocode}
\def\@nonchangecase#1{\def#1##1{\NoCaseChange{#1{##1}}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\NoCaseChange}
% For hiding arbitrary text from |\uppercase|. This innocuous
% definition is used for any occurrence of |\NoCaseChange|
% in text that is not passed to |\MakeTextUppercase|. For example a 
% section heading may be uppercased, but the toc entry may not.
% It is also used for nested definitions of |\cite| etc, where the 
% |\NoCaseChange| is inserted by expansion, but not removed as it is
% hidden by the brace group.
%    \begin{macrocode}
\let\NoCaseChange\@firstofone
%    \end{macrocode}
% \end{macro}
%
%\begin{macro}{\@skipmath}
% |#1|: operation |\uppercase| / |\lowercase|\\
% |#2|: text up to first (next) |$|\\
% |#3|: first math mode material (or |\valign| sentinel)
%    \begin{macrocode}
\def\@skipmath#1#2$#3${%
  \@skip@nonchangecase#1#2\NoCaseChange\valign
  \ifx\valign#3%
  \else
    $#3$%
    \expandafter\@skipmath\expandafter#1%
  \fi}
%    \end{macrocode}
% \end{macro}
%
%\begin{macro}{\@skip@nonchangecase}
% |#1|: |\uppercase| or |\lowercase|\\
% |#2|: Text up to the first command (such as |\cite|) made `safe'.
%       or the first use of |\NoCaseChange|.
%    \begin{macrocode}
\def\@skip@nonchangecase#1#2\NoCaseChange#3{%
  #1{#2}%
  \ifx\valign#3%
  \else
    #3%
    \expandafter\@skip@nonchangecase\expandafter#1%
  \fi}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\MakeTextUppercase}
% Put it all together. Arrange for \i\ and \j\ to uppercase, and
% to read the pairs in the ucase list `forwards'.
%    \begin{macrocode}
\DeclareRobustCommand\MakeTextUppercase{%
  \@uclcnotmath{\def\i{I}\def\j{J}}{##1##2}\uppercase}
%    \end{macrocode}
%
%    \begin{macrocode}
\protected@edef\MakeTextUppercase#1{\MakeTextUppercase{#1}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\MakeTextLowercase}
% Use |\lowercase| and read the pairs in the uppercase list `backwards'.
%    \begin{macrocode}
\DeclareRobustCommand\MakeTextLowercase{%
  \@uclcnotmath{}{##2##1}\lowercase}
%    \end{macrocode}
%
%    \begin{macrocode}
\protected@edef\MakeTextLowercase#1{\MakeTextLowercase{#1}}
%    \end{macrocode}
% \end{macro}
%    \begin{macrocode}
%%%% End copy from textcase.dtx 
%    \end{macrocode}
% \DeleteShortVerb{\|}
%
%
% \section{Initialization} \label{sec:init}
%
% \subsection{Words and phrases}
% 
% This document class is for documents prepared in the English language.
% To prepare a version for another language, various English words 
% and phrases must
% be replaced.  The English elements that require replacement are
% defined below in command names.
%
% \begin{macro}{\abstractname}
% \begin{macro}{\contentsname}
% \begin{macro}{\listfigurename}
% \begin{macro}{\listtablename}
% \begin{macro}{\bookname}
% \begin{macro}{\partname}
% \begin{macro}{\chaptername}
% \begin{macro}{\appendixname}
% \begin{macro}{\appendixtocname}
% \begin{macro}{\appendixpagename}
% \begin{macro}{\bibname}
% \begin{macro}{\indexname}
% \begin{macro}{\glossaryname}
%
%    This list is for titles of document sections.
%
%    \begin{macrocode}
\newcommand*{\abstractname}{Abstract}
\newcommand*{\contentsname}{Contents}
\newcommand*{\listfigurename}{List of Figures}
\newcommand*{\listtablename}{List of Tables}
\newcommand*{\bookname}{Book}
\newcommand*{\partname}{Part}
\newcommand*{\chaptername}{Chapter}
\newcommand*{\appendixname}{Appendix}
\newcommand*{\appendixtocname}{Appendices}
\newcommand*{\appendixpagename}{Appendices}
\newcommand*{\bibname}{Bibliography}
\newcommand*{\indexname}{Index}
\newcommand*{\glossaryname}{Glossary}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\figurename}
% \begin{macro}{\tablename}
% \begin{macro}{\figurerefname}
% \begin{macro}{\tablerefname}
% \begin{macro}{\pagename}
% \begin{macro}{\pagrefename}
%
%    These are the names and phrases used for general elements.
%
%    \begin{macrocode}
\newcommand*{\figurename}{Figure}
\newcommand*{\tablename}{Table}
\newcommand*{\figurerefname}{Figure}
\newcommand*{\tablerefname}{Table}
\newcommand*{\pagename}{page}
\newcommand*{\pagerefname}{page}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\bookrefname}
% \begin{macro}{\partrefname}
% \begin{macro}{\chapterrefname}
% \begin{macro}{\sectionrefname}
% \begin{macro}{\appendixrefname}
% More names for referencing.
% \changes{v1.2}{2002/07/27}{Added \cs{partrefname}, \cs{chapterrefname}
%                            and \cs{sectionrefname}}
% \changes{v1.61803}{2008/01/30}{Added \cs{bookrefname} (mempatch v4.9+)}
% \changes{v1.61803}{2008/05/17}{Added \cs{appendixrefname}}
%    \begin{macrocode}
\newcommand*{\bookrefname}{Book~}
\newcommand*{\partrefname}{Part~}
\newcommand*{\chapterrefname}{Chapter~}
\newcommand*{\sectionrefname}{\S}
\newcommand*{\appendixrefname}{Appendix~}

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%
% \subsection{Date}
%
% \begin{macro}{\today}
%    This macro uses the \TeX\ primitives \cs{month}, \cs{day} and \cs{year}
%    to provide the date of the \LaTeX-run.
%    \begin{macrocode}
\newcommand{\today}{\ifcase\month\or
  January\or February\or March\or April\or May\or June\or
  July\or August\or September\or October\or November\or December\fi
  \space\number\day, \number\year}
%    \end{macrocode}
% \end{macro}
%
% \subsection{Two column mode}
%
% \begin{macro}{\columnsep}
%    This gives the distance between two columns in two column mode.
%    \begin{macrocode}
\setlength\columnsep{10\p@}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\columnseprule}
%    This gives the width of the rule between two columns in two
%    column mode. We have no visible rule.
%    \begin{macrocode}
\setlength\columnseprule{0\p@}
%    \end{macrocode}
% \end{macro}
%
% \subsection{The page style and counters}
%    We use the page style \pstyle{headings} by
%    default and arabic page numbering. But if the \verb?article?
%    class option is in effect, we will use the \pstyle{plain} style
%    which is the default in the \verb?article? class.
% \changes{v3.6d}{2010/05/13}{When emulating the article class the
% plain page style should used instead of headings}
%    \begin{macrocode}
\ifartopt
\pagestyle{plain}
\else
\pagestyle{headings}
\fi
\pagenumbering{arabic}

%    \end{macrocode}
%    We set the sectional counters to zero, the \verb?tocdepth? to
%    one (sections and above listed), the \verb?secnumdepth? to
%    two (sections and above numbered), and \cs{maxsecnumdepth} to
% the same.
% \changes{v1.1a}{2002/04/28}{Added initialisation of \cs{maxsecnumdepth}}
%    \begin{macrocode}
\setcounter{part}{0}
\setcounter{chapter}{0}
\setcounter{tocdepth}{1}
\setcounter{secnumdepth}{2}
\maxsecnumdepth{section}

%    \end{macrocode}
%
% Set the \cs{linenumberfrequency} to zero to prohibit line numbering
% and also set the font for line numbers. Can now set the final space
% for boxed verbatim line numbers.
%    \begin{macrocode}
\linenumberfrequency{0}
\linenumberfont{\small\rmfamily}
\settowidth{\bvnumlength}{\vlvnumfont 9999}

%    \end{macrocode}
%
%
% \subsection{Single or double sided printing}
%
%
%    Unless the \Lopt{twoside} wasn't specified, We do not try to make 
% each page of equal height.
%    \begin{macrocode}
\if@twoside
\else
  \raggedbottom
\fi
%    \end{macrocode}
%    When the \Lopt{twocolumn} option was specified we call
%    \cs{twocolumn} to activate this mode. We try to make each column as
%    long as the others, but call \cs{sloppy} to make our life easier.
%    \begin{macrocode}
\if@twocolumn
  \twocolumn
  \sloppy
  \flushbottom
%    \end{macrocode}
%    Normally we call \cs{onecolumn} to initiate typesetting in one
%    column.
%    \begin{macrocode}
\else
  \onecolumn
\fi

%    \end{macrocode}
%
% \subsection{Floats}
%
%    Here are the implementations of the figure and table environments
% and their accompanying List of\ldots
%
% \begin{environment}{figure}
% \begin{environment}{figure*}
%    This is the definition of the actual environment. The form with the
%    \verb?*? is used for double column figures. We use \cs{newfloat} to set it.
% In this class figures are numbered per chapter, but we need to change 
% the default definition of \cs{thefigure} if a figure
% is in a pre-numbered chapter.
% \changes{v1.3a}{2002/11/22}{Added \cs{kill@lastcounter} after new 
%                             figure float}
% \changes{v1.61803}{2008/01/30}{Killed \cs{kill@lastcounter} after new 
%                             figure float}
%    \begin{macrocode}
\newfloat[chapter]{figure}{lof}{\figurename}
%%%  \kill@lastcounter{lofdepth}
\renewcommand{\thefigure}{\thechapter.\@arabic\c@figure}

%    \end{macrocode}
% \end{environment}
% \end{environment}
%
% \begin{macro}{\listoffigures}
% \begin{macro}{\listoffigures*}
% These macros request that LaTeX produces a list of figures.
% The LoF heading is added to the ToC unless the starred
% version is used.
% \changes{v1.3}{2002/11/14}{Added \cs{kill@lastcounter} after new 
%                             list of figures}
% \changes{v1.61803}{2008/01/30}{Killed \cs{kill@lastcounter} after new 
%                             listoffigures}
%    \begin{macrocode}
\newlistof{listoffigures}{lof}{\listfigurename}
%%%  \kill@lastcounter{lofdepth}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\l@figure}
%  \cs{l@figure}\marg{title}\marg{page} typesets the LoF entry for
% a \cs{figure} caption heading. 
% \changes{v1.3a}{2002/11/22}{Deleted \cs{kill@lastcounter} after new 
%                             figure listentry}
%    \begin{macrocode}
\newlistentry[chapter]{figure}{lof}{0}
  \cftsetindents{figure}{0em}{2.3em}
%%  \kill@lastcounter{lofdepth}

%    \end{macrocode}
% \end{macro}
%
%
% \begin{environment}{table}
% \begin{environment}{table*}
%  The definition for tables is almost identical.
% \changes{v1.3a}{2002/11/22}{Added \cs{kill@lastcounter} after new 
%                             table float}
% \changes{v1.61803}{2008/01/30}{Killed \cs{kill@lastcounter} after new 
%                             table float}
%    \begin{macrocode}
\newfloat[chapter]{table}{lot}{\tablename}
%%%  \kill@lastcounter{lotdepth}
\renewcommand{\thetable}{\thechapter.\@arabic\c@table}

%    \end{macrocode}
% \end{environment}
% \end{environment}
%
% \begin{macro}{\listoftables}
% \begin{macro}{\listoftables*}
% These macros request that LaTeX produces a list of tables.
% The LoT heading is added to the ToC unless the starred
% version is used.
% \changes{v1.3}{2002/11/14}{Added \cs{kill@lastcounter} after new 
%                             list of tables}
% \changes{v1.61803}{2008/01/30}{Killed \cs{kill@lastcounter} after new 
%                             list of tables}
%    \begin{macrocode}
\newlistof{listoftables}{lot}{\listtablename}
%%%  \kill@lastcounter{lotdepth}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\l@table}
%  \cs{l@table}\marg{title}\marg{page} typesets the LoT entry for
% a \cs{table} caption heading. 
% \changes{v1.3a}{2002/11/22}{Deleted \cs{kill@lastcounter} after new 
%                             table listentry}
%    \begin{macrocode}
\newlistentry[chapter]{table}{lot}{0}
  \cftsetindents{table}{0em}{2.3em}
%%  \kill@lastcounter{lotdepth}

%    \end{macrocode}
% \end{macro}
%
% The \Lpack{subfigure} package defines \verb?lofdepth? and \verb?lotdepth?
% counters. If is not used, then we have to define them. The \Lpack{subfig}
% package replaced \Lpack{subfigure} in 2005, and this only defined
% the counters if they were not previously defined. It now seems sensible
% to ignore any use of the \Lpack{subfigure} package. This makes life a lot
% simpler.
% \changes{v1.61803}{2008/01/30}{Ignore subfig(ure) package re \cs{lofdepth}
%                    and \cs{lotdepth}}
%    \begin{macrocode}
%%%\AtBeginDocument{%
%%%  \@ifundefined{c@lofdepth}%
%%%     {\newcounter{lofdepth}\setcounter{lofdepth}{1}}{}
%%%  \@ifundefined{c@lotdepth}%
%%%     {\newcounter{lotdepth}\setcounter{lotdepth}{1}}{}}

%    \end{macrocode}
%
% \subsection{The \Lopt{article} option}
%
% The \Lopt{article} option requires changes to the default chapterstyle,
% and the numbering of floats, etc.
%
% Emanuele Vicentini (2003/07/21) suggested making \cs{maketitle} more
% closely match the real article's appearance.
% Alan Budden\footnote{\texttt{alan.s.budden@bristol.ac.uk}} commented
% on 2003/12/18 that the equation counter should be continuous.
% \changes{v1.0a}{2001/12/07}{Added footnote and chaptername changes to the article option}
% \changes{v1.4}{2003/11/22}{Added some resets of maketitle macros to 
% the article option (from patch v1.7)}
% \changes{v1.4}{2003/12/18}{Added equation counter to article resets}
%
% Victor Ivrii\footnote{\texttt{vivrii@gmail.com}} (October 2014)
% noted that adding \pstyle{headings} and english \Lpack{babel}
% produce unexpected headers containing the frase ``Chapter''. 
%    \begin{macrocode}
\ifartopt
  \chapterstyle{article}
  \counterwithout{figure}{chapter}
  \counterwithout{table}{chapter}
  \counterwithout{footnote}{chapter}
  \counterwithout{equation}{chapter}
%    \end{macrocode}
% Setting \cs{chaptername} empty was added in v1.0a, with no
% indication why. Because of \Lpack{babel} (and others) this is
% clearly not a good idea. We will adjust \pstyle{headings} in a
% different manner, but leave all the other page styles alone as using
% the \Lopt{article} as the basis of design work might not be
% recommended. 
% \changes{v3.7d}{2014/11/05}{Redone \cs{chaptername} adjustment plus
% \pstyle{headings} under \Lopt{article} option}
%    \begin{macrocode}
  %\renewcommand{\chaptername}{}
  \if@twoside
    \addtopsmarks{headings}{}{%
      \createmark{chapter}{left}{shownumber}{}{. \ }
    }
  \else
    \addtopsmarks{headings}{}{%
      \createmark{chapter}{right}{shownumber}{}{. \ }
    }
  \fi
  \renewcommand{\maketitlehookb}{%
    \vskip -1.5\topsep\vskip -1.5\partopsep}
  \renewcommand{\maketitlehookc}{%
    \vskip -1.5\topsep\vskip -1.5\partopsep}
\fi

%    \end{macrocode}
%
%
% \subsection{The \Lopt{ms} option}
%
% This should be done last as it makes various changes to the defaults.
%
% \begin{macro}{\msdoublespacing}
% \begin{macro}{\mssinglespacing}
%  These do nothing unless the \Lopt{ms} option is used; then they change
% the \cs{baselinestretch}.
%    \begin{macrocode}
\newcommand{\msdoublespacing}{}
\newcommand{\mssinglespacing}{}
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%    \begin{macrocode}
\ifmsdoc
  \renewcommand{\msdoublespacing}{%
    \renewcommand{\baselinestretch}{1.6}\large\normalsize}
  \renewcommand{\mssinglespacing}{%
    \renewcommand{\baselinestretch}{1.0}\large\normalsize}
  \renewcommand{\familydefault}{cmtt}
  \renewcommand{\rmdefault}{cmtt}
  \renewcommand{\sfdefault}{cmtt}
  \renewcommand{\bfdefault}{m}
  \renewcommand{\itdefault}{n}
  \renewcommand{\sldefault}{n}
  \renewcommand{\scdefault}{n}
  \renewcommand{\baselinestretch}{1.6}
  \@twocolumnfalse
  \onecolumn
  \sloppy
  \@twosidefalse
  \raggedbottom
  \pagestyle{plain}
\fi

%    \end{macrocode}
%
% \subsection{Emulated packages}
%
%    Many of the `emulations' are extensions and integration of package
% facilities. In some cases an `emulated' package just won't work with the
% class, so I've added it here to prevent it from being loaded. In any case, 
% most of the packages are mine.
% \changes{v1.6180339}{2008/07/23}{Added dates to emulated packages}
% \changes{v1.61803398d}{2010/02/13}{Emulated tocvsec2, used the date
% from the other lines, tocvsec2 provides the same macros as memoir}
%    \begin{macrocode}
\EmulatedPackage{abstract}[2008/07/23]
\EmulatedPackage{appendix}[2008/07/23]
%    \end{macrocode}
% \changes{v3.6k}{2012/07/19}{Changed the enumated date for the
% \Lpack{array} package. Apparently the only thing changed between
% v2.4b (2005) and c (2008) are some copyright years.}
% \changes{v3.7g}{2018/03/05}{Embedded the latest version of the
% \Lpack{array} package}
% \changes{v3.7h}{2018/09/06}{\Lpack{array} no longer embedded,
% required instead}
%    \begin{macrocode}
 % \EmulatedPackage{array}[2016/10/06]
\EmulatedPackage{booktabs}[2016/05/16]
\EmulatedPackage{ccaption}[2008/07/23]
\EmulatedPackage{changepage}[2008/07/23]
\EmulatedPackage{chngcntr}[2008/07/23]
\EmulatedPackage{chngpage}[2008/07/23]
\EmulatedPackage{crop}
%    \end{macrocode}
% \changes{v3.7h}{2018/09/06}{\Lpack{dcolumn} is no longer embedded,
% emulation removed. We require it instead}
%    \begin{macrocode}
 % \EmulatedPackage{dcolumn}[2008/07/23]
%    \end{macrocode}
% \changes{v3.7g}{2018/03/06}{Adjusted the date for \Lpack{delarray},
% the code is the same}
% \changes{v3.7h}{2018/09/06}{\Lpack{delarray} is no longer embedded,
% emulation removed. We require it instead}
%    \begin{macrocode}
 % \EmulatedPackage{delarray}[2014/10/28]
\EmulatedPackage{enumerate}[2008/07/23]
\EmulatedPackage{epigraph}[2008/07/23]
%%%%%\EmulatedPackage{framed}[2008/07/23]
\EmulatedPackage{ifmtarg}[2008/07/23]
%    \end{macrocode}
% \changes{v3.7g}{2018/03/08}{Removed if\meta{engine} emulation}
%    \begin{macrocode}
 %\ifm@mifetex\EmulatedPackage{ifetex}[2008/07/23]\fi
 %\ifm@mifluatex\EmulatedPackage{ifluatex}[2008/07/23]\fi
 %\ifm@mifpdf\EmulatedPackage{ifpdf}[2008/07/23]\fi
 %\ifm@mifxetex\EmulatedPackage{ifxetex}[2008/07/23]\fi
\EmulatedPackage{index}[2008/07/23]
\EmulatedPackage{makeidx}[2008/07/23]
\EmulatedPackage{moreverb}[2008/07/23]
\EmulatedPackage{mparhack}[2008/07/23]
\EmulatedPackage{needspace}[2008/07/23]
\EmulatedPackage{newfile}[2008/07/23]
\EmulatedPackage{nextpage}[2008/07/23]
\EmulatedPackage{pagenote}[2008/07/23]
\EmulatedPackage{parskip}[2008/07/23]
\EmulatedPackage{patchcmd}[2008/07/23]
\EmulatedPackage{setspace}[2008/07/23]
\EmulatedPackage{shortvrb}[2008/07/23]
\EmulatedPackage{showidx}[2008/07/23]
%    \end{macrocode}
% \changes{v3.7g}{2018/03/02}{Updated the embedded version of \Lpack{tabularx} to v2.11 2016/02/03}
% \changes{v3.7h}{2018/09/08}{\Lpack{tabularx} is no longer emulated,
% but a required package}
%    \begin{macrocode}
 % \EmulatedPackage{tabularx}[2016/02/03]
\EmulatedPackage{titleref}[2008/07/23]
\EmulatedPackage{titling}[2008/07/23]
\EmulatedPackage{tocbibind}[2008/07/23]
\EmulatedPackage{tocloft}[2008/07/23]
\EmulatedPackage{tocvsec2}[2008/07/23]
\EmulatedPackage{verbatim}[2008/07/23]
\EmulatedPackage{verse}[2008/07/23]

%    \end{macrocode}
%
% \subsection{Interaction with the \Lpack{caption} package}
%
% Although the author of the \Lpack{caption} package has, over the
% years, made it work with many other classes he has not extended it
% to either recognise or work with the memoir class. Some authors want
% to use the \Lpack{caption} package, hence\ldots
%
% The easiest manner in which to make the \Lpack{caption} package to
% work with the class, is to restore the kernel defaults for the main
% captioning macros. 
%
% Kill changes to the caption macros when the \Lpack{caption} package
% is used.  The \Lpack{caption} package checks the definitions of the
% \cs{@makecaption}, \cs{caption} and \cs{@caption} macros. These need
% to be identical to the definitions in the standard classes for the
% package to disbelieve that the \Lpack{memoir} class is being used.
%
% \begin{macro}{\@makecaption}
% \begin{macro}{\caption}
% \begin{macro}{\@caption}
% \changes{v1.61803}{2008/01/30}{Killed memoir's captioning when the caption
% package is used (mempatch v4.9).}
% \changes{v3.6k}{2012/05/04}{Changed the warning text to be more informative.}
%    \begin{macrocode}
%%% revert changes to captioning macros if the caption package is used.
\AtBeginPackage{caption}{
  \ClassWarningNoLine{memoir}{%
    You are using the caption package with the memoir class.
    To prepare we will now reset all captioning macros and 
    configurations to kernel defaults, and then let the 
    caption package take over. Please remember to use^^J
    the caption package interfaces in order to^^J
    configure your captions}

  \long\def\@makecaption##1##2{%
    \vskip\abovecaptionskip
    \sbox\@tempboxa{##1: ##2}%
    \ifdim \wd\@tempboxa >\hsize
      ##1: ##2\par
    \else
      \global \@minipagefalse
     \hb@xt@\hsize{\hfil\box\@tempboxa\hfil}%
    \fi
    \vskip\belowcaptionskip}

  \def\caption{%
    \ifx\@captype\@undefined
      \@latex@error{\noexpand\caption outside float}\@ehd
       \expandafter\@gobble
    \else
      \refstepcounter\@captype
      \expandafter\@firstofone
    \fi
    {\@dblarg{\@caption\@captype}}%
  }

  \long\def\@caption##1[##2]##3{%
    \par
    \addcontentsline{\csname ext@##1\endcsname}{##1}%
    {\protect\numberline{\csname the##1\endcsname}{\ignorespaces ##2}}%
    \begingroup
      \@parboxrestore
      \if@minipage
        \@setminipage
      \fi
      \normalsize
      \@makecaption{\csname fnum@##1\endcsname}{\ignorespaces ##3}\par
      \endgroup}

%    \end{macrocode}
% By request of the \Lpack{caption} package author (Axel Sommerfeldt),
% we also restore the caption skips to the kernel defaults. The class
% sets both to be 0.5\cs{onelineskip}, which may cause confusion when
% using certain features in the \Lpack{caption} package.
% \changes{v3.6k}{2012/05/04}{Added \cs{captionXskip} reset to default
% values.}
%    \begin{macrocode}

  \setlength\abovecaptionskip{10\p@}
  \setlength\belowcaptionskip{0\p@}

} % end \AtBeginPackage

%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \subsection{Interaction with the \Lpack{float} package}
%
%    The \Lpack{float} package also defines \cs{newfloat}, so kill memoir's
% version when the \Lpack{float} package gets used.
% \changes{v1.61803}{2008/01/30}{Killed \cs{newfloat} when float package is
%                    used (mempatch v4.9)}
%    \begin{macrocode}
\AtBeginPackage{float}{\let\newfloat\relax}

%    \end{macrocode}
%
% ^^A\subsection{Patch file}
% ^^A
% ^^A At the suggestion of Danie Els (\texttt{DanieEls@sun.ac.za}), Dan Leucking
% ^^A (\texttt{luecking@uark.edu}) and others, input a patch file, if one exists,
% ^^A as the final act. (This is preferable to my series of \file{memfixa.sty},
% ^^A \file{memfixb.sty} packages, and so on, for each release of the class.)
% ^^A \changes{v1.3}{2002/11/14}{Added input of mempatch.sty}
% ^^A \changes{v1.6180339c}{2008/12/26}{Added the two missing arguments when inputting
% ^^A  mempatch.sty (courtesy of Wilhelm Muller)}
% ^^A \changes{v1.61803398}{2009/07/27}{PW: changed call to mempatch, which I think
% ^^A          restores Lars' v1.6180339h change}
% ^^A \changes{v3.7g}{2018/03/08}{mempatch have been empty for almost
% ^^A 10years, we will no longer load it.}
% ^^A    \begin{macrocode}
% ^^A\IfFileExists{mempatch.sty}{%
% ^^A  \RequirePackage{mempatch}}{} 
% ^^A
% ^^A    \end{macrocode}
% ^^A
%    The end of the class definitions.
%    \begin{macrocode}
%</class>
%    \end{macrocode}
%
% \section{Glossary Makeindex style file}
%
% Here is the basic style (configuration) file for Makeindex 
% for use with the default glossary setup.
% \changes{v1.618}{2005/09/25}{Added basic.gst file}
%
%    \begin{macrocode}
%<*gst>
%%%%% basic.gst    basic makeindex glossary configuration file for memoir
%%%%% Output style parameters
preamble "\\begin{theglossary}"
postamble "\n\\end{theglossary}\n"
group_skip "\n\\glossaryspace\n"
item_0    "\n\\glossitem"
delim_0   "{\\memglonum{"
encap_suffix "}}}"
%%% Input style parameters
keyword "\\glossaryentry"

%</gst>
%    \end{macrocode}
%
% The end of the configuration file code
%
% \bibliographystyle{alpha}
% \begingroup
% \raggedright
% \begin{thebibliography}{GMSN94A}
%
%
%    \bibitem[ABH90]{bk:Impatient}
%      Paul W.~Abrahams, Karl Berry and Kathryn A.~Hargreaves.
%      \newblock \emph{TeX{} for the Impatient}.
%      \newblock
%       Addison-Wesley, Reading, Massachusetts, 1990.
%      \newblock (Available from CTAN in \texttt{info/impatient})
%
% \bibitem[Ars01a]{TITLEREF}
% Donald Arseneau.
% \newblock \emph{\Lpack{Titleref} package (version 3.1)}.
% \newblock April 2001.
% \newblock (Available from CTN as
%            \texttt{macros/latex/contrib/misc/titleref.sty})
%
% \bibitem[Ars01b]{CHAPTERBIB}
% Donald Arseneau.
% \newblock \emph{\Lpack{Chapterbib} package (version 1.9)}.
% \newblock September 2001.
% \newblock (Available from CTN as
%            \texttt{macros/latex/contrib/misc/chapterbib.sty})
%
% \bibitem[Ars03]{FRAMED}
% Donald Arseneau.
% \newblock \emph{\Lpack{Framed} package (version 0.8a)}.
% \newblock July 2003.
% \newblock (Available from CTAN as
%            \texttt{macros/latex/contrib/misc/framed.sty})
%
% \bibitem[Ars05]{PLACEINS}
% Donald Arseneau.
% \newblock \emph{\Lpack{Placeins} package (version 2.2)}.
% \newblock May 2005.
% \newblock (Available from CTN as
%            \texttt{macros/latex/contrib/placeins/placeins.sty})
%  
%
% \bibitem[ArWi00]{IFMTARG}
% Donald Arseneau and Peter Wilson.
% \newblock \emph{The ifmtarg package}.
% \newblock March, 2000.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/misc})
%
%
%  \bibitem[Car94]{DELARRAY}
%  David Carlisle.
%  \newblock \emph{The \Lpack{delarray} package}.
%  \newblock March 1994.
%  \newblock (Available from CTAN in
%             \texttt{/macros/latex/required/tools})
%
%
% \bibitem[Car98a]{ENUMERATE}
% David Carlisle.
% \newblock \emph{The enumerate package}.
% \newblock August, 1998.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/required/tools})
%
% \bibitem[Car98b]{REMRESET}
% David Carlisle.
% \newblock \emph{The remreset package}.
% \newblock August, 1998.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/carlisle})
%
%  \bibitem[Car99]{TABULARX}
%  David Carlisle.
%  \newblock \emph{The \Lpack{tabularx} package}.
%  \newblock February 2016.
%  \newblock (Available from CTAN in
%             \texttt{/macros/latex/required/tools})
%
%  \bibitem[Car01]{DCOLUMN}
%  David Carlisle.
%  \newblock \emph{The \Lpack{dcolumn} package}.
%  \newblock May, 2001.
%  \newblock (Available from CTAN in
%             \texttt{/macros/latex/required/tools})
%
% \bibitem[Car04]{TEXTCASE}
%  David Carlisle.
% \newblock \emph{The \Lpack{textcase} package}.
% \newblock October, 2004.
% \newblock (Available from CTAN in 
%       \texttt{/macros/latex/contrib/textcase})
%
% \bibitem[Coc02]{SUBFIGURE}
% Steven Douglas Cochran.
% \newblock \emph{The subfigure package}.
% \newblock March, 2002.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/subfigure})
%
% \bibitem[Dal99]{NATBIB}
% Patrick W. Daly.
% \newblock \emph{Natural Sciences Citations and References}.
% \newblock May, 1999.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/natbib})
%
% \bibitem[Dow00]{PATCHCMD}
% Michael J. Downes
% \newblock \emph{The patchcmd package}.
% \newblock July 2000.
% \newblock (Available from CTAN in
%            \texttt{/macros/latex/contrib/patchcmd})
%
% \bibitem[Fai98]{MOREVERB}
% Robin Fairbairns.
% \newblock \emph{The moreverb package}.
% \newblock December, 1998.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/moreverb})
%
% \bibitem[Fai03]{FOOTMISC}
% Robin Fairbairns.
% \newblock \emph{\Lpack{footmisc} --- a portmanteau package for 
%            customising footnotes in LaTeX}.
% \newblock February 2003.
% \newblock (Available from CTAN in
%            \texttt{macros/latex/contrib/footmisc})
%
%
%    \bibitem[Fea03]{BOOKTABS}
%      Simon Fear.
%      \newblock \emph{Publication quality tables in \LaTeX}.
%       \newblock March, 2003.
%      \newblock (Available from CTAN in 
%                 \texttt{macros/latex/contrib/booktabs})
%
% \bibitem[Fra00]{CROP}
% Melchior Franz.
% \newblock \emph{The crop package}.
% \newblock February, 2000.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/crop})
%
%
% \bibitem[GMS94]{GOOSSENS94}
% Michel Goossens, Frank Mittelbach, and Alexander Samarin.
% \newblock {\em The LaTeX Companion}.
% \newblock Addison-Wesley Publishing Company, 1994.
%
%
%
%    \bibitem[Knu84]{bk:knuth}  
%       Donald E. Knuth.
%       \newblock  \emph{The \TeX{}book}.
%       \newblock
%       Addison-Wesley, Reading, Massachusetts, 1984.
%
%
% \bibitem[KWG]{TUFTE}
% Bil Kleb, Bill Wood, and Kevin Godby.
% \newblock \emph{Tufte LaTeX}.
% \newblock December 2009.
% \newblock (Available from CTAN in \texttt{macros/latex/contrib/tufte-latex/})
% 
%    \bibitem[Lam94]{bk:lamport} 
%       Leslie Lamport.
%       \newblock  \emph{\LaTeX\ --- A Document Preparation System}.
%       \newblock
%       Addison-Wesley, Reading, Massachusetts, 1994.
%
% \bibitem[LMB99]{CLASSES}
% Leslie Lamport, Frank Mittelbach and Johannes Braams.
% \newblock \emph{Standard Document Classes for LaTeX version 2e}.
% \newblock September, 1999.
% \newblock (Available from CTAN as 
%            \texttt{/macros/latex/base/classes.dtx})
%
%  \bibitem[MC98]{ARRAY}
%  Frank Mittelbach and David Carlisle.
%  \newblock \emph{A new implementation of LaTeX's tabular and array 
%                  environment}
%  \newblock April 2017.
%  \newblock (Available from CTAN in
%             \texttt{/macros/latex/required/tools})
%
% \bibitem[Oos96]{FANCYHDR}
% Piet van Oostrum.
% \newblock \emph{Page layout in LaTeX}.
% \newblock June, 1996.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/fancyhdr})
%
%
% \bibitem[Rah01]{NAMEREF}
% Sebastian Rahtz.
% \newblock \emph{Section name references in LaTeX}.
% \newblock January 2001.
% \newblock (Available from CTAN in
%            \texttt{/macros/latex/contrib/hyperref})
%
% \bibitem[Rah02]{HYPERREF}
% Sebastian Rahtz.
% \newblock \emph{Hypertext marks in LaTeX}.
% \newblock March 2002.
% \newblock (Available from CTAN in
%            \texttt{/macros/latex/contrib/hyperref})
%
%
% \bibitem[Sch98]{EVERYSHI}
% Martin Schr\"{o}der.
% \newblock \emph{The everyshi package}.
% \newblock August, 1998.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/ms})
%
% \bibitem[SRR01]{VERBATIM}
% Rainer Sch\"{o}pf, Bernd Raichle and Chris Rowley.
% \newblock \emph{A new implementation of LaTeX's verbatim and verbatim*
%                 environments}.
% \newblock March, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/required/tools})
%
% \bibitem[Wil99]{TOCVSEC2}
% Peter Wilson.
% \newblock \emph{The tocvsec2 package}.
% \newblock January, 1999.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/tocvsec2})
%
% \bibitem[Wil00a]{EPIGRAPH}
% Peter Wilson.
% \newblock \emph{The epigraph package}.
% \newblock February, 2000.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/epigraph})
%
% \bibitem[Wil00b]{ISOCLASS}
% Peter Wilson.
% \newblock \emph{LaTeX files for typesetting ISO standards}.
% \newblock February, 2000.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/isostds/iso})
%
% \bibitem[Wil00c]{NEXTPAGE}
% Peter Wilson.
% \newblock \emph{The nextpage package}.
% \newblock February, 2000.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/misc})
%
% \bibitem[Wil00d]{NEEDSPACE}
% Peter Wilson.
% \newblock \emph{The needspace package}.
% \newblock March, 2000.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/misc})
%
% \bibitem[Wil01a]{ABSTRACT}
% Peter Wilson.
% \newblock \emph{The abstract package}.
% \newblock February, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/abstract})
%
% \bibitem[Wil01b]{CHNGPAGE}
% Peter Wilson.
% \newblock \emph{The chngpage package}.
% \newblock February, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/misc})
%
% \bibitem[Wil01c]{APPENDIX}
% Peter Wilson.
% \newblock \emph{The appendix package}.
% \newblock March, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/appendix})
%
% \bibitem[Wil01d]{CCAPTION}
% Peter Wilson.
% \newblock \emph{The ccaption package}.
% \newblock March, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/ccaption})
%
% \bibitem[Wil01e]{CHNGCNTR}
% Peter Wilson.
% \newblock \emph{The chngcntr package}.
% \newblock March, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/misc})
%
% \bibitem[Wil01f]{HANGING}
% Peter Wilson.
% \newblock \emph{The hanging package}.
% \newblock March, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/hanging})
%
% \bibitem[Wil01g]{TITLING}
% Peter Wilson.
% \newblock \emph{The titling package}.
% \newblock March, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/titling})
%
% \bibitem[Wil01h]{TOCBIBIND}
% Peter Wilson.
% \newblock \emph{The tocbibind package}.
% \newblock April, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/tocbibind})
%
% \bibitem[Wil01i]{TOCLOFT}
% Peter Wilson.
% \newblock \emph{The tocloft package}.
% \newblock April, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/tocloft})
%
% \bibitem[Wil01j]{VERSE}
% Peter Wilson.
% \newblock \emph{Typesetting simple verse with LaTeX}.
% \newblock August, 2001.
% \newblock (Available from CTAN in 
%            \texttt{/macros/latex/contrib/verse})
%
%
% \bibitem[Wil03]{LEDMAC}
% Peter Wilson.
% \newblock \emph{\Lpack{ledmac}: A presumptuous attempt to port EDMAC and
%                 TABMAC to LaTeX}. 
% \newblock August 2003.
% \newblock (Available from CTAN in
%            \texttt{macros/latex/contrib/ledmac})
%
% \bibitem[Wil07]{GLISTER07}
% Peter Wilson.
% \newblock `Glisterings' \emph{TUGboat}, 28(2):229--232,
% \newblock 2007.
%
% \bibitem[Wil08]{GLISTER08}
% Peter Wilson.
% \newblock `Glisterings' \emph{TUGboat}, 29(2):324--327,
% \newblock 2008.
%
%
%
%
%
% \end{thebibliography}
% \endgroup
%
%
% \Finale
%
\endinput

%% \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         \~}
%%

