#!/usr/bin/perl

use strict;

$| = 1;

my $STN = shift @ARGV;
my @BaB_PSAP = split(/[:;,\s]+/, shift @ARGV);
my @BaB_CLAP = split(/[:;,\s]+/, shift @ARGV);
my @BaG_PSAP = split(/[:;,\s]+/, shift @ARGV);
my @BaG_CLAP = split(/[:;,\s]+/, shift @ARGV);
my @BaR_PSAP = split(/[:;,\s]+/, shift @ARGV);
my @BaR_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(@BaB_PSAP),
    GenerateMapping(@BaB_CLAP),
    GenerateMapping(@BaG_PSAP),
    GenerateMapping(@BaG_CLAP),
    GenerateMapping(@BaR_PSAP),
    GenerateMapping(@BaR_CLAP)
);


print "STN,EPOCH,BaB_PSAP,BaB_CLAP,BaG_PSAP,BaG_CLAP,BaR_PSAP,BaR_CLAP\n";

while (<>) {
    my @output = ($STN,"NA", "NA","NA","NA","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";
}
