% This is a small, but not minimal, .bst program, intended to include all of the
% elements of the .bst language, and expected to produce the same output
% from beastie and BibTeX.
%
% This file is part of Beastie <https://purl.org/nxg/dist/beastie>
% SPDX-FileCopyrightText: 2023 Norman Gray <https://nxg.me.uk>
% SPDX-License-Identifier: BSD-2-Clause


ENTRY
  { author booktitle title journal publisher year month }
  {}
  { label }

STRINGS { s t }

INTEGERS { nameptr namesleft numnames global.var }

function {initialise.dummy}
{ #1 'nameptr :=
  #1 'global.var := }

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 {output.bibitem}
{ newline$
  "\bibitem{" write$
  cite$ write$
  "}" write$ newline$
  "" % leave an empty starter string on the stack
}

%FUNCTION {output.nonnull} {}

FUNCTION {format.title}
{ title empty$ % comment1
    { "<absent>" % comment2
    }
    { title "t" change.case$ }
  if$
}

FUNCTION {format.authors}
{ author empty$
    { "<absent>" }
    { author format.names }
  if$
}

FUNCTION {format.date}
{ month empty$
    { "" }
    { month " " * }
  if$
  year empty$
    { "9999" }
    { year }
  if$
  *
}

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

function {article}
{ output.bibitem
  %"key: " sort.key$ * write$ newline$
  "Article: authors=" * format.authors *
  ", title=" * format.title *
  ", date=" *  format.date *
  add.period$
  write$ newline$
}

function {default.type}
{ output.bibitem
  "Type: " * type$ empty$ { "UNDEFINED" } { type$ } if$ *
  " -- authors=" * format.authors *
  "; title=" * format.title *
  booktitle missing$
    'skip$
    { "; booktitle=" * booktitle * }
  if$
  "; date=" *  format.date *
  "; global.var=" * global.var int.to.str$ *
  add.period$
  write$ newline$
}

MACRO {jan} {"Januarius"}
MACRO {feb} { "February" }

READ

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

% function {presort}
% { year field.or.null sortify
%   "  " *
%   author field.or.null sortify *
%   "  " * cite$ *
%   'sort.key$ :=
% }
% the following is simpler
function {presort}
{
  cite$ 'sort.key$ :=
}

execute{initialise.dummy}

ITERATE{presort}
reverse{presort}                %redundant, but means we exercise all functions

SORT

ITERATE{call.type$}
