#!/usr/bin/perl

BEGIN {
use lib 'd:/Programs/Perl/lib';
use lib '/home/tkamiya/bin/lib';
my $BaseDir = $ENV{'TkPerlDir'};
#print "\nBaseDir: $BaseDir\n";
@INC = ("$BaseDir/lib", "$BaseDir/VNL", "d:/Programs/Perl/lib", @INC);
}

use strict;
#use warnings;

use MyApplication;
use Sci::ChemicalReaction;

my $PrintDetail = 0;
#my $Reaction    = ($ARGV[0] eq '')? "2Cu+F2" : $ARGV[0];
my $Reaction    = ($ARGV[0] eq '')? "2CaF2+2CaS+Cu2S" : $ARGV[0];
#my $Reaction    = ($ARGV[0] eq '')? "CaF2+2CaS+2Cu2S" : $ARGV[0];
my $TotalWeight = 20;

my $BaseDBDir = "Databases";
my @DBFiles   = ("AeCuFCh-High.csv");#, "AeCuFCh.csv", "LaMnOPn.csv", "BaFe2As2.csv", "SrFe2As2.csv", "LaCuOSe.csv", 
#			"LaZnOP-all.csv",
#			"aIGZO-Dens608.csv", "ZnO.csv",
#			"aIGZO-Dens608-all.csv", "AOS-PBE96-all.csv", "C12A7-all.csv",
#			"LaMnOPn-all.csv", "LaTMOPn-AFM-Collinear-new2-all.csv",
#			"LaTMOPn-AFM-Collinear-new-all.csv", "LaTMOPn-AFM-Collinear-all.csv",
#			"Root-all.csv",
#			);
#my @DBFiles   = ("AeFe2As2-High.csv", "AeCuFCh-High.csv", "AeCuFCh.csv");

#=============================================
# Create ChemicalReaction object
#=============================================
my $R = new ChemicalReaction(\@DBFiles, $BaseDBDir); #"Compound" , "Composition");
if(!$R) {
	print "Error: $!: Can not create ChemicalReaction Object.\n";
	exit;
}
if(!$R->GetCSVDB()) {
	print "Error: $!: Can not read a DB.\n";
	exit;
}

#=============================================
# Analyze reaction
#=============================================
print "Reaction: $Reaction\n";
$R->Analyze($Reaction, 0);
my $pReagentHash      = $R->ReagentsHash();
my $pReagentCompounds = $R->pCompounds('Reagents');
my $pReagentElements  = $R->pElements("Reagents");

#=============================================
# Batch calculation
#=============================================
my $TotalMolWeight = 0.0;
my @MolWeight;
for(my $i = 0 ; $i < @$pReagentCompounds ; $i++) {
	my $c = $pReagentCompounds->[$i];

	my $nCompound = $R->nCompound('Reagents', $c);
	$MolWeight[$i] = $R->MolecularWeight($c);
	$TotalMolWeight += $nCompound * $MolWeight[$i];
}
print "Total molecular weight: $TotalMolWeight\n";
my @BatchWeight;
for(my $i = 0 ; $i < @$pReagentCompounds ; $i++) {
	my $c = $pReagentCompounds->[$i];
	my $nCompound = $R->nCompound('Reagents', $c);
	$BatchWeight[$i] = $TotalWeight / $TotalMolWeight * $nCompound * $MolWeight[$i];
	print "  $c: $nCompound (M=$MolWeight[$i]): $BatchWeight[$i] g\n"; 
}

exit;
