#!/usr/bin/perl
# $Id: make_report,v 1.5 2015/11/09 09:51:29 sqko Exp $
use strict;
use warnings;
use AFM;
chdir;
my $VERSION = 3.0;
my $PROGRAM = 'make_report';


if ( scalar(@ARGV) < 1 ) 
{
    print
'Usage: make_report [otional --version] $rig [optional: $testno --debug --inter]'.",\n".'where $rig is the rig number';
    print '$testno is the test number'."\n".'if an other test than the current is to be processed',
      "\n";
    print "Use the --inter option if interactive processing is to be used!\n";
    exit 1;
}
my $debug = 0;
my $test = 0;
my $edit = 0;
my $inter = 0;
my $plotonly = 0;
my $plotonly1 = 0;
my $do = 1;
my $recompile = 0;
my $old = 0;
for my $string (@ARGV)
{
    if ($string =~ /--version/)
    {
	print "$PROGRAM is: $VERSION\n";
	exit 0;
    }
    if ($string =~ /--debug/)
    {
	$debug = 1;
    }
    if ($string =~ /--test/)
    {
	$test = 1;
    }
    if ($string =~ /--edit/)
    {
	$edit = 1;
    }
    if ($string =~ /--inter/)
    {
	$inter = 1;
    }
    if ($string =~ /--plot/)
    {
	$plotonly = 1;
    }
    if ($string =~ /--plot_only/)
    {
	$plotonly1 = 1;
    }
    if ($string =~ /--old/)
    {
	$old = 1;
    }
    if ($string =~ /--recompile/)
    {
	$recompile = 1;
    }
}

my $rig = $ARGV[0];
&check_run($rig);

my $testno = &AFM::get_test_nr($rig);
if (scalar(@ARGV) > 1) 
{
    my $string = $ARGV[1];
    $string =~ /(\d+)/;
    my $ttest = $1;
    if (defined($ttest))
    {
	$testno = $ttest+0;
    }
}
my $command;
#####################################################
### Cleanup of old data #############################
#####################################################
my $dir = &get_path.'ps/';
if (-e($dir))
{
    $command = '/bin/rm -rf '.$dir.'*';
    print $command,"\n" if ($debug);
    if ($inter)
    {
	$do = &interactive($command); 
    }
    system($command) if ((!$test) && ($do) && (!$plotonly));
}
$dir = &get_path.'png/';
if (-e($dir))
{
    $command = '/bin/rm -rf '.$dir.'*';
    print $command,"\n" if ($debug);
    if ($inter)
    {
	$do = &interactive($command); 
    }
    system($command) if ((!$test) && ($do) && (!$plotonly));
}
$dir = &get_path.'txt/';
if (-e($dir))
{
    my $command = '/bin/rm -rf '.$dir.'*';
    print $command,"\n" if ($debug);
    if ($inter)
    {
	$do = &interactive($command); 
    }
    system($command) if ((!$test) && ($do) && (!$plotonly));
}

$command = '';
print "#####  Creating history plot using history-plot.pl  ######\n";
$command = '/usr/local/bin/history-plot-3.0.pl '.$rig.' '.$testno;
print $command,"\n" if ($debug);
if ($inter)
{
    $do = &interactive($command);
}
system($command) if ((!$test) && ($do));


&multiplot();

sub multiplot()
{
    print "#####  Creating multiplots using multiplot.pl       ######\n";
	$command = '/usr/local/bin/multiplot.pl '. $rig .' '.$testno;
    print $command,"\n" if ($debug);
    
    if ($inter)
    {
	$do = &interactive($command);
    }
    
    system($command) if ((!$test) && ($do));
    
    my $file = &get_path.'multi.gp';
    if (!$edit)
    {
	print "Remember to manually edit $file\nand run \'gnuplot $file\' afterwards!\n";
    }
    else
    {
	my $emacs = '/usr/bin/emacs -nw';
	my $gnuplot = '/usr/local/bin/gnuplot';
	my $continue = 1;
	while ($continue)
	{
	    $command = "$emacs $file";
	    print $command,"\n" if ($debug);
	    system($command) if (!$test);
	    $command = "$gnuplot $file";
	    print $command,"\n" if ($debug);
	    system($command) if (!$test);
	    my $source = $file;
	    $source =~ s/multi.gp//;
	    my $targetdir = $source.'png/';
	    my $sourcedir = $source.'ps/';
	    my @filelst = ('multi','multi-1','multi-2');
	    for my $ps (@filelst)
	    {
		my $source = $sourcedir.$ps.'.ps';
		my $target = $targetdir.$ps.'.png';
		$command = "/usr/local/bin/ps2png $source $target";
		print $command,"\n" if ($debug);
		system($command) if (!$test);
	    }
	    print "Type quit when satisfied with result!, else press ENTER to redo.\n";
	    if (<STDIN> =~ /quit/)
	    {
		$continue = 0;
	    }
	}
    }
}


print "#####  Creating start and end multiplots using multiplot.pl       ######\n";
$command = '/usr/local/bin/multiplot.pl '. $rig .' '.$testno.' 0 50';
print $command,"\n" if ($debug);

if ($inter)
{
    $do = &interactive($command);
}

system($command) if ((!$test) && ($do));
$command = '/usr/local/bin/long_term_degradation '. $rig .' '.$testno;
my $cont = 1;
$cont = 0 if (($plotonly1) || ($recompile));
if ($cont)
{
    ### Only print information that is relevant.. ####
    print "#####  Input start and end time (in hours) for degradation rate ####\n";
    print "#####  calculation: (Press return if no long term experiemet    ####\n";
    print "#####  has been run):   ";
}
while ($cont)
{
    my $string = <STDIN>;
    if ($string =~ /^$/)
    {
        $cont = 0;
	$command = '';
    }
    if ($string =~ /(\d+)\s+(\d+)/)
    {
        my $st = $1+0;
	my $et = $2+0;
        $command = $command . " $st $et";
        $cont = 0;
	$command = '' unless ($st < $et);
    }
}
print $command,"\n" if (($debug) && ($command));
if (($inter) && ($command))
{
    $do = &interactive($command);
}
system($command) if ((!$test) && ($do) && (!$plotonly1) && (!$recompile));

$command = '/usr/local/bin/multiplot.pl '. $rig .' '.$testno;
$cont = 1;
my $cmd = 'tail -1 '.&get_path."jdata | awk '{print \$1}'";
my $end = `$cmd`-50;
$end = 0 if ($end < 0);

print "#####  Input beginning time of end of test (before cooling) in hours (return for $end)";
while ($cont)
{
    my $string = 0;
#    if ((!$plotonly1) && (!$recompile))
    if (!$plotonly1)
    {
	$string = <STDIN>;
    }
    else
    {
	my $str = '/bin/ls -1 '.&get_path.'ps/multi_*_0.ps';
	my @l = `$str`;
	for my $str1 (@l)
	{
	    if ($str1 =~ /multi_(\d\d+)_0.ps/)
	    {
		$string = $1+0;
	    }
	}
    }
    if ($string =~ /^$/)
    {
        $cont = 0;
	$command = $command . ' ' . $end . "\"\"";
    }
    if ($string =~ /\d+/)
    {
        $string =~ /(\d+)/;
        my $Res = $1;
        $command = $command . ' ' . $Res . "\"\"";
        $cont = 0;
    }
}
print $command,"\n" if ($debug);
if ($inter)
{
    $do = &interactive($command);
}
system($command) if ((!$test) && ($do));

my $ivcurve = &get_path;
$ivcurve = $ivcurve.'iv/ivtable';
$cmd = "/bin/cat $ivcurve";
my @lines = `$cmd`;
my $isiv = scalar(@lines);
my $do_iv_curves_temp = 1;
my @ivcurves = ();
my $file = &get_path.'iv/tempvariation';
my $do_iv_curves_fig4 = 1;
my $filefig4 = &get_path.'iv/fig4iv';
my @fig4ivcurves = ();
my $do_drywet = 1;
my @drywet = ();
my $filedrywet = &get_path.'iv/drywet-iv';
if ($isiv)
{
    print "\n\n";
    print "######################################\n";
    print "###  i-V plots finished.           ###\n";
    print "###  make_report ready to make     ###\n";
    print "###  temperature wariations plots  ###\n";
    print "###  Input iv-curve numbers for    ###\n";
    print "###  plots (with space between     ###\n";
    print "###  each i-v curve number         ###\n";
    print "###  type q and return for quit    ###\n";
    print "###  if no iv-curves have been     ###\n";
    print "###  run type 0                    ###\n";
    print "######################################\n";
    print "###  Input i-V numbers: ";
    my $continue = 1;
    my $string;
    while ($continue)
    {
	my $str = '';
	if(!$plotonly1)
	{
	    $str = <STDIN>; 
	}
	else
	{
	    $do_iv_curves_temp = 1;
	    open MYIN,'<',$file or die "Could not open file $file $!\n";
	    while (<MYIN>)
	    {
		chomp;
		push @ivcurves,$_ if /\d+/;
	    }
	    close MYIN;
	    last;
	}
	if ($str =~ /^\s*0\s*$/)
	{
	    $do_iv_curves_temp = 0;
	    $continue = 0;
	    open OUT, "> $file" or die "Could not open file $file!\n";
	    print OUT "";
	    close(OUT);
	    last;
	}
	if ($str =~ /\d+/)
	{
	    chomp $str;
	    @ivcurves = split(/\s+/,$str);
	    $continue = 0;
	    $do_iv_curves_temp = 1;
	    open OUT, "> $file" or die "Could not open file $file!\n";
	    for my $str (@ivcurves)
	    {
		print OUT $str,"\n";
	    }
	    close(OUT);
	    last;
	}
	if ($str =~ /q/)
	{
	    $do_iv_curves_temp = 0;
	    $continue = 0;
	    last;
	}
    }
    print "########################################################\n";
    print "###  Input numbers of first, best and last i-V curve ###\n"; 
    print "###  if no iv-curves have been                       ###\n";
    print "###  run type 0                                      ###\n";
    print "########################################################\n";
    print "###  Input i-V numbers: ";
    $continue = 1;
    while ($continue)
    {
	my $str = '';
	if(!$plotonly1)
	{
	    $str = <STDIN>; 
	}
	else
	{
	    $do_iv_curves_fig4 = 1;
	    open MYIN,'<',$filefig4 or die "Could not open file $filefig4 $!\n";
	    while (<MYIN>)
	    {
		chomp;
		push @fig4ivcurves,$_ if /\d+/;
	    }
	    close MYIN;
	    last;
	}
	if ($str =~ /^\s*0\s*$/)
	{
	    $continue = 0;
	    $do_iv_curves_fig4 = 0;
	    open OUT, "> $filefig4" or die "Could not open file $filefig4!\n";
	    print OUT "";
	    close(OUT);
	    last;
	}
	if ($str =~ /\d+/)
	{
	    chomp $str;
	    @fig4ivcurves = split(/\s+/,$str);
	    $continue = 0;
	    $do_iv_curves_fig4 = 1;
	    open OUT, "> $filefig4" or die "Could not open file $filefig4!\n";
	    for my $str (@fig4ivcurves)
	    {
		print OUT $str,"\n";
	    }
	    close(OUT);
	    last;
	}
	if ($str =~ /q/)
	{
	    $do_iv_curves_fig4 = 0;
	    $continue = 0;
	    last;
	}
    }
    print "############################################################\n";
    print "###  Input numbers of 2 i-V curves run at the same       ###\n"; 
    print "###  temperature and hydrogen and air flow but           ###\n";
    print "###  with different hydrogen humidity (0 and 2 L/hour)   ###\n";
    print "###  type the number of the i-v curve runin dry h2 first ###\n";
    print "###  If no i-V curves ahve been run type 0               ###\n";
    print "############################################################\n";
    print "###  Input i-V numbers: ";
    $continue = 1;
    while ($continue)
    {
	my $str = '';
	if(!$plotonly1)
	{
	    $str = <STDIN>; 
	}
	else
	{
	    $do_drywet = 1;
	    open MYIN,'<',$filedrywet or die "Could not open fiel $filedrywet $!\n";
	    while (<MYIN>)
	    {
		chomp;
		push @drywet,$_ if /\d+/;
	    }
	    close MYIN;
	    last;
	}
	if ($str =~ /^\s*0\s*$/)
	{
	    $continue = 0;
	    $do_drywet = 0;
	    open OUT, "> $filedrywet" or die "Could not open file $filedrywet!\n";
	    print OUT "";
	    close(OUT);
	    last;
	}
	if ($str =~ /\d+/)
	{
	    chomp $str;
	    @drywet = split(/\s+/,$str);
	    $continue = 0;
	    $do_drywet = 1;
	    open OUT, "> $filedrywet" or die "Could not open file $filedrywet!\n";
	    for my $str (@drywet)
	    {
		print OUT $str,"\n";
	    }
	    close(OUT);
	    last;
	}
	if ($str =~ /q/)
	{
	    $do_drywet = 0;
	    $continue = 0;
	    last;
	}
    }
}
else
{
    $do_iv_curves_temp = 0;
    open OUT, "> $file" or die "Could not open file $file!\n";
    print OUT "";
    close(OUT);
    $do_iv_curves_fig4 = 0;
    open OUT, "> $filefig4" or die "Could not open file $filefig4!\n";
    print OUT "";
    close(OUT);
    $do_drywet = 0;
    open OUT, "> $filedrywet" or die "Could not open file $filedrywet!\n";
    print OUT "";
    close(OUT);
}
print $file,"\n" if ($debug);
print $filefig4,"\n" if ($debug);
print $filedrywet,"\n" if ($debug);

if ($isiv > 0)
{
    print "\n";
    print "#####  Creating temperature and flow wariation plots #####\n";
    print "#####  and resistance_flow_variation_plot.pl       #####\n";
    print "#####  using make_iv_flowvar.pl                        #####\n";
    $command = '/usr/local/bin/make_iv_flowvar.pl '.$rig.' '.$testno;
    $command = '/usr/local/bin/make_iv_flowvar.pl '.$rig.' '.$testno.' --replot' if ($plotonly1);
    print $command,"\n" if ($debug);
    if ($inter)
    {
	$do = &interactive($command);
    }
    system($command) if ((!$test) && ($do));
    $command = '/usr/local/bin/resistance_flow_variation_plot.pl '.$rig.' '.$testno.' 2> /dev/null';
    print $command,"\n" if ($debug);
    if ($inter)
    {
	$do = &interactive($command);
    }
    system($command) if ((!$test) && ($do));
}

if ($do_iv_curves_temp)
{
    print "\n";
    print "#####  Creating i-V curves of temperature variation  #####\n";
    print "#####  using iv-plot-report                          #####\n";
    my @labels = ();
    $command = "/usr/local/bin/iv-plot-report $rig $testno";
    for (my $x = 0; $x < scalar(@ivcurves) ; $x++)
    {
	my $f = $file;
	my $nr = $ivcurves[$x];
	$f =~s/tempvariation/ivdatadir-$nr\/data\/T_center/;
	my $cmd = "head -n 1 $f";
	print $cmd,"\n" if ($debug);
	my $res = `$cmd`;
	$res =~ /\s+(\d+)/; 
	$labels[$x] = "\"" .$1." C\"";
	print " $x $nr $labels[$x]\n" if ($debug);
	$command = $command . " $ivcurves[$x] $labels[$x]";
    }
    if ($inter)
    {
	$do = &interactive($command);
    }
    my $tcmd = $command . ' 2> /dev/null';
    system($tcmd) if ((!$test) && $do && @ivcurves > 0 && $ivcurves[0]);
}

if ($do_iv_curves_fig4)
{
    print "\n";
    print "#####  Creating i-V curves of time variation         #####\n";
    print "#####  using iv-plot-report                          #####\n";
    $command = "/usr/local/bin/iv-plot-report $rig $testno";
    my @labelsfig4=('"first','"best','"last');
    for (my $x = 0; $x < scalar(@fig4ivcurves) ; $x++)
    {
	my $f = $filefig4;
	my $nr = $fig4ivcurves[$x];
	$f =~s/fig4iv/ivdatadir-$nr\/data\/T_center/;
	my $cmd = "head -n 1 $f";
	print $cmd,"\n" if ($debug);
	my $res = `$cmd`;
	$res =~ /([\d\.]+)/; 
	my $time = $1;
	if ($time =~ /\d+\.\d+/)
	{
	    $time =~ /(\d+\.\d)/;
	    $time = $1;
	}
	$labelsfig4[$x] = $labelsfig4[$x]." i-V, time : $time h\"" ;
	print " $x $nr $labelsfig4[$x]\n" if ($debug);
	$command = $command . " $fig4ivcurves[$x] $labelsfig4[$x]";
    }
    print $command,"\n" if ($debug);
    if ($inter)
    {
	$do = &interactive($command);
    }
    system($command) if ((!$test) && $do && @fig4ivcurves > 0 && $fig4ivcurves[0]);
}

if ($do_drywet)
{
    print "\n";
    print "#####  Creating i-V curves of pH2O variation         #####\n";
    print "#####  using iv-plot-report                          #####\n";
    $command = "/usr/local/bin/iv-plot-report $rig $testno";
    my @labelsdrywet=('"dry','"wet');
    for (my $x = 0; $x < scalar(@drywet) ; $x++)
    {
	my $f = $filedrywet;
	my $nr = $drywet[$x];
	$f =~s/drywet-iv/ivdatadir-$nr\/data\/air/;
	my $cmd = "head -n 1 $f";
	print $cmd,"\n" if ($debug);
	my $res = `$cmd`;
	$res =~ /(\d+)\.*\d*\s+(\d+)/; 
	my $time = $1;
	my $airflow = $2;
	if ($time =~ /\d+\.\d+/)
	{
	    $time =~ /(\d+\.\d)/;
	    $time = $1;
	}
	$f =~ s/\/air/\/h2/;
	$cmd = "head -n 1 $f";
	print $cmd,"\n" if ($debug);
	$res = `$cmd`;
	$res =~ /[\d\.]+\s+(\d+\.?\d?)/; 
	my $h2flow = $1;
	$f =~ s/\/h2/\/T_center/;
	$cmd = "head -n 1 $f";
	print $cmd,"\n" if ($debug);
	$res = `$cmd`;
	$res =~ /[\d\.]+\s+(\d+)/; 
	my $temp = $1;
	$f =~ s/\/T_center/\/o2/;
	$cmd = "head -n 1 $f";
	print $cmd,"\n" if ($debug);
	$res = `$cmd`;
	$res =~ /[\d\.]+\s+(\-*\d+\.?\d?)/; 
	my $o2flow = $1;
	if ($o2flow <0){$o2flow = 0};
	my $o2cutoff = &AFM::get_config_value_old($rig,'o2_cutoff',$testno);
	$o2cutoff = &AFM::get_usercv_test($rig,$testno,'gas_o2','cutoff_report') unless ($o2cutoff);
	if ($o2flow < $o2cutoff) {$o2flow = 0};
	$labelsdrywet[$x] = $labelsdrywet[$x].", t:$time h, h2:$h2flow, air:$airflow, o2:$o2flow, T:$temp \"" ;
	print " $x $nr $labelsdrywet[$x]\n" if ($debug);
	$command = $command . " $drywet[$x] $labelsdrywet[$x]";
    }
    print $command,"\n" if ($debug);
    if ($inter)
    {
	$do = &interactive($command);
    }
    system($command) if ((!$test) && $do && @drywet > 0 && $drywet[0]);
}    



### Copying plots to main dir ###
#my $tcmd = "/usr/local/bin/copyplot.pl $rig $testno";
#system($tcmd) if ((!$test) && ($do) && ($do_iv_curves_fig4));


### Creating leak plots ###
$file = &get_path.'proglog';
my @list = `/bin/cat $file`;
my $isleak = 0;
for my $st (@list)
{
    if ($st =~ /Leak measurement\s+\#/)
    {
	$isleak = 1;
    }
}
if ($isleak)
{
    print "#####  Creating leak plots using plot_leak.pl ######\n";
	print "\n";
    $command = '/usr/local/bin/plot_leak.pl '.$rig.' '.$testno;
    print $command,"\n" if ($debug);
    if ($inter)
    {
	$do = &interactive($command);
    }
    system($command) if ((!$test) && ($do));
}

print "#####  Creating plots of all measured values  ######\n";
$command = '/usr/local/bin/plotall.pl '.$rig.' '.$testno;
print $command,"\n" if ($debug);
if ($inter)
{
    $do = &interactive($command);
}
system($command) if ((!$test) && ($do));

print "##### Copying plot files ...           ######\n";
system("/usr/local/bin/copyplot.pl $rig $testno");

my $type = &get_cv('GNUPLOT','output_type');
$type = 'pdf' unless ($type);
print "#####  Creating report in $type format   ######\n";
print "\n";
if ((!$plotonly) && (!$recompile))
{
    $command = "/usr/local/bin/remake_latex_report $rig $testno";
}
else
{
    $command = "/usr/local/bin/remake_latex_report $rig $testno --recompile";
}
print $command,"\n" if ($debug);
if ($inter)
{
    $do = &interactive($command);
}
system($command) if ((!$test) && ($do));

print "\n";
print "#######################\n";
print "#####  Finished!  #####\n";
print "#######################\n";
print "\n#####  Plots of individual i-V curves can be made with iv-plot-report ###\n\n";

exit;


sub get_path
{
    my $dir = $AFM::publicdir.'rig'.$rig.'/'.$rig.'test'.$testno.'/';
    return $dir;
}


sub get_cell
{
    my $file = &get_path.'info.txt';
    my $res = `/bin/cat $file`;
    $res =~ /(?:Cell|Sample) number\s+:\s+([\d\w\-]+)/;
    my $name = $1;
    return $name;
}



sub interactive($)
{
    my $doit = 0;
    my $command = $_[0];
    my $continue = 1;
    while ($continue)
    {
        print "#####  Execute command $command \?  #####\n#####  (y/n/c) use \'c\' to leave noninteractive mode  #####\n";
        my $str = <STDIN>;
        if ($str =~ /c/)
        {
            $inter = 0;
            $continue = 0;
            $doit = 1;
	    print "######################################\n";
	    print "#####  Leaving interactive mode  #####\n";
	    print "######################################\n";
        }
        if ($str =~ /y/)
        {
            $doit = 1;
            $continue = 0;
        }
        if ($str =~ /n/)
        {
            $doit = 0;
            $continue = 0;
	    print "#####  Skipping $command !  #####\n";
        }
    }
    return $doit;
}
