#!/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 CSV;
use Sci::Science;

#===============================================
# デバッグ関係変数
#===============================================
#$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();

#==========================================
# コマンドラインオプション読み込み
#==========================================
$App->AddArgument("--Action",
		"--Action=[Convolute]",       '');
$App->AddArgument("--Width", "--Width=val [Def: 0.1]", '');
$App->AddArgument("--IgnoreZeroValue", "--IgnoreZeroValue=[0|1] [Def: 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 =~ /Convolute/i) {
	&Convolute();
}
else {
	$App->print("Error: Invald Action: $Action\n");
}

#Utils::EndHTML();

exit $ret;

#===============================================
# スクリプト終了
#===============================================

#==========================================
# &Subroutines
#==========================================
sub Convolute
{
	$App->print("\n\n<b>Convolute CSV File:</b>\n");
	my $pi = Sci::pi;

	my $Width = $Args->GetGetArg("Width");
	$Width = 0.1 if(!defined $Width);
	my $IgnoreZeroValue = $Args->GetGetArg("IgnoreZeroValue");
	$IgnoreZeroValue = 1 if(!defined $IgnoreZeroValue);
	my $InputFile = $Args->GetGetArg(0);
	my $OutputFile = $Args->GetGetArg(1);
	my ($drive, $directory, $filename, $ext, $lastdir, $filebody)
			= Deps::SplitFilePath($OutputFile);
	if(!$OutputFile) {
		$OutputFile = Deps::MakePath("$drive$directory", 
				"$filename-Convoluted.$ext", 0);
	}

	$App->print("  Read $InputFile\n");
	$App->print("  Save to $OutputFile\n");
	$App->print("  Width: $Width\n");
	$App->print("  IgnoreZeroValue: $IgnoreZeroValue\n");

	my $csv = new CSV;
	if($csv->Read($InputFile)) {
		$App->print("  Read [$InputFile]\n");
	}
	else {
		$App->print("  Error!!: Can not read [$InputFile]\n");
		return -1;
	}
	my $pLabelArray = $csv->LabelArray();
print "la: $pLabelArray\n";
	my $pDataArray  = $csv->DataArray();
	my $nDataRow = @$pDataArray;
	my $pX       = $pDataArray->[0];
	my $nData = @$pX;
	$App->print("  nDataRow: $nDataRow\n");
	$App->print("  nData   : $nData\n");
	my $x0 = $pX->[0];
	my $x1 = $pX->[@$pX - 1];
	my $dx = $pX->[1] - $pX->[0];
	my $di = int(($Width * 5.0) / $dx + 1.1);
	$App->print("  x: $x0 - $x1     dx: $dx\n");
	$App->print("  di: $di\n");
	
	my $coeff = 1/sqrt($pi)/($Width/$dx);

	for(my $i = 1 ; $i < $nDataRow ; $i++) {
		my $pY = $pDataArray->[$i];
		my @y;
		for(my $j = 0 ; $j < $nData ; $j++) {
			my $x0 = $pX->[$j];
			my $y0 = $pY->[$j];
			for(my $k = -$di ; $k <= $di ; $k++) {
				next if($j+$k < 0 or $j+$k >= $nData);
				next if($IgnoreZeroValue and $pY->[$j+$k] == 0.0);

				my $dvx = $dx*$k;
				$y[$j+$k] += $coeff * $y0 * exp(-$dvx*$dvx/$Width/$Width);
			}
		}
		$pDataArray->[$i] = \@y;
	}

	if($csv->Save($OutputFile)) {
		$App->print("  Save to [$OutputFile]\n");
	}
	else {
		$App->print("  Error!!: Can not write to [$OutputFile]\n");
		return -2;
	}

	$App->print("\n\n<b>Convolute CSV File: Finished</b>\n");
}
