#!/usr/bin/perl
# $Id: plot_current_imp.pl,v 1.3 2011/01/05 11:49:38 sofc Exp $
use strict;
use warnings;
use AFM;
my $VERSION = 0.2;
my $PROGRAM = 'plot_current_imp.pl';
my $GNUPLOT = &get_cv('GNUPLOT','location');
my $type = &get_cv('GNUPLOT','impedance_time_plot_type');
$type = 'points' unless ($type);
for my $string (@ARGV)
{
    if ($string =~ /--version/)
    {
        warn "$PROGRAM is: $VERSION\n";
        exit;
    }
}
#### Get rig and test numbers and exit if wrong user ####
my $rig = shift;
&check_run($rig);
my $testno = 1;
if ( scalar(@ARGV) > 0 )
{
    my $ttestno = shift;
    $ttestno =~ /(\d+)/;
    $testno = $1;
}
#### Get frerquency array for plot ###
my @freqs = ();
for (my $x = 0; $x < @ARGV-1; $x++)
{
    if ($ARGV[$x] =~ /--freqs/)
    {
	my $str = $ARGV[$x+1];
	@freqs = split(/\:/,$str);
    }
}
if (!@freqs)
{
    my $str = &get_cv('impedance','current_plot_frequencies');
    chomp $str;
    @freqs = split(/\:/,$str);
}
## End get freq array ####

my $homedir =  $AFM::publicdir . 'rig' . $rig . "/" . $rig . "test" . $testno  . "/impedance/";
my $psdir  = $homedir . "ps";
my $pngdir = $homedir . "png";
if ( !( -d $psdir ) )  { system("mkdir $psdir") }
if ( !( -d $pngdir ) ) { system("mkdir $pngdir") }

my $file = $homedir.'imp_data';
exit unless (-e($file));
open MYIN ,'<', $file or die "Could not open file $file\n";
my @list = <MYIN>;
close MYIN;
my @isok = ();
for (my $x = 0; $x < @list; $x++)
{
    $list[$x] =~ /Current:([\-\d\.]+)/;
    my $c = $1+0;
    $c = abs($c);
    push @isok,$x if (($c > 1) || ($c < -1)) ;
}
### Exit if no impedance at current was found ###
exit if (@isok < 1);
### Open datafile ###
my $fid = '/tmp/'.$$.'.txt';
open OUT ,'>', $fid or die "Could not open file $fid for writing!\n";
my $str = join(" ",@freqs);
print OUT "Frequencies: ",$str,"\n";
### Add extra 0 to frequencylist to awoid indefined values ###
push @freqs,0;
### Print impedance data to datafile ###
for my $x (@isok)
{
    $list[$x] =~ /^\s*([\w\.\-]+)/;
    my $f = $homedir.$1;
    if (-e($f))
    {
	$list[$x] =~ /Time:(\d+)/;
	print OUT $1;
	my @l = `/bin/cat $f`;
	my $start = 0;
	my $y = 0;
	my $case = 0;
	my $index = 0;
	my $end = 0;
	while($y < @l)
	{
	    my $str = $l[$y];
	    $str =~ s/^\s+//;
	    if ($case == 0)
	    {
		if ($str =~ /^\d+\s*$/)
		{
		    $y++;
		    $str = $l[$y];
		    $str =~ s/^\s+//;
		    my @n = split(/[\s\t]+/,$str);
		    print OUT " ",$n[1];
		    $case = 1;
		}
		$y++;
	    }
	    if ($case == 1)
	    {
		if ($str =~ /\d+/)
		{
		    my @n = split(/[\s\t]+/,$str);
		    if ($n[0] < $freqs[$index])
		    {
			print OUT " ",$n[1];
			$index++;
		    }
		}
		$y++;
	    }
	}
	$y = @l;
	while ($y && !$end)
	{
	    $y--;
	    my $str = $l[$y];
	    if ($str =~ /\d+/)
	    {
		my @n = split(/[\s\t]+/,$str);
		if ($n[0] > 0)
		{
		    print OUT " ",$n[1];
		    $end = 1;
		}
	    }	    
	}
	print OUT "\n";
    }
}
close OUT;
### End datafile ###

my $area = &AFM::get_usercv_test($rig,$testno,'main','cell_area')+0;
$area = &AFM::get_config_value_old($rig,'area',$testno)+0 unless ($area);
die "No cell area could be found !\n" unless ($area);
$file = 'impedance_vs_time';
my $outfile = $psdir.'/'.$file.'.ps';
my $term = &get_cv( "GNUPLOT", 'postportterm' );
$term =~ s/color\s*//;

### Write gnuplot command file ###
my $gid = '/tmp/'.$$.'.gp';
open GP ,'>', $gid or die "Could not open file $gid for writing!\n";
print GP "set term $term\n";
print GP "set size 1,0.42\n";
print GP "set out '$outfile'\n";
print GP "set yrange [0:]\n";
print GP "set yla 'Z_{real} ({/Symbol W}cm^2)\'\n";
print GP "set xla 'Time (h)'\n";
print GP "plot \"<awk 'NR>1' $fid\" u 1:(\$2*$area) tit 'F_{max}' with $type";
for (my $x = 1; $x < @freqs; $x++)
{
    my $y = $x+2;
    print GP ", '' u 1:(\$$y*$area) tit '$freqs[$x-1] Hz' with $type";
}
my $y = @freqs+2;
my $x = $y-2;
print GP ", '' u 1:(\$$y*$area) tit 'F_{min}' with $type\n";
close GP;

### Run gnuplot ###
my $cstr = "$GNUPLOT $gid";
system($cstr);

### Convert to png ###
my $pngfile = $pngdir.'/'.$file.'.png';
$cstr = "/usr/local/bin/ps2png  $outfile $pngfile";
system($cstr);

### Remove temporary files ###
unlink $fid;
unlink $gid;
exit;


