#!/usr/bin/perl

use strict;

use lib 'd:/Programs/Perl/lib';
use Deps;
use Utils;
use JFile;
use Crystal::VASP;

my $BaseFileName = ($ARGV[0])? $ARGV[0] : 'KPOINTS';

my $vasp = new VASP;

my $KPOINTS  = $vasp->GetKPOINTSFileName($BaseFileName);
#my $EIGENVAL = $vasp->GetEIGENVALFileName($BaseFileName);
#my $OutputEIGENVAL = Deps::ReplaceExtension($EIGENVAL, ".extract");
my $OutputEIGENVAL = $vasp->GetEIGENVALFileName($BaseFileName);
my $EIGENVAL       = Deps::ReplaceExtension($OutputEIGENVAL, ".original");
print "KPOINTS: $KPOINTS\n";
print "EIGENVAL: $EIGENVAL\n";
print "OutputEIGENVAL: $OutputEIGENVAL\n";

my $in = new JFile($KPOINTS, "r") or die "$!: Can not read [$KPOINTS]\n";
my $line = $in->ReadLine();
my $nKPoints = $in->ReadLine() + 0;
print "nKPoints: $nKPoints\n";

$line = $in->ReadLine();
my @Weights;
my $nkSave = 0;
for(my $i = 0 ; $i < $nKPoints ; $i++) {
	$line = $in->ReadLine();
	my ($kx, $ky, $kz, $weight) = Utils::Split("\\s+", $line);
	$Weights[$i] = $weight;
	if($weight > 0) {
		print "Skipped: $i: ($kx, $ky, $kz) w=$weight\n";
	}
	else {
		$nkSave++;
		print "Added: $i: ($kx, $ky, $kz) w=$weight\n";
	}
}
$in->Close();
print "nkSave: $nkSave\n";

my $in = new JFile($EIGENVAL, "r") or die "$!: Can not read [$EIGENVAL]\n";
my $out = new JFile($OutputEIGENVAL, "w") or die "$!: Can not write to [$OutputEIGENVAL]\n";
for(my $i = 0 ; $i < 5 ; $i++) {
	$line = $in->ReadLine();
	$out->print($line);
}
my ($na, $nk, $nlevels) = Utils::Split("\\s+", $in->ReadLine());
print "na, nk, nlevels: $na, $nk, $nlevels\n";
$out->printf("%5d %4d %4d\n", $na, $nkSave, $nlevels);

for(my $ik = 0 ; $ik < $nk ; $ik++) {
	my $blank  = $line = $in->ReadLine();
	my $header = $in->ReadLine();
	my @levels;
	for(my $il = 0 ; $il < $nlevels ; $il++) {
		$levels[$il] = $in->ReadLine();
	}
	if($Weights[$ik] == 0) {
		$out->print($blank);
		print($header);
		$out->print($header);
		for(my $il = 0 ; $il < $nlevels ; $il++) {
#			print($levels[$il]);
			$out->print($levels[$il]);
		}
	}
}

$out->Close();
$in->Close();
