%        File: cpdnbr.sty
%      Author: H.A.Trujillo
%     Created: Sat Jul 18 08:00 PM 2015 E
% Last Change:     26 Aug 2015
%
%
%     Generates compound numbers that may be recalled by a
%     \ref{label}-type command.
%
%
%    Usage:
%     
%       When a compound is first used, the command
%	      \cpd {label} [suffix]	
%       creates a compound number for it, with an optional suffix, and prints
%       the result.
%   
%       To use the number later, recall it with its label and any optional
%       suffix:
%	      \cref {label} [suffix]
%   
%       eg:
%		  \cpd{fred}  ...  \cpd{debbie}[a]  ...  \cpd{mary}[-13C]
%		  \cref{debbie} ... \cref{debbie}[a,b]
%	 will produce
%		  1 ... 2a ... 3-13C
%		  2 ... 2a,b
%   
%    Formatting:
%       
%       By default, the compound numbers print in bold arabic numerals of
%       the default font, but this may be changed by redefining \cnfmt .
%   
%       Starred versions of the commands (\cpd* and \cref*) will print in
%       an alternative format, for possible use in equations or figures
%       (eg, through the psfrag package).  The starred format defaults to
%       bold palatino, but may be changed by redefining \altcnfmt, eg:
%       	\renewcommand{\altcnfmt}{\textsf}	.


\ProvidesPackage{cpdnbr}[2015/08/22 v2.0 Auto-numbering of chemical compounds]
\RequirePackage{xspace}


\newcounter{cpd@nbr}


% Formatting hooks
\newcommand{\cnfmt}{\textbf}
\newcommand{\altcnfmt}{\fontfamily{ppl}\selectfont\textbf}


% User-level commands
\newcommand{\cpd} {%
  \refstepcounter{cpd@nbr}%
  \@ifstar 
    {\let\@cnfmt=\altcnfmt \@cpd}
    {\let\@cnfmt=\cnfmt \@cpd}}

\newcommand{\cref} {%
  \@ifstar
    {\let\@cnfmt=\altcnfmt \@cnref}
    {\let\@cnfmt=\cnfmt \@cnref}}


% Internal commands.  
\newcommand{\@cpd}	[1] {\@ifnextchar[{\@cpd@{#1}} {\@cpd@{#1}[]}}
\newcommand{\@cnref}	[1] {\@ifnextchar[{\@cnref@{#1}} {\@cnref@{#1}[]}}


\def\@cpd@#1[#2]{%
  \bgroup
    \@cnfmt{\thecpd@nbr\relax#2\xspace}%
    \label{#1}%
  \egroup}

\def\@cnref@#1[#2]{%
  \bgroup
    \@cnfmt{\ref{#1}#2}\xspace%
  \egroup}


% Abort if label is defined more than once
%	nb/ this error only appears on even-numbered passes
\AtEndDocument{%
  \ifx\@multiplelabels\relax \else 
    \PackageError{cpdnbr}{Multiply-defined labels -- see log file}
  \fi}


% v1.0	18jul15	 starting somewhere. :)
% v1.1	19jul15	 tidied
% v1.2	19jul15	 error message if multiply-defined labels
% v1.3	21jul15	 internal commands consolidated
% v2.0	22aug15  more intuitive command names and order of arguments

%							  vim: sw=2

