#!/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 File::Path;
use File::Basename;
use File::Find;

use Math::Matrix;
use Math::MatrixReal;

use Deps;
use Utils;
use JFile;
use Crystal::VASP;

my $InputPath  = (defined $ARGV[0])? $ARGV[0] : "OUTCAR";
$InputPath = "$InputPath/OUTCAR" if(-d $InputPath);
my $OutputPath = (defined $ARGV[1])? $ARGV[1] : "Convergence.csv";
$OutputPath = "$OutputPath/Convergence.csv" if(-d $OutputPath);

my $in  = new JFile($InputPath, "r")  or die "$!: Can not read [$InputPath].\n";
my $out = new JFile($OutputPath, "w") or die "$!: Can not write to [$OutputPath].\n";

my $line = $in->SkipTo("EDIFF\\s*=");
my ($EDIFF) = ($line =~ /\=\s*([+-\.\deEdD]+)/);
print "EDIFF=$EDIFF\n";

my $line = $in->SkipTo("EDIFFG\\s*=");
my ($EDIFFG) = ($line =~ /\=\s*([+-\.\deEdD]+)/);
print "EDIFFG=$EDIFFG\n";

my $line = $in->SkipTo("NSW\\s*=");
my ($NSW) = ($line =~ /\=\s*(\d+)/);
print "NSW=$NSW\n";

$out->print("Cycle,iSCF,Ecycle(eV),Escf(eV),dEcycle(eV),dEscf(eV)\n");
my $PrevIter = -1;
my (@iIter, @iSCF, @E);
my $c = 0;
while(1) {
	$line = $in->SkipTo("---\\s+Iteration ");
	last if(!defined $line);

	my ($iIter, $iSCF) = ($line =~ /(\d+)\s*\(\s*(\d+)\)/);
	next if(!defined $iSCF);

	$line = $in->SkipTo("TOTEN\\s*=");
	next if(!defined $line);
	my ($TOTE) = ($line =~ /=\s*([+-eEdD\d\.]+)/);

	$iIter[$c] = $iIter;
	$iSCF[$c]  = $iSCF;
	$E[$c]     = $TOTE;

#	print "$iIter, $iSCF: $TOTE eV\n";

	$PrevIter = $iIter;
	$c++;
}

my $nCycle = $c;
my $PrevEcycle = '';
my $PrevEscf = '';
for(my $i = 0 ; $i < $nCycle ; $i++) {
	my $Escf = '';
	if((!defined $iIter[$i+1]) or $iSCF[$i+1] == 1) {
		$Escf = $E[$i];
	}

	my $dEcycle = ($iSCF[$i] > 1)?  -($E[$i] - $E[$i-1])  : '';
	my $dEscf   = ($iIter[$i] > 1)? -($E[$i] - $PrevEscf) : '';

	if($Escf eq '') {
		print "$i: $iIter[$i], $iSCF[$i]: $E[$i] eV\n";
		$out->print("$iIter[$i],$iSCF[$i],$E[$i],,$dEcycle\n");
	}
	else {
		print "$i: $iIter[$i], $iSCF[$i]: $E[$i] eV   $Escf eV\n";
		$out->print("$iIter[$i],$iSCF[$i],$E[$i],$Escf,$dEcycle,$dEscf\n");
	}
	
	if($Escf ne '') {
		$PrevEscf = $Escf;
	}
}
$out->Close();
$in->Close();
