%D \module
%D   [       file=m-cweb,
%D        version=1997.01.15,
%D          title=\CONTEXT\ Extra Modules,
%D       subtitle=\CWEB\ Pretty Printing Macros,
%D         author=Hans Hagen,
%D           date=\currentdate,
%D      copyright={PRAGMA / Hans Hagen \& Ton Otten}]
%C
%C This module is part of the \CONTEXT\ macro||package and is
%C therefore copyrighted by \PRAGMA. See mreadme.pdf for
%C details.

%D First some auxiliary stuff, to be moved to system module.

\def\dodofindfirstcharacter#1%
  {\ifx#1\relax
     \let\next=\egroup
   \else
     \handlecase
       {\expandafter\ifnum\expandafter\catcode\expandafter`#1=11
        \def\next##1\relax{\egroup\def\firstcharacter{#1}}%
     \fi}%
   \fi
   \next}

\def\dofindfirstcharacter#1#2%
  {\def\firstcharacter{}%
   \bgroup
   \convertargument#2\to\ascii
   \let\next=\dodofindfirstcharacter
   \let\handlecase=#1
   \expandafter\next\ascii\relax}

\def\normalcase#1%
  {#1}

\def\findfirstcharacter%
  {\dofindfirstcharacter\lowercase}

\def\FindFirstCharacter%
  {\dofindfirstcharacter\normalcase}

\def\FINDFIRSTCHARACTER%
  {\dofindfirstcharacter\uppercase}

% nog doen:
%
% \deactivateCWEB in output routine
% status info
% gelinkte entries
% parskip en parindent

%D \gdef\CWEBquote#1.{{\em Quote :}\ #1.} % checks the .

%D This module (re)implements the \CWEB\ macros as defined in
%D the file \type{cwebmac.tex}.
%D
%D \CWEB\ uses short, often one character long, names for
%D macros. This is no real problem because no one is supposed
%D to read and understand the files generated by \CWEB. The
%D standard macros are meant for \PLAIN\ \TEX\ users. In
%D \CONTEXT\ and other macro packages however, there is a
%D potential conflict with format specific or user defined
%D commands. Furthermore, the \CWEB\ macros implement their own
%D output routines. When integrating \CWEB\ documents in
%D another environment, the \CWEB\ specific macros have to be
%D made local. The first part of this module is dedicated to
%D this feature.
%D
%D Instead of using \type{\def} and \type{\let} for defining
%D macros, we use:
%D
%D \starttyping
%D \defCEBmacro arguments {meaning}
%D \letCEBmacro arguments {meaning}
%D \stoptyping
%D
%D \CWEB files contain implicit calls to macros that generate
%D the table of contents, the lists of sections and the index.
%D Because we want to be much more flexible, we implemented our
%D own alternatives, and therefore have to bypass the original
%D ones. The next macro is used for defining these obsolete
%D \CWEB\ macros. The dummies take care of arguments.
%D
%D \starttyping
%D \defCEBdummy arguments {meaning}
%D \stoptyping
%D
%D The list of \CWEB\ specific macro names is saved in a
%D \TOKENLIST. This serves two purposes. First it enables us to
%D activate the \CWEB\ macros, which are saved under a
%D different name, second it can be used to temporary restore
%D the meanings, for instance when the output routine builds
%D the page.

\newtoks\CWEBmacros

%D Activating and deactivating is done by means of:
%D
%D \starttyping
%D \activateCWEB
%D \deactivateCWEB
%D \stoptyping
%D
%D Which are implemented as:

\def\activateCWEB%
  {\let\doCWEB=\activateCWEBmacro
   \the\CWEBmacros}

\def\deactivateCWEB%
  {\let\doCWEB=\deactivateCWEBmacro
   \the\CWEBmacros}

%D The three definition macros append the name of the macro to
%D the list. The first two macros save the meaning, the last one
%D assigns \type{{}} to the macro and gobbles original meaning.

\long\def\defCWEBmacro#1%
  {\appendtoks\doCWEB#1\to\CWEBmacros
   \setvalue{newCWEB\string#1}}

\long\def\letCWEBmacro#1%
  {\appendtoks\doCWEB#1\to\CWEBmacros
   \letvalue{newCWEB\string#1}}

\long\def\defCWEBdummy#1#2#%
  {\appendtoks\doCWEB#1\to\CWEBmacros
   \setvalue{newCWEB\string#1}#2{}%
   \gobbleoneargument}

%D The macro \type{\defCWEBdummy} of course takes care of the
%D argument. This leaves the two (de|)|activating macros:

\def\CWEBmacro#1%
  {\getvalue{newCWEB\string#1}}

\def\activateCWEBmacro#1%
  {\letvalue{oldCWEB\string#1}=#1%
   \def#1{\CWEBmacro#1}}

\def\deactivateCWEBmacro#1%
  {\expandafter\let\expandafter#1\expandafter=\csname oldCWEB\string#1\endcsname}

%D I did consider loading the \CWEB\ macros using temporary
%D substitutes of \type{\def}, \type{\font}, \type{\newbox} etc.
%D The main problem is that the file contains more than
%D definitions and taking all kind of assignments into account
%D too would not make things easier. So I decided to stick to
%D the method as just described.

%D Now we're ready for the real job. What follows is a partial
%D adaption of the file \type{cwebmac.tex}, version 3.1, dated
%D September 1994 and written by Levy and Knuth. When possible
%D we kept the original meaning, but we've granted ourselves
%D the freedom to reformat the macro's for readibility.
%D
%D We'll only present the macros we actually use. The source
%D however contains the original implementation.

% standard macros for CWEB listings (in addition to plain.tex)
% Version 3.1 --- September 1994.
%
% \ifx\documentstyle\undefined\else\endinput\fi % LaTeX will use other macros
%
% \xdef\fmtversion{\fmtversion+CWEB3.1}

%D \macros{.}{}
%D
%D \CWEBquote preserve a way to get the dot accent (all
%D other accents will still work as usual).

\letCWEBmacro\: = \.

% \parskip   = 0pt % no stretch between paragraphs
% \parindent = 1em % for paragraphs and for the first line of C text

% \font\ninerm           = cmr9
% \let\mc                = \ninerm                 % medium caps
% \font\eightrm          = cmr8
% \let\sc                = \eightrm                % small caps (NOT a caps-and-small-caps font)
% \let\mainfont          = \tenrm
% \let\cmntfont          = \tenrm
% \font\tenss            = cmss10
% \let\cmntfont          = \tenss                  % alternative comment font
% \font\titlefont        = cmr7 scaled \magstep4   % title on the contents page
% \font\ttitlefont       = cmtt10 scaled \magstep2 % typewriter type in title
% \font\tentex           = cmtex10                 % TeX extended character set (used in strings)
% \fontextraspace\tentex = 0pt                     % no double space after sentences

%D \macros{mc,sc,cmntfont,eightrm}{}
%D
%D The naming of the fonts in in line with those in \PLAIN\
%D \TEX. Although \CONTEXT\ implements its own scheme, there is
%D still support for the \PLAIN\ ones. We keep the original
%D names, but change their meaning. That way the macros obey
%D switching to other sizes or styles.

\defCWEBmacro\mc       {\tx}
\defCWEBmacro\sc       {\txx}
\defCWEBmacro\cmntfont {\ss}
\defCWEBmacro\eightrm  {\tx}

%D \macros{tentex,sevenrm,sevensy,teni}{}
%D
%D The next one uses a temporary solution. The \type{cmtex10}
%D font is not part of the default mechanism. We make use of
%D the \CONTEXT\ variables \type{\textface}, \type{\scriptface}
%D and \type{\scriptscriptface}, which hold the current
%D sizes.

\defCWEBmacro\tentex%
  {\font\next=cmtex10 at \textface
   \fontextraspace\next\zeropoint
   \next}

\defCWEBmacro\sevenrm  {\getvalue{\scriptface rmtf}}
\defCWEBmacro\sevensy  {\getvalue{\scriptface mmsy}}
\defCWEBmacro\teni     {\getvalue{\textface   mmmi}}

%D \macros{CWEBpt}{}
%D
%D The original macros are based on a 10~point bodyfont size. We
%D therefore have to specify dimension in points a bit
%D different. Specifications like .6pt are changed to
%D \type{.06} times \type{\bodyfontsize}.

\defCWEBmacro\CWEBpt   {\bodyfontsize} % still dutch

%D \macros{CEE,UNIX,TEX,CPLUSPLUS}{}
%D
%D Next come some logo's. It does not make much sense to use
%D the \CONTEXT\ logo mechanism here, so we simply say:

\defCWEBmacro      \CEE/{{\mc C\spacefactor1000}}
\defCWEBmacro     \UNIX/{{\mc U\kern-.05emNIX\spacefactor1000}}
\defCWEBmacro      \TEX/{\TeX}
\defCWEBmacro\CPLUSPLUS/{{\mc C\PP\spacefactor1000}}
\defCWEBmacro       \Cee{\CEE/} % for backward compatibility

%D \macros{\ }{}
%D
%D Now we come to the real work: the short commands that make
%D up the typography.
%D
%D \CWEBquote italic type for identifiers.

\defCWEBmacro\\#1%
  {\leavevmode\hbox{\it#1\/\kern.05em}}

%D \macros{\string|}{}
%D
%D \CWEBquote one letter identifiers look better this way.

\defCWEBmacro\|#1%
  {\leavevmode\hbox{$#1$}}

%D \macros{\string&}{}
%D
%D \CWEBquote boldface type for reserved words.

\defCWEBmacro\&#1%
  {\leavevmode
   \hbox
     {\def\_%
        {\kern.04em
         \vbox{\hrule width.3em height .06\CWEBpt}% .6pt}%
         \kern.08em}%
      \bf#1\/\kern.05em}}

%D \macros{.}{}
%D
%D Here we use the previously saved period. This macro
%D takes care of special characters in strings.

\defCWEBmacro\.#1%
  {\leavevmode
    \hbox
      {\tentex    % typewriter type for strings
       \let\\=\BS % backslash in a string
       \let\{=\LB % left brace in a string
       \let\}=\RB % right brace in a string
       \let\~=\TL % tilde in a string
       \let\ =\SP % space in a string
       \let\_=\UL % underline in a string
       \let\&=\AM % ampersand in a string
       \let\^=\CF % circumflex in a string
       #1\kern.05em}}

%D \macros{)}{}
%D
%D Some discretionary hack.

\defCWEBmacro\)%
  {\discretionary{\hbox{\tentex\BS}}{}{}}

%D \macros{AT}{}
%D
%D \CWEBquote at sign for control text (not needed in versions
%D $>=$ 2.9).

\defCWEBmacro\AT{@}

%D \macros{ATL,postATL,NOATL}{}
%D
%D A two step macro that handles whatever.

\defCWEBmacro\ATL%
  {\par
   \noindent
   \bgroup
   \catcode`\_=12
   \postATL}

\defCWEBmacro\postATL#1 #2 %
  {\bf letter \\{\uppercase{\char"#1}} tangles as \tentex "#2"%
   \egroup
   \par}

\defCWEBmacro\noATL#1 #2 %
  {}

%D \macros{noatl}{}
%D
%D \CWEBquote suppress output from \type{@l}.

\defCWEBmacro\noatl%
  {\let\ATL=\noATL}

% \defCWEBmacro\ATH%
%   {\X\kern-.5em:Preprocessor definitions\X}

%D \macros{PB}
%D
%D \CWEBquote hook for program brackets {\tttf\string|...\string|}
%D in TeX part or  section name.

\defCWEBmacro\PB%
  {\relax}

% \chardef\AM = `\&  % ampersand character in a string
% \chardef\BS = `\\  % backslash in a string
% \chardef\LB = `\{  % left brace in a string
% \chardef\RB = `\}  % right brace in a string
% \chardef\TL = `\~  % tilde in a string
% \chardef\UL = `\_  % underline character in a string
% \chardef\CF = `\^  % circumflex character in a string

\defCWEBmacro\AM {\char`\&}      % ampersand character in a string
\defCWEBmacro\BS {\char`\\}      % backslash in a string
\defCWEBmacro\LB {\char`\{}      % left brace in a string
\defCWEBmacro\RB {\char`\}}      % right brace in a string
\defCWEBmacro\TL {\char`\~}      % tilde in a string
\defCWEBmacro\UL {\char`\_}      % underline character in a string
\defCWEBmacro\CF {\char`\^}      % circumflex character in a string

\defCWEBmacro\SP {{\tt\char`\ }} % (visible) space in a string

% \newbox\PPbox  \setbox\PPbox=\hbox
%   {\kern.5pt\raise1pt\hbox{\sevenrm+\kern-1pt+}\kern.5pt}
% \newbox\MMbox  \setbox\MMbox=\hbox
%   {\kern.5pt\raise1pt\hbox{\sevensy\char0\kern-1pt\char0}\kern.5pt}
% \newbox\MGbox  \setbox\MGbox=\hbox % symbol for ->
%   {\kern-2pt\lower3pt\hbox{\teni\char'176}\kern1pt}
% \newbox\MODbox \setbox\MODbox=\hbox
%   {\eightrm\%}
%
% \def\PP  {\copy\PPbox}
% \def\MM  {\copy\MMbox}
% \def\MG  {\copy\MGbox}
% \def\MOD {\mathbin{\copy\MODbox}}

\defCWEBmacro\PP% symbol for ++
  {\kern.05\CWEBpt
   \raise.1\CWEBpt\hbox{\sevenrm+\kern-.1\CWEBpt+}%
   \kern.05\CWEBpt}

\defCWEBmacro\MM%
  {\kern.05\CWEBpt
   \raise.1\CWEBpt\hbox{\sevensy\char0\kern-.1\CWEBpt\char0}%
   \kern.05\CWEBpt}

\defCWEBmacro\MG%
  {\kern-.2\CWEBpt
   \lower.3\CWEBpt\hbox{\teni\char'176}%
   \kern .1\CWEBpt}

\defCWEBmacro\MRL#1%
  {\mathrel{\let\K==#1}}

% \def\MRL#1%
%   {\KK#1}
% \def\KK#1#2%
%   {\buildrel\;#1\over{#2}}

\letCWEBmacro\GG   = \gg
\letCWEBmacro\LL   = \ll
\letCWEBmacro\NULL = \Lambda

% \mathchardef\AND   = "2026     % bitwise and; also \& (unary operator)

\defCWEBmacro\AND% redefines itself (funny)
  {\mathchardef\AND="2026 \AND}  % bitwise and; also \& (unary operator)

\letCWEBmacro\OR   = \mid                     % bitwise or
\letCWEBmacro\XOR  = \oplus                   % bitwise exclusive or
\defCWEBmacro\CM     {{\sim}}                 % bitwise complement
\defCWEBmacro\MOD    {\mathbin{\eightrm\%}}
\defCWEBmacro\DC     {\kern.1em{::}\kern.1em} % symbol for ::
\defCWEBmacro\PA     {\mathbin{.*}}           % symbol for .*
\defCWEBmacro\MGA    {\mathbin{\MG*}}         % symbol for ->*
\defCWEBmacro\this   {\&{this}}

% \newbox  \bak    % backspace one em
% \newbox  \bakk   % backspace two ems
%
% \setbox\bak =\hbox to -1em{}
% \setbox\bakk=\hbox to -2em{}

\newcount\CWEBind  % current indentation in ems

\defCWEBmacro\1%     indent one more notch
  {\global\advance\CWEBind by 1
   \hangindent\CWEBind em}

\defCWEBmacro\2%     indent one less notch
  {\global\advance\CWEBind by -1 }

\defCWEBmacro\3#1%   optional break within a statement
  {\hfil
   \penalty#10
   \hfilneg}

\defCWEBmacro\4%   backspace one notch
  {\hbox to -1em{}}

\defCWEBmacro\5%   optional break
  {\hfil
   \penalty-1
   \hfilneg
   \kern2.5em
   \hbox to -2em{}%
   \ignorespaces}

\defCWEBmacro\6%   forced break
   {\ifmmode
    \else
      \par
      \hangindent\CWEBind em
      \noindent
      \kern\CWEBind em
      \hbox to -2em{}%
      \ignorespaces
    \fi}

\defCWEBmacro\7%   forced break and a little extra space
  {\Y
   \6}

\defCWEBmacro\8%   no indentation
  {\hskip-\CWEBind em
   \hskip 2em}

\defCWEBmacro\9#1%
  {}

\newcount\gdepth  % depth of current major group, plus one
\newcount\secpagedepth
\secpagedepth=3   % page breaks will occur for depths -1, 0, and 1

% \newtoks\gtitle % title of current major group
% \newskip\intersecskip
% \intersecskip=12pt minus 3pt % space between sections

% \let\yskip=\smallskip

\defCWEBmacro\?%
  {\mathrel?}

% \def\note#1#2.%
%   {\Y\noindent
%    {\hangindent2em\baselineskip10pt\eightrm#1~#2.\par}}

\defCWEBmacro\lapstar%
  {\rlap{*}}

% \def\stsec%
%   {\rightskip=0pt % get out of C mode (cf. \B)
%    \sfcode`;=1500
%    \pretolerance 200
%    \hyphenpenalty 50
%    \exhyphenpenalty 50
%    \noindent{\let\*=\lapstar\bf\secstar.\quad}}
%
% \let\startsection=\stsec

\defCWEBmacro\defin#1%
  {\global\advance\CWEBind by 2 \1\&{#1 } } % begin `define' or `format'

% \def\A% xref for doubly defined section name
%   {\note{See also section}}
%
% \def\As% xref for multiply defined section name
%   {\note{See also sections}}

\defCWEBmacro\B%
 {\rightskip=0pt plus 100pt minus 10pt % go into C mode
  \sfcode`;=3000
  \pretolerance 10000
  \hyphenpenalty 1000 % so strings can be broken (discretionary \ is inserted)
  \exhyphenpenalty 10000
  \global\CWEBind=2 \1\ \unskip}

\defCWEBmacro\C#1%
  {\5\5\quad$/\ast\,${\cmntfont #1}$\,\ast/$}

% \let\SHC\C % "// short comments" treated like "/* ordinary comments */"

\defCWEBmacro\SHC#1%
  {\5\5\quad$//\,${\cmntfont#1}}

% \def\C#1{\5\5\quad$\triangleright\,${\cmntfont#1}$\,\triangleleft$}
% \def\SHC#1{\5\5\quad$\diamond\,${\cmntfont#1}}

\defCWEBmacro\D% macro definition
  {\defin{\#define}}

\letCWEBmacro\E=\equiv % equivalence sign

% \def\ET% conjunction between two section numbers
%   { and~}
%
% \def\ETs% conjunction between the last two of several section numbers
%   {, and~}

\defCWEBmacro\F% format definition
  {\defin{format}}

\letCWEBmacro\G = \ge % greater than or equal sign

% \H is long Hungarian umlaut accent

\letCWEBmacro\I = \ne % unequal sign

\defCWEBmacro\J% TANGLE's join operation
  {\.{@\&}}

% \let\K== % assignment operator

\letCWEBmacro\K = \leftarrow % "honest" alternative to standard assignment operator

% \L is Polish letter suppressed-L

% \outer\def\M#1%
%   {\MN{#1}%
%    \ifon
%      \vfil
%      \penalty-100
%      \vfilneg % beginning of section
%      \vskip\intersecskip
%      \startsection
%     \ignorespaces}
%
% \outer\def\N#1#2#3.%
%   {\gdepth=#1%
%    \gtitle={#3}%
%    \MN{#2}% beginning of starred section
%    \ifon
%      \ifnum#1<\secpagedepth
%        \vfil
%        \eject % force page break if depth is small
%      \else
%        \vfil
%        \penalty-100
%        \vfilneg
%        \vskip\intersecskip
%      \fi
%    \fi
%    \message{*\secno}% progress report
%    \edef\next%
%      {\write\cont % write to contents file
%         {\ZZ{#3}{#1}{\secno}{\noexpand\the\pageno}}}%
%    \next % \ZZ{title}{depth}{sec}{page}
%    \ifon
%      \startsection
%      {\bf#3.\quad}%
%      \ignorespaces}
%
% \def\MN#1%
%   {\par % common code for \M, \N
%    {\xdef\secstar{#1}%
%     \let\*=\empty
%     \xdef\secno{#1}}% remove \* from section name
%    \ifx\secno\secstar
%      \onmaybe
%    \else
%      \ontrue
%    \fi
%    \mark{{{\tensy x}\secno}{\the\gdepth}{\the\gtitle}}}
%
% each \mark is {section reference or null}{depth plus 1}{group title}

% \O is Scandinavian letter O-with-slash
% \P is paragraph sign

\defCWEBmacro\Q  {\note{This code is cited in section}}  % xref for mention of a section
\defCWEBmacro\Qs {\note{This code is cited in sections}} % xref for mentions of a section

% \S is section sign

\defCWEBmacro\T#1%
  {\leavevmode % octal, hex or decimal constant
   \hbox
     {$\def\?{\kern.2em}%
      \def\$##1{\egroup_{\,\rm##1}\bgroup}% suffix to constant
      \def\_{\cdot 10^{\aftergroup}}% power of ten (via dirty trick)
      \let\~=\oct
      \let\^=\hex
      {#1}$}}

\defCWEBmacro\U  {\note{This code is used in section}} % xref for use of a section
\defCWEBmacro\Us {\note{This code is used in sections}} % xref for uses of a section

\letCWEBmacro\R  = \lnot % logical not
\letCWEBmacro\V  = \lor  % logical or
\letCWEBmacro\W  = \land % logical and

% defined later on
%
% \def\X#1:#2\X%
%   {\ifmmode
%      \gdef\XX{\null$\null}%
%    \else
%      \gdef\XX{}%
%    \fi % section name
%    \XX$\langle\,${#2\eightrm\kern.5em#1}$\,\rangle$\XX}

\unprotect

\def\theCWEByskip {\blank[\v!small]}
\def\theCWEBvskip {\blank[\v!big]}

\protect

\defCWEBmacro\Y%
  {\par
   \yskip}

\defCWEBmacro\yskip%
  {\theCWEByskip}

\letCWEBmacro\Z  = \le
% \letCWEBmacro\ZZ = \let % now you can \write the control sequence \ZZ
\letCWEBmacro\*  = *

\defCWEBmacro\oct%
  {\hbox{$^\circ$\kern-.1em\it\aftergroup\?\aftergroup}}

\defCWEBmacro\hex%
  {\hbox{$^{\scriptscriptstyle\#}$\tt\aftergroup}}

\defCWEBmacro\vb#1%
  {\leavevmode
   \hbox
     {\kern.2\CWEBpt
      \vrule
      \vtop
        {\vbox
           {\hrule
            \hbox{\strut\kern.2\CWEBpt\.{#1}\kern.2\CWEBpt}}
         \hrule}%
      \vrule
      \kern.2\CWEBpt}} % verbatim string

\def\onmaybe%
  {\let\ifon=\maybe}

\let\maybe=\iftrue

\newif\ifon

% \newif\iftitle
% \newif\ifpagesaved
%
% \def\lheader%
%   {\mainfont
%    \the\pageno
%    \eightrm
%    \qquad
%    \grouptitle
%    \hfill
%    \title
%    \qquad
%    \mainfont
%    \topsecno} % top line on left-hand pages
%
% \def\rheader%
%   {\mainfont
%    \topsecno
%    \eightrm
%    \qquad
%    \title
%    \hfill
%    \grouptitle
%    \qquad
%    \mainfont
%    \the\pageno} % top line on right-hand pages
%
% \def\grouptitle
%   {\let\i=I
%    \let\j=J
%    \uppercase\expandafter{\expandafter\takethree\topmark}}
%
% \def\topsecno%
%   {\expandafter\takeone\topmark}
%
% \def\takeone   #1#2#3{#1}
% \def\taketwo   #1#2#3{#2}
% \def\takethree #1#2#3{#3}
%
% \def\nullsec%
%   {\eightrm
%    \kern-2em} % the \kern-2em cancels \qquad in headers
%
% \let\page=\pagebody % \def\page {\box255 }
% \raggedbottom       % \normalbottom % faster, but loses plain TeX footnotes
%
% \def\normaloutput#1#2#3%
%   {\shipout\vbox
%      {\ifodd
%         \pageno
%         \hoffset=\pageshift
%       \fi
%       \vbox to \fullpageheight
%         {\iftitle
%            \global\titlefalse
%          \else
%            \hbox to \pagewidth
%              {\vbox to 10pt{}%
%               \ifodd\pageno #3\else#2\fi}
%          \fi
%         \vfill#1}} % parameter #1 is the page itself
%    \global\advance\pageno by 1}
%
% \gtitle={\.{CWEB} output} % this running head is reset by starred sections
%
% \mark{\noexpand\nullsec0{\the\gtitle}}
%
% \def\title%
%   {\expandafter\uppercase\expandafter{\jobname}}
%
% \def\topofcontents%
%   {\centerline{\titlefont\title}
%    \vskip.7in
%    \vfill} % this material will start the table of contents page

\def\botofcontents%
  {\vfill
   \centerline{\covernote}} % this material will end the table of contents page

\def\covernote%
  {}

% some leftover

\defCWEBmacro\contentspagenumber{0} % default page number for table of contents

% \newdimen\pagewidth      \pagewidth      = 158mm % the width of each page
% \newdimen\pageheight     \pageheight     = 223mm % the height of each page
% \newdimen\fullpageheight \fullpageheight = 240mm % page height including headlines
% \newdimen\pageshift      \pageshift      = 0in   % shift righthand pages wrt lefthand ones
%
% \def\magnify#1%
%   {\mag=#1
%    \pagewidth=6.5truein
%    \pageheight=8.7truein
%    \fullpageheight=9truein
%    \setpage}
%
% \def\setpage%
%   {\hsize\pagewidth
%    \vsize\pageheight} % use after changing page size
%
% \def\contentsfile  {\jobname.toc} % file that gets table of contents info
% \def\readcontents  {\input \contentsfile}
% \def\readindex     {\input \jobname.idx}
% \def\readsections  {\input \jobname.scn}
%
% \newwrite\cont
% \output{\setbox0=\page % the first page is garbage
% \openout\cont=\contentsfile
% \write\cont{\catcode `\noexpand\@=11\relax}   % \makeatletter
% \global\output{\normaloutput\page\lheader\rheader}}
% \setpage
% \vbox to \vsize{} % the first \topmark won't be null

\defCWEBdummy\magnify#1%  magnify the page
  {}

\defCWEBmacro\ch%
  {\note{The following sections were changed by the change file:}
   \let\*=\relax}

% \newbox\sbox % saved box preceding the index
% \newbox\lbox % lefthand column in the index
%
% \def\inx%
%   {\par\vskip6pt plus 1fil % we are beginning the index
%    \def\page{\box255 }
%    \normalbottom
%    \write\cont{} % ensure that the contents file isn't empty
%    \write\cont{\catcode `\noexpand\@=12\relax}   % \makeatother
%    \closeout\cont % the contents information has been fully gathered
%    \output
%      {\ifpagesaved
%         \normaloutput{\box\sbox}\lheader\rheader
%       \fi
%       \global\setbox\sbox=\page
%       \global\pagesavedtrue}
%    \pagesavedfalse
%    \eject % eject the page-so-far and predecessors
%    \setbox\sbox\vbox{\unvbox\sbox} % take it out of its box
%    \vsize=\pageheight
%    \advance\vsize by -\ht\sbox % the remaining height
%    \hsize=.5\pagewidth
%    \advance\hsize by -10pt
%    % column width for the index (20pt between cols)
%    \parfillskip 0pt plus .6\hsize % try to avoid almost empty lines
%    \def\lr{L} % this tells whether the left or right column is next
%    \output
%      {\if L\lr
%         \global\setbox\lbox=\page
%         \gdef\lr{R}
%       \else
%         \normaloutput
%           {\vbox to\pageheight
%              {\box\sbox
%               \vss
%               \hbox to\pagewidth{\box\lbox\hfil\page}}}
%           \lheader
%           \rheader
%    \global\vsize\pageheight\gdef\lr{L}\global\pagesavedfalse\fi}
%    \message{Index:}
%    \parskip 0pt plus .5pt
%    \outer\def\I##1, {\par\hangindent2em\noindent##1:\kern1em} % index entry
%    \def\[##1]{$\underline{##1}$} % underlined index item
%    \rm
%    \rightskip0pt plus 2.5em
%    \tolerance 10000
%    \let\*=\lapstar
%    \hyphenpenalty 10000
%    \parindent0pt
%    \readindex}
%
% \def\fin%
%   {\par\vfill\eject % this is done when we are ending the index
%    \ifpagesaved\null\vfill\eject\fi % output a null index column
%    \if L\lr\else\null\vfill\eject\fi % finish the current page
%    \parfillskip 0pt plus 1fil
%    \def\grouptitle{NAMES OF THE SECTIONS}
%    \let\topsecno=\nullsec
%    \message{Section names:}
%    \output={\normaloutput\page\lheader\rheader}
%    \setpage
%    \def\note##1##2.{\quad{\eightrm##1~##2.}}
%    \def\Q{\note{Cited in section}} % crossref for mention of a section
%    \def\Qs{\note{Cited in sections}} % crossref for mentions of a section
%    \def\U{\note{Used in section}} % crossref for use of a section
%    \def\Us{\note{Used in sections}} % crossref for uses of a section
%    \def\I{\par\hangindent 2em}\let\*=*
%    \readsections}
%
% \def\con%
%   {\par\vfill\eject % finish the section names
%    %\ifodd\pageno\else\titletrue\null\vfill\eject\fi % for duplex printers
%    \rightskip     = 0pt
%    \hyphenpenalty = 50
%    \tolerance     = 200
%    \setpage
%    \output={\normaloutput\page\lheader\rheader}
%    \titletrue % prepare to output the table of contents
%    \pageno=\contentspagenumber
%    \def\grouptitle{TABLE OF CONTENTS}
%    \message{Table of contents:}
%    \topofcontents
%    \line{\hfil Section\hbox to3em{\hss Page}}
%    \let\ZZ=\contentsline
%    \readcontents\relax % read the contents info
%    \botofcontents
%    \end} % print the contents page(s) and terminate
%
% \def\contentsline#1#2#3#4%
%   {\ifnum#2=0
%      \smallbreak
%    \fi
%    \line{\consetup{#2}#1
%    \rm\leaders\hbox to .5em{.\hfil}\hfil\ #3\hbox to3em{\hss#4}}}
%

\defCWEBmacro\consetup#1%
  {\ifcase#1 \bf        % depth -1 (@**)
   \or                  % depth  0 (@*)
   \or       \hskip2em  % depth  1 (@*1)
   \or       \hskip4em  % depth  2 (@*2)
   \or       \hskip6em  % depth  3 (@*3)
   \or       \hskip8em  % depth  4 (@*4)
   \or       \hskip10em % depth  5 (@*5)
   \else     \hskip12em
   \fi}                 % depth  6 or more

\defCWEBdummy \inx    {} % index
\defCWEBdummy \fin    {} % finish
\defCWEBdummy \con    {} % table of contents and finish

\defCWEBdummy \noinx  {} % no indexes or table of contents
\defCWEBdummy \nosecs {} % no index of section names or table of contents
\defCWEBdummy \nocon  {} % no table of contents

\defCWEBmacro\,%
  {\relax
   \ifmmode
     \mskip\thinmuskip
   \else
     \thinspace
   \fi}

% \def\noinx%
%   {\let\inx=\end}
%
% \def\nosecs%
%   {\let\FIN=\fin
%    \def\fin%
%      {\let\parfillskip=\end
%       \FIN}}
%
% \def\nocon%
%   {\let\con=\end}
%
% \newcount\twodigits
%
% \def\hours%
%   {\twodigits=\time
%    \divide\twodigits by 60
%    \printtwodigits
%    \multiply\twodigits by -60
%    \advance\twodigits by \time
%    :\printtwodigits}
%
% \def\gobbleone1{}
%
% \def\printtwodigits%
%   {\advance\twodigits by 100
%    \expandafter\gobbleone\number\twodigits
%    \advance\twodigits by -100 }
%
% \def\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}
%
% \def\datethis%
%   {\def\startsection%
%      {\leftline{\sc\today\ at \hours}
%       \bigskip
%       \let\startsection=\stsec
%       \stsec}}
%
% \def\datecontentspage%
%   {\def\topofcontents%
%      {\leftline{\sc\today\ at \hours}
%        \bigskip
%        \centerline{\titlefont\title}
%        \vfill}}

\defCWEBdummy\datethis         {} % say `\datethis' in limbo, to get your listing timestamped before section 1
\defCWEBdummy\datecontentspage {} % timestamps the contents page

\defCWEBmacro\TeX%
  {{\ifmmode\it\fi
    \leavevmode
    \hbox{T\kern-.1667em\lower.424ex\hbox{E}\hskip-.125em X}}}

% alternative implementation

\newif\ifCWEBnotes

\defCWEBmacro\Q  {\CWEBnotesfalse \note{This code is cited in section}}  % xref for mention of a section
\defCWEBmacro\Qs {\CWEBnotestrue  \note{This code is cited in sections}} % xref for mentions of a section

\defCWEBmacro\U  {\CWEBnotesfalse \note{This code is used in section}}  % xref for use of a section
\defCWEBmacro\Us {\CWEBnotestrue  \note{This code is used in sections}} % xref for uses of a section

\defCWEBmacro\A  {\CWEBnotesfalse \note{See also section}}  % xref for doubly defined section name
\defCWEBmacro\As {\CWEBnotestrue  \note{See also sections}} % xref for multiply defined section name

\defCWEBmacro\ET% conjunction between two section numbers
  { and~}

\defCWEBmacro\ETs% conjunction between the last two of several section numbers
  {, and~}

%\def\processCWEBsectionnumbers[#1]%
%  {\bgroup
%   \def\CWEBcomma%
%     {\def\CWEBcomma{, }}%
%   \def\docommand##1%
%     {\bgroup
%      \def\[####1]{####1}%
%      \xdef\CWEBreference{##1}%
%      \egroup
%      \CWEBcomma{\naar{\donottest{##1}}[web:\CWEBreference]}}%
%   \processcommalist[{#1}]\docommand
%   \egroup}

% \def\processCWEBsectionnumbers[#1]%
%   {\bgroup
%    \def\CWEBcomma%
%      {\def\CWEBcomma{, }}%
%    \def\docommand##1%
%      {\bgroup
%       \def\(####1){####1}%
%       \xdef\CWEBreference{##1}%
%       \egroup
%       \CWEBcomma
%       {\localcolortrue\naar{\donottest{##1}}[web:\CWEBreference]}}%
%    \bgroup
%    \def\[##1]{\(##1)}\let\(=\relax\xdef\CWEBreferences{#1}%
%    \egroup
%    \unexpanded\def\(##1){\[##1]}%
%    \processcommacommand[\CWEBreferences]\docommand
%    \egroup}

\def\processCWEBsectionnumbers[#1]%
  {\bgroup
   \def\CWEBcomma%
     {\def\CWEBcomma{, }}%
   \def\docommand##1%
     {\bgroup
      \def\[####1]{####1}%
      \xdef\CWEBreference{##1}%
      \egroup
      \CWEBcomma{\localcolortrue\goto{\donottest{##1}}[web:\CWEBreference]}}%
   \processlist{(}{)}{,}\docommand(#1)
   \egroup}

\def\processCWEBsectionnotes%
  {\catcode`\s=12
   \doprocessCWEBsectionnotes}

\def\doprocessCWEBsectionnotes#1.%
  {\ifCWEBnotes
     \def\next##1\ET##2##3.%
       {\processCWEBsectionnumbers[##1]%
        \if##2s%
          {, and~\goto{##3}[web:##3]}%
        \else
          { and~\goto{##2##3}[web:##2##3]}%
        \fi}%
      \next#1.%
   \else
     \goto{#1}[web:#1]%
   \fi
   \afterCWEBnote % inside group!
   \egroup}

\let\afterCWEBnote=\relax

\defCWEBmacro\note#1%
  {\bgroup
   \Y\noindent
   \def\afterCWEBnote{\par}%
   \hangindent2em
   %\baselineskip10pt
   \eightrm#1~\processCWEBsectionnotes}

\def\oldCWEBmacroX#1:#2\X% original
  {\ifmmode
     \gdef\XX{\null$\null}%
   \else
     \gdef\XX{}%
   \fi % section name
   \XX$\langle\,${#2\eightrm\kern.5em#1}$\,\rangle$\XX}

\defCWEBmacro\ATH%
  {\oldCWEBmacroX\kern-.5em:Preprocessor definitions\X}

\def\newCWEBmacroX#1:#2\X% original
  {\ifmmode
     \gdef\XX{\null$\null}%
   \else
     \gdef\XX{}%
   \fi % section name
   \XX$\langle\,$%
   {#2\eightrm\kern.5em\processCWEBsectionnumbers[{#1}]}%
   $\,\rangle$\XX}

\defCWEBmacro\X#1:#2\X%
  {\newCWEBmacroX#1:#2\X}

\definemarking[CWEBfilename]
\definemarking[CWEBsectiontitle]
\definemarking[CWEBsectionnumber]
\definemarking[CWEBsectiondepth]

\defCWEBmacro\M#1%
  {\MN{#1}%
   \ifon
     \vfil
     \penalty-100
     \vfilneg % beginning of section
     \theCWEBvskip
     \startsection
     \pagereference[web:#1]%
     \expanded{\marking[CWEBsectionnumber]{\secno}}%
     \expanded{\marking[CWEBsectiondepth]{\the\gdepth}}%
     \ignorespaces}

\defCWEBmacro\N#1#2#3.%
  {\gdepth=#1%
   \MN{#2}% beginning of starred section
   \ifon
     \ifnum#1<\secpagedepth
       \vfil
       \eject % force page break if depth is small
     \else
       \vfil
       \penalty-100
       \vfilneg
       \theCWEBvskip
     \fi
   \fi
   \message{*\secno}% progress report
   \makesectionformat % context
   \convertargument#3\to\ascii
   \edef\next%
     {\write\CWEBcont % write to contents file
        {\string\ZZ{\ascii}{#1}{\secno}%
           {\sectionformat::\noexpand\userfolio}{\noexpand\realfolio}}}%
   \next % \ZZ{title}{depth}{sec}{page}
   \ifon
     \startsection
     \pagereference[web:#2]%
     \marking[CWEBsectiontitle] {#3}%
     \expanded{\marking[CWEBsectionnumber]{\secno}}%
     \expanded{\marking[CWEBsectiondepth]{\the\gdepth}}%
     {\bf#3.\quad}%
     \ignorespaces}

\defCWEBmacro\MN#1%
  {\par % common code for \M, \N
   {\xdef\secstar{#1}%
    \let\*=\empty
    \xdef\secno{#1}}% remove \* from section name
   \ifx\secno\secstar
     \onmaybe
   \else
     \ontrue
   \fi}

\newif\iflinktoCWEBfile

\def\setCWEBlinkfile#1%
  {\linktoCWEBfiletrue
   \def\otherCWEBfile{#1}}

\unprotect

\def\gotoCWEBsection#1[#2]%
  {\iflinktoCWEBfile
     \bgroup
       \setupinteraction[\c!color=,\c!style=]%
       \let\savedreferenceprefix=\referenceprefix
       \localcolortrue
       \goto{#1}[\otherCWEBfile::\savedreferenceprefix web:#2]%
     \egroup
   \else
     #1%
   \fi}

\protect

\defCWEBmacro\startsection%
  {\rightskip=0pt % get out of C mode (cf. \B)
   \sfcode`;=1500
   \pretolerance 200
   \hyphenpenalty 50
   \exhyphenpenalty 50
   \noindent
   \bgroup
   \let\*=\lapstar
   \gotoCWEBsection{\bf\secstar.\quad}[\secno]%
   \egroup}

\def\ignoreCWEBinput%
  {\let\normalinput=\input
   \def\input ##1 %
     {\let\input=\normalinput}}

\def\loadCWEBmacros#1%
  {\let\oldN=\N
   \def\N{\bgroup\setbox0=\vbox\bgroup\endinput}%
   \ignoreCWEBinput
   \ReadFile{#1.tex}%
   \egroup\egroup
   \let\N=\oldN}

\def\resetCWEBcontext%
  {\catcode`\|=12  % used in context discretionaries
   \everypar{}     % used for context indentation and floats
   \parskip=0pt    % no stretch between cweb paragraphs
   \parindent=1em} % is related to cweb backspace etc

\newwrite\CWEBcont

\def\processCWEBsource #1 %
  {\bgroup
   \resetCWEBcontext
   \activateCWEB
   \ignoreCWEBinput
   \immediate\openout\CWEBcont=#1.toc
   \write\CWEBcont{\noexpand\unprotect}
   \message{Source:}
   \marking[CWEBfilename]{#1}
   \ReadFile{#1.tex}\relax
   \write\CWEBcont{\noexpand\protect}
   \closeout\CWEBcont
   \par
   \egroup}

\def\resetCWEBindexentry%
  {\xdef\currentCWEBindexentry{}}

\def\showCWEBindexentry#1% can be redefined
  {\theCWEBvskip
   \vskip3\lineheight
   \goodbreak
   \vskip-3\lineheight
   {\pagereference[web:#1]\bf#1}%
   \theCWEBvskip}

\def\checkCWEBindexentry#1%
  {\bgroup
   \def\\##1{##1}%  a dummy that also removes the {}
   \def\|##1{##1}%  another dummy
   \def\.##1{*##1}% and another (the typewriter one)
   \def\&##1{##1}%  and a last one
   \def\9##1{##1}%  hold this one
   \catcode`*=11
   \expandafter\def\expandafter\entry\expandafter{#1}%
   \convertcommand\entry\to\ascii
   \expanded{\FINDFIRSTCHARACTER{\ascii}}%
   \doifnot{\currentCWEBindexentry}{\firstcharacter}
     {\doifnot{\firstcharacter}{*} % signal for \firstbunch
        {\global\let\currentCWEBindexentry=\firstcharacter
         \showCWEBindexentry{\currentCWEBindexentry}}}%
   \egroup}

\def\theCWEBbeforeindex {\startcolumns}
\def\theCWEBafterindex  {\stopcolumns}

\def\processCWEBindex #1 %
  {\bgroup
   \resetCWEBcontext
   \activateCWEB
   \resetCWEBindexentry
   \def\I##1, %
     {\par
      \checkCWEBindexentry{##1}%
      \hangindent2em
      \noindent##1:\kern1em%
      \def\next####1.%
        {\processCWEBsectionnumbers[{####1}]}%
      \next}%
   \def\[##1]%
     {$\underline{##1}$}%
   \let\*=\lapstar
   \parfillskip 0pt plus .6\hsize % try to avoid almost empty lines
%   \parskip 0pt plus .5pt
   \rightskip0pt plus 2.5em
   \tolerance 10000
   \hyphenpenalty 10000
   \parindent0pt
   \message{Index:}
   \marking[CWEBfilename]    {#1}
   \marking[CWEBsectiontitle] {index}
   \marking[CWEBsectionnumber]{}
   \marking[CWEBsectiondepth]{}
   \loadCWEBmacros{#1}
   \theCWEBbeforeindex
   \ReadFile{#1.idx}\relax
   \theCWEBafterindex
   \par
   \egroup}

\def\processCWEBsections #1 %
  {\bgroup
   \resetCWEBcontext
   \activateCWEB
   \loadCWEBmacros{#1}
   \parfillskip = 0pt plus 1fil
   \parindent   = 0pt
   \let\topsecno=\nullsec
   \def\note##1%
     {\quad
      \bgroup
      \eightrm
      ##1~\processCWEBsectionnotes}
   \def\Q {\CWEBnotesfalse \note{Cited in section}}  % crossref for mention of a section
   \def\Qs{\CWEBnotestrue  \note{Cited in sections}} % crossref for mentions of a section
   \def\U {\CWEBnotesfalse \note{Used in section}}   % crossref for use of a section
   \def\Us{\CWEBnotestrue  \note{Used in sections}}  % crossref for uses of a section
   \def\I {\par\hangindent 2em}%
   \let\*=*
   \message{Section names:}
   \marking[CWEBfilename]    {#1}
   \marking[CWEBsectiontitle] {sections}
   \marking[CWEBsectionnumber]{}
   \marking[CWEBsectiondepth]{}
   \loadCWEBmacros{#1}
   \ReadFile{#1.scn}\relax
   \par
   \botofcontents
   \par
   \egroup}

\def\processCWEBcontents #1 %
  {\bgroup
   \resetCWEBcontext
   \activateCWEB
   \loadCWEBmacros{#1}
   \rightskip     = 0pt
   \hyphenpenalty = 50
   \tolerance     = 200
   \parindent     = 0pt
   \line{\hfil Section\hbox to3em{\hss Page}}
   \let\ZZ=\contentsline
   \message{Table of contents:}
   \marking[CWEBfilename]    {#1}
   \marking[CWEBsectiontitle] {table of contents}
   \marking[CWEBsectionnumber]{}
   \marking[CWEBsectiondepth]{}
   \loadCWEBmacros{#1}
   \ReadFile{#1.toc}\relax
   \par
   \egroup}

\defCWEBmacro\contentsline#1#2#3#4#5%
  {\ifnum#2=0
     \smallbreak
   \fi
   \line{\consetup{#2}#1
   \rm
   \leaders\hbox to .5em{.\hfil}\hfil\
   {\localcolortrue\goto{#3}[web:#3]}%  below: \gotorealpage ? should be changed
   \hbox to3em{\localcolortrue\hss\gotorealpage{}{}{#5}{\translatednumber[#4]\presetgoto}}}}

%D A last hack, needed because a file can overload of the
%D above. (Some day: a check like \type{\ifx#1\CWEBdefined}.)

\def\outer#1#2%
  {\ifx#2\undefined
     \expandafter#1\expandafter#2%
   \else
     \expandafter#1\expandafter\ThrowAway
   \fi}

\endinput
