#!/usr/bin/perl

use strict;
use warnings;

use Time::localtime;
my $tm=localtime;
my ($day,$month,$year)=($tm->mday,$tm->mon,$tm->year);
$year += 1900;
$month = sprintf '%02d', $month+1;
$day = sprintf '%02d', $day;
my $curr_date = "$year$month$day";



# check for arguments and explain usage
if ($#ARGV !=2) {
	print "usage: association_file_from_orthologs.pl in_assoc_file ortho_file out_file\n";
	exit;
}
	
# Grab the find_species subroutines to get the species and taxon id
if(-e "$ENV{HOME}/scripts/jaiswallab/interactome_scripts/find_species.pl") {
	require "$ENV{HOME}/scripts/jaiswallab/interactome_scripts/find_species.pl";
}elsif(-e "$ENV{HOME}/bin/find_species.pl") {
	require "$ENV{HOME}/bin/find_species.pl";
}


my $ingaffile = $ARGV[0];
my $inorthofile = $ARGV[1];
my $outfile = $ARGV[2];

# Get species and taxon
my $species = find_species("$inorthofile");
my $new_taxon = find_taxon($species);


my %ortho_hash;
open (INORTHOFILE, $inorthofile);
while(<INORTHOFILE>) {
		my $line = $_;
		chomp $line;
		next if ($line =~ /^id/);
		my ($gene, $ortho) = split("\t", $line);

		$ortho_hash{$ortho} = $gene;

}
close(INORTHOFILE);
		

open (INGAFFILE, $ingaffile);
open (OUTFILE, ">$outfile");

print OUTFILE "!gaf-version: 2.0\n";
print OUTFILE "!Created via ortholog similiarity from Arabidopsis thaliana\n";
while(<INGAFFILE>) {
		my $line = $_;
		chomp $line;
		#skip comments
		next if ($line =~ /^!/);
		
		my ($db,$db_id,$db_symbol,$qual,$ont_id,$db_ref,$ev,$with,$aspect,$db_obj_name,$db_obj_syn,$db_obj_type,$taxon,$date,$assigned_by,$annot_ext,$gp_form_id) = split("\t", $line);
		#check if symbol found in %gene_hash
		if(defined($ortho_hash{$db_obj_name})) {
				my $ortho_gene = $ortho_hash{$db_obj_name};
				print OUTFILE "EnsemblPlants\t$ortho_gene\t$ortho_gene\t$qual\t$ont_id\tPMID:24919147|PMID:21186353\tISO\tAGI_LocusCode:$db_obj_name\t$aspect\t$ortho_gene\t\t$db_obj_type\ttaxon:$new_taxon\t$curr_date\tPlanteome:Justin_Elser\t$annot_ext\t$gp_form_id\n";
		}
		
}
close(INGAFFILE);
close(OUTFILE);
