#!/usr/bin/perl

use strict;

use lib 'd:/Programs/Perl/lib';
use JFile;

my $direction = 'z';
my $InFile  = (defined $ARGV[0])? $ARGV[0] : "LOCPOT.vasp";
my $CSVFile = Deps::ReplaceExtension($InFile, "csv");
if($ARGV[1]) {
	if($ARGV[1] eq 'x') {
		$direction = 'x';
	}
	elsif($ARGV[1] eq 'y') {
		$direction = 'y';
	}
	elsif($ARGV[1] eq 'z') {
		$direction = 'z';
	}
	else {
		$CSVFile = $ARGV[1];
	}
}
if($ARGV[2]) {
	$CSVFile = $ARGV[2];
}

my $out = new JFile;
$out->Open($CSVFile, "w") or die "$!: Can not write to [$CSVFile]\n";
$out->print("z(A),pot(eV)\n");

my $in = new JFile;
$in->Open($InFile, "r") or die "$!: Can not read [$InFile].\n";
my $title = $in->ReadLine();
my $a = $in->ReadLine() + 0.0;
my $line = $in->ReadLine();
my ($a11, $a12, $a13) = Utils::Split("\\s+", $line);
$line = $in->ReadLine();
my ($a21, $a22, $a23) = Utils::Split("\\s+", $line);
$line = $in->ReadLine();
my ($a31, $a32, $a33) = Utils::Split("\\s+", $line);

$line = $in->ReadLine();
if($line =~ /[\s\d]/) {
	$line = $in->ReadLine();
}
my @nAtoms = Utils::Split("\\s+", $line);
$line = $in->ReadLine();

for(my $i = 0 ; $i < @nAtoms ; $i++) {
	for(my $j = 0 ; $j < $nAtoms[$i] ; $j++) {
		$line = $in->ReadLine();
		last if(!$line);
	}
}
while(1) {
	$line = $in->ReadLine();
	last if(!$line);
	Utils::DelSpace($line);
	next if($line eq '');
	
	last;
}

my ($nx, $ny, $nz) = Utils::Split("\\s+", $line);
my $nTotal   = $nx * $ny * $nz;
my $nxyTotal = $nx * $ny;
print "n=($nx, $ny, $nz)=$nTotal\n";

my @pot;
for(my $iz = 0 ; $iz < $nz ; $iz++) {
	$pot[$iz] = 0.0;
}

my $c = 0;
for(my $iz = 0 ; $iz < $nz ; $iz++) {
	for(my $iy = 0 ; $iy < $ny ; $iy++) {
		for(my $ix = 0 ; $ix < $nx ; $ix++) {
			my $d = &ReadOne($in);
			if(!defined $d) {
				print "Short data!!\n";
				last;
			}
#print "$ix,$iy,$iz ($c): $d\n";

			if($direction eq 'x') {
				$pot[$ix] += $d;
			}
			if($direction eq 'y') {
				$pot[$iy] += $d;
			}
			else {
				$pot[$iz] += $d;
			}
			$c++;
		}
	}
}
print "last c=$c ($nTotal)\n";
for(my $iz = 0 ; $iz < $nz ; $iz++) {
	$pot[$iz] = $pot[$iz] / $nxyTotal;
	$out->print("$iz,$pot[$iz]\n");
}
$out->Close();

$in->Close();
exit;

my @d;
my $count = 0;
sub ReadOne
{
	my ($in) = @_;

	if($count >= @d) {
#print "read\n";
		$count = 0;
		my $line = $in->ReadLine();
		return undef if(!defined $line);

		@d = Utils::Split("\\s+", $line);
	}

	my $val = $d[$count];
	$count++;
	return $val;
}
