#!/usr/bin/perl
#$Id: imp_multiplot_analytic.pl,v 1.5 2019/06/03 11:27:47 sqko Exp $
use strict;
use warnings;
use File::Copy qw/copy/;
my $rig = shift;
my $test = shift;
my $area = shift;
my $httpdconf = `/usr/bin/locate httpd.conf | grep 'conf\$' | grep etc`;
chomp $httpdconf;
my $html = `/bin/grep '^DocumentRoot' $httpdconf`;
exit unless ($html);
$html =~ /\"([\w\-\/\.]+)\"/;
$html = $1;
my $cgi = $html;
$cgi =~ s/html$/cgi-bin/;
my $cmd = $cgi.'/analytic/ajax_multi.cgi';


my @args = ();
push @args,'action=plot';
push @args,'ajax=1';
my $comm = <<END;
set ylabel %27-Z_{imag} ({/Symbol W} cm^2)%27
set xlabel %27Z_{real} ({/Symbol W} cm^2)%27
z(x) = x * $area
END
    chomp $comm;

$comm =~ s/\n/%0A/g;

push @args,'comm="'.$comm.'"';
push @args,'system=RFCcontrol';
push @args,'user=rig'.$rig;
push @args,'labels=decade';
push @args,'usersession='.$rig.'test'.$test;
push @args,'session='.$$;
push @args,'color=Monochrome';
push @args,'key=bottom';
my @files = ();
my @outfiles = ();
while (@ARGV)
{
    my $f = shift;
    push @outfiles,$f;
    my $file = $$.'_'.$f.'.data';
    my $label = shift;
    $label =~ s/\s/\\ /g;
    push @files,$file.':'.$label;
}
push @args,'filenames='.join(',',@files);
my $command = join(' ',$cmd,@args);
my $res = `$command`;
unless ($res && $res =~ /OK/)
{
    warn $res;
    exit;
}
$res =~ /(multiplot_\d+).png/;
my $psfile = $html.'/analytic/png/'.$1.'.ps';
my $pngfile = $html.'/analytic/png/'.$1.'.png';

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

foreach (@outfiles)
{
    s/\.i2b$//;
}
my $outfn = join('',@outfiles);
my $outps = $psdir.'/'.$outfn.'-impedance.ps';
my $outpng = $pngdir.'/'.$outfn.'-impedance.png';
copy($psfile,$outps);
copy($pngfile,$outpng);

## Bode plot


@args = ();
push @args,'action=plot';
push @args,'ajax=1';
$comm = <<END;
set ylabel %27-Z ({/Symbol W} cm^2)%27
z(x) = x * $area
END
    chomp $comm;

$comm =~ s/\n/%0A/g;

push @args,'comm="'.$comm.'"';
push @args,'system=RFCcontrol';
push @args,'user=rig'.$rig;
push @args,'labels=decade';
push @args,'usersession='.$rig.'test'.$test;
push @args,'session='.$$;
push @args,'mode=bode';
push @args,'color=Monochrome';
push @args,'filenames='.join(',',@files);
$command = join(' ',$cmd,@args);
$res = `$command`;
unless ($res && $res =~ /OK/)
{
    warn $res;
    exit;
}
$res =~ /(multiplot_\d+).png/;
$psfile = $html.'/analytic/png/'.$1.'.ps';
$pngfile = $html.'/analytic/png/'.$1.'.png';

foreach (@outfiles)
{
    s/\.i2b$//;
}
$outps = $psdir.'/'.$outfn.'-bode.ps';
$outpng = $pngdir.'/'.$outfn.'-bode.png';
copy($psfile,$outps);
copy($pngfile,$outpng);
