#!/usr/bin/perl
#$Id: hio_korr,v 1.10 2020/08/11 12:20:47 sqko Exp $
use strict;
use Math::Complex;
my @freq_korr;
my @data_corr;
my @freq;
my @data;
my $line         = 0;
my $headerlines  = 7;
my $freq_abs_tol = 0.001;
my $freq_rel_tol = 0.1;
my $freq_switch  = 1.0;
my $freq_ok;

if ( $#ARGV < 2 ) {
    print
"usage: hio_korr mode korrection_data data_to_be corrected [.  .  . more  data_to_be corrected] \n";
    print "Where mode is either A for addition or, S for subtraction M for multiplication or D for division\n";
    exit;
}
my $mul = 0; 
if ($ARGV[0] =~ /M/i)
{
    $mul = 1
}
my $sup = 0;
if ($ARGV[0] =~ /S/i)
{
    $sup = 1;
}
my $div = 0;
if ($ARGV[0] =~ /D/i)
{
    $div = 1;
}
my %corr = ();
my %dat = ();

open( INPUT, '<', $ARGV[1] );
while (my $st = <INPUT>) {
    next unless ($st =~ /^[\s\t\d\.\+\-eE]+$/);
    $st =~ s/^\s*//;
    my @res = split (/[\s\t]+/, $st );
    next unless (@res > 2);
    $line++;
    $freq_korr[$line] = $res[0];
    $data_corr[$line] = cplx($res[1]+0,$res[2]+0);
    $corr{$freq_korr[$line]} = $data_corr[$line];
}
### Sort compensation data ###
my @cor = ();
foreach my $f (reverse sort {$a <=> $b} keys %corr)
{
    my %h = ();
    $h{'freq'} = $f;
    $h{'imp'} = $corr{$f};
    push @cor, \%h;
}

for ( 2 .. $#ARGV ) {
    %dat = ();
    $line = 0;
    open( INPUT,  '<', $ARGV[$_] );
    my $outputf = $ARGV[$_];
    if ($outputf =~ /\.i2b$/)
    {
	$outputf =~ s/\.i2b$/_cor\.i2b/;
    }
    else
    {
	$outputf = $outputf . '.out';
    }
    my $found = 0;
    open( OUTPUT, '>', $outputf);
    while (my $st = <INPUT>) {
	chomp $st;
	$st =~ s/^\s*//;
	unless  ($st =~ /^[\s\t\d\.\+\-eE]+$/)
	{
	    print OUTPUT $st,"\n" unless ($found);
	    next;
	}
	my @res = split (/[\s\t]+/, $st );
	if (@res < 3)
	{
	    print OUTPUT $st,"\n";
	    next;	    
	}
	next unless (@res > 2);
	$found = 1;
	$line++;
	$freq[$line] = $res[0];
	$data[$line] = cplx($res[1]+0,$res[2]+0);
	$dat{$freq[$line]} = $data[$line];
    }
    my $fline = 0;    
    foreach my $f (reverse sort {$a <=> $b} keys %dat)
    {
	my $fline = &get_fline($f);
	## Only process lines where the frequencies are ok 
	## that is abs(ln(f_measure) - ln(f_corr)) < 0.01 
	if (defined $fline) 
	{
	    my $result = cplx(0,0);
	    my $d = $dat{$f};
	    my $c = $cor[$fline]{'imp'};
	    unless ($mul || $div)
	    { 
		if ($sup)
		{
		    $result = $d - $c;
		}
		else
		{
		    $result = $d + $c;
		}
	    }
	    if ($mul)
	    {
		$result = $d * $c;
	    }
	    if ($div)
	    {
		$result = $d / $c;
	    }
	    print OUTPUT sprintf("%.6g  %.5g  %.5g\n",$f,Re($result),Im($result));
	}
	$fline++;
    }
}


sub get_fline($)
{
    my $f = shift;
    return undef unless ($f > 0);
    my $logf = log($f);
    my $fline = undef;
    for (my $x = 0; $x < @cor; $x++)
    {
	my $logcf = log($cor[$x]{'freq'});
	if (abs($logcf - $logf) < 0.01)
	{
	    $fline = $x;
	    last;
	}
    }
    return $fline;
}
