#!/usr/bin/perl
# $Id: rplot.pl,v 1.4 2016/04/18 11:32:25 sqko Exp $


my $VERSION = 0.2;
my $PROGRAM = 'rplot.pl';

use AFM;


my $GNUPLOT = &AFM::get_config_global('GNUPLOT','location');
#$GNUPLOT   = '/usr/bin/gnuplot';
$CONVERT   = '/usr/bin/convert';

$xlabel = "Current, A/cm^2";
$key    = " nokey";
$ncol   = 3;
$rigno  = 0;
my $debug = 0; 
my $usexmin = 1;
for my $teststr (@ARGV) {
    if ( $teststr =~ /--version/ ) {
        print "$PROGRAM is: $VERSION\n";
        exit;
    }
    if ( $teststr =~ /--debug/ )
    {
	$debug = 1; 
    }
    if ( $teststr =~ /--nozero/)
    {
	$usexmin = 0;
    }
}

if ( scalar(@ARGV) < 4 ) {
    print "Usage: $PROGRAM rignr testnr [iv_curvenr \"label\"]\n";
    exit;
}

if ( scalar(@ARGV) > 3 ) {
    for ( $i = 2 ; $i < $#ARGV ; $i += 2 ) {
        print "using iv-curve ",$ARGV[$i], "  with label \'$ARGV[$i+1]\'\n";
        push ( @ivnumbers, $ARGV[$i] );
        push ( @ivlabels,  $ARGV[ $i + 1 ] );

    }
}

my $usernumber   = $<;
my $username     = &AFM::get_user_name($usernumber);
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;
}

if ( scalar(@ARGV) > 0 ) 
{
    $rigno = $ARGV[0];
    $rigno =~ /(\d+)/;
    $rigno = $1;
}
if ( !&AFM::check_rig_nr($rigno) ) 
{
    die "Error: $rigno is not a valid rignumber!\n";
}
my $debug = 0;
if ($ARGV[scalar(@ARGV)-1] =~ /--debug/)
{
    $debug = 1;
    pop @ARGV;
}
$gsize       = "1,0.44"; # 0.7,0.35";
$psize       = "1,0.5";
$idat        = 0;
$awklocation = "/usr/local/bin/awk/";


our $testno = 1;
my $ivno   = 1;

if ( scalar(@ARGV) > 1 ) 
{
    $ttestno = $ARGV[1];
    $ttestno =~ /(\d+)/;
    $testno = $1;
}
$currenttest = $testno;

if ( scalar(@ARGV) > 2 ) 
{
    $ivno = $ARGV[2];
    $ivno =~ /(\d+)/;
    $ivno = $1;
}

my $dir = $AFM::publicdir.'rig'.$rigno.'/'.$rigno.'test'.$testno.'/iv/';

if (!(-e($dir)))
{
    exit;
}

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

my $pltcmdR_s = "plot ";
my $pltcmdASR = "plot ";
$outpsR_s = 'R_s_vs_I';
$outpsASR = 'ASR_vs_I';
@tmpfilesASR = ();
@tmpfilesR_s = ();
@tempt = ();
for (my $i = 0; $i < scalar(@ivnumbers); $i++)
{
    my $sourceT = $dir.'ivdatadir-'.$ivnumbers[$i].'/data/T_center';
    my $t = `/usr/bin/head -n 1 $sourceT`;
    $t =~ /\s+(\d+)/;
    my $t = $1;
    $tempt[$i] = $t;
    my $sourceR_s = $dir.'ivdatadir-'.$ivnumbers[$i].'/data/R_secant';
    my $sourceC = $dir.'ivdatadir-'.$ivnumbers[$i].'/data/current';
    my $sourceASR = $dir.'ivdatadir-'.$ivnumbers[$i].'/data/ASR_corr';
    $outpsASR = $outpsASR . "_$ivnumbers[$i]";
    $outpsR_s = $outpsR_s . "_$ivnumbers[$i]";
    push @tmpfilesASR , "/tmp/".$$.'ASR_'.$i.'.dat';
    push @tmpfilesR_s , "/tmp/".$$.'R_s_'.$i.'.dat';
    &convert($tmpfilesASR[$i],$sourceC,$sourceASR);
    &convert($tmpfilesR_s[$i],$sourceC,$sourceR_s);
    $pltcmdR_s = $pltcmdR_s."\'".$tmpfilesR_s[$i]."\' u 2:\(f\(\$4\)\) tit \"$ivlabels[$i]\" w linesp ,";     
    $pltcmdASR = $pltcmdASR."\'".$tmpfilesASR[$i]."\' u 2:\(f\(\$4\)\) tit \"$ivlabels[$i]\" w linesp ,"; 
}

my @psfiles = ();
my @pnuplotfiles = ();

$pltcmdR_s =~ s/ ,$//;
$pltcmdASR =~ s/ ,$//;
#print $pltcmdR_s,"\n" if ($debug);
#print $pltcmdASR,"\n" if ($debug);

$term    = "post portrait enhanced color";
$reset   = "reset";

$pltcmd = $pltcmdASR;
$gpfile = $custumdir.'/'.$outpsASR.'.gp';
push @gnuplotfiles, $gpfile;
open( GRAPH, "> $gpfile" );
$outfile = $psdir.'/'.$outpsASR.'.ps';
printgp();
$command = "$GNUPLOT $gpfile";
system($command);
push @psfiles, $outfile;
if ($debug)
{
    print "\n\nASR plot\n\n";
    my $str = `/bin/cat $gpfile`;
    print $str;
}
unlink $gpfile;

$pltcmd = $pltcmdR_s;
$gpfile = $custumdir.'/'.$outpsR_s.'.gp';
push @gnuplotfiles, $gpfile;
open( GRAPH, "> $gpfile" );
$outfile = $psdir.'/'.$outpsR_s.'.ps';
printgp();
$command = "$GNUPLOT $gpfile";
system($command);
push @psfiles, $outfile;
if ($debug)
{
    print "\n\nR_sek plot\n\n";
    my $str = `/bin/cat $gpfile`;
    print $str;
}
unlink $gpfile;

my $outtxt = $txtdir.'/'.$outpsASR.'.txt';
open OUT, "> $outtxt";
for (my $x=0; $x < scalar(@tmpfilesASR);$x++)
{
    print OUT "\n",$ivlabels[$x];
    my $cmd = "head -n 1 $tmpfilesASR[$x]";
    my $header = `$cmd`;
    $header =~ /([\d\.]+)/;
    my $st = "Time: $1     i-V curve: $ivnumbers[$x]";
    print OUT "\n",$st;
    print OUT "\nTemperature: $tempt[$x]\n";
    $cmd = "cat $tmpfilesASR[$x] | awk \'\{print \$2\"\t\"\$4\}\'";
    my $res = `$cmd`;
    print OUT "\nCurrent density   ASR_FU\n",$res;
}
close(OUT);
$outtxt = $txtdir.'/'.$outpsR_s.'.txt';
open OUT, "> $outtxt";
for (my $x = 0; $x < scalar(@tmpfilesR_s); $x++)
{
    print OUT "\n",$ivlabels[$x];
    my $cmd = "head -n 1 $tmpfilesASR[$x]";
    my $header = `$cmd`;
    $header =~ /([\d\.]+)/;
    my $st = "Time: $1     i-V curve: $ivnumbers[$x]";
    print OUT "\n",$st;
    $cmd = "cat $tmpfilesR_s[$x] | awk \'\{print \$2\"\t\"\$4\}\'";
    my $res = `$cmd`;
    print OUT "\nCurrent density   R_sekant\n",$res;
}
close(OUT);


for my $files (@tmpfilesASR)
{
    unlink($files);
}
for my $files (@tmpfilesR_s)
{
    unlink($files);
}
for my $files (@gnuplotfiles)
{
    unlink($files);
}

for my $files (@psfiles)
{
    my $source = $files;
    my $target = $files;
    $target =~ s/\/ps\//\/png\//;
    $target =~ s/\.ps/\.png/;
    $command = "/usr/local/bin/ps2png $source $target";
#    print $command,"\n" if ($debug);
    system($command);
}

exit;




sub convert($$$)
{
    $area = &AFM::get_usercv_test($rigno,$testno,'main','cell_area');
    $area = &AFM::get_config_value_old($rigno,'area',$testno) unless ($area);
    my $outfile = $_[0];
    my $current = $_[1];
    my $asr = $_[2];
    open (CURR ,"$current") or die "could not open current file $file.\n";
    open (ASR ,"$asr") or die "Could not open resistance file $file.\n";
    open (OUT ,"> $outfile") or die "could not open output file $file\n";
    while (!eof(CURR))
    {
	my $test = <CURR>;
	chomp $c;
	$test =~ /([\d\.]+)\s+([\d\.\-]+)/;
	my $t = $1;
	my $c = $2;
	$c = $c/$area;
	my $r = <ASR>;
	chomp $r;
	my $string = "$t $c $r\n";
	print OUT $string;
    }
    close(OUT);
    close(ASR);
    close(CURR);
}




sub printgp 
{
    my $yrange = '';
    if ($usexmin)
    {
	$yrange = 'set yr[0:]';
    }
    
    print GRAPH <<END;
    $reset
f(x)=x!=-32768?x:1/0
set term $term
set out \'$outfile\'
set nomulti
set ylabel "Area specific resistance ({/Symbol W} cm^2)"
set lmargin 12
set rmargin 10
set bmargin 4
set size $gsize
set grid  linetype 5
set border 3
set xtics nomirror
set ytics nomirror
set xlabel \"$xlabel\"
set au
#set xr[0:]
$yrange
$pltcmd
END
}
