#!/usr/bin/perl
# $Id: impedance_multiplot.pl,v 1.2 2013/08/12 09:21:02 sqko Exp $
use AFM;
use strict;
use Carp; 

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

if ( scalar(@ARGV) < 5 )
{
    print "\nImpedance_multiplot.pl plots multiple impedance files in one plot\n\n";
    print 'Usage:',"\n",'impedance_multiplot.pl rigno testno factor[opt. ASR opt DEC$number opt lines opt bottom] [file1 "label1"] ...',"\n\n";
    print 'where rigno is the rig number testno is the',"\n";
    print 'test number, factor is the scaling factor and if ASR is included',"\n";
    print 'in the factor (ex. 16ASR) the figure uses area specific resistance',"\n";
    print "instead of just resistance on the axes.\n";
    print "If the DEC\$number option is used (eg DEC4) a number of the points\n";
    print "in the impedance plots are labeled with frequency. The \$number \n";
    print "Determines how many points are plotted\n";
    print "If the 'lines' option is used, the plot is with lines and if the\n";
    print "'bottom' option is used, the legend is placed at the bottom\n\n\n";
    exit 1;
}

my @lt = (-1,1,3,8,7,-1,1,3,8,7,-1,1,3,8,7,-1,1,3,8,7,-1,1,3,8,7);
my $lengthinput = scalar(@ARGV);
my $BV = 0;

if ($ARGV[$lengthinput-1] =~ /--BV/)
{
    pop @ARGV;
    $BV = 1;
    @lt = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
}

my $tmpstr = $ARGV[0];
if ( $tmpstr =~ /^([-\@\w.]+)$/ ) { $tmpstr = $1 }
my $rig = $tmpstr;

&check_run($rig);

$tmpstr = $ARGV[1];
if ( $tmpstr =~ /^([-\@\w.]+)$/ ) { $tmpstr = $1 }
my $test = $tmpstr;

$tmpstr = $ARGV[2];
$tmpstr =~ /^([\d\.]+)/;
my $factor = $1;
my $label = '{/Symbol W}';
if ($tmpstr =~ /ASR/)
{
    $label = '{{/Symbol W}cm^2}';
}
my $showdecade = 0;
if ($tmpstr =~ /DEC\d/)
{
    $tmpstr =~ /DEC(\d)/;
    $showdecade = $1+1;
}
my $lines = '';
if ($tmpstr =~ /lines/)
{
    $lines = 'with lines';
}
my $bottom = 0;
if ($tmpstr =~ /bottom/)
{
    $bottom = 1;
}

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

my $fileid = '';

my $gpfile = '/tmp/multiimp'.$$ . ".gp";
my $t = 0;
my @freq = ();
my @real = ();
my @imag = ();
my @DEClist = ();
my $totalp = 1;
my %freqlst = ();


for (my $x = 3; $x < scalar(@ARGV); $x+=2)
{
    my $datafile = $homedir.$ARGV[$x];
    $datafile =~ /([\w\.\-\:]+)\.\w+\s*$/;
    $fileid = $fileid . $1;
    open DATAFILE , '<' , $datafile or die "could not open $datafile\n";
    my @data = <DATAFILE>;
    close DATAFILE;
    my $fr = 0;
    my $count = 0;
    if ($x == 3)
    {
	$totalp = scalar(@data)-6;
    }
    for (my $i = 7 ; $i <= $#data ; $i++ ) 
    {

	my @col = split ( " ", $data[$i] );
	$freq[$t] = $col[0];
	$real[$t] = $col[1] * $factor;
	$imag[$t] = -$col[2] * $factor;
	$t++;
	if ($showdecade)
	{
	    if ($count > ($totalp/$showdecade))
	    {
		push @DEClist, $data[$i];
		chomp $data[$i];
		$count = 0;
		$freqlst{$fr} = $freqlst{$fr} . $data[$i].'#';
		$fr++;
		}
	}
	$count++;
    }
}

my @FRQL = ();
my @FRQh = ();
my $totalfiles = (scalar(@ARGV) - 4)/2;
for (my $count = 0; $count < $totalfiles  ; $count++)
{
    for (my $x = 0; $x < $showdecade-1; $x++) 
    {
	my @l = split(/\#/,$freqlst{$x});
	my $teststr = $l[$count];
	$teststr =~ s/^\s*//;
	my ($freq,$real,$imag) = split(/\s+/,$teststr);
	$freq += 0;
	$real += 0;
	$imag += 0;
	if (!defined($FRQh[$x])) {$FRQh[$x] = $freq};
	if ($FRQh[$x] != $freq) 	
	{
	    warn "Frequency ranges does not match!!\n";
	}
	$FRQL[$count] = $FRQL[$count] . "$real $imag ";
    }
}

my $rfactor = 1;
my @sortedreal = sort numerically @real;
my @sortedimag = sort numerically @imag;
my $imagrange  = $sortedimag[$#sortedimag] - $sortedimag[$0];
my $realrange  = $sortedreal[$#sortedreal] - 0;
my $ymin       = ($sortedimag[0] - 0.1 * $realrange)* $rfactor;
my $ymax       = ($sortedimag[0] + 0.6 * $realrange)* $rfactor;

my $decadefile = '/tmp/decade'.$$.'.txt';
if ($showdecade)
{
    open OUT, "> $decadefile" or die "Could not open decadefile $decadefile!\n";
    for (my $x = 0; $x < scalar(@FRQL); $x++)
    {
	print OUT $FRQL[$x],"\n";
    }
    close OUT;
}

open( GPFILE,   ">$gpfile" )  || die "could not open $gpfile\n";
print GPFILE "\nset yla '-Z imaginary ($label)\'\n";
print GPFILE "set xla 'Z real ($label)\'\n";
my $term = &AFM::get_config_global( "GNUPLOT", 'postportterm' );
if ($BV)
{
    $term =~ s/color\s*//;
}
print GPFILE "set term ", $term, "\n";
print GPFILE "set size 1,0.42\n";
print GPFILE "set yr[$ymin:$ymax]\n";
print GPFILE "set xr[0:]\n";
if ($bottom) 
{
    print GPFILE "set key bottom\n";
}
print GPFILE "set out \'$psdir" . "/" . "$fileid" . "-impedance.ps\'\n";
print GPFILE "plot ";
my $c = 0;
for (my $x = 3;$x < scalar(@ARGV); $x+=2)
{
    my $datafile = $homedir . $ARGV[$x];
    my $tit = $ARGV[$x+1];
    print GPFILE "\"<awk 'NR>6&&NF>1' $datafile\"  u (\$2>0?\$2*$factor:1/0):(-\$3*$factor) tit '$tit' $lines lt $lt[$c]";
    $c++;
    print GPFILE ", " unless ((!$showdecade) && ($x > scalar(@ARGV)-3));
}
if ($showdecade)
{
    for (my $x = 0; $x < scalar(@FRQh); $x++)
    {
	my $xcol = $x*2+1;
	my $ycol = $x*2+2;
	my $fr = $FRQh[$x]+0;
	my $tit = '';
	if ($fr > 100)
	{
	    $fr = $fr/1000;
	    if ($fr =~ /^(\d\d\d+)\./){$fr = $1+0};
	    if ($fr =~ /^(\d\d\d\.)\d*/){$fr = $1+0};
	    if ($fr =~ /^(\d\d\.)\d*/){$fr = $1+0};
	    if ($fr > 5)
	    {
		if ($fr =~ /^(\d\.)\d*/){$fr = $1+0};
	    }
	    elsif ($fr > 1)
	    {
		if ($fr =~ /^(\d\.\d)\d*/){$fr = $1+0};
	    }
	    if ($fr > 0.5)
	    {
		if ($fr =~ /^(0\.\d)\d*/){$fr = $1+0};
	    }
	    else
	    {
		if ($fr =~ /^(0\.\d\d)\d*/){$fr = $1+0};
	    }
	    $tit = "$fr kHz";
	}
	else
	{
	    if ($fr =~ /^(\d\d\d+)\./){$fr = $1+0};
	    if ($fr =~ /^(\d\d\d\.)\d*/){$fr = $1+0};
	    if ($fr =~ /^(\d\d\.)\d*/){$fr = $1+0};
	    if ($fr > 5)
	    {
		if ($fr =~ /^(\d\.)\d*/){$fr = $1+0};
	    }
	    elsif ($fr > 0.5)
	    {
		if ($fr =~ /^(\d\.\d)\d*/){$fr = $1+0};
	    }
	    if ($fr > 0.5)
	    {
		if ($fr =~ /^(0\.\d)\d*/){$fr = $1+0};
	    }
	    else
	    {
		if ($fr =~ /^(0\.\d\d)\d*/){$fr = $1+0};
	    }
	    $tit = "$fr Hz";	    
	}
	print GPFILE " \"$decadefile\" u (\$$xcol>0?\$$xcol*$factor:1/0):(-\$$ycol*$factor) tit '$tit' lt $lt[$c]";
	$c++;
	print GPFILE ", " unless ($x > scalar(@FRQh) -2);
    }

}
print GPFILE "\n";
##### Bodeplot ###
my $maxlogy = int(log($ymax*$factor)/log(10)+2);
$maxlogy = 10**$maxlogy;
my $minlogy = $maxlogy / 1000000;
print GPFILE "set au; set log;\n";
print GPFILE "set yrange [$minlogy:$maxlogy]\n" unless ($bottom);
print GPFILE "set out \'$psdir" . "/" . "$fileid" . "-bode.ps\'\n";
print GPFILE "set yla 'Z ({/Symbol W})\'\n";
print GPFILE "set xla 'Frequency (Hz)\'\n";
print GPFILE "plot ";
$c = 0;
for (my $x = 3;$x < scalar(@ARGV); $x+=2)
{
    my $datafile = $homedir . $ARGV[$x];
    my $tit = $ARGV[$x+1];
    print GPFILE "\"<awk 'NR>6&&NF>1' $datafile\"  u 1:(\$3<0?-\$3*$factor:1/0) tit '$tit -Z_\{imag\}' $lines lt $lt[$c], '' u 1:(\$3>0?\$3*$factor:1/0) tit '$tit Z_\{imag\}' $lines lt $lt[$c+1], '' u 1:(\$2*$factor) tit '$tit Z_\{real\}' $lines lt $lt[$c+2]";
    $c += 3;
    print GPFILE ", " unless ($x > scalar(@ARGV)-3);
}
print GPFILE "\n";
close(GPFILE);
my $cstr = "$GNUPLOT $gpfile";
system($cstr);

for ( "-impedance" ) {

    $cstr =
      "/usr/local/bin/ps2png  $psdir" . "/" . $fileid . $_
      . ".ps $pngdir" . "/"
      . $fileid
      . $_ . ".png ";
system($cstr);

}

unlink($gpfile);

if ($showdecade)
{
    unlink $decadefile;
}
exit;


sub numerically 
{
  $a <=> $b;
}

