%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Part of the ptx2pdf macro package for formatting USFM text
% copyright (c) 2007 by SIL International
% written by Jonathan Kew
%
% Permission is hereby granted, free of charge, to any person obtaining  
% a copy of this software and associated documentation files (the  
% "Software"), to deal in the Software without restriction, including  
% without limitation the rights to use, copy, modify, merge, publish,  
% distribute, sublicense, and/or sell copies of the Software, and to  
% permit persons to whom the Software is furnished to do so, subject to  
% the following conditions:
%
% The above copyright notice and this permission notice shall be  
% included in all copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  
% EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  
% MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND  
% NONINFRINGEMENT. IN NO EVENT SHALL SIL INTERNATIONAL BE LIABLE FOR  
% ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  
% CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  
% WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
%
% Except as contained in this notice, the name of SIL International  
% shall not be used in advertising or otherwise to promote the sale,  
% use or other dealings in this Software without prior written  
% authorization from SIL International.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Note style macros

%+cnote_makenote
% We keep a list of all the note classes in \n@tecl@sses, each prefixed with \\ and enclosed in braces.
% Then we can define \\ on the fly, and execute the \n@tecl@sses list to apply it to all classes.
\newif\ifDBGshownoteboxes
\newtoks\n@tecl@sses
\newcount\n@teid % Each note should have a unique number. 

% for each Note marker defined in the stylesheet, we allocate a "note class"
% with its own \insert number (see TeXbook!)
%
\def\m@ken@tecl@ss#1{%
  \trace{n}{m@ken@tecl@ss #1}%
        \trace{fp}{Penalties are ilp:\the\interlinepenalty, wp:\the\widowpenalty, cp:\the\clubpenalty}%
  \newcl@sstrue
  \def\n@wcl@ss{#1}%
  \let\\=\ch@ckifcl@ss \the\n@tecl@sses % check if this note class is already defined
  \ifnewcl@ss \allocatecl@ss{#1}\fi
}
\def\ch@ckifcl@ss#1{\def\t@st{#1}\ifx\t@st\n@wcl@ss\newcl@ssfalse\fi}
\newif\ifnewcl@ss

% new note class: append to the list in \n@tecl@sses, and allocate an \insert number
\def\allocatecl@ss#1{%
  \x@\n@tecl@sses\x@{\the\n@tecl@sses \\{#1}}%
  \ifcsname zplacenotes-#1\endcsname\else% zplacenotes-#1 is an endnote macro. (as is ztestnotes-#1) Trigger a warning rather than leave an undefined macro.
    \x@\gdef\csname zplacenotes-#1\endcsname{\write1{WARNING: p.\the\pageno: zplacenotes-#1 used in text when #1 is a footnote, not an endnote.}}%
    \x@\gdef\csname ztestnotes-#1\endcsname{\write1{WARNING: p.\the\pageno: ztestnotes-#1 used in text when #1 is a footnote, not an endnote.}\@ndnotesfoundfalse}%
  \fi
  \relax%
  \ifdiglot%
    \def\col@do##1{\n@wnoteins@rt{#1\@g@tdst@t{##1}}}%
    \x@\each@col\diglot@list\E
  \else%
    \n@wnoteins@rt{#1}%
  \fi%
}
\def\n@wnoteins@rt#1{%
    \trace{n}{Creating note class #1}%
	\x@\n@winsert\csname note-#1\endcsname
	\x@\newb@x\csname noteb@x-#1\endcsname
	\x@\newb@x\csname notesave1-#1\endcsname
	\x@\newb@x\csname notesave2-#1\endcsname
        \x@\newc@unt\csname refn@te-#1\endcsname
}
\def\clearn@tecount#1{\global\csname refn@te-#1\endcsname=0 }
\def\incn@tecount#1{\global\advance\csname refn@te-#1\endcsname by 1 }
\def\exp@ndn@tes#1{\x@\unvcopy\csname noteb@x-#1\endcsname}
\def\clearn@teboxes#1{\global\x@\setbox\csname noteb@x-#1\endcsname\box\voidb@x \global\x@\setbox\csname note-#1\endcsname\box\voidb@x}

\let\n@winsert=\newinsert % work around the \outer nature of \newinsert
%-cnote_makenote
\def\FootnoteMulC{1} % Centrecolumn text
\def\FootnoteMulT{400} % Twocolumn text
\def\FootnoteMulS{400} % Sg column text
\def\FootnoteMulD{900} % Diglot column text - deliberately read excess text for diglots

%+c_setnotecount
% iterate over note classes, set \count for each class  
\def\s@tn@tec@unt#1{%
  \x@\let\x@\th@cl@ss\csname note-#1\endcsname
  \edef\tmp{#1}%
  \ifx \tmp\XrefNotes 
    \global\count\th@cl@ss=\FootnoteMulC % Don't take space for centre column notes.
  \else
    \global\count\th@cl@ss=\count255 
  \fi
  \global\skip\th@cl@ss=0pt
  \trace{n}{Note #1: Count: \the\count\csname note-#1\endcsname}%
}
%-c_setnotecount

%+cnote_initnotes
% set default insert parameters for a note class (updated if we switch to double-column)
\def\initn@testyles{\let\\=\s@tn@tep@rams \the\n@tecl@sses}
\def\s@tn@tep@rams#1{%
  \checkp@ranotes{#1}%
  \ifdiglot
    \ifdiglotSepNotes\s@tn@tep@r@ms{#1}\s@tn@tep@r@ms{#1R}\else\s@tn@tep@r@ms{#1}\fi
  \else\s@tn@tep@r@ms{#1}\fi
}
\def\s@tn@tep@r@ms#1{%
  \count255=\ifdiglot \FootnoteMulD \else \ifp@ranotes \FootnoteMulT \else \FootnoteMulS \fi\fi 
  \s@tn@tec@unt{#1}%
  \x@\skip\csname note-#1\endcsname=\AboveNoteSpace %Skip before footntoes
  \x@\dimen\csname note-#1\endcsname=\maxdimen %Max note skip
}
\newdimen\AboveNoteSpace \AboveNoteSpace=\medskipamount
\newdimen\InterNoteSpace \InterNoteSpace=3.5pt
\newdimen\NoteCallerWidth %Now set in 1timesetup \NoteCallerWidth=1.1ex %Minimum width for callers/callees, helps alignment.
\newdimen\NoteCallerSpace \NoteCallerSpace=.2em
\newdimen\n@tedepth
%-cnote_initnotes

%
% Each USFM note marker is defined to call \n@testyle, with the marker name as parameter
%
%+cnote_notestyle
\def\n@testyle#1{\trace{n}{n@testyle:#1 \c@rrdstat}%
 \let\@@par@f@ntextend\f@ntextend
 \let\notef@ntextend\empty 
 \def\newn@testyle{#1}%
 \catcode32=12\relax % look ahead to see if space or * follows (like char styles)
 \futurelet\n@xt\don@testyle}
\def\don@testyle{\catcode32=10\relax 
 \trace{f}{don@testyle: n@xt='\meaning\n@xt'}%
 \if\n@xt*\ifinn@te\let\n@xt\endn@testyle\else\let\n@xt\badendn@testyle\fi
  \else
  \if\n@xt^\relax
    \let\n@xt\@@startn@testyle
  \else
   \let\n@xt\startn@testyle\fi\fi
 \n@xt}

{\catcode`\^=12 
 \gdef\@@startn@testyle^#1 #2 {%
  \trace{f}{@@startn@testyle: ^#1 #2}%
  %\tracingmacros=1
   \xdef\notef@ntextend{\p@rcent #1xx\E}%
   \@@@startn@testyle{#2}%
}}
\lowercase{\gdef\@@@startn@testyle#1{\startn@testyle~#1 }}%
%-cnote_notestyle

\newif\ifstructmarkerlistcorrect \structmarkerlistcorrecttrue
\newcount\fmc@unt

%+cnote_startnote_start
\def\b@lance{BALANCE}
\lowercase{
 \def\startn@testyle~#1 {% get the caller code as a space-delimited parameter
  \ifinn@te \MSG{Note marker (\newn@testyle) found while still in note style, after \c@rref. End notes properly, notes may not nest.}\endn@testyle*\fi
  \trace{n}{startn@testyle \newn@testyle #1}%
  \traceifset{startnotestyle}%
  \t@stpublishability{\newn@testyle}\ifn@npublishable
    \trace{n}{Not publishable \newn@testyle\c@rrdstat}%
    \begingroup
    %\implicitcl@setrue % Char styles in notes may implicitly close other ones.  We don't care here.
    \let\aftern@te\relax
    %\ifhe@dings\bgroup\fi
    \setbox0=\vbox\bgroup \skipn@testyletrue \inn@tetrue
    \global\n@tenesting=1\relax
    \ifdim\lastskip>0pt \sp@cebeforetrue \else \sp@cebeforefalse \fi % was there a preceding space?
    %-cnote_startnote_start
%+cnote_startnote
  \else
    \leavevmode
    \advance\fmc@unt 1
    \getp@ram{notebase}{\newn@testyle}{\newn@testyle}\ifx\p@ram\relax\edef\n@tebase{\newn@testyle}\else\edef\n@tebase{\p@ram}\fi
    \csname before-\newn@testyle\endcsname
    \def\t@st{#1}%
    \ifx\t@st\pl@s % if it is + then generate an auto-numbering caller
      \inc@utonum{\newn@testyle}%
      \x@\gen@utonum\x@{\newn@testyle}%
    \else\ifx\t@st\min@s \def\them@rk{}% if it is - then there is no caller
    \else \trace{n}{the note parameter is \t@st \space and is \ifx\t@st\-\else not\fi\space \- \space catcode - is \the\catcode`\-}\def\them@rk{#1}% otherwise the caller is the parameter
    \fi\fi
    \trace{n}{starn@testyle - create tmp}%
    \edef\fnt@mp{\string\@parnote{\newn@testyle}{\ifdiglot\dc@rref\else\c@rref\fi}{\the\fmc@unt}{\them@rk}}%
    \begingroup
    \ifstructmarkerlistcorrect\else
      \implicitcl@setrue % Char styles in notes implicitly close other ones unless someone declares the list of structural markers is correct (see structm@rker in ptx-charstyle. FIXME: develop testcase for new structural markers.
    \fi
    \x@\let\x@\aftern@te\csname after-\newn@testyle\endcsname
    \ifdim\lastskip>0pt \sp@cebeforetrue \else \sp@cebeforefalse \fi % was there a preceding space?
    \resetp@rstyle                                                              %(1)
    \getp@ram{callerstyle}{\newn@testyle}{\newn@testyle}% see if a caller style was defined
    \ifx\p@ram\relax\edef\c@llerstyle{v}\else\edef\c@llerstyle{\p@ram}\fi % if not, treat it like "v"
    \getp@ram{notecallerstyle}{\newn@testyle}{\newn@testyle}\ifx\p@ram\relax 
      \let\n@tec@llerstyle\c@llerstyle
    \else
      \let\n@tec@llerstyle\p@ram
    \fi
    \m@kenote{\n@tebase}{\newn@testyle}{%
        \everypar={\ifRTL\beginR\fi}\cancelcutouts % begin a note insertion in the given style
        \ifx\them@rk\empty \trace{n}{note caller is EMPTY}\setbox0=\box\voidb@x \else
          \trace{n}{note main caller}%
          \ifversion{2}{\let\f@ntextend\@@par@f@ntextend}{}%
          \setbox0=\hbox{\x@\cstyle\x@{\c@llerstyle}{\them@rk}}\ht0=0pt\dp0=0pt
          \trace{n}{note caller is \the\wd0 \space wide}%
        \fi
        %\edef\m@sg{\string\noteonpage{\newn@testyle}{#1}}%
        \set@utonum{\newn@testyle}\ifcsname \@utonum\endcsname
          \edef\m@sg{\string\noteonpage{\newn@testyle}{\csname \@utonum\endcsname}}%
          \x@\write\x@\n@tepages\x@{\m@sg{\the\pageno}}% record the page where this note occurred
        \fi
        \pdfsavepos
        \x@\write\x@\p@rlocs\x@{\fnt@mp{\the\pdflastxpos}{\the\pdflastypos}}%
        \getp@ram{callerraise}{\newn@testyle}{\newn@testyle}\ifx\p@ram\relax\box0\else\raise\p@ram\box0\fi % suppress height of caller
        \ifnum\pagetracing>0
          \edef\n@tetxt{\b@lance\space note \newn@testyle\space in \n@tebase. \id@@@\space \ch@pter.\v@rse}%
          \x@\x@\x@\write-1\x@{\n@tetxt}%
        \fi
      }{%
        \ifx\them@rk\empty \trace{n}{note caller is EMPTY}\setbox0=\box\voidb@x \else
          \trace{n}{note caller}%
          \ifversion{2}{\let\f@ntextend\notef@ntextend}{}%
          \setbox0=\hbox{\hss\x@\cstyle\x@{\n@tec@llerstyle}{\them@rk}\hss}\ht0=0pt\dp0=0pt
        \fi
        \getp@ram{notecallerraise}{\newn@testyle}{\newn@testyle}\ifx\p@ram\relax
          \getp@ram{callerraise}{\newn@testyle}{\newn@testyle}\fi
        \ifx\p@ram\relax\box0\else\raise\p@ram\box0\fi
      }\bgroup \ifversion{2}{\let\f@ntextend\notef@ntextend}{}%
    \global\n@tenesting=1\relax
    \trace{b}{BALANCE note: style=\newn@testyle}%
    \csname start-\newn@testyle\endcsname % execute the <start> hook, if defined
    \ignorespaces
  \fi
 }
}
%-cnote_startnote

%+cnote_endnote
\def\badendn@testyle*{\trace{n}{badendn@testyle}%
  \MSG{Bad marker \newn@testyle* (end-of-note when not in a note) near \c@rref. Ignored.}%
}
\def\endn@testyle*{\trace{n}{endn@testyle}%
 \end@llpoppedstyles{N*}%end any character styles within the note
 \ifskipn@testyle \else
  \csname end-\newn@testyle\endcsname % execute <end> hook
   \ifp@ranotes\else\ifhmode\endgraf\fi\ifvmode \n@tedepth=\prevdepth\kern-\n@tedepth \fi\fi% Kill decenders at the end of the note
 \fi
 \egroup % end the insert (started in \f@@t from \m@kenote, triggers \@foot)
 \ifx\@wrap\empty\else\egroup\let\@wrap\empty\fi%\@wrap would have started a box
 \global\inn@tefalse
 \global\n@tenesting=0 
 \ifsp@cebefore \global\let\n@xt=\ignorespaces % ignore following spaces if there was a preceding one
   \else \global\let\n@xt\relax \fi
 \aftern@te
 \endgroup
 \beginL\x@\write\x@\p@rlocs\x@{\n@tesize}\endL
 %\showboxbreadth=999\showlists
 \traceifcheck{startnotestyle}%
 \n@xt}
\newif\ifsp@cebefore
\newif\ifskipn@testyle
%-cnote_endnote

%+cnote_autonum
\def\inc@utonum#1{\set@utonum{#1}\count255=0\csname \@utonum\endcsname\relax % increment note counter for class #1
 \advance\count255 by 1 \x@\xdef\csname \@utonum\endcsname{\number\count255}}

%% overridden by ptx-callers.tex
\ifx\gen@utonum\undefined
 \def\gen@utonum#1{%
  \set@utonum{#1}%
  \count255=0\csname \@utonum \endcsname
  \loop \ifnum\count255>26 \advance\count255 by -26 \repeat
  \advance\count255 by 96 \edef\them@rk{\char\count255}}%
\fi
\newif\ifresetallcols\resetallcolstrue
\def\resetautonum#1{\set@utonum{#1}\x@\xdef\csname \@utonum\endcsname{0}\trace{n}{Resetting autonum#1}} % Reset the current note counter (f)
\def\resetSpecAutonum#1{\x@\xdef\csname autonum#1\endcsname{0}} % reset the exact note counter f / fL / R
\def\resetAllAutonum#1{\def\col@do##1{\ifcsname autonum#1##1\endcsname\resetSpecAutonum{#1##1}\fi}%
   \x@\each@col\diglot@list\E} %reset all note counters.
\def\carefulResetAutonum#1{%Reset note counters if they're not page-reset
  \expandafter\ifx\csname page-caller #1\endcsname\relax 
    \trace{n}{resetting callers (#1}%
    \ifdiglot
      \ifresetallcols
        \resetAllAutonum{#1}%
      \else
        \resetSpecAutonum{#1\c@rrdstat}%
      \fi
    \else\resetSpecAutonum{#1}%
    \fi
  \fi
}
\newif\ifbookresetcallers 
\bookresetcallerstrue
\addtostartptxhooks{\resetallcolstrue\ifbookresetcallers\let\\=\carefulResetAutonum\the\n@tecl@sses\fi}
%-cnote_autonum

%+c_makenote
% footnote macros based on plain.tex \footnote, \vfootnote
\newbox\he@dingnotes
\newbox\t@blenotes
\newbox\n@tetmp % temporary note box.
%:
% #1 ~ class to store the note in. E.g. f, x. The results of `\NoteBlendInto`.
% #2 ~ class to use for styling (what the source had in it)
% #3 ~ styled text for main text caller
% #4 ~ styled text for in note caller
\def\@wrap{}
\def\m@kenote#1#2#3#4{\let\@sf\empty
  % text is read later
  \x@\ifx\csname ch@pter\g@tdstat waiting\endcsname\undefined
    \x@\let\csname ch@pter\g@tdstat waiting\endcsname\relax
  \fi
  \ifhmode\def\@sf{\spacefactor\the\spacefactor}\/\fi%
  % if footnote is on a chapter number ...
  \ifinextended #3\def\@wrap{\global\setbox\sid@barnotes=\vbox\bgroup\unvbox\sid@barnotes}\else
    \ifdoingt@ble #3\def\@wrap{\global\setbox\t@blenotes=\vbox\bgroup\unvbox\t@blenotes\hsize=\t@blehsize}\else%
      \ifhe@dings #3\def\@wrap{\global\setbox\he@dingnotes=\vbox\bgroup\unvbox\he@dingnotes}%
      \else\def\@wrap{}%
        \x@\ifx\csname ch@pter\g@tdstat waiting\endcsname\relax #3
        \else % there is a chapter number waiting
          \trace{n}{Note will be saved for chapter number}%
          \everypar={}\x@\let\csname ch@pter\g@tdstat waiting\endcsname\relax
          \global\setbox\ch@pternote=\hbox{\box\ch@pternote #3}%
        \fi % output caller
      \fi
    \fi
  \fi%
  % @sf preserves the space factor (e.g. extra space after a period), restore it now
  \@sf \@wrap\vm@kenote{#1}{#2}{#4}}
%-c_makenote

%+c_vmakenote
\newtoks\d@note
\newif\ifFootNoteGlyphMetrics %Relationship between the margin and the last footnote: does the note use the descender or the actual bottom of the glyph. If the former, then the bottom of notes have a common baseline. If the latter, then the glyphs sit as close to the bottom margin as they can, which may permit an extra line of text. 
\FootNoteGlyphMetricsfalse
  
\newcount\currn@tetparnum % Note type paragraph number
\newif\ifusespacebefore \usespacebeforetrue
\def\vm@kenote#1#2#3{%
  \inn@tetrue%
  \global\advance\n@teid by 1 %
  \edef\m@sg{\string\@noteid{\the\n@teid}{#1}}%
  \let\next\relax%
  \edef\n@tetype{#1\g@tndstat}%
  \TRACE{vm@kenote \n@tetype}%
  \x@\let\x@\th@sins\csname note-no-insert-\n@tetype\endcsname
  \checkp@ranotes{#1}% check whether this note class is to be paragraphed 
  \trace{M}{note-no-insert-\n@tetype \space is \ifx\th@sins\relax not \fi defined, p@ranotes\ifp@ranotes true\else false\fi, group=\the\currentgrouplevel}%
  \setn@tewidth{#1}\trace{M}{noteboxwidth hsize=\the\hsize}%
  \ifnum 1=\ifp@ranotes\ifnewparnotes 1 \else 0 \fi\else 1 \fi 
    \beginL\pdfsavepos\x@\write\x@\p@rlocs\x@{\m@sg{c}{\the\pageno}{\the\pdflastxpos}{\the\pdflastypos}}\endL%
  \fi
  %\ifx\th@sins\relax \d@note{\x@\insert\csname note-\n@tetype\endcsname}%
  \ifx\th@sins\relax \d@note{\x@\insert\csname note-\n@tetype\endcsname}%
  \else \d@note{\th@sins}\fi
  \x@\let\x@\currn@tenum\csname refn@te-#1\endcsname
  \global\advance\currn@tenum by 1
  \global\currn@tetparnum=1
  \xdef\currn@tetype{#1}%
  \trace{n}{Footnote (\n@tetype) [\ch@pter:\v@rse] will \ifp@ranotes\else not \fi be paragraphed and \the\n@tewidth \space wide (page is \the\hsize)}%
  \global\floatingpenalty\@MM % make sure note does not float away from caller to another page
  \the\d@note
  \bgroup\setbox9=\vbox\bgroup% insert note-f (or note-x)
    \ifFootNoteGlyphMetrics
      \XeTeXuseglyphmetrics=3 % so that notes sit on the baseline based on content and not font descender
    \else
      \XeTeXuseglyphmetrics=0 % so that notes sit on the baseline based font descender not contents
    \fi
    \ifp@ranotes\ifcsname nm-cref-#1\endcsname\else
      \hsize=\maxdimen
    \fi\else
      \hsize=\n@tewidth
    \fi
%%% single-column notes:
    \interlinepenalty\interfootnotelinepenalty % set penalty to break lines (Typ 100. Allow the note to be broken by the page-builder
    \let\styst@k\empty
    \ifp@ranotes\leftskip=0pt\rightskip=0pt\parfillskip=0pt\else
    \s@tsideskips{#1}{\noteRag}\fi
    \trace{n}{note(#1) justification=\p@ram, leftskip=\the\leftskip, rightskip=\the\rightskip, parfillskip=\the\parfillskip}%
    \ifx\th@sins\relax
      \s@tbaseline{#1}{#1}%
    \else
      \ifp@ranotes\ifcsname nm-cref-#1\endcsname\else
        \baselineskip=0pt
      \fi\else
        \s@tbaseline{#1}{#1}%
      \fi
    \fi
    \ifp@ranotes\else
      \ifvmode \prevdepth=0pt \fi % Ensure that we start with a baselineskip.
      \ifusespacebefore\getp@ram{spacebefore}{#1}{#1}\trace{n}{note(#1) spacebefore: \p@ram}\ifx\p@ram\relax\else\ifdim\p@ram\verticalsp@ceunit=0pt\else\penalty10004\kern\p@ram\verticalsp@ceunit\penalty10003\fi\fi\fi
    \fi
    \leavevmode % begin paragraph
    \ifnum 1=\ifp@ranotes\ifnewparnotes 1 \else 0 \fi\else 1 \fi 
      \pdfsavepos\beginL\x@\write\x@\p@rlocs\x@{\m@sg{n}{\the\pageno}{\the\pdflastxpos}{\the\pdflastypos}}\endL
    \fi
    \ifdiglot \x@\the\csname diglot\c@rrdstat ho@ks\endcsname \fi%
    \ifRTL\setbox2=\lastbox\beginR\box2\fi % if RTL text this paragraph needs to be RTL
    \xdef\n@tefli{0pt}%
    \ifnum 1= \ifp@ranotes\ifcsname nb-char-#1\endcsname 1\else 0\fi \else 1\fi
      \getp@ram{firstindent}{#1}{#1}\trace{n}{note(#1) firstindent: \p@ram}%
      \dimen0=0pt \ifx\p@ram\relax\else\dimen0=\p@ram \IndentUnit \fi
      \xdef\n@tefli{\the\dimen0 }%
      \ifx\p@ram\relax\else\kern\n@tefli\fi
    \fi
    % if note omitting caller from note (i.e. all callers are *'s)
    \let\stylet@pe\ss@Note\mcpush{\stylet@pe}{#2}%
    \testomitc@ller{#2}\ifomitc@ller\trace{n}{Omitting caller}\else
    % save copy of caller in temporary box, if non-empty add a little space
    \setbox0=\hbox{#3}%
    \ifdim\wd0>0pt \ifdim\wd0 <\NoteCallerWidth% Allow for wide callers, but standardise normal callers to \NoteCallerWidth, for better alignment
      \setbox0=\hbox{\hbox to \NoteCallerWidth{\hfil\box0\hfil}}%
    \fi\fi
    \setbox1=\copy0\unhbox1\ifdim\wd0>0pt \kern\NoteCallerSpace\fi
  \fi
  % currently we do not allow footnotes to break to the next page, so this may not be necessary
%  \splittopskip\ht\f@@tstrut % top baseline for broken footnotes
%  \splitmaxdepth\dp\f@@tstrut
  \t@gstart{Note}{\n@tetype}%
  %\getp@ram{fontsize}{#2}\edef\c@rrfontsize{\ifx\p@ram\relax12\else\p@ram\fi}%
  \s@tfont{#2}{#2}%
  \ifp@ranotes\else\@ch@ckadjustments\fi
  %\ifnum\interactionmode=1\showlists\fi
  %\traceifset{mnote}%
  \futurelet\next\fo@t}% use plain.tex footnote processor, see plain.tex 1166. It ensures that @foot after the following group.
%-c_vmakenote

%+c_endnotes

\def\NoteAtEnd#1{%Treat the specified note as an end-note. Don't use note-#1, as that gets cleared, etc.
  \x@\newb@x\csname endn@te-#1\endcsname
  \x@\gdef\csname addt@endnote-#1\endcsname{%thanks to afterassignment, this gets put immediately after the start of the vbox
    \checkp@ranotes{#1}%
    \ifp@ranotes
      \hsize=\maxdimen
      \x@\ifvoid \csname endn@te-#1\endcsname\else
        %\x@\showbox\csname endn@te-#1\endcsname
        \vbox{}%Sacrificial box for makehboxofhboxes to consume
        \x@\unvbox\csname endn@te-#1\endcsname%
        %\setbox0=\hbox{\unhbox0 \removehboxes}%
        %\ifDBGshownoteboxes\showbox0 \fi
      \fi
    \else
      \x@\ifvoid \csname endn@te-#1\endcsname
        \hbox{}%Empty hbox to force some baselineskip at the top of the box
      \else
        %\x@\showbox\csname endn@te-#1\endcsname
        \unvbox\csname endn@te-#1\endcsname
      \fi
    \fi
    }%
  \x@\gdef\csname note-no-insert-#1\endcsname{\x@\afterassignment\csname addt@endnote-#1\endcsname\global\setbox\csname endn@te-#1\endcsname\vbox}%
  \trace{M}{Setting note-no-insert-#1 addt@endnote-#1}%
  \x@\gdef\csname ztestnotes-#1\endcsname{% Set the @ndnotesfound flag based on one type of note. 
      \ifvoid\csname endn@te-#1\endcsname\@ndnotesfoundfalse\else\@ndnotesfoundtrue\fi}%
  \x@\gdef\csname zplacenotes-#1\endcsname{\ifvmode\else\par\fi \n@tedepth=\prevdepth %
    %\showbox\csname endn@te-#1\endcsname
    \checkp@ranotes{#1}%
    \ifp@ranotes
      \ifdim \n@tedepth>0pt \kern-\n@tedepth\fi
      \ifvoid\csname endn@te-#1\endcsname\else
        \setbox0=\vbox{\maken@tepara{\csname endn@te-#1\endcsname}{#1}}%
        \ifDBGshownoteboxes\showbox0 \fi
        \unvbox0
      \fi
    \else
      \s@tbaseline{#1}{#1}%
      {%\x@\showbox\csname endn@te-#1\endcsname
      \setbox0=\vbox{\unvbox\csname endn@te-#1\endcsname}%
      \ifDBGshownoteboxes\showbox0 \fi
      \unvbox0}%
    \fi
    }% Individual note placement
  \x@\endn@teclasses\x@{\the\endn@teclasses \\{#1}}%
  \x@\plac@ndnotes\x@{\the\plac@ndnotes\csname zplacenotes-#1\endcsname}%
}
\newtoks\endn@teclasses
\newtoks\plac@ndnotes
\newif\if@ndnotesfound
\def\pretextb@rderskip{0pt}
\def\posttextb@rderskip{0pt}
\plac@ndnotes{\ifhmode\endgraf\fi\endn@terule} % Pre-fill the toklist
\def\ch@ckendnotes#1{\x@\ifvoid\csname endn@te-#1\endcsname\else\global\@ndnotesfoundtrue\fi}
\def\zplaceallnotes{\ifhmode\end@llpoppedstyles{N}\fi\bgroup\setbox0\vbox{\the\plac@ndnotes}\unvbox0\egroup}

\newif\ifnotesEachBook
\newif\ifEndNotesEarly % When are automatic endnotes inserted?  Before or after
% the columnswap?   If early, then they occur in 2 column mode and before the
% bookend- hooks. If late, between bookend-all and bookend-final, and may trigger single column mode, 
\newif\ifEndNotesSingleCol % Do Endnotes trigger singlecolumn? (If so, they get set full width!)
\notesEachBooktrue
\EndNotesEarlytrue
\EndNotesSingleColfalse
\addtoinithooks{\NoteAtEnd{fe}}

%-c_endnotes

% use \OmitCallerInNote{f} to omit callers from the note at foot of page
% but leave them in the body text (e.g. all the callers are *'s)
\def\OmitCallerInNote#1{%
  \expandafter\let\csname omit-in-note #1\endcsname=1}
%
\def\testomitc@ller#1{\expandafter\ifx\csname omit-in-note #1\endcsname\relax
  \omitc@llerfalse \else \omitc@llertrue \fi}
\newif\ifomitc@ller

% create a "strut" (see TeXbook) of suitable size for the note style
\def\footstrut{\s@tfont{\newn@testyle}{\newn@testyle}%
  \s@tbaseline{\newn@testyle}{\newn@testyle}%
  \setbox\f@@tstrut=\hbox to 0pt{\XeTeXuseglyphmetrics=0 \char32 \hss}%
  \dimen0=\ht\f@@tstrut \dimen2=\dp\f@@tstrut
  \dimen4=\dimen0 \advance\dimen4 by \dimen2
%  \ifdim\dimen4<\baselineskip
    \dimen6=100\baselineskip \divide\dimen6 by \dimen4
    \multiply\dimen0 by \dimen6 \divide\dimen0 by 100
    \multiply\dimen2 by \dimen6 \divide\dimen2 by 100
%  \fi
  \setbox\f@@tstrut=\hbox{}\ht\f@@tstrut=\dimen0 \dp\f@@tstrut=\dimen2
  \copy\f@@tstrut}

%+c_foot
% called at end of note
\def\n@tesize{}
\def\@foot{%This ends the group that starts with the footnote class.
  %\traceifcheck{mnote}%
  \trace{f}{End of note}%
  \ifp@ranotes \parfillskip=0pt \else\parfillskip=0pt plus 1fil\fi%\else\strut\fi
  \t@gend{Note}%
  \par
  \ifp@ranotes\@ch@ckadjustments
  \else\getp@ram{spaceafter}{\n@tetype}{\n@tetype}\trace{n}{note(\n@tetype) spaceafter: \p@ram}%
    \ifx\p@ram\relax\penalty0 \else\vskip\p@ram\verticalsp@ceunit\fi %FIXME Penalty0??? 
    \setbox0=\hbox to 0pt{\XeTeXuseglyphmetrics=0 \char32 \hss}%
    % surely we don't want a strut above and below?
    %\dimen0=\baselineskip \advance\dimen0 by -\ht0 \advance\dimen0 by -\prevdepth
    %\vskip \dimen0
  \fi
  \x@\xdef\csname n@te-\n@tetype-bls\endcsname{\the\baselineskip}%
  \egroup
  \end@llpoppedstyles{N*}%
  \def\d@##1+##2\E{\if ##1N\else\MSG{Bad marker ##2\space but expected a closing note marker}\fi}\mctopnoms
  \ifDBGshownoteboxes\showbox9 \fi
  \ifp@ranotes\setbox8=\copy9\setbox7=\vbox{\unvbox8\global\setbox6=\lastbox}\setbox8=\hbox{\unhbox6}%
    \xdef\n@tesize{\string\@notebox\string{\n@tetype\string}\string{\the\wd8\string}\string{\the\ht9\string}}%
  \else
    \xdef\n@tesize{\string\@notebox\string{\n@tetype\string}\string{\the\wd9\string}\string{\the\ht9\string}}%
  \fi
  \mcpop\trace{i}{note \n@tetype, height=\the\ht9, \ifn@npublishablec@t non\fi publishable \n@tesize, p@ranotes\ifp@ranotes true \else false\fi, st@dynotes\ifst@dynotes true\else false\fi, \ifx\XrefNotes\n@tetype xrefnote\else normal\fi}%
  \trace{M}{box9[\n@tetype]=\the\ht9 +\the\dp9 *\the\wd9}%
  \ifn@npublishablec@t\global\n@npublishablec@tfalse\else
    \ifx\n@tetype\XrefNotes\relax
      \unvbox9 % Simple normal-height boxes.
    \else
      \ifp@ranotes
        \reheighthboxes{9}{\csname n@te-\n@tetype-bls\endcsname}%
      \else
        \unvbox9 % Simple normal-height boxes.
      \fi
    \fi
  \fi
  \egroup
  \ifcsname endnote-no-insert-\n@tetype\endcsname\csname endnote-no-insert-\n@tetype\endcsname\fi
  \trace{M}{endnote-no-insert-\n@tetype \space is \ifcsname endnote-no-insert-\n@tetype\endcsname\else not \fi defined}%
 %\ifnum\interactionmode=1\showboxbreadth=1000 \showlists\fi
}
\newbox\f@@tstrut
\def\n@teglue{2em plus 1em minus .5em\relax} % glue to be used between paragraphed notes
%-c_foot

\newif\ifkeepn@tes
\newif\ifst@dynotes
\newif\ifnotst@dynotes
\newif\ifonlyst@dynotes
\newif\iffindsh@ve
\def\ins@rtn@tecl@ss#1{% insert the given note class, either paragraphed or separately
  \checkp@ranotes{#1}\setn@tewidth{#1}\ifst@dynotes\ifnotst@dynotes\let\n@xt=\n@ffin\else\let\n@xt=\studyins@rtn@tecl@ss\fi\else
    \ifonlyst@dynotes\let\n@xt=\n@ffin\else
      \ifp@ranotes\let\n@xt=\parains@rtn@tecl@ss\else\let\n@xt=\separateins@rtn@tecl@ss\fi
  \fi\fi
  \trace{f}{note-#1: \l@gdims{\csname note-#1\endcsname} noteb@x-#1:\l@gdims{\csname noteb@x-#1\endcsname}}
  \ifversion{6}{%In v6, unwrapping happens per-notestyle. This isolates note styles from each other and allows per-notestyle shaving
    \x@\let\x@\tnoteb@x\csname noteb@x-#1\endcsname
    \global\setbox\tnoteb@x\vbox{%
      \n@xt{#1}\x@\xdef\csname bls-#1\c@rrdstat\endcsname{\the\baselineskip}}\iffindsh@ve\ifx\n@xt\n@ffin\else\findsh@venotes{\tnoteb@x}{#1}\fi\fi\unvcopy\tnoteb@x}{\n@xt{#1}}}%


% insert a note class in which each note is on its own line
\def\separateins@rtn@tecl@ss#1{%
  \edef\cl@ss{#1\g@tndstat}%
  \edef\tmp{#1}\ifx\tmp\l@stnoteclass\lastn@tetrue\else\ifversion{6}{\lastn@tetrue}{\lastn@tefalse}\fi
  \x@\let\x@\th@cl@ss\csname note-\cl@ss\endcsname % make \th@cl@ss be a synonym for the current note class
  \trace{f}{seperateins@rtn@tecl@ss \ifkeepn@tes keep \fi\cl@ss\space \the\ht\th@cl@ss}%
  % if the noteclass has content to output ...
  \ifvoid\th@cl@ss\TRACE{no note}\else%
    \trace{f}{Noteclass #1: dim:\the\ht\th@cl@ss+\the\dp\th@cl@ss, \the\skip\th@cl@ss, \the\count\th@cl@ss.}%
    %\ifnum\interactionmode=1
      %\showbox\th@cl@ss
    %\fi
    \iff@rstnote\ifvoid\verybottomins\vfill\fi\fi % ignore depth of body text; fill space
    \iff@rstnote\footnoterule\global\f@rstnotefalse\else\kern\InterNoteSpace\fi\penalty10000
    \setbox0\vbox{%
      \ifversion{6}{\penalty0}{}%This will be discarded by the vsplit!
      \ifkeepn@tes\unvcopy\else\unvbox\fi \th@cl@ss
      \iflastn@te%\showlists
        {\count255=\lastnodetype \trace{fp}{separateins@rtn@tecl@ss lnt:\the\count255 \space \decod@lastnode{\count255}}}%
        \count255=\lastpenalty
        \unpenalty
        \trace{fp}{pen:\the\count255}\dimen0=\lastkern\unkern
        \setbox0\lastbox\penalty\lastnoteclubpenalty \box0\kern\dimen0
        \xdef\l@stnotebls{\the\baselineskip}%
      \fi
    }%
    \ifversion{6}{\setbox1\vsplit 0 to 0pt  % Remove initial discardable items.
      \box0 %
    }{\box0 }%
    \fi}% output notes

% insert a note class in which each note is in the same paragraph
\def\parains@rtn@tecl@ss#1{%
  \edef\cl@ss{#1\g@tndstat}%
  \n@tedepth=\prevdepth
  \x@\let\x@\th@cl@ss\csname note-\cl@ss\endcsname % make \th@cl@ss be a synonym for the current note class
  \def\@@oright{}%
  \trace{f}{parains@rtn@tecl@ss \cl@ss, pd=\the\n@tedepth, c:\the\count\th@cl@ss. iniboxSz:\the\ht\th@cl@ss}%
  % if the noteclass has content to output ...
  \ifvoid\th@cl@ss\else
    \iff@rstnote%\ifvoid\verybottomins\vfill\fi %\kern-\lastd@pth\vfil % ignore depth of body text; fill space
      \footnoterule% output rule before first note
    \else
      \kern\InterNoteSpace
    \fi
    \penalty10000
    %\ifnum\pagenumber=8\showbox\th@cl@ss\fi
    {\maken@tepara{\th@cl@ss}{#1}}%
    \global\f@rstnotefalse 
  \fi
}

% insert a note class which is two column study notes style
\def\studyins@rtn@tecl@ss#1{%
  \edef\cl@ss{#1\g@tndstat}%
  \trace{n}{studyins@rtn@tecl@ss \cl@ss \space (from #1)}%
  \x@\let\x@\th@cl@ss\csname note-\cl@ss\endcsname % make \th@cl@ss be a synonym for the current note class
  % if the noteclass has content to output ...
  \ifvoid\th@cl@ss\trace{n}{no note}\else
    \dimen10=0.4\ht\th@cl@ss
    \setbox10=\box1
    \splittopskip=\baselineskip%0pt
    \@@LOOP\temptrue
      \setbox1=\copy\th@cl@ss
      \trace{n}{splitting study box to \the\dimen10}%
      \splittopskip=0pt
      \setbox11=\vsplit1 to \dimen10%
      \setbox12=\vsplit1 to \dimen10%
      \trace{n}{split box remainder \the\ht1}%
      \ifdim\ht1>0pt
        \ifdim\ht1 < \baselineskip \advance\dimen10 by \baselineskip\else \advance \dimen10 by 0.5\ht1\fi
      \else\tempfalse\fi \iftemp\@@REPEAT
    \setbox1=\box10
    \iff@rstnote
      \ifvoid\verybottomins\vfill\fi % ignore depth of body text; fill space
      \noterule{\AboveStudyNoteSpace}{\BelowStudyNoteRuleSpace}{\textwidth}{%
      \StudyNoteRuleLeftIndent \vrule height \StudyNoteRuleThickness width \StudyNoteRuleWidth\textwidth \StudyNoteRuleRightIndent}%
      \global\f@rstnotefalse
    \else\kern\InterNoteSpace\fi
    \setbox11=\vbox{\unvbox11}\setbox12=\vbox{\unvbox12}%
    \ifdim\ht12=0pt \setbox12=\vbox{\hbox to \wd11{}}\fi
    \dimen11=\ht11 \ifdim\dimen11<\ht12 \dimen11=\ht12\fi
    \dimen12=\dp11 \ifdim\dimen12<\dp12 \dimen12=\dp12\fi
    \trace{n}{Study notes (\the\ht11, \the\ht12)=\the\dimen11}%
    \trace{o}{StudyGutterRule\ifStudyGutterRule true\else false\fi, ColumnGutterRule\ifColumnGutterRule true\else false\fi, ht=\the\dimen11 (\the\ht11 >\the\ht12 ) \space dp=\the\dimen12(\the\dp11 <\the\dp12 )}%
    \hbox to \textwidth {\vbox to \dimen11{\unvbox\ifRTL 12\else11\fi \vfil}%
      \makestudycolumngutter{\the\dimen11}{\the\dimen11}{\the\dimen12}{\the\dimen11}{0}%
      \vbox to \dimen11{\unvbox\ifRTL 11\else12\fi \vfil}}%
    \kern\dimen12
    \ifkeepn@tes\else
      \global\setbox\th@cl@ss\box\voidb@x
    \fi
  \fi}

\def\BelowFootNoteRuleSpace{0.5\AboveNoteSpace}
\def\FootNoteRuleThickness{0.4pt}
\def\FootNoteRuleWidth{1}
\def\FootNoteRuleLeftIndent{\hskip 0.00 mm}
\def\FootNoteRuleRightIndent{\hss}
\def\AboveStudyNoteSpace{\AboveNoteSpace}
\def\BelowStudyNoteRuleSpace{0.5\AboveStudyNoteSpace}

\def\StudyNoteRuleThickness{0.4pt}
\def\StudyNoteRuleWidth{1}
\def\StudyNoteRuleLeftIndent{\hskip 0.00 mm}
\def\StudyNoteRuleRightIndent{\hss}
\newif\ifStudyGutterRule

\newif\iff@rstnote
\f@rstnotetrue
\def\footnoterule{\noterule{\AboveNoteSpace}{\BelowFootNoteRuleSpace}{\n@tewidth}{%
  \FootNoteRuleLeftIndent \vrule height \FootNoteRuleThickness width \FootNoteRuleWidth\n@tewidth
  \FootNoteRuleRightIndent}\penalty10000 \hrule height 0pt depth 0pt width 0pt}% 

\def\noterule#1#2#3#4{\trace{f}{noterule #1=\the#1 #2 #3 #4}{\dimen1=#1
  \ifversion{2}{\advance\dimen1 -#2}{}%
  \kern 0pt \penalty10000 \vskip\dimen1 minus 0.5 \dimen1
  \dimen1=#2 % what's this for? \kern -\dimen1
  \t@gstart{Layout}{\cl@ss}%
  \setbox0=\hbox to #3{#4}\dimen0=0.5\ht0\kern-\dimen0\box0\kern-\dimen0\penalty10000
  \vskip \dimen1 minus 0.5 \dimen1
  \penalty10000\kern 0pt\t@gend{Layout}}\prevdepth=-1000pt}


\def\EndNoteRuleWidth{0.5}
\def\EndNoteRuleThickness{0.4pt}
\def\EndNoteRuleLeftIndent{\hss}
\def\EndNoteRuleRightIndent{\hss}
\newdimen\AboveEndNoteSpace \AboveEndNoteSpace=14pt
\def\BelowEndNoteRuleSpace{10pt}

\def\endn@terule{\relax
  \@ndnotesfoundfalse
  \let\\=\ch@ckendnotes\the\endn@teclasses
  \if@ndnotesfound\zendnoterule\fi
}
\def\EndNoteSeparator{\hbox to \hsize{\EndNoteRuleLeftIndent
    \vrule width \EndNoteRuleWidth \hsize  height \EndNoteRuleThickness
    \EndNoteRuleRightIndent}%
  \kern-\EndNoteRuleThickness %
} 
\def\zendnoterule{\noterule{\AboveEndNoteSpace}{\BelowEndNoteRuleSpace}{\hsize}{%
  \EndNoteRuleLeftIndent\vrule width \EndNoteRuleWidth\hsize height \EndNoteRuleThickness
  \EndNoteRuleRightIndent}}

\def\zpostendnoterule{\if@ndnotesfound{%
    \toks0=\everypar\everypar={}\parskip=0pt \parindent=0pt \let\par=\endgraf\parfillskip=0pt %
%  \noindent\hbox{\noindent\kern\columnshift\vbox{\hrule width \dimen0}}\par
    \par
    \n@tedepth=\prevdepth\ifdim \n@tedepth>0pt \kern-\n@tedepth\fi
    \vbox{\kern 0.5\baselineskip
      \EndNoteSeparator
      \kern 0.5\baselineskip}%
    \everypar=\toks0 
  }\fi%
}

% determine if a given note class is to be paragraphed
%+c_paragraphedNotes
\def\ParagraphedNotes#1{\Par@gr@phedNotes{#1\g@tndstat}}
\def\Par@gr@phedNotes#1{\TRACE{Par@gr@phedNotes #1}\x@\let\csname paranotes-#1\endcsname=1}
\def\StudyNotes#1{\x@\let\csname studynotes-#1\g@tndstat\endcsname=1}
\def\NotStudyNotes#1{\x@\let\csname studynotes-#1\g@tndstat\endcsname\relax}

\newif\ifp@ranotes
\newif\ifColNotes \ColNotesfalse
\def\checkp@ranotes#1{%
  \edef\tmp{#1}%
  \ifnum\ifColNotes\ifx\tmp\XrefNotes 0\else 1\fi\else 1\fi =1 %Normal...
    \st@dynotesfalse
    \x@\ifx\csname paranotes-#1\endcsname\relax
      \x@\ifx\csname studynotes-#1\endcsname\relax\else\st@dynotestrue\fi
      \p@ranotesfalse
    \else\p@ranotestrue\fi
  \else
    \ifx\csname paranotes-#1\endcsname\relax
      \p@ranotesfalse%ColNotes but not non-par notes
    \else
      \p@ranotestrue% ColNotes and par notes.
    \fi
  \fi}
%-c_paragraphedNotes

% Notewidth for diglots depends on settings and column. 
%+c_setnotewidth
\def\StudyGutterFactor{1} %A default,
\newdimen\n@tewidth
\def\setn@tewidth#1{%
  \x@\let\x@\th@sins\csname note-no-insert-#1\endcsname
  \ifx\th@sins\relax % Normal footnote
   \ifdiglot
     \trace{d}{setn@tewidth (\show@dstat)}%
     \ifdiglotSepNotes
        \ifnum 1=\ifx\c@rrdstat\empty 0\else \ifcsname column\c@rrdstat fullwidth\endcsname 1 \else 0\fi\fi
          \n@tewidth=\csname column\c@rrdstat fullwidth\endcsname
        \else
          \trace{d}{c@rrdstat currently set to '\c@rrdstat'.  No column fullwidth}%
          \n@tewidth=\csname columnLwidth\endcsname
        \fi
     \else
       \ifst@dynotes\global\n@tewidth=0.5\textwidth
         \dimen9=\StudyGutterFactor\FontSizeUnit
         \advance\n@tewidth by -0.5\dimen9
       \else
         \ifColNotes\ifnum\c@rrentcols=2\global\n@tewidth=\colwidth\else\onecolwidth{\n@tewidth}\fi
         \else\n@tewidth=\textwidth\fi
       \fi
     \fi
   \else
     \ifst@dynotes\global\n@tewidth=0.5\textwidth
       \dimen9=\StudyGutterFactor\FontSizeUnit
       \advance\n@tewidth by -0.5\dimen9
     \else
       \ifColNotes\ifnum\c@rrentcols=2\global\n@tewidth=\colwidth\else\onecolwidth{\n@tewidth}\fi
       \else\n@tewidth=\textwidth\fi
     \fi
   \fi
  \else
    %Assume that the note will be inserted using the current text width.
    \ifnum\c@rrentcols=1 \onecolwidth{\n@tewidth}\else
      \ifcsname endn@te-#1\endcsname 
        \ifEndNotesSingleCol \onecolwidth{\n@tewidth}\else \n@tewidth=\hsize \fi
      \else
        \n@tewidth=\ifdiglot\csname column\c@rrdstat width\endcsname
          \else\ifColNotes\colwidth\else\textwidth\fi \fi
      \fi
    \fi
    %\advance\n@tewidth by -\columnshift
  \fi
  \trace{f}{setn@tewidth #1[\c@rrdstat]: \the\n@tewidth}%
}
%-c_setnotewidth

% reformat the contents of a note class insertion into a single paragraph.
% this is usually done for \x. It is sometimes done for \f.
% (based on code from the TeXbook, appendix D)
% #1 is vbox containing notes as individual paragraphs.
%+c_makenotepara
\newif\ifNoteTracing \NoteTracingfalse
\newif\ifnewparnotes \newparnotesfalse
\newif\ifparnoteskillprevdepth \parnoteskillprevdepthtrue % Kill the depth between note styles
\newif\ifparnoteskilldepth \parnoteskilldepthfalse % Kill the depth of (the last row of) paragraphed note styles 
\newif\ifparnotesruletopskip \parnotesruletopskipfalse % Add topskip after the rule
\newif\ifparnotesmidtopskip \parnotesmidtopskiptrue % add topskip between note styles

\newif\iflastn@te % Is this the last note style that will appear on the page? (ptxv6: last one in the cluster)
\newcount\lastnoteinterlinepenalty % interline penalties when processing the last footnote on the page(allow long note breaking).
\newcount\lastnoteparpenalty % the penalty associated with a manual par-break in the last note.
\newcount\lastnotewidowpenalty % the penalty associated with a widow(last line) in the last note.
\newcount\lastnoteclubpenalty % the penalty associated with a club/orphan (last line) in the last note.
\lastnoteinterlinepenalty=10000
\lastnoteparpenalty=100
\lastnoteclubpenalty=10000
\lastnotewidowpenalty=10000
\newcount\earlynoteinterlinepen@lty % The penalty associated with a re-written note when NOT in the last note. Should be 10k OR MORE. Only a variable for debugging (identification) needs.
\earlynoteinterlinepen@lty=10000
\newskip\internoteskip \internoteskip=15pt plus 12pt minus 7pt
\newskip\noteRag\noteRag=0pt plus 36pt
\def\setl@stnoteclass#1{%define \l@stnoteclass to be the noteclass of the last content-containing note
  \x@\ifdim\x@\ht\csname note-#1\endcsname >0pt
    \xdef\l@stnoteclass{#1}%
  \fi
}

\def\maken@tepara#1#2{%
  % set appropriate hsize width for diglot or not.
  \setn@tewidth{#2}%
  \edef\tmp{#2}\let\th@snoteclass\tmp\ifx\tmp\l@stnoteclass\lastn@tetrue
  \else
    \ifversion{6}{\lastn@tetrue}{\lastn@tefalse}%In ptxversion 6, always consider a note shavable
  \fi
  \n@tedepth=\prevdepth
  \dimen0=0pt
  \trace{f}{maken@tepara #2 f@rstnote\iff@rstnote true \else false \fi parnoteskillprevdepth\ifparnoteskillprevdepth true \else false \fi parnoteskilldepth\ifparnoteskilldepth true \else false \fi FootNoteGlyphMetrics\ifFootNoteGlyphMetrics true \else false \fi pd=\the\n@tedepth}%
  \ifnewparnotes\ifparnoteskillprevdepth
    \ifdim\n@tedepth>0pt \kern-\n@tedepth \fi
  \fi\fi % Prevdepth correction, because makevboxofhboxes won't (can't) obey it.
  \ifnewparnotes\else
    \iff@rstnote\else\prevdepth=0pt \fi
  \fi%
  \n@tedepth=0pt
  \hsize=\n@tewidth%\advance\hsize by -\columnshift % width is full page size
  \let\par=\endgraf\x@\let\csname ch@pter\g@tdstat waiting\endcsname\relax
  \getp@ram{firstindent}{#2}{#2}\let\notef@rstindent=\p@ram
  \everypar={%
    \ifRTL\beginR\fi % respect directionality
    \ifx\notef@rstindent\relax\else\kern\notef@rstindent\IndentUnit \fi}% don't do body text formatting
  %\showbox#1
  \ifkeepn@tes\unvcopy\else\unvbox\fi #1 % open up the vbox of notes to get at the list of individual note boxes
  %\ifnum\interactionmode=1 \showlists\fi
  \ifnewparnotes\else
    \makehboxofhboxes % make a single hbox for all notes of this class
    \unskip\unskip
    %\ifnum\interactionmode=1 \showbox 0\showlists\fi
    \setbox0=\hbox{\unhbox0 \removehboxes}% add internote space                   %(1)
  \fi
  \trace{j}{maken@tepara #2 \c@rrdstat: baseline was \the\baselineskip}%
  \s@tbaseline{#2}{#2}%
  % Enable justification according to marker.
  \trace{j}{maken@tepara #2 \c@rrdstat: baseline now \the\baselineskip}%
  \lineskiplimit=-10pt \leftskip=0pt \rightskip=0pt \parskip=0pt \parfillskip=0pt plus 1fil%\lineskip=10pt
  \linepenalty50
  \interlinepenalty\@MM % set default penalty to separate lines
  \getp@ram{justification}{#2}{#2}%
  \ifx\p@ram\c@nter
     \leftskip=\noteRag\rightskip=\noteRag
  \else\ifx\p@ram\l@ftb@l
     \rightskip=\noteRag
  \else\ifx\p@ram\l@ft
     \rightskip=\noteRag
  \else\ifx\p@ram\r@ght
     \leftskip=\noteRag
  \fi\fi\fi\fi
  \edef\@seglyphmetrics{\the\XeTeXuseglyphmetrics}%
  \ifColNotes\else\XeTeXuseglyphmetrics=3\fi 
  \edef\n@tetype{#2}%
  \ifnewparnotes
    \makevboxofhboxes
    %\ifnum\interactionmode=1 \showbox 3\showlists\fi
    \penalty10000
    \dimen1=\dp3
    \trace{f}{Note placed \the\ht3+\the\dp3}%
    \unvbox3
    %\kern -\dimen1
  \else
    \penalty 10000 % Prevent breaking before par!
    \noindent % starting making new paragraph
    \ifNoteTracing\tracingparagraphs=1\fi
    \unhbox0 % unbox the text so it can be line-wrapped
  \fi
  \unskip\unpenalty\unskip\unskip % remove internote skip info after last note
  % set penalty which allows breaking between notes unless this would cause
  % an extra line to be created.
  \ifhmode
    \par\leftskip=0pt \ifNoteTracing\tracingparagraphs=0\fi
    \dimen1=\prevdepth
  \else
    \global\prevdepth=\dimen1
  \fi
  \ifnum 1=\ifparnoteskilldepth 1 \else \ifx\th@snoteclass\l@stnoteclass 0 \else \ifparnoteskillprevdepth 1 \else 0 \fi\fi\fi
    \trace{f}{removing \the\dimen1 becasue we don't want prevdepth getting in the way}%
    \kern-\dimen1
    \global\prevdepth=0pt
  \fi
  \XeTeXuseglyphmetrics=\@seglyphmetrics
  \trace{f}{Note #2 baselineskip=\the\baselineskip, useglyphmetrics=\the\XeTeXuseglyphmetrics, pd=\the\dimen1 \ifparnoteskilldepth (killed)\fi}%
}
%-c_makenotepara
% make box0 = an hbox contining all the contents of this class
%+c_makehboxofhboxes
\def\makehboxofhboxes{%
  \trace{f}{makehboxofhboxes}%
  \setbox0=\hbox{}%
  \loop\unskip\dimen0=\lastkern \ifdim\dimen0=1sp \unkern\fi\unpenalty\setbox2=\lastbox\unskip \ifhbox2\setbox0=\hbox{\box2\unhbox0}\repeat} 
%
% remove inside level of boxing and adding inter note space after each
%     [[a][b][c]] --> [a \internotespace b \internotespace c \internotespace]
\def\disc@rds#1{%
  %\showlists
  \@LOOP\tmpcount=\lastnodetype\tempfalse\trace{fp}{#1:LNT:\the\tmpcount(\decod@lastnode{\the\tmpcount})}\advance\tmpcount by -10 \ifnum\tmpcount>0 \ifcase\tmpcount % 10= math
      \or\disc@rdskip\unskip\temptrue  %11=glue
      \or\disc@rdkern% 12=kern
      \or\disc@rdpenalty%13=penalty
    \fi\fi
    \iftemp\@REPEAT}
\let\disc@rdskip\empty
\let\disc@rdkern\empty
\let\disc@rdpenalty\empty
\def\removehboxes{%
  \let\disc@rdskip\empty
  \let\disc@rdkern\empty
  \let\disc@rdpenalty\empty
  \disc@rds{rhb}%
  \setbox0=\lastbox\disc@rds{Rhb}%
  \ifhbox0{\removehboxes}\unhbox0 \ifnewparnotes\else \internotespace\fi%
    \fi}
%
\let\disc@rdskip@mvbohb\empty % What does mkvboxofhboxes need discards to do with a skip
\def\disc@rdkern@mvbohb{\dimen0=\lastkern\ifdim\dimen0=1sp \unkern\temptrue\fi}%
\def\disc@rdkern@active{\unkern\temptrue}%
\def\disc@rdpenalty@active{\unpenalty\temptrue}
\def\disc@rdskip@rhh{\skip0=\lastskip\unskip\setbox\n@tetmp\vbox{\vskip\the\skip0\unvbox\n@tetmp}}
\def\disc@rdpenalty@rhh{\count255=\lastpenalty\unpenalty\setbox\n@tetmp\vbox{\penalty\the\count255\unvbox\n@tetmp}\temptrue}
\def\disc@rdkern@rhh{\dimen0=\lastkern\unkern\setbox\n@tetmp\vbox{\kern\dimen0\unvbox\n@tetmp}\temptrue}

\def\reheighthboxes#1#2{%
  \traceifset{reheighthboxes}%
  \trace{n}{reheighthboxes. bls=#2 (\the\baselineskip) }%
  \setbox\n@tetmp\vbox{}%
  \let\disc@rdskip\disc@rdskip@rhh
  \let\disc@rdkern\disc@rdkern@rhh
  \let\disc@rdpenalty\disc@rdpenalty@rhh
  \baselineskip=#2\relax
  %\showbox#1
  \r@tio{\the\baselineskip}{\the\n@tewidth}%
  \let\reheightfactor\@@r@tio
  \trace{n}{Before adjustment, \the\ht#1. Note-width to baselineskip ratio (\the\baselineskip/\the\n@tewidth) is \reheightfactor  (\c@rref)}%
  \unvbox#1
  \disc@rds{rhh}%
  \reheighthb@xes
  \trace{n}{After adjustment box is \the\ht\n@tetmp}%
  \ifDBGshownoteboxes\showbox\n@tetmp\fi
  \unvbox\n@tetmp
}
\def\reheighthb@xes{%
  \setbox2=\lastbox
  \ifvoid2 
    \let\n@xt\relax
  \else
    \ifhbox2
      \setbox1=\hbox{\unhcopy2}%remove stretch
      % calculate proportionate height
      \trace{n}{hbox width: \the\wd1}%
      \ht2=\reheightfactor\wd1
    \fi
    \setbox\n@tetmp\vbox{\box2\unvbox\n@tetmp}%
    \disc@rds{rhh@}%
    \let\n@xt\reheighthb@xes
  \fi
  \n@xt
}
% Discards for makevboxofhboxes
\def\disc@rdmvbohb{%
    \dimen0=0pt
    \let\disc@rdskip\disc@rdskip@mvbohb
    \let\disc@rdkern\disc@rdkern@mvbohb
    \let\disc@rdpenalty\disc@rdpenalty@active
    \disc@rds{mvb}%
}

\let\@@adj\empty
\let\@@adjP\empty
\def\s@t@@adj{\ifdim\dimen0<14sp \ifdim\dimen0>6sp 
    \xdef\@@adj{\looseness\the\numexpr \dimen0 -10\relax \relax}%
    \trace{fp}{Adjustment request:\@@adj}%
    \dimen0=\lastkern\unkern 
  \fi\fi
  \ifdim\dimen0=-2sp
    \ifx\@@adj\empty\else
      \trace{fp}{2nd Adjustment request:\@@adj}%
      \xdef\@@adjP{\@@adj}\global\let\@@adj\empty
    \fi
    \dimen0=\lastkern\unkern 
    \s@t@@adj
  \fi
  }
% Rather than make a single hbox, make vbox of hboxes

\def\makevboxofhboxes{%
  \trace{f}{makevboxofhboxes}%
  \traceifset{vboxofhboxes}%
  \setbox3=\vbox{}% Build up from processed content(new paragraphs prepended)
  \setbox5=\box\voidb@x % The final line of the paragaph.
  \setbox1=\hbox{}% The un-paragraphed current line.
  \setbox0\box\voidb@x % Used to store (remains of) previous vbox content
  %\tracingassigns=1
  %\tracingrestores=1
  \linec@unt=0
  \let\@@adj\empty\let\@@adjP\empty \looseness=0
  \disc@rdmvbohb % trash any trailing glue/penalties, etc.
  \s@t@@adj % but apply adjustment if one was found.
  \ifNoteTracing\tracingparagraphs=1\fi
  \loop
    \setbox2=\lastbox
    \disc@rdmvbohb
    %\showboxdepth=4 \showlists
    \ifvbox2 % Found when there's a carried-over note. Such things should merge seamlessly. Probably has a de-depth kern at the the end, and who knows what line-end /par end kerns
      %\showbox2
      \setbox0\vbox{\ifRTL\beginR\fi%
        \ifvoid0 \else \message{* Unexpected situation in paragraphing footnotes. Please report}%
          \unvbox0
        \fi
        \unvbox2
        {\let\disc@rdkern\disc@rdkern@active\disc@rds{mvb2}}%
        \setbox2=\lastbox
        \global\setbox2\hbox{\unhbox2\let\disc@rdkern\disc@rdkern@active\disc@rds{mvb3}}%
        %\vskip\dimexpr \baselineskip - \ht2\relax
        \unskip
        %\showbox2
        %\showlists
      }%
    \fi
    \ifhbox2
      \setbox2\hbox{\unhbox2}%
      \count255=\wd2 
      \divide\count255 by \hsize 
      \ifDBGshownoteboxes\showbox2 \fi
      %\showboxu%2
    \fi
    \tmpcount=\lastnodetype
    \trace{fp}{Between boxes: kern of \the\dimen0, LNT=\the\tmpcount(\decod@lastnode{\the\tmpcount}) lastn@te\iflastn@te true\else false\fi}%
    %\let\@@adj\empty
    \s@t@@adj
    \trace{fp}{adj: \@@adj, adjP: \@@adjP}%
    \ifdim\dimen0=1sp % Special value - footnote paragraph
      \getp@ram{firstindent}{fp}{fp}%+\n@tetype}%
      \let\onotef@rstindent\notef@rstindent
      \let\n@fli\p@ram
      \advance\linec@unt by \count255
      \trace{f}{firstlineindent for fp+\n@tetype+\styst@k is \notef@rstindent, baselineskip=\the\baselineskip, next back box is \the\ht2+\the\dp2, b5=\the\wd5}%
      \iflastn@te
        \xdef\l@stnotebls{\the\baselineskip}%
        \xdef\lastn@tewid{\the\hsize}%Force no join
      \fi
      \setbox3=\vbox{%box 3 is completed paragraphs.
        \iflastn@te
          \count255=\linec@unt
          \advance\count255 by  -\NoteShaveShortest
          \trace{fp}{note is \the\wd2 \space wide, \the\hsize, \the\count255->\the\linec@unt}%
          \ifnum \count255>-1
            \penalty\lastnoteparpenalty % a paragraph in the last note is a very reasonable place to break if notes are going to break.
            \interlinepenalty=\lastnoteinterlinepenalty \widowpenalty=\lastnotewidowpenalty \clubpenalty=\lastnoteclubpenalty
          \else 
            \interlinepenalty=\earlynoteinterlinepen@lty
            \penalty12346
          \fi
        \else 
          \interlinepenalty=\earlynoteinterlinepen@lty
          \penalty12345
        \fi
        \trace{fp}{Penalties are ilp:\the\interlinepenalty, wp:\the\widowpenalty, cp:\the\clubpenalty}%
        %\showbox2
        \ifvoid2\else
          \vskip\dimexpr\baselineskip - \ht2\relax %reimpose topskip
        \fi
        %\message{nfli:\n@tefli, ep:\the\everypar}%
        \let\notef@rstindent\n@fli
        \ifvoid2 
          \ifdim\wd1>0pt 
            \trace{fp}{Expanding  \currn@tetype\space 1(\the\wd1)}%
            %\penalty 12347
            \unhbox1  \@@adjP\global\let\@@adjP\empty
            {\removehboxes}%
            %\showlists
            \endgraf
          \fi
        \else
          \ifdim\wd1 >0pt \setbox1 \hbox{\unhbox1 {\removehboxes}}\fi%
          \trace{fp}{Joining \currn@tetype\space 2(\the\wd2) with 1(\the\wd1)}%
          %\penalty 12348
          \noindent\leavevmode \@@adjP\global\let\@@adjP\empty
          \unhbox2 
          \ifdim\wd1 >0pt \internotespace \unhbox1\fi
          %\showlists
          \endgraf
        \fi
        \let\notef@rstindent\onotef@rstindent
        \ifdim\ht3>0pt \n@tedepth=\prevdepth
        \ifdim\n@tedepth=0pt \else\kern-\n@tedepth\fi\fi
        \unvbox3}%
        %\setbox1\hbox{\box2
          %\unhbox1}%
        \setbox2\hbox{}%
        %\nonstopmode
        %\showbox
        %\@@adjP\global\let\@@adjP\empty
    \else
      \linec@unt=\count255
      \iflastn@te
        \advance\count255 by  -\NoteShaveShortest
        \xdef\l@stnotebls{\the\baselineskip}%
        \ifdim\lastn@tewid=0pt
          \ifhbox2\xdef\lastn@tewid{\the\wd2}%Remember the width of the last note. If the last line's width is < lastn@tewid, then there might be a case to break it.
            \setbox5\box2\setbox2\hbox{}%
            \trace{fp}{Saved last footnotebox}%
          \fi %
          \lastn@tefalse
        \fi
        \interlinepenalty=\earlynoteinterlinepen@lty % set penalty to break lines
        \trace{fp}{Penalties are ilp:\the\interlinepenalty, wp:\the\widowpenalty, cp:\the\clubpenalty}%
        \ifnum\tmpcount=1\else\lastn@tefalse\fi
      \fi
    \fi
    \trace{fp}{box2 is \ifvoid2 void\else\ifhbox2 hbox \the\ht2+\the\dp2 x\the\wd2 \else\ifvbox2 vbox\fi\fi\fi}%
    \ifhbox2
      \setbox1=\hbox{\ifdim\wd2>0pt \unhbox2 \internotespace \fi\unhbox1}%\nonstopmode\showbox1
      \repeat
  \trace{fp}{After unboxing, \the\tmpcount, b0=\l@gdims{0}, b1=\l@gdims{1}, b3=\l@gdims{3}, b5=\l@gdims{5} lnw=\lastn@tewid a:\@@adj, aP:\@@adjP}%
  %\showlists
  \tempfalse\ifnum\tmpcount=3 \temptrue\else\ifnum\tmpcount=-1 \iff@rstnote \temptrue\fi\fi\fi
  \ifhbox1 \ifdim \dimexpr\wd1 +\ht1 \relax >0pt
    \ifDBGshownoteboxes\showbox0 \showbox1 \showbox3 \fi 
    \setbox3=\vbox{\ifnum 1=
        \iftemp \ifparnotesruletopskip 1 \else 0 \fi
      \else
        \ifparnotesmidtopskip 1 \else 0 \fi
      \fi
      \relax\trace{fp}{imposing midtopskip \the\baselineskip-\the\ht1 }%
      \vskip\dimexpr\baselineskip - \ht1\relax
    \fi%
    %\ifvbox2 \unvbox2\fi
    \ifvbox0 \n@tedepth=\dp0 \box0 \penalty10000 \prevdepth=\n@tedepth \fi
    \noindent\leavevmode
    \ifx\@@adj\empty\else\trace{fp}{Applying adjust, b1:\the\wd1}%
      \@@adj \global\let\@@adj\empty
    \fi
    \unhbox1{\removehboxes}\endgraf\ifdim\ht3>0pt\n@tedepth=\prevdepth\ifdim\n@tedepth=0pt\else\kern-\n@tedepth\fi\fi\unvbox3%
    %\nonstopmode\showbox3
  }\fi\fi%
  %\showbox5
  \lastn@tefalse 
  \ifvoid5
    \trace{fp}{No final line/note?? box 3 is \the\ht3}%
  \else
    \trace{fp}{Reinstating final line/note  a:\@@adj, aP:\@@adjP}%
    \ifDBGshownoteboxes\showbox5 \fi 
    \setbox3\vbox{\interlinepenalty=\lastnoteinterlinepenalty\widowpenalty=\lastnotewidowpenalty \clubpenalty=\lastnoteclubpenalty %\baselineskip=\csname n@te-\n@tetype-bls\endcsname
       \unvbox3 \setbox1 \lastbox\dimen1=\lastskip\unskip
       %\ifvoid1\ifDBGshownoteboxes\showlists\fi\fi
       %\setbox6=\lastbox\global\prevdepth=\dp6\box6 %
       \trace{fp}{skip of \the\dimen1 before last line }%
       \ifdim\ht1>0pt 
         \advance\dimen1 by \ht1 
         \advance\dimen1 by -\baselineskip
         \prevdepth=-\dimen1
       \fi
       \trace{fp}{Prevdepth \the\dimexpr -\dimen1\relax}%
       \disc@rdmvbohb
       \trace{fp}{kern of \the\dimen0 \space before last line}%
       \ifdim \dimen0=0pt % A normal skip = normal paragraph
         \penalty\earlynoteinterlinepen@lty
         %\ifdim\dimen1=0pt\else \vskip\dimen1 \fi
       \else % interline kern means a lastnotepar
         \penalty\lastnoteparpenalty
       \fi
       %\hrule\penalty10000
       \ifDBGshownoteboxes\showbox1 \showbox5 \fi
       \penalty 12340
       \leavevmode\unkern \@@adj\global\let\@@adj\@@adjP\global\let\@@adjP\empty\ifdim\ht1 >0pt  \unhbox 1{\removehboxes}\internotespace\else\fi \unhbox5}%
    \ifDBGshownoteboxes\showbox3 \fi
    %\showbox3
  \fi
  %\ifnum\pageno=3 \showbox 2\fi
  \ifDBGshownoteboxes\showbox3 \fi
  \tracingassigns=0
  \tracingrestores=0
  \traceifcheck{vboxofhboxes}%
} 
% skip between notes in paragraph. skip is good place to break.
\def\internotepenalty{-10}
\def\internotespace{\penalty\internotepenalty\hskip\internoteskip}%
%\def\internotespace{\hfil\hskip\intern@teskip\penalty-10\hfilneg}

\def\r@versevb@x#1{\setbox#1=\vbox{}\loop
  \unskip\unpenalty\setbox0=\lastbox\ifdim\ht0>0pt
    \setbox#1=\vbox{\unvbox#1\box0}\unskip\unpenalty\unskip\repeat
}
\newbox\xr@fbox
\newbox\XrefB@x
\newdimen\XrefSkip \XrefSkip=0pt
\def\m@ke@te@mp#1{%
  \dimen0=\ht\xr@fbox \advance\dimen0 by \baselineskip
  \advance\dimen0 by -\dimen2\advance\dimen0 by -\dp\xr@fbox
  \setbox0=\hbox{}\trace{o}{current height=\the\dimen0}%
  \ifdim\dimen0>#1\loop
    \setbox1=\vbox{\unvbox1\unskip\unpenalty\global\setbox3=\lastbox\unskip}%
    \ifdim\ht3>0pt \setbox0=\hbox{\ifRTL\beginR\fi\unhbox3\unskip\unpenalty\space\unhbox0}\repeat
    \setbox1=\box\voidb@x
  \else\temptrue\loop
    \setbox1=\vbox{\unvbox1 \unskip\unpenalty\global\setbox3=\lastbox\unskip}%
    \ifdim\ht3>0pt \setbox0=\hbox{\ifRTL\beginR\hskip-\leftskip\fi\unhbox3\unskip\unpenalty\unskip\unpenalty\space\unhbox0}%
    \else\ifvoid3\tempfalse\else\trace{o}{m@kexrefbox: Weird nonempty box3 \the\ht3+\the\dp3}\fi\fi
    \dimen1=\dimen0 \advance\dimen1 by \ht1 \advance\dimen1 by \dp1
    \advance\dimen1 by 0pt % This is redundant, but makes it work by I think separating the \fi\ifdim
    \advance\dimen1 by \baselineskip \advance\dimen1 by -\dimen2 \advance\dimen1 by \XrefSkip
    \trace{o}{\space now height is \the\dimen1}%
    \ifdim\dimen1<#1\tempfalse\fi
    \iftemp\repeat
  \fi}
\def\m@kexrefbox#1#2#3#4{%
% #1: height, #2: xrefbox width, #3: note marker/style, returns vbox of remaineder and results in xr@fbox
% #4: justification (only r is significant)
  \setbox\xr@fbox=\ifXrefTopfill\vbox{\vfil}\else\box\voidb@x\fi
  \temptrue
  \let\par=\endgraf\x@\let\csname ch@pter\g@tdstat waiting\endcsname\relax
  \everypar={}% don't do body text formatting
  \x@\let\x@\th@cl@ss\csname note-#3\endcsname % make \th@cl@ss be a synonym for the current note class
  \hsize=#2%\advance\hsize-\XrefNotesMargin\advance\hsize-\XrefNotesMargin
  \if#4r\relax \leftskip=0pt plus 0.8\hsize
    \rightskip=0pt \parfillskip=0pt \else
    \leftskip=0pt \rightskip=0pt plus 0.8\hsize \parfillskip=0pt\fi
  \ifRTL\skip0=\rightskip \rightskip=\leftskip \leftskip=\skip0\fi
  \trace{o}{Inside m@kexrefbox leftskip=\the\leftskip, rightskip=\the\rightskip}%
  % Empty the xref notes so that they don't crop up elsewhere
  \global\setbox\XrefB@x=\copy\th@cl@ss
  \unvbox\th@cl@ss \r@versevb@x{3}\unvbox3
  \s@tbaseline{#3}{#3}%
  \advance\baselineskip 0pt plus 1pt minus 0.1pt
  \loop
    \setbox0=\lastbox
    \dimen2=\ht0
    \ifdim\ht0>0pt
      \dimen1=\ht0
      \setbox1=\vbox{\ifRTL\beginR\fi\unhbox0}%
      \dimen0=\ht\xr@fbox \advance\dimen0 by \ht1 \advance\dimen0 by \baselineskip
      \advance\dimen0 by -\dimen1 \advance\dimen0 by -\dp\xr@fbox
      \ifdim\dimen0>#1
        \trace{o}{Bottom of xref box aiming for \the #1 but currently \the\dimen0. Lastbox \the\ht1}%
        \tempfalse % we're done with the main loop
        \setbox0=\hbox{}%
        \m@ke@te@mp{#1}%
        \ifdim\ht0>0pt \hbox{\unhbox0\unskip\unskip\unpenalty\unskip\unpenalty}\fi
      \fi
      \dimen1=\baselineskip\advance\dimen1-\dp\xr@fbox\advance\dimen1-\dimen2\advance\dimen1\XrefSkip
      \ifdim\ht1>0pt \global\setbox\xr@fbox=\vbox{\unvbox\xr@fbox\vskip\dimen1\unvbox1}\fi
    \else \ifvoid0\else\trace{o}{Unexpected 0 height box in m@kexrefbox}\fi\tempfalse
    \fi
  \iftemp\repeat
  %\ifdim\ht\xr@fbox=0pt \message{empty xref box}\setbox\xr@fbox=\vbox{\hbox to \hsize{\space}}\fi
% completed the main box. Now capture the rest as a normal paragraphed note
  \setbox1=\vbox{}%
  \loop
    \setbox0\lastbox
    \ifdim\ht0>0pt \setbox1=\vbox{\unvbox1\box0}\repeat
  \trace{o}{m@kexrefbox(\the#1, \the#2, marker #3): othernotes=\the\ht1, dimensions of xr@fbox= \the\ht\xr@fbox x \the\wd\xr@fbox, copy \the\ht\XrefB@x}%
  \prevdepth=-10000pt \maken@tepara{1}{#3}%
}
%-c_makehboxofhboxes
%+c_notedbgruler
\def\noteDBGruler{\message{noteruler: \the\AboveNoteSpace, \the\dimexpr \BelowFootNoteRuleSpace\relax, \the\InterNoteSpace}{\smash{\special{color push rgb 1 0 0}\vrule height \dimexpr \baselineskip + \BelowFootNoteRuleSpace \relax depth 0pt width 0.5pt
  \raise \baselineskip \hbox{\vrule height \AboveNoteSpace width 1pt}\special{color pop}%
  \setbox0\hbox{GMl984}%
  \special{color push rgb \ifFootNoteGlyphMetrics 0 1 0\else 0 .3 1\fi}%
  \vrule height \dimexpr \ht0 + \BelowFootNoteRuleSpace \relax depth 0pt width 0.5pt 
  \raise \ht0 \hbox{\vrule height \AboveNoteSpace width 1pt}%
  \special{color pop}%
  \kern 0.5pt
  \special{color push rgb 0.5 0 0}%
  \vrule height \baselineskip width 0.5pt
  \raise \baselineskip \hbox{\vrule height \InterNoteSpace width 1.5pt}%
  \special{color pop}%
  \kern 0.5pt
  \special{color push rgb \ifFootNoteGlyphMetrics 0 .5 0\else 0 0 .5\fi}%
  \raise \ht0 \hbox{\vrule height \InterNoteSpace width 1.5pt}%
  \vrule height\ht0 depth\dp0 width 0.5pt
  \special{color pop}%
}}}
%-c_notedbgruler

% Marginal notes
\def\marginaln@te#1{\x@\gdef\csname note-no-insert-#1\endcsname{\n@test@rt{#1}}%
  \trace{M}{Setting note-no-insert-#1 -> n@testart}%
  \x@\gdef\csname endnote-no-insert-#1\endcsname{\n@te@nd{#1}}%
  \x@\newb@x\csname nm-box-#1\endcsname
  \x@\gdef\csname nm-cref-#1\endcsname{#1}%
  \x@\newc@unt\csname nm-count-#1\endcsname
}
\newcount\tracingonce \tracingonce=0
\def\flyflag{\trace{M}{6. group=\the\currentgrouplevel, \ifcsname endnote-no-insert-x\endcsname fndefined\fi}}
\def\n@test@rt#1{\n@tewidth=\dimexpr \marginnoteswidth - \marginnotesgap\relax
  %\ifnum\tracingonce > 0 \tracingmacros=0\tracinggroups=0\tracingcommands=0\else\tracingmacros=1\tracinggroups=1\tracingcommands=1\fi \advance \tracingonce by 1
  \trace{M}{n@testart #1, starting with n@tewidth=\the\n@tewidth, group=\the\currentgrouplevel}%
  \traceifset{n@test@rt}%
  \x@\setbox\csname nm-box-#1\endcsname\vtop\bgroup%\aftergroup\flyflag\usespacebeforefalse
    \global\p@ranotesfalse
    \s@tsideskips{#1}{-1pt}%
    \ifXrefSideAlign\testXrefSideL\getp@ram{justification}{#1}{#1}%
      \ifnum\tmp=1 % right align
        \ifx\p@ram\c@nter\else
          \ifx\p@ram\r@ght\else
            \dimen1=\leftskip \leftskip=\rightskip \rightskip=\dimen1
        \fi\fi
      \else
        \ifx\p@ram\c@nter\else
          \ifx\p@ram\l@ft\else
            \dimen1=\leftskip \leftskip=\rightskip \rightskip=\dimen1
        \fi\fi
      \fi
    \fi
    \n@tewidth=\marginnoteswidth \advance\n@tewidth -\marginnotesgap \hsize=\n@tewidth
    \ifdim\parfillskip>0pt\hfil\fi
}
\def\n@te@nd#1{%
  \egroup\trace{M}{group=\the\currentgrouplevel}%
  \x@\ifx\csname nm-cref-#1\endcsname\c@rref
    \x@\advance\csname nm-count-#1\endcsname 1%
  \else \csname nm-count-#1\endcsname=0 \x@\xdef\csname nm-cref-#1\endcsname{\c@rref}\fi
  \x@\ifnum\csname nm-count-#1\endcsname=0\relax \edef\t@@mp{\c@rref}\else \edef\t@@mp{\c@rref!#1[\x@\the\csname nm-count-#1\endcsname]}\fi
  \skip1=\baselineskip \s@tbaseline{#1}{#1}%
  \getp@ram{spacebeside}{#1}{#1}\ifx\p@ram\relax\dimen0=1pt\else\dimen0=\p@ram pt\fi
  \advance\dimen0 \marginnotesgap
  \trace{M}{nm-box-#1 \x@\the\x@\ht\csname nm-box-#1\endcsname +\x@\the\x@\dp\csname nm-box-#1\endcsname *\x@\the\x@\wd\csname nm-box-#1\endcsname}%
  \d@marginnote{\x@\the\csname nm-box-#1\endcsname}{\t@@mp}{#1}{\MarginNoteSide}{bottom}{\the\dimen0}{\dimexpr -\dp\pstr@t -\baselineskip}%
  \baselineskip=\skip1
  \traceifcheck{n@test@rt}%
}

%+cnote_declare
\edef\pl@scatcode{\the\catcode`+}
\catcode`+=11
\edef\pl@s{+}
\catcode`+=\pl@scatcode
\catcode`-=11
\def\min@s{-}
\catcode`-=12
%-cnote_declare
\endinput
