#!/usr/bin/perl

use strict;

$| = 1;

my @PSAP = split(/[:;,\s]+/, shift @ARGV);
my @CLAP = split(/[:;,\s]+/, shift @ARGV);
my @SCATTERING = split(/[:;,\s]+/, shift @ARGV);

my $header = <>;
chomp $header;
my @names = split(",", $header);

sub GenerateMapping {
    my @matches = @_;

    my @result;
    MATCH: foreach my $m (@matches) {
        for (my $i=0; $i<@names; $i++) {
            my $n=$names[$i];
            if ($n =~ /^$m$/) {
                push @result, $i;
                next MATCH;
            }
        }
    }
    return \@result;
}

my $BS = GenerateMapping(@SCATTERING);
exit 1 if (scalar(@{$BS}) == 0);

my @mapping = (
    GenerateMapping("Epoch", "EPOCH"),
    GenerateMapping(@PSAP),
    GenerateMapping(@CLAP)
);

exit 1 if (scalar(@{$mapping[1]}) == 0 || scalar(@{$mapping[2]}) == 0);


print "EPOCH,PSAP,CLAP\n";

sub Value {
    my ($fields, $map) = @_;
    foreach my $check (@{$map}) {
        my $v = $fields->[$check];
        if (defined($v) and $v ne "NA") {
            return $v;
        }
    }
    return undef;
}

sub fTr {
    my ($tr) = @_;
    return  1.0 / (1.0796 * $tr + 0.71);
}

my $fTr1 = fTr(1.0);
my $K1 = 0.02;
my $K2 = 1.22;

while (<>) {
    my @output = ("NA","NA","NA");

    chomp;
    my @fields = split(",");

    my $b = Value(\@fields, $BS);
    if (not defined($b) or $b eq "NA") {
        print join(",", @output) . "\n";
        next;
    }

    MAP: for (my $i=0; $i<@mapping; $i++) {
        foreach my $check (@{$mapping[$i]}) {
            my $v = $fields[$check];
            if (defined($v) and $v ne "NA") {
                if ($i > 0) {
                    $v = ($K2 * $v  + $K1 * $b) / 0.85 / $fTr1;
                }
                $output[$i] = $v;
                next MAP;
            }
        }
    }

    print join(",", @output) . "\n";
}
