% Dmitri Pavlov's Plain TeX macros
% Copyright 2017, 2018 Dmitri Pavlov

% Remove \outer
\edef\inewcount{\noexpand\csname newcount\endcsname}
\edef\inewdimen{\noexpand\csname newdimen\endcsname}
\edef\inewskip{\noexpand\csname newskip\endcsname}
\edef\inewmuskip{\noexpand\csname newmuskip\endcsname}
\edef\inewbox{\noexpand\csname newbox\endcsname}
\edef\inewhelp{\noexpand\csname newhelp\endcsname}
\edef\inewtoks{\noexpand\csname newtoks\endcsname}
\edef\inewread{\noexpand\csname newread\endcsname}
\edef\inewwrite{\noexpand\csname newwrite\endcsname}
\edef\inewfam{\noexpand\csname newfam\endcsname}
\edef\inewlanguage{\noexpand\csname newlanguage\endcsname}
\edef\inewinsert{\noexpand\csname newinsert\endcsname}
\edef\inewif{\noexpand\csname newif\endcsname}

\input plain-utf8

\newif\ifscroll % scroll vs codex
\newif\ifsuppressunusedbib % suppress unused bibliography items?

% Diagonostics
\tracinglostchars=2
\def\print#1{\immediate\write16{#1}}
\def\printerr#1{\immediate\write17{#1}}
\def\warningline#1#2{\printerr{! #2}\printerr{l.#1}\printerr{}}
\def\ewarningline#1#2#3{\printerr{! #2}\printerr{l.#1 #3}\printerr{}}
\def\warning{\warningline{\the\inputlineno}}
%\let\warning\errmessage % turn warnings into errors

% Syntactic macros
\long\def\gobble#1{}
\ifx\gobbleinit\undefined{\long\gdef\gobbleinit#1\par{}}\fi
\def\expand#1{\edef\expandmacro{#1}\expandmacro\let\expandmacro\undefined}
\def\setetok#1#2{\expand{\noexpand#1{#2}}}
\def\expandtoks#1{\expandafter\edef\expandafter\expandmacro\expandafter{\the#1}#1\expandafter{\expandmacro}}
\def\appendexpand#1#2{\setetok#1{\the#1#2}}
\long\def\append#1#2{#1\expandafter{\the#1#2}}
\long\def\appendtoksexpand#1#2{#1\expandafter\expandafter\expandafter{\expandafter\the\expandafter#1\the#2}}
\long\def\appendonceexpand#1#2{#1\expandafter\expandafter\expandafter{\expandafter\the\expandafter#1#2}}

% Macros that use \special, known to work with xdvi, dvips, dvipdfm
\let\printlink\gobble
%\let\printlink\print % print links and anchors
\def\link#1#2{\special{html:<a href="#1">}\lhighlight{#2}\special{html:</a>}}
\def\llink#1{\printlink{llink #1}\link{\ohash#1}}
\catcode`\#=11 \def\ohash{#}\catcode`\#=6
\catcode`\&=11 \def\ampersand{&}\catcode`\&=4
\def\anchor#1#2{\printlink{anchor #1 #2}\special{html:<a name="#1">}#2\special{html:</a>}}
\def\highlight#1#2{\leavevmode\special{color push rgb #1}#2\special{color pop}}
\def\setpapersize#1#2{\special{papersize=\the#1,\the#2}} % \number#1 sp triggers bugs in dvips and does not work with dvipdfm(x)
\def\dumpbox#1#2#3{\shipout\vbox{\setpapersize{#1}{#2}\unvbox#3}}
\def\mps#1{\epsfbox{#1}}
\def\metadata#1#2{\special{pdf: docinfo << /Title (#1) /Author (#2) >>}}
\def\src{\special{src:\the\inputlineno\space\jobname.tex}} % for proper match between bibliographic references and source code

% A simplified version of the epsfbox macro from epsf.tex, exclusively for METAPOST output, with HiResBoundingBox
% Normally should be invoked through \mps, which works also with PDF
\newread\epsffilein
\newif\ifepsfbbfound\inewif\ifepsffilecont
\newdimen\epsfxsize\inewdimen\epsfysize
\newdimen\pspoints\pspoints1bp
\let\runmp\errmessage % will be set to \warning if the METAPOST file cannot be compiled
\def\epsfbox#1{\openin\epsffilein=#1 \ifeof\epsffilein\runmp{Could not open file #1}\else
	{\def\do##1{\catcode`##1=12}\dospecials\catcode`\ =10\epsffileconttrue
		\epsfbbfoundfalse
		\loop\read\epsffilein to\epsffileline \ifeof\epsffilein\epsffilecontfalse\else\expandafter\epsfaux\epsffileline :. \\\fi\ifepsffilecont\repeat
		\ifepsfbbfound\else\errmessage{No HiResBoundingBox comment found in file #1}\fi}%
	\closein\epsffilein
	\epsfysize\epsfury\pspoints \advance\epsfysize-\epsflly\pspoints
	\epsfxsize\epsfurx\pspoints \advance\epsfxsize-\epsfllx\pspoints
	% We create a box with height and depth corresponding to the two vertical dimensions in the bounding box and width given by the total width
	\setbox0\hbox{\vbox to\epsfury\pspoints{\vfil\hbox to\epsfxsize{\dimen0=\epsfllx\pspoints \kern-\dimen0 \special{PSfile=#1}\hfil}}}%
	\dp0=\epsflly\pspoints \dp0=-\dp0
	\box0 \fi}
%	\hbox{\vbox to\epsfysize{\vfil\hbox to\epsfxsize{\special{psfile=#1}\hfil}}}}
% llx=\epsfllx\space lly=\epsflly\space urx=\epsfurx\space ury=\epsfury
%	    rwi=\number\epsftmp\space rhi=\number\epsfrsize
\catcode`\%=12 \def\epsfbblit{%%HiResBoundingBox} \catcode`\%=14
\let\dummybrace=} % to compensate for { on the previous line when it is read by \read
\def\epsfaux#1:#2\\{\def\testit{#1}\ifx\testit\epsfbblit \epsfgrab #2 . . . \\\epsffilecontfalse\epsfbbfoundtrue\fi}
\def\empty{}
\def\epsfgrab #1 #2 #3 #4 #5\\{\gdef\epsfllx{#1}\ifx\epsfllx\empty\epsfgrab #2 #3 #4 #5 .\\\else\gdef\epsflly{#2}\gdef\epsfurx{#3}\gdef\epsfury{#4}\fi} % gdef because epxfbox wraps us in a group

% pdfTeX completely ignores established conventions for \special
\newif\ifpdf \pdffalse \ifx\pdfoutput\undefined\else\ifx\pdfoutput\relax\else\ifnum\pdfoutput<1 \else\pdftrue\fi\fi\fi
\ifpdf
\pdfcompresslevel=0 % HTTP offers better compression methods anyway
\pdfobjcompresslevel=0
\def\pdflink#1#2{\leavevmode \lhighlight{\pdfstartlink user { /Subtype /Link /Border [0 0 0] /A << /S #1 >> }#2\pdfendlink}}
\def\llink#1{\pdflink{/GoTo /D (#1)}}
\def\link#1{\pdflink{/URI /URI (#1)}}
\def\anchor#1#2{\pdfdest name {#1} xyz #2}
\def\highlight#1#2{\leavevmode\pdfliteral{#1 rg}#2\pdfliteral{0 0 0 rg}}
\def\setpapersize#1#2{\pdfpagewidth#1 \pdfpageheight#2 }
\def\dumpbox#1#2#3{\setpapersize{#1}{#2}\shipout\box#3}
%\def\image#1{\pdfximage{#1.pdf}\pdfrefximage\pdflastximage}
\def\metadata#1#2{\pdfinfo{/Title (#1) /Author (#2)}}
\input supp-pdf.mkii % the only external dependence of DPMAC: a converter from METAPOST's output to PDF
\def\mps#1{\convertMPtoPDF{#1}{1}{1}}
%\chardef\makeMPintoPDFobject=1
\fi

% Embedded METAPOST
\newtoks\buffertoks
\def\addcode{\immediate\write\mpout}
\def\addunexpandedcode#1{{\toks0={#1}\addcode{\the\toks0}}}
\def\addcodebuffer#1{\edef\tmp{#1}\buffertoks\expandafter\expandafter\expandafter{\expandafter\the\expandafter\buffertoks\tmp}}
\def\addunexpandedcodebuffer#1{\buffertoks\expandafter{\the\buffertoks#1}}
\def\inlinemp{\begininlinemp\grabcode}
\def\grabcode{\catcode`\#=12 \endlinechar=10 
	\afterassignment\dumpcode\outtoks} % make sure the newline characters get written
\def\dumpcode{\addcode{\the\outtoks}\endinlinemp\gobble} % \gobble the newline with character code 10
\def\begininlinemp{\inimp\begingroup\catcode`\^=7 \iftypesetting\mps{\filestem.\the\figno}\let\addcode\gobble\fi \addcode{beginfig(\the\figno);}}
\def\endinlinemp{\addcode{endfig;}\addcode{}\endgroup\global\advance\figno1\relax}
\ifx\endprolog\undefined\let\endprolog\relax\fi

% Repair LaTeX damage
\def\plainfmtname{plain}\ifx\fmtname\plainfmtname\else
\edef\plainoutput{\the\output}
\global\chardef\itfam=4
\def\_{\leavevmode \kern.06em \vbox{\hrule width.3em}} % for LaTeX

\outputpenalty=0
\tracingstats=0
\newlinechar=-1
\maxdeadcycles=25
\showboxbreadth=5
\showboxdepth=3
\errorcontextlines=5
\overfullrule=5pt
%\hsize=6.5in
%\vsize=8.9in
\maxdepth=4pt
\parindent=20pt
\abovedisplayskip=12pt plus 3pt minus 9pt
\belowdisplayskip=12pt plus 3pt minus 9pt
\belowdisplayshortskip=7pt plus 3pt minus 4pt

\font\teni=cmmi10 % math italic
\font\seveni=cmmi7
\font\fivei=cmmi5
\font\tensy=cmsy10
\font\sevensy=cmsy7
\font\fivesy=cmsy5
\font\tenbf=cmbx10
\font\sevenbf=cmbx7
\font\fivebf=cmbx5
\font\tenrm=cmr10
\font\sevenrm=cmr7
\font\fiverm=cmr5
\font\tenit=cmti10
\font\tenex=cmex10
\font\tensl=cmsl10
\font\tentt=cmtt10

\catcode"18=12
\catcode`@=11
{
\global\let\end\@@end
\global\let\input\@@input
}
%\let\everymath\frozen@everymath
%\let\everydisplay\frozen@everydisplay
% copied from plain.tex:
\def\eqalign#1{\null\,\vcenter{\openup\jot\m@th
  \ialign{\strut\hfil$\displaystyle{##}$&$\displaystyle{{}##}$\hfil
      \crcr#1\crcr}}\,}
\catcode`@=12
%\def\line{\hbox to\hsize}
%\everymath{}
%\everydisplay{}
\fi

% AMS fonts: family 8, 9, 10
\font\tenmsa=msam10 \font\sevenmsa=msam7 \font\fivemsa=msam5 \newfam\msafam \textfont\msafam=\tenmsa \scriptfont\msafam=\sevenmsa \scriptscriptfont\msafam=\fivemsa % 8
\font\tenmsb=msbm10 \font\sevenmsb=msbm7 \font\fivemsb=msbm5 %\newfam\msbfam \textfont\msbfam=\tenmsb \scriptfont\msbfam=\sevenmsb \scriptscriptfont\msbfam=\fivemsb
%\def\Bbb{\fam\msbfam}
\font\teneufm=eufm10 \font\seveneufm=eufm7 \font\fiveeufm=eufm5 \newfam\eufmfam \textfont\eufmfam=\teneufm \scriptfont\eufmfam=\seveneufm \scriptscriptfont\eufmfam=\fiveeufm % 9
\def\frak{\fam\eufmfam}
\font\teneufb=eufb10 \font\seveneufb=eufb7 \font\fiveeufb=eufb5 \newfam\eufbfam \textfont\eufbfam=\teneufb \scriptfont\eufbfam=\seveneufb \scriptscriptfont\eufbfam=\fiveeufb % 10
\def\frakbf{\fam\eufbfam}
\font\teneurm=eurm10 \font\seveneurm=eurm7 \font\fiveeurm=eurm5 \newfam\eurmfam \textfont\eurmfam=\teneurm \scriptfont\eurmfam=\seveneurm \scriptscriptfont\eurmfam=\fiveeurm % 11
\def\eurm{\fam\eurmfam}
\font\teneurb=eurb10 \font\seveneurb=eurb7 \font\fiveeurb=eurb5 \newfam\eurbfam \textfont\eurbfam=\teneurb \scriptfont\eurbfam=\seveneurb \scriptscriptfont\eurbfam=\fiveeurb % 12
\def\eubf{\fam\eurbfam}
\font\teneusm=eusm10 \font\seveneusm=eusm7 \font\fiveeusm=eusm5 \newfam\eusmfam \textfont\eusmfam=\teneusm \scriptfont\eusmfam=\seveneusm \scriptscriptfont\eusmfam=\fiveeusm % 13
\def\eucal{\fam\eusmfam}
\font\teneusb=eusb10 \font\seveneusb=eusb7 \font\fiveeusb=eusb5 \newfam\eusbfam \textfont\eusbfam=\teneusb \scriptfont\eusbfam=\seveneusb \scriptscriptfont\eusbfam=\fiveeusb % 14
\def\eucalbf{\fam\eusbfam}
%\font\teneuex=euex10 \font\seveneuex=euex7 \newfam\euexfam \textfont\euexfam=\teneuex \scriptfont\euexfam=\seveneuex

\font\tenss=cmss10 \font\sevenss=cmss7 \font\fivess=cmss5 \newfam\ssfam \textfont\ssfam\tenss \scriptfont\ssfam\sevenss \scriptscriptfont\ssfam\fivess % 15
\def\sf{\fam\ssfam}

\font\tenbfit=cmbxti10
\font\twelvebf=cmbx12
\font\fourteenss=cmss14
\font\seventeenss=cmss17

\font\sevenex=cmex7
\font\sevenit=cmti7 \scriptfont\itfam=\sevenit
\font\tenmib=cmmib10
\font\fourteensy=cmsy14
\font\tenbsy=cmbsy10
\font\twelvebsy=cmbsy12

% Font style
\let\articletitle\seventeenss
\let\chaptertitle\twelvebf
\let\sectiontitle\tenbf
\let\subsectiontitle\tenbfit
\let\subsubsectiontitle\tenit
\let\contchaptertitle\tenbf % chapter titles in the table of contents
\let\contsectiontitle\tenrm % ditto for sections
\let\contsubsectiontitle\sevenrm % ditto for subsections
\let\contsubsubsectiontitle\fiverm % ditto for subsubsections
\let\parnumfont\tenrm % paragraph numbers
\let\parbackreffont\fiverm % back references at the end of paragraphs
\let\proclaimfont\tenbf
\let\prooffont\tenit
\let\mainfont\tenrm

% Formatting of draft comments
\font\tenbfit=cmbxti10
\def\lhighlight{} % in principle, links can be highlighted, but this is usually done by the renderer
\def\colorcomments#1#2{\highlight{#1}} % for screen
\def\boldcomments#1#2#3{\tenbfit[#2] #3\rm} % for printing drafts
\def\suppresscomments#1#2#3{} % for sharing drafts
\def\prohibitcomments#1#2#3{\errmessage{Draft comments are not allowed in the final version}} % for final versions

\ifx\format\undefined\else\format\fi % default paper size is letter
\ifx\comment\undefined\def\comment{\prohibitcomments}\fi

\newdimen\hmargin
\hmargin=1in
\newdimen\vmargin
\vmargin=1in
\newdimen\plaintextwidth
\plaintextwidth=6.5in
\newdimen\plaintextheight
\plaintextheight=8.9in

% Output routine for scrolls with variable height
\newdimen\totalht
\newdimen\totalwd
\def\shipbox#1{%
	\totalht\ht#1
	\advance\totalht2\vmargin
	\totalwd\wd#1
	\advance\totalwd2\hmargin
	\hoffset-1in
	\advance\hoffset\hmargin
	\voffset-1in
	\advance\voffset\vmargin
	\dumpbox\totalwd\totalht{#1}}

% Contents
\newtoks\cont
\def\contents{\begingroup\suppressbackreftrue\let\anchor\gobble\the\cont\endgroup}
\let\printcont\gobble
%\let\printcont\print % print the table of contents
\def\contlinechapt#1#2{\printcont{#2}\smallskip\everypar{}\noindent{\contchaptertitle\llink{chapter.#1}{#2}}\par} % Link: contents to chapter
\def\contlinesect#1#2{\printcont{#1.  #2}\everypar{}\indent{\contsectiontitle\llap{#1.\enskip}\llink{section.#1}{#2}}\par} % Link: contents to section
\def\contlineunsect#1#2{\printcont{#2}\everypar{}\noindent{\contsectiontitle\llink{section.#1}{#2}}\par} % Link: contents to section
\def\contlinesubsect#1#2{\printcont{#1.  #2}\everypar{}\indent{\contsubsectiontitle{#1.\enskip}\llink{paragraph.#1}{#2}}\par} % Link: contents to subsection
\def\contlinesubsubsect#1#2{\printcont{#1.  #2}\everypar{}\indent\indent\indent{\contsubsubsectiontitle\llap{#1.\enskip}\llink{paragraph.#1}{#2}}\par} % Link: contents to subsubsection
\def\addcont#1#2#3{\append\cont{#1}\appendexpand\cont{{#2}}\append\cont{{#3}}}

% Chapters
\newif\ifpresec \presecfalse % true if we are in a chapter, but before its first section
\def\chapter#1\par{%
	\def\chapname{#1}%
	\parn0
	\subparn0
	\presectrue
	\numbfalse
	\addcont\contlinechapt\chapname{#1}%
	\curverb{Chapter~}%
	\assignlabel{chapter}{\chapname}%
	\tchapter#1\par}
\def\tchapter#1\par{% typeset chapter title
	\everypar{\let\beforesect\beforesection}% do not number paragraphs before the first section
	\chapbreak\bigbreak
	\centerline{\plabel\chaptertitle\anchor{chapter.#1}{#1}}% Anchor: chapter
	\nobreak\medskip
	\let\beforesect\relax % do not break pages right after a chapter title
}
\def\tchapbreak{\vfill\break}
\let\chapbreak\relax % \let\chapbreak\tchapbreak to start chapters on a new page

% Sections
\newcount\secn \secn0
\def\section#1\par{%
	\ifx\sectionid\undefined\advance\secn1 \edef\sectionid{\the\secn}\fi
	\everypar{\numpar}% number paragraphs inside a section
	\parn0
	\subparn0
	\presecfalse
	\numbfalse
	\addcont\contlinesect\sectionid{#1}%
	\curverb{\S}%
	\assignlabel{section}{\sectionid}%
	\tsection#1\par
}
\def\unsection#1\par{%
	%\ifx\sectionid\undefined \edef\sectionid{#1}\fi
	\everypar{\numpar}% number paragraphs inside a section
	\parn0
	\subparn0
	\presecfalse
	\numbfalse
	\addcont\contlineunsect{#1}{#1}%
	\curverb{\S}%
	\assignlabel{section}{#1}%
	\tsection#1\par
}
\def\tsection#1\par{
	\beforesect\let\beforesect\beforesection
	\typesetsection{#1}%
	\aftersection	
	\let\sectionid\undefined
}
\def\beforesection{\vskip0pt plus.3\vsize \penalty-250 \vskip0pt plus-.3\vsize \bigskip \vskip\parskip}
\def\aftersection{\nobreak\smallskip}
\def\typesetsection#1{\leftline{\sectiontitle
	\ifx\sectionid\undefined
		\plabel\anchor{section.#1}{}%
		%\indent
	\else
		\hbox to \parindent{\hss\plabel\anchor{section.\sectionid}{\sectionid}\enspace\hfill}%
	\fi#1}} % Anchor: section
\let\beforesect\beforesection

% Subsections
\def\subsection#1\par{\bigbreak\numbtrue\curverb{\S}\subsectiontitle\noindent#1\/\mainfont\par\nobreak\medskip\addcont\contlinesubsect{\the\secn.\the\parn}{#1}}
\def\subsubsection#1\par{\bigbreak\numbtrue\curverb{\S}\subsubsectiontitle\noindent#1\/\mainfont\par\nobreak\medskip\addcont\contlinesubsubsect{\the\secn.\the\parn}{#1}}

% Theorems and proofs
\def\sskip#1{\ifdim\lastskip<\medskipamount \removelastskip\penalty#1\medskip\fi}
\def\slug{\hbox{\kern1.5pt\vrule width2.5pt height6pt depth1.5pt\kern1.5pt}}
\newif\ifqed \newif\ifneedqed
\def\qed{\unskip\nobreak\ \slug\ifhmode\spacefactor3000 \fi\global\qedtrue}
\def\proclaim{\medbreak\atendpar{\sskip{55}}\numbtrue\gproclaim\proclaimfont} % always number theorems etc.
\def\proof{\medbreak\atendpar{\sskip{-55}}\needqedtrue\gproclaim\prooffont}
\def\xproclaim#1.{\medbreak\atendpar{\sskip{55}}{\everypar{}\noindent}{\proclaimfont#1.\enspace}\ignorespaces} % like \proclaim, no numbering
\let\abstract\xproclaim % abstracts don't get numbered

% Paragraphs
\def\pseudopar{\vadjust{\vskip\parskip}\hfil\break\indent} % pseudo paragraph, cannot be labeled, does not have backrefs
\def\ersatzpar{\vadjust{\vskip\parskip}\hfil\break\indent\numpar} % ersatz paragraph with numbering, cannot be labeled, does not have backrefs
\def\ppar{\endgraf{\everypar{}\indent}} % paragraph inside a proof, not seen by \proof, has backrefs
%\def\ppar{\the\atendbr\atendbr{}\endgraf\numbfalse} % paragraph inside a proof, not seen by \proof, has backrefs
\newtoks\atendpar % tokens to be inserted after \endgraf
\newtoks\atendbr % paragraph backreferences
\newif\ifnumb \numbfalse % number this paragraph?
\def\finishpar{\ifhmode\ifneedqed\ifqed\else\qed\fi\qedfalse\needqedfalse\fi\iflist\endlist\fi\the\atendbr\atendbr{}\endgraf\the\atendpar\atendpar{}\numbfalse\fi}
\def\endlist{\iflist\listfalse\endgraf{\parskip\smallskipamount\everypar{}\noindent}\fi} % terminate a list without starting a new paragraph
\newcount\parn
\newcount\subparn
\newif\ifparbref
\def\nextpar{\ifnumb\advance\parn1 \printlabel{advancing paragraph number to \the\parn}\def\brt{}%
	\ifparbref\edef\cseq{\csname backreference-list.paragraph.\the\secn.\the\parn\endcsname}%
	\expandafter\ifx\cseq\relax\else\edef\brt{\cseq}\printbackref{back references for paragraph.\the\secn.\the\parn: \cseq}\fi\fi
	\assignlabel{paragraph}{\the\secn.\the\parn}\fi}
\def\numpar{\ifnumb\nextpar\expand{\noexpand\typesetparnum{\the\secn.\the\parn}\noexpand\typesetpbr{\brt}}\fi}
\newdimen\pindent \pindent\parindent

% Paragraph and theorem numbering
\ifx\draftnum\undefined % normal numbering
\def\gproclaim#1#2.{\curverb{#2~}% #1: font, #2: prefix
	\ifnumb\nextpar\fi
	{\everypar{}\noindent}%
	\plabel#1#2%
	\ifnumb\ \anchor{paragraph.\the\secn.\the\parn}{}\the\secn.\the\parn\fi.\enspace\mainfont % Anchor: proclaim
	\ifnumb\expand{\noexpand\typesetpbr{\brt}}\fi
	\ignorespaces}
\def\typesetparnum#1{\ifnumb{\plabel\parnumfont\anchor{paragraph.#1}{}#1.\enspace}\fi} % Anchor: explicitly numbered paragraph
\def\typesetpbr#1{\ifnumb\def\brtext{#1}\ifx\brtext\empty\else\setetok\atendbr{{\parbackreffont Used in \noexpand\stripcomma\brtext.}}\fi\fi}
\else % number everything for proofreading purposes
\let\numbfalse\relax \numbtrue
\def\gproclaim#1#2.{\curverb{#2~}\medbreak\noindent#1#2.\enspace\mainfont\ignorespaces}
\inewdimen\brwidth \brwidth.6in
\parindent0pt \parskip1ex plus 1ex minus 1ex
\def\typesetparnum#1{\ifnumb\llap{\plabel\anchor{paragraph.#1}{}\parnumfont#1\enspace}\fi} % Anchor: implicitly numbered paragraph
\def\typesetpbr#1{\ifnumb\def\brtext{#1}\ifx\brtext\empty\else
	\llap{\smash{\vtop{\everypar{}\raggedright\rightskip0pt plus 0pt \leftskip0pt plus 1fill \hsize\brwidth
	\parnumfont \strut \break % the first line contains paragraph number
	\parbackreffont\stripcomma#1}}\enspace}\fi\fi}
\fi

% Lists
\def\hang{\hangindent\pindent}
\newif\iflist
\def\textindent#1{{\everypar{}\parindent\pindent\indent}\llap{#1\enspace}\listtrue\ignorespaces}
\def\itemitem{\endgraf{\everypar{}\parindent\pindent\indent}\hangindent2\pindent \textindent}
\def\li{\item{$\bullet$}}

% \par replaced by \endgraf
\def\item{\endgraf\hang\textindent}
\def\filbreak{\endgraf\vfil\penalty-200\vfilneg}
\def\goodbreak{\endgraf\penalty-500 }
\def\eject{\endgraf\break}
\def\supereject{\endgraf\penalty-20000}
\def\smallbreak{\endgraf\ifdim\lastskip<\smallskipamount
	\removelastskip\penalty-50\smallskip\fi}
\def\medbreak{\endgraf\ifdim\lastskip<\medskipamount
	\removelastskip\penalty-100\medskip\fi}
\def\bigbreak{\endgraf\ifdim\lastskip<\bigskipamount
	\removelastskip\penalty-200\bigskip\fi}

% Email obfuscation (source and output)
%\newdimen\plht \setbox0\hbox{\char`\_} \plht\ht0 \setbox1\hbox{.} \advance\plht-\ht1 % compute the amount by which a dot accent should be lowered to become a period
%\catcode`\.\active \def.{\lower\plht\hbox{\char`\_}} \catcode`\.=12 % emails are typeset with a lowered dot accent instead of a period
%\def\email{\bgroup\catcode`.\active\xemail}
%\def\xemail#1#2{\rlap{\hphantom{#2}@#1}#2\hphantom{@#1}\egroup}

% Back references for labels and bibliography
\let\printbackref\gobble
%\let\printbackref\print % print back references
\def\predefbackref#1{%
	\printbackref{defining back reference list backreference-list.#1}%
	\expandafter\gdef\expandafter\cseq\expandafter{\csname backreference-list.#1\endcsname}
	\expandafter\ifx\cseq\relax\expandafter\gdef\cseq{}\else\printbackref{duplicate omitted}\fi
}
\newcount\backref \backref0
\newif\ifsuppressbackref \suppressbackreffalse
\def\firstletter#1#2\endletter{#1}
\newtoks\backreflist
\newif\ifaddbr \addbrfalse
\def\recordbackref#1{%
	\edef\params{{\ifpresec\expandafter\firstletter\chapname\endletter\else\the\secn\fi.\the\parn\ifnumb\else*\fi}{\the\backref}{\the\inputlineno}}%
	\printbackref{recording back reference \string#1 for future processing with params \params}%
	\edef\tmp{\the\backreflist\noexpand\processbackref\noexpand#1\params}%
	\global\backreflist\expandafter{\tmp}%
	\printbackref{new content of backreflist: \the\backreflist}} % \global is needed because this can be invoked inside {\it ...}, say
\def\processbackref#1#2#3#4{%
	\edef\key{\expandafter\gobble\string#1}%
	\edef\cseq{\csname id.\key\endcsname}%
	\expandafter\ifx\cseq\relax \ewarningline{#4}{Undefined reference \string#1.}{\string#1}\else
		\edef\lseq{\csname backreference-list.\cseq\endcsname}%
		\printbackref{processing back reference number #3 \string#1, originating from #2, at line #4; adding to \lseq}%
		% Check for duplicates
		\edef\lastnumber{\csname lastnumber.\cseq\endcsname}%
		\edef\newnumber{#2}%
		\addbrtrue
		\printbackref{lastnumber: \lastnumber; newnumber: \newnumber;}%
		\expandafter\ifx\csname lastnumber.\cseq\endcsname\relax % we are the first back reference
		\else\ifx\lastnumber\newnumber % same as the last one
			\printbackref{Suppressing duplicate back reference #2.}%
			\addbrfalse
		\fi\fi
		\expandafter\edef\csname lastnumber.\cseq\endcsname{#2}% record the new number
		\ifaddbr
			\expandafter\expandafter\expandafter\gdef\expandafter\expandafter\csname backreference-list.\cseq\endcsname\expandafter{\lseq, \llink{backreference.#3}{#2}}% Link: from a back reference list to the point of origin
			% Step 1: \expandafter\gdef\expandafter\"backreference-list.\cseq"\expandafter{\lseq, \llink{backreference.#3}{#2}}\fi
			% Step 2: \gdef\"backreference-list.\cseq"{\"expanded lseq", \llink{backreference.#3}{#2}}\fi
		\fi
	\fi
}
\newtoks\labelinitlist
\def\xxstripcomma, {}
\def\xstripcomma{\if\ntok,\let\xcont\xxstripcomma\else\let\xcont\relax\fi\xcont}
\def\stripcomma{\futurelet\ntok\xstripcomma}

% Prevention of duplicate labels
\inewif\ifrecorddups \recorddupstrue
\def\checkduplicates#1#2{\edef\key{\expandafter\gobble\string#1}%
	\iftypesetting\else
	\expandafter\ifx\csname line:\key\endcsname\relax\printlabel{keydefline: relax}\ifrecorddups\expandafter\xdef\csname line:\key\endcsname{\the\inputlineno}\fi\else\edef\keydefline{\csname line:\key\endcsname}\errmessage{#2}\fi\fi}

% Labels
\let\printlabel\gobble
%\let\printlabel\print % print labels
\newtoks\curverb % curverb stores the current block name, such as "Chapter", "Theorem", etc.
\ifx\draftlabel\undefined
\def\plabel{}
\else
\def\labeltext{} % label text for proofreading purposes
\def\plabel{\ifx\labeltext\empty\else\smash{\llap{\parbackreffont\labeltext\quad}}\gdef\labeltext{}\fi} % gdef because \plabel is used inside boxes
\fi
\def\assignlabel#1#2{% #1: name (e.g., reference, paragraph, section, chapter), #2: text (e.g., 2.1)
	\ifx\lastlabel\undefined\else
	\edef\key{\expandafter\expandafter\expandafter\gobble\expandafter\string\lastlabel}% label name without backslash
	\printlabel{label \key: id.\key\space = #1.#2, text.\key\space = #2}%
	\expandafter\xdef\csname id.\key\endcsname{#1.#2}% id for DVI hrefs and backreference lists
	\expandafter\xdef\csname text.\key\endcsname{#2}% text that is actually typeset
	\edef\tmp{\the\curverb}%
	\ifx\tmp\empty\else % if curverb is nonempty, define a "verbal" label with a prefix "v"
	\printlabel{label v\key: id.v\key\space = #1.#2, text.v\key\space = \the\curverb#2}%
	\expandafter\xdef\csname id.v\key\endcsname{#1.#2}% id for DVI hrefs and backreference lists
	\expandafter\xdef\csname text.v\key\endcsname{\the\curverb#2}% text that is actually typeset
	\fi
	\predefbackref{#1.#2}%
	\fi\let\lastlabel\undefined}
\newtoks\vlist % Verification list
\def\label#1{%
	\iftypesetting\else
	\checkduplicates#1{Label \string#1 was already defined at line \keydefline}%
	\addverunused#1\verifylabel
	\def\lastlabel{#1}%
	\fi
	\numbtrue % always number labeled paragraphs
}

% Bibliography
\newif\ifyearkey % use years as bibliographic keys?
\def\y{} % use in bibliography as \y{1967}
\newdimen\bibindent % the maximum width of a bibliographic key
\newtoks\bibt % token list for all bibliographic items
\def\tbib#1{% #1 = \Paper
	\checkduplicates#1{Bibliographic reference \string#1 already defined at line \keydefline}%
	\addverunused#1\verifybib
	\edef\key{\expandafter\gobble\string#1}% reference name without backslash
	\printlabel{reference \key: id.\key\space = reference.\key, text.\key\space = \key}%
	\expandafter\edef\csname id.\key\endcsname{reference.\key}% id for DVI hrefs and backreference lists
	\expandafter\edef\csname text.\key\endcsname{\key}% text that is actually typeset
	\predefbackref{reference.\key}%
	\ifyearkey\else\setbox0=\hbox{[\key]}\ifdim\bibindent<\wd0 \bibindent=\wd0 \fi \fi % \bibindent holds the maximum length of all reference [keys]
	\appendexpand\bibt{\noexpand\typesetbib\noexpand#1\src}%
	\ifyearkey\let\next\xxftbib\else\let\next\ftbibalpha\fi\next}
\def\ftbibalpha#1\par{\append\bibt{#1\par}}
\def\xxftbib{\futurelet\next\xftbib}
\def\xftbib{\if\next[\let\next\ftbibyear\else\let\next\ftbibnoyear\fi\next}
\def\ftbibyear[#1]{\edef\yearkey{#1}\expandafter\ftbibyearbis\ignorespaces}
\def\ftbibyearbis#1\par{\append\bibt{#1\par}\ftbibend}
\def\ftbibnoyear#1\par{\append\bibt{#1\par}\edef\yearkey{\extractyear#1\par}\ftbibend}
\def\ftbibend{\expandafter\ifx\csname year.\yearkey\endcsname\relax
		\edef\yearindex{0}%
	\else
		\edef\yearindex{\csname year.\yearkey\endcsname}%
	\fi
	{\count0=\yearindex
	\advance\count0 by 1 %
	\expandafter\xdef\csname year.\yearkey\endcsname{\the\count0 }%
	\xdef\alphakey{\ifcase \count0 ?\or a\or b\or c\or d\or e\or f\or g\or h\or i\or j\or k\or l\or m\or n\or o\or p\or q\or r\or s\or t\or u\or v\or w\or x\or y\or z\else .\the\count0 \fi}}%
	\printlabel{key \key, year key \yearkey, alpha key \alphakey}%
	\expandafter\edef\csname text.\key\endcsname{\noexpand\typesetyearalpha{\key}{\yearkey}{\alphakey}}%
	\printlabel{reference \key\space adjustment: id.\key\space = reference.\key, text.\key\space = \yearkey.\alphakey}%
	\setbox0=\hbox{[\yearkey.\alphakey]}\ifdim\bibindent<\wd0 \bibindent=\wd0 \fi% \bibindent holds the maximum length of all reference [keys]
}
\def\typesetyearalpha#1#2#3{%
	\edef\yearindex{\csname year.#2\endcsname}%
	\ifnum\yearindex=1 #2\else#2.#3\fi}
\def\extractyear#1\y#2#3\par{#2}
\newif\iftype
\def\typesetbib#1#2\par{\edef\key{\expandafter\gobble\string#1}%
	\edef\bibbr{\csname backreference-list.reference.\key\endcsname}%
	\typetrue\ifsuppressunusedbib\ifx\bibbr\empty\typefalse%\warning{Suppressing unused bibliography item \string#1}
	\fi\fi
	\iftype
	\noindent\hbox to \bibindent{[\anchor{reference.\key}{\csname text.\key\endcsname}]\hfil}#2% Anchor: reference
	\ifx\bibbr\empty\else\expandafter\stripcomma\bibbr.\fi
	\hangindent\bibindent\filbreak
	\fi}

% Diagnostic messages for unused references and labels
\let\printverify\gobble
%\let\printverify\print % print verifications
\def\addverunused#1#2{\appendexpand\vlist{\noexpand#2\noexpand#1{\the\inputlineno}}}
\def\verifyref#1#2#3{\printverify{verifying for #3 \string#1 (line #2)}%
	\edef\key{\expandafter\gobble\string#1}%
	\edef\cseq{\csname id.\key\endcsname}%
	\edef\tmp{\csname backreference-list.\cseq\endcsname}%
        \ifx\tmp\empty\ewarningline{#2}{#3 \string#1.}{\string#1}\fi}
\def\verifylabel#1#2{\verifyref#1{#2}{Unused label}}
\def\verifybib#1#2{\verifyref#1{#2}{Unused reference}}

% URLs
\let\printurl\gobble
%\let\printurl\print % print URLs
\newtoks\urltext
\newtoks\urlt
\newif\ifpunct
\def\urldash{-}
\def\urltilde{{\tensy^^X}} % like \sim
\def\ndash{\def\urldash{--}}
\def\http://{\hfil\penalty900\hfilneg\urltext={http://}\urlt={http:/\negthinspace/}\punctfalse\urlgrab}
\def\https://{\hfil\penalty900\hfilneg\urltext={https://}\urlt={https:/\negthinspace/}\punctfalse\urlgrab}
\def\urlgrab{\catcode`\#=11 \catcode`\&=11 \futurelet\ntok\urldispatch}
\def\urldispatch{%
	\ifx\ntok~\let\proceed\urlcont\else
	\ifcat\noexpand\ntok\space\let\proceed\urlfinish\else
	\ifcat\noexpand\ntok\relax\let\proceed\urlfinish\else
	\let\proceed\urlcont
	\fi\fi\fi\proceed}
\def\urlcont#1{\ifpunct\appendexpand\urltext\punctc\appendexpand\urlt\punctc\punctfalse\fi
	\ifx\ntok~\appendexpand\urltext{\noexpand~}\appendexpand\urlt\urltilde
	\else\if\ntok\ampersand\appendexpand\urltext{&}\appendexpand\urlt{\&}%
	\else\if\ntok\ohash\appendexpand\urltext\ohash\appendexpand\urlt\#%
	\else\if\ntok_\appendexpand\urltext_\appendexpand\urlt\_%
	\else\if\ntok-\appendexpand\urltext-\appendexpand\urlt\urldash
	\else\if\ntok.\puncttrue\def\punctc{.}%
	\else\if\ntok,\puncttrue\def\punctc{,}%
	\else\if\ntok;\puncttrue\def\punctc{;}%
	\else\appendexpand\urltext{#1}\appendexpand\urlt{#1}%
	\fi\fi\fi\fi\fi\fi\fi\fi\urlgrab}
\def\urlfinish{\catcode`\#=6 \catcode`\&=4 \hbox{\printurl{\the\urltext}\link{\the\urltext}{\the\urlt}}\ifpunct\punctc\punctfalse\fi\def\urldash{-}}
\def\idgrab{\futurelet\ntok\iddispatch}
\def\iddispatch{\ifcat\noexpand\ntok\space\let\proceed\urlfinish
		\else\if\ntok,\let\proceed\urlfinish
		\else\let\proceed\idcont
		\fi\fi\proceed}
\def\idcont#1{\ifpunct\appendexpand\urltext.\appendexpand\urlt.\punctfalse\fi
	\if\ntok.\puncttrue\def\punctc{.}%
	\else\if\ntok_\appendexpand\urltext_\appendexpand\urlt\_%
	\else\appendexpand\urltext{#1}\appendexpand\urlt{#1}%
	\fi\fi\idgrab}

% Mathematical string grabbing
\let\printgrab\gobble
%\let\printgrab\print % print all mathematical string grabs
\newtoks\grabname
\newtoks\grabtoks % beginning
\newtoks\grabcseq % control sequence name
\newtoks\subsuptoks % ^ or _
\newtoks\dtoks % first letter of a subscript
\newcount\grabsize
\newif\ifgrabsubscript % include subscript?
\newif\ifgrabsupscript % include superscript?
\def\grabsequence{\bgroup % \bgroup allows us to say things like $C^@op$, with "op" being a superscript
	\grabsubscripttrue\grabsupscripttrue % do grab sub/superscripts
	\grabstring}
\def\grabalpha{\bgroup % same
	\grabsubscriptfalse\grabsupscriptfalse % do not grab sub/superscripts
	\grabstring}
\def\grabingroup{\ifinfont\errmessage{Already inside a math token}\fi\append\grabtoks{\bgroup\grablink}\infonttrue}
\def\graboutgroup{\ifinfont\append\grabtoks{\endgrablink\egroup}\infontfalse\fi}
\def\grabstring#1#2#3{% #1 = descriptive name like cat, fun, trans; #2 = font like \bf, \rm, \it; #3 = postcommand like \nolimits
	\let\specialhat^
	\catcode`\^=7
	\aftergroup#3 % #3 could be \nolimits or \limits
	\ifx\specialaddon\undefined\else\expandafter\aftergroup\specialaddon\let\specialaddon\undefined\fi
	\inewif\ifdefine \inewif\ifinfont
	\printgrab{}\printgrab{grab a string of type #1, typeset using font \string#2, with postcommand \string#3}%
	\grabname{#1}\def\grabfont{#2}\grabsize0 \grabtoks={}\grabingroup \append\grabtoks{#2}\grabcseq={}%
	\futurelet\ntok\grabdeflookahead}
\def\grabdeflookahead{\if=\noexpand\ntok % @=Set creates an anchor, whereas @Set refers to it
	\definetrue\printgrab{defining}\expandafter\grabgobblefuturelet
	\else\printgrab{referencing}\definefalse\expandafter\grablookahead\fi}
\def\grabgobblefuturelet#1{\futurelet\ntok\grabtestforsilent} % gobble = and look for another =
\newif\ifsilentgrab
\def\grabtestforsilent{\if=\noexpand\ntok \silentgrabtrue \let\ncom\grabsilenteq \else \silentgrabfalse \let\ncom\grablookahead \fi \ncom}
\def\grabsilenteq={\grabfuturelet}
\def\grabfuturelet{\futurelet\ntok\grablookahead}
\def\grablookahead{\printgrab{futurelet token meaning: \meaning\ntok}%
	\let\ncom\grabfinish
	\if\bgroup\noexpand\ntok \printgrab{left brace, terminating}%
	\else \if\egroup\noexpand\ntok \printgrab{right brace, terminating}%
	\else \if\space\noexpand\ntok \printgrab{blank space, terminating}%
	\else \let\ncom\grabexamine \fi\fi\fi \ncom}
\def\grabexamine#1{\printgrab{grabexamine argument: \string#1, meaning \meaning#1}%
	\def\ncom{\grabfinish#1}%
	\ifcat$\ifcat*\string#1\fi$% is #1 not a command sequence?
		\ifcat _\noexpand#1 \ifgrabsubscript\printgrab{subscript, continuing}%
			\graboutgroup \append\grabtoks{#1}\subsuptoks{#1}\def\ncom{\grabsubsupfuturelet}%
						\else\printgrab{subscript, terminating}\fi
		\else \ifcat ^\noexpand#1 \ifgrabsupscript\printgrab{superscript, continuing}%
			\graboutgroup \append\grabtoks{#1}\subsuptoks{#1}\def\ncom{\grabsubsupfuturelet}%
						\else\printgrab{superscript, terminating}\fi
		\else \ifx \specialhat#1 \ifgrabsupscript\printgrab{specialhat superscript, continuing}%
			\graboutgroup \append\grabtoks{#1}\subsuptoks{#1}\def\ncom{\grabsubsupfuturelet}%
						\else\printgrab{superscript, terminating}\fi
		\else \ifcat\noexpand~\noexpand#1 \printgrab{active character \string#1, examining further}%
			\ifnum1=\uccode`#1 \printgrab{UTF-8 letter, continuing}%
				\advance\grabsize1 \append\grabtoks{#1}\appendexpand\grabcseq{\string#1}\def\ncom{\grabfuturelet}%
			\else
				\ifnum\the\grabsize=0 \printgrab{Nothing grabbed so far, continuing}%
					\advance\grabsize1 \append\grabtoks{#1}\appendexpand\grabcseq{\string#1}\def\ncom{\grabfuturelet}%
				\else\printgrab{Not a UTF-8 letter and not the first character in a string, terminating}%
				\fi
			\fi
		\else \ifcat a\noexpand#1 \printgrab{letter #1, continuing}%
			\advance\grabsize1 \append\grabtoks{#1}\append\grabcseq{#1}\def\ncom{\grabfuturelet}%
		\else\printgrab{nonactive character \string#1}%
			\ifnum\the\grabsize=0 \printgrab{sole argument, adding and terminating}%
				\advance\grabsize1 \append\grabtoks{#1}\append\grabcseq{#1}\def\ncom{\grabfinish}%
			\else\printgrab{terminating}\fi
		\fi\fi\fi\fi\fi
	\else \printgrab{command sequence \string#1, terminating}\fi
	\ncom}
\def\grabsubsupfuturelet{\futurelet\ntok\grabsubsuplookahead}
\newcount\dig
\newif\ifdigit
\def\grabsubsuplookahead{\printgrab{subsup futurelet token meaning: \meaning\ntok}%
	\if\bgroup\noexpand\ntok \printgrab{left brace, continuing}\let\ncom\grabentiresubsup%
	\else \if\egroup\noexpand\ntok \printgrab{right brace, continuing}\let\ncom\grabentiresubsup%
	\else \if\space\noexpand\ntok \errmessage{Blank space after \the\subsuptoks}%
	\else \let\ncom\grabsubsupexamine \fi\fi\fi \ncom}
\def\grabentiresubsup#1{\printgrab{subsup entire group added}\grabingroup\append\grabtoks{#1}\graboutgroup\grabfuturelet}
\iffalse % can be deleted now
\def\grabsubsupremainderfuturelet{\futurelet\ntok\grabsubsupremainderlookahead}
\def\grabsubsupremainderlookahead{\printgrab{futurelet token meaning: \meaning\ntok}%
	\let\ncom\grabfinish
	\if\bgroup\noexpand\ntok \printgrab{left brace, terminating}%
	\else \if\egroup\noexpand\ntok \printgrab{right brace, terminating}%
	\else \if\space\noexpand\ntok \printgrab{blank space, terminating}%
	\else \let\ncom\grabsubsupremainderexamine \fi\fi\fi \ncom}
\def\grabsubsupremainderexamine#1{\printgrab{grabsubsupremainderexamine argument: \string#1, meaning \meaning#1}%
	\def\ncom{\grabfinish#1}%
	\ifcat$\ifcat*\string#1\fi$% is #1 not a command sequence?
		\ifcat\noexpand~\noexpand#1 \printgrab{active character \string#1, continuing}%
			\append\grabtoks{#1}\def\ncom{\grabsubsupremainderfuturelet}%
		\else \ifcat _\noexpand#1 \ifgrabsubscript\printgrab{subscript, continuing}%
			\graboutgroup \append\grabtoks{#1}\subsuptoks{#1}\def\ncom{\grabsubsupfuturelet}%
						\else\printgrab{subscript, terminating}\fi
		\else \ifcat ^\noexpand#1 \ifgrabsupscript\printgrab{superscript, continuing}%
			\graboutgroup \append\grabtoks{#1}\subsuptoks{#1}\def\ncom{\grabsubsupfuturelet}%
						\else\printgrab{superscript, terminating}\fi
		\else \ifnum"8000=\the\mathcode`#1 \printgrab{math active character \string#1, continuing}%
			\warning{math active B: \string#1}%
			\append\grabtoks{#1}\def\ncom{\grabsubsupremainderfuturelet}%
		\else \ifcat a\noexpand#1 \printgrab{letter #1, continuing}%
			\append\grabtoks{#1}\def\ncom{\grabsubsupremainderfuturelet}%
		\else \printgrab{nonactive character \string#1, terminating}\fi\fi\fi\fi\fi
	\else \printgrab{command sequence \string#1, terminating}\fi
	\ncom}
\fi
\def\grabsubsupexamine#1{\printgrab{examining subsup argument \string#1, meaning \meaning#1}%
	% We pass through (1) single letters; (2) command sequences
	\ifcat$\ifcat*\string#1\fi$% is #1 not a command sequence?
		\ifcat\noexpand~\noexpand#1 \printgrab{active character \string#1, continuing}%
			%\warning{math active C: \string#1, grabsize=\the\grabsize, grabtoks=\the\grabtoks, grabcseq=\the\grabcseq}%
			%\grabingroup\appendexpand\grabtoks{\grabfont\noexpand#1}\let\ncom\grabsubsupremainderfuturelet
			\grabingroup\appendexpand\grabtoks{\grabfont\noexpand#1}\let\ncom\grabfuturelet
		\else\ifnum"8000=\the\mathcode`#1 \printgrab{math active character \string#1, continuing}%
			%\warning{math active A: \string#1, grabsize=\the\grabsize, grabtoks=\the\grabtoks, grabcseq=\the\grabcseq}%
			%\grabingroup\appendexpand\grabtoks{\grabfont\noexpand#1}\let\ncom\grabsubsupremainderfuturelet
			\let\specialaddon\egroup
			\def\ncom{#1}%
			\grabtypeset
		\else\ifcat a\noexpand#1 \printgrab{letter #1, checking whether single or not}%
			\dtoks{#1}\def\ncom{\futurelet\ntok\grabsubsupsecondletterlookahead}%
		\else\printgrab{something else, inserting a single-character sub/superscript, continuing}
			\appendexpand\grabtoks{\bgroup\grabfont\noexpand#1\egroup}%
			\advance\grabsize2 \appendexpand\grabcseq{\the\subsuptoks\string#1}% possibly ignore digits here
			\def\ncom{\grabfuturelet}\fi\fi\fi
	\else \printgrab{command sequence \string#1, continuing}%
		\append\grabtoks{#1}\let\ncom\grabfuturelet\fi
	\ncom}
\def\grabsubsupsecondletterlookahead{\def\ncom{\appendexpand\grabtoks{\the\dtoks}\grabfuturelet}%
	\ifcat a\noexpand\ntok \printgrab{not a single letter, grabbing the entire subsupscript}%
		\advance\grabsize1 \appendexpand\grabcseq{\expandafter\string\the\subsuptoks}% append _ or ^ to the label
		\grabingroup
		\appendexpand\grabtoks{\grabfont\the\dtoks}%
		\appendexpand\grabcseq{\the\dtoks}%
		\def\ncom{\grabfuturelet}%
	\else \printgrab{single letter, continuing}\fi\ncom}
\def\grabfinish{\printgrab{grabfinish}\graboutgroup\grabtypeset\egroup}
\def\grabtypeset{\printgrab{grabtypeset grabsize=\the\grabsize, grabtoks=\the\grabtoks, grabcseq=\the\grabcseq}%
	\def\grablink##1\endgrablink{##1}%
	\ifnum\the\grabsize=0 \errmessage{No string to grab}\fi
	\ifnum\the\grabsize>1 % single-letter names are not references
		\ifdefine % defining a mathematical identifier
			\expandafter\checkduplicates\csname\the\grabname.\the\grabcseq\endcsname{Mathematical identifier \key\space already defined at line \keydefline}%
			\iftypesetting % if we are actually typesetting, create an anchor
				\ifsilentgrab
					\expandafter\gdef\csname silent:\the\grabname.\the\grabcseq\endcsname{}% record that this id is silent
				\else
					\anchor{\the\grabname.\the\grabcseq}{}% Anchor: definition of a mathematical identifier
				\fi % only create if not silent
			\else
				\expandafter\xdef\csname id.\the\grabname.\the\grabcseq\endcsname{paragraph.\the\secn.\the\parn}% paragraph id for a back reference list
				\predefbackref{paragraph.\the\secn.\the\parn}%
  			\fi
		\else % referencing a mathematical identifier
			\iftypesetting % we are actually typesetting
				\global\advance\backref1
				\expandafter\ifx\csname line:\the\grabname.\the\grabcseq\endcsname\relax % identifier is undefined
					\warning{Undefined mathematical identifier \the\grabname.\the\grabcseq}%
					\expandafter\gdef\csname\the\grabname.\the\grabcseq\endcsname{\relax}% report undefined references only once; gdef because inside bgroup..egroup
				\else % identifier has ben defined
					\expandafter\ifx\csname silent:\the\grabname.\the\grabcseq\endcsname\empty
						\edef\grablink##1\endgrablink{{##1}}%
					\else % not silent, need a hyperlink
						\edef\grablink##1\endgrablink{\noexpand\llink{\the\grabname.\the\grabcseq}{##1}% Link: from a mathematical identifier to its definition 
							\noexpand\anchor{backreference.\the\backref}{}}% Anchor: back reference for a mathematical identifier reference
					\fi
				\fi
			\else % not yet typesetting, just collecting back references
				\ifsuppressbackref\else
					\global\advance\backref1
					\printbackref{math back reference to \the\grabname.\the\grabcseq: backref.\the\backref\space at line \the\inputlineno}%
					\expandafter\recordbackref\csname\the\grabname.\the\grabcseq\endcsname
				\fi
			\fi
		\fi
	\fi
	\ifsilentgrab\else\the\expandafter\grabtoks\fi}
%		\ifcat 0\noexpand\ntok \printgrab{subsupscript is followed by a catcode 12 character, examining further}%
%			\dig=0 \loop \if\the\dig\ntok \digittrue \fi \ifnum\dig<9 \advance\dig1 \repeat
%			\ifdigit \printgrab{subsupscript is followed by a digit, passed through}%
%				\advance\grabsize2
%				\appendexpand\grabtoks{\subsup#1}%
%				\appendexpand\grabcseq{\expandafter\string\subsup#1}%
%				\def\ncom{\grabfinish}%
%			\else \printgrab{subsupscript is followed not by a digit or a letter, terminating}\fi

% index macros modeled after manmac.tex
% ^={...}: setup an anchor and typeset in italic font
% ^=:{...}: setup an anchor and typeset in roman font
% ^^={...}: setup an anchor, do not typeset
% ^{...}: record a back reference and typeset
% ^^{...}: record a back reference, do not typeset
% ^!{...}: reference a proclaimed statement in the format Theorem~3.5
\inewif\ifsilent \inewif\ifanchor
\newif\ifsuppresscs
\catcode`\^=7 \def\singlehat{^} \edef\doublehat{\singlehat\singlehat} \def\specialhat{\ifmmode\def\next{^}\else\let\next\beginxref\fi\next} \catcode`\^=\active \let^=\specialhat
\def\silentxref#1{\futurelet\next\silentxrefswitch}
\def\silentxrefswitch{\silenttrue\xref}
\def\beginxref{\futurelet\next\beginxrefswitch}
\def\beginxrefswitch{\ifx\next\specialhat\let\next\silentxref \else\silentfalse\let\next\xref\fi \next}
\def\xref{\leavevmode\futurelet\next\xrefswitch}
\def\xrefswitch{\ifx\next!\let\next\verbalxref \else \ifx\next=\let\next\anchorxref \else \anchorfalse \let\next\normalxref \fi \fi \next}
\newtoks\vtoksl
{\count0="C2 \loop\ifnum\count0<"F5 \catcode\count0=11 \advance\count0 by 1 \repeat % make all legitimate initial UTF-8 octets letters
\gdef\plainaccents{\suppresscstrue%
	\def\`##1{##1\empty ̀}%
	\def\'##1{##1\empty ́}%
	\def\^##1{##1\empty ̂}%
	\def\"##1{##1\empty ̈}%
	\def\~##1{##1\empty ̃}%
	\def\=##1{##1\empty ̄}%
	\def\.##1{##1\empty ̇}%
	\def\u##1{##1\empty ̆}%
	\def\v##1{##1\empty ̌}%
	\def\H##1{##1\empty ̋}%
	\def\t##1{##1\empty ͡}%
}}
\def\plainaccents{\let\xcsname=\empty \let\xendcsname=\empty}
\def\verbalxref!{\begingroup\plainaccents\verbalxrefaux}
\def\verbalxrefaux#1{%
	\lowercase{\vtoksl{#1}}%
	\expandtoks\vtoksl
	\iftypesetting
		\expandafter\gdef\expandafter\cseq\expandafter{\csname verbal.\the\vtoksl\endcsname}%
		\printlabel{verbal xref \the\vtoksl}%
		\expandafter\ifx\cseq\relax\errmessage{Undefined reference to \the\vtoksl}\else\cseq\fi
	\else
		\ifsuppressbackref\else
			\global\advance\backref1 %
			\printbackref{label verbal.#1: backref.\the\backref\space at line \the\inputlineno}%
			\blah
			\expandafter\recordbackref\csname verbal.\the\vtoksl\endcsname
		\fi
	\fi
	\endgroup}
\def\initverballabelcommand#1{%
	\printlabel{initializing verbal label #1 (\the\curverb\the\secn.\the\parn)}%
	\expandafter\xdef\csname id.verbal.#1\endcsname{paragraph.\the\secn.\the\parn}%
	\ifnum\parn=0 %
	\expandafter\xdef\csname text.verbal.#1\endcsname{\the\curverb\the\secn}%
	\else
	\expandafter\xdef\csname text.verbal.#1\endcsname{\the\curverb\the\secn.\the\parn}%
	\fi
	\expandafter\initlabelcommand\csname verbal.#1\endcsname
}
\def\anchorxref={\anchortrue\futurelet\next\anchorxrefswitch}
\def\anchorxrefswitch{\ifx\next:\let\next\nonitalicanchor\else\italictrue\let\next\normalxref\fi \next}
\def\nonitalicanchor:{\italicfalse\normalxref}
\newtoks\firsttoks \newtoks\secondtoks \inewif\ifplural \inewif\ifitalic
\def\parseplural#1[#2|#3]{\let\next\parseplural\ifx\hfuzz#2\hfuzz\ifx\hfuzz#3\hfuzz\let\next\relax\else\pluraltrue\fi\else\pluraltrue\fi
	\append\firsttoks{#1#2}\append\secondtoks{#1#3}\next}
\newtoks\firsttoksl
\newtoks\secondtoksl
\newtoks\nexttoks
\def\normalxref{\begingroup\plainaccents\normalxrefaux}
\def\normalxrefaux#1{\firsttoks{}\secondtoks{}\pluralfalse\parseplural#1[|]%
	\lowercase\expandafter{\expandafter\firsttoksl\expandafter{\the\firsttoks}}%
	\expandtoks\firsttoksl
	\lowercase\expandafter{\expandafter\secondtoksl\expandafter{\the\secondtoks}}%
	\expandtoks\secondtoksl
	\ifanchor
		\iftypesetting\else
			\initverballabelcommand{\the\firsttoksl}%
			\ifplural\initverballabelcommand{\the\secondtoksl}\fi
			\predefbackref{paragraph.\the\secn.\the\parn}%
			\expandafter\checkduplicates\csname\the\firsttoksl\endcsname{Verbal label \the\firsttoksl\space was already defined at line \keydefline}
			\ifplural\expandafter\checkduplicates\csname\the\secondtoksl\endcsname{Verbal label \the\secondtoksl\space was already defined at line \keydefline}\fi
		\fi
		\anchor{verbal.\the\firsttoksl}{}% Anchor: verbal reference
		\ifplural\anchor{verbal.\the\secondtoksl}{}\fi % Anchor: plural verbal reference
	\else
		\ifsuppressbackref\else
			\global\advance\backref1
			\printbackref{label normal.#1: backref.\the\backref\space at line \the\inputlineno}%
			\iftypesetting
			\else
				\expandafter\recordbackref\csname verbal.\the\secondtoksl\endcsname
			\fi
			\anchor{backreference.\the\backref}{}% Anchor: back reference for a verbal reference
		\fi
	\fi
	% The actual text is typeset after \endgroup
	\nexttoks{}%
	\ifsilent
		\nexttoks{\ignorespaces}%
	\else
		\ifanchor
			\ifitalic\nexttoks\expandafter{\expandafter\bgroup\expandafter\it\the\firsttoks\italcorr}%
			\else\nexttoks\expandafter{\the\firsttoks}%
			\fi
		\else
			\edef\tmp{{verbal.\the\secondtoksl}}%
			\nexttoks\expandafter{\expandafter\llink\tmp}% Link: from a verbal reference to its definition
			\nexttoks\expandafter\expandafter\expandafter{\expandafter\the\expandafter\nexttoks\expandafter{\the\firsttoks}}%
		\fi
	\fi
	\expandafter\endgroup\the\nexttoks}
\def\italcorr{\futurelet\next\italcorrtest}
\def\italcorrtest{\if,\noexpand\next\else\if.\noexpand\next\else\/\fi\fi\egroup}

% Individual repositories
\def\scans{\https://dmitripavlov.org/scans}
%\def\mathjournals{\ndash\http://www.mathjournals.org}
%\def\numdam{\urltext={http://www.numdam.org/item/?id=}\urlt={numdam:}\punctfalse\expandafter\idgrab\ignorespaces}
\def\numdam{\urltext={http://www.numdam.org/item/?id=}\urlt={numdam:}\punctfalse\idgrab}
\def\proquest{\https://search.proquest.com/docview}
%\def\matwbn{\http://matwbn.icm.edu.pl/ksiazki}
\def\gen:{\http://libgen.rs/book/index.php?md5=}
\def\jstor:{\https://www.jstor.org/stable/}
\def\eudml:{\https://eudml.org/doc/}
\def\repo#1#2{\urltext={#1}\urlt={#2}\punctfalse\idgrab}
\def\arXiv:{\urltext={https://arxiv.org/abs/}\urlt={arXiv:}\punctfalse\idgrab}
\def\MR{\urltext={https://mathscinet.ams.org/mathscinet-getitem?mr=}\urlt={MR}\punctfalse\idgrab}
\def\Zbl:{\urltext={https://zbmath.org/?q=an:}\urlt={Zbl:}\punctfalse\idgrab}
\def\doi:{\ndash\urltext={https://doi.org/}\urlt={doi:}\punctfalse\urlgrab}

% Squares
\def\sqr#1#2{{\thinspace\vbox{\hrule height.#2pt \hbox{\vrule width.#2pt height#1pt \kern#1pt \vrule width.#2pt} \hrule height0pt depth.#2pt}\thinspace}}
%\def\square{\mathchoice\sqr34\sqr34\sqr{2.1}3\sqr{1.5}3}
\def\square{\mathchoice\sqr64\sqr64\sqr{4.2}3\sqr33}

% Long arrows
\def\ltoarr#1{\mathop{\count0=#1 \loop\ifnum\count0>0 \smash-\mkern-7mu \advance\count0 -1 \repeat \mathord\rightarrow}\limits} % parametrized \rightarrowfill
\def\lto#1#2{\mathrel{\ltoarr{#1}^{#2}}} % parametrized \rightarrowfill, with a label
\def\longto#1^#2_#3{\mathrel{\ltoarr{#1}^{#2}_{#3}}} % parametrized \rightarrowfill, with a label above and below
\def\lgetsarr#1{\mathop{\mathord\leftarrow \count0=#1 \loop\ifnum\count0>0 \mkern-7mu\smash-\advance\count0 -1 \repeat}\limits} % parametrized \leftarrowfill
\def\lgets#1#2{\mathrel{\lgetsarr{#1}\limits^{#2}}} % parametrized \leftarrowfill, with a label
\def\longgets#1^#2_#3{\mathrel{\lgetsarr{#1}\limits^{#2}_{#3}}} % parametrized \leftarrowfill, with a label

% Double arrows
\let\To\Rightarrow
\def\toto{\mathrel{\vcenter{\hbox{$\to$}\kern-1.5ex \hbox{$\to$}}}}
\def\prearrfill{\smash-\mkern-7mu}
\def\postarrfill{\mkern-7mu\smash-}
\def\midarrfill#1{\cleaders\hbox{$\mkern-2mu\smash-\mkern-2mu$}\hskip0pt plus #1fil}
\def\rightarrfill{\mkern-7mu\mathord\rightarrow}
\def\leftarrfill{\mathord\leftarrow\mkern-7mu\midarrfill1\postarrfill}
\def\ltoto#1#2#3{\ifinner
	\mathrel{\vcenter{\hbox to #1em{$\prearrfill\midarrfill1{\scriptstyle#2}\midarrfill3 \rightarrfill$}%
		\kern-1.5ex \hbox to #1em{$\prearrfill\midarrfill3{\scriptstyle#3}\midarrfill1 \rightarrfill$}}}%
	\else
	\mathrel{\mathop{\vcenter{\hbox to #1em{\rightarrowfill}%
		\kern-1.5ex \hbox to #1em{\rightarrowfill}}}\limits^{#2}_{#3}}%
	\fi}
\def\ltogets#1#2#3{\ifinner
	\mathrel{\vcenter{\hbox to #1em{$\prearrfill\midarrfill1{\scriptstyle#2}\midarrfill3 \rightarrfill$}%
		\kern-1.5ex \hbox to #1em{$\leftarrfill\midarrfill3{\scriptstyle#3}\midarrfill1 \postarrfill$}}}%
	\else
	\mathrel{\mathop{\vcenter{\hbox to #1em{\rightarrowfill}%
		\kern-1.5ex \hbox to #1em{\leftarrowfill}}}\limits^{#2}_{#3}}%
	\fi}

% New macros for arrows
\def\ltogetscore#1#2{\dimen0=\fontdimen6 #1 2 \divide\dimen0 by 2 \multiply\dimen0 by #2 \vcenter{\hbox to \dimen0{\rightarrowfill}\kern-1.8ex \hbox to \dimen0{\leftarrowfill}}}
\def\ltogets#1#2#3{\mathrel{\mathop{\mathchoice{\ltogetscore\textfont{#1}}{\ltogetscore\textfont{#1}}{\ltogetscore\scriptfont{#1}}{\ltogetscore\scriptscriptfont{#1}}}^{#2}_{#3}}}

% Diagonal arrows
\def\rx#1#2{\rlap{\kern #1pt \raise#1pt \hbox{#2}}}
\def\dottednearrow{\rx{-8}. \rx{-6}. \rx{-4}. \rx{-2}. \rx0. \rx2. \rx4. \kern6pt \raise7.7pt \hbox{$\nearrow$}}

% Rectangular commutative diagrams
% \matrix from Plain TeX: #1 = \hfil$##$\hfil&&\quad\hfil$##$\hfil
\def\gmatrix#1#2{\null\,\vcenter{\normalbaselines
	\ialign{#1\crcr
		\mathstrut\crcr\noalign{\kern-\baselineskip}
		#2\crcr\mathstrut\crcr\noalign{\kern-\baselineskip}}}\,}
\def\cdmatrix{\gmatrix{\hfil$##$\hfil&&\enspace\hfil$##$\hfil\enspace&\hfil$##$\hfil}}
\def\sqmatrix{\gmatrix{\hfil$##$&\enspace\hfil$##$\hfil\enspace&$##$\hfil}}
\def\cdbl{\def\normalbaselines{\baselineskip20pt \lineskip3pt \lineskiplimit3pt }}
\def\scriptpmatrix{\def\normalbaselines{\baselineskip11pt \lineskip2pt \lineskiplimit2pt \sizeseven \rm}\pmatrix}
\def\sizeseven{
	\textfont0=\sevenrm \scriptfont0=\fiverm
	\def\rm{\fam0 \sevenrm}
	\textfont1=\seveni \scriptfont1=\fivei
	\def\mit{\fam1 } \def\oldstyle{\fam1 \seveni}
	\textfont2=\sevensy \scriptfont2=\fivesy
	\def\cal{\fam2 }
	\textfont3=\sevenex \scriptfont3=\sevenex \scriptscriptfont3=\sevenex
	\def\bf{\fam\bffam\sevenbf} % \bf is family 6
	\textfont\bffam=\sevenbf \scriptfont\bffam=\fivebf
}
\def\gencd{\cdbl\gmatrix}
\def\cd{\cdbl\cdmatrix}
\def\sqcd{\cdbl\let\vagap\;\sqmatrix}

% Horizontal and vertical diagram arrows
\newcount\arrowsize \arrowsize3
\def\mapright#1{\smash{\lto\arrowsize{#1}}}
\def\mapleft#1{\smash{\lgets\arrowsize{#1}}}
%\def\dmapright#1{\smash{\mathop{\vcenter{\offinterlineskip\hbox{$\lto\arrowsize{}$}\hbox{$\lto\arrowsize{}$}}}\limits^{#1}}} % double arrow
\def\rvagap{\vagap} \def\lvagap{\vagap} \def\rvaskip{\vaskip} \def\lvaskip{\vaskip} \def\vaskip{} \def\vagap{}
\def\mapdown#1{\rvagap\Big\downarrow\rlap{$\vcenter{\hbox{$\scriptstyle#1$}}$}\rvaskip}
\def\mapup#1{\rvagap\Big\uparrow\rlap{$\vcenter{\hbox{$\scriptstyle#1$}}$}\rvaskip}
\def\lmapdown#1{\lvaskip\llap{$\vcenter{\hbox{$\scriptstyle#1$}}$}\Big\downarrow\lvagap}
\def\lmapup#1{\lvaskip\llap{$\vcenter{\hbox{$\scriptstyle#1$}}$}\Big\uparrow\lvagap}

% Wrappable diagrams
\newcount\forno \forno0
\def\arrno#1#2{\global\advance\arr1 \edef\eeqnno{\the\arr}%
	\global\advance\forno1 \edef\eforno{\the\forno}%
	\xdef#2{\noexpand\llink{equation.\eforno}{\eeqnno}}% Link: from an equation number to its definition; xdef to ensure it can be seen outside of \wrapdiagram
	#1{(\anchor{equation.\eforno}{\eeqnno})}} % Anchor: equation number
\newbox\mdiag
\def\wrapdiagram{%
	\setbox\mdiag\vtop\bgroup
	\null % an empty hbox to ensure proper vertical positioning
	\vskip\baselineskip
	\inewcount\arr \arr0
	\baselineskip0pt
	\lineskip4pt
	\lineskiplimit4pt
	\let\par\cr
	\obeylines
	\halign\bgroup\hfil$\displaystyle##$\hfil\cr
	\ewrapdiagram}

\def\ewrapdiagram#1{#1
	\egroup
	\egroup
	\vskip0pt plus \dp\mdiag \penalty-250 \vskip0pt plus-\dp\mdiag % ensure the diagram fits on a single page
	\hangafter-\dp\mdiag
	\divide\hangafter\baselineskip
	\advance\hangafter-2
	\hangindent-\wd\mdiag
	\advance\hangindent-2em
	\hbox to\hsize{\hfil\dp\mdiag0pt \box\mdiag}%
	\ignorespaces}

% METAPOST diagrams                                                                                                     
\newlinechar=10
\inewtoks\preamble
{\endlinechar=10 \catcode`#=12 \global\preamble{
prologues := 3;

verbatimtex
\let\endprolog\endinput
\input dpmac/dpmac

\expandafter\gobbleinit\input }\global\appendonceexpand\preamble\jobname\global\append\preamble{
\catcode`\^=7
etex

input cmarrows
setup_cmarrows(arrow_name = "texarrow"; parameter_file = "cmr10.mf"; macro_name = "drawarrow");
setup_cmarrows(arrow_name = "doublearrow"; parameter_file = "cmr10.mf"; macro_name = "drawdarrow");
def drawmarrow expr p = _apth:=p; _finmarr enddef;
rule_thickness#:=.4pt#;    % cmr10.mf: thickness of lines in math symbols
def _finmarr text t_ =
  drawarrow subpath(0, 0.5 * length(_apth)) of _apth t_;
  draw subpath(0.5 * length(_apth), length(_apth)) of _apth withpen pencircle scaled rule_thickness# t_;
enddef;

def object(suffix O)(expr x,y)(expr l) =
  save O;       
  pair O;
  O := (x,y) * u;
  picture O.tx;    
  O.tx := thelabel(l,O);
  draw O.tx;                         
enddef;                                    

def smorphism(suffix A,B) =
  save ss, tt;
  ss := xpart ((A..B) intersectiontimes bbox A.tx);
  tt := xpart ((A..B) intersectiontimes bbox B.tx);
  drawarrow subpath(ss,tt) of (A..B);
enddef;

def morphism(suffix A,B)(expr l)(expr f)(suffix $) =
  smorphism(A, B);
  label.$(l, point f[ss, tt] of (A..B));
enddef;
}}%

\newcount\vertex                                      
\ifx\mathspecials\undefined\def\mathspecials{}\fi
\def\diagram{\begininlinemp\buffertoks={}\grabdiagram}
\def\grabdiagram{\mathspecials\grabdiagramaux}                                                 
\def\grabdiagramaux#1;{\vertex0 \dcom#1,*}                          
\def\dcom{\futurelet\next\dcomswitch}                                          
\def\dcomswitch{\ifcat a\noexpand\next \let\next\dcomalpha                                       
        \else\if*\noexpand\next \addcode{\the\buffertoks}\endinlinemp\let\next\gobble                                                 
        \else\if[\noexpand\next \let\next\grabscale                                                                
        \else\errmessage{Unrecognized diagram command \next}\let\next\relax\fi\fi\fi\next}
\def\grabscale[#1]{\dimen0=#1 \addcode{save u; u = \the\dimen0;}\dcom}
\def\dcomalpha#1{\def\objectname{#1}\futurelet\next\dcomalphaswitch}
\def\dcomalphaswitch{\ifcat a\noexpand\next \let\next\dcommorphism\else                                                          
        \expandafter\edef\csname vertex:\objectname\endcsname{\the\vertex}%              
        \if:\noexpand\next\let\next\grabcoords                                              
        \else\if=\noexpand\next\let\next\grabobjectequ                                     
        \else\errmessage{Expected : or = while processing a diagram object, got \meaning\next}\let\next\relax\fi\fi\fi\next}
\def\grabcoords:#1,#2={\toks\vertex{#1,#2}\grabobjectlabel}
\def\grabobjectequ={\edef\tmp{\the\toks\vertex}\ifx\tmp\empty\errmessage{No coordinates specified for vertex \the\vertex: \objectname}\fi\grabobjectlabel}
\def\grabobjectlabel#1,{\addcode{object(\objectname, \the\toks\vertex, }\addunexpandedcode{btex #1 etex);}\advance\vertex1 \dcom}
\def\dcommorphism#1{\def\tobjectname{#1}%
        %\edef\tmpa{\csname vertex:\objectname\endcsname}\expandafter\ifx\tmpa\relax\errmessage{No such vertex: \objectname}\fi
        %\edef\tmpb{\csname vertex:\tobjectname\endcsname}\expandafter\ifx\tmpb\relax\errmessage{No such vertex: \tobjectname}\fi
        \def\labelpos{.5}%                                      
        \futurelet\next\dcommorphismswitch}                     
\def\dcommorphismswitch{\if.\noexpand\next \expandafter\grabmorphismdir \else \setupmorphismlabel \expandafter\grabmorphismpos\fi}
\def\setupmorphismlabel{
        \edef\vlabeldira{direction.\objectname.\tobjectname}%
        \edef\vlabeldirb{direction.\tobjectname.\objectname}%
        \expandafter\ifx\csname\vlabeldira\endcsname\relax
        	\expandafter\ifx\csname\vlabeldirb\endcsname\relax
		        \edef\tmpa{\csname vertex:\objectname\endcsname}\expandafter\ifx\tmpa\relax\errmessage{No such vertex: \objectname}\fi
		        \edef\tmpb{\csname vertex:\tobjectname\endcsname}\expandafter\ifx\tmpb\relax\errmessage{No such vertex: \tobjectname}\fi
		        \ifnum \tmpa<\tmpb \edef\vlabeldir{direction.\tmpa.\tmpb}\else \edef\vlabeldir{direction.\tmpb.\tmpa}\fi
		        \expandafter\ifx\csname\vlabeldir\endcsname\relax\errmessage{No label direction specified for morphism \objectname->\tobjectname}\fi
		        \edef\labeldir{\csname\vlabeldir\endcsname}%                        
		\else
        		\edef\labeldir{\csname\vlabeldirb\endcsname}%                        
		\fi
	\else
        	\edef\labeldir{\csname\vlabeldira\endcsname}%                        
	\fi
}                                                                                        
\def\grabmorphismdir.{\def\labeldir{}\futurelet\next\grabmorphismdirec}
{\catcode`\@=13                                                               
\gdef\grabmorphismdirec{\ifx@\next \let\next\grabmorphismposition
        \else\if=\noexpand\next \let\next\grabmorphismequ               
        \else \let\next\grabmorphismdirect\fi\fi\next}                       
\gdef\grabmorphismdirect#1{\edef\labeldir{\labeldir#1}\futurelet\next\grabmorphismdirec}
\gdef\grabmorphismpos{\ifx@\next \expandafter\grabmorphismposition \else \expandafter\grabmorphismequ\fi} 
\gdef\grabmorphismposition@#1={\def\labelpos{#1}\grabmorphismlabel}
}
\def\grabmorphismequ={\grabmorphismlabel}
\def\grabmorphismlabel#1,{%
        \addcodebuffer{morphism(\objectname, \tobjectname, }%
        \addunexpandedcodebuffer{btex \everymath{\scriptstyle}#1 etex, }%
        \addcodebuffer{\labelpos, \labeldir);}%
        \dcom}

% Label extraction and definition
\let\printextract\gobble
%\let\printextract\print % print all extracted labels
\def\hinitlabelcommand#1{\printextract{initializing label command \string#1}%
	\gdef#1{\printlabel{invoked label \string#1}% #1: label command, #2: label id for DVI, #3: typesetted text
		\ifsuppressbackref
			\edef\key{\expandafter\gobble\string#1}%
			\llink{\csname id.\key\endcsname}{\csname text.\key\endcsname}% Link: from a label (theorem or bibliography) to its definition
			%\csname text.\key\endcsname
		\else
			\global\advance\backref1 %
			\printbackref{label \expandafter\gobble\string#1: backref.\the\backref\space at line \the\inputlineno}%
			\iftypesetting
			\else
				\blah
				\recordbackref#1
			\fi
			\anchor{backreference.\the\backref}{}% Anchor: back reference for a label (theorem or bibliography)
			\edef\key{\expandafter\gobble\string#1}%
			\llink{\csname id.\key\endcsname}{\csname text.\key\endcsname}% Link: from a label (theorem or bibliography) to its definition
		\fi
		}}
\let\initlabelcommand\hinitlabelcommand
\def\pinitlabelcommand#1{\printextract{initializing label command \string#1}%
	\gdef#1{\printlabel{invoked plain label \string#1}% #1: label command, #2: label id for DVI, #3: typesetted text
		\iftypesetting
			\edef\key{\expandafter\gobble\string#1}%
			\csname text.\key\endcsname
		\else
			\blah
		\fi}}
\newread\labelin
\newif\iflabelcont
\let\terminate=\relax % allow \terminate to be read by \read
\long\def\labelauxaux#1\terminate
{}
\def\preprocesslabel#1{%
	\printextract{Processing label \string#1}%
	\edef\key{\expandafter\gobble\string#1}%
	\initlabelcommand#1
	\expandafter\initlabelcommand\csname v\key\endcsname
	\labelauxaux
}
\def\preprocessbib#1{%
	\printextract{Processing bib \string#1}%
	\initlabelcommand#1
	\labelauxaux
}
\long\def\labelaux#1{\ifx#1\label\let\next\preprocesslabel\else\ifx#1\bib\let\next\preprocessbib\else\let\next\labelauxaux\fi\fi\next}
\def\processoneline{\expandafter\labelaux\labelline\relax\relax\relax\terminate}
\def\preprocess#1{% preprocessing stage to define all labels, back references, bibliographic items, and the table of contents
	% first pass: predefine command sequences for labels and references
	\openin\labelin=#1 \labelconttrue
	\loop
		\read\labelin to\labelline
		\ifeof\labelin\let\next\labelcontfalse\else\let\next\processoneline\fi
		\next
	\iflabelcont\repeat
	% second pass: process labels, bibliography, back references, and the table of contents
	\expandafter\gobbleinit\input#1
	\ifhmode\par\fi\vfill\eject % for LaTeX
	\ifhmode\par\fi\vfill\supereject
}

\def\importlabels#1{ % import labels from an external document
	\recorddupsfalse
	\let\initlabelcommand\pinitlabelcommand
	\preprocess{#1}%
	\let\initlabelcommand\hinitlabelcommand
	\recorddupstrue
	\cont={}% discard the external table of contents
	\vlist={}% discard the verification list
	\let\chapname\undefined \secn0 \parn0 \backref0 % reset the numbering
}

% Primary typesetting routine

\newif\iftypesetting % are we in the final typesetting stage?

% Label and bibliography collection stage
\typesettingfalse % no typesetting at this stage
\def\blah{blah} % placeholder for future references
\output{\setbox0\box255 \setbox0\box\footins \deadcycles0 } % fake typesetting
\let\bib\tbib % collect bibliographic items at this stage
\let\refs\relax % do not typeset bibliography
\everypar{\numpar}
\parn0
\def\par{\finishpar} % no paragraph back references
% Collect embedded METAPOST files and write them to \jobname.gen.mp
\newif\ifmetapost \metapostfalse
\edef\filestem{\jobname.gen}
\newcount\figno
\newwrite\mpout
\newtoks\outtoks
\def\inimp{\ifmetapost\else\global\metaposttrue\immediate\openout\mpout=\filestem.mp \addcode{\the\preamble}\fi}
\figno0
% Temporarily set up large width and height to suppress over/underfull boxes
\newdimen\oldhsize
\oldhsize=\hsize
\newdimen\oldvsize
\oldvsize=\vsize
\hsize\maxdimen
\vsize\maxdimen
\hbadness10000
% Preprocess the file
\preprocess\jobname % collect all labels and bibliography from the main documents and possibly also external labels
% Restore the previously saved dimensions
\hsize\oldhsize
\vsize\oldvsize
\ifx\fmtname\plainfmtname
\hsize\plaintextwidth
\vsize\plaintextheight
\fi
\hbadness1000
% Process back references
\printerr{(\jobname.tex}
\printbackref{list of all back references: \the\backreflist}%
\the\backreflist % process all back references
\ifsuppressunusedbib\def\verifybib#1#2{}\fi
\the\vlist % verify if there are any unused references or bibliography items
\printerr{)}
% Finalize and compile the METAPOST file
\ifmetapost
\addcode{end}
\immediate\closeout\mpout
\immediate\write18{mpost -interaction nonstopmode \filestem.mp}% can also compile the METAPOST file separately
\ifeof18 \warning{Compile the METAPOST file \filestem.mp manually using mpost \filestem.mp}\let\runmp\warning\fi
\fi
\let\addcode\gobble % do not write to the closed file again

% The typesetting stage
\typesettingtrue
\def\importlabels#1{} % stop collecting labels and bibliographic items from other documents
\ifscroll \vsize\maxdimen\inewbox\abox\output{\setbox\abox\vbox{\unvbox255\unskip}\shipbox\abox}%
\else % real typesetting
	\ifx\fmtname\plainfmtname
	\totalht\plaintextheight
	\advance\totalht.1in
	\advance\totalht2\vmargin
	\totalwd\plaintextwidth
	\advance\totalwd2\hmargin
	\setpapersize\totalwd\totalht
	\hoffset-1in
	\advance\hoffset\hmargin
	\voffset-1in
	\advance\voffset\vmargin
	\fi
	\output{\plainoutput}
\fi
\let\blah\undefined % disallow placeholder references
\def\bib#1\par{} % do not collect bibliographic items at this stage
\def\refs{\raggedright\rightskip0em plus \maxdimen \advance\bibindent1em \everypar{}\the\bibt\ignorespaces} % typeset bibliography at this stage
\def\addverunused#1#2{} % do not collect verification data at this stage
\def\addcont#1#2#3{} % do not touch the table of contents at this stage
\def\prepass#1{} % do not collect labels and bibliography from other files at this stage
\parn0
\parbreftrue % typeset paragraph back references at this stage
\everypar{\numpar}
\let\chapname\undefined \secn0 \backref0 % reset the numbering
\figno0
\expandafter\gobbleinit\input\jobname\relax
\ifhmode\par\fi\vfill\eject % for LaTeX
\ifhmode\par\fi\vfill\supereject
\end
