#!/usr/bin/perl
# $Id: impedance_plot.pl,v 1.3 2016/03/10 09:09:55 sqko Exp $
use RFC::Rig;
use RFC::Main;
use RFC::Header;
#use AFM;

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

my $rig = RFC::Rig->new(shift);
$rig->check_run();
my $test = shift;
if ($test =~ /(\d+)/)
{
    $test = $1;
}
else
{
    $test = 0;
}
$test = $rig->session if ($test > $rig->session || !$test);

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

my $datafile = $homedir . shift;
my @filename = ();
$datafile =~ /\/([\w\.\-\:\+]+)\.(\w+)$/;
$filename[0] = $1;
$filename[1] = $2;
my $fileid = $filename[0];
my $gpfile = $homedir.$fileid . ".gp";
open GPFILE,'>',$gpfile  or die "could not open $gpfile for writing $!\n";
open DATAFILE,'<', $datafile or die die "could not open $datafile for reading $!\n";
@data = <DATAFILE>;
my @freq = ();
my @real = ();
my @imag = ();
my $ndata;
for ( $i = 0 ; $i <= $#data ; $i++ ) {
    @col = split ( " ", $data[$i] );
    if ( $i == 6 ) { $ndata = $col[0]; }
    if ( $i > 6 ) {
        $freq[$i] = $col[0];
        $real[$i] = $col[1];
        $imag[$i] = $col[2];
    }
}

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

print GPFILE "\nset yla '-Z imaginary ({/Symbol W})\'\n";
print GPFILE "set xla 'Z real ({/Symbol W})\'\n";

print GPFILE "set term ", RFC::Main::get_cv( "GNUPLOT", 'postportterm' ),"\n";

print GPFILE "set yr[$ymin:$ymax]\n";
print GPFILE "set size ratio -1\n";

print GPFILE "set xr[0:]\n";

print GPFILE "set out \'$psdir" . "/" . "$fileid" . "-impedance.ps\'\n";

print GPFILE "plot \"<awk 'NR>6&&NF>1' $datafile\"  u 2:(-\$3) tit ''\n";
print GPFILE "reset\n";
print GPFILE "set term ". &RFC::Main::get_cv( "GNUPLOT", 'postportterm' ).  "\n";

print GPFILE "set size ". &RFC::Main::get_cv( "GNUPLOT", 'postportsize' )."\n";

print GPFILE "set au; set log;\n";
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 \"<awk 'NR>6&&NF>1' $datafile\" u 1:(\$3<0?-\$3:1/0) tit '-Z imag' w linesp,''  u 1:(\$3>0?\$3:1/0) tit 'Z imag' w linesp,'' u 1:(\$2) tit 'Z real' w linesp\n";
close(GPFILE);
my $cstr = "$GNUPLOT $gpfile";

system($cstr);

for ( "-bode", "-impedance" ) {

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

}

unlink($gpfile);

exit;


sub numerically { $a <=> $b }

