#!/usr/bin/perl

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

use strict;
#use warnings;

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

use Deps;
use Utils;
use JFile;

use MyApplication;
use Sci::Algorism;
use Sci::GeneralFileFormat;

use Crystal::CIF;
use Crystal::Crystal;
use Crystal::SpaceGroup;
use Crystal::AtomType;
use Crystal::CASTEP;

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

my $HOME = $ENV{'HOME'};
my $CASTEPDir = Deps::MakePath($HOME, 'bin', 1);
$CASTEPDir = Deps::MakePath($CASTEPDir, 'Perl', 1);
$CASTEPDir = Deps::MakePath($CASTEPDir, 'CASTEP', 1);

#===============================================
# 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();

#==========================================
# コマンドラインオプション読み込み
#==========================================
$App->AddArgument("--Action",
		"--Action=[CopyInputFiles]",       '');
$App->AddArgument("--Prefix",        "--Prefix=PrefixName",       "");
$App->AddArgument("--SourceDir",     "--SourceDir=DirName",       "");
$App->AddArgument("--TargetDir",     "--TargetDir=DirName",       "");
$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 =~ /CopyInputFiles/i) {
	&CopyInputFiles();
}
else {
	$App->print("Error: Invald Action: $Action\n");
}

#Utils::EndHTML();

exit $ret;

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

#==========================================
# &Subroutines
#==========================================
sub CopyInputFiles
{
	$App->print("\n\n<b>Copy CASTEP Input Files:</b>\n");

	my $Prefix    = $Args->GetGetArg("Prefix");
	my $SourceDir = $Args->GetGetArg("SourceDir");
	my $TargetDir = $Args->GetGetArg("TargetDir");
	my $CellFile = Deps::MakePath($TargetDir, "$Prefix.cell", 0);
	my $PotentialDir = Deps::MakePath($CASTEPDir, "Potentials", 1);
	$App->print("  CASTEP Dir   : $CASTEPDir\n");
	$App->print("  Potential Dir: $PotentialDir\n");
	$App->print("  Prefix   : $Prefix\n");
	$App->print("  SourceDir: $SourceDir\n");
	$App->print("  TargetDir: $TargetDir\n");
	$App->print("  CellFile : $CellFile\n");

	my $fname = Deps::MakePath($SourceDir, "*", 0);
	my @files = glob("\"$fname\"");
	foreach my $f (@files) {
		next if(-d $f);
		my ($drive, $dir, $filename, $ext, $lastdir, $filebody)
			= Deps::SplitFilePath($f);

		my $newpath = Deps::MakePath($TargetDir, $filename);
#		$App->print("  cp \"$f\" \"$newpath\"\n");
		system("cp \"$f\" \"$newpath\"");
		unless(-f $newpath) {
			$App->print("    Error: $newpath was not created.\n");
		}
	}

	$App->print("  Read [$CellFile].\n");
	my $in = new JFile($CellFile, "r");
	unless($in) {
		$App->print("  Error: Can not read [$CellFile].\n");
		$App->print("  CASTEP.pl terminated.\n\n");
		return;
	}
	$in->SkipTo("%BLOCK SPECIES_POT");
	while(!$in->eof()) {
		my $line = $in->ReadLine();
		last if($line =~ /^%ENDBLOCK/);
		last if($in->eof());
		my ($PSFile) = ($line =~ /(\S+)\s*$/);
		my $SourceFile = Deps::MakePath($PotentialDir, $PSFile, 0);
		my $TargetFile = Deps::MakePath($TargetDir, $PSFile, 0);
		$App->print("   cp $SourceFile $TargetFile\n");
		system("cp $SourceFile $TargetFile");
		unless(-f $TargetFile) {
			$App->print("    Error: $TargetFile was not created.\n");
		}
	}
	$in->Close();
	
	$App->print("\n\n<b>Copy CASTEP Input Files: Finished</b>\n\n");
}

