% \iffalse meta-comment
%
% Copyright (C) 2005 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{endheads}
%<package>   [2007/01/18 v1.2 endheads file] 
%
%<*driver>
\documentclass{ltxdoc}
\usepackage{makeidx,multicol,keyval,ifthen,needspace,titleref}
\EnableCrossrefs         
\CodelineIndex
\RecordChanges
\begin{document}
  \DocInput{endheads.dtx}
\end{document}
%</driver>
% \fi
%
% \CheckSum{327}
%
% \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}{2005/08/21}{Initial version}
% \changes{v1.1}{2005/09/25}{uses needspace prevent orphan chapter 
% beginnings in notes}
% \changes{v1.15}{2005/09/25}{uses titleref to capture chapter titles for 
% notes}
% \changes{v1.151}{2005/09/25}{Corrections to user's guide}
% \changes{v1.152}{2006/11/10}{Fixed strange white space error}
% \changes{v1.2}{2006/11/10}{Added commands for multilingual use}
% \GetFileInfo{endheads.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{18 January 2007}
% \def\docdate{18 January 2007}
% \title{Running Headers for Endnotes\thanks{This document
%   corresponds to \textsf{endheads}~\fileversion, dated \filedate.}}
% \author{John Burt \\ \texttt{burt@brandeis.edu}}
% \date{January 18, 2007}
% \maketitle
% \begin{abstract}
%  \textsf{endheads} provides running headers of the form ``Notes to 
%  pp.~xx--yy'' for endnotes. \textsf{endheads} is designed to work 
%  with \textsf{endnotes} and \textsf{fancyhdr}. 
% \end{abstract}
% \tableofcontents
% \hfuzz=50pt
% \section{Introduction} It is a convenience, if you are 
% flipping though the endnotes of a book, to be able to find the 
% endnote you are looking for by looking at the running header. 
% \textsf{endheads} uses the |\mark| mechanism to update the running 
% header continuously, so that it always indicates to what pages in 
% the main text the notes on a particular page refer.  
% \textsf{endheads} also enables one to reset endnote numbering at 
% the beginning of each chapter.
%
% \textsf{endheads} requires the following packages to work correctly:
% \textsf{endnotes} (obviously), \textsf{fancyhdr} (also obviously),
% \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).
%
% \section{Setup} \DescribeMacro{\setupendnoteheaders} This is the
% only macro you need to call to use this package.  If you use
% |\setupendnoteheaders| you should remember to start your endnotes on
% a new page.  |\setupendnoteheaders| sets the first page of the 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 header will appear in the center of
% each header.  Then it modifies the |\endnote| command, having it
% increment a counter that keeps track of all the endnotes (even if
% you are resetting the number by chapter), and defines a label for
% that note.  Finally, it writes on the external file for the endnotes
% a command to set the |\mark| for that page of the endnotes using a
% |\pageref| to the label it has just defined.  \textsf{endheads}
% creates a label and a pageref for every note.
%
% \DescribeMacro{\notesbychapter} |\notesbychapter| resets the note 
% counter every time you issue a |\chapter| command, and it puts a 
% centered line reading ``Chapter \textless\emph{chapter 
% number}\textgreater ~ \textless\emph{chapter title}\textgreater'' in the 
% notes at that point. If you want only the chapter number, not its 
% title, issue |\titleinnotesfalse| in your preamble. Please note 
% that \textsf{endheads} modifies |\@chapter|, adding a few lines on 
% to the end of the command. If some other package does the same, you 
% will need to reconcile them.
%
% \DescribeMacro{\resetendnotes} Conceivably you might wish to do what
% |\notesbychapter| does for each chapter individually.  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 \LaTeX\ 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.
% 
% \section{Using \textsf{endheads} in a Multilingual World}
% 
% \begin{sloppypar}
% \DescribeMacro{\changecontentsname}
% By default, \textsf{endheads} uses English language running headers.  
% As of version 1.2 these
% are easily changed. \end{sloppypar} 
% 
% \begin{sloppypar}
% \DescribeMacro{\changenotesname} To change the name for the endnote
% section for notes (the default is Notes), issue
% |\changenotesname{your version}|.  To change the running header (by
% default ``Notes to'') issue |\changenotesheader{your version}|.  To
% change the name for the  notes in the table of contents ( by
% default ``Notes'') issue |\changenotescontentsname{your version}|.
% \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}
% 
% \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}
%    \end{macrocode}
%    \begin{macro}{\mymarks}
% A command to set the marks. This will be called by the page style.
%    \begin{macrocode}
\newtoks{\singlepageabbrev}
\singlepageabbrev={p.}
\newcommand{\changesinglepageabbrev}[1]{\singlepageabbrev={#1}}
\newtoks{\multiplepageabbrev}
\newcommand{\changemultiplepageabbrev}[1]{\multiplepageabbrev={#1}}
\multiplepageabbrev{pp.}
\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.
%    \begin{macrocode}

\newtoks{\endnotesname}
\endnotesname={Notes}
\newcommand{\changenotesname}[1]{\def\notesname{#1}}
\newtoks{\notesheadername}
\notesheadername={Notes to}
\newcommand{\changenotesheader}[1]{\notesheadername={#1}}
\newtoks{\notescontentsname}
\notescontentsname={Notes}
\newcommand{\changenotescontentsname}[1]{\textnotescontentsname={#1}}	
\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 file for the endnotes, |\jobname.ent|. 
% 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, 
% |\jobname.ent|, all these tokens become a command to set the |\mark|.
%    \begin{macrocode}
\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}{\setupendnoteheaders}
% |\setupendnoteheaders| turns on processing of running headers, and 
% adds two lines to the definition of |\endnote|
%    \begin{macrocode}
\newif\ifendnoteheaderson \endnoteheadersonfalse
\newcommand{\setupendnoteheaders}{%
\endnoteheadersontrue
\if@enotesopen \else \@openenotes \fi
\immediate\write\@enotes{%
\string\thispagestyle\string{empty\string}
\string\pagestyle\string{endnotesstyle\string}}
\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}{\resetendnotes}
% Tells the |\chapter| macro to reset the note counter and to 
% put a line with the chapter number in the endnotes.
%    \begin{macrocode}
\newif\iftitleinnotes \titleinnotestrue
\newcommand{\resetendnotes}{%
\setcounter{endnote}{0}%
\if@enotesopen \else \@openenotes \fi
\immediate\write\@enotes{\string\goodbreak}
\immediate\write\@enotes{\string\Needspace\string{5\string\baselineskip\string}}
\immediate\write\@enotes{\string\begin\string{center\string}}
\immediate\write\@enotes{Chapter \thechapter\string~}
\iftitleinnotes
\immediate\write\@enotes{\string\titleref\string{chapter\thechapter\string}}
\fi
\immediate\write\@enotes{\string\end\string{center\string}}
\immediate\write\@enotes{\string\nopagebreak}
}          
%    \end{macrocode}
%    \end{macro}
%    \begin{macro}{\notesbychapter}
%    \begin{macrocode}
% \newcommand{\notesbychapter}{%
% \appendtomacro{\chapter}{%
% \relax
% \resetendnotes}%
% }
\newif\ifnotesbychapteron \notesbychapteronfalse
\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}
% \Finale
\endinput			   