%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 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.
\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}%
  \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 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 }

\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{500} % 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
%-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

%+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}%
  \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
    \getp@ram{notebase}{\newn@testyle}{\newn@testyle}\edef\n@tebase{\ifx\p@ram\relax\newn@testyle\else\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
    \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
        \pdfsavepos\x@\write\x@\p@rlocs\x@{\x@\noexpand\x@\@parnote\x@{\newn@testyle}{\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 \dimen0=\prevdepth\kern-\dimen0 \fi\fi% Kill decenders at the end of the note
 \fi
 \egroup % end the insert (started in \m@kenote) 
 \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
 \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}} % 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\edef\@sf{\spacefactor\the\spacefactor}\/\fi%
  % if footnote is on a chapter number ...
  \ifinextended #3\edef\@wrap{\global\setbox\sid@barnotes=\vbox\bgroup\unvbox\sid@barnotes}\else
    \ifdoingt@ble #3\edef\@wrap{\global\setbox\t@blenotes=\vbox\bgroup\unvbox\t@blenotes\hsize=\t@blehsize}\else%
      \ifhe@dings #3\edef\@wrap{\global\setbox\he@dingnotes=\vbox\bgroup\unvbox\he@dingnotes}%
      \else\edef\@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 
  \setn@tewidth{#1}%
  \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
      \hsize=\maxdimen
    \else
      \hsize=\n@tewidth
    \fi
%%% single-column notes:
    \interlinepenalty\interfootnotelinepenalty % set penalty to break lines
    \let\styst@k\empty
    \parfillskip=0pt plus 1fil
    \leftskip=0pt \rightskip=0pt
    \getp@ram{justification}{#1}{#1}%
    \ifx\p@ram\c@nter
     \leftskip=\noteRag \rightskip=\leftskip \parfillskip=0pt
    \else\ifx\p@ram\l@ftb@l
     \rightskip=\noteRag \ifRTL\parfillskip=0pt \fi
    \else\ifx\p@ram\l@ft
     \rightskip=\noteRag \ifRTL\parfillskip=0pt \fi
    \else\ifx\p@ram\r@ght
     \leftskip=\noteRag \ifRTL\else\parfillskip=0pt \fi
    \fi\fi\fi\fi
    \getp@ram{leftmargin}{#1}{#1}%
    \ifx\p@ram\relax \else \advance \ifRTL\rightskip\else\leftskip\fi\p@ram \IndentUnit \fi
    \getp@ram{rightmargin}{#1}{#1}%
    \ifx\p@ram\relax \else \advance \ifRTL\leftskip\else\rightskip\fi\p@ram \IndentUnit \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
        \baselineskip=0pt
      \else
        \s@tbaseline{#1}{#1}%
      \fi
    \fi
    \ifp@ranotes\else
      \prevdepth=0pt % 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
%      \setbox0=\hbox{\XeTeXuseglyphmetrics=0 \char32}\dimen0=\ht0
%      \ifdim\dimen0<\baselineskip
%        \dimen1=\baselineskip\advance\dimen1 by -\dimen0
%        \vskip\dimen1
%		\trace{f}{\ch@pter:\v@rse : Footnote vskip=\the\dimen1, baselineskip=\the\baselineskip, strut height=\the\dimen0, prevdepth=\prevdepth}%
%        \prevdepth=-1000pt
%	  \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}%
    \ifp@ranotes\else\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
  \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%
        %\showbox0
        %\setbox0=\hbox{\unhbox0 \removehboxes}%
      \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}%
  \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 \dimen0=\prevdepth %
    %\showbox\csname endn@te-#1\endcsname
    \checkp@ranotes{#1}%
    \ifp@ranotes
      \ifdim \dimen0>0pt \kern-\dimen0\fi
      \ifvoid\csname endn@te-#1\endcsname\else
        \setbox0=\vbox{\maken@tepara{\csname endn@te-#1\endcsname}{#1}}%
        %\showbox0
        \unvbox0
      \fi
    \else
      \s@tbaseline{#1}{#1}%
      {%\x@\showbox\csname endn@te-#1\endcsname
      \setbox0=\vbox{\unvbox\csname endn@te-#1\endcsname}%
      %\showbox0
      \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.
  \ifp@ranotes \parfillskip=0pt \else\parfillskip=0pt plus 1fil\fi%\else\strut\fi
  \t@gend{Note}%
  \par
  \ifp@ranotes \@ch@ckadjustments   \fi
  %\setbox0\lastbox\setbox0\hbox{\unhbox0}\xdef\l@stboxwid{\the\wd0}\box0
  \ifp@ranotes\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
  \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}%
      %\showbox9
  \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
 %\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
\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
  \n@xt{#1}}

% insert a note class in which each note is on its own line
\def\separateins@rtn@tecl@ss#1{%
  \def\cl@ss{#1\g@tndstat}%
  \edef\tmp{#1}\ifx\tmp\l@stnoteclass\lastn@tetrue\else\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\box\voidb@x
    \vbox{%
    \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
    }% This would permit breaking the last paragraph. Unfortunately it also permits breaking before the last note.: \setbox0\lastbox\unvbox0 %\showlists
    \fi}% output notes

% insert a note class in which each note is in the same paragraph
\def\parains@rtn@tecl@ss#1{%
  \def\cl@ss{#1\g@tndstat}%
  \dimen0=\prevdepth
  \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}{parains@rtn@tecl@ss \cl@ss, pd=\the\dimen0, c:\the\count\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\global\f@rstnotefalse % output rule before first note
    \else
      \kern\InterNoteSpace
    \fi
    \penalty10000
    %\ifnum\pagenumber=8\showbox\th@cl@ss\fi
    {\maken@tepara{\th@cl@ss}{#1}}%
  \fi}

% insert a note class which is two column study notes style
\def\studyins@rtn@tecl@ss#1{%
  \def\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
    \fi%\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
    \dimen0=\prevdepth\ifdim \dimen0>0pt \kern-\dimen0\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}
\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 width\endcsname 1 \else 0\fi\fi
          \n@tewidth=\csname column\c@rrdstat width\endcsname
        \else
          \trace{d}{c@rrdstat currently set to '\c@rrdstat'.  No column width}%
          \n@tewidth=\csname columnLwidth\endcsname
        \fi
     \else\n@tewidth=\textwidth\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
        \else\ifColNotes\colwidth\else\textwidth\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?
\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
\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}\ifx\tmp\l@stnoteclass\lastn@tetrue
  \else
    \lastn@tefalse
  \fi
  \ifnewparnotes\ifparnoteskillprevdepth
    \dimen0=\prevdepth\ifdim\dimen0>0pt \kern-\dimen0 \prevdepth=0pt \fi
  \fi\fi % Prevdepth correction, because makevboxofhboxes won't (can't) obey it.
  \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
  \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}%
  \XeTeXuseglyphmetrics=3 
  \edef\n@tetype{#2}%
  \ifnewparnotes
    \makevboxofhboxes
    %\ifnum\interactionmode=1 \showbox 3\showlists\fi
    \penalty10000
    \dimen1=\dp3
    \unvbox3
    %\kern -\dimen1
  \else
    \penalty 10000 % Prevent breaking before par!
    \noindent % starting making new paragraph
    \ifNoteTracing\tracingparagraphs=1\fi
    %\ifnum\pagenumber=8\showbox0\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
  \ifparnoteskilldepth
    \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{%
  \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}%
  %\showbox\n@tetmp
  \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
  \disc@rdmvbohb % trash any trailing glue/penalties, etc.
  \s@t@@adj
  \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 
      %\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=\interfootnotelinepenalty
            \penalty12346
          \fi
        \else 
          \interlinepenalty=\interfootnotelinepenalty
          \penalty12345
        \fi
        %\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)}%
            \unhbox1  \@@adjP\global\let\@@adjP\empty
            {\removehboxes}
            %\showlists
            \endgraf
          \fi
        \else
          \trace{fp}{Joining \currn@tetype\space 2(\the\wd2) with 1(\the\wd1)}%
          \noindent\leavevmode \@@adjP\global\let\@@adjP\empty
          \unhbox2 \internotespace
          \setbox1\hbox{\unhbox1{\removehboxes}}%
          \unhbox1
          %\showlists
          \endgraf
        \fi
        \let\notef@rstindent\onotef@rstindent
        \ifdim\ht3>0pt \dimen0=\prevdepth
        \ifdim\dimen0=0pt \else\kern-\dimen0\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=\interfootnotelinepenalty % set penalty to break lines
        \ifnum\tmpcount=1\else\lastn@tefalse\fi
      \fi
    \fi
    \ifhbox2
      \setbox1=\hbox{\ifdim\wd2>0pt \unhbox2 \internotespace \fi\unhbox1}%\nonstopmode\showbox1
      \repeat
  \trace{fp}{After unboxing, \the\tmpcount, h1=\the\ht1, lnw=\lastn@tewid a:\@@adj, aP:\@@adjP}%
  \tempfalse\ifnum\tmpcount=3 \temptrue\else\ifnum\tmpcount=-1 \iff@rstnote \temptrue\fi\fi\fi
  \ifhbox1\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 \dimen0=\dp0 \box0 \penalty10000\prevdepth=\dimen0 \fi
    \noindent\leavevmode\@@adj\global\let\@@adj\empty
      \unhbox1{\removehboxes}\endgraf\ifdim\ht3>0pt\dimen0=\prevdepth\ifdim\dimen0=0pt\else\kern-\dimen0\fi\fi\unvbox3%
    %\nonstopmode\showbox3
  }\fi%
  %\showbox5
  \lastn@tefalse 
  \ifvoid5\else
    \trace{fp}{Reinstating final line/note}%
    \setbox3\vbox{\interlinepenalty=\lastnoteinterlinepenalty\widowpenalty=\lastnotewidowpenalty \clubpenalty=\lastnoteclubpenalty %\baselineskip=\csname n@te-\n@tetype-bls\endcsname
       \unvbox3\setbox1\lastbox\dimen1=\lastskip\unskip
       %\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 before last line}%
       \ifdim \dimen0=0pt % A normal skip = normal paragraph
         \penalty\interfootnotelinepenalty
         %\ifdim\dimen1=0pt\else \vskip\dimen1 \fi
       \else % interline kern means a lastnotepar
         \penalty\lastnoteparpenalty
       \fi
       %\hrule\penalty10000
       \leavevmode\unkern \@@adj\global\let\@@adj\@@adjP\global\let\@@adjP\empty\ifdim\ht1 >0pt  \unhbox 1{\removehboxes}\internotespace\else\fi \unhbox5}%
    %\showbox3
  \fi
  %\ifnum\pageno=3 \showbox 2\fi
  %\showbox3
  \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


%+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
