#!/usr/bin/perl
use AFM;

$VERSION = 0.11;
$PROGRAM = 'plot_iv_curves';

my $usernumber = $<;
my $username = &AFM::get_user_name($usernumber);


if ( scalar(@ARGV) < 1 ) {
    print 'Use: ivplot.pl $rig   $testno {"plotno label"}*
 where $rig is the rig number' . "\n";
    print '$testno is the test number' . "\n"
      . ' and {"plotno labels"} are linenumber in the ivtable-file, followed by the  quoted label for each curve'
      . "\n";
    exit 1;
}
my $debug = 0;

for(my $x = 0; $x < scalar(@ARGV); $x++)
{
    if ($ARGV[$x] =~ /--version/)
    {
	print "$PROGRAM is: $VERSION\n";
	exit 0;
    }
}

if ($ARGV[scalar(@ARGV)-1] =~ /--debug/)
{
    $debug = 1;
    pop @ARGV;
}


my $testusername = 'rig'.$ARGV[0];
if ($username ne $testusername)
{
    print "wrong user: $username !\n";
    print "To access data for rig $ARGV[0] you must be user rig$ARGV[0]!\n";
    exit 1;
}


$ii = 0;

if ( scalar(@ARGV) > 2 ) {
    for ( $i = 2 ; $i < scalar(@ARGV) ; $i += 2 ) {
        $ii++;
        $lineno[$ii] = $ARGV[$i];
        $namepart = $namepart . $ARGV[$i] . "-";
        $label[$ii] = $ARGV[ $i + 1 ];
    }
}

$GNUPLOT = '/usr/bin/gnuplot';

sub round {
    local ( $X, $a ) = @_;

    #    print x,a
    int( ( $X / $a ) + 0.5 ) * $a;
}


$nskip = 10;

$termtype  = "post portrait  enhanced color 10";
$pointsize = 1;
$rigno     = $ARGV[0];
if ( !&AFM::check_rig_nr($rigno) ) {
    print "Rig $rigno is not valid!\n";
    exit 1;
}

$awklocation = '/usr/local/bin/awk/';

my $testno = 0;

if ( scalar(@ARGV) > 1 ) {
    $ttestno = $ARGV[1];
    $ttestno =~ /(\d+)/;
    $testno = $1;
}
my $dir = $AFM::publicdir.'rig'.$rigno.'/'.$rigno.'test'.$testno.'/iv/';

if (!(-d $dir))
{
    my $command = "/bin/mkdir $dir";
    print $command,"\n" if ($debug);
    system($command);
}

$custumdir = $dir.'custom';
if (!(-d $custumdir))
{
    my $command = "/bin/mkdir $custumdir";
    print $command,"\n" if ($debug);
    system($command);
}
my $pngdir = $custumdir.'/png';
if (!(-d $pngdir))
{
    my $command = "/bin/mkdir $pngdir";
    print $command,"\n" if ($debug);
    system($command);
}
my $psdir = $custumdir.'/ps';
if (!(-d $psdir))
{
    my $command = "/bin/mkdir $psdir";
    print $command,"\n" if ($debug);
    system($command);
}
my $txtdir = $custumdir.'/txt';
if (!(-d $txtdir))
{
    my $command = "/bin/mkdir $txtdir";
    print $command,"\n" if ($debug);
    system($command);
}

$area = &AFM::get_config_value_old( $rigno, 'area' ,$testno);
$area = &AFM::get_usercv_test($rigno,$testno,'main','cell_area') unless ($area);

$htmllocation = $AFM::publicdir.'rig' . $rigno . "/" . $rigno . "test" . $testno;
$gpfilename = $htmllocation . "/iv/" . $namepart . "iv.gp";

open( GRAPH, "> $gpfilename" ) || die;

$plotfile = $htmllocation . "/jdata";
if ( !( -e ($plotfile) ) ) {
    print "$plotfile not found!!\n";
    exit 1;
}

$line = `head -1 $plotfile`;
@Fld  = split ( ' ', $line, 9999 );

for ( $i = 2 ; $i < $#Fld ; $i += 2 ) {

    $data{ $Fld[$i] } = $Fld[ $i + 1 ];
    $col{ $Fld[$i] }  = $i + 2

}

$ivtablefile = $htmllocation . "/iv/ivtable";
if ( !( -e ($ivtablefile) ) ) {
    print "$ivtablefile  not found!!\n";
    exit 1;
}

$psfilename  = $htmllocation . "/iv/custom/ps/" . $namepart . "iv.eps";
$pngfilename = $htmllocation . "/iv/custom/png/" . $namepart . "iv.png";
$txtfilename = $htmllocation . "/iv/custom/txt/" . $namepart . "iv.txt";

open(TXT, "> $txtfilename") or die "Could not open outputtextfile $txtfilename\n";

for ( $iloop = 1 ; $iloop <= $ii ; $iloop++ ) 
{
    $my_awkcmd = ''; 
    print $lineno[$iloop], " ", $label[$iloop], "\n";
    $cstr  = "awk 'NR==$lineno[$iloop]' $ivtablefile";
    $aline = `$cstr`;
    $aline =~ /tstart\s+([\d\.]+)/; 
    my $tstart = $1;
    print TXT "$label[$iloop]\n";
    print TXT "Time: $tstart    i-V curve: $lineno[$iloop]\n";
    my $sourceT = $dir.'ivdatadir-'.$lineno[$iloop].'/data/T_center';
    my $t = `/usr/bin/head -n 1 $sourceT`;
    $t =~ /\s+(\d+)/;
    my $t = $1;
    print TXT "Temperature: $t\n\n";
    @afld  = split ( ' ', $aline, 9999 );

    for ( $i = 0 ; $i < $#afld ; $i += 2 ) {

        $adata{ $afld[$i] } = $afld[ $i + 1 ];

        #    $acol{ $afld[$i] }  = $i + 1

    }

    if ($aline) {
        $nskip    = 1;
        $outfile  = "\'/dev/null\'";
        $term     = "dumb";
        $key      = "key";
        $title    = "notitle";
        $pltcmd   = "";
        $plottype = " lines lt $iloop";
        printgp();
        $nskip    = 10;
        $key      = "key";
#        $plottype = " points lt $iloop   pointsize $pointsize $iloop ";
        $plottype = " points lt $iloop pointsize $pointsize ";

        #    $title="title \"$label[$iloop]\"";
        $pltcmd = "";
        printgp();
        $pltcmd = "rep";

        $plottype = " linespoints lt $iloop pointsize $pointsize";
#        $plottype = " linespoints lt $iloop   pointsize $pointsize $iloop ";
        $title    = "title \"$label[$iloop]\"";
        $pltcmd   = "rep 1/0 $title w $plottype ";
        printgp();
    }
    $my_awkcmd =~ /(awk\s+.+\/jdata)/;
    $my_awkcmd = $1;
    $my_awkcmd =~ s/NR\%\(10\)/NR\%\(1\)/;
    $my_awkcmd = $my_awkcmd. ' | awk '."\'".'{print $';
    my $my_head = `/usr/bin/head -n 1 $plotfile`;  
    my @my_fields = split(/\s+/,$my_head);
    for (my $x = 2; $x < scalar(@my_fields); $x++)
    {  
        if ($my_fields[$x] =~ /current/)
        {
            $my_currentf = $x+2;
        }  
        if ($my_fields[$x] =~ /cell_voltage/)
        {
            $my_voltf = $x+2;
        }  
    }
    $my_awkcmd = $my_awkcmd. $my_currentf. "\"\\t\"\$". $my_voltf. "\}\'";
    print TXT "Current   Cell_Voltage\n";
    my $outstr = `$my_awkcmd`;
    print TXT $outstr;
    print TXT "\n\n\n";
}
$pltcmd  = "rep";
$outfile = "'" . $psfilename . "'";
$term    = $termtype;
printgp();
$cstr = "$GNUPLOT $gpfilename";
system($cstr);

$cstr =
"echo \"quit\" | /usr/bin/gs -q -sDEVICE=png256 -sOutputFile=$pngfilename  $psfilename > /dev/null";

#print $cstr;
system($cstr);

if ($debug)
{
    my $str = `/bin/cat $gpfilename`;
    print $str;
}
unlink $gpfilename;


sub printgp {
    if ($first) { $pl = "replot" }
    else { $pl = "plot" }
    $first++;
    if ( !($pltcmd) ) {
        $pltcmd =
          "$pl \"< awk 'NR>("
          . $adata{"nstart"}
          . "-1)&&NR%($nskip)==0;NR>("
          . $adata{"nstop"}
          . "-1){exit}' $plotfile\"  u ((\$"
          . $col{"current"}
          . ")/$area):"
          . $col{"cell_voltage"}
          . " $title "
          . "w  $plottype";
        ;
	$my_awkcmd = $pltcmd;
    }
    print GRAPH <<END;
set $key
set term $term 
set out $outfile
set nomulti
set lmargin 10
set rmargin 10
set bmargin 4
set size 1,0.5
set grid  linetype 5
set border 3
set xtics nomirror
set ytics nomirror
set ylabel "Cell voltage (mV)"
set xlabel "current density (A/cm^2)"
#set xr[0:]
#set yr[400:1100]
#set ytics 400,100,1100
#set yr[:1100]
set ytics 100
$pltcmd
END
}

