% \iffalse meta-comment
% !TEX TS-program = dtxmk 
%
% Copyright (C) 2008 by John Burt <burt@brandeis.edu>
% --------------------------------------------------
% 
% This file may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either version 1.2
% of this license or (at your option) any later version.
% The latest version of this license is in:
%
%    http://www.latex-project.org/lppl.txt
%
% and version 1.2 or later is part of all distributions of LaTeX 
% version 1999/12/01 or later.
%
% \fi
%
% \iffalse
%<package>\NeedsTeXFormat{LaTeX2e}[1997/12/01]
%<package>\ProvidesPackage{edmargin}
%<package>   [2012/09/04 v1.2 edmargin file] 
%
%<*driver>
\documentclass{ltxdoc}
\usepackage{makeidx,multicol,keyval,ifthen}
\EnableCrossrefs         
\CodelineIndex
\RecordChanges
\begin{document}
  \DocInput{edmargin.dtx}
\end{document}
%</driver>
% \fi
%
% \CheckSum{1970}
%
% \CharacterTable
%  {Upper-case    \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
%   Lower-case    \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
%   Digits        \0\1\2\3\4\5\6\7\8\9
%   Exclamation   \!     Double quote  \"     Hash (number) \#
%   Dollar        \$     Percent       \%     Ampersand     \&
%   Acute accent  \'     Left paren    \(     Right paren   \)
%   Asterisk      \*     Plus          \+     Comma         \,
%   Minus         \-     Point         \.     Solidus       \/
%   Colon         \:     Semicolon     \;     Less than     \<
%   Equals        \=     Greater than  \>     Question mark \?
%   Commercial at \@     Left bracket  \[     Backslash     \\
%   Right bracket \]     Circumflex    \^     Underscore    \_
%   Grave accent  \`     Left brace    \{     Vertical bar  \|
%   Right brace   \}     Tilde         \~}
%
% 
% \changes{v1.0}{2008/04/21}{Initial version}
% \changes{v1.01}{2008/04/23}{Bug fix in macro for defining new 
% endnote kinds.}
% \changes{v1.02}{2008/04/28}{Corrections to manual.}
% \changes{v1.2}{2012/09/04}{Fixed a bug the interfered with use of memoir class}


% \GetFileInfo{edmargin.sty}
% 
% \DoNotIndex{\newcommand,\newenvironment,\def,\edef,\else,\renewcommand,\makeatletter,\makeatother}
% \DoNotIndex{\abovedisplayskip,\belowdisplayskip,\abovedisplayshortskip,\belowdisplayshortskip}
% \DoNotIndex{\newcommand, \section, \subsection, \subsubsection,
% \fileversion,} \DoNotIndex{\filedate, \docdate, \leavevmode,
% \vspace, \small, \normalsize, \fontsize,} \DoNotIndex{\newcommand,
% \section, \subsection, \subsubsection, \fileversion}
% \DoNotIndex{\filedate, \docdate, \leavevmode, \vspace, \small,
% \normalsize, \fontsize} \DoNotIndex{\selectfont, \abovedisplayskip,
% \belowdisplayskip, \setlength, \item} \DoNotIndex{\global, \input,
% \def, \edef, \texttt, \textsf, \setcounter}
% \DoNotIndex{\pagenumbering, \oddsidemargin, \evensidemargin,
% \newdimen, \renewcommand} \DoNotIndex{\makeatletter, \let, \@listi,
% \@listl, \z@, \@xpt, \@xipt, \p@ , \@plus2} \DoNotIndex{\@minus5,
% \@minus3, \@plus3, \makeatother, \@minus4, \relax, \pagestyle}
% \DoNotIndex{\fancyhead, \fancyfoot, \thepage, \@ixp}
% \DoNotIndex{\begin \botmark, \botmark, \catcode, \croppadbot,
% \croppadtop} \DoNotIndex{\croppagewidth, \endverse, \equal,
% \fancyfoot, \fancyhead, \fancyhf} \DoNotIndex{\fancypagestyle,
% \firstmark, \footrulewidth, \hbox, \hbox, \headrulewidth}
% \DoNotIndex{\hfil, \hspace, \ifthenelse, \immediate, \itemindent,
% \listparindent} \DoNotIndex{\makeatletter, \nolinebreak, \openout,
% \raggedbottom, \setcounter, \textrm} \DoNotIndex{\value, \vspace,
% \write} 
% \DoNotIndex{\afterpoemtitleskip, \addtocounter, \advance,
% \begin, \bf, \bigskip}
% \DoNotIndex{\bigskipamount, \fi, \@fulltitle, \label, \large, \leftheader}
% \DoNotIndex{\leftheadervalue, \leftmargin, \leftmargini}
% \DoNotIndex{\medskip, \newcounter, \nobreak, \par, \textbf}
% \DoNotIndex{\closeout,\em,\emph,\expandafter,\Huge,\it,\jobname,\kern,\newif,
% \newwrite,\p@,\pageref,\renewenvironment,\rm,\scriptsize,\string, 
% \textsc, \unskip}
% \setcounter{IndexColumns}{2}
% \MakeShortVerb{|}
% \def\fileversion{1.2}
% \def\filedate{4 September 2012}
% \def\docdate{4 September 2012}
% \title{\textsf{Edmargin:} A Simple Design for Critical Editions with Multiple Endnote Series\thanks{This document
%   corresponds to \textsf{edmargin}~\fileversion, dated \filedate.}}
% \author{John Burt \\ \texttt{burt@brandeis.edu}}
% \date{September 4, 2012}
% \maketitle
% \begin{abstract}
%  \textsf{edmargin} provides multiple endnotes sections with running
%  headers of the form ``Notes to pp.~xx--yy'' for critical editions.
%  Rather than having endnote marks in the text, \textsf{edmargin}
%  puts markers in the margins referring to the page in the endnotes
%  sections to which the note refers.
% \end{abstract}
% \tableofcontents
% \hfuzz=50pt

% \section{Introduction} \textsf{edmargin} provides a simple scheme
% for making critical editions.  All critical editions provide several
% series of notes, such as notes about emendations, explanatory notes,
% and notes about the text.  It is a common practice to tie these
% notes to line numbers in the text, whether typographical lines in
% prose text or verse lines in poetry.  Some editions of prose works
% enumerate sentences and paragraphs rather than lines, as the Bible
% does. All of these systems involve considerable amounts of 
% laborious markup.  \textsf{edmargin} provides a different system of 
% annotation which minimizes markup, and also minimizes the 
% possibilities of conflicts among commands. In the text, instead of 
% placing a marker, or remembering the line or sentence number, 
% \textsf{edmargin} simply places a mark in the margin (as for 
% instance ``c'' for a commentary, ``t'' for a textual note, or ``e'' 
% for an emendation) followed by the page number in the relevant 
% endnotes section to which the note refers. So, for instance, if on 
% page 42 of my text I have the anchor for an explanatory note which 
% appears on page 563 of the endnotes section for explanatory notes, 
% \textsf{edmargin} would put \emph{c: p.~563} in the margin on page 
% 42 of the line where that note occurs, and the text of the note 
% would appear on p.~563, with a reference to the page in the text to 
% which it occurs and a lemma drawn from that text. \textsf{edmargin} 
% comes with three built in categories of endnotes (emendations, 
% explanatory notes, textual notes), and facilities for easily 
% constructing other categories of endnote. All of the endnote 
% sections will have running headers of the form ``Textual Notes to 
% pp.~xx--yy.''
%
% This scheme for a critical edition, while considerably simpler than 
% the traditional schemes, does provide the information a critical 
% edition requires, and should be easy for readers to use, provided 
% that there are not many notes on every line. The scheme is modelled 
% on that used by David V. Erdman and Harold Bloom in their edition of 
% \emph{The Complete Poetry and Prose of William Blake}. \textsf{edmargin} 
% can also make notes with markers in the text, in the traditional 
% fashion.
%
%
% With the standard document classes, or the komascript classes,  
%  \textsf{edmargin} requires the following packages to work correctly:
% \textsf{fancyhdr},
% \textsf{ifthen} (for comparing page numbers), \textsf{needspace} (to
% prevent widowed chapter titles in notes sections when resetting
% notes by chapter using either |\notesbychapter| or
% |\resetendnotes|), and \textsf{titleref} (to send the chapter titles
% to the notes section). Because the marginal references are set with 
% |\marginpar| you should also call \textsf{mparhack} if you are 
% setting with the ``twoside'' option. \textsf{edmargin} sets very 
% narrow margin references (only 2em wide). If you are using 
% marginpars for any other purpose, you may need to adjust the width, 
% and monkey with the other parameters to make the marginal 
% references on both sides look symmetrical. To change the width of 
% the marginpars to 4em, issue |\setlength{\marginparwidth}{4em}|.
%
% With \textsf{memoir} class, \textsf{edmargin} requires fewer
% packages, since many of the package functions are built into
% \textsf{memoir} and some, \textsf{fancyhdr} most especially,
% conflict with it.  Minimally, you will need 
% \textsf{ifthen}.  You might wish to call \textsf{memoir} with the
% oldfontcommands option.
%
% \section{Setup} \DescribeMacro{\setupendnoteheaders}
% |\setupendnoteheaders| opens an external channel to receive each of the
% three preset kinds of endnote,  opening external
% files for emendations, textual collations, and explanatory notes
% (with extensions .emd, .ent, and .enx respectively).  Then it sets
% the first page of each notes section to the |empty| pagestyle, since
% you normally don't have running headers on the first page of a
% section.  And it changes the pagestyle for subsequent pages to have
% a running header of the form ``Notes to pages xx--yy.''  This text
% will appear in the center of each header.  It also writes
% information to the external file which will send information to the
% table of contents when the external file for the endnotes section is read back into your
% document.  Each note written to the file increments a counter that
% keeps track of all the endnotes (even if you are resetting the
% number by chapter).  \textsf{edmargin} creates two labels and two
% pagerefs for every note, a label and a pageref for each page in the
% main text \emph{from} which a note comes, and a label and a pageref
% for each page in the notes sections \emph{upon} which the note is
% written.  Finally \textsf{edmargin} writes on the external file for
% the endnotes a command to update the running header for that page of the
% endnotes to be sure that it correctly reflects the pages in the 
% main text from which the notes are drawn.
%
% \DescribeMacro{\makeemendations} \DescribeMacro{\maketextnotes}
% \DescribeMacro{\makeexplanatorynotes} You can use these commands
% individually to set up the predefined classes of endnote, rather
% than using |\setupendnoteheaders| to have \textsf{edmargin} put all three classes
% of  notes in the backmatter of your volume.  (This would be useful if you are not
% intending to make use of all three classes of note.)

% \DescribeMacro{\putemendations} \DescribeMacro{\puttextnotes}
% \DescribeMacro{\putexplanatory} |\puttextnotes|, |\putexplanatory|,
% or |\putemendation| read the external files back into your document
% at the place you specify. Remember that these commands change the
% page style, so if any sections that do not use the same type of running
% header follow these sections (the bibliography, 
% for instance), be sure to restore your prevailing headings style by 
% issuing, for example, |\pagestyle{headings}|
% |\thispagestyle{empty}|. 
%  
%
% \DescribeMacro{\notesbychapter} |\notesbychapter| 
%  resets  the note counters for each kind of endnote and 
% puts a centered line reading ``Chapter \textless\emph{chapter
% number}\textgreater ~ \textless\emph{chapter title}\textgreater'' in
% each of the three predefined sections of the the notes whenever
% |\chapter| is issued.  If you want only the chapter number, not its
% title, issue |\titleinnotesfalse| in your preamble.  Please note
% that with the standard classes \textsf{edmargin} modifies
% |\@chapter|, adding a few lines on to the end of the command.  If
% some other package does the same, you may need to reconcile them.
% With \textsf{memoir} class, |\chapter| is modified only if
% |\notesbychapter| is issued.
%
% \begin{sloppypar}
% \DescribeMacro{\setstyleforchapternotebegin} 
% \DescribeMacro{\setstyleforchapternoteend} 
% |\setstyleforchapternotebegin| and |\setstyleforchapternoteend| 
% allows you to customize the appearance of the line that separates 
% chapters in the endnotes. If, for instance, rather having a 
% centered line in the small font size, you want a flushleft line in 
% the large fontsize, issue 
% |\setstyleforchapternotebegin{\begin{flushleft}\large}| and 
% |\setstyleforchapternoteend{\end{flushleft}}| in your preamble.
% To set these lines in italic or bold, issue 
% |\setstyleforchapternotebegin{\em}| or 
% |\setstyleforchapternotebegin{\bf}| in your preamble. (It's safe, 
% indeed required, to use the old style font commands here, since the 
% chapter title line in the notes is confined to a group, which 
% restricts the scope of the font style command to the line.) If you are
% using \textsf{memoir} class, you should use the oldfontcommands option if you
% plan on issuing |\setstyleforchapternotebegin| and |\setstyleforchapternoteend|.
% Remember that if you open an environment with 
% |\setstyleforchapternotebegin| you must close it in 
% |\setstyleforchapternoteend|. So, for instance, if you wish the 
% chapter line to be set flushleft, in boldface, in normal font size, 
% you would issue 
% |\setstyleforchapternotebegin{\begin{flushleft}\begin{bf}\normalsize}| and 
% |\setstyleforchapternoteend{\end{bf}\end{flushleft}}| in your 
% preamble.
% \end{sloppypar}
%
% \DescribeMacro{\resetendnotes} Conceivably you might wish to do what
% |\notesbychapter| does for each chapter individually. Issue this 
% command just after theh |\chapter| command.  For instance,
% there may be a chapter without endnotes, in which case
% |\notesbychapter| would issue the centered line for that chapter,
% but no notes would follow, which is ugly.  Also, since the
% Bibliography is, as far as memoir class is concerned, a chapter, you
% must use |\resetendnotes| before each chapter rather issuing
% |\notesbychapter| in the preamble if you have a bibliography, or odd
% results will follow.  |\resetendnotes| will put a divider line (and
% give the chapter name) in the endnotes for all three of the preset
% endnote sections.  It will also put a divider line (and give the
% chapter name) for any section you add using |\definenewnotetype|, if
% you define new species of note types.  This is convenient if you
% know that there will be each species of note for a given chapter.
% If the chapter does not include one of the species of notes, you
% would be wiser to use the individual commands in the next paragraph
%
% \DescribeMacro{\resettextnotes} \DescribeMacro{\resetemendations}
% \DescribeMacro{\resetexplanatory} These commands do what
% |\resetendnotes| does, but only for the named section, not for all
% three predefined endnote sections.  If you used |\definenewnotetype|
% to create a new kind of endnote, you will also be able to use the
% corresponding ``reset'' command.  For instance, if you created an
% |\xyznote| command, you can issue |\resetxyznotes|.  If you use
% these commands, issue |\label{chapter\thechapter}| just after the
% |\chapter| command, and then issue the reset commands you plan to 
% use.
%
% \section{Predefined Endnote Sections}
% \textsf{edmargin} comes with three predefined endnotes sections and 
% three predefined kinds of endnote, |\textnote{}|, |\emendation{}|, 
% and |\explanatory{}|. 
%
%
% \DescribeMacro{\textnote} \DescribeMacro{\explanatory} 
% \DescribeMacro{\emendation} Use |\textnote| and its siblings as you 
% would use an ordinary |\endnote|. The argument of each note can be whatever you 
% wish, but for clarity it is a good idea to use as a lemma from the 
% text, since that will make the passage the note refers to clear. 
% For example: |\textnote{lemma] comment}|.
%
% \DescribeMacro{\literaltextnote} \DescribeMacro{\literalemendation} 
% \DescribeMacro{\literalexplanatory} |\literaltextnote| and its 
% siblings are useful for sending information directly to the 
% endnotes section to which the command refers. All of these commands 
% send unexpanded text to the endnote sections, so you use this command
% to send  to the endnote sections commands which will be executed when the endnote section is 
% read back into your document. You can send expanded text using 
% |\immediate\write\textnotes| and its siblings.
%
% \DescribeMacro{\notesincontents} If you do not wish to include a
% line for the endnotes in the table of contents, issue
% |\notesincontentsonfalse|. (This is the default).  To include a line
% for the endnotes in the table of contents, issue |\notesincontents|
% or (toggling the boolean) |\notesincontentsontrue|.  If you wish to
% rethink how to present the notes in the table of contents, rather than
% issuing |\notesincontents|  include
% an |\addtocontents| line in the main text just before you issue |\puttextnotes| or its siblings, the
% command which will read all of your endnotes into your document at
% that point.  For instance, |\notesincontents| sets the word ``Textual Notes'' in the
% table of contents flush with the left margin, just where the numbers
% in the preceding chapters are.  You might, however, wish to indent
% that word just a bit, so that it will be flush with the chapter
% titles above, rather than with the chapter numbers.  If you wish to
% do this, just before issuing |\puttextnotes|, issue
% |\addcontentsline{toc}{chapter}{\protect\numberline{}\the\textnotescontentsname}|.
% Use a similar line for the other endnotes sections, replacing |\textnotescontentsname|
% with |\emendationscontentsname| or |\explanationscontentsname| as the case may be.
%
% \section{Creating New Endnote Sections} 
% \DescribeMacro{\definenewnotetype} You can create as many new kinds 
% of endnote sections as you wish, using the |\definenewnotetype| 
% command. This macro will 
% \begin{enumerate}
% \item Open a new output stream and create a new external file to hold the 
% notes.
% \item Define a ``literalwrite'' command, on the model of 
% |\literaltextnote| for writing literal text directly to that external file.
% \item Send information to that file to set the page style and the 
% running header
% \item Send information to that file to set the title of the endnotes 
% section, and formatting information for the note text. 
% \item Sets up an entry for the table of contents for the note section
% \item Defines a new ``note'' command, and a new marginal marker for 
% that note
% \item Defines a new ``reset'' command for setting notes by chapter, 
% and modifies |\resetendnotes| and |\notesbychapter| to include that 
% new reset command when those two commands are issued
% \item Defines a new ``put'' command (on the model of 
% |\puttextnotes|) 
% for closing the external file and reading it into the text.
% \end{enumerate}
%
% This monster command takes \emph{six} arguments, which are used for 
% setting the names of the various files and commands it creates, and 
% for defining such things as the title of the new notes section and 
% the marginal mark it places in the main text. These arguments, in 
% order, specify
% \begin{enumerate}
% \item The base name used to construct all the commands.
% \item The extension used for the external file
% \item The section title in the running headers of the note section
% \item The section title at the beginning of the note section
% \item The name of the section in the table of contents section
% \item The marginal mark placed by the note command in the text
% \end{enumerate}
% 
% So, for instance,\begin{verbatim}
% \definenewnotetype{xyznote}{xyz}{Xyznotes to}{XYZNOTES}{Xyznotes}{x}
% \end{verbatim} creates a note command |\xyznote{}|, and a command
% for sending literal text to the new note section |\literalxyznote|,
% both of which write to an external file |\jobname.xyz|, sets running
% headers for the notes sections of the form ``Xyznotes to
% pp.~52-60,'' write a title line in the endnotes section giving the
% title as XYZNOTES, writes an entry in the table of contents for
% Xyznotes, and sets the marginal mark set by an |\xyznote| to be
% ``x''. You can read in the xyznotes section into your document with 
% the command |\putxyznote|. And |\resetendnotes| and 
% |\notesbychapter| will put chapter titles in the xyznotes section, 
% just as they do for the textual notes, the explanatory notes, and 
% the emendations sections. Finally, you can use |\resetxyznotes| to 
% set a chapter title in only the xyznotes section.
%
% A trivial use of this commmand would be to make traditional
% endnotes, in which case \textsf{edmargin} would merely be a
% replacement (with a slightly different command set) for
% \textsf{endnote} and \textsf{endheads}.  The command for doing this
% would be \begin{verbatim} \definenewnotetype{endnote}{enn}{Endnotes
% to}{ENDNOTES}{Endnotes}{\relax} \end{verbatim}
% 
% \section{Using \textsf{edmargin} in a Multilingual World}
% 
% By default, \textsf{edmargin} uses English language running 
% headers, but these are easily changed.
% 
% \begin{sloppypar} \DescribeMacro{\changetextnotesname} To change the
% title in the text for the endnote section for textual notes (the
% default is TEXTUAL NOTES), issue |\changetextnotesname{yourversion}|.  To change the running header (by default ``Textual Notes
% to'') issue |\changetextnotesheader{your version}|.  To change the
% name of the textual notes section in the table of contents (the
% default is ``Textual Notes'') issue |\changetextnotescontentsname.|
% Equivalent commands for emendations are |\changeemendationsname|
% |\changeemendationsheadername| and |\changeemendationscontentsname|.
% Equivalent commands for explanatory notes are
% |\changeexplanationsname| |\changeexplanationsheader| and
% |\changeexplanationscontentsname|.  \end{sloppypar}
%
%
% \begin{sloppypar}
% \DescribeMacro{\changesinglepageabbrev}
% \DescribeMacro{\changemultiplepageabbrev} Running headers refer to
% single pages with the English abbreviation ``p.''  and to multiple
% pages with the English abbreviation ``pp.''  To change these issue
% |\changesinglepageabbrev{new abbrev}| or
% |\changemultiplepageabbrev{new abbrev}| respectively.  The ultimate
% outcome is to translate a header of the form ``Notes to
% pp.~xx-yy'' to the form appropriate for your
% language. \end{sloppypar}
%
% \begin{sloppypar}
% \DescribeMacro{\changechapternotesline}If you are using |\resetendnotes| 
% or |\setnotesbychapter| you may also want to 
% change the text of the line those commands add to the endnotes so as to use some
% other word than ``Chapter.''  To change this, 
% issue |\changechapternotesline{your version}|.\end{sloppypar}
%
% \DescribeMacro{\backmattertextfont} |\edmargin| sets the endnote 
% text in the |\small| size. To change it to |\normalsize| issue
% |\renewcommand{\backmattertextfont}{\normalsize}|.
%
% \section{Customization} 
% \DescribeMacro{\notemarkinmargin} 
% \DescribeMacro{\notemarkintext}
% Rather than using marginal references, 
% \textsf{edmargin} can be set to put regular endnote markers in the 
% text and in the endnote sections. The different series of endnotes 
% will be distinguished by using the same abbrevations that were used 
% for marginal references. So, for 
% instance, the third textual note will have a mark that looks 
% ``t:3'' both in the text and in the textual notes section, and the 
% fifth explanatory note will have a mark that ``c:5'' both in the 
% text and in the textual notes section. You can put the endnote 
% markers in the main text rather than in the margins by issuing 
% |\notemarkintext| in your preamble. Putting the endnote 
% markers in the margin is the default, but you can make sure that 
% they go there by issuing |\notemarkinmargin|.
%
% \begin{sloppypar}
% \DescribeMacro{\textnotesparamode} 
% \DescribeMacro{\emendationsparamode} 
% \DescribeMacro{\explanationsparamode} If you wish to print your 
% endnotes as block paragraphs, rather than giving a paragraph to 
% each note, issue |\textnotesparamode|, |\emendationsparamode|, or 
% |\explanationsparamode|, as the case may require. If you have used 
% |\definenewnotetype| to define a note type called |\xyznote|, you 
% can set these notes in block paragraphs by issuing 
% |\xyznotesparamode|. You might consider setting your notes in block 
% paragraphs if you have very many very short notes. \end{sloppypar}
% 
% \section{Known Issues} Because the marginal references are set with 
% |\marginpar| some of them will appear on the wrong side in 
% two-sided printing, unless you include \textsf{mparhack} in your 
% list of packages. Also, if you have more than one reference on a 
% line, the second reference will be moved down a line (marginpars 
% are floats). This may not be an issue if the lemma in the second note 
% makes it clear what in the text it refers to. This problem can be 
% remedied by substituting the \textsf{marn} package and using the 
% |\marn| command in place of |\marginpar|.
%
% Using |\definenewnotetype| with |\notesbychapter| or 
% |\resetendnotes| causes a complaint that an |\iftrue| has been left 
% open whenever a |\chapter| command is written. The origin is 
% probably a problem with |\appendtomacro|. But the error is 
% harmless, it turns out, so I haven't tracked it down.
%
% \StopEventually{\PrintChanges\PrintIndex}
% \section{Implementation}
% \subsection{General Purpose Routines}
% Essentially these routines are code posted by Heiko Oberdiek to 
% comp.text.tex. If you set a counter from a |\pageref|, that 
% |\pageref| is undefined on the first run, and \TeX\ will not only 
% complain about the undefined reference, but give a ``missing 
% number'' error if you try to do anything with that reference, such 
% as compare one page number to another. These commands enable one to 
% use the |\pageref| without generating the missing number error on 
% the first run.
%    \begin{macrocode}
\providecommand*{\ifrefundefined}[1]{%
  \expandafter\ifx\csname r@#1\endcsname\relax
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
}
\providecommand*{\@extract@ref}[2]{%
  \expandafter\expandafter\expandafter#1\csname
r@#2\endcsname{}{}\@nil
}

\providecommand*{\@extractref}{%
  \@extract@ref\@car
}

\providecommand*{\@extractpageref}{%
  \@extract@ref\@secondcar
}

\long\def\@secondcar#1#2#3\@nil{#2}

\providecommand*{\setcounterfromref}[2]{%
  \ifrefundefined{#2}{%
    \protect\G@refundefinedtrue
    \@latex@warning{Reference `#2' on page \thepage \space
        undefined}%
    \setcounter{#1}{0}%
  }{%
    \setcounter{#1}{\@extractref{#2}}%
  }%
}
\providecommand*{\setcounterfrompageref}[2]{%
  \ifrefundefined{#2}{%
    \protect\G@refundefinedtrue
    \@latex@warning{Reference `#2' on page \thepage \space
        undefined}%
    \setcounter{#1}{0}%
  }{%
    \setcounter{#1}{\@extractpageref{#2}}%
  }%
}
\long\def\appendtomacro#1#2{%
\begingroup
    \toks@\expandafter{#1#2}%
    \xdef#1{\the\toks@}%
  \endgroup}
%    \end{macrocode}
% \subsection{Building Blocks}
% First, define some counters:
%    \begin{macrocode}
\newcounter{allendnotes}
\setcounter{allendnotes}{1}
\newcounter{notepageholder} \setcounter{notepageholder}{1}
%    \end{macrocode}
%    \begin{macro}{\mymarks}
% A command to set the marks. This will be called by the page style. 
% Notice that there is a test to see whether \textsf{memoir} class is being 
% loaded, so that marks will be set using \textsf{memoir} commands if 
% they are available.
%    \begin{macrocode}
\newtoks{\singlepageabbrev}
\singlepageabbrev={p.}
\newcommand{\changesinglepageabbrev}[1]{\singlepageabbrev={#1}}
\newtoks{\multiplepageabbrev}
\newcommand{\changemultiplepageabbrev}[1]{\multiplepageabbrev={#1}}
\newtoks{\chapternoteslinename}
\chapternoteslinename={Chapter}
\newcommand{\changechapternotesline}[1]{\chapternoteslinename={#1}}
\multiplepageabbrev{pp.}
\@ifclassloaded{memoir}{\newcommand{\mymarks}{%
   \ifthenelse{\equal{\rightmark}{\leftmark}}%
        {\unskip ~\the\singlepageabbrev~\rightmark}% if equal
        {\unskip ~\the\multiplepageabbrev~\rightmark--\leftmark}}%if not equal
}
{\newcommand{\mymarks}{%
   \ifthenelse{\equal{\firstmark}{\botmark}}%
        {\unskip ~\the\singlepageabbrev~\firstmark}% if equal
        {\unskip ~\the\multiplepageabbrev~\firstmark--\botmark}}%if not equal
}
%    \end{macrocode}
%    \end{macro}
%    \begin{macro}{\endnotespagestyle}
% A command to set the page style in \textsf{fancyhdr}. You might 
% want to change some aspects of this, such as where to put the page 
% number, to make it consistent with the rest of your document.
% Notice that there is a test to see whether \textsf{memoir} class is being 
% loaded, so that the header commands built in to \textsf{memoir} are 
% used if they are available, and the header commands from 
% \textsf{fancyhdr} are used if they are not.
%    \begin{macrocode}	
\@ifclassloaded{memoir}{\makepagestyle{plain}
\makeevenhead{plain}{}{}{{\small\textrm{\thepage}}}
\makeoddhead{plain}{{\small\textrm{\thepage}}}{}{}
\makeevenfoot{plain}{}{}{}
\makeoddfoot{plain}{}{}{}
\makepagestyle{endnotesstyle}
\makeevenhead{endnotesstyle}{{\small\textrm{\thepage}}}
{{\small{\em \the\notesheadername~\mymarks}}}{}
\makeoddhead{endnotesstyle}{}{{\small{\em \the\notesheadername~\mymarks}}}
{{\small\textrm{\thepage}}}
\makeevenfoot{endnotesstyle}{}{}{}
\makeoddfoot{endnotesstyle}{}{}{}
}{\fancypagestyle{plain}{%
\fancyhf{}
\fancyhead[RO,LE]{{\small\textrm{\thepage}}}
\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{0pt}
}
\fancypagestyle{endnotesstyle}{%
\fancyhf{}
\fancyhead[CO]{{\small{\em \the\notesheadername~\mymarks}}}
\fancyhead[CE]{{\small{\em \the\notesheadername~\mymarks}}}	
\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{0pt}
\fancyhead[RO,LE]{{\small\textrm{\thepage}}}
}
}		
%    \end{macrocode}
%    \end{macro}
%    \begin{macro}{\checknoteheaders}
% This macro sets the counter notepageholder to the value given by the
% pageref of the note that is being output.  All that strange business
% with |\string| is there because I want to use the |\immediate\write|
% mechanism to control what gets expanded and what doesn't get
% expanded on the external files for the endnotes, |\jobname.ent| and
% its friends.  Everything except the actual number of the endnote is
% written to the external file as unexpanded tokens.  When, after you
% call |\theendnotes|, you read in the external file for the endnotes,
% for example |\jobname.ent|, all these tokens become a command to set
% the |\mark|.  Notice that there are two forms of this command, one
% for the standard document classes, one for memoir class.
% \textsf{edmargin} chooses which form depending upon which class is
% loaded.
%    \begin{macrocode}
\@ifclassloaded{memoir}{\newcommand{\checknoteheaders}{%
\string\setcounterfrompageref\string{notepageholder\string}%
\string{notl\theallendnotes\string}%
\string\markboth\string{\string\thenotepageholder
\string}\string{\string\thenotepageholder\string}%
}
}{\newcommand{\checknoteheaders}{%
\string\setcounterfrompageref\string{notepageholder\string}%
\string{notl\theallendnotes\string}%
\string\mark\string{\string\thenotepageholder\string}%
}
}

%    \end{macrocode}
%    \end{macro}
% \subsection{User Code}
%    \begin{macro}{\notesincontents}
% This command just sets a boolean. Later, that boolean will be used 
% to determine whether you use the default line for the table of 
% contents for each endnote class, or whether you define one for 
% yourself using |\addtocontents|.
%    \begin{macrocode}
\newif\ifnotesincontentson \notesincontentsonfalse
\newcommand{\notesincontents}{\notesincontentsontrue}
%    \end{macrocode}
%    \end{macro}
% 
%    \begin{macro}{\maketextnotes} 
% Next, setting up the textual collations: |\maketextnotes| opens an
% external file with the extension .ent.  And it sends formatting
% information for the first page of the section, as well as
% information to send to the table of contents.  Also, it sets a label
% for sending the page number of the textual notes to the table of
% contents.
%    \begin{macrocode}
% Extra white space at the top of the first page
\newcommand{\backmatterafterheadersink}{\leavevmode\vspace{11pt}}
% Set notes in small type
\newcommand{\backmattertextfont}{\small}
% writes unexpanded text on the specified external file
\def\strip#1>{}
\newcommand{\literaltextnote}[1]{%
     \begingroup%
        \def\next{#1}%
        \newlinechar='40%
        \immediate\write\textnotes{\expandafter\strip\meaning\next}%
     \endgroup%
 }
\newcommand{\literalemend}[1]{%
     \begingroup%
        \def\next{#1}%
        \newlinechar='40%
        \immediate\write\emendations{\expandafter\strip\meaning\next}%
     \endgroup%
}
\newcommand{\literalexplain}[1]{%
     \begingroup%
        \def\next{#1}%
        \newlinechar='40%
        \immediate\write\explanations{\expandafter\strip\meaning\next}%
     \endgroup%
}
% Nothing happens to textual notes unless you say you want to collect 
% them.
\newif\iftextnoteson \textnotesonfalse
\newif\ifexplanon \explanonfalse
\newif\ifemendationson \emendationsonfalse
% Use tokens rather than hard coded names to make multilingual use easier
\newtoks{\notesheadername}
\newtoks{\edmrgnotesname}
\edmrgnotesname={TEXTUAL NOTES}
\newcommand{\changetextnotesname}[1]{\edmrgnotesname={#1}}
\newtoks{\textnotesheadername}
\textnotesheadername={Textual Notes to}
\newcommand{\changetextnotesheader}[1]{\textnotesheadername={#1}}
\newtoks{\textnotescontentsname}
\textnotescontentsname={Textual Notes}
\newcommand{\changetextnotescontentsname}[1]{\textnotescontentsname={#1}}
% font size for endnote section titles
\newcommand{\backmatterheadingfont}{\fontsize{16}{20}\selectfont}
% setting up an empty page
\newcommand{\clearemptydoublepage}{\newpage{\pagestyle{empty}\cleardoublepage}}
% white space at top of back matter sections
\newcommand{\backmattersink}{\leavevmode\vspace{21.5pt}}
% set up the external file for textual notes
\newcommand{\maketextnotes}{\global\textnotesontrue
  \newwrite\textnotes
  \immediate\openout\textnotes=\jobname.ent
  \literaltextnote{{\par\clearpage
  {\pagestyle{empty}\cleardoublepage}
\thispagestyle{empty}}
\notesheadername={\the\textnotesheadername}
\pagestyle{endnotesstyle}
% \fancyhead{}
% \fancyfoot{}
% \fancyhead[RO,LE]{{\small\textrm{\thepage}}}
% \fancyhead[CO]{{\small{\em \the\textnotesheadername~\mymarks}}}
% \fancyhead[CE]{{\small{\em \the\textnotesheadername~\mymarks}}}
% \fancyfoot[C]{}
\mark{3}
\backmattersink
\begin{center}{\normalfont \backmatterheadingfont \the\edmrgnotesname}\end{center}
\label{textualnotes}
% \lefthyphenmin=2\backmatterafterheadersink\tolerance=500\language=0
\normalfont \backmattertextfont}
\immediate\write\textnotes{\string\ifnotesincontentson}%
\immediate\write\textnotes{\string\addcontentsline\string{toc\string}
\string{chapter\string}\string{\string\the\string\textnotescontentsname\string}}%
%\immediate\write\@enotes{\string{\string\notescontentsname\string}}%
%\string{\string\protect\string\numberline
%\string{\string}  \string\notescontentsname \string}
\immediate\write\textnotes{\string\fi}
}
%    \end{macrocode}
% \end{macro}

% \begin{macro}{\makeemendations}
% Next, the emendations section:
%    \begin{macrocode}
\newtoks{\emendationsname}
\emendationsname={EMENDATIONS}
\newcommand{\changeemendationsname}[1]{\emendationsname={#1}}
\newtoks{\emendationsheadername}
\emendationsheadername={Emendations to}
\newcommand{\changeemendationsheader}[1]{\emendationsheadername={#1}}
\newtoks{\emendationscontentsname}
\emendationscontentsname={Emendations}
\newcommand{\changeemendationscontentsname}[1]{%
\emendationscontentsname={#1}}                                               
\newcommand{\makeemendations}{\global\emendationsontrue 
  \newwrite\emendations
   \immediate\openout\emendations=\jobname.emd
   \literalemend{{\par\clearpage
   {\pagestyle{empty}\cleardoublepage}
\thispagestyle{empty}}
\notesheadername={\the\emendationsheadername}
\pagestyle{endnotesstyle}
% \fancyhead{}
% \fancyhead[RO,LE]{{\small\textrm{\thepage}}}
% \fancyhead[CO]{{\small{\em \the\emendationsheadername~\mymarks}}}
% \fancyhead[CE]{{\small{\em \the\emendationsheadername~\mymarks}}}
% \fancyfoot{}
\mark{3}
\backmattersink
\begin{center}{\normalfont \backmatterheadingfont 
	\the\emendationsname}\end{center}
\label{emendationnotes}
% \lefthyphenmin=2\backmatterafterheadersink\tolerance=500\language=0
\normalfont \backmattertextfont}
\immediate\write\emendations{\string\ifnotesincontentson}%
\immediate\write\emendations{\string\addcontentsline\string{toc\string}
\string{chapter\string}\string{\string\the\string\emendationscontentsname\string}}%
%\immediate\write\@enotes{\string{\string\notescontentsname\string}}%
%\string{\string\protect\string\numberline
%\string{\string}  \string\notescontentsname \string}
\immediate\write\emendations{\string\fi}
}
%    \end{macrocode}
% \end{macro}

% \begin{macro}{\makeexplanatorynotes}
% And the explanatory notes:
%    \begin{macrocode}
\newtoks{\explanationsname}
\explanationsname={EXPLANATORY NOTES}
\newcommand{\changeexplanationsname}[1]{\explanationsname={#1}}
\newtoks{\explanationsheadername}
\explanationsheadername={Explanatory Notes to}
\newcommand{\changeexplanationsheader}[1]{\explanationsheadername={#1}}
\newtoks{\explanationscontentsname}
\explanationscontentsname={Explanatory Notes}
\newcommand{\changeexplanationscontentsname}[1]{%
\explanationscontentsname={#1}}
\newcommand{\makeexplanatorynotes}{\global\explanontrue
     \newwrite\explanations
     \immediate\openout\explanations=\jobname.enx
     \literalexplain{{\par\clearpage
	 {\pagestyle{empty}\cleardoublepage}
\thispagestyle{empty}}
\notesheadername={\the\explanationsheadername}
\pagestyle{endnotesstyle}
% \fancyhead[RO,LE]{{\small\textrm{\thepage}}}
% \fancyhead[CO]{{\small{\em \the\explanationsheadername~\mymarks}}}
% \fancyhead[CE]{{\small{\em \the\explanationsheadername~\mymarks}}}
% \fancyfoot{}
\mark{3}
\backmattersink
\begin{center}{\normalfont \backmatterheadingfont 
	\the\explanationsname}\end{center}
\label{explanatorynotes}
% \lefthyphenmin=2\backmatterafterheadersink\tolerance=500\language=0
\normalfont \backmattertextfont }
\immediate\write\explanations{\string\ifnotesincontentson}%
\immediate\write\explanations{\string\addcontentsline\string{toc\string}
\string{chapter\string}\string{\string\the\string\explanationscontentsname\string}}%
%\immediate\write\@enotes{\string{\string\notescontentsname\string}}%
%\string{\string\protect\string\numberline
%\string{\string}  \string\notescontentsname \string}
\immediate\write\explanations{\string\fi}
}
%    \end{macrocode}
% \end{macro}

% Auxiliary commands for note and title sections
%    \begin{macrocode}
%  
\newcommand{\argpageref}[1]{\pageref{#1}}
\newcommand{\@pagemarktotextnotes}[1]{%
\immediate\write\textnotes{\string\setcounterfrompageref\string{notepageholdertitle\string}%
\string{#1\string}\string\unskip}%
\immediate\write\textnotes{\string\mark%
\string{\string\thenotepageholdertitle\string}}%
}
\newcommand{\@poempagetotextnotes}[1]{%
\immediate\write\textnotes{\string\par\string\argpageref\string{#1\string}\string\unskip}%
\@pagemarktotextnotes{#1}}     
\newcommand{\@poemtitletotextnotes}[1]{\literaltextnote{\textbf{#1}}}
%    \end{macrocode}
%    \begin{macro}{\setupendnoteheaders}
% |\setupendnoteheaders| turns on processing of running headers.
%    \begin{macrocode}
\newif\ifendnoteheaderson \endnoteheadersonfalse
\newcommand{\setupendnoteheaders}{%
\endnoteheadersontrue
\maketextnotes
\makeexplanatorynotes
\makeemendations
}
% \newcommand{\setupendnoteheaders}{%
% \endnoteheadersontrue
% \if@enotesopen \else \@openenotes \fi
% \immediate\write\@enotes{%
% \string\thispagestyle\string{empty\string}
% \string\pagestyle\string{endnotesstyle\string}}
% \immediate\write\@enotes{\string\ifnotesincontentson}%
% \immediate\write\@enotes{\string\addcontentsline\string{toc\string}
% \string{chapter\string}\string{\string\the\string\notescontentsname\string}}%
% %\immediate\write\@enotes{\string{\string\notescontentsname\string}}%
% %\string{\string\protect\string\numberline
% %\string{\string}  \string\notescontentsname \string}
% \immediate\write\@enotes{\string\fi}
% \def\endnote{\@ifnextchar[\@xendnote{\stepcounter{endnote}%
% % my addition begins
%      \stepcounter{allendnotes}\label{notl\theallendnotes}%
%      \immediate\write\@enotes{\checknoteheaders}%
% % my addition ends
%      \protected@xdef\@theenmark{\theendnote}%
%      \@endnotemark\@endnotetext}}
% \let\oldtheendnotes=\theendnotes
% \renewcommand{\theendnotes}{%
% \immediate\write\@enotes{\string\thispagestyle\string{endnotesstyle\string}}
% \oldtheendnotes}
% }
%    \end{macrocode}
%    \end{macro}
% \begin{macro}{\putemendations} This macro closes external file for emendations, 
% reads it in, and puts an entry for the emendations into the table of contents
% file. The macro tests to see whether there is an .aux file from a previous run 
% before doing this, and complains in the .log file if the .aux file does not
% exist.
% 
%    \begin{macrocode}
% \newcommand{\hyphenationforsmall}{\small\bf \hyphenchar\font=45
% \small\it \hyphenchar\font=45
% \small\rm \hyphenchar\font=45
% }
\newcommand{\putemendations}{
\ifemendationson
   \clearemptydoublepage
%    \hyphenationforsmall
   \immediate\closeout\emendations
   \input \jobname.emd
%    \ifpoemcontentson
%        \ifemendationson
% 	\immediate\write\poemcontents{\string\contentspoemtitlefont\ \the\emendationscontentsname}
% 	\immediate\write
%   \poemcontents{\string~ \string\contentsleaders  \string~\ 
%   \string\pageref{emendationnotes} \string\par}
% 	\immediate\write\poemcontents{\string\par \string\smallskip}
%        \fi
%\fi
\else
 \relax
\fi}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\putexplanatory} Does the same for explanatory notes.
% 
%    \begin{macrocode}
\newcommand{\putexplanatory}{
\ifexplanon
   \clearemptydoublepage
%    \hyphenationforsmall
   \immediate\closeout\explanations
   \input \jobname.enx
%    \ifpoemcontentson
%        \ifexplanon
% 	\immediate\write\poemcontents{\string\contentspoemtitlefont\ \the\explanationscontentsname}
% 	\immediate\write
%   \poemcontents{\string~ \string\contentsleaders  \string~\ 
%   \string\pageref{explanatorynotes} \string\par}
% 	\immediate\write\poemcontents{\string\par \string\smallskip}
%        \fi
% \fi
\else
 \relax
\fi}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\puttextnotes} Does the same for textual notes.
% 
%    \begin{macrocode}
\newcommand{\puttextnotes}{
\iftextnoteson
   \clearemptydoublepage
%    \hyphenationforsmall
   \immediate\closeout\textnotes
   \input \jobname.ent
%    \ifpoemcontentson
%        \iftextnoteson
% 	\immediate\write\poemcontents{\string\contentspoemtitlefont\ \the\textnotescontentsname}
% 	\immediate\write
%   \poemcontents{\string~ \string\contentsleaders  \string~\ 
%   \string\pageref{textualnotes} \string\par}
% 	\immediate\write\poemcontents{\string\par \string\smallskip}
%        \fi
% \fi
\else
 \relax
\fi}
%    \end{macrocode}
%    \end{macro}
%    \begin{macro}{\margreftextnote} Macros to set marginal page 
% references showing where in the apparatus a comment upon the 
% marked line is to be found. |\margrefspecial{}| is for occasions
% when you might need to set the label by hand. For instance, suppose
% you have several textnotes on a line, and the note you wish to draw
% attention to is on a different page from the other notes.
% |\margreftextnote| under those circumstances will point only to the
% first note. Use |\margrefspecial| to point to the other note,
% giving |\margrefspecial| a unique argument, and opening that note
% with a \label{} command using the same argument.   
%     
%    \begin{macrocode}
\setlength{\marginparwidth}{2em}
\newcounter{margrefnumber}
\setcounter{margrefnumber}{1}
\newtoks{\margrefmarker}
\margrefmarker={\dag}
\newcommand{\setmargrefmarker}[1]{\margrefmarker={#1}}%
\newcommand{\makemargreflabel}{\string\label\string{margref\themargrefnumber\string}}
\newcommand{\setmargref}{%
\marginpar{\scriptsize{\the\margrefmarker~\the\singlepageabbrev~\pageref{margref\themargrefnumber}}}%
}
\newcommand{\margreftextnote}{%
\iftextnoteson\addtocounter{margrefnumber}{1}%
\immediate\write\textnotes{\makemargreflabel}%
\setmargref\else\relax\fi%                                             
}
\newcommand{\margrefexplanatory}{%
\ifexplanon\addtocounter{margrefnumber}{1}%
\immediate\write\explanations{\makemargreflabel}%
\setmargref\else\relax\fi%                                             
}
\newcommand{\margrefemendation}{%
\ifemendationson\addtocounter{margrefnumber}{1}%
\immediate\write\emendations{\makemargreflabel}%
\setmargref\else\relax\fi%                                             
}
\newcommand{\margrefspecial}[1]{%
\marginpar{\scriptsize {\the\margrefmarker~\the\singlepageabbrev~\pageref{#1}}}
}
% or, perhaps the note marker should be in the text rather than in 
% the margin
\newif\ifn@temarkinmargin%
\n@temarkinmargintrue%
\newif\ifn@temarkintext%
\n@temarkintextfalse%
\newcommand{\notemarkinmargin}{\n@temarkinmargintrue\n@temarkintextfalse}
\newcommand{\notemarkintext}{\n@temarkinmarginfalse\n@temarkintexttrue}
%\newif\ifnotemarkinmargin \notemarkinmargintrue%
\newcounter{enmrnotescratchcount}%
\setcounter{enmrnotescratchcount}{0}
\newtoks{\enmrendnotemarker}%
\newcommand{\makeenmrendnotemarker}{%
\enmrendnotemarker={\the\margrefmarker\theenmrnotescratchcount}}%
\newcommand{\putenmrnotemarkerintext}{%
\hbox\textsuperscript{\scriptsize{\the\enmrendnotemarker}}}%
% To set notes in as a block paragraph, rather than individually
\newif{\iftextnotespara}{\textnotesparafalse}
\newcommand{\textnotesparamode}{\textnotesparatrue}
\newif{\ifemendationspara}{\emendationsparafalse}
\newcommand{\emendationsparamode}{\emendationsparatrue}
\newif{\ifexplanationspara}{\explanationsparafalse}
\newcommand{\explanationsparamode}{\explanationsparatrue}
%    \end{macrocode}
%    \end{macro}
%    \begin{macro}{\textnote}
%    \begin{macrocode}
% \newcommand{\textnote}[1]{%
% \iftextnoteson%
% \margrefmarker={t:}%
% \stepcounter{allendnotes}\label{notl\theallendnotes}%
% \immediate\write\textnotes{\checknoteheaders}%
% \immediate\write\textnotes{\string\par\string{\string\textbf\string{p.\
% \string\pageref\string{notl\theallendnotes\string}\string}\string}}%
% \literaltextnote{~#1}%
% \margreftextnote%
% \fi
% }
\newcounter{enmrtextnotecount}
\newcommand{\textnote}[1]{%
\iftextnoteson%
\margrefmarker={t:}%
\ifn@temarkinmargin%n@temarkinmargin
\margreftextnote%
\else%
\stepcounter{enmrtextnotecount}%
\setcounter{enmrnotescratchcount}{\value{enmrtextnotecount}}%
\makeenmrendnotemarker%
\putenmrnotemarkerintext%
\fi%
\stepcounter{allendnotes}\label{notl\theallendnotes}%
\immediate\write\textnotes{\checknoteheaders}%
\ifn@temarkinmargin%
\iftextnotespara\relax\else%
\immediate\write\textnotes{\string\par}\fi%
\immediate\write\textnotes{\string{\string\textbf\string{\the\singlepageabbrev\
\string\pageref\string{notl\theallendnotes\string}\string}\string}}%
\else
\iftextnotespara\relax\else%
\immediate\write\textnotes{\string\par}\fi%
\immediate\write\textnotes{\string\textsuperscript\string{\theenmrnotescratchcount\string}%
}%
\fi
\literaltextnote{~#1}%
\fi
}
%    \end{macrocode}
%    \end{macro}
%    \begin{macro}{\explanatory}
%    \begin{macrocode}
\newcounter{enmrexplanatorycount}
\newcommand{\explanatory}[1]{%
\ifexplanon%
\margrefmarker={c:}%
\ifn@temarkinmargin%
\margrefexplanatory%
\else%
\stepcounter{enmrexplanatorycount}%
\setcounter{enmrnotescratchcount}{\value{enmrexplanatorycount}}%
\makeenmrendnotemarker%
\putenmrnotemarkerintext%
\fi%
\stepcounter{allendnotes}\label{notl\theallendnotes}%
\immediate\write\explanations{\checknoteheaders}%
\ifn@temarkinmargin%
\ifexplanationspara\relax\else%
\immediate\write\explanations{\string\par}\fi%
\immediate\write\explanations{\string{\string\textbf\string{\the\singlepageabbrev\
\string\pageref\string{notl\theallendnotes\string}\string}\string}}%
\else%
\ifexplanationspara\relax\else%
\immediate\write\explanations{\string\par}\fi%
\immediate\write\explanations{\string%
\textsuperscript\string{\theenmrnotescratchcount\string}%
}%
\fi
\literalexplain{~#1}%
\fi}
%    \end{macrocode}
%    \end{macro}
%    \begin{macro}{\emendation}
%    \begin{macrocode}
\newcounter{enmremendationcount}
\newcommand{\emendation}[1]{%
\ifemendationson%
\margrefmarker={e:}%
\ifn@temarkinmargin%
\margrefemendation%
\else%
\stepcounter{enmremendationcount}%
\setcounter{enmrnotescratchcount}{\value{enmremendationcount}}%
\makeenmrendnotemarker%
\putenmrnotemarkerintext%
\fi%
\stepcounter{allendnotes}\label{notl\theallendnotes}%
\immediate\write\emendations{\checknoteheaders}%
\ifn@temarkinmargin%
\ifemendationspara\relax\else%
\immediate\write\emendations{\string\par}\fi%
\immediate\write\emendations{\string{\string\textbf\string{\the\singlepageabbrev\
\string\pageref\string{notl\theallendnotes\string}\string}\string}}%
\else%
\ifemendationspara\relax\else%
\immediate\write\emendations{\string\par}\fi%
\immediate\write\emendations{\string\textsuperscript\string{\theenmrnotescratchcount\string}%
}%
\fi
\literalemend{~#1}%
\fi}
%    \end{macrocode}
%    \end{macro}
%    \begin{macro}{\setstyleforchapternotebegin}
%    \begin{macrocode}
\newif\iftitleinnotes \titleinnotestrue%
\newcommand{\styleforchapternotebegin}{%
}
\newcommand{\styleforchapternoteend}{%
}
\newcommand{\setstyleforchapternotebegin}[1]{%
\renewcommand{\styleforchapternotebegin}{#1}}
\newcommand{\setstyleforchapternoteend}[1]{%
\renewcommand{\styleforchapternoteend}{#1}}%
\setstyleforchapternotebegin{\begin{center}}
\setstyleforchapternoteend{\end{center}}
\newcommand{\resettextnotes}{%
% \label{chapter\thechapter}%
\immediate\write\textnotes{\string\begingroup}%
\immediate\write\textnotes{\string\goodbreak}%
\immediate\write\textnotes{\string\Needspace\string{5\string\baselineskip\string}}%
\immediate\write\textnotes{\string\styleforchapternotebegin}%
\immediate\write\textnotes{\the\chapternoteslinename\string\ \thechapter\string~}%
\iftitleinnotes%
\immediate\write\textnotes{\string\titleref\string{chapter\thechapter\string}}%
\fi%
%\immediate\write\textnotes{\string}}
\immediate\write\textnotes{\string\styleforchapternoteend}%
% \immediate\write\textnotes{\string\end\string{center\string}}
\immediate\write\textnotes{\string\nopagebreak}%
\immediate\write\textnotes{\string\endgroup}%
}
\newcommand{\resetemendations}{%
% \label{chapter\thechapter}%
\immediate\write\emendations{\string\begingroup}%
\immediate\write\emendations{\string\goodbreak}%
\immediate\write\emendations{\string\Needspace\string{5\string\baselineskip\string}}%
\immediate\write\emendations{\string\styleforchapternotebegin}%
\immediate\write\emendations{\the\chapternoteslinename\string\ \thechapter\string~}%
\iftitleinnotes%
\immediate\write\emendations{\string\titleref\string{chapter\thechapter\string}}%
\fi%
\immediate\write\emendations{\string\styleforchapternoteend}%
\immediate\write\emendations{\string\nopagebreak}%
\immediate\write\emendations{\string\endgroup}%
}
\newcommand{\resetexplanatory}{%
% \label{chapter\thechapter}%
\immediate\write\explanations{\string\begingroup}%
\immediate\write\explanations{\string\goodbreak}%
\immediate\write\explanations{\string\Needspace\string{5\string\baselineskip\string}}%
\immediate\write\explanations{\string\styleforchapternotebegin}%
\immediate\write\explanations{\the\chapternoteslinename\string\ \thechapter\string~}%
\iftitleinnotes%
\immediate\write\explanations{\string\titleref\string{chapter\thechapter\string}}%
\fi%
\immediate\write\explanations{\string\styleforchapternoteend}%
\immediate\write\explanations{\string\nopagebreak}%
\immediate\write\explanations{\string\endgroup}%
}
\newcommand{\resetendnotes}{%
% \label{chapter\thechapter}% removed SEP-04-2012
\resettextnotes%
\resetemendations%
\resetexplanatory}          
%    \end{macrocode}
%    \end{macro}
%    \begin{macro}{\notesbychapter}
%    \begin{macrocode}
\newif\ifnotesbychapteron \notesbychapteronfalse
\@ifclassloaded{memoir}{\newcommand{\notesbychapter}{\notesbychapterontrue}
\addtoiargdef{\chapter}{}{ \iftitleinnotes%
   \label{chapter\thechapter}%
    \fi%
    \ifnotesbychapteron%
    \relax%
    \resetendnotes%
    \fi}
}{\newcommand{\notesbychapter}{\notesbychapterontrue}
\def\@chapter[#1]#2{\ifnum \c@secnumdepth >\m@ne
                       \if@mainmatter
                         \refstepcounter{chapter}%
                         \typeout{\@chapapp\space\thechapter.}%
                         \addcontentsline{toc}{chapter}%
                                   {\protect\numberline{\thechapter}#1}%
                       \else
                         \addcontentsline{toc}{chapter}{#1}%
                       \fi
                    \else
                      \addcontentsline{toc}{chapter}{#1}%
                    \fi
                    \chaptermark{#1}%
                    \addtocontents{lof}{\protect\addvspace{10\p@}}%
                    \addtocontents{lot}{\protect\addvspace{10\p@}}%
                    \if@twocolumn
                      \@topnewpage[\@makechapterhead{#2}]%
                    \else
                      \@makechapterhead{#2}%
                      \@afterheading
                    \fi
		    \iftitleinnotes%
		    \label{chapter\thechapter}%
		    \fi%
		    \ifnotesbychapteron%
		    \relax%
		    \resetendnotes%
		    \fi}
}
%    \end{macrocode}
%    \end{macro}
%    \begin{macro}{\definenewnotetype}
%    \begin{macrocode}
% first, some building block commands
% make some new ifs (Thanks to Igor Pechtchanski and Ulrich Schwarz)
\newcommand{\m@kenewnoteif}[1]{%
\expandafter\newif\csname if#1son\endcsname%
\global\csname #1sontrue\endcsname%
\expandafter\newif\csname ifno#1yet\endcsname%
\csname no#1yettrue\endcsname%
}
% make a new output stream
\newcommand{\n@woutputstream}[2]{%
\expandafter\newwrite\csname #1s\endcsname%
\immediate\expandafter\openout\csname #1s\endcsname=\expandafter\jobname .#2%
}
% set up a new literalwrite command
\newcommand{\n@wliteralwrite}[1]{%
\expandafter\newcommand\csname literal#1\endcsname[1]{%
\begingroup%
\def\next{##1}%
\newlinechar='40
\immediate\write\expandafter\csname #1s\endcsname{\expandafter\strip\meaning\next}%
\endgroup}
}
% heading material for new notes, label, font, par mode default
\newcommand{\n@wnoteheadingmaterial}[3]{%
\csname literal#1\endcsname{%
\par\clearpage%
{\pagestyle{empty}\cleardoublepage}%
\thispagestyle{empty}%
}
\immediate\write\csname #1s\endcsname{%
\string\notesheadername=\string{#2\string}%
\string\pagestyle\string{endnotesstyle\string}%
}
\immediate\write\csname #1s\endcsname{%
\string\mark\string{3\string}%
\string\backmattersink%
\string\begin\string{center\string}%
\string{\string\normalfont \string%
\backmatterheadingfont\ #3\string}\string\end\string{center\string}%
}
\immediate\write\csname #1s\endcsname{\string\label\string{#3\string}}%
\immediate\write\csname #1s\endcsname{\string\normalfont\string\backmattertextfont}%
\immediate\write\csname #1s\endcsname{\string\paramodefalse}%
}
% new entry for table of contents
\newcommand{\n@wentryfortoc}[2]{%
\immediate\write\csname #1s\endcsname{\string\ifnotesincontentson}%
\immediate\write\csname #1s\endcsname{\string\addcontentsline\string{toc\string}%
\string{chapter\string}\string{#2\string}}%
\immediate\write\csname #1s\endcsname{\string\fi}%
}
% new marginal reference kind
\newcommand{\n@wmargrefkind}[1]{%
\expandafter\newcommand\csname margref#1\endcsname[1]{%
\addtocounter{margrefnumber}{1}%
\immediate\write\csname #1s\endcsname{\makemargreflabel}%
\setmargref%
}
}
% new note counter
\newcommand{\n@wnotecounter}[1]{%
\expandafter\newcounter{enmr#1count}%
}
\newcommand{\n@wparaboolean}[1]{%
\expandafter\newif\csname if#1spara\endcsname}%
\newcommand{\n@wputmargref}[1]{%
\expandafter\csname margref#1\endcsname%
}
\newcommand{\n@wputnotenum}[1]{%
\expandafter\stepcounter{enmr#1count}%
\setcounter{enmrnotescratchcount}{\expandafter\value{enmr#1count}}%
\makeenmrendnotemarker%
\putenmrnotemarkerintext%
}
\newif\ifparamode \paramodefalse%
\newcommand{\n@wsetparamode}[1]{%
\expandafter\newcommand\csname #1sparamode\endcsname{%
%\csname #1sparatrue\endcsname
\immediate\write\expandafter\csname #1s\endcsname{\string\paramodetrue}%
}
}
\newcommand{\enmrconditionalpar}{%
\ifparamode%
% \if#1spara 
\relax%
\else% 
\par%
\fi%
}
\newcommand{\n@wnotecommand}[2]{%
\expandafter\newcommand\csname #1\endcsname[1]{%
\margrefmarker={#2:}%
\ifn@temarkinmargin%
\n@wputmargref{#1}%
\fi%
\ifn@temarkintext%
\n@wputnotenum{#1}%
\fi%
\stepcounter{allendnotes}\label{notl\theallendnotes}%
\immediate\write\expandafter\csname #1s\endcsname{\checknoteheaders}%
\ifn@temarkinmargin%
\immediate\write\expandafter\csname #1s\endcsname{\string\enmrconditionalpar}%
%\immediate\write\expandafter\csname #1s\endcsname{\string\par}
\immediate\write\expandafter\csname #1s\endcsname{\string{\string\textbf\string{\the\singlepageabbrev\
\string\pageref\string{notl\theallendnotes\string}\string}\string}}%
\else%
% \immediate\write\csname #1s\endcsname{\string\par}
\immediate\write\expandafter\csname #1s\endcsname{\string\enmrconditionalpar}%
\immediate\write\csname #1s\endcsname{%
\string\textsuperscript\string{\theenmrnotescratchcount\string}%
}%
\fi
\expandafter\csname literal#1\endcsname{~##1}%
}}
%%%%%%%%%%%%%%
\newcommand{\definenewnotetype}[6]{%
% 1. make new ifs
\m@kenewnoteif{#1}%
% 2 # new output stream and external file
\n@woutputstream{#1}{#2}%
% 4. set up a literalwrite command
\n@wliteralwrite{#1}%
% 5. First a blank page than a page in the empty pagestyle
% set the page style and running header
\n@wnoteheadingmaterial{#1}{#3}{#4}%
% 6. set up entry for table of contents
\n@wentryfortoc{#1}{#5}%
% % 7. set up a command to write the note
\n@wmargrefkind{#1}%
% % then a counter for the note kind
\n@wnotecounter{#1}
% % then a boolean for setting the notes in paragraph format
\n@wparaboolean{#1}
\n@wsetparamode{#1}
% % then the note command
\n@wnotecommand{#1}{#6}
% 8. make a reset command for setting by chapter
\expandafter\newcommand\csname reset#1s\endcsname[1]{%
\immediate\write\csname #1s\endcsname{\string\begingroup}%
\immediate\write\csname #1s\endcsname{\string\goodbreak}%
\immediate\write\csname #1s\endcsname{\string\Needspace\string{5\string\baselineskip\string}}%
\immediate\write\csname #1s\endcsname{\string\styleforchapternotebegin}%
\immediate\write\csname #1s\endcsname{\the\chapternoteslinename\string\ \thechapter\string~}%
\iftitleinnotes%
\immediate\write\csname #1s\endcsname{\string\titleref\string{chapter\thechapter\string}}%
\fi%
\immediate\write\csname #1s\endcsname{\string\styleforchapternoteend}%
\immediate\write\csname #1s\endcsname{\string\nopagebreak}%
\immediate\write\csname #1s\endcsname{\string\endgroup}%
}
% 9. add this to resetchapter and setbychapter
%\appendtomacro{\notesbychapter}{\expandafter\csname reset#1s\endcsname}
\appendtomacro{\resetendnotes}{\expandafter\csname reset#1s\endcsname}%
% 10. command for closing the file and reading in the endnotes section
\expandafter\newcommand\csname put#1s\endcsname{%
\immediate\expandafter\closeout\csname #1s\endcsname%
\expandafter\input \jobname.#2%
}%
}
%    \end{macrocode}
%    \end{macro}
% \Finale
\endinput