#!/usr/bin/perl

# Program to determine whether both genes in the L2/L5 homolog pairs blast to the same BAL199 protein
use strict;
use warnings;

my $homolog_pairs = '13-Feb-13_synteny_table_plus_roles_curated_unix.txt';
my $L2_blast = 'L2_BAL199_blastp_curated_unix.txt';
my $L5_blast = 'L5_BAL199_blastp_curated_unix.txt';
my $table_output = 'L2_L5_BAL199_homologs.tab';

# Parse homolog pairs and make a hash
my %homologs;
my %homolog_pidents;
open (HOMOLOGS, "<$homolog_pairs") or die "\nCouldn't open $homolog_pairs\n";
my $first_line = <HOMOLOGS>;
while (<HOMOLOGS>)
{
	my $line = $_;
	chomp $line;
	my @linearray = split( "\t", $line );
	# Keyed by L2 gene name
	$homologs{ $linearray[1] } = $linearray[0];
	$homolog_pidents{ $linearray[1] } = $linearray[2];
}
close HOMOLOGS;

# Parse L2 table
my %L2_hits;
my %L2_BAL199_pidents;
open (L2TABLE, "<$L2_blast") or die "\nCouldn't open $L2_blast\n";
while (<L2TABLE>)
{
	my $line = $_;
	chomp $line;
	my @linearray = split( "\t", $line );
	# Keyed by L2 gene name
	$L2_hits{ $linearray[0] } = $linearray[1];
	$L2_BAL199_pidents{ $linearray[0] } = $linearray[3];
}
close L2TABLE;

# Parse L5 table
my %L5_hits;
my %L5_BAL199_pidents;
open (L5TABLE, "<$L5_blast") or die "\nCouldn't open $L5_blast\n";
while (<L5TABLE>)
{
	my $line = $_;
	chomp $line;
	my @linearray = split ( "\t", $line );
	# Keyed by L5 gene name
	$L5_hits{ $linearray[0] } = $linearray[1];
	$L5_BAL199_pidents{ $linearray[0] } = $linearray[3];
}
close L5TABLE;

# Go through homologs and work out what is going on
open (OUTPUT, ">$table_output") or die "\nCouldn't open $table_output\n";
print OUTPUT "L2_gene\tL5_gene\tBAL199_gene\tL2_L5_pident\tL2_BAL199_pident\tL5_BAL199_pident\n";
foreach my $L2_gene ( keys %homologs )
{
	my $L5_gene = $homologs{ $L2_gene };
	my $undefined = 0;
	unless ( defined $L2_hits{ $L2_gene } )
	{
		print "$L2_gene does not have a BAL199 homolog\n";
		$undefined++;
	}
	unless ( defined $L5_hits{ $L5_gene } )
	{
		print "$L5_gene does not have a BAL199 homolog\n";
		$undefined++;
	}
	
	next if ( $undefined > 0 );
	
	if ( $L2_hits{ $L2_gene } eq $L5_hits{ $L5_gene } )
	{
		print "$L2_gene and $L5_gene are both homologous to $L2_hits{$L2_gene}\n";
		print OUTPUT "$L2_gene\t$L5_gene\t$L2_hits{$L2_gene}\t$homolog_pidents{$L2_gene}\t$L2_BAL199_pidents{$L2_gene}\t$L5_BAL199_pidents{$L5_gene}\n";
	} else {
		print "$L2_gene is homologous to $L2_hits{$L2_gene} and $L5_gene is homologous to $L5_hits{$L5_gene}\n";
	}
}
close OUTPUT;