#!/usr/bin/perl -w
# maps A.th. expression data to gene loci, writes to file, and sorts
use strict;
use Data::Dumper;

my %gene_list;

open GENES,$ARGV[0];
readline GENES;

while (<GENES>) {
	chomp;

	$_ =~ s/\s+$//; # rtrim whitespace
        $_ =~ s/^\s+//; # ltrim whitespace

	$gene_list{$_} = "";
}

close GENES;

#print Dumper(\%gene_list) . "\n\n";

open EXPR, $ARGV[1];
readline EXPR;

while (<EXPR>) {
	#print uc($_);
	chomp;
	my @expr_ary = split('\t',$_);

	$expr_ary[0] =~ s/\s+$//; # rtrim whitespace
        $expr_ary[0] =~ s/^\s+//; # ltrim whitespace
	$expr_ary[1] =~ s/\s+$//; # rtrim whitespace
        $expr_ary[1] =~ s/^\s+//; # ltrim whitespace

	#print $expr_ary[0] . "|" . $expr_ary[1] . "\n";
	if (exists $gene_list{uc($expr_ary[0])}) {
		$gene_list{uc($expr_ary[0])} = $expr_ary[1];
	}
}

close EXPR;

#print Dumper(\%gene_list);

open OUTFILE, ">mapped_$ARGV[1]";

foreach my $mapping (keys %gene_list) {
	if ($gene_list{$mapping} ne "") {
		print OUTFILE "$mapping\t$gene_list{$mapping}\n"
	}
}

close OUTFILE;

system "cat ./mapped_$ARGV[1] | sort | uniq > ./mapping_output/sorted_mapped_$ARGV[1]; rm ./mapped_$ARGV[1]";

exit(0);
