#!/usr/bin/perl
#$Id: cnv.pl,v 1.29 2024/05/23 10:42:58 sqko Exp $
use strict;
use warnings;
use RFC::Rig;
use RFC::Main;
use RFC::Header;
use SemaforeFile;
use File::Copy;
use POSIX;
use Date::Manip;

my $rig = RFC::Rig->new(shift,0,'nocheck');
$rig->check_run();
my $currenttest = $rig->session;
my $sleep = shift;
sleep($sleep) if ($sleep);
my $mode = shift;
my $olddate;
if ($mode && $mode =~ /recreate/)
{
    $currenttest = shift;
    $olddate = shift;    
}
my $GNUPLOT = &get_cv('GNUPLOT','location');
my $rigno = 'rig' . $rig->name;
my $ncol        = $rig->get_cv_test('main','number_of_plot_cols' ,$currenttest);
$ncol        = $rig->get_cv('main','number_of_plot_cols') unless ($ncol);
$ncol = 3 unless ($ncol);
$ncol = 2 unless ($ncol > 1);
$ncol = int($ncol);
my $area        = $rig->get_cv_test('main','cell_area' ,$currenttest);
$area        = $rig->get_cv('main','cell_area' ) unless ($area);
$area = 16 unless ($area);
my $gsize       = &get_cv('GNUPLOT','png-size');
$gsize = '0.4,0.4' unless ($gsize);
my $psize       = &get_cv('GNUPLOT','ps-size');
$psize = '1,1' unless ($psize);
my $idat        = 0;
my $awklocation = "/usr/local/bin/celltest/awk/";
my $homedir     = '/home/' . $rigno;


my $hdir = $RFC::Header::publicdir.'rig'.$rig->name. '/' . $rig->name . 'test' . $currenttest;

my $dir =
  $RFC::Header::publicdir . $rigno . "/"
  . $rig->name . 'test'
  . $currenttest;

my $date =	new Date::Manip::Date;
$date->parse("today");
my $dat = $date->printf("%Y:%m:%d");
my $dat2 = $date->printf("%Y_%m_%d");
#my $dat = `date +"%Y:%m:%d"`;
#my $dat2 = `date +"%Y_%m_%d"`;
chomp $dat;
chomp $dat2;
if ( $mode &&  $mode =~ /midnight/ ) {
    $idat = 1;
    $date->parse(DateCalc('today','- 1 day'));
    $dat = $date->printf("%Y:%m:%d");
    $dat2 = $date->printf("%Y_%m_%d");
    #$dat = `date --date="$idat days ago" +"%Y:%m:%d"`;
    #$dat2 = `date --date="$idat days ago" +"%Y_%m_%d"`;
    my $workdir = $RFC::Header::publicdir.'rig'.$rig->name.'/';
    my $source = $workdir.'configfile';
    my $target = $workdir.$rig->name.'test'.$currenttest.'/configfile';
    copy($source,$target);
    ## Create tarfile with data ##
    my $rignr = $rig->name;
    my $cstr = "/usr/local/bin/celltest/create_data_export.pl $rignr > /dev/null 2> /dev/null";
    system($cstr);
}
my ($nextdat,$nextdat2,$prevdat,$prevdat2);
if ($idat)
{
    $date->parse('today');
    $nextdat = $date->printf("%Y:%m:%d");
    $nextdat2 = $date->printf("%Y_%m_%d");
    $date->parse(DateCalc('today',"- 2 days"));
    $prevdat = $date->printf("%Y:%m:%d");
    $prevdat2 = $date->printf("%Y_%m_%d");
}
else
{
    $date->parse(DateCalc('today',"+ 1 day"));
    $nextdat = $date->printf("%Y:%m:%d");
    $nextdat2 = $date->printf("%Y_%m_%d");
    $date->parse(DateCalc('today',"- 1 day"));
    $prevdat = $date->printf("%Y:%m:%d");
    $prevdat2 = $date->printf("%Y_%m_%d");
}

if ($mode && $mode =~ /recreate/)
{
    ## Set all dates to something based on $olddate
    $date->parse($olddate);
    $dat = $date->printf("%Y:%m:%d");
    $dat2 = $date->printf("%Y_%m_%d");
    $date->parse(DateCalc($olddate,"+ 1 day"));
    $nextdat = $date->printf("%Y:%m:%d");
    $nextdat2 = $date->printf("%Y_%m_%d");
    $date->parse(DateCalc($olddate,"- 1 day"));
    $prevdat = $date->printf("%Y:%m:%d");
    $prevdat2 = $date->printf("%Y_%m_%d");
    $idat = 1;
}

chomp $dat;
chomp $dat2;
chomp $nextdat;
chomp $prevdat;
chomp $nextdat2;
chomp $prevdat2;

if ( !( -d $dir ) ) { mkdir $dir; }

unless (-e $dir.'/imp_comp')
{
    my $cmd = "/usr/bin/ln -s $dir/../imp_comp $dir/imp_comp";
    system($cmd);
}

my $dirdat    = $dir . "/" . $dat;
my $dirdatpng = $dirdat . "/png";
if ( !( -d $dirdat ) ) 
{
    mkdir $dirdat;
    mkdir $dirdatpng;
}

if ($idat) 
{
    my $source;
    if (-e $hdir.'/raadata.'.$dat)
    {
	$source = $hdir.'/raadata.'.$dat;
    }
    else
    {
	$source = $hdir.'/raadata_'.$dat2;	
    }
    if (-e $source && $mode =~ /midnight/)
    {
	open MYIN,'<',$source or die "Could not open file $source for reading! $!";	
	my $target = $dir.'/raadata';
	open MYOUT,'>>',$target or die "Could not open $target for appending! $!";
	while (my $str = <MYIN>)
	{
	    print MYOUT $str;
	}
	close MYIN;
	close MYOUT;
    }
    if (-e $hdir.'/raadata.'.$dat)
    {
	copy($hdir.'/raadata.'.$dat,$dir.'/'.$dat.'/tabel');
    }
    else
    {
	copy($hdir.'/raadata_'.$dat2,$dir.'/'.$dat.'/tabel');
    }
}
else {
    if (-e $hdir.'/raadata.'.$dat)
    {
	copy($hdir.'/raadata.'.$dat,$dir.'/'.$dat.'/tabel');
    }
    else
    {
	copy($hdir.'/raadata_'.$dat2,$dir.'/'.$dat.'/tabel');
    }
}
my $ivname = $homedir. '/' . $rig->name . 'test' . $currenttest . '/ivcurve.' . $dat;
my $cstr   = "cp $ivname $dirdat/ivtabel";
my $ivnumber = 0;
if ( -f $ivname ) 
{
    copy($ivname,$dirdat.'/ivtabel');
    open MYIN,'<',$dirdat.'/ivtabel' or die "Could not open file $dirdat./ivtabe $!";
    while (my $str = <MYIN>)
    {
	next unless ($str && $str =~ /\d+/);
	my @list = split(/[\s\t]+/,$str);
	$ivnumber = POSIX::ceil(@list/5);
    }
}
my $cnvdir = $hdir.'/convert';
if ( !( -d $cnvdir ) ) { mkdir $cnvdir; }

if ( !( -d $dirdat ) ) { 
    mkdir $dirdat;
    mkdir $dirdatpng;
}
if (-d $hdir.'/convert')
{
    my $cstring = "rm  $hdir/convert/*";
    `$cstring 2> /dev/null `;
}
my $cstring;
if (-e $hdir.'/raadata.'.$dat)
{
    $cstring = "/usr/bin/awk -f /usr/local/bin/awk/splt.awk convertdir=$hdir/convert/ $hdir/raadata.$dat";
}
else
{
    $cstring = "/usr/bin/awk -f /usr/local/bin/awk/splt.awk convertdir=$hdir/convert/ $hdir/raadata_$dat2";
}
`$cstring`;

$cstring = "cp $hdir/convert/* $dirdat";
`$cstring`;

open  HTML, '>', $dirdat.'/index.html' or die "Could not open file $dirdat./index.html! $!";
open  HTML2, '>', $dirdat.'/index_2.html' or die "Could not open file $dirdat./index_2.html! $!";


$| = 1;

my $c     = "head -1  $dir/$dat/tabel";
my @line1 = split ( " ", `$c` );

print HTML <<END;
<html>
<head>
<title>Plot</title>
</head>
<body>
<table cellpadding=20 border=1>
<tbody>
<tr>
END

print HTML2 <<END;
<html>
<head>
<title>Plot</title>
</head>
<body>
<table cellpadding=20 border=1>
<tbody>
<tr>
END

open( GRAPH, "| $GNUPLOT 2> /dev/null" ) || die;

if ( -f $ivname ) {
    my $pcmd = "plot '$ivname' u (f(\$3)):4";
    for (my $x = 1; $x < $ivnumber; $x++)
    {
	my $c = $x*6+3;
	my $y = $x*6+4;
	$cstr .= ",'' u (f(\$$c)):$y";
    } 

    print GRAPH <<END;
reset
f(x)=x;fa(x)=abs(x)>1e10?1/0:x;
set nokey
set size $psize
set term png
set nokey
set yla "mV"
set xla "Ampere"
set title \047ivdata\047
set out \047$dirdatpng/ivdata.png\047
$pcmd
set out
END

    $pcmd = "plot '$ivname' u 3:(\$5)";
    for (my $x = 1; $x < $ivnumber; $x++)
    {
	my $c = $x*6+3;
	my $y = $x*6+5;
	$cstr .= ",'' u $c:$y";
    }     

    print GRAPH <<END;
reset
f(x)=x;fa(x)=abs(x)>1e10?1/0:x;
set nokey
set size $psize
set term png
set nokey
set xla 'Ampere'
set yla 'Ohm cm^2'
set title \047area specific resistance (ref. OCV)\047
set out \047$dirdatpng/specres.png\047
$pcmd
set out
END

    $cstr = "plot '$ivname' u 3:(\$3*\$4*0.001/$area)";
    for (my $x = 1; $x < $ivnumber; $x++)
    {
	my $c = $x*6+3;
	my $y = $x*6+3;
	my $z = $x*6+4;
	$cstr .= ",'' u $c:(\$$y*\$$z*0.001/$area)";
    } 

    print GRAPH <<END;
reset
f(x)=x;fa(x)=abs(x)>1e10?1/0:x;
set nokey
set size $psize
set term png
set xla 'Ampere'
set yla 'Watt pr cm^2'
set title 'power vs current'
set out \'$dirdatpng/specpow.png\'
$cstr
set out
END

}

my $count = 0;
my $count2 = 0;
for ( my $i = 0 ; $i <= $#line1 ; $i += 4 ) {
    chomp( $line1[$i] );
    my $title = $line1[$i];
    ### Find if channel has a title defined and if so use this instead ###
    my $show = 1;
    foreach my $key ('filter_','water_','channel_','temp_','gas_','relay_','Tcontrol_','gas_multiplexer_','analog_out_','gas_group_','controler_','PID_')
    {
	if ($title =~ /(.*)_(enabled|setpoint|error|temp)$/)
	{
	    my $name = $1;
	    my $ts = $rig->get_cv($key.$name,'show_plot');
	    $show = 0 if ($ts && $ts =~ /no/i);
	    my $t = $rig->get_cv($key.$name,'title');
	    next unless $t;
	    $title = $t.' enabled';
	    last;	    
	}
	else
	{
	    my $ts = $rig->get_cv($key.$title,'show_plot');
	    $show = 0 if ($ts && $ts =~ /no/i);
	    my $t = $rig->get_cv($key.$title,'title');
	    next unless $t;
	    $title = $t;
	    last;
	}
    }
    $show = 0 if ($title eq 'VERSION');  ## Only show the software version graph in 'all graphs'
    $title =~ s/_/ /g;
    if ($show)
    {
	if ( $count % $ncol == 0 ) 
	{
	    print HTML "</tr>\n<tr>"; 
	}
	$count++;
	print HTML "<td><a href=\"$line1[$i]\"><img src=\"png/$line1[$i].png\" alt=\"image\" width=400></a><br><center>$title</center></td>\n";
    }
    if ( $count2 % $ncol == 0 ) 
    {
	print HTML2 "</tr>\n<tr>"; 
    }
    $count2++;
    print HTML2 "<td><a href=\"$line1[$i]\"><img src=\"png/$line1[$i].png\" alt=\"image\" width=400></a><br><center>$title</center></td>\n";
    my $ic   = $i + 2;
    my $ida  = $i + 4;
    my $pcmd = "plot '$dirdat/tabel' u $ic:(fa(\$$ida))";

    print GRAPH <<END;

reset
f(x)=x;fa(x)=abs(x)>1e10?1/0:x;
set xdata time
set timefmt "%Y:%m:%d:%H:%M:%S"
set format x "%H"
set bmargin 3
set nokey
set size $psize
set term png
set nokey
set title '$title'
set out '$dirdatpng/$line1[$i].png'
$pcmd
set out

END

}

if ( -f $ivname ) {
    print HTML <<END;
<tr>
<td><a href="ivtabel"><img src="png/ivdata.png" alt="image"></a>
<td><a href="ivtabel"><img src="png/specres.png" alt="image"></a>
<td><a href="ivtabel"><img src="png/specpow.png" alt="image"></a>
END
    print HTML2 <<END;
<tr>
<td><a href="ivtabel"><img src="png/ivdata.png" alt="image"></a>
<td><a href="ivtabel"><img src="png/specres.png" alt="image"></a>
<td><a href="ivtabel"><img src="png/specpow.png" alt="image"></a>
END

}
   
print HTML <<END;
<tr></table>
END
print HTML2 <<END;
<tr></table>
END

if ( -f $ivname ) {
    print HTML <<END;
<p>
<a href="ivtabel">iv-curve  $dat</a>
<p>
<table>
<tr>
END

    print HTML2 <<END;
<p>
<a href="ivtabel">iv-curve  $dat</a>
<p>
<table>
<tr>
END

    $cstr =
      "/bin/awk -f $awklocation"
      . "iv.awk  convertdir=\"" . "$hdir"
      . "/convert/\" $ivname";
    system($cstr);

    opendir( DIRDAT, "$hdir/convert" ) or die "dir error";

    my @files = grep { /iv.[0-9]*/ } readdir DIRDAT;

    my $i = 0;
    for (@files) {
        my @ze = stat "$hdir"."/convert/".$_ ;    # filesize
        if ( $ze[7] < 2 ) { next }
        my $title = $_;
        chomp($_);
        if ( ( $i % 3 == 0 ) && ( $i > 0 ) ) { print HTML "</tr>\n<tr>" }
        $i++;
        print HTML "<td><center>$_</center><br><a href=\"$_\"><img src=\"png/$_.png\" alt=\"image\"></a></td>\n";
        print GRAPH <<END;
reset
f(x)=x;fa(x)=abs(x)>1e10?1/0:x;
set bmargin 3
set nokey
set size $gsize
set term png
set nokey
set xla 'A'
set yla 'mV'
set title '$title'
set out '$dirdatpng/$_.png'
plot '$hdir/convert/$_' u 2:fa(\$3) w linesp
set out
END

    }

}

close(GRAPH);
if ( -f $ivname ) { 
    print HTML "</tr>\n</table>\n"; 
    print HTML2 "</tr>\n</table>\n"; 
}


opendir MYDIR,$dirdat or die "Could not open directory $dirdat $!";
my @files = grep {/\.png$/} readdir MYDIR;
close MYDIR;

if (@files)
{
    print HTML "<table border=0 cellstacing=10>\n";
    print HTML '<tr>';
    print HTML2 "<table border=0 cellstacing=10>\n";
    print HTML2 '<tr>';
    my $c = 0;
    foreach (@files)
    {
	/(\w+)\./;
	my $tit = $1;
	print HTML "<td><center>$tit</center><br><img src='$_' alt='image'></td>\n";
	print HTML2 "<td><center>$tit</center><br><img src='$_' alt='image'></td>\n";
	if (!(++$c%2))
	{
	    print HTML "</tr><tr>\n"; 
	    print HTML2 "</tr><tr>\n";
	}
    }
    print HTML '</tr>';
    print HTML "</table>\n<p>\n";
    print HTML2 '</tr>';
    print HTML2 "</table>\n<p>\n";
}

my $nextstring = "<a href=\"../$nextdat/\"> Next day </a>";
$nextstring = '' unless ($idat);

print HTML <<END;

<a href="tabel">Data table for $dat</a>
<p>
<a href="../raadata">All data for current test</a>
 - 
<a href="index_2.html">All graphs for this day</a>
<p>
<a href="../$prevdat/"> Previous day</a>
$nextstring
</body>
</html>
END

$nextstring = "<a href=\"../$nextdat/index_2.html\"> Next day </a>" if ($nextstring);

print HTML2 <<END;

<a href="tabel">Data table for $dat</a>
<p>
<a href="../raadata">All data for current test</a>
 - 
<a href="index.html">Normal view</a>
<p>
<a href="../$prevdat/index_2.html"> Previous day</a>
$nextstring
</body>
</html>
END

$cstr = "cp  $hdir/convert/iv.[0-9]*  $dirdat";
if ( -f $hdir . "/convert/iv.1" ) { `$cstr` }

