% \iffalse meta-comment
%
% todo - package for to-do lists.
% Copyright 2002 Federico Garcia (feg8@pitt.edu, fedegarcia@hotmail.com)
% -------------------------------------------
% 
%
% This program can be redistributed and/or modified under the terms
% of the LaTeX Project Public License distributed from CTAN archives
% in the directory macros/latex/base/lppl.txt; either version 1 of
% the License, or (at your option) any later version.
%
%
%<*driver>
% \fi
\ProvidesFile{opcit.dtx}[2002/12/25 v1.1 Footnote references]
% \iffalse
\documentclass{ltxdoc}
\GetFileInfo{opcit.dtx}
\title{A package for footnote-style bibliographical references}
\date{\filedate{}}
 \author{Federico Garcia\\\texttt{feg8@pitt.edu}}
\begin{document}
\maketitle
 \DocInput{\filename}
\end{document}
%</driver>
% \fi
%\section{Introduction}
%
%The basic bibliography styles of \LaTeXe\ and \textsc{Bib}\TeX, with labels between [~and~], are very foreign to the common uses of humanities-writing. In recent times, the category of bibliographical styles known as `author-date' seem to be gaining acceptance and becoming the most usual way to refer to a final list of references and have been successfully implemented in \LaTeX\ and \textsc{Bib}\TeX, for example in packages such as |achicago| and |harvard|. 
%
%But certain disciplines---I have in mind musicology---still use, almost exclusively, the `old way' of footnote-referencing, above all in journal articles, which do not have a final list of `References' to which any key can refer. Author-year styles have the significant drawback that the labels interfere with the reading; and, as Susan~King and Oren~Patashnik point out in their `Editorial note' in the |apalike.bst| file, the main reason to use them (that changes to the bibliography does not mean ``changing numbers in both references and text") is rendered weakest by computerized typography. As far as I know, the `footnote category' of bibliographical styles has not been particularly addressed by package-writers. This is what |opcit| intends to do.
%
%Actually, there \emph{is} a package intended to place the bibliography as footnotes, namely |footbib|.\footnote{By Eric Domenjoud, 1995.} In this package, the labels appear as superscripts---$^{[1]}$---and the information about the source is appended to the bottom of the page. It is not, however, \emph{really} a footnote, for their numbering is independent, and if other footnotes (not reference-ones) appear, they appear separated from the reference-ones. In this way, the whole approach is a kind of `hybrid' between label-oriented and footnote-oriented bibliographical styles. 
%
%The system I provide with |opcit| makes the references footnotes in every sense. On the other hand, as is usual in this kind of style, it keeps track of what sources have already been cited, in order to avoid multiple copies of the same, potencially long, footnote. So it makes automatic use of usual (and beautiful) conventions such as \emph{Op.~Cit.}---which fives the package its name---and \emph{Idem}, or allows the user to set `hereafters' to repeatedly refer to the same publication.
%
%What I regret most about this package is that I was not able to make it `|bst|-independent,' i.e., able to run with any \textsc{Bib}\TeX\ style that the user could want to use. (This, for example, is one of the good things about |footbib|.) The main reason why this was not possible is that |bst| files are designed to print the information in a list, not as footnotes, inserting, for example, periods instead of commas, and giving the author names with last-name first. 
%
%Since I do not want to fix the \textsc{Bib}\TeX\ style to use with |opcit| (and, OK, also because of lack of time), I have made one with support for just four kinds of entry (the ones I have needed and tested): \texttt{ARTICLE}, \texttt{BOOK}, \texttt{INCOLLECTION}, and \texttt{MISC}. In this documentation I will try to make clear what is needed for new entries to be appended by the users.\footnote{Changing, as usual, the name of the file.} Eventually, I will add more of them, as well as implement the cross-referencing mechanisms. 
%
%\section{Use}
%
%\DescribeMacro{\cite}
%The user keeps citing bibliographical references with |\cite|. Thus, |\cite{texbook}| will produce the footnote `\footnote{Donald E. Knuth, \emph{The \TeX book} (Reading, Mass.: Addison Wesley, 1986).}'. The optional argument has the usual meaning, so |\cite[p.~100]{taruskin}| creates `\footnote{Richard Taruskin, \emph{Defining Russia musically: Historical and Hermeneutical Essays} (Princeton: Princeton University Press, 1997), p.~100.}'.
%
%Note that |opcit| adds a period at the end of the footnotes; however, if the user adds it (for example, in |\cite[Introduction.]{gellner}|), it will refrain from adding it: `\footnote{Ernest Gellner, \emph{Thought and change} (Chicago: University of Chicago Press, 1964), introduction.}'. It will also avoid it after `?' or `!'; in general, after any character with a |\sfcode| equal to the one of the period. (I am afraid this is lost in |\frenchspacing| and similar situations, where |opcit| has no way to `see' the period, and will \emph{always} add one.)
%
%\textbf{Warning!} I have no clue as to why, but there is a problem when the optional argument to |\cite| starts with two identical symbols (which is unfortunately very often in expressions such as |\cite[pp.~10ff.]|!). A |\relax| should be put between them (|\cite[p\relax p~10.ff]|) to ensure proper behavior.
%
%A |\cite| command can also occur within the argument of a |\footnote|. In that case, the information on the source is added to the text of the footnote, with \emph{no} period added.\footnote{This is because it is assumed that the user will always `close' the footnote with a final period. Issuing here \texttt{\textbackslash cite\{martinb\}}, which produces Jes\'us Mart\'{\i}n-Barbero, \emph{Communication, culture, and hegemony: From media to mediations} (London: SAGE Publications, 1993), I do not want |opcit| to add a period.}
%
%A later citation of the \TeX book through |\cite{texbook}| will not render the whole footnote text again, but rather `\footnote{Knuth, \emph{Op.~cit.}}'. The author name has been reduced to the last-name, and the rest of the information is replaced by `\emph{Op.~cit.}' Again, the period is appropriately handled: no period is added to the one at the end of this expression. But in the case of |\cite[p.~101]{taruskin}|, it is added: `\footnote{Taruskin, \emph{Op.~cit.}, p.~101.}'.
%
%A similar feature is that of `\emph{Idem}.' If a reference is cited twice or more times consecutively, the second footnote (and after) will contain only `\emph{Idem},' followed by the optional argument, if any (and by a period if necessary). Thus, a further citation of Taruskin's book here, through |\cite{taruskin}|, renders `\footnote{\emph{Idem.}}'.
%
%\DescribeMacro{\opcittext}\DescribeMacro{\idemtext}
%The user can change the expressions `\emph{Op.~Cit.}' and `\emph{Idem}' by |\renewcommand|'ing the |\opcittext| and |\idemtext| commands, respectively.
%
%\DescribeMacro{\cite*}
%A starred version of |\cite| is provided, by which the author's name is omitted from the reference. So we can say that Gellner expanded one of the ideas presented from his mentioned book in a later study.|\cite*{gellner2}|\footnote{\emph{Nations and Nationalism} (Ithaca: Cornell University Press, 1983).}
%
%\subsection{The `herafter' mechanism}\label{hereafter}
%
%\DescribeMacro{hereafter = ""}When two or more works by the same author are |\cite|'d, the \emph{Op.~Cit.}\ mechanism is not reliable (there are many `\emph{oOpera~citat\ae}'). The user should then provide, in the \texttt{bib} file and for all the works of that author, a value for the new entry \texttt{hereafter}. Then, |opcit| will use the value of this entry in the place of \emph{Op.~Cit.} 
%
%For example, if Gellner's mentioned books had \texttt{hereafter} entries of |"T{\&}C"| and |"N{\&}N"|, respectively, the commands |\cite{gellner}| and |\cite{gellner2}| will produce `\footnote{Gellner: \emph{T\&C}.}' and `\footnote{Gellner: \emph{N\&N}.}' (of course, from the second time these works are cited on). Note that the strings were emphasized. Still, the starred version |\cite*| hides the author's name, and the `\emph{Idem}' mechanism will apply if any of the works is |\cite|'d for the second time in a row.
%
%In case no \texttt{hereafter} entry is found, a warning will be issued, and the deliberately unacceptable expression \emph{?Op.?Cit.?} substituted.
%
%\DescribeMacro{\hereafter}
%The |\hereafter| command typesets the \texttt{hereafter} string of the last work |\cite|'d, so that we can say something like 
%
%\begin{verbatim}
%\footnote{See \cite{gellner}; hereafter I will refer to this text as 
%\hereafter.}
%\end{verbatim}
%
%\subsection{The final references list}
%
%The command |\bibliography| has the usual effect of producing a final section (or chapter) for `References.' According to the \textsc{Bib}\TeX\ style used, the format of the entries is different in the references list from the footnotes. 
%
%Frequently, a document with bibliographical references in footnote style does not include a final references list. However, it is the |\bibliography| command that tells \textsc{Bib}\TeX\ what database file to look at, so |opcit| needs it to be present. If the final list is not wanted, the user should include this command (and the list) at least once, so that the file \texttt{\jobname.bbl} is created, and then comment it out. In this way, |opcit| will have a file to read, but no reference list will be actually typeset.
%
%\subsection{Modifying the bibliography style}\label{bsts}
%
%This distribution of |opcit| includes a \textsc{Bib}\TeX\ style file, |opcit.bst|, designed to fulfill the package's conventions. This style is far from being (and from pretending to be) complete. It supports only four generic entry-types: \\
%|@ARTICLE|\\
%|@BOOK|\\
%|@INCOLLECTION|\\
%|@MISC|
%
%These entries take the usual fields of the |plain.bst| style, just adding one more, namely |hereafter| (see section~\ref{hereafter}). Cross-reference, moreover, has been turned off.\footnote{In part, because a footnote-oriented style does not naturally lend itself to cross reference, for there are no `labels' to refer to.}
%
%This style has been, in general, sufficient for my own needs (I have made |@INBOOK| entries as |@INCOLLECTION|). But I regard it mainly as a model for new, more specific (but also less versatile) bibliography styles that use the features of the package. This section states clearly what is needed from such a style.
%
%If a style is created to work with |opcit|, the user has to indicate it as an option to the package, with the usual \TeX\ conventions for file names, and with no extension, for example |\usepackage[c:/texmf/bibtex/bst/modopcit]{opcit}|. If no style is specified, |opcit.bst| will be used. 
%
%Many details of formatting differ between a footnote-style and a list-style reference. The most visible one is that in footnotes commas are used when periods are preferred in a list. Also, while in the list address and publisher form a block independent from year, in the footnotes the three things are grouped by parentheses. And so on. 
%
%Because of all this, a way has to be available for |opcit| the package to communicate with the \textsc{Bib}\TeX-sylte. To properly find out and assign the information of each |\bibitem|, |opcit| has to know what exactly is the author's name, what the last-name (for second and later citations of the same work, in which the first name is omitted), etc.
%
%The convention chosen is that the \textsc{Bib}\TeX-style writes out every |\bibitem| in the form
%
%|\bibitem{|\meta{label}|}|
%
%|\biblastnames{|\meta{last name(s)}|}|\meta{\dots additional declarations\dots}
%
%|\opcitstart |\meta{Name(s)}|\bibpunctuation \newblock|
%
%\meta{remaining info}|\opcitends|
%
%\smallskip
%As long as this scheme is strictly followed, |opcit| will run.\footnote{This can be easily achieved in the style by suitably modifying the |bibstart| and |fin.entry| functions.} Other conventions are needed but not required, for example that instead of periods or commas, the style appends |\bibpunctuation| commands (this command is converted into commas in the footnotes, into periods in the references list). Similarly, |\bibIn| will decide if the particle `in' for \texttt{@INCOLLECTION} and similar entries is capitalized or not, and |\bibparenthesis| does or does not parenthesize its argument according to the situation.
%
%\DescribeMacro{\sameauthors}
% If the style substitutes a line for the author(s)' name(s), |opcit| needs a way to know the `real' author. This is achieved by the style not typesetting the line by itslef, but rather appending a |\sameauthors| command, which is defined by |opcit| as a 23pt-rule for the references list. 
%
%Also, |opcit| requires the style to provide the author's last name as the argument to the command |\biblastnames|. Another command of this kind is |\hereafter|, which gives as its argument the abbreviation that the user chose in the |hereafter| field. This kind of commands is what is represented by \meta{\dots additional declarations\dots}.
%
%\DescribeMacro{\newBibCommand} The `communication commands' mentioned are those that I have already implemented in |opcit.bst|. Others can be created with the macro
%
%|\newBibCommand{|\meta{command}|}{|\meta{footnote-style}|{|\meta{list-style}|}|
%
%This macro is used in |opcit.sty| to define |\bibpunctuation|, |\bibIn| and |\bibparenthesis|. As a complementary example, let's suppose the style will support videocassettes. The particle `videocassette' is to be appended at the end of the item. In a footnote, it comes after a comma (the current meaning of |\bibpunctuation|), but in the references list it comes after a period. The command
%
%|\newBibCommand{\videocassette}{(videocassette)}{Videocassette.}|
%
%\noindent will manage this properly. If a new communication command needs arguments, the |[|$n$|]| part has to be inside the first argument of |\newBibCommand| (see the definition of |\bibparenthesis| below, code line~21).
%
%When to issue the |\newBibCommand|'s? A good place to do it is the style itself, when it appends the |\begin{thebibliography}| command (usually the |begin.bib| function). Since |\newBibCommand| does not typeset anything, it causes no problem either in the preamble nor at the start of the list.
%
%\section{Implementation}
%
%    \begin{macrocode}
%<*package>
\NeedsTeXFormat{LaTeX2e}[1995/12/01]
\ProvidesPackage{opcit}[2002/12/25 Footnote references (Federico Garcia)]
\RequirePackage{xspace}
\newcommand{\opcit@bst}{opcit}
\DeclareOption*{\PackageInfo{opcit}{%
    `\CurrentOption' used as bibliography style}%
    \let\opcit@bst\CurrentOption}
\ProcessOptions
%    \end{macrocode}
%
%\subsection{Basic idea}
%
%The basic idea behind the working of |opcit| is that the \texttt{bbl} file produced by \textsc{Bib}\TeX\ is read at the beginning of the document. Each reference item starts in this file with the |\bibitem| command (used in the |thebibliography| environment to crete the different items). But when reading the file at the beginning, |\bibitem| is redefined so that, instead of appending an item to a list, it defines the control sequences that will produce the footnotes. 
%
%Thus, for each work |\cite|'d there will be a set of newly defined control sequences, identified by the label by which the user refers to it in |\cite| commands. For example, there will be a set for the label \texttt{texbook} used above: the commands |\texbook|, |\texbook@star|, |\texbook@author|, and so on. These commands (of whose existence the user does not need to know) contain the actual text to be written in the footnotes.
%
%The |\cite| command itself is redefined here to execute the appropriate control sequence each time. In this way, |\cite{texbook}| means basically |\footnote{\texbook}|. But it also redefines |\texbook| so that the next time it is used it will expand to `Knuth, \emph{Op.~Cit.}'
%
%\subsection{The macros}
%Three conditionals are needed: one to check if there is a \texttt{bbl} file to read from; another to check if |\cite| occurs inside or outside the argument of |\footnote|; and one more to check whether the last character was a period. The rule for repeated authors is also set here to 23pt.
%    \begin{macrocode}
\newif\ifopcit@bbl\opcit@bblfalse
\newif\ifopcit@footnote\opcit@footnotefalse
\newif\ifperi@d\peri@dfalse
\newlength{\sameauthorsrule}\setlength{\sameauthorsrule}{23pt}
%    \end{macrocode}
%
%The following section sets up the `communication commands.' Note that the commands that add a punctuation mark do so only if the last character was not period, question, or exclamation marks (all of which have a |\sfcode| different from other characters). Within the |thebibliography| environment, however, the period is set to |\sfcode| of 1000 (as letters), so it is not good for the test. |\last@cited| is initialized to a value unlikely to occur.
%
%    \begin{macrocode}
\newtoks\opcit@redefs
\newcommand{\newBibCommand}[3]{%
    \newcommand#1{#2}%
    \opcit@redefs\expandafter{\the\opcit@redefs%
        \renewcommand#1{#3}}}
\newcommand{\opcitstart}{\relax} 
\newBibCommand{\opcitend}{\relax}{\ifnum\spacefactor=\sfcode`?\else.\fi}
\newBibCommand{\bibparenthesis[1]}{ (#1)}{. \newblock #1}
\newBibCommand{\bibIn}{in}{In}
\newBibCommand{\bibpunctuation}{%
    \ifnum\spacefactor=\sfcode`.\else,\fi\xspace}{%
    \ifnum\spacefactor=\sfcode`?\else.\fi\xspace}
\newcommand{\sameauthors}{\rule{\sameauthorsrule}{.4pt}}
\newBibCommand{\biblastnames[1]}{%
    \global\@namedef{\@curr@bibitem @authors}{#1}}{\relax}
\newBibCommand{\bibhereafter[1]}{%
    \global\@namedef{\@curr@bibitem @hereafter}{#1}}{\relax} 
\newcommand{\last@cited}{)OpcitFirst(}
\newcommand{\opcittext}{Op.~Cit.}
\newcommand{\idemtext}{Idem}
%    \end{macrocode}
%After having set up the communication, the bibliography style is called, and the \texttt{bbl} file is read, if exists. This is done within a group, for |thebibliography| and |\bibitem| are redefined (the former as nothing). Recall that, by now, the communication commands have their `footnote meaning,' the first part of their definition (the second part has been stored in |\opcit@redefs|, to be redeemed later on).
%
%In |\bibitem|, |#1| is the label for the |\cite| command; |#2| is a series of declarations written out to the |bbl| file by the \textsc{Bib}\TeX\ style (one of them, required, is the command |\biblastnames|, whose argument contains only the last name(s) of the author(s); another is |\hereafter|, if any). |#3| is the full author(s)' name(s), that appears the first time the work is |\cite|'d. Finally, |#4| is the rest of the information for the entry.
%
%    \begin{macrocode}
\bibliographystyle{\opcit@bst}
\bgroup
    \renewenvironment{thebibliography}[1]{\relax}{\relax}
    \def\bibitem#1#2\opcitstart #3\bibpunctuation \newblock#4\opcitend{%
        \ifx#3\sameauthors\else\def\@lastauthors{#3}\fi
        \global\expandafter\edef\csname#1@author\endcsname{\@lastauthors}%
        \global\def\@curr@bibitem{#1}%
        \global\expandafter\def\csname#1\endcsname{\@nameuse{#1@author}, #4}%
        \global\@namedef{#1@star}{#4}%
        \bibhereafter{\opcittext}%
        #2}
    \InputIfFileExists{\jobname.bbl}{\global\opcit@bbltrue}%
        {\global\opcit@bblfalse\PackageWarningNoLine{opcit}{%
            No information found about bibliographical references.}}
\egroup
%    \end{macrocode}
%
% The effect of all this, if |\jobname.bbl| exists, is that for each entry \texttt{foo} the following commands are defined: |\foo@author| as \meta{author} (avoiding the rule for a repeated author); |\foo|, as `|\foo@author|, \meta{info}'; and |\foo@star| as `\meta{info}'. Also, |\bibhereafter| is applied, so the command |\foo@hereafter| is defined as |\opcittext| (=`Op.~Cit.'). If the user provided a value for the |hereafter| field, the \textsc{Bib}\TeX\ style will issue a |\bibhereafter| command as part of \meta{\dots additional declarations\dots}, which will override the one just applied when |#2| is executed.
%
%And now for the |\cite| and |\cite*| commands. They check if they are in a footnote (note that this requires |\interfootnotelinepenalty| to be different from |\interlinepenalty| in the main text); if not, they call a |\footnote|, and append a period at the end, if necessary.  After that, they execute one of the commands defined by |\bibitem| above. Then they call the redefinition routine |\renew@cites|, which will redefine those very commands to produce different things the next time the work is |\cite|'d. They are redefined only if there was a \texttt{bbl} from which those commands were initially defined.
%    \begin{macrocode}
\ifopcit@bbl
\renewcommand{\cite}{\@ifstar{\opcit@cite@star}{\opcit@cite}}%
\newcommand{\opcit@cite}[2][.]{\nocite{#2}%
    \ifnum\interlinepenalty=\interfootnotelinepenalty\opcit@footnotetrue%
        \else\opcit@footnotefalse\expandafter\footnote\fi%
    {\@nameuse{#2}\ifx#1.\check@for@period{\@nameuse{#2}}%
        \else\check@for@period{#1}%
        {, #1}\fi%
        \ifopcit@footnote\peri@dtrue\fi%
        \ifperi@d\else.\fi}%
    \renew@cites{#2}}
\newcommand{\opcit@cite@star}[2][.]{\nocite{#2}%
    \ifnum\interlinepenalty=\interfootnotelinepenalty\opcit@footnotetrue%
        \else\opcit@footnotefalse\expandafter\footnote\fi%
    {\@nameuse{#2star}\ifx#1.\check@for@period{\@nameuse{#2}}%
        \else\check@for@period{#1}%
        {, #1}\fi%
        \ifopcit@footnote\peri@dtrue\fi%
        \ifperi@d\else.\fi}%
    \renew@cites{#2}}
\fi
%    \end{macrocode}
%
% The redefinition routine is in charge of catching two identical |\cite|'s in a row, to produce \emph{Idem} (or the current value of |\idemtext|) in the second. Also, after the first time a work is |\cite|'d, it redefines its commands to produce only the author(s)' last name(s) followed by the \texttt{hereafter} (which is either \emph{Op.~Cit.} or the \texttt{hereafter} field in the |bib| file). After that, |\check@for@period| is defined.
%
%    \begin{macrocode}
\newcommand{\renew@cites}[1]{%
    \global\expandafter\edef\csname\last@cited\endcsname{%
        \@nameuse{\last@cited @authors},%
        ~{\noexpand\em\@nameuse{\last@cited @hereafter}}}%
    \global\expandafter\edef\csname\last@cited star\endcsname{%
        {\noexpand\em\@nameuse{\last@cited @hereafter}}}%
    \global\def\last@cited{#1}%
    \global\@namedef{#1}{{\em\idemtext}}%
    \global\@namedef{#1star}{{\em\@nameuse{#1@hereafter}}}%
    \global\def\hereafter{\@nameuse{#1@hereafter}}}
\def\check@for@period#1{{\normalsfcodes\setbox0\hbox{#1%
    \ifnum\spacefactor=\sfcode`.\global\peri@dtrue\else%
    \global\peri@dfalse\fi}}}
%    \end{macrocode}
%
%Finally, the redefinitions of the communication commands have to be executed before the references list is compiled. |thebibliography| environment is formatted to produce no labels. 
%
%    \begin{macrocode}
\let\opcit@bibliography\bibliography
\renewcommand{\bibliography}{\the\opcit@redefs\opcit@bibliography}
\newcommand{\thebib@renew}{}
\@ifclassloaded{article}{%
    \renewcommand{\thebib@renew}{\section*{\refname}\@mkboth{\refname}{\refname}}}{%
    \renewcommand{\thebib@renew}{\chapter*{\bibname}\@mkboth{\bibname}{\bibname}}}%
\renewenvironment{thebibliography}[1]
     {\thebib@renew%
      \the\opcit@redefs%
      \list{}%
           {\setlength\labelwidth{\z@}%
            \leftmargin\bibindent
            \itemindent -\bibindent
            \parsep \z@
            \@openbib@code
            \usecounter{enumiv}%
            \let\p@enumiv\@empty
            \renewcommand\theenumiv{\@arabic\c@enumiv}}%
      \sloppy
      \clubpenalty4000
      \@clubpenalty \clubpenalty
      \widowpenalty4000%
      \sfcode`\.\@m}
     {\def\@noitemerr
       {\@latex@warning{Empty `thebibliography' environment}}%
      \endlist}
%</package>
%    \end{macrocode}
%
%\subsection{The \texttt{opcit.bst} bibliography style}
%
%This style was prepared adapting the \texttt{plain.bst} file, crudely simplifying it, and adding new functions for communication commands.
%
%    \begin{macrocode}
%<*bst>
ENTRY
  { address
    author
    booktitle
    chapter
    edition
    editor
    howpublished
    institution
    journal
    key
    month
    note
    number
    organization
    pages
    publisher
    school
    series
    title
    type
    volume
    year
    hereafter
  }
  {}
  { label }

INTEGERS { output.state before.all mid.sentence after.sentence after.block quoted.state }

STRINGS { s t last.authors }

FUNCTION {init.state.consts}
{ #0 'before.all :=
  #1 'mid.sentence :=
  #2 'after.sentence :=
  #3 'after.block :=
  #0 'quoted.state :=
  "" 'last.authors :=
}
%    \end{macrocode}
%
% The string \texttt{last.authors} is used to check for works by the same author, to replace the name by the |\sameauthors| command. In the following section, defining basic functions, the communication commands are implemented.
%
%    \begin{macrocode}
FUNCTION {output.nonnull}
{ 's :=
  output.state mid.sentence =
    { " " * write$ }
    { output.state after.block =
    { "\bibpunctuation" * 
      quoted.state #1 =
        { #2 'quoted.state := }
        { quoted.state #2 = 
            { "''" * #0 'quoted.state := }
            'skip$
            if$
        }
        if$
      write$
      newline$
      "\newblock " write$
    }
    { output.state before.all =
        'write$
        { "\bibpunctuation" * write$ }
      if$
    }
      if$
      mid.sentence 'output.state :=
    }
  if$
  s
}

FUNCTION {output}
{ duplicate$ empty$
    'pop$
    'output.nonnull
  if$
}

FUNCTION {output.check}
{ 't :=
  duplicate$ empty$
    { pop$ "empty " t * " in " * cite$ * warning$ }
    'output.nonnull
  if$
}


FUNCTION {fin.entry}
{ "\opcitend%" * write$
  newline$
}

FUNCTION {new.block}
{ output.state before.all =
    'skip$
    { after.block 'output.state := }
  if$
}
%    \end{macrocode}
%
% Then some logical and general-purpose functions:
%
%    \begin{macrocode}
FUNCTION {not}
{   { #0 }
    { #1 }
  if$
}

FUNCTION {and}
{   'skip$
    { pop$ #0 }
  if$
}

FUNCTION {or}
{   { pop$ #1 }
    'skip$
  if$
}

FUNCTION {new.block.checka}
{ empty$
    'skip$
    'new.block
  if$
}

FUNCTION {new.block.checkb}
{ empty$
  swap$ empty$
  and
    'skip$
    'new.block
  if$
}

FUNCTION {field.or.null}
{ duplicate$ empty$
    { pop$ "" }
    'skip$
  if$
}

FUNCTION {emphasize}
{ duplicate$ empty$
    { pop$ "" }
    { "{\em " swap$ * "}" * }
  if$
}
%    \end{macrocode}
%
% The next formatting-functions are very similar (though not quite identical) to those in \texttt{plain.bst}:
%
%    \begin{macrocode}

INTEGERS { nameptr namesleft numnames }

FUNCTION {format.names}
{ 's :=
  #1 'nameptr :=
  s num.names$ 'numnames :=
  numnames 'namesleft :=
    { namesleft #0 > }
    { s nameptr "{ff~}{vv~}{ll}{, jj}" format.name$ 't :=
      nameptr #1 >
    { namesleft #1 >
        { ", " * t * }
        { numnames #2 >
        { "," * }
        'skip$
          if$
          t "others" =
        { " et~al." * }
        { " and " * t * }
          if$
        }
      if$
    }
    't
      if$
      nameptr #1 + 'nameptr :=
      namesleft #1 - 'namesleft :=
    }
  while$
}

FUNCTION {format.authors}
{ author empty$
    { "" 
      "" 'last.authors :=
    }
    { author last.authors =
        { "\sameauthors" }
        { author format.names }
      if$
      author 'last.authors :=
    }
  if$
}

FUNCTION {format.editors}
{ editor empty$
    { "" }
    { editor format.names }
  if$
}

FUNCTION {format.editors.ed}
{ editor empty$
    { "" }
    { editor format.names " (ed.)" * }
  if$
}

FUNCTION {format.title}
{ title empty$
    { "" }
    { title }
  if$
}

FUNCTION {n.dashify}
{ 't :=
  ""
    { t empty$ not }
    { t #1 #1 substring$ "-" =
    { t #1 #2 substring$ "--" = not
        { "--" *
          t #2 global.max$ substring$ 't :=
        }
        {   { t #1 #1 substring$ "-" = }
        { "-" *
          t #2 global.max$ substring$ 't :=
        }
          while$
        }
      if$
    }
    { t #1 #1 substring$ *
      t #2 global.max$ substring$ 't :=
    }
      if$
    }
  while$
}

FUNCTION {format.date}
{ year empty$
    { month empty$
    { "" }
    { "there's a month but no year in " cite$ * warning$
      month
    }
      if$
    }
    { month empty$
    'year
    { month " " * year * }
      if$
    }
  if$
}

FUNCTION {format.btitle}
{ title emphasize
}

FUNCTION {tie.or.space.connect}
{ duplicate$ text.length$ #3 <
    { "~" }
    { " " }
  if$
  swap$ * *
}

FUNCTION {either.or.check}
{ empty$
    'pop$
    { "can't use both " swap$ * " fields in " * cite$ * warning$ }
  if$
}

FUNCTION {format.bvolume}
{ volume empty$
    { "" }
    { "volume" volume tie.or.space.connect
      series empty$
    'skip$
    { " of " * series emphasize * }
      if$
      "volume and number" number either.or.check
    }
  if$
}

FUNCTION {format.number.series}
{ volume empty$
    { number empty$
    { series empty$
        { "" }
        { ", series " * series * "" }
        if$ }
    { output.state mid.sentence =
        { "number" }
        { "Number" }
      if$
      number tie.or.space.connect
      series empty$
        { "there's a number but no series in " cite$ * warning$ }
        { " in " * series * }
      if$
    }
      if$
    }
    { "" }
  if$
}

FUNCTION {format.edition}
{ edition empty$
    { "" }
    { output.state mid.sentence =
    { edition "l" change.case$ " edition" * }
    { edition "t" change.case$ " edition" * }
      if$
    }
  if$
}

INTEGERS { multiresult }

FUNCTION {multi.page.check}
{ 't :=
  #0 'multiresult :=
    { multiresult not
      t empty$ not
      and
    }
    { t #1 #1 substring$
      duplicate$ "-" =
      swap$ duplicate$ "," =
      swap$ "+" =
      or or
    { #1 'multiresult := }
    { t #2 global.max$ substring$ 't := }
      if$
    }
  while$
  multiresult
}

FUNCTION {format.pages}
{ pages empty$
    { "" }
    { pages multi.page.check
    { "pages" pages n.dashify tie.or.space.connect }
    { "page" pages tie.or.space.connect }
      if$
    }
  if$
}

FUNCTION {format.vol.num.date.pages}
{ volume empty$
    'skip$
    { volume }
    if$
    number empty$
    'skip$
    { "/" number * *
      volume empty$
    { "there's a number but no volume in " cite$ * warning$ }
    'skip$
      if$
    }
  if$
  " (" * format.date * ")" *
  pages empty$
    'skip$
    { duplicate$ empty$
    { pop$ format.pages }
    { ": " * pages n.dashify * }
      if$
    }
  if$
}

FUNCTION {format.chapter.pages}
{ chapter empty$
    'format.pages
    { type empty$
    { "chapter" }
    { type "l" change.case$ }
      if$
      chapter tie.or.space.connect
      pages empty$
    'skip$
    { ", " * format.pages * }
      if$
    }
  if$
}

FUNCTION {format.in.ed.booktitle}
{ booktitle empty$
    { "" }
    { "\bibIn \ " booktitle emphasize * 
    editor empty$
        'skip$
        { ", ed.~" * format.editors * }
      if$
    }
  if$
}

FUNCTION {empty.misc.check}
{ author empty$ title empty$ howpublished empty$
  month empty$ year empty$ note empty$
  and and and and and
  key empty$ not and
    { "all relevant fields are empty in " cite$ * warning$ }
    'skip$
  if$
}
%    \end{macrocode}
%
% The next three functions are new. \texttt{get.lastnames} is used to provide the argument for the |\biblastnames| command; \texttt{make.address.publisher.year} group those fields as the argument to |\bibparenthesis|; and \texttt{format.title.quoted} is used to wrap the quotes for |@ARTICLE| and |@INCOLLECTION| titles. The integer \texttt{quoted.state}, there modified, has an effect in the \texttt{output.nonnull} function above.
%
%    \begin{macrocode}
FUNCTION{get.lastnames}
{ 's :=
  #1 'nameptr :=
  s num.names$ 'numnames :=
  numnames 'namesleft :=
    { namesleft #0 > }
    { s nameptr "{vv~}{ll}" format.name$ 't :=
      nameptr #1 >
    { namesleft #1 >
        { ", " * t * }
        { numnames #2 >
        { "," * }
        'skip$
          if$
          t "others" =
        { " et~al." * }
        { " and " * t * }
          if$
        }
      if$
    }
    't
      if$
      nameptr #1 + 'nameptr :=
      namesleft #1 - 'namesleft :=
    }
  while$
}

FUNCTION {make.address.publisher.year}
{   "\unskip\bibparenthesis{" 
    address empty$
        'skip$
        { address * ": " * }
        if$
    publisher empty$
        'skip$
        { publisher * ", " * }
        if$
    format.date * "}" *
}

FUNCTION{format.title.quoted}
{  title empty$
        { "" }
        { "``" title * }
        if$
    #1 'quoted.state :=  
}
%    \end{macrocode}
%
% It is the |output.bibitem| function, which starts each |\bibitem|, that is in charge of fulfilling almost all the convention for this command (see section~\ref{bsts}), by inserting the key commands |\biblastname| and |\opcitstart| (|\opcitend| is added by |fin.entry|, above). The \texttt{hereafter} field is also handled here.
%
%    \begin{macrocode}
FUNCTION {output.bibitem}
{ newline$
  "\bibitem{" write$
  cite$ "}" * write$
  ""
  newline$
  "\biblastnames{" write$
  author empty$
    { editor get.lastnames }
    { author get.lastnames }
    if$
  "}" * write$ 
  hereafter empty$
    'skip$
    { "\bibhereafter{" write$ hereafter "}" * write$ }
    if$
  newline$
  "\opcitstart " write$
  before.all 'output.state :=
    #0 'quoted.state :=
}
%    \end{macrocode}
%
% Then the four entry functions. Note that they do not reveal by themselves the |opcit| conventions.
%
%    \begin{macrocode}
FUNCTION {article}
{ output.bibitem
  format.authors "author" output.check
  new.block
  format.title.quoted "title" output.check
  new.block
  journal emphasize "journal" output.check
  format.vol.num.date.pages "year" output.check
  new.block
  note output
  fin.entry
}

FUNCTION {book}
{ output.bibitem
  author empty$
    {   format.editors.ed "author and editor" output.check }
    {   format.authors output.nonnull
    "author and editor" editor either.or.check 
    }
  if$
  new.block
  format.btitle "title" output.check
  edition new.block.checka
  format.edition output
  format.bvolume output
  format.number.series output
  make.address.publisher.year output
  new.block
  note output
  fin.entry
}

FUNCTION {incollection}
{ output.bibitem
  format.authors "author" output.check
  new.block
  format.title.quoted "title" output.check
  new.block
  format.in.ed.booktitle "booktitle" output.check
  format.bvolume output
  format.number.series output
  make.address.publisher.year output
  format.chapter.pages output
  new.block
  note output
  fin.entry
}

FUNCTION {misc}
{ output.bibitem
  format.authors "author" output.check
  new.block
  format.title output
  howpublished new.block.checka
  howpublished output
  format.date output
  new.block
  note output
  fin.entry
  empty.misc.check
}
%    \end{macrocode}
%
%The next has been copied almost verbatim (I am not even sure if all these functions are actually used by the style\dots)
%
%    \begin{macrocode}

FUNCTION {default.type} { misc }

MACRO {jan} {"January"}

MACRO {feb} {"February"}

MACRO {mar} {"March"}

MACRO {apr} {"April"}

MACRO {may} {"May"}

MACRO {jun} {"June"}

MACRO {jul} {"July"}

MACRO {aug} {"August"}

MACRO {sep} {"September"}

MACRO {oct} {"October"}

MACRO {nov} {"November"}

MACRO {dec} {"December"}

MACRO {acmcs} {"ACM Computing Surveys"}

MACRO {acta} {"Acta Informatica"}

MACRO {cacm} {"Communications of the ACM"}

MACRO {ibmjrd} {"IBM Journal of Research and Development"}

MACRO {ibmsj} {"IBM Systems Journal"}

MACRO {ieeese} {"IEEE Transactions on Software Engineering"}

MACRO {ieeetc} {"IEEE Transactions on Computers"}

MACRO {ieeetcad}
 {"IEEE Transactions on Computer-Aided Design of Integrated Circuits"}

MACRO {ipl} {"Information Processing Letters"}

MACRO {jacm} {"Journal of the ACM"}

MACRO {jcss} {"Journal of Computer and System Sciences"}

MACRO {scp} {"Science of Computer Programming"}

MACRO {sicomp} {"SIAM Journal on Computing"}

MACRO {tocs} {"ACM Transactions on Computer Systems"}

MACRO {tods} {"ACM Transactions on Database Systems"}

MACRO {tog} {"ACM Transactions on Graphics"}

MACRO {toms} {"ACM Transactions on Mathematical Software"}

MACRO {toois} {"ACM Transactions on Office Information Systems"}

MACRO {toplas} {"ACM Transactions on Programming Languages and Systems"}

MACRO {tcs} {"Theoretical Computer Science"}

READ

FUNCTION {sortify}
{ purify$
  "l" change.case$
}

INTEGERS { len }

FUNCTION {chop.word}
{ 's :=
  'len :=
  s #1 len substring$ =
    { s len #1 + global.max$ substring$ }
    's
  if$
}

FUNCTION {sort.format.names}
{ 's :=
  #1 'nameptr :=
  ""
  s num.names$ 'numnames :=
  numnames 'namesleft :=
    { namesleft #0 > }
    { nameptr #1 >
    { "   " * }
    'skip$
      if$
      s nameptr "{vv{ } }{ll{ }}{  ff{ }}{  jj{ }}" format.name$ 't :=
      nameptr numnames = t "others" = and
    { "et al" * }
    { t sortify * }
      if$
      nameptr #1 + 'nameptr :=
      namesleft #1 - 'namesleft :=
    }
  while$
}

FUNCTION {sort.format.title}
{ 't :=
  "A " #2
    "An " #3
      "The " #4 t chop.word
    chop.word
  chop.word
  sortify
  #1 global.max$ substring$
}

FUNCTION {author.sort}
{ author empty$
    { key empty$
    { "to sort, need author or key in " cite$ * warning$
      ""
    }
    { key sortify }
      if$
    }
    { author sort.format.names }
  if$
}

FUNCTION {author.editor.sort}
{ author empty$
    { editor empty$
    { key empty$
        { "to sort, need author, editor, or key in " cite$ * warning$
          ""
        }
        { key sortify }
      if$
    }
    { editor sort.format.names }
      if$
    }
    { author sort.format.names }
  if$
}

FUNCTION {author.organization.sort}
{ author empty$
    { organization empty$
    { key empty$
        { "to sort, need author, organization, or key in " cite$ * warning$
          ""
        }
        { key sortify }
      if$
    }
    { "The " #4 organization chop.word sortify }
      if$
    }
    { author sort.format.names }
  if$
}

FUNCTION {editor.organization.sort}
{ editor empty$
    { organization empty$
    { key empty$
        { "to sort, need editor, organization, or key in " cite$ * warning$
          ""
        }
        { key sortify }
      if$
    }
    { "The " #4 organization chop.word sortify }
      if$
    }
    { editor sort.format.names }
  if$
}

FUNCTION {presort}
{ type$ "book" =
  type$ "inbook" =
  or
    'author.editor.sort
    { type$ "proceedings" =
    'editor.organization.sort
    { type$ "manual" =
        'author.organization.sort
        'author.sort
      if$
    }
      if$
    }
  if$
  "    "
  *
  year field.or.null sortify
  *
  "    "
  *
  title field.or.null
  sort.format.title
  *
  #1 entry.max$ substring$
  'sort.key$ :=
}
%    \end{macrocode}
%
%By contrast, |begin.bib| has been heavily lengthened, by adding all the formatting commands. This would be the best place for inserting any |\newBibCommand|'s.
%
%    \begin{macrocode}
FUNCTION {begin.bib}
{ preamble$ empty$
    'skip$
    { preamble$ write$ newline$ }
  if$
  "\begin{thebibliography}{}"   write$ newline$
}
%    \end{macrocode}
%
% Finally, the `executive functions:'
%
%    \begin{macrocode}
ITERATE {presort}

SORT

EXECUTE {begin.bib}

EXECUTE {init.state.consts}

ITERATE {call.type$}

FUNCTION {end.bib}
{ newline$
  "\end{thebibliography}" write$ newline$
}

EXECUTE {end.bib}
%</bst>
%    \end{macrocode}
