#!/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 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::VASP;
use Crystal::VESTA;
use Crystal::XCrySDen;

#===============================================
# デバッグ関係変数
#===============================================
#$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=[MergePositionsInCIFs]", '');
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 $ret = &CopyPOSCARFlags();

#Utils::EndHTML();

exit $ret;

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

#==========================================
# &Subroutines
#==========================================
sub CopyPOSCARFlags
{
	$App->print("\n\n<b>Copy POSCAR flags from template:</b>\n");

	my $VASP = new VASP;

	my $CARDir         = $Args->GetGetArg(0);
#	my $TemplateCARDir = $Args->GetGetArg(1);
	my $TemplatePOSCARPath = $Args->GetGetArg(1);
	my $OutputPOSCAR   = $Args->GetGetArg(2);

	if(!$CARDir) {
		$App->print("CAR dir should be specified.\n");
		$App->print("   Usage: CopyPOSCARFlags.pl CARDir TemplateCARDir OutputPOSCAR\n");
		return 0;
	}

	my $POSCARPath         = $VASP->GetPOSCARFileName($CARDir);
#	my $TemplatePOSCARPath = $VASP->GetPOSCARFileName($TemplateCARDir);

$App->print("CAR dir             : [$CARDir]\n");
$App->print("Input POSCAR path   : [$POSCARPath]\n");
#$App->print("Template CAR dir    : [$TemplateCARDir]\n");
$App->print("Template POSCAR path: [$TemplatePOSCARPath]\n");
$App->print("Output POSCAR path  : [$OutputPOSCAR]\n");

	if(!$TemplatePOSCARPath) {
		$App->print("TemplateCARDir path should be specified.\n");
		$App->print("   Usage: CopyPOSCARFlags.pl CARDir TemplateCARDir OutputPOSCAR\n");
		return 0;
	}

	if(!$OutputPOSCAR) {
		$App->print("OutputPOSCAR path should be specified.\n");
		$App->print("   Usage: CopyPOSCARFlags.pl CARDir TemplateCARDir OutputPOSCAR\n");
		return 0;
	}

	$App->print("  Read from [$POSCARPath].\n");
	my $in    = new JFile();
	my @lines = $in->ReadFileToLines($POSCARPath);
	$in->Close();

	$App->print("  Read flags from [$TemplatePOSCARPath].\n");
	my $inT    = new JFile();
	my @linesT = $inT->ReadFileToLines($TemplatePOSCARPath);
	$inT->Close();

	my $out = new JFile($OutputPOSCAR, "w");
	if(!$out) {
		print "Error: Can not write to [$OutputPOSCAR].\n";
		return undef;
	}

#SeonO-MgO                               
#   4.21700000000000     
#     1.0000000000000000    0.0000000000000000    0.0000000000000000
#     0.0000000000452967    1.0000000000000000    0.0000000000000000
#     0.0000000003623737    0.0000000003623737    8.0000000000000000
#   Mg   O    Se
#     8     8     1
	my $i = 0;
	for( ; $i < 6 ; $i++) {
		$out->print($lines[$i]);
	}
	$out->print($lines[$i++]) if($lines[5] !~ /^[\s\d]+$/);

#Selective dynamics
#Direct
	$out->print($lines[$i++]);
	$out->print($lines[$i++]);


	for( ; ; $i++) {
		last if(!defined $lines[$i]);
		last if(!defined $linesT[$i]);
#print "check $i: $lines[$i]";
#print "      $i: $linesT[$i]";

		my ($x,  $y,  $z)                    = Utils::Split("\\s+", $lines[$i]);
		my ($xT, $yT, $zT, $idx, $idy, $idz) = Utils::Split("\\s+", $linesT[$i]);
#      0.500000000    0.500000000    0.000000000 T T T
		printf     ("$i: %14.9f %14.9f %14.9f %s %s %s\n", $x, $y, $z, $idx, $idy, $idz);
		$out->printf("   %14.9f %14.9f %14.9f %s %s %s\n", $x, $y, $z, $idx, $idy, $idz);
	}

	$out->Close();

	$App->print("\nCopy POSCAR flags from template: Finished\n");

	return 1;
}

1;
