#!/usr/bin/perl

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

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

use strict;
#use warnings;

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

use Deps;
use Utils;
use JFile;

use MyApplication;
use Sci::Science;
use Crystal::VESTA;
use Crystal::CIF;
use Crystal::Crystal;

#===============================================
# デバッグ関係変数
#===============================================
#$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->SetOutputMode("auto");

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

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

#==========================================
# コマンドラインオプション読み込み
#==========================================
$App->AddArgument("--Action",
		"--Action=[MakeVESTAFromCIF]",       '');
$App->AddArgument("--BondLength",     "--BondLength=val [def: 3.0A]", '3.0A');
$App->AddArgument("--Boundary",       "--Boundary=val [def: 0:1.0]",  '0:1.0');
$App->AddArgument("--BeyondBoundary", "--BeyondBoundary=[0|1] [def: 1]", 1);
$App->AddArgument("--DebugMode"     , "--DebugMode: Set DebugMode", '');
exit 1 if($App->ReadArgs(0) != 1);
my $Args = $App->Args();
#my $form = new CGI;
#$Args->SetCGIForm($form);
#$Args->parseInput($WebCharCode);

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

#Utils::InitHTML("Research", $WebCharSet, "_self");

my $Debug = $Args->GetGetArg("DebugMode");
$App->SetDebug($Debug);
my $Action = $Args->GetGetArg("Action");

my $ret = 0;
if($Action =~ /MakeVESTAFromCIF/i) {
	&MakeVESTAFromCIF();
}
else {
	$App->print("Error: Invald Action: $Action\n");
}

#Utils::EndHTML();

exit $ret;

#===============================================
# スクリプト終了
#===============================================

#==========================================
# &Subroutines
#==========================================
sub MakeVESTAFromCIF
{
	$App->print("\n\n<b>Make VESTA File From CIF:</b>\n");

	my $CIFFile     = $Args->GetGetArg(0);
	my $VESTAFile   = $Args->GetGetArg(1);
	$VESTAFile = Deps::ReplaceExtension($VESTAFile, ".vesta");
	my $DensityFile = $Args->GetGetArg(2);
	$App->print("Input  CIF  : $CIFFile\n");
	$App->print("Output VESTA: $VESTAFile\n");
	$App->print("Density file: $DensityFile\n") if($DensityFile);
	my $BondLength = $Args->GetGetArg("BondLength");
	$App->print("BondLength  : $BondLength\n");
	my $Boundary = $Args->GetGetArg("Boundary");
	$App->print("Boundary  : $Boundary\n");
	my $BeyondBoundary = $Args->GetGetArg("BeyondBoundary");
	$App->print("BeyondBoundary  : $BeyondBoundary\n");

	$App->print("\n");
	$App->print("Read CIF from [$CIFFile].\n");
	my $cif = new CIF;
	$cif->Read($CIFFile);
	my $Crystal = $cif->GetCCrystal();

	my $a0 = Sci::a0() * 1e10;
	my $Volume = $Crystal->Volume() / $a0 / $a0 / $a0;
	$App->print("Volume  : $Volume\n");
	$Volume = 1 if($Volume <= 0);
	my ($DensityMin, $DensityMax);
	my $DensityIsoLevel;
	my $TotalDensity = 0.0;
	if($DensityFile) {
		my $in = new JFile;
		if(!$in->Open($DensityFile, "r")) {
			print "Can not read [$DensityFile].\n";
			exit;
		}
		my ($min, $max) = (1.0e100, -1.0e100);
		while(1) {
			my $line = $in->ReadLine();
			Utils::DelSpace($line);
			last if($line eq '');
		}
		my $line = $in->ReadLine();
		while(1) {
			my $line = $in->ReadLine();
			last if($in->eof());
			for(my $i = 0 ; $i < 10 ; $i++) {
				my $idx = $i * 12;
				my $v = substr($line, $idx, 12) + 0.0;
				$TotalDensity += $v;
				$min = $v if($min > $v);
				$max = $v if($max < $v);
			}
		}
		$in->Close();
		if($DensityFile !~ /(LOCCAR|ELFCAR)/i) {
			$min /= $Volume;
			$max /= $Volume;
		}
		($DensityMin, $DensityMax) = ($min, $max);
		$max = abs($min) if(abs($min) > $max);
		$DensityIsoLevel = $max * 0.1;
		$TotalDensity /= $Volume;
#print "min,max=$min,$max,$DensityIsoLevel,$TotalDensity\n";
	}

	my $VESTA = new VESTA;
	$App->print("VESTA Atom Inf File: ", $VESTA->VESTAAtomInfFile(), "\n");
	my $ret = $VESTA->WriteVESTAFileFromCrystal(
				$Crystal, $DensityFile, $VESTAFile, 
				$BondLength, $Boundary, $BeyondBoundary,
				$DensityMin, $DensityMax, $DensityIsoLevel
				);
	if($ret == -1) {
		$App->print("Can not read [", $VESTA->VESTAAtomInfFile(), "].\n");
		return;
	}
	elsif($ret == 0) {
		$App->print("Can not write to [$VESTAFile].\n");
		return;
	}

	$App->print("\n\n<b>Make VESTA File From CIF: Finished</b>\n");
}
