#!/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 Deps;
use Utils;
use JFile;

use MyApplication;
use Sci qw($pi);

use Crystal::CIF;
use Crystal::Crystal;
use Crystal::Madel;

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

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

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;

my $KMP = 14.39965; # e/Angstrong in eV

#==========================================
# コマンドラインオプション読み込み
#==========================================
$App->AddArgument("--Action",    "--Action=[MakeInput|AddSummaryCSV]", '');
$App->AddArgument("--IonRadius", "--IonRadius=val [Def: 1.0, smaller than inter-ionic d]", 1.0);
$App->AddArgument("--Grange",    "--Grange=val    [Def: 4.0, typically 2.0 - 4.0]", 3.0);
$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 %ArgHash = $Args->GetArgHash();
foreach my $key (keys %ArgHash) {
#print "key: $key: $ArgHash{$key}\n";
	if($key =~ /^Param:(.*?)$/i) {
		$ParamHash{$1} = $ArgHash{$key};
#print "$1:  $ArgHash{$key}\n";
	}
}
$App->{pParamHash} = \%ParamHash;

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

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

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

my $ret = 0;
if($Action =~ /MakeInput/i) {
	&MakeInput();
}
elsif($Action =~ /AddSummaryCSV/i) {
	&AddSummaryCSV();
}
else {
	$App->print("Error: Invalid Action: [$Action]\n");
	print "Usage:\n";
	print "  perl Madel.pl --Action=MakeInput CIF_File\n";
	print "  perl Madel.pl --Action=AddSummaryCSV Summary_File\n";
}

print "\n";
print "Note:\n";
print "  The unit of the Madelung potentials is e/Angstrom\n";
print "  Multiply 1 e/Angstrom = 14.39965 eV to convert to eV\n";

#Utils::EndHTML();

exit $ret;

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

#==========================================
# &Subroutines
#==========================================
sub AddSummaryCSV
{
	my $OutputFile = $Args->GetGetArg(0);
	my $CSVFile    = $Args->GetGetArg(1);
	$App->print("<H2>Add summary of [$OutputFile] to [$CSVFile].</H2>\n");
	
	my $in  = JFile->new($OutputFile, 'r') or die "$!: Can not read [$OutputFile].\n";
	my $out = JFile->new($CSVFile, 'a')    or die "$!: Can not write to [$CSVFile].\n";

	$in->SkipTo("\\*\\*\\*\\*\\*");
	$in->SkipTo("\\*\\*\\*\\*\\*");
	$in->ReadLine();
	my $title    = Utils::DelSpace($in->ReadLine());
	my $line     = $in->ReadLine();
	my ($IR)     = ($line =~ /sphere:\s*(\S+)/);
	$line        = $in->ReadLine();
	my ($Grange) = ($line =~ /range:\s*(\S+)/);
	$out->print("Title: $title\n");
	$out->print("  Ion radius: $IR A\n");
	$out->print("  G range   : $Grange A^-1\n");
	$in->SkipTo("Potentials");
	$in->ReadLine();
	$line = $in->ReadLine();
	my @a = ('Atom', 'MP(eV)', Utils::Split("\\s+", $line));
	$out->print(join(',', @a), "\n");;
	while(1) {
		$line = $in->ReadLine();
		last if(!$line);
		
		my @a = Utils::Split("\\s+", $line);
		last if(@a < 4);
		
		for(my $i = 1 ; $i < @a ; $i++) {
			$a[$i] += 0.0 if($a[$i] =~ /^[\s\.+\-\deEdD]+$/);
		}
		my $MP = $KMP * $a[6];
		$out->print(join(',', ($a[0], $MP, $a[1], $a[2], $a[3], $a[4], $a[5], $a[6])), "\n");;
	}
	$out->print("\n");
	$out->Close();
	$in->Close();

	$App->print("<H2>Add summary: finished</H2>\n");
}

sub MakeInput
{
	$App->print("<H2>Make MADEL input file.</H2>\n");

	my $CIFFile = $Args->GetGetArg(0);
	my @filenames = fileparse($CIFFile, "\.[^\.]+");
	my $fname     = $filenames[0];
	my $IonRadius = $Args->GetGetArg('IonRadius');
	$IonRadius    = 1.0 if($IonRadius eq '');
	my $Grange    = $Args->GetGetArg('Grange');
	$Grange       = 4.0 if($Grange eq '');

	$App->print("<b>CIFFile  :</b> $CIFFile\n");
	$App->print("<b>IonRadius:</b> $IonRadius\n");
	$App->print("<b>Grange   :</b> $Grange\n");

	my $CIF = new CIF();
	unless($CIF->Read($CIFFile)) {
		$App->print("  Error: Can not read [$CIFFile].\n\n");
		return -1;
	}
	my $Crystal = $CIF->GetCCrystal();
	$Crystal->ExpandCoordinates();

	my $Madel = new Madel();
	$Madel->SetSampleName($fname);
	if($Madel->MakeInputFile($Crystal, $fname, $IonRadius, $Grange) <= 0) {
		$App->print("Error in Madel.pl::MakeInputFile: Can not write files.\n");
		return 0;
	}

	$App->print("<H2>Make MADEL input file: finished</H2>\n");

	return 1;
}
