#!/usr/bin/perl
##!d:/Perl/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 CGI::Carp qw(fatalsToBrowser);
use Cwd;

use Deps;
use Utils;
use Crystal::AtomType;

BEGIN {
#	$| = 1;
	open (STDERR, ">&STDOUT");
}

#===============================================
# ϐ
#===============================================
my $ScriptCharCode = 'utf8';
my $FileSystemCharCode = 'sjis';

my $CSVFile = "TotalEnergy-AB-LDA.csv";
my $OutFile = "TotalEnergy-AB-LDA-graph.csv";


my $csv = new CSV;
$csv->Read($CSVFile, 0) or die "$!: Can not read [$CSVFile].\n";

my $pLabelArray = $csv->LabelArray();
my $pDataArray  = $csv->DataArray();
my $nData = $csv->nData();
print "nData: $nData\n";

#for(my $il = 0 ; $il < @$pLabelArray ; $il++) {
#	print "," if($il > 0);
#	print "$pLabelArray->[$il]";
#}
#print "\n";

my %d;
for(my $i = 0 ; $i < $nData ; $i++) {
	my $pHash = $csv->HashByIndex($i);
	my ($a, $s) = ($pHash->{Source} =~ /^([A-Za-z]+)\-([A-Za-z]+)/);
	$d{$a}{Atom} = $a;
	$d{$a}{$s}{Etot} = $pHash->{Etot} / $pHash->{Z};
	$d{$a}{$s}{Density} = $pHash->{Density};

	print "i=$i: $pHash->{Source}: $a: $s: E=$d{$a}{$s}{Etot}: d=$d{$a}{$s}{Density}\n";
}

open(OUT, ">$OutFile") or die "$!: Can not write to [$OutFile].\n";
print OUT "Compound,StableStructure,NaCl,CsCl,ZB,WZ,NiAs,d(NaCl),d(CsCl),d(ZB),d(WZ),d(NiAs)\n";
foreach my $a (sort keys %d) {
	my $p = $d{$a};
	next if(!defined $p);

	$p->{NaCl}{Etot} = 1.0e10 if($p->{NaCl}{Etot} == 0.0);
	$p->{CsCl}{Etot} = 1.0e10 if($p->{CsCl}{Etot} == 0.0);
	$p->{ZB}{Etot}   = 1.0e10 if($p->{ZB}{Etot} == 0.0);
	$p->{WZ}{Etot}   = 1.0e10 if($p->{WZ}{Etot} == 0.0);
	$p->{NiAs}{Etot} = 1.0e10 if($p->{NiAs}{Etot} == 0.0);

	my ($mins, $minE) = ('', 1.0e100);
	($mins, $minE) = ("NaCl", $p->{NaCl}{Etot}) if($minE > $p->{NaCl}{Etot});
	($mins, $minE) = ("CsCl", $p->{CsCl}{Etot}) if($minE > $p->{CsCl}{Etot});
	($mins, $minE) = ("ZB",   $p->{ZB}{Etot})   if($minE > $p->{ZB}{Etot});
	($mins, $minE) = ("WZ",   $p->{WZ}{Etot})   if($minE > $p->{WZ}{Etot});
	($mins, $minE) = ("NiAs", $p->{NiAs}{Etot}) if($minE > $p->{NiAs}{Etot});

	print "$a: $mins\n";
	print OUT "$a,$mins,", 
				$p->{NaCl}{Etot}-$minE, ",", $p->{CsCl}{Etot}-$minE, ",", $p->{ZB}{Etot}-$minE, ",", 
				$p->{WZ}{Etot}-$minE,  ",", $p->{NiAs}{Etot}-$minE, ",",
				$p->{NaCl}{Density}, ",", $p->{CsCl}{Density}, ",", $p->{ZB}{Density}, ",", 
				$p->{WZ}{Density},  ",", $p->{NiAs}{Density},
				"\n";
}
close(OUT);

exit;
