#!/usr/bin/perl -w

######################################################################
##  This program is copyright (c) 2002 Bruce Ravel
##  <ravel@phys.washington.edu>
##  http://feff.phys.washington.edu/~ravel/
##
## -------------------------------------------------------------------
##     All rights reserved. This program is free software; you can
##     redistribute it and/or modify it under the same terms as Perl
##     itself.
##
##     This program is distributed in the hope that it will be useful,
##     but WITHOUT ANY WARRANTY; without even the implied warranty of
##     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##     Artistic License for more details.
## -------------------------------------------------------------------
######################################################################
## Code:

## Very simple interface to Chemistry::Formula

use Chemistry::Formula qw(parse_formula);
use strict;

(@ARGV) or &usage;
($ARGV[0] =~ /-{1,2}h(elp)?/i) and &usage;

my (%count, $string);
$string = $ARGV[0];
my $ok = parse_formula($string, \%count);

($ok) or do {
  print "Input error:\n\t$count{error}";
  die "\n";
};

print <<EOH;

Input string: "$string"

  element     number
 ---------   --------
EOH

foreach my $k (sort (keys(%count))) {
  if ($count{$k} > 0.001) {
    printf("    %-2s        %.3f\n", $k, $count{$k});
  } else {
    printf("    %-2s        %g\n", $k, $count{$k});
  };
};

sub usage {
  print <<EOH;
 Enumerate chemical formulas

     formula <string>

  <string> can be any reasonable chemical formula as expressed in
  ASCII, in latex, or by INSPEC.  Thus parens and square brackets can
  be used for groupings.  All element symbols must be capitalized
  (i.e. first letter capital and second letter lower case).

EOH
  exit;
};
