#!/usr/bin/perl 

# Molar Mass Calculator
# (c) 2010-2011, Denis G. Samsonenko <d.g.samsonenko@gmail.com>
# LGPL

# console version

use 5.008009;
use strict;
use MMCalc 20240208;

# restrict warnigs
local $SIG{__WARN__} = sub { };

# main function
sub execute
# input:  formula string
# output: text formatted
{
  my $calc = shift;
  my $str = shift;

  # $atoms[$i][0] = atom symbol, [1] = quantity,
  # [2] = concentration, [3] = concentration error
  my @atoms = ();

  # molar mass
  my $mass = 0;

  # mass error
  my $error = 0;

  # calculate molar mass, contents, concentrations and absolute errors
  if ($calc->calculate($str))
  {
    $mass = $calc->get_mass();
    $error = $calc->get_error();
    @atoms = @{$calc->get_atoms()};

    # return empty string if no molar mass
    return "" unless ($mass);

    my $plist = "\n";
    my $contlist = "Formula: " . $calc->get_formula();

    # concentrations
    if ($#atoms > 0)
    {
      # more than one atom
      for (my $i = 0; $i <= $#atoms; ++$i)
      {
        next unless ($atoms[$i][1]);
        $plist .= sprintf("%2s   %7.2f\t ",  $atoms[$i][0], $atoms[$i][1]) . $atoms[$i][2];
        $plist .= " +- " . $atoms[$i][3] if ($error);
        $plist .= " %\n";
      }
    }
    else
    {
      # one atom
      $plist .= sprintf("%2s   %7.2f\t ",  $atoms[0][0], $atoms[0][1]) . "100 %\n";
    }

    # output
    $str = "Molar mass: " . $mass;
    $str .= " +- " . $error if ($error);
    $str .= " g/mol\n\n" . $contlist . "\n" . $plist;
  }

  # return 'syntax error' if formula was incorrect
  else
  {
    $str = "Syntax error!\n";
  }
  return $str;
}

my $calc = MMCalc->new();

if (defined($calc))
{
  foreach my $str (@ARGV)
  {
    # remove leading and finishing spaces
    $str =~ s/^\s+//;
    $str =~ s/\s+$//;
    next unless ($str);

    print "--------------------------------------\n";
    print "\"$str\"\n";
    print "--------------------------------------\n";

    # calculete mass, concentrations and errors;
    # prepare string to print
    $str = execute($calc, $str);

    # print mass, concentrations and errors;
    print "$str\n" if ($str);
  }
}
else
{
  die "ERROR: Initialization failed! $@";
}

0;
