%\iffalse meta-comment
%
% Copyright (C) 2007-2008 by
%    Joseph Wright <joseph.wright@morningstar2.co.uk>
%
% This work may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either
% version 1.3c 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.3c or later is part of all distributions of
% LaTeX version 2005/12/01 or later.
%
% This work has the LPPL maintenance status `maintained'.
%
% The current maintainer of this work is Joseph Wright.
%
% This work consists of the source file notes2bib.dtx
%                 and the derived files notes2bb.ins,
%                                       notes2bib.sty and
%                                       notes2bib.pdf
%
% Unpacking:
%    (a) If notes2bib.ins is present:
%           tex notes2bib.ins
%    (b) Without notes2bib.ins:
%           tex notes2bib.dtx
%    (c) If you use LaTeX to generate files:
%           latex \let\install=y\input{notes2bib.dtx}
%
% Documentation:
%    (a) Without write18 enabled:
%          pdflatex notes2bib.dtx
%          bibtex8 --wolfgang notes2bib
%          makeindex -s gind.ist notes2bib.idx
%          makeindex -s gglo.ist -o notes2bib.gls  notes2bib.glo
%          pdflatex notes2bib.dtx
%          makeindex -s gind.ist notes2bib.idx
%          makeindex -s gglo.ist -o notes2bib.gls  notes2bib.glo
%          pdflatex notes2bib.dtx
%    (b) With write18 enabled:
%          pdflatex notes2bib.dtx
%          bibtex8 --wolfgang notes2bib
%          pdflatex notes2bib.dtx
%          pdflatex notes2bib.dtx
%
% Installation:
%     Copy notes2bib.sty to a location searched by TeX, and
%     if required by your TeX installation, run the appropriate
%     command to build a hash of files (texhash, mpm --update-db,
%     etc.)
%
% Note:
%     The jawltxdoc.sty file is not needed for installation,
%     only for building the documentation.  It may be deleted.
%
%<*ignore>
% This is all taken verbatim from Heiko Oberdiek's packages
\begingroup
  \def\x{LaTeX2e}%
\expandafter\endgroup
\ifcase 0\ifx\install y1\fi\expandafter
         \ifx\csname processbatchFile\endcsname\relax\else1\fi
         \ifx\fmtname\x\else 1\fi\relax
\else\csname fi\endcsname
%</ignore>
%<*install>
\input docstrip.tex
\keepsilent
\askforoverwritefalse
\preamble
 ----------------------------------------------------------------
 note2bib --- Integrating notes into the bibliography
 Maintained by Joseph Wright
 E-mail: joseph.wright@morningstar2.co.uk
 Released under the LaTeX Project Public License v1.3 or later
 See http://www.latex-project.org/lppl.txt
 ----------------------------------------------------------------

\endpreamble
\Msg{Generating notes2bib files:}
\usedir{tex/latex/contib/notes2bib}
\generate{\file{\jobname.ins}{\from{\jobname.dtx}{install}}
          \file{\jobname.sty}{\from{\jobname.dtx}{package}}
          \file{jawltxdoc.sty}{\from{\jobname.dtx}{jawltxdoc}}
}
\endbatchfile
%</install>
%<*ignore>
\fi
% Will Robertson's trick
\immediate\write18{makeindex -s gind.ist -o \jobname.ind  \jobname.idx}
\immediate\write18{makeindex -s gglo.ist -o \jobname.gls  \jobname.glo}
%</ignore>
%<*driver>
\PassOptionsToClass{a4paper}{article}
\documentclass{ltxdoc}
\EnableCrossrefs
\CodelineIndex
\RecordChanges
%\OnlyDescription
% The various formatting commands used in this file are collected
% together in |jawltxdoc|.
\usepackage{jawltxdoc}
\begin{document}
  \DocInput{\jobname.dtx}
\end{document}
%</driver>
%\fi
%
%\CheckSum{843}
%
%\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         \~}
%
%\GetFileInfo{\jobname.sty}
%
%\changes{v1.0}{2007/08/30}{Initial public release}
%\changes{v1.1}{2007/09/29}{License changed from GPL to LPPL}
%\changes{v1.1}{2007/09/29}{\cs{Percent} macro removed}
%\changes{v1.1}{2007/09/29}{Documentation improvements}
%\changes{v1.1}{2007/09/29}{Several code sections re-factored}
%\changes{v1.1}{2007/09/29}{Improvements to documentation and
%  \texttt{dtx} file}
%\changes{v1.2}{2007/10/26}{Altered implementation of \texttt{head}
%   and \texttt{tail} options to allow moving of superscript
%   citations}
%\changes{v1.3}{2008/01/08}{Added \pkg{xkeyval} option interface}
%\changes{v1.3}{2008/01/08}{All options now work anywhere in input}
%\changes{v1.3}{2008/01/08}{Fixed serious errors with \opt{head}
%  and \opt{tail} implementation}
%
%\DoNotIndex{\@auxout,\@empty,\@fileswfalse,\@for,\@ifnextchar}
%\DoNotIndex{\@ifpackagelater,\@ifpackageloaded,\@ifundefined}
%\DoNotIndex{\@nameuse,\AtBeginDocument,\AtEndDocument}
%\DoNotIndex{\AtEndPreamble,\AtNextCite,\begingroup,\closeout}
%\DoNotIndex{\csname,\DeclareRobustCommand,\def,\define@boolkey}
%\DoNotIndex{\define@choicekey,\define@cmdkeys,\do,\edef,\else}
%\DoNotIndex{\endcsname,\endgroup,\endinput,\expandafter,\fi}
%\DoNotIndex{\g@addto@macro,\gappto,\gdef,\if@filesw,\iffalse,\ifnum}
%\DoNotIndex{\ifx,\immediate,\jobname,\let,\long,\MessageBreak}
%\DoNotIndex{\NeedsTeXFormat,\newcommand,\newcounter,\newif}
%\DoNotIndex{\nocite,\noexpand,\openout,\PackageError,\PackageInfo}
%\DoNotIndex{\newwrite,\PackageWarning,\patchcmd,\printbibliography}
%\DoNotIndex{\ProcessOptionsX,\ProvidesPackage,\relax,\renewcommand}
%\DoNotIndex{\RequirePackage,\setkeys,\space,\stepcounter,\string}
%\DoNotIndex{\the,\typeout,\unexpanded,\value,\write,\xdef,\z@}
%
%\title{\currpkg\ --- Integrating notes into the
%  bibliography^^A
%  \thanks{This file describes version \fileversion, last revised
%          \filedate.}}
%\author{Joseph Wright^^A
%  \thanks{E-mail: joseph.wright@morningstar2.co.uk}}
%\date{Released \filedate}
%
%\maketitle
%
%\begin{abstract}
% The \currpkg package defines a new type of note, \cs{bibnote},
% which will always be added to the bibliography.  The package allows
% footnotes and endnotes to be moved into the bibliography in the
% same way.  The package can be used with \pkg{natbib} and
% \pkg{biblatex} as well as plain \LaTeX\ citations. Both sorted and
% unsorted bibliography styles are supported.
%\end{abstract}
%
%\begin{multicols}{2}
%\tableofcontents
%\end{multicols}
%
%\section{Background}
% In most subject areas, bibliographic citations and notes are
% separate entities. However, in some parts of the physical sciences
% (chemistry and physics) it is usual for references to the
% literature and notes to be given together in a ``References and
% Notes'' section.  By default, this requires that \BibTeX\ users
% create a notes database for each document that they write.
%
%\newcommand*{\APS}{\textsc{aps}\xspace}
%\newcommand*{\REVTeX}{REV\TeX\xspace}
% The \pkg{endnotes} package allows the user to create endnotes
% rather than footnotes.  However, this does not place the notes in
% the bibliography.  The \APS have developed the \REVTeX
% document class, which allows footnotes and endnotes to be added to
% the bibliography.  Notes can only be placed at the end of the
% bibliography using this system.  Furthermore, the code to achieve
% this effect is not available as a package separate from \REVTeX.
%
% The aim of the \currpkg package is to make integration of notes
% into the bibliography easy.  Notes can be written as normal in the
% \LaTeX\ source, and are automatically moved to the bibliography.
% The package is compatible with sorted and unsorted bibliography
% styles. The package has been designed for use with numerical
% citations, although it will work with other systems.
%
%\section{Basic use}
%\DescribeMacro{\bibnote}
% In the most basic form, the package can be used simply by loading
% it in the preamble as normal.  This adds a new type of note to the
% existing \cs{footnote} type: \cs{bibnote}\marg{text}. This can be
% used in exactly the same way as a footnote, taking one mandatory
% argument \meta{text}.  The \meta{text} will be made available as to
% the bibliography as a note (henceforth referred to as a bibnote).
%\begin{LaTeXexample}
%  A very simple example of a bibliography note
%  \bibnote{Note for the first example}.
%\end{LaTeXexample}
% By default, each bibnote is given an automatically-generated label.
%  However, \cs{bibnote} accepts an optional argument \meta{label},
% which can be used to over-ride this. This is particularly useful
% when a note will be referenced several times (The use of the
% \cs{citenote} command is covered in
% Section~\ref{subsec:cross-ref}).
%\begin{LaTeXexample}
%  An example of a named note \bibnote[labelled-note]{Note for the
%  second example}. The text can then continue and reference the note
%  again later \citenote{labelled-note}.
%\end{LaTeXexample}
%
%\DescribeMacro{\bibnotemark}
%\DescribeMacro{\bibnotetext}
% In common with \cs{footnote}, the basic \cs{bibnote} macro has
% companion macros \cs{bibnotemark} and \cs{bibnotetext}. The text
% provided for each not is not ``fragile,'' and so it should not be
% necessary to use \cs{bibnotemark} directly.  It is needed when
% replacing footnotes by bibnotes.  Notice that there \emph{are}
% places where bibnotes will be problematic, for example in section
% headings which also appear in the Table of Contents. In these
% contexts, use \cs{citenote} to reference the note, or use an
% optional argument to the \cs{section}, \etc
%\begin{LaTeXexample}
%  It is hard to write a good example for this \bibnotemark! The text
%  continues here\bibnotetext{Note for the third example}.
%\end{LaTeXexample}
%
%\subsection{Package control}
%\DescribeMacro{\niibsetup}
% The \currpkg package can be controlled using package options, and
% also dynamically using the \cs{niibsetup} macro.  In both cases the
% same list of \pkg{keyval} options are recognised, in a similar
% manner to the \pkg{graphicx} or \pkg{hyperref} packages.  Several
% of the package options are aimed at controlling the package
% internally, but by providing a single macro to control this, use is
% made easier.\footnote{Users upgrading from earlier versions of
% \currpkg will note that the large number of control macros have all
% been removed from v1.3.}
%
% Almost all of the package options take literal text; those which do
% not are true/false switches.
%\begin{itemize}
%  \item \opt{cite}: The csname of the macro used to cite bibnotes;
%    by default ``cite''.
%  \item \opt{endnotes}: Whether to convert endnotes into bibnotes;
%    takes a Boolean value.
%  \item \opt{field}: The \BibTeX\ database field name for notes.
%  \item \opt{footnotes}: Whether to convert footnotes into bibnotes;
%    takes a Boolean value, and does not affect the \cs{thanks}
%    macro.
%  \item \opt{keyhead}, \opt{keynone}, \opt{keytail}: Sorted \BibTeX\
%    styles can use the \texttt{key} field to sort citations; by
%    setting a prefix to the bibnote name, extra control over sorting
%    can be obtained.
%  \item \opt{log}: The amount of detail to add to the log; expects a
%    value from the list \opt{debug} (very detailed information),
%    \opt{verbose} (the same as \opt{debug}), \opt{normal},
%    \opt{errors} (errors only), \opt{none}.
%  \item \opt{name}: The name given to bibnote citations; by default,
%    this is followed by an automatically-generated number.
%  \item \opt{prefix}: The file-name prefix used for the \BibTeX\
%    database holding the notes.
%  \item \opt{presorthead}, \opt{presortnone}, \opt{presorttail}: For
%    \pkg{biblatex} users, the presort field can be used to control
%    sorting of the bibliography; these keys control the value used
%    depending on the setting of the \opt{sort} key.
%  \item \opt{record}: The name of the \BibTeX\ record type used to
%    store notes.
%  \item \opt{sort}: Controls the placement of notes relative to real
%    citations in the bibliography; expected a value \opt{none} (no
%    control of sorting, intended for unsorted bibliographies and
%    interspersed citations and notes), \opt{head} (notes appear
%    before real citations) and \opt{tail} (notes appear after real
%    citations).
%\end{itemize}
% The default options are:
%\begin{LaTeXexample}[\typesetcodeonly]
%  \niibsetup{%
%    cite=cite,
%    endnotes=false,
%    field=note,
%    footnotes=false,
%    keyhead=aaa,
%    keynone={},
%    keytail=zzz,
%    log=normal,
%    name=Bibnote,
%    prefix=niib-,
%    presorthead=ml,
%    presortnone=mm,
%    presorttail=mn,
%    record=Misc,
%    sort=none}
%\end{LaTeXexample}
%
% The \opt{sort} option requires some comment.  By default, \currpkg
% places notes where cited into the \ext{aux} file, which means that
% the order of citations and notes depends on the \ext{bst} file in
% use.  With an unsorted style, citations and notes will be mixed in
% the order they appear in the \LaTeX\ source.  The \opt{sort=head}
% option will cause \currpkg to place notes before real citations.
% This should work with sorted and unsorted \ext{bst} files, but
% requires two \LaTeX\ runs \emph{before} a \BibTeX\ run in order to
% work.  The package warns if extra runs are needed.  The
% \opt{sort=tail} option places notes after citations; here, only one
% \LaTeX\ run is needed.
%
% The options \opt{head} and \opt{tail} are provided as shortcuts for
% \opt{sort=head} and \opt{sort=tail}, respectively. The \opt{debug}
% option is a shortcut for \opt{log=debug}.  As the \opt{endnotes}
% and \opt{footnotes} options take Boolean values, giving the option
% name alone is the same as giving \opt{\meta{option}=true}.
%
%\subsection{Output of notes}
% Bibnotes are only printed when a bibliography is created.  This
% means that at the very least a \cs{bibliographystyle} command must
% appear in the source.\footnote{For \pkg{biblatex} users, the
% package must be loaded!}  Under most circumstances, the user will
% be citing literature, and so will also include a \cs{bibliography}
% command in their source. Bibliography notes are automatically added
% to the citations to be printed.
%
%\DescribeMacro{\printbibnotes}
% If bibnotes are being used without any other citations, then the
% user cannot place \cs{bibliography} in the source.\footnote{\LaTeX\
% will complain if the user puts \cs{bibliography\{\}}.}  The package
% therefore provides the macro \cs{printbibnotes}, which will output
% only the notes.  If the \pkg{endnotes} package has been loaded, the
% \cs{theendnotes} macro is redefined to achieve the same effect.
%
%\subsection{Cross-referencing notes\label{subsec:cross-ref}}
%\DescribeMacro{\citenote}
% As explained above, each note is automatically assigned a label, or
% the user can provide one as an optional argument to the note.  In
% either case, notes may then be cross-referenced.  Notes are
% available to be cited directly using the \cs{cite} command.
% However, this can cause problems when using the \opt{sort=tail}
% option. The \cs{citenote} command is therefore provided.  This is
% aware of the options, and will act correctly in all circumstances.
%\begin{LaTeXexample}
%  Cross-references to the note labelled earlier
%  using \cite{labelled-note} and using
%  \citenote{labelled-note}.
%\end{LaTeXexample}
%
%\subsection{Interaction with other packages}
% \currpkg is designed to work well with as many other packages as
% possible. It has been tested with \pkg{cite}, \pkg{natbib},
% \pkg{hyperref} and \pkg{mciteplus} with no problems. The \currpkg
% package is compatible with the current release of \pkg{biblatex}
% (v0.7); older versions of \pkg{biblatex} may or may not
% work.\footnote{As \pkg{biblatex} is experimental and is not
% currently added to \TeX\ distributions, users have little excuse
% for not using the latest release.}
%
%\section{Special effects}
%\DescribeMacro{\flushnotestack}
% When using the \opt{sort=tail} option, citations are added to a
% stack as they are made.  This stack is then flushed to the
% \ext{aux} file at the end of the document.  If references are given
% by chapter (or other unit), this may not give the desired effect.
% The \cs{flushnotestack} macro will cause all saved citations to be
% written at that point, and will reset the stack for continued use.
% This can therefore be used to control when citation
% occurs.\footnote{This macro was called \cs{flushcitestack} prior to
% v1.3.}
%
%\DescribeMacro{\thebibnote}
% If a sorted bibliography style is in use, and more than nine notes
% are created, the sort order will be incorrect.  This is because by
% default \currpkg does not pad the automatically-created labels with
% zeros.  To get the correct sort order, \cs{thebibnote} should be
% redefined.
%\begin{LaTeXexample}[\typesetcodeonly]
%  \makeatletter
%  \renewcommand*{\thebibnote}{%
%    \niib@name%
%    \ifnum\value{bibnote} < 9 0\fi%
%    \the\value{bibnote}}
%  \makeatother
%\end{LaTeXexample}
%
%\section{Package requirements}
% \currpkg has certain requirements to run successfully; if these are
% not met the package will abort loading.
%\begin{itemize}
%  \item \eTeX:  The package uses the \eTeX\ \cs{unexpanded}
%    primitive, and so the extensions must be available.
%  \item \pkg{xkeyval}, v2.5 or later: Option handling uses
%    \pkg{xkeyval}, and the features used here are only available
%    from v2.5 of that package.
%  \item \pkg{etoolbox}, v1.3 or later:  Patching the \cs{thanks} macro
%    to allow the \opt{footnotes} option also uses \pkg{etoolbox}.
%    Various hooks are set up by \pkg{etoolbox}, which are used here
%    to make the code clearer; these are only available from v1.3.
%\end{itemize}
%
%\section{Known issues}
% From v1.1, the method for writing notes to the \BibTeX\ database has
% been modified.  This means that bibnotes cannot contain verbatim
% text.\footnote{Actually, they can, but the spacing will go wrong.
% \LaTeX\ will only complain if a note ends with verbatim text.
% However, verbatim text is not supported in bibnotes: don't do it!}
% This is the same as for normal footnotes, and so the usual
% work-arounds are applicable.
%\begin{LaTeXexample}
%  The next note contains some awkward text
%  \bibnote{Some \texttt{\textbackslash verb}-like output}.
%\end{LaTeXexample}
%
% The package relies on \BibTeX\ being able to open and process the
% temporary database containing the note text.  The name of this file
% contains \cs{jobname}, the name of the main \LaTeX\ file being
% processed.  This must consist only of characters that \BibTeX\ can
% handle.  In particular, spaces in the file name will lead to
% problems.
%
%\bibliographystyle{unsrt}
%\renewcommand*{\refname}{Notes}
%\StopEventually{\printbibnotes}
%
%\section{The mechanism}
% The mechanism for positioning notes in the bibliography is somewhat
% involved.  Rather than expect interested users to read all of the
% code that follows, a condensed overview is given here.  The
% thinking behind the system used is explained first, by considering
% the \pkg{endnotes} package and \REVTeX class.  Both of these
% provided inspiration for this package.
%
%\subsection{The \texttt{endnotes} approach}
% The \pkg{endnotes} package\footnote{%
% \url{http://tug.ctan.org/macros/latex/contrib/misc/endnotes.sty}}
% allows the user to generate endnotes in the same way as footnotes.
% In \pkg{endnotes}, the text of the note is written to a \ext{ent}
% file. This is achieved in an unexpanded form using the \cs{meaning}
% \TeX\ primitive.  To produce the list of endnotes, this file is
% read back into \LaTeX, with the extra information \cs{meaning} also
% writes being stripped off in the process.
%
% This method is relativity simple in concept, but obviously does
% not integrate with \BibTeX.  The use of \cs{meaning} for unexpanded
% output also means that information requires further processing before
% it can be included in the bibliography.
%
%\subsection{The \REVTeX approach}
% \REVTeX takes a similar approach to creating endnotes, but also
% allows footnotes to be converted into endnotes.  This results in a
% file containing all of the non-literature citations in a document
% in a single external file (in this case a \ext{end} file).  \REVTeX
% also uses a different method to achieve unexpanded output, meaning
% that several macros are not ``active'' in notes.
%
% The second part of the \REVTeX approach is to (optionally) read the
% notes back into the document.  This is achieved  by modifying the
% \cs{bibliography} environment to output each note in the
% bibliography. This takes place \latin{en masse}, after the normal
% citations.
%
% \REVTeX makes a number of modifications to \LaTeX, and is dependent
% on using \pkg{natbib}.  The method used is also not compatible with
% interspersing normal citations and notes.
%
%\subsection{The \texttt{notes2bib} approach}
%
% In \currpkg, notes are again written to an external file. However,
% in contrast to the methods those outlined above, \currpkg writes
% its output in the well-known \BibTeX\ database format.  All of the
% note text is written almost completely unexpanded to the file, the
% only requirement being that the braces match within the
% argument.\footnote{Writing to the file uses the \eTeX\
% \cs{unexpanded} primitive.}
%
% Each note results in a citation being placed by \currpkg in the
% \ext{aux} file.  The  \cs{bibliography} command is also modified so
% that the new database will be used by \BibTeX. After the \BibTeX\
% run, the note text will appear in the \ext{bbl} file, in the same
% way as any other citation.  Using an unsorted \BibTeX\ style, this
% results in notes interspaced with the normal citations.  For sorted
% styles, \currpkg allows various methods for controlling the
% placement of notes, based on writing appropriate fields in the
% \BibTeX\ database.
%
%\DescribeMacro{niibheadcite}
% The \opt{sort=head} option works by adding an additional macro to
% the \ext{aux} file: \cs{niibheadcite}.  On the next \LaTeX\ run,
% this causes the relevant notes to be cited right at the beginning
% of the document, before any real citations.\footnote{Thanks to
% Michael Shell for the idea for this method.}  For \opt{sort=tail},
% the value of \cs{if@filesw} is temporarily altered to prevent
% writing of a citation to the \ext{aux} file.  The citation is added
% to a stack, and is written at the end of the document.
%
%\iffalse
%<*package>
%\fi
%\section{The package code}
%
%\subsection{Package setup code}
% The package starts with the usual identification code.
%\changes{v1.1}{2007/09/29}{Removed use of \pkg{xspace}}
%    \begin{macrocode}
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{notes2bib}
  [2008/01/16 v1.3b Integrating notes into the bibliography]
%    \end{macrocode}
% The package requires \eTeX, so before going any further, this is
% tested.  This code is taken more-or-less verbatim from
% \pkg{biblatex}.
%\changes{v1.1}{2007/09/29}{Require \eTeX\ extensions}
%    \begin{macrocode}
\begingroup
  \@ifundefined{eTeXversion}
    {\PackageError{notes2bib}
       {Not running under e-TeX}
       {This package requires e-TeX. Try compiling the document
        with\MessageBreak `elatex' instead of `latex'. When using
        pdfTeX, try `pdfelatex'\MessageBreak instead of `pdflatex'}
     \endgroup\endinput}
    {\endgroup}
%    \end{macrocode}
%\changes{v1.3a}{2008/01/09}{Require at least v2.5 of \pkg{xkeyval}}
%\changes{v1.3a}{2008/01/09}{Require at least v1.3 of \pkg{etoolbox}}
% The necessary support packages are loaded.  The method used in
% \pkg{biblatex} is used to check the date of the packages: \currpkg
% bails out if the support packages are too old.
%    \begin{macrocode}
\RequirePackage{xkeyval,etoolbox}
\@ifpackagelater{xkeyval}{2005/05/07}
  {}
  {\PackageError{notes2bib}
     {xkeyval >= 2.5 required}
     {notes2bib requires the `xkeyval' package, version 2.5 or
       later.\MessageBreak The version loaded is:
       `\@nameuse{ver@etoolbox.sty}'.\MessageBreak
        This is a fatal error; the package will abort.}%
   \endinput}
\@ifpackagelater{etoolbox}{2007/10/08}
  {}
  {\PackageError{notes2bib}
     {etoolbox >= 1.3 required}
     {notes2bib requires the `etoolbox' package, version 1.3 or
       later.\MessageBreak The version loaded is:
       `\@nameuse{ver@etoolbox.sty}'.\MessageBreak
        This is a fatal error; the package will abort.}%
   \endinput}
%    \end{macrocode}
%\begin{macro}{\niib@tempa}
%\changes{v1.3}{2008/01/08}{New macro}
%\begin{macro}{\niib@tempb}
%\changes{v1.3}{2008/01/08}{New macro}
% Some private temporary macros are declared.
%    \begin{macrocode}
\newcommand*{\niib@tempa}{}
\newcommand*{\niib@tempb}{}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%
%\subsection{Logging}
%\begin{macro}{\ifniib@debug}
%\begin{macro}{\ifniib@logmin}
%\begin{macro}{\ifniib@lognone}
% To control logging, some new switches are declared.
%    \begin{macrocode}
\newif\ifniib@debug
\newif\ifniib@logmin
\newif\ifniib@lognone
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib@log@err}
%\begin{macro}{\niib@log@warn}
%\begin{macro}{\niib@log@inf}
% Some handy re-usable macros are defined here.  These all take names
% beginning  These pop up in various places.  First errors, warnings
% and information are handled.  Package options are used to control
% how much output is given.
%    \begin{macrocode}
\newcommand*{\niib@log@err}[2]{%
  \ifniib@lognone\else
    \ifniib@logmin
      \PackageWarning{notes2bib}{#1}%
    \else
      \PackageError{notes2bib}{#1}{#2}%
    \fi
  \fi}
\newcommand*{\niib@log@warn}[1]{%
  \ifniib@lognone\else
    \ifniib@logmin\else
      \PackageWarning{notes2bib}{#1}%
    \fi
  \fi}
\newcommand*{\niib@log@inf}[1]{%
  \ifniib@lognone\else
    \ifniib@logmin\else
      \PackageInfo{notes2bib}{#1}%
    \fi
  \fi}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@log@debug}
% The debug macro only gives output if the appropriate package option
% is set.
%    \begin{macrocode}
\newcommand*{\niib@log@debug}[1]{%
  \ifniib@lognone\else
    \ifniib@debug
      \PackageInfo{notes2bib}{#1}%
    \fi
  \fi}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%
%\subsection{Package options}
%\begin{macro}{\niib@opt@boolkey}
% To aid maintenance, some shortcuts are defined for generating keys.
% These also allow the debugging messages to be added automatically
% to every key.
%    \begin{macrocode}
\newcommand*{\niib@opt@boolkey}[2][]{%
  \define@boolkey[niib]{opt}[niib@]{#2}[true]
  {#1\niib@log@debug{Option #2 set to ##1}}}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@opt@choicekey}
% A ``fill in the blanks'' choice key.  In all
% cases, \cs{niib@tempa} is used to hold the value given to the key,
% so that \cs{ifx} testing can occur.
%    \begin{macrocode}
\newcommand*{\niib@opt@choicekey}[5][]{%
  \define@choicekey*+[niib]{opt}{#2}[\niib@tempa]{#3}[#1]
    {#4\niib@log@debug{Option #2 set to ##1}}
    {#5\niib@log@debug{Option #2 set to ##1}}}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@opt@cmdkeys}
% A shortcut for \pkg{xkeyval} command keys.
%    \begin{macrocode}
\newcommand*{\niib@opt@cmdkeys}[1]{%
  \define@cmdkeys[niib]{opt}[niib@]{#1}}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niibsetup}
%\changes{v1.3}{2008/01/08}{New macro}
% To allow modification of options at run time, a setup macro is
% provided.  The run of strange tests are to prevent problems in
% arrays and the like.
%    \begin{macrocode}
\newcommand*{\niibsetup}[1]{%
  \iffalse{\fi\ifnum0=`}\fi
  \setkeys[niib]{opt}{#1}%
  \ifnum0=`{\fi\iffalse}\fi}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@opt@log}
%\begin{macro}{\niib@tempa}
%\begin{macro}{\niib@tempb}
% The \pkg{xkeyval} package option for logging is declared. This is
% then processed to set the switches correctly.
%    \begin{macrocode}
\niib@opt@choicekey[normal]{log}{debug,verbose,normal,errors,none}
%    \end{macrocode}
% A series of comparisons are made to assign the logging mode.  The
% \opt{normal} option is not tested, as executing the option sets the
% switches appropriately.
%    \begin{macrocode}
  {\niib@debugfalse
   \niib@logminfalse
   \niib@lognonefalse
   \renewcommand*{\niib@tempb}{none}%
   \ifx\niib@tempa\niib@tempb
     \niib@lognonetrue
   \fi
   \renewcommand*{\niib@tempb}{minimal}%
   \ifx\niib@tempa\niib@tempb
     \niib@logmintrue
   \fi
   \renewcommand*{\niib@tempb}{debug}%
   \ifx\niib@tempa\niib@tempb
     \niib@debugtrue
   \fi
   \renewcommand*{\niib@tempb}{verbose}%
   \ifx\niib@tempa\niib@tempb
     \niib@debugtrue
   \fi}
%    \end{macrocode}
% The option has not been recognised: give a warning (if
% appropriate).
%    \begin{macrocode}
   {\niib@log@warn{Unrecognised value `#1' for option log}}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib@opt@debug}
% A quick method to set \opt{log=debug}.
%    \begin{macrocode}
\niib@opt@boolkey{debug}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@opt@footnotes}
%\begin{macro}{\niib@opt@ndnotes}
%\begin{macro}{\ifniib@footnotes}
%\begin{macro}{\ifniib@endnotes}
% The \opt{footnote} and \opt{endnote} options are declared here.
%    \begin{macrocode}
\niib@opt@boolkey[\niib@swapfoot]{footnotes}
\niib@opt@boolkey[\niib@swapend]{endnotes}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\begin{macro}{\ifniib@head}
%\begin{macro}{\ifniib@tail}
% Switches are needed for placing notes before and after normal
% citations.
%    \begin{macrocode}
\newif\ifniib@tail
\newif\ifniib@head
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib@opt@sort}
%\begin{macro}{\niib@tempa}
%\begin{macro}{\niib@tempb}
% This option controls the position of notes \latin{versus} normal
% citations. The \pkg{xkeyval} option replaces the earlier \opt{head}
% and \opt{tail} options, which are retained for backward
% compatibility.\footnote{This may change in a future release; the
% options \opt{head} and \opt{tail} are ``depreciated.''}
%    \begin{macrocode}
\niib@opt@choicekey[none]{sort}{none,head,tail}
  {\niib@headfalse
   \niib@tailfalse
   \renewcommand*{\niib@tempb}{head}%
   \ifx\niib@tempa\niib@tempb
     \niib@headtrue
   \fi
   \renewcommand*{\niib@tempb}{tail}%
   \ifx\niib@tempa\niib@tempb
     \niib@tailtrue
   \fi}
  {\niib@log@warn{Unrecognised value `#1' for option sort}}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib@opt@head}
%\begin{macro}{\niib@opt@tail}
% The back-compatibility code; unlike earlier versions, this will
% take whatever the \opt{sort}-type key is given.
%    \begin{macrocode}
\niib@opt@boolkey[%
  \ifniib@head
    \ifniib@tail
      \niib@tailfalse
      \niib@log@inf{Option head cancels existing\MessageBreak
        tail or sort=tail option}
    \fi
  \fi]{head}
\niib@opt@boolkey[%
  \ifniib@tail
    \ifniib@head
      \niib@headfalse
      \niib@log@inf{Option tail cancels existing\MessageBreak
        head or sort=head option}
    \fi
  \fi]{tail}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib@opt@cite}
%\begin{macro}{\niib@cite}
%\begin{macro}{\niib@opt@name}
%\begin{macro}{\niib@name}
%\begin{macro}{\niib@opt@prefix}
%\begin{macro}{\niib@prefix}
%\begin{macro}{\niib@opt@record}
%\begin{macro}{\niib@record}
%\begin{macro}{\niib@opt@field}
%\begin{macro}{\niib@field}
%\begin{macro}{\niib@opt@presorthead}
%\begin{macro}{\niib@presorthead}
%\begin{macro}{\niib@opt@presortnone}
%\begin{macro}{\niib@presortnone}
%\begin{macro}{\niib@opt@presorttail}
%\begin{macro}{\niib@presorttail}
%\begin{macro}{\niib@opt@keyhead}
%\begin{macro}{\niib@keyhead}
%\begin{macro}{\niib@opt@keynone}
%\begin{macro}{\niib@keynone}
%\begin{macro}{\niib@opt@keytail}
%\begin{macro}{\niib@keytail}
% The various internal control values are set up as command keys.
%    \begin{macrocode}
\niib@opt@cmdkeys{%
  cite,
  name,
  prefix,
  record,
  field,
  presorthead,
  presortnone,
  presorttail,
  keyhead,
  keynone,
  keytail}
\niibsetup{%
  cite=cite,
  name=Bibnote,
  prefix=niib-,
  record=Misc,
  field=note,
  presorthead=ml,
  presortnone=mm,
  presorttail=mn,
  keyhead=aaa,
  keynone={},
  keytail=zzz}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%
%\subsection{Footnote and endnote handling}
%\begin{macro}{\niib@org@footnote}
%\begin{macro}{\niib@org@footnotemark}
%\begin{macro}{\niib@org@footnotetext}
%\begin{macro}{\niib@org@thanks}
% To allow dynamic handling of footnotes and endnotes, the original
% definitions are backed up.  This is done at the start of the
% document, so that changes from any other packages are picked up.
%    \begin{macrocode}
\AtBeginDocument{%
  \let\niib@org@footnote\footnote
  \let\niib@org@footnotemark\footnotemark
  \let\niib@org@footnotetext\footnotetext
  \let\niib@org@thanks\thanks
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib@org@endnote}
%\begin{macro}{\niib@org@endnotemark}
%\begin{macro}{\niib@org@endnotetext}
%\begin{macro}{\niib@org@theendnotes}
% If \pkg{endnotes} is loaded, then \cs{endnote} and friends have to
% be saved.
%    \begin{macrocode}
  \@ifpackageloaded{endnotes}
    {\let\niib@org@endnote\endnote
     \let\niib@org@endnotemark\endnotemark
     \let\niib@org@endnotetext\endnotetext
     \let\niib@org@theendnotes\theendnotes}}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib@thanks}
% The first step of converting footnotes into bibnotes is to patch
% the \cs{thanks} macro so that it uses the original definitions of
% \cs{footnotemark} and \cs{footnotetext}.  The necessary setup is
% also put in place for on-the-fly swapping of footnotes and
% bibnotes.
%    \begin{macrocode}
\AtBeginDocument{%
  \let\niib@thanks\thanks
  \let\niib@footnotetext\footnotetext
  \let\niib@footnotemark\footnotemark
  \patchcmd{\niib@thanks}{\footnotetext}{\niib@org@footnotetext}
    {\patchcmd{\niib@thanks}{\footnotemark}
      {\niib@org@footnotemark}
%    \end{macrocode}
%\begin{macro}{\thanks}
%\begin{macro}{\niib@footnotetext}
%\begin{macro}{\niib@footnotemark}
% If the package gets here, then both replacements have worked.  The
% updated definition of \cs{thanks} is applied (it does not depend on
% package options), and the definitions of \cs{footnotemark} and
% \cs{footnotetext} that are needed are set up.
%    \begin{macrocode}
      {\let\thanks\niib@thanks
       \let\niib@footnotetext\bibnotetext
       \let\niib@footnotemark\bibnotemark
       \niib@log@debug{Successfully patched \noexpand\thanks}}
%    \end{macrocode}
% This group deals with a failure of the second patch.
%    \begin{macrocode}
      {\niib@log@warn{Failed to patch \noexpand\thanks\MessageBreak
         \noexpand\footnotemark\space and
         \noexpand\footnotetext\MessageBreak are unmodified}%
       \niib@log@debug{Could not substitute
         \noexpand\footnotemark\MessageBreak in \noexpand\thanks}}}
%    \end{macrocode}
% If the first patch fails, then the error shows up here.
%    \begin{macrocode}
    {\niib@log@warn{Failed to patch \noexpand\thanks\MessageBreak
       \noexpand\footnotemark\space and
       \noexpand\footnotetext\MessageBreak are unmodified}%
     \niib@log@debug{Could not substitute
       \noexpand\footnotetext\MessageBreak in \noexpand\thanks}}}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib@swapfoot}
%\begin{macro}{\footnote}
%\begin{macro}{\footnotemark}
%\begin{macro}{\footnotetext}
% The swapping code can now be implemented.
%    \begin{macrocode}
\newcommand*{\niib@swapfoot}{}
\AtBeginDocument{%
  \renewcommand*{\niib@swapfoot}{%
    \ifniib@footnotes
      \let\footnote\bibnote
      \let\footnotemark\niib@footnotemark
      \let\footnotetext\niib@footnotetext
      \niib@log@debug{Converting footnotes to bibnotes}%
    \else
      \let\footnote\niib@org@footnote
      \let\footnotemark\niib@org@footnotemark
      \let\footnotetext\niib@org@footnotetext
      \niib@log@debug{Using kernel definition of footnotes}%
    \fi}
  \niib@swapfoot}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib@swapend}
%\begin{macro}{\endnote}
%\begin{macro}{\endnotemark}
%\begin{macro}{\endnotetext}
%\begin{macro}{\theendnotes}
% For endnotes, the code needed depends on whether the \pkg{endnotes}
% package is available or not.  If it is, then swapping the two
% definitions is set up.
%    \begin{macrocode}
\newcommand*{\niib@swapend}{}
\AtBeginDocument{%
  \@ifpackageloaded{endnotes}
    {\renewcommand*{\niib@swapend}{%
       \ifniib@endnotes
         \let\endnote\bibnote
         \let\endnotemark\bibnotemark
         \let\endnotetext\bibnotetext
         \let\theendnotes\printbibnotes
         \niib@log@debug{Converting endnotes to bibnotes}%
       \else
         \let\endnote\niib@org@endnote
         \let\endnotemark\niib@org@endnotemark
         \let\endnotetext\niib@org@endnotetext
         \let\theendnotes\niib@org@theendnotes
         \niib@log@debug{Using endnotes package to handle endnotes}%
       \fi}
     \niib@swapend}
%    \end{macrocode}
% \pkg{endnotes} is not loaded; once the \opt{endnotes} option has been
% given, there is nothing to go back.  Of course, if the user does not
% give the \opt{endnotes} option, \cs{endnote} is not defined at all.
%    \begin{macrocode}
    {\ifniib@endnotes
       \let\endnote\bibnote
       \let\endnotemark\bibnotemark
       \let\endnotetext\bibnotetext
       \let\theendnotes\printbibnotes
       \niib@log@debug{Converting endnotes to bibnotes}%
     \fi
     \renewcommand*{\niib@swapend}{%
       \ifniib@endnotes
         \let\endnote\bibnote
         \let\endnotemark\bibnotemark
         \let\endnotetext\bibnotetext
         \let\theendnotes\printbibnotes
         \niib@log@debug{Converting endnotes to bibnotes}%
       \else
         \niib@log@inf{endnotes package not loaded\MessageBreak
           endnotes=false ignored}%
       \fi}}}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%
%\subsection{User macros}
%\begin{macro}{\thebibnote}
% A counter is needed for the notes created.  In analogy to other
% counters in \LaTeX, this is given a \cs{the\dots} name.  The user
% should not really need to use this macro, but convention dictate
% that it has a user-space name.  The \LaTeX\ \cs{newcounter} macro
% is used (rather than the \TeX\ \cs{newcount}) as the automatic
% system expects the numbers to be globally unique.
%    \begin{macrocode}
\newcounter{bibnote}
\renewcommand*{\thebibnote}{\niib@name\the\value{bibnote}}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\bibnote}
%\changes{v1.1}{2007/09/29}{Macro made robust}
% Each new bibnote increments the note counter, then checks for an
% optional label, before handing off to the internal macro
% \cs{niib@bibnote}.
%    \begin{macrocode}
\DeclareRobustCommand*{\bibnote}{%
  \stepcounter{bibnote}%
  \@ifnextchar[%]
    {\niib@bibnote}
    {\niib@bibnote[\thebibnote]}}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\bibnotemark}
%\changes{v1.1}{2007/09/29}{Macro made robust}
% The \cs{bibnotemark} macro works in the same way as \cs{bibnote},
% but calls \cs{niib@mark} rather than \cs{niib@bibnote}.
%    \begin{macrocode}
\DeclareRobustCommand*{\bibnotemark}{%
  \stepcounter{bibnote}%
  \@ifnextchar[%]
    {\niib@mark}
    {\niib@mark[\thebibnote]}}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\bibnotetext}
%\changes{v1.1}{2007/09/29}{Macro made robust}
% The text companion to the mark macro above, with no increment of
% the counter.  There is nothing special to do, so the \LaTeX\ kernel
% handling of optional arguments can be used.
%    \begin{macrocode}
\DeclareRobustCommand*{\bibnotetext}[1][\thebibnote]{%
  \niib@text{#1}}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\printbibnotes}
%\changes{v1.1}{2007/09/29}{Macro made robust}
%\changes{v1.3b}{2008/01/16}{Definition moved to beginning of
%  document}
% To allow for the possibility of there being no other notes, a
% command to print only notes is given.  In the \pkg{biblatex} case,
% the best that can be done is to issue \cs{printbibliography}.
%    \begin{macrocode}
\AtBeginDocument{%
  \@ifpackageloaded{biblatex}
    {\let\printbibnotes\printbibliography}
    {\DeclareRobustCommand*{\printbibnotes}
       {\niib@org@bib{\niib@prefix\jobname}}}}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\flushnotestack}
%\changes{v1.1}{2007/09/29}{Macro made robust}
%\changes{v1.3}{2008/01/08}{Fixed bug with empty stack}
%\changes{v1.3}{2008/01/08}{Renamed from \cs{flushcitestack}}
%\changes{v1.3b}{2008/01/16}{Writes stack to \ext{aux} file}
%\changes{v1.3b}{2008/01/16}{Added check for correct \opt{tail}
%  citations in \ext{aux} file}
% In order to delay citations to the end of the bibliography (and
% thus force others to the start), a ``stack'' is created of
% citations which need to be written to the \ext{aux} file.  This
% is done here, and the stack is cleared so collection can begin
% again.
%    \begin{macrocode}
\DeclareRobustCommand*{\flushnotestack}{%
  \let\niib@taillist\niib@stack
  \ifniib@rerun\else
    \niib@checkrerun{tail}%
  \fi
  \ifx\@empty\niib@stack\@empty
    \niib@log@debug{Citation stack empty: nothing for\MessageBreak
      \noexpand\flushnotestack to do}%
  \else%
    \niib@log@debug{Flushing note citations to aux file}%
    \if@filesw
      \immediate\write\@auxout{\string\niibtailcite{\niib@stack}}%
    \fi
    \expandafter\nocite\expandafter{\niib@stack}%
    \gdef\niib@stack{}%
  \fi}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\citenote}
%\changes{v1.0a}{2007/09/03}{New macro}
%\changes{v1.1}{2007/09/29}{Macro made robust}
%\changes{v1.3}{2008/01/08}{Now a wrapper for \cs{niib@mark}}
% Problems arise with \cs{cite} and the \opt{sort=tail} option.  Rather
% than overload \cs{cite} with all of the problems that can bring, a
% new command is provided that can be guaranteed to work.
%    \begin{macrocode}
\DeclareRobustCommand*{\citenote}[1]{\niib@mark[#1]}
%    \end{macrocode}
%\end{macro}
%
%\subsection{Internal macros}
%\begin{macro}{\niib@keyname}
%\changes{v1.3}{2008/01/08}{Moved to \cs{AtBeginDocument}}
% If \pkg{biblatex} is in use, the key field in the \BibTeX\ database
% should be called ``keysort,'' whereas otherwise it should be
% ``key.''
%    \begin{macrocode}
\AtBeginDocument{%
  \@ifpackageloaded{biblatex}
    {\niib@log@debug{Using field `keysort' for sorting key}%
     \newcommand*\niib@keyname{keysort}}
    {\niib@log@debug{Using field `key' for sorting key}%
     \newcommand*\niib@keyname{key}}}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@presort}
%\changes{v1.3}{2008/01/08}{Dynamic rather than static definition}
%\begin{macro}{\niib@key}
%\changes{v1.3}{2008/01/08}{Dynamic rather than static definition}
% The values taken by \cs{niib@presort} and \cs{niib@key} depend
% on the desired positioning of notes in the bibliography.
%    \begin{macrocode}
\newcommand*{\niib@presort}{%
  \ifniib@head
    \niib@presorthead%
  \else
    \ifniib@tail
      \niib@presorttail%
    \else
      \niib@presortnone%
    \fi
  \fi}
\newcommand*{\niib@key}{%
  \ifniib@head
    \niib@keyhead%
  \else
    \ifniib@tail
      \niib@keytail%
    \else
      \niib@keynone%
    \fi
  \fi}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib@msg}
% To inform the user, the automatically-created \BibTeX\ database
% needs to carry suitable information on its source.
%    \begin{macrocode}
\edef\niib@msg{%
  This is an auxiliary file used by the `notes2bib' package.^^J%
  This file may safely be deleted. It will be recreated as
  required.^^J}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@stack}
% This macro is needed to store any citations at the end of the
% bibliography.  Initially, this is empty.
%    \begin{macrocode}
\newcommand*{\niib@stack}{}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@addtostack}
%\changes{v1.3}{2008/01/08}{Macro renamed from \cs{niib@stackup}}
%\begin{macro}{\niib@tempa}
% The various optional argument tricks above all use the same core
% code, which adds the mandatory argument of the citation to the
% stack.  The stack is global (see also \cs{flushnotestack}).
%    \begin{macrocode}
\newcommand*{\niib@addtostack}[1]{%
  \niib@log@debug{Adding citation #1\MessageBreak to `tail' stack}%
  \edef\niib@tempa{#1}%
  \ifx\@empty\niib@stack\@empty
    \xdef\niib@stack{\niib@tempa}%
  \else
    \xdef\niib@stack{\niib@stack,\niib@tempa}%
  \fi}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib@bibnote}
%\changes{v1.3}{2008/01/08}{Use \cs{niib@mark} for citation}
% Two steps are needed here, writing the text of the note to file
% (handled by \cs{niib@text}, and marking the citation (using
% \cs{niib@cite}).
%    \begin{macrocode}
\long\def\niib@bibnote[#1]#2{%
  \niib@text{#1}{#2}%
  \niib@mark[#1]}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@headlist}
% To inform the user that a re-run of \LaTeX\ is needed, tracking is
% needed of any ``head'' citations.
%    \begin{macrocode}
\newcommand*{\niib@headlist}{}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@mark}
%\begin{macro}{\niib@tempa}
% Adding a citation to the \LaTeX\ file is handled here.  When using
% the \opt{sort=head} option, the citation is written to the
% \ext{aux} file for sorting control.  The normal citation command is
% then called.
%    \begin{macrocode}
\def\niib@mark[#1]{%
  \ifniib@head
    \edef\niib@tempa{#1}%
    \ifx\@empty\niib@headlist\@empty
      \xdef\niib@headlist{\niib@tempa}%
    \else
      \xdef\niib@headlist{\niib@headlist,\niib@tempa}%
    \fi
    \if@filesw
      \niib@log@debug{Adding citation #1 to list for next run}%
      \immediate\write\@auxout{\string\niibheadcite{#1}}%
    \fi
  \fi
%    \end{macrocode}
%\end{macro}
% When the \opt{sort=tail} option is active, citation is handled by
% another macro, so a switch is needed.
%    \begin{macrocode}
  \ifniib@tail
    \expandafter\niib@tailcite%
  \else
    \expandafter\niib@normcite%
  \fi
  {#1}}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\ifniib@filesw}
% A switch is used to back up \cs{if@filesw}.
%    \begin{macrocode}
\newif\ifniib@filesw
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@tailcite}
% When using the \opt{sort=tail} option, bibnote citation need to be
% stored for later.   With \pkg{biblatex}, the \cs{AtEndCite} macro
% is available to provide a hook for the necessary switch.  In other
% cases, the current value of \cs{if@filesw} is then saved, before
% turning it off and setting up the restore system.
%\end{macro}
%    \begin{macrocode}
\AtBeginDocument{%
  \@ifpackageloaded{biblatex}
    {\newcommand{\niib@tailcite}[1]{%
       \niib@addtostack{#1}%
       \AtNextCite{\@fileswfalse}%
       \niib@normcite{#1}}}
    {\newcommand{\niib@tailcite}[1]{%
       \niib@addtostack{#1}%
       \let\ifniib@filesw\if@filesw
       \@fileswfalse
       \let\niib@auxhook\niib@restorefilesw
       \niib@tcite{#1}}}}
%    \end{macrocode}
%\begin{macro}{\niib@restorefilesw}
% Restoring the switch is set up here.  The reference to
% \cs{niib@auxhook} ensures that the mechanism is turned off for the
% next real citation.
%    \begin{macrocode}
\newcommand*{\niib@restorefilesw}{%
  \let\if@filesw\ifniib@filesw
  \let\niib@auxhook\relax}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@tcite}
% Actually carrying out the citation, and restoring the value of
% \cs{if@filesw} depends on whether \pkg{cite} is loaded.
%    \begin{macrocode}
\AtBeginDocument{%
  \@ifpackageloaded{cite}
    {\newcommand*{\niib@tcite}[1]{\niib@normcite{#1}}}
    {\newcommand*{\niib@tcite}[1]{%
       \niib@normcite{#1}%
       \niib@restorefilesw}}}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@normcite}
% The normal citation command.
%    \begin{macrocode}
\newcommand*{\niib@normcite}{\@nameuse{\niib@cite}}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@text}
%\changes{v1.1}{2007/09/29}{Combined \cs{niib@text}
%  and \cs{niib@@text}}
%\changes{v1.1}{2007/09/29}{Improved awareness of files switch}
% The ``business end'' of writing the notes to file.  This is a
% \cs{long} macro, so no star is used for \cs{newcommand}.
%    \begin{macrocode}
\newcommand{\niib@text}[2]{%
%    \end{macrocode}
%\begin{macro}{\niib@out}
%\begin{macro}{\niib@stream}
% If this is the first note, then a new output stream is needed,
% otherwise it will already be open.
%    \begin{macrocode}
  \@ifundefined{niib@out}{%
    \if@filesw
      \newwrite\niib@out%
      \gdef\niib@stream{\niib@prefix\jobname.bib}%
      \niib@log@debug{Creating BibTeX database file \MessageBreak
        \niib@stream\space to contain bibnotes}%
      \immediate\openout\niib@out\niib@stream\relax
%    \end{macrocode}
% The new file starts with the message that it has been automatically
% generated by \currpkg.
%    \begin{macrocode}
      \immediate\write\niib@out{\niib@msg}%
    \fi}{}%
%    \end{macrocode}
%\end{macro}
%\end{macro}
% The new record is now written to file.  The \cs{unexpanded} \eTeX\
% primitive is used to avoid expansion of macros in the note text.
% The only issue with this is the addition of spaces after command
% names; this is the reason verbatim text cannot be used in bibnotes.
%    \begin{macrocode}
  \if@filesw
    \niib@log@debug{Writing bibnote #1 contents
      \MessageBreak---\MessageBreak#2\MessageBreak---\MessageBreak
      to BibTeX database}%
    \immediate\write\niib@out{%
      @\niib@record\string{#1,^^J%
      presort = \string{\niib@presort\string},^^J%
      \niib@keyname\space= \string{\niib@key#1\string},^^J%
      \niib@field\space= \string{\unexpanded{#2}\string}^^J%
      \string}^^J}%
  \fi}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@headcitelist}
% To inform the user that a re-run of \LaTeX\ is needed, tracking is
% needed of any citations that have been moved to the start of the
% \ext{aux} file. This needs an initially-empty macro.
%    \begin{macrocode}
\newcommand*{\niib@headcitelist}{}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\document}
%\changes{v1.3}{2008/01/08}{Added hook after \ext{aux} files has been
%  read but before document begins}
%\begin{macro}{\niib@dochook}
%\begin{macro}{\niibheadcite}
%\changes{v1.3}{2008/01/08}{New macro}
%\begin{macro}{\niib@tempa}
% When using the \opt{sort=head} option, bibnotes need to appear in
% the \ext{aux} file before other citations.  Other approaches cause
% all sorts of problems, so the suggestion of Michael Shell is
% implemented here. When \opt{head} is active, \cs{niibheadcite} is
% added to the \ext{aux} file.  At the next \LaTeX\ run, this will
% add a citation to the beginning of the \ext{aux} file.  To get the
% \cs{nocite} to work, a hook has to be added to \cs{document}.  The
% reason is that \cs{AtBeginDocument} cannot be used here: it is not
% available once the old \ext{aux} file has been read.
%    \begin{macrocode}
\g@addto@macro{\document}{\niib@dochook}
\newcommand*{\niibheadcite}[1]{%
  \edef\niib@tempa{#1}%
  \ifx\@empty\niib@headcitelist\@empty
    \xdef\niib@headcitelist{\niib@tempa}%
  \else
    \xdef\niib@headcitelist{\niib@headcitelist,\niib@tempa}%
  \fi
  \if@filesw
    \niib@log@debug{Adding citation #1 to start of .aux file}%
  \fi
  \g@addto@macro{\niib@dochook}{\nocite{#1}}}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib@tailcitelist}
%\changes{v1.3b}{2008/01/16}{New macro}
%\begin{macro}{\niibtailcite}
%\changes{v1.3b}{2008/01/16}{New macro}
%\begin{macro}{\niib@tempa}
% To enable proper logging of citations when \opt{sort=tail}, a
% similar system to the above is employed without the \cs{nocite}
% part.
%    \begin{macrocode}
\newcommand*{\niib@tailcitelist}{}
\newcommand*{\niibtailcite}[1]{%
  \edef\niib@tempa{#1}%
  \ifx\@empty\niib@tailcitelist\@empty
    \xdef\niib@tailcitelist{\niib@tempa}%
  \else
    \xdef\niib@tailcitelist{\niib@tailcitelist,\niib@tempa}%
  \fi}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib@auxhook}
%\changes{v1.3}{2008/01/08}{New macro}
%\begin{macro}{\niib@dochook}
%\changes{v1.3}{2008/01/08}{New macro}
%\begin{macro}{\@restore@auxhandle}
% To allow the automatic punctuation-searching of \pkg{cite} to work,
% some code has to be added to the hook available there.  However, as
% that is intended for \pkg{multibib}, care is needed to get the
% desired result.  \cs{niib@dochook} is defined here, even though it
% is needed above, as the code here will always be executed.
%    \begin{macrocode}
\newcommand*{\niib@dochook}{%
  \@ifundefined{@restore@auxhandle}
    {\newcommand*{\@restore@auxhandle}{\niib@auxhook}}
    {\ifx\relax\@restore@auxhandle\relax
       \newcommand*{\@restore@auxhandle}{\niib@auxhook}%
     \else
       \g@addto@macro{\@restore@auxhandle}{\niib@auxhook}%
     \fi}}
\newcommand*{\niib@auxhook}{}
\let\niib@auxhook\relax
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\begin{macro}{\blx@bibfiles}
%\changes{v1.2}{2007/10/26}{Fixed bug with \pkg{biblatex} support}
%\changes{v1.3}{2008/01/08}{Modification now at beginning of
%  document}
%\changes{v1.3}{2008/01/08}{Updated for \pkg{biblatex} v0.7: moved
%  to end of preamble, switch from \cs{bib@gadd} to \cs{gappto}}
% The \cs{bibliography} macro is patched to ensure that when it is
% executed the note file is also processed.  \pkg{biblatex} does
% things very differently, but this actually makes it much easier to
% patch for.
%    \begin{macrocode}
\AtEndPreamble{%
  \@ifpackageloaded{biblatex}%
    {\expandafter\gappto\expandafter\blx@bibfiles\expandafter%
       {,\niib@prefix\jobname}
     \niib@log@debug{Added bibnotes database to biblatex file list}}%
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@org@bib}
%\begin{macro}{\bibliography}
%\changes{v1.3}{2008/01/08}{Modification now at beginning of
%  document}
% Without \pkg{biblatex}, the bibliography command is patched so that
% it will run on the automatically-generated \BibTeX\ database.  If
% no notes have been added, then the macro doesn't actually do
% anything.
%    \begin{macrocode}
    {\let\niib@org@bib\bibliography
     \renewcommand{\bibliography}[1]{%
       \ifnum\the\value{bibnote} > \z@
         \niib@org@bib{\niib@prefix\jobname,#1}%
       \else
         \niib@org@bib{#1}%
       \fi}
     \niib@log@debug{Added bibnote database to
       \noexpand\bibliography}}}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%
%\subsection{Finalisation}
%\begin{macro}{\ifniib@rerun}
% A switch is needed for the re-run test.
%    \begin{macrocode}
\newif\ifniib@rerun
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@checkrerun}
%\changes{v1.3b}{2008/01/16}{Added ability to check for both
%  \opt{head} and \opt{tail} re-runs}
%\changes{v1.3b}{2008/01/16}{Bug fix with logging for
%  \opt{debug} logging}
% Any ``head'' notes may mean a second \LaTeX\ run is needed.
%    \begin{macrocode}
\newcommand*{\niib@checkrerun}[1]{%
  \niib@rerunfalse
  \expandafter\ifx\expandafter\@empty\csname niib@#1list\endcsname%
    \@empty
    \expandafter\ifx\expandafter\@empty\csname niib@#1citelist%
      \endcsname\@empty
      \niib@log@debug{No `#1' notes detected}%
    \else
      \niib@reruntrue
      \niib@log@debug{No `#1' notes found this run\MessageBreak
        but .aux files contained the `#1' requests:\MessageBreak
        \csname niib@#1citelist\endcsname}%
    \fi
  \else
    \expandafter\ifx\expandafter\@empty\csname niib@#1citelist%
      \endcsname\@empty
      \niib@reruntrue
      \niib@log@debug{No `#1' requests in .aux file\MessageBreak
        but `#1' notes in this run:\MessageBreak
        \csname niib@#1list\endcsname}%
    \else
%    \end{macrocode}
% If the package gets here, then there are some notes and some
% requests in the aux file.  The two lists are now compared.
%    \begin{macrocode}
      \niib@checklists{#1}%
    \fi
  \fi
  \ifniib@rerun
%    \end{macrocode}
% Both human-readable requests for new runs, and \pkg{biblatex}-style
% automated requests are made.  The package does not know if \BibTeX8
% is in use, so just asks for \BibTeX.
%    \begin{macrocode}
    \niib@log@warn{Rerun LaTeX to get correct \MessageBreak
      `#1' notes}%
    \niib@log@warn{Please (re)run BibTeX on the file(s):
      \MessageBreak\jobname.aux
      \MessageBreak and rerun LaTeX afterwards.}%
    \ifniib@lognone\else
      \typeout{%
        REQ:3:latex:REQ^^J%
        REQ:2:bibtex:REQ^^J%
        REQ:1:latex:REQ}%
    \fi
  \fi}
%    \end{macrocode}
%\end{macro}
%\begin{macro}{\niib@checklists}
%\changes{v1.3b}{2008/01/16}{Added ability to check for both
%  \opt{sort=head} and \opt{sort=tail}}
%\begin{macro}{\niib@tempa}
%\begin{macro}{\niib@tempb}
% The business end of comparing the two lists.  Two sweeps are made,
% to check that the lists match entirely.
%    \begin{macrocode}
\newcommand*{\niib@checklists}[1]{%
%    \end{macrocode}
%\begin{macro}{\niib@list}
%\changes{v1.3b}{2008/01/16}{New macro}
%\begin{macro}{\niib@citelist}
%\changes{v1.3b}{2008/01/16}{New macro}
% To allow \cs{niib@checklists} to handle both \opt{sort=head} and
% \opt{sort=tail} citations, the expanded list is needed for the
% \cs{@for} loops.
%    \begin{macrocode}
  \expandafter\edef\expandafter\niib@list\expandafter%
    {\csname niib@#1list\endcsname}%
  \expandafter\edef\expandafter\niib@citelist\expandafter%
    {\csname niib@#1citelist\endcsname}%
%    \end{macrocode}
%\end{macro}
%\end{macro}
% The loops can now being.
%    \begin{macrocode}
  \@for\niib@tempa:=\niib@list\do{%
    \niib@reruntrue
    \@for\niib@tempb:=\niib@citelist\do{%
      \ifx\niib@tempa\niib@tempb
        \niib@rerunfalse
      \fi}
    \ifniib@rerun
      \niib@log@debug{Note \niib@tempa\space is a `#1' note
        \MessageBreak but request not in .aux file}%
    \fi}
  \ifniib@rerun\else
    \@for\niib@tempa:=\niib@citelist\do{%
      \niib@reruntrue
      \@for\niib@tempb:=\niib@list\do{%
        \ifx\niib@tempa\niib@tempb
          \niib@rerunfalse
        \fi}
      \ifniib@rerun
        \niib@log@debug{Note \niib@tempa\space is set to `#1' in
          .aux\MessageBreak file but is not a `#1' note}%
      \fi}
  \fi}
%    \end{macrocode}
%\end{macro}
%\end{macro}
%\end{macro}
%\begin{macro}{\niib@taillist}
%\changes{v1.3b}{2008/01/16}{New macro}
% At the end of the document, any delayed citations are written to the
% \ext{aux} file, and the database file is closed cleanly.  A check is
% also made for the need for an additional \LaTeX\ run for ``head''
% notes.
%    \begin{macrocode}
\AtEndDocument{%
  \niib@rerunfalse
  \niib@checkrerun{head}%
  \flushnotestack%
  \@ifundefined{niib@out}{}
    {\immediate\closeout\niib@out%
     \niib@log@debug{Closed BibTeX database file\MessageBreak
       \niib@stream}}}
%    \end{macrocode}
%\end{macro}
% Options are processed at the end of the package, to avoid any odd
% issues arising with definition of macros.
%    \begin{macrocode}
\ProcessOptionsX[niib]<opt>
%    \end{macrocode}
%
%\iffalse
%</package>
%\fi
% \PrintChanges
% \PrintIndex
% \Finale
%\iffalse
%<*jawltxdoc>
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{jawltxdoc}
\usepackage[T1]{fontenc}
\usepackage[english,UKenglish]{babel}
\usepackage[scaled=0.95]{helvet}
\usepackage[version=3]{mhchem}
\usepackage[final]{microtype}
\usepackage[osf]{mathpazo}
\usepackage{booktabs,array,url,graphicx,courier,xspace}
\usepackage{upgreek,ifpdf,listings}
\ifpdf
  \usepackage{embedfile}
  \embedfile[%
    stringmethod=escape,%
    mimetype=plain/text,%
    desc={LaTeX docstrip source archive for package `\jobname'}%
    ]{\jobname.dtx}
\fi
\IfFileExists{\jobname.sty}
  {\usepackage{\jobname}}{}
\usepackage[numbered]{hypdoc}
\newlength\LaTeXwidth
\newlength\LaTeXoutdent
\newlength\LaTeXgap
\setlength\LaTeXgap{1em}
\setlength\LaTeXoutdent{-0.15\textwidth}
\newcommand*{\typesetexampleandcode}{%
  \begin{list}{}{%
    \setlength\itemindent{0pt}
    \setlength\leftmargin\LaTeXoutdent
    \setlength\rightmargin{0pt}
  }
  \item
    \setlength\LaTeXoutdent{-0.15\textwidth}
    \begin{minipage}[c]{\textwidth-\LaTeXwidth-\LaTeXoutdent-\LaTeXgap}
      \lst@sampleInput
    \end{minipage}%
    \hfill%
    \begin{minipage}[c]{\LaTeXwidth}%
      \hbox to\linewidth{\box\lst@samplebox\hss}%
    \end{minipage}%
  \end{list}
}
\newcommand*{\typesetcodeandexample}{%
  \begin{list}{}{%
    \setlength\itemindent{0pt}
    \setlength\leftmargin{0pt}
    \setlength\rightmargin{0pt}
  }
  \item
    \begin{minipage}[c]{\LaTeXwidth}%
      \hbox to\linewidth{\box\lst@samplebox\hss}%
    \end{minipage}%
    \lst@sampleInput
  \end{list}
}
\newcommand*{\typesetfloatexample}{%
  \begin{list}{}{%
    \setlength\itemindent{0pt}
    \setlength\leftmargin{0pt}
    \setlength\rightmargin{0pt}
  }
  \item
    \lst@sampleInput
    \begin{minipage}[c]{\LaTeXwidth}%
      \hbox to\linewidth{\box\lst@samplebox\hss}%
    \end{minipage}%
  \end{list}
}
\newcommand*{\typesetcodeonly}{%
  \begin{list}{}{%
    \setlength\itemindent{0pt}
    \setlength\leftmargin{0pt}
    \setlength\rightmargin{0pt}
  }
  \item
    \begin{minipage}[c]{\LaTeXwidth}%
      \hbox to\linewidth{\box\lst@samplebox\hss}%
    \end{minipage}%
  \end{list}
}
\edef\LaTeXexamplefile{\jobname.tmp}
\lst@RequireAspects{writefile}
\newbox\lst@samplebox
\lstnewenvironment{LaTeXexample}[1][\typesetexampleandcode]{%
  \let\typesetexample#1
  \global\let\lst@intname\@empty
  \setbox\lst@samplebox=\hbox\bgroup
  \setkeys{lst}{language=[LaTeX]{TeX},tabsize=4,gobble=3,%
    breakindent=0pt,basicstyle=\small\ttfamily,basewidth=0.51em,%
    keywordstyle=\color{blue},%
    morekeywords={% notes2bib
      niibsetup,bibnote,bibnotetext,bibnotemark,thebibnote,%
      flushnotestack,citenote,printbibnotes}}
  \lst@BeginAlsoWriteFile{\LaTeXexamplefile}
}{%
  \lst@EndWriteFile\egroup
  \setlength\LaTeXwidth{\wd\lst@samplebox}
  \typesetexample%
}
\newcommand*{\lst@sampleInput}{%
  \MakePercentComment\catcode`\^^M=10\relax
  \small%
  {\setkeys{lst}{SelectCharTable=\lst@ReplaceInput{\^\^I}%
    {\lst@ProcessTabulator}}%
    \leavevmode \input{\LaTeXexamplefile}}%
  \MakePercentIgnore%
}
\newcommand*{\pkg}[1]{\textsf{#1}}
\newcommand*{\currpkg}{\pkg{\jobname}\xspace}
\newcommand*{\opt}[1]{\texttt{#1}}
\newcommand*{\file}[1]{\texttt{#1}}
\newcommand*{\ext}[1]{\file{.#1}}
\newcommand*{\latin}[1]{\emph{#1}}
\newcommand*{\etc}{%
  \@ifnextchar.
    {\latin{etc}}
    {\latin{etc.}}
  \xspace}
\newcommand*{\eg}{%
  \@ifnextchar.
    {\latin{e.g}}
    {\latin{e.g.}}
  \xspace}
\newcommand*{\ie}{%
  \@ifnextchar.
    {\latin{i.e}}
    {\latin{i.e.}}
  \xspace}
\newcommand*{\AMS}{{\protect\usefont{OMS}{cmsy}{m}{n}%
  A\kern-.1667em\lower.5ex\hbox{M}\kern-.125emS}}
\providecommand*{\eTeX}{\ensuremath{\varepsilon}-\TeX}
\newcommand*{\XeTeX}
  {X\kern-.125em\lower.5ex\hbox{\reflectbox{E}}\kern-.1667em\TeX}
%</jawltxdoc>
%\fi
