#!/usr/bin/perl
# $Id: impedance_html.pl,v 1.14 2021/03/18 10:13:40 sqko Exp $
use RFC::Main qw();
use AFM;
use strict;
use warnings;
use CGI qw(:standard :netscape);
use SemaforeFile;

my $debug = 0;
for my $string (@ARGV) {
    if ( $string =~ /--debug/ ) {
        $debug = 1;
    }
}

my $testno = 0;
my $rigno = 0;
if ( scalar(@ARGV) > 0 ) {
    $rigno = $ARGV[0];
    $rigno =~ /(\d+)/;
    $rigno = $1;
}
&check_run($rigno);
if ( scalar(@ARGV) > 1 ) {
    my $ttestno = $ARGV[1];
    $ttestno =~ /(\d+)/;
    $testno = $1;
}

### Find list of gasses to include in table ###
my @gaslist = ('h2','ch4','o2','air','backup','sweep');
my $gstr = &AFM::get_usercv_test($rigno,$testno,'report','gas_names_ivtable');
$gstr = &AFM::get_usercv($rigno,'report','gas_names_ivtable') unless ($gstr);
@gaslist = split(/\s*\,\s*/,$gstr) if ($gstr);
my @relaylist = ();
my $relstr = &AFM::get_usercv_test($rigno,$testno,'report','relay_names_ivtable');
@relaylist = split(/\s*\,\s*/,$relstr) if ($relstr);


my $currentlabel = ucfirst(&AFM::get_usercv_test($rigno,$testno,'IV_control','current_label'));
my $voltlabel = ucfirst(&AFM::get_usercv_test($rigno,$testno,'IV_control','voltage_label'));
$currentlabel = 'Current' unless ($currentlabel); ## Default value for backwards compatibility ###
$voltlabel = 'Cell_voltage' unless ($voltlabel);  ## Default value for backwards compatibility ###
my $templabel = ucfirst(&AFM::get_usercv_test($rigno,$testno,'IV_control','temp_label'));
$templabel = 'T_center' unless ($templabel);




my $homedir     = '/home/rig'. $rigno;
my $currenttest = $testno;
my $impedancedir       =
  $AFM::publicdir . "rig" . $rigno . "/" . $rigno . "test"
  . $currenttest . "/impedance";
print $impedancedir, "\n" if ($debug);
my $impedancetable    = $impedancedir . "/imp_data";
my $htmlfile;
my $htmltablefile;
my $htmltablefileps;
my $htmltablefiletex;
my $latex;
my ($headingstring,$lineno,$tabnr,$clearpagenr);
my ($i,%tabledata,$nrowtable,$htmlrow,$startrowsep,$startrow,$startseparator,$endseparator);
my ($pval,$endrow,$cstr,$res);
my ($beginmulti,$endmulti,$startsub,$deg,$gasst,$l_min,$endsub,$current,$omega);
my ($starttable,$endtable,$html,$startsup,$endsup,$ttype);


for (my $itype=1;$itype<3;$itype++)  {
    if ($itype==1)
    {
	latexsep();
    } 
    else 
    { 
	htmlsep();
    }
    open( HTML, "> $htmlfile" );
    print HTML <<END;
<html>
<script src="/celltest/RFCcontrol.js" type="text/javascript"></script>
<head>
<title>Plot</title>
</head>
<body>
<center>
END

open( HTMLTABLE, '>', $htmltablefile ) or die &RFC::Main::errorlog("Could not open file $htmltablefile\n");
    if ($latex) {
	print HTMLTABLE <<END;
\\documentclass[10pt]{article}
\\usepackage{fullpage, graphicx, url,dcolumn,rotating}
\\setlength{\\parskip}{1ex}
\\setlength{\\parindent}{0ex}
%\\setlength{\\textheight}{ 24cm}
\\setlength{\\tabcolsep}{ 1.0 mm}
\\pagestyle{empty}
\\newcolumntype{d}[1]{D{.}{.}{\#1}}
\\begin{document}

END

}
  else {
    print HTMLTABLE <<END;
<html>
<script src="/celltest/RFCcontrol.js" type="text/javascript"></script>
<head>
<title>Impedance-table</title>
</head>
<body>
<table>
<table border>
<tbody>
END
}

$headingstring= heading();

    exit unless (-e $impedancetable);  ### NO need to continue if no table exsists ###
open( IMPEDANCETABLE,'<',$impedancetable ) or die &RFC::Main::errorlog("Could not open file $impedancetable $!");
$lineno = 0;
    $tabnr = 0;
while (<IMPEDANCETABLE>) 
{
    print $_ if ($debug);
    my @Fld = split (' ', $_);
    $Fld[0] =~ /([\w\-]+)/;
    my $filename = $1;
    my $fullfilename= $Fld[0];
    my $fname = $fullfilename;
    $fname =~ /(^[\w\.\-\:]+)\.\w+$/;
    $fname = $1;
    $filename = $fname;
    $fname =~s/_/\\_/g if ($latex);
    for ( $i = 1 ; $i <= $#Fld ; $i ++ ) 
    {
	my ($id,$val) = split ( /:/, $Fld[$i] );
	$tabledata{$id} = $val;
    }
    
    print HTML <<END;
<table>
<tbody>
END


    print $lineno,"\n" if ($debug);
    if (($lineno % $nrowtable)==0 ) 
    {
	print $lineno % $nrowtable,"\n";
	if ($lineno>0) 
	{  
	    tex_table_end();
	    print HTMLTABLE '\clearpage',"\n" if ($tabnr % $clearpagenr == 0);
	}
	tex_table_heading();
	++$tabnr;
    }
    ++$lineno;
    print HTMLTABLE "\n";
    $htmlrow = $startrowsep;
    $htmlrow = $htmlrow . $startrow;

    $htmlrow = $htmlrow
      . $startseparator
      . $lineno
      . $endseparator . "\n"
      . $startseparator
	.$fname
      . $endseparator;
    $pval= $tabledata{"Time"};
    $htmlrow = $htmlrow . $startseparator . $pval . $endseparator;
    $pval = sprintf( "%.0f", 0 );
    $pval = sprintf( "%.0f",$tabledata{$templabel}) if ($tabledata{$templabel});
    $htmlrow = $htmlrow . $startseparator . $pval . $endseparator;
    if (!$latex)
    {
	$pval= $tabledata{$voltlabel};
	$htmlrow = $htmlrow . $startseparator . $pval . $endseparator;
    }
    for (@gaslist)
    {
	$pval = sprintf( "%.1f", 0 );
        $pval = sprintf( "%.1f", $tabledata{$_} ) if (defined($tabledata{$_}));
        $htmlrow = $htmlrow . $startseparator . $pval . $endseparator;
    }
    for (@relaylist)
    {
	$pval = sprintf( "%i", 0 );
        $pval = sprintf( "%i", $tabledata{$_} ) if (defined($tabledata{$_}));
        $htmlrow = $htmlrow . $startseparator . $pval . $endseparator;
    }
    $pval= $tabledata{$currentlabel};
    $htmlrow = $htmlrow . $startseparator . $pval . $endseparator;
    $pval= $tabledata{"Rs"};
    $htmlrow = $htmlrow . $startseparator . $pval . $endseparator;
    $pval= $tabledata{"Rp"};
    $htmlrow = $htmlrow . $startseparator . $pval . $endseparator;
    $htmlrow = $htmlrow;

    print HTML "<H3>", $lineno, "</H3>\n";
    print HTML $startrow;
    for ("bode","impedance") 
    {
	print HTML "<td><a href=\"".$fullfilename."\"><img src=\"png/";
	print HTML $filename."-".$_.".png\" alt=\"image\"></a>\n";
    }
    my $button = '';
    my $plotbtn = '';
    ### Hook for ElchemeaAnalytic ###
    if (-e '/home/analytic/')
    {
	my $file = $impedancedir.'/'.$fullfilename;
        my $name = '';
        my @data = ();
        my $f = SemaforeFile->new($file);
        my @lines = $f->readlines();
        my $x = 0;
        while ($x++ < @lines)
        {
            next unless ($lines[$x] =~ /^[\s\t]*\d+[\s\t]*$/);
            last;
        }
        while ($x++ < @lines)
        {
            push @data,$lines[$x] if ($lines[$x] && $lines[$x] =~ /\d/);
        }
        if ($file =~ /([\w\d\-\.]+)$/)
        {
            $name = $1;
        }
	print HTML "<br>\n";
	my $multiname = $$.'_'.$fullfilename.'.data';
	$plotbtn = button(-name=>'Compare',onclick=>"set_multiname('$multiname')");
	$button = button(-name=>'Fit with ElchemeaAnalytic',onclick=>'run_ajax("/cgi-bin/celltest/rig_ajax_run.cgi","&action=get_imp_data&rig='.$rigno.'&testno='.$testno.'&file='.$fullfilename.'",set_imp_data)');
	print HTML $button.$plotbtn;
    }
    print HTML "</td></tr></table><table><table border><tbody>";
    print HTML $headingstring, $htmlrow  . $endrow;
    print HTML "</table>";
    print HTML "<p>";
    if ($button && !$latex)
    {
	print HTMLTABLE $htmlrow.$startseparator.$button.$plotbtn.$endseparator.$endrow;
    }
    else
    {
	print HTMLTABLE $htmlrow . $endrow;
    }
}
if ($latex) {
 tex_table_end ();
    print HTMLTABLE <<END;
\\end{document}
END
}
else {
    print HTMLTABLE <<END;
</tbody>
</table>
END


    print HTML start_form(-name=>'login_info');
    print HTML hidden(-name=>'name');
    print HTML hidden(-name=>'pass');
    print HTML hidden(-name=>'time');
    print HTML hidden(-name=>'jscheck');
    print HTML hidden(-name=>'rig',-value=>$rigno,-force=>1);
    print HTML end_form;
    print HTML start_form(-name=>'Elchemea',-action=>'/cgi-bin/analytic/main.cgi');
    print HTML hidden(-name=>'filename');
    print HTML hidden(-name=>'data');
    print HTML hidden(-name=>'mode',-value=>'plot',-force=>1);
    print HTML hidden(-name=>'RFC_file');
    print HTML hidden(-name=>'action',-value=>'Fit with ElchemeaAnalytic');
    print HTML end_form;
    print HTML start_form(-name=>'Elchemea_multi',-action=>'/cgi-bin/analytic/multiplot.cgi');
    print HTML hidden(-name=>'name');
    print HTML hidden(-name=>'pass');
    print HTML hidden(-name=>'user',-value=>'rig'.$rigno,-force=>1);
    print HTML hidden(-name=>'id',-value=>$$,-force=>1);
    print HTML hidden(-name=>'session',-value=>$rigno.'test'.$testno,-force=>1);
    print HTML hidden(-name=>'filelist');
    print HTML end_form;
    print HTMLTABLE start_form(-name=>'login_info');
    print HTMLTABLE hidden(-name=>'name');
    print HTMLTABLE hidden(-name=>'pass');
    print HTMLTABLE hidden(-name=>'time');
    print HTMLTABLE hidden(-name=>'jscheck');
    print HTMLTABLE hidden(-name=>'rig',-value=>$rigno,-force=>1);
    print HTMLTABLE end_form;
    print HTMLTABLE start_form(-name=>'Elchemea',-action=>'/cgi-bin/analytic/main.cgi');
    print HTMLTABLE hidden(-name=>'filename');
    print HTMLTABLE hidden(-name=>'data');
    print HTMLTABLE hidden(-name=>'mode',-value=>'plot',-force=>1);
    print HTMLTABLE hidden(-name=>'RFC_file');
    print HTMLTABLE hidden(-name=>'action',-value=>'Fit with ElchemeaAnalytic');
    print HTMLTABLE end_form;
    print HTMLTABLE start_form(-name=>'Elchemea_multi',-action=>'/cgi-bin/analytic/multiplot.cgi');
    print HTMLTABLE hidden(-name=>'name');
    print HTMLTABLE hidden(-name=>'pass');
    print HTMLTABLE hidden(-name=>'user',-value=>'rig'.$rigno,-force=>1);
    print HTMLTABLE hidden(-name=>'id',-value=>$$,-force=>1);
    print HTMLTABLE hidden(-name=>'session',-value=>$rigno.'test'.$testno,-force=>1);
    print HTMLTABLE hidden(-name=>'filelist');
    print HTMLTABLE end_form;
    
        print HTML <<END;
</center>
</body>
<script>

function set_multiname(fname)
{
    document.Elchemea_multi.filelist.value = fname;
    document.Elchemea_multi.submit();
}

function set_imp_data(res)
{
    var arr = res.split("\\n");
    if (arr[0] == "OK")
    {
	document.Elchemea.filename.value = arr[1];
	document.Elchemea.RFC_file.value = arr[2];
	var data = arr.slice(3,arr.length);
	document.Elchemea.data.value = data.join("\\n");
	document.Elchemea.submit();
    }
    else
    {
        alert(res);
    }
}



</script>
</html>
END

    print HTMLTABLE <<END;
</center>
</body>
<script>

function set_multiname(fname)
{
    document.Elchemea_multi.filelist.value = fname;
    document.Elchemea_multi.submit();
}

function set_imp_data(res)
{
    var arr = res.split("\\n");
    if (arr[0] == "OK")
    {
	document.Elchemea.filename.value = arr[1];
	document.Elchemea.RFC_file.value = arr[2];
	var data = arr.slice(3,arr.length);
	document.Elchemea.data.value = data.join("\\n");
	document.Elchemea.submit();
    }
    else
    {
        alert(res);
    }
}



</script>
</html>
END
}

if ($latex) {
    $cstr =
      "cat $htmltablefile  | sed 's#& \\\\# \\\\#g' > $htmltablefiletex";
    system($cstr);
}

}

sub heading {
    $res="";
    $res = $res . $startrow;
    $res = $res . $startseparator . $endseparator;
    $res = $res . $startseparator . "File name" . $endseparator;
    $res = $res
      . $startseparator
      . $beginmulti
      . ptable( "Time", "h" )
      . $endmulti
      . $endseparator;
    my $ltemp = $templabel;
    $ltemp =~ s/_/ /g;
    $res = $res
      . $startseparator
      . $beginmulti
      . ptable( ucfirst($ltemp), $startsup . $deg . $endsup . "C" )
      . $endmulti
      . $endseparator;
    my $lvolt = $voltlabel;
    $lvolt =~ s/_/ /g;
    if (!$latex)
    {
	$res = $res
	    . $startseparator
	    . $beginmulti
	    . ptable( ucfirst($lvolt),"(mV)" )
	    . $endmulti
	    . $endseparator;
	
    }
    for my $gas (@gaslist)
    {
        $gasst = ucfirst($gas);
        $gasst =~ s/_/\\_/g if ($beginmulti);
        $gasst =~ s/([a-zA-Z])(\d+)/\u$1$startsub$2$endsub/g;
        $res = $res
            . $startseparator
            . $beginmulti
            . ptable( $gasst, $l_min )
            . $endmulti
            . $endseparator;
    }
    for my $gas (@relaylist)
    {
        $gasst = ucfirst($gas);
        $gasst =~ s/_/\\_/g if ($beginmulti);
        $gasst =~ s/([a-zA-Z])(\d+)/\u$1$startsub$2$endsub/g;
        $res = $res
            . $startseparator
            . $beginmulti
            . ptable( $gasst, '' )
            . $endmulti
            . $endseparator;
    }

    $res = $res
      . $startseparator
      . $beginmulti
      . ptable( ucfirst($currentlabel), $current )
      . $endmulti
      . $endseparator;
    $res = $res
      . $startseparator
      . $beginmulti
      . ptable( "Rs",  $omega )
      . $endmulti
      . $endseparator;
    $res = $res
      . $startseparator
      . $beginmulti
      . ptable( "Rp", $omega )
      . $endmulti
      . $endseparator;
    $res = $res . $endrow;
    return $res;
}

sub ptable {
    my $localtable = $starttable;
    for (@_) {
        $localtable =
          $localtable . $startseparator . $_ . $endseparator . $endrow;
    }
    $localtable = $localtable . $endtable;
    return $localtable;
}

sub htmlsep 
{
    $latex=0;
    $htmltablefile = $impedancedir . "/impedancetable.html"; 
    $htmlfile   = $impedancedir . "/impedance.html";
    $nrowtable=10000;
    $clearpagenr = 1000000;
    $starttable = "\n  <table>\n";
    $endtable   = "  </table>\n";
    $beginmulti = "";
    $endmulti   = "";
    
    $ttype          = "td";
    $startrow       = "<tr align=center>\n";
    $startrowsep    = "";
    $startseparator = "<" . $ttype . ">";
    $endseparator   = "</" . $ttype . ">";
    $endrow         = "</tr>\n";
    $startsup       = "<sup>";
    $endsup         = "</sup>";
    $startsub       = "<sub>";
    $endsub         = "</sub>";
    $omega          = "&#937";
    $deg            = "o";
    $l_min          = "l/h";
    $current        = "A";
    
}

sub latexsep {
    $htmltablefile    = $impedancedir . "/impedancetable.txttex";
    $htmltablefiletex = $impedancedir . "/impedancetable.tex";
    $htmltablefileps  = $impedancedir . "/impedancetable.ps";
    $htmlfile   = "/dev/null";
    $nrowtable=20;
    $clearpagenr = 10;
    $latex = 1;
    $html  = 0;

    $starttable     = "\n\\begin{tabular}{c}\n";
    $endtable       = "\\end{tabular}\n";
    $beginmulti     = "\\multicolumn {1}{c|} {";
    $endmulti       = "}";
    $startrowsep    = "\\hline\n";
    $startrow       = "";
    $startseparator = " ";
    $endseparator   = " & ";
    $endrow         = "\\\\\n";
    $startsup       = "\$^";
    $endsup         = "\$";
    $startsub       = "\$_";
    $endsub         = "\$";
    $omega          = "\$\\Omega\$";
    $deg            = "\\circ";
    $l_min          = "\$\\ell\$" . "/h";
    $current        = "A";
}

sub tex_table_heading {
if ($latex) {
    my $str = '|d{1}' x (scalar(@gaslist)+scalar(@relaylist));
    print HTMLTABLE <<END;
\\begin{sidewaystable}
\\begin{tabular}{|c|c|c|d{1}$str|c|d{7}|d{7 }|}
\\hline
END
}
print HTMLTABLE $headingstring;

}

sub tex_table_end {
if ($latex) {
    print HTMLTABLE <<END;
\\hline
\\end{tabular}
\\end{sidewaystable}
END
}
}
