
%%% comma.sty 
%%%
%%% David Carlisle carlisle@ma.man.ac.uk
%%%
\ProvidesPackage{comma}
      [1996/09/05 v1.0 Insert commas every three digits (DPC)]

%% This package provides a means of producing numbers with a separator
%% (by default a comma) every three digits.
%%
%% Given a LaTeX counter (eg section)
%%
%% \renewcommand\thesection{\commaform{section}}
%%
%% If section is 12345, \thesection will now print as 12,345
%% 
%% If you want something other than a comma, for instance a thin
%% space, or a full word space, redefine \commaformtoken, for instance
%% \renewcommand\commaformtoken{\,}
%% \renewcommand\commaformtoken{ }
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% #1 is the name of a LaTeX counter.
\def\commaform#1{%
  \expandafter\@commaform\csname c@#1\endcsname}

%     The token to place every three digits.
\def\commaformtoken{,}

% Internal version.
% #1 is the number. It may be a TeX count register, eg \count@
%    or an explicit number such as `1234 ' but in this latter case it
%    *must* end with an explicit space token.
\def\@commaform#1{%
  \expandafter\@commaaux
    \expandafter{\expandafter}%
    \number#1%
    \@empty\@empty\@empty}

% Wander down to the end of the number and then see where the first
%    \@empty turns up.
% #1 List of digits already seen (initially {} )
% #2#3#4 next three digits (or \@empty) in list.
\def\@commaaux#1#2#3#4{%
  \ifx\@empty#2%
    \addcomma#1\relax
  \else
    \ifx\@empty#3%
      \addcomma\@empty\@empty#1#2\relax
    \else
      \ifx\@empty#4%
        \addcomma\@empty#1#2#3\relax
      \else
         \@commaauxafterfi{#1#2#3#4}%
      \fi
    \fi
  \fi}


% Get out of the nested \if before recursing down the list of digits.
% #1 list of digits seen so far.
\def\@commaauxafterfi#1\fi\fi\fi{%
  \fi\fi\fi\@commaaux{#1}}

% Go down adding a `comma' every three tokens. (The list will have
%    been padded with 0 1 or 2  \@empty at the start so there is
%    definitely a multiple of three tokens before the \relax.
% #1#2#3 are next three digits
% #4 is next digit, or \relax to stop
\def\addcomma#1#2#3#4{%
  #1#2#3%
  \if#4\relax
  \else
    \commaformtoken
    \expandafter\addcomma\expandafter#4%
  \fi}
 
