#!bin/perl

do "parameters.pl";

# Open the file for reading.
open DATA1, "Uloop_dp.csv" or die "can't open file $!";
my @data1 = <DATA1>;
close (DATA1);

# Open the file for reading.
open DATA2, "Iplasma_dp.csv" or die "can't open file $!";
my @data2 = <DATA2>;
close (DATA2);

open DATA3, "PlasmaStartRow" or die "can't open file $!";
my $PlasmaStartRow = <DATA3>;
close (DATA3);

open DATA4, "PlasmaEndRow" or die "can't open file $!";
my $PlasmaEndRow = <DATA4>;
close (DATA4);

for ($i=0;$i<$LineCount;++$i)
{
	@row1=split(';',$data1[$i]);
	@row2=split(';',$data2[$i]);
	$Time[$i]=$row1[0];
	$ElectronTemperatureTime[$i]= $row1[1]==0 ? 0 : 89.8*(abs($row2[1]*0.001/($row1[1])))**(2/3);
}

#$maxElectronTemperature=0;
#$row=0;
#for ($i=$PlasmaStartRow;$i<$PlasmaEndRow;++$i)
#{
#	$row= $maxElectronTemperature < $ElectronTemperatureTime[$i] ? $i : $row;
#	$maxElectronTemperature= $maxElectronTemperature < $ElectronTemperatureTime[$i] ? $ElectronTemperatureTime[$i] : $maxElectronTemperature;
#}
#@row1=split(';',$data1[$row]);
#$time=$row1[0];

#$Sum=0;
#for ($i=$row-10;$i<=$row+10;++$i)
#{
#	$Sum=$Sum + $ElectronTemperatureTime[$i];
#	$maxElectronTemperature=$Sum/21;
#}

open CIL1, ">ElectronTemperatureTime.txt";
for ($i=0;$i<$LineCount;$i++)
{
	print CIL1 "$Time[$i]	$ElectronTemperatureTime[$i]\n";
}
close (CIL1);

#open CIL2, ">maxElectronTemperature";
#print CIL2 "$time	$maxElectronTemperature	$row";
#close (CIL2);

# medianovy filtr
$median_samples=7;

$hmedian= int($median_samples/2);
for ($i=0; $i<=$LineCount-$median_samples; $i++)
{
  for ($j=0; $j<=$median_samples; $j++)
  {
    $arr[$j]= $ElectronTemperatureTime[$i+$j]
  }
  @sorted= sort {$a <=> $b} @arr;
  push @filtered, $sorted[$hmedian];
  #push @filtered, ($sorted[1]+$sorted[2]+$sorted[3]+$sorted[4]+$sorted[5]+$sorted[6]+$sorted[7]+$sorted[8]+$sorted[9]+$sorted[10]+$sorted[11])/11;
}

for ($i=0; $i< $hmedian; $i++)
{
  unshift @filtered, $filtered[0];
  push @filtered, $filtered[$#filtered];
}

open CIL3, ">ElectronTemperatureMedianFilter.txt";
for ($i=0; $i< $LineCount; $i++)
{
  print CIL3 "$Time[$i]	$filtered[$i]\n";
}
close (CIL3);

$maxElectronTemperature=0;
$row=0;
for ($i=$PlasmaStartRow;$i<$PlasmaEndRow;++$i)
{
        $row= $maxElectronTemperature < $filtered[$i] ? $i : $row;
        $maxElectronTemperature= $maxElectronTemperature < $filtered[$i] ? $filtered[$i] : $maxElectronTemperature;
}
@row1=split(';',$data1[$row]);
$time=$row1[0];

open CIL2, ">maxElectronTemperature";
print CIL2 "$time       $maxElectronTemperature $row";
close (CIL2);
$maxT=sprintf("%.3f", $maxElectronTemperature);
open CIL4, ">maxElectronTemperatureT";
print CIL4 "$maxT";
close (CIL4);
