#!/usr/bin/perl -w

use strict;

my $helpStr=qq{

Usage:
	join2files.pl <first inputFile> <file ID column> <second inputFile> <2nd file ID column> 
	
Description:
	This script takes two tab-delimited files and join them by their common identifiers.
	Output is to STDOUT: joined tab-delimited results 	 

	<file ID column>: which column the IDs are at.  start counting columns from zero!!
Note:
	if no common IDs are found, the line would be ignored, hence not printed...

};

unless (@ARGV==4){die "$helpStr";}

my ($fileA, $idColA, $fileB, $idColB) = @ARGV;

my %hash = ();

&parse(\%hash, $fileA, $idColA, 'A');
&parse(\%hash, $fileB, $idColB, 'B');

map{print join "\t", $_, $hash{$_}{A}, $hash{$_}{B}."\n" if $hash{$_}{A}&&$hash{$_}{B}} sort keys %hash;
exit;

sub parse(){
 	my ($hashR, $file, $idCol, $name) = @_;
	open FILE, "$file" or die "Can't open $file: $!\n";
	while (<FILE>){
		s/\n//g;
		my @temp = split /\t/;
		$hashR->{$temp[$idCol]}{$name}=$_;
	}
	close FILE;
	return;
}


