#!/bin/perl

do "parameters.pl";


# Open the file for reading.
open DATA, "Iplasma_dp.csv" or die "can't open file $!";
my @data = <DATA>;
close (DATA);
system("echo 0 > Plasma;rm -f PlasmaStart PlasmaEnd PlasmaStartAdvanced PlasmaEndDelayed");



$maxI= 0;
$minI = 0;
for ($i = 1; $i < $LineCount; ++$i)  
{
    @row = split(';',$data[$i]);
    $Ipl=$row[1];
    if($maxI<$Ipl){$maxI=$Ipl;}
    if($minI>$Ipl){$minI=$Ipl;} 
}
$polar = 1;
if(-$minI>$maxI){
    $polar = -1;
    system("echo 1 > ReversedCD;");
}#reverse polarity
else 
{
    system("echo 0 > ReversedCD;");
}
$StartRow = 500;


for ($i = 51; $i < $LineCount-500; ++$i)  
{
    @row = split(';',$data[$i-50]) ;$Ipl10=$row[1]*$polar;
    @row = split(';',$data[$i]);    $Ipl1=$row[1]*$polar;
    $TimeStart=$row[0]+120*$DeltaT;
    @row = split(';',$data[$i+150]);$Ipl2=$row[1]*$polar;
    @row = split(';',$data[$i+175]);$Ipl3=$row[1]*$polar;
    @row = split(';',$data[$i+200]);$Ipl4=$row[1]*$polar;
    if ( $Ipl2 > ($Ipl1+$Ipl0)/2+$PlCurrentRise && $Ipl3 > $Ipl1+$PlCurrentRise && $Ipl4 > $Ipl1+$PlCurrentRise ){ $StartRow=$i+120;system ("echo $TimeStart > PlasmaStart;echo $StartRow > PlasmaStartRow");$i=$LineCount};
}

for ($i = $LineCount-50; $i >  $StartRow; --$i)  
{
    @row = split(';',$data[$i+50]); $Ipl0=$row[1]*$polar;
    @row = split(';',$data[$i]);    $Ipl1=$row[1]*$polar;
    $TimeEnd=$row[0]-30*$DeltaT;
    @row = split(';',$data[$i-50]);$Ipl2=$row[1]*$polar;
    @row = split(';',$data[$i-100]);$Ipl3=$row[1]*$polar;
    @row = split(';',$data[$i-150]);$Ipl4=$row[1]*$polar;
    if ( $Ipl2 > ($Ipl1+$Ipl0)/2+$PlCurrentRise && $Ipl3 > $Ipl1+$PlCurrentRise && $Ipl4 > $Ipl1+$PlCurrentRise ){$EndRow=$i-30;$dT=$TimeEnd-$TimeStart; system ("echo $TimeEnd > PlasmaEnd;echo $TimeEnd*11/10 > PlasmaEndDelayed;echo $dT > PlasmaTimeLength;echo $EndRow > PlasmaEndRow;echo 1 > Plasma");$i=1};
}


$EFieldTrigger  =`cat ../Te_aktual`;
$EFieldTrigger = $EFieldTrigger/1000; # [ms]	

$start = ($TororoidalMagneticFieldTrigger+$EFieldTrigger)-$DeltaT*10;
system ("echo $start > PlasmaStartAdvanced;")