#!/usr/bin/perl

use strict;

$| = 1;

my @PSAP = split(/[:;,\s]+/, shift @ARGV);
my @CLAP = 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 @mapping = (
    GenerateMapping("Epoch", "EPOCH"),
    GenerateMapping(@PSAP),
    GenerateMapping(@CLAP)
);

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


print "EPOCH,PSAP,CLAP\n";

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

    chomp;
    my @fields = split(",");
    MAP: for (my $i=0; $i<@mapping; $i++) {
        foreach my $check (@{$mapping[$i]}) {
            my $v = $fields[$check];
            if (defined($v) and $v ne "NA") {
                $output[$i] = $v;
                next MAP;
            }
        }
    }

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