#!/usr/bin/perl

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

use strict;
#use warnings;
use Utils;
use JFile;

use MyApplication;
use Crystal::CIF;
use Crystal::Crystal;
use Crystal::SpaceGroup;
use Crystal::AtomType;
use Crystal::VASP;
use Crystal::VESTA;

#===============================================
# デバッグ関係変数
#===============================================
#$PrintLevelが大きいほど、情報が詳しくなる
my $PrintLevel = 0;

#===============================================
# 文字コード関係変数
#===============================================
# sjis, euc, jis, noconv
my $PrintCharCode      = Deps::PrintCharCode();
my $OSCharCode         = Deps::OSCharCode();
my $FileSystemCharCode = Deps::FileSystemCharCode();

my $LF        = Deps::LF();
my $DirSep    = Deps::DirSep();
my $RegDirSep = Deps::RegDirSep();

#===============================================
# Applicationオブジェクト作成
#===============================================
my $App = new MyApplication;
exit if($App->Initialize() < 0);

#$App->SetLF("<br>\n");
#$App->SetPrintCharCode("sjis");
#$App->SetDebug($Debug);
$App->SetDeleteHTMLFlag(1);

#===============================================
# スクリプト大域変数
#===============================================
my $InitialDirectory = Deps::GetWorkingDirectory();
my %ParamHash;

#==========================================
# コマンドラインオプション読み込み
#==========================================
$App->AddArgument("--Action",         "--Action=[ModifyFiles]", '');
$App->AddArgument("--kVector",        "--kVector=val", 1.0);
$App->AddArgument("--ArrowColor",     "--ArrowColor=[R:G:B]", '128:128:128');
$App->AddArgument("--ArrowRadius",    "--ArrowRadius=val", 0.2);
$App->AddArgument("--PenetrateAtoms", "--PenetrateAtoms=[0|1]", '');

$App->AddArgument("--DebugMode",  "--DebugMode: Set DebugMode", '');
exit 1 if($App->ReadArgs(1, "sjis", 0) != 1);

my $Args = $App->Args();
#my $form = new CGI;
#$Args->SetCGIForm($form);
#$Args->parseInput($WebCharCode);

	my $Action     = $Args->GetGetArg("Action");
	my $InCIF1     = $Args->GetGetArg(0);
	my $InCIF2     = $Args->GetGetArg(1);
	my $VESTAFile  = $Args->GetGetArg(2);
	my $VESTAFile2 = $Args->GetGetArg(3);

#==========================================
# メイン関数スタート
#==========================================

	$App->print("Make VESTA File with Displacement Vectors from VASP *CAR Files:\n");

	$App->print("CIF1      : $InCIF1\n");
	$App->print("CIF2      : $InCIF2\n");
	$App->print("VESTAFile : $VESTAFile\n");
	$App->print("VESTAFile2: $VESTAFile\n");

	my $kVector = $Args->GetGetArg('kVector');
	$kVector = 1.0 if(!defined $kVector);
	$App->print("kVector: $kVector\n");
	my $ArrowColor = $Args->GetGetArg('ArrowColor');
	$ArrowColor = "128:128:128" if(!defined $ArrowColor);
	$App->print("ArrowColor: $ArrowColor\n");
	my $ArrowRadius = $Args->GetGetArg('ArrowRadius');
	$ArrowRadius = 0.2 if(!defined $ArrowRadius);
	$App->print("ArrowRadius: $ArrowRadius\n");
	my $PenetrateAtoms = $Args->GetGetArg('PenetrateAtoms');
	$PenetrateAtoms = 1 if(!defined $PenetrateAtoms);
	$App->print("PenetrateAtoms: $PenetrateAtoms\n");

	my $VASP = new VASP;
	unless($VESTAFile) {
		$App->print("File names should be specified.\n");
		$App->print("   Usage: MakeDisplacementVESTAFileFromVASP.pl --kVector=val --ArrowColor=color --ArrowRadius=val --PenetrateAtoms=[0|1] CIF1 CIF2 VESTAFile\n");
		return 0;
	}

	my $CIF1 = new CIF();
	unless($CIF1->Read($InCIF1)) {
		$App->print("  Error: Can not read [$InCIF1].\n\n");
		return -1;
	}
	my $CIF2 = new CIF();
	unless($CIF2->Read($InCIF2)) {
		$App->print("  Error: Can not read [$InCIF2].\n\n");
		return -1;
	}

	$App->print("\n");
	$App->print("  Read from [$InCIF1] and [$InCIF2].\n");
	$App->print("  Save to [$VESTAFile].\n");

	my $Crystal1 = $CIF1->GetCCrystal();
	$Crystal1->ExpandCoordinates();

	my $Crystal2 = $CIF2->GetCCrystal();
	$Crystal2->ExpandCoordinates();


	my @AtomSiteList = $Crystal1->GetCExpandedAtomSiteList();
	for(my $i = 0 ; $i < @AtomSiteList ; $i++) {
		my $site1 = $Crystal1->GetCExpandedAtomSite($i);
		next if(!$site1);
		my $site2 = $Crystal2->GetCExpandedAtomSite($i);
		next if(!$site2);

		my $atomname1 = $site1->Label(); #AtomName();
		my $atomname  = $site1->AtomNameOnly();
		my $atomname2 = $site2->Label(); #AtomName();
#print "$i: $atomname\n";
		if($atomname1 ne $atomname2) {
			$App->H2("Error: The names of atom #[$i] are not the same [$atomname1][$atomname2].\n");
			exit 1;
		}

		my ($x1, $y1, $z1) = $site1->Position();
		my ($x2, $y2, $z2) = $site2->Position();

		my ($vx, $vy, $vz) = ($x2 - $x1, $y2 - $y1, $z2 - $z1);
#$App->print("vec[$atomname1: $i]: ($vx, $vy, $vz)\n");
		$x1 -= 1.0 if(abs($vx) > abs($vx + 1.0));
		$x1 += 1.0 if(abs($vx) > abs($vx - 1.0));
		$y1 -= 1.0 if(abs($vy) > abs($vy + 1.0));
		$y1 += 1.0 if(abs($vy) > abs($vy - 1.0));
		if(abs($vz) > abs($vz + 1.0)) {
			$z1 -= 1.0;
		}
		if(abs($vz) > abs($vz - 1.0)) {
			$z1 += 1.0;
		}
		($vx, $vy, $vz) = ($x2 - $x1, $y2 - $y1, $z2 - $z1);
#$App->print("vec[$atomname1: $i]: ($vx, $vy, $vz)\n");

		$vx *= $kVector;
		$vy *= $kVector;
		$vz *= $kVector;

		$site1->SetVelocity($vx, $vy, $vz);
		$site2->SetVelocity($vx, $vy, $vz);
$App->print("vec[$atomname1: $i]: ($vx, $vy, $vz)\n");

		$atomname1 .= '{a}';
		$Crystal2->AddAtomSite($atomname1, $atomname, $x1, $y1, $z1, 0.5); #$fx, $fy, $fz)
	}
#exit;

	my $VESTA = new VESTA;
	$VESTA->WriteVESTAFileFromCrystal($Crystal1, undef, $VESTAFile,
					undef, 0, 0, undef, undef, undef,
					kVector        => $kVector,
					ArrowColor     => $ArrowColor,
					ArrowRadius    => $ArrowRadius,
					PenetrateAtoms => $PenetrateAtoms,
					);
	$VESTA->WriteVESTAFileFromCrystal($Crystal2, undef, $VESTAFile2,
					undef, 0, 0, undef, undef, undef,
					kVector        => $kVector,
					ArrowColor     => $ArrowColor,
					ArrowRadius    => $ArrowRadius,
					PenetrateAtoms => $PenetrateAtoms,
					);

	$App->print("\nMake VESTA File with Displacement Vectors from VASP *CAR Files: Finished\n");

