#!/usr/bin/perl
# $Id: ivhtml_tex.pl,v 1.9 2017/03/13 09:29:51 sqko Exp $

use strict;
use warnings;
use RFC::Rig;
use CGI qw(:standard :netscape);

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


my $rig = RFC::Rig->new(shift);
$rig->check_run();
$rig->name =~ /(\d+)/;
my $rigno = $1;
$rig->debug(1) if ($debug);

my $testno = $rig->session();
if (@ARGV)
{
    $testno = shift;
    $testno+= 0;
}

### Find list of gasses to include in table ###
my @gaslist = $rig->get_cv_test('report','gas_names_ivtable',$testno);
@gaslist = $rig->get_cv('report','gas_names_ivtable') unless (@gaslist);
@gaslist = ('h2','ch4','o2','air','backup','sweep') unless (@gaslist);
my $voltlabel = 'cell_voltage';
my $templabel = 'T_center';

my ($htmlfile,$htmltablefile,$latex,$headingstring,$nrowtable,$rminline,$rmin,@rminarr,%rmintabledata);
my ($i,$rfu,$avg,@Fld,$x,%tabledata,$htmlrow,$startrow,$startseparator,$endseparator,$pval,$startrowsep,$pval1,$pval2,$ttype,$endrow);
my ($htmltablefiletex,$res,$beginmulti,$endmulti,$startsup,$endsup,$deg,$startsub,$endsub,$l_min,$omega,$starttable,$endtable,$html,$htmltablefileps);
my $homedir     = $rig->homedir();
my $currenttest = $testno;
my $ivdir       = $rig->webdir($testno).'iv/';
print $ivdir, "\n" if ($debug);
my $ivtable    = $ivdir . "/ivtable";
my $ivavgtable = $ivdir . "/ivtable-avg";
my $rmintable  = $ivdir . "/plotdata/rminvalues";
for (my $itype=1;$itype<3;$itype++)  
{
    if ($itype==1)
    {
	latexsep();
    } else 
    { 
	htmlsep();
    }
}
my ($HTML,$HTMLTABLE);

open( $HTML, "> $htmlfile" );

print $HTML <<END;
<html>
<head>
<title>Plot</title>
</head>
<body>
<center>
END

open( $HTMLTABLE, "> $htmltablefile" );

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
#    tex_table_heading();
}
else {
    print $HTMLTABLE <<END;
<html>
<head>
<title>IV-table</title>
</head>
<body>
<table>
<table border>
<tbody>
END
}

$headingstring = heading();

open( IVTABLE,    $ivtable );
open( IVAVGTABLE, $ivavgtable );
open( RMINTABLE,  $rmintable );
my $lineno = 0;

while (<IVTABLE>) 
{

    print $HTML "<table>\n<tbody>\n";
    if (($lineno % $nrowtable)==0 ) 
    {    
	if ($lineno>0) {  tex_table_end ();};
	tex_table_heading();
    }
    ++$lineno;
    print $HTMLTABLE "\n";
    $rminline = <RMINTABLE>;
    @rminarr  = split ( ' ', $rminline );
    $rmin     = $rminarr[0];
    for my $key (keys %rmintabledata)
    {
	$rmintabledata{$key} = 0;
    }
    for ( $i = 1 ; $i < $#rminarr ; $i += 2 ) {
	
        $rmintabledata{ $rminarr[$i] } = $rminarr[ $i + 1 ];
    }
    $rfu = $rmintabledata{"ASR_corr"};
    $avg = <IVAVGTABLE>;
    print $_. $avg if ($debug);
    @Fld = split ( /\s+/, $_ . $avg, 9999 );

    for ( $i = 0 ; $i < $#Fld ; $i++ ) 
    {
        if ($Fld[$i] && $Fld[$i] =~ /\w+/)
	{
	    $tabledata{ $Fld[$i] } = $Fld[ $i + 1 ];
	}
    }
    
    $htmlrow = $startrowsep;
    $htmlrow = $htmlrow . $startrow;
    $htmlrow = $htmlrow
      . $startseparator
      . $lineno
      . $endseparator . "\n"
      . $startseparator
      . $tabledata{"dstart"}
      . $endseparator;

    $pval = sprintf( "%.1f", ( $tabledata{"tstart"} ) );
    $htmlrow = $htmlrow . $startseparator . $pval . $endseparator;

    $pval =
      sprintf( "%.1f", ( $tabledata{"tstop"} - $tabledata{"tstart"} ) * 60 );

    $pval = sprintf( "%.1f", $tabledata{"cmax"} );
    $htmlrow = $htmlrow . $startseparator . $pval . $endseparator;

    $pval1 = sprintf( "%.1f", $tabledata{"tempavgup"} );

    $pval2 = sprintf( "%.1f", $tabledata{"tempavgdown"} );

    $ttype   = "td";
    $htmlrow =
      $htmlrow . $startseparator . ptable( $pval1, $pval2 ) . $endseparator;

    $pval1 = sprintf( "%.1f", $tabledata{"ocvavgup"} );

    $pval2 = sprintf( "%.1f", $tabledata{"ocvavgdown"} );

    $htmlrow =
      $htmlrow . $startseparator . ptable( $pval1, $pval2 ) . $endseparator;

    for (@gaslist)
    {
        $pval = sprintf( "%.1f", $tabledata{$_} );
        $htmlrow = $htmlrow . $startseparator . $pval . $endseparator;
    }

    $pval = sprintf( "%.3f", $rmin );
    $htmlrow = $htmlrow . $startseparator . $pval . $endseparator;
    $pval    = sprintf( "%.3f", $rfu );
    $htmlrow = $htmlrow . $startseparator . $pval . $endseparator;
    unless ($latex)
    {
	my $plotbtn = button(-name=>'Compare',onclick=>"set_multiname($lineno)");
	$htmlrow = $htmlrow . $startseparator . $plotbtn . $endseparator;
    }
    $htmlrow .= $endrow;
    print $HTML "<H3>", $lineno, "</H3>\n";
    print $HTML $startrow;
    print $HTML "<td><a href=\"ivdatadir-" . $lineno
      . "/ivdata\"><img src=\"ivdatadir-"
      . $lineno
      . "/png/ivcurve.png\" alt=\"image\"></a></td>\n";
    print $HTML "<td><a href=\"ivdatadir-" . $lineno
      . "/ivdata\"><img src=\"ivdatadir-"
      . $lineno
      . "/png/ivcurve-resistance.png\" alt=\"image\"></a></td>\n";
    print $HTML "</tr></table><table><table border><tbody>";

    print $HTML $headingstring, $htmlrow;
    print $HTML "</table>";
    print $HTML "<p>";

    print $HTMLTABLE $htmlrow;
}

if ($latex) 
{
    tex_table_end ();
    print $HTMLTABLE <<END;
\\end{document}
END
}
else {
    foreach my $FH ($HTMLTABLE,$HTML)
{
    print $FH "</tbody></table></center>\n\n";
    print $FH start_form(-name=>'login_info',-action=>'/cgi-bin/celltest/multi_iv.cgi');
    print $FH hidden(-name=>'name');
    print $FH hidden(-name=>'pass');
    print $FH hidden(-name=>'time');
    print $FH hidden(-name=>'jscheck');
    print $FH hidden(-name=>'rig',-value=>$rigno,-force=>1);
    print $FH hidden(-name=>'session',-value=>$testno,-force=>1);
    print $FH hidden(-name=>'id',-value=>0,-force=>1);
    print $FH hidden(-name=>'filedata',-value=>'',-force=>1);
    print $FH end_form();

    print $FH <<END;

<script src='/celltest/RFCcontrol.js'></script>

<script>

function set_multiname(ivnr)
{
    document.login_info.id.value = ivnr;
    run_ajax('/cgi-bin/celltest/ajax_interface.cgi','&action=rig_iv_file&rig=$rigno&runnr=$testno&filenr='+ivnr,set_iv_data);
}

function set_iv_data(res)
{
    var arr = res.split("\\n");
    if (arr[0] == 'OK')
    {
	arr.shift();
	document.login_info.filedata.value = arr.join('\\n');
	document.login_info.submit();
	return true;
    }
    alert(res);
}

</script>
</body>
</html>
END

}
}

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

sub heading {
    $res="";
    $res = $res . $startrow;
    $res = $res . $startseparator . $endseparator;
    $res = $res . $startseparator . "start date" . $endseparator;
    $res = $res
      . $startseparator
      . $beginmulti
      . ptable( "Time", "h" )
      . $endmulti
      . $endseparator;

    $res = $res
      . $startseparator
      . $beginmulti
      . ptable( "Max", "A" )
      . $endmulti
      . $endseparator;
    my $ltemp = $templabel;
    $ltemp =~ s/_/ /g;
    $res = $res
      . $startseparator
      . $beginmulti
      . ptable( ucfirst($ltemp), "start", "stop", $startsup . $deg . $endsup . "C" )
      . $endmulti
      . $endseparator;
    my $lvolt = $voltlabel;
    $lvolt =~ s/_/ /g;
    $res = $res
      . $startseparator
      . $beginmulti
      . ptable( ucfirst($lvolt), "start", "stop", "mV" )
      . $endmulti
      . $endseparator;
    for my $gas (@gaslist)
    {
	my $gasst = ucfirst($gas);
	$gasst =~ s/_/ /g;
#	$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;
    }
    $res = $res
      . $startseparator
      . $beginmulti
      . ptable( "Rsec", "min", $omega . " cm" . $startsup . "2" . $endsup )
      . $endmulti
      . $endseparator;
    $res = $res
      . $startseparator
      . $beginmulti
      . ptable( "Rfu", $omega . " cm" . $startsup . "2" . $endsup )
      . $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 = $ivdir . "/ivtable.html"; 
    $htmlfile   = $ivdir . "/ivcurves.html";
    $nrowtable=10000;
    $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/hour";
}

sub latexsep {
    $htmltablefile    = $ivdir . "/ivtable.txttex";
    $htmltablefiletex = $ivdir . "/ivtable.tex";
    $htmltablefileps  = $ivdir . "/ivtable.ps";
    $htmlfile   = "/dev/null";
    $nrowtable=12;
    $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";
}

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

}

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