#!/usr/bin/perl

use warnings;
use strict;


if ($#ARGV != 0) {
	print "usage: inparanoid_orthologs.pl output_file\n";
	exit;
}
open(OUTFILE,">$ARGV[0]") || die "Error: file '$ARGV[0]' can not be opened\n";

# define the database handle to be used 
use lib "$ENV{HOME}/scripts/jaiswallab/interactome_scripts";

use DbiFloret;

my $dbh = DbiFloret::dbconnect;
	
my @species = ("Arabidopsis_thaliana", "Populus_trichocarpa");
my $num_species = @species;

for (my $i=0; $i<$num_species-1; $i++) {
	for (my $j=$i+1; $j<$num_species; $j++) {
		# hashes to store the paralogs and orthologs
		my (%species_1_gene_hash, %species_2_gene_hash);

		# make sure the species are listed in alphabetical order to get correct table names
		my $species_1 = $species[$i];
		my $species_2 = $species[$j];
		if ($species_1 lt $species_2) {
			$species_1 = $species_1;
			$species_2 = $species_2;
		} else {
			my $spec_temp = $species_1;
			$species_1 = $species_2;
			$species_2 = $spec_temp;
		}
	
		my $spec_table = "$species_1" . "_" . "$species_2";
		my $safe_species_table = $dbh->quote_identifier($spec_table);
		my $sth = $dbh->prepare("select * from $safe_species_table");
	
		my $id_prev = "";
	
		$sth->execute();
	
		while (my @line = $sth->fetchrow_array()) {
			my ($id, $bit_score, $spec, $score, $gene) = @line;
			if ($id ne $id_prev) {
				if ($spec eq $species_1) {
					$species_1_gene_hash{$id} = $gene;
				}else {
					$species_2_gene_hash{$id} = $gene;
				}
			}else {
				if ($spec eq $species_1) {
					if(defined($species_1_gene_hash{$id})) {
						$species_1_gene_hash{$id} = "$species_1_gene_hash{$id} $gene";
					} else {
						$species_1_gene_hash{$id} = $gene;
					}
				}else {
					if(defined($species_2_gene_hash{$id})) {
						$species_2_gene_hash{$id} = "$species_2_gene_hash{$id} $gene";
					} else {
						$species_2_gene_hash{$id} = $gene;
					}
				}
			}
			$id_prev = $id;
		}
		
		foreach my $key (keys %species_1_gene_hash) {
			if(defined($species_2_gene_hash{$key})) {
				my @species_1_gene_array = split(" ", $species_1_gene_hash{$key});
				my @species_2_gene_array = split(" ", $species_2_gene_hash{$key});
				foreach my $gene_1 (@species_1_gene_array) {
					print OUTFILE "$gene_1\t@species_2_gene_array" ."\n";
				}
				#foreach my $gene_1 (@species_1_gene_array) {
				#	foreach my $gene_2 (@species_2_gene_array) {
				#		print OUTFILE "$gene_1\t$gene_2\n";
				#	}
				#}
			}
		}
		$sth->finish();
	}
}

close(OUTFILE);

