use strict;
use Bio::Seq;
use Bio::SeqIO;
use Bio::AlignIO;

open(OUT,">99.01orth_pro_seq.txt");
open(OUT2,">99.01mis_orth_pro.txt");

open(NAME168,"Bacillus_subtilis_subsp_subtilis_str_168.GCA_000009045.1.17.gtf");
my %gene1;
while(my $line=<NAME168>){
	chomp $line;
	my @data=split("\t",$line);
	my @data2=split(";",$data[8]);
	$data2[1]=~/transcript_id \"(.+)\"/;
	my $geneid1=$1;#CAB11777
	$data2[3]=~/gene_name \"(.+)\"/;
	my $geneid2=$1;	#dnaA
	$gene1{$geneid2}=$geneid1;
	$gene1{$geneid1}=$geneid2;
}

open(GENE,"99.00gene.txt");
my %gene2;
while(my $line=<GENE>){
	chomp $line;
	my @data=split("\t",$line);
	if(exists $gene1{$data[0]}){
		$gene2{$gene1{$data[0]}}=$data[1];
	}
	else{
		print OUT2 $data[0]." no name\n";
	}
}

open(ORTH,"99.00orth.txt");
my %gene3;
while(my $line=<ORTH>){
	chomp $line;
	my @data=split("\t",$line);
	if(exists $gene2{$data[0]}){
		$gene3{"168"}->{$data[0]}=$data[0];
		$gene3{"bsn5"}->{$data[1]}=$data[0];
		$gene3{"ro"}->{$data[2]}=$data[0];
		$gene3{"tu"}->{$data[3]}=$data[0];
		$gene3{"w23"}->{$data[4]}=$data[0];
	}
}

my %pro5spe;
open(GENOME,"99.00genome.txt");
while(my $line=<GENOME>){
	chomp $line;
	my @data=split("\t",$line);
	my $seqs=new Bio::SeqIO(-file=>$data[1],-format=>"fasta");
	my $hashdata=$gene3{$data[0]};
	while(my $seq=$seqs->next_seq){
		foreach my $tgene (keys %$hashdata){
			if($tgene eq $seq->id){
				$pro5spe{$gene3{$data[0]}->{$tgene}}->{$data[0]}=$seq->seq;
			}
		}
	}
}


foreach my $gene (keys %pro5spe){
	my $hashdata=$pro5spe{$gene};
	
	if(scalar(keys %$hashdata)==5){
		print OUT $gene."\t".$gene1{$gene}."\t".$gene2{$gene}."\n";
		foreach my $spe (keys %$hashdata){
			print OUT ">".$spe."\n".$pro5spe{$gene}->{$spe}."\n";
		}
	}
	else{
		my $tem="";
		foreach my $spe (keys %$hashdata){
			$tem.=$spe." ";
		}	
		print OUT2 $gene." ".$tem." not in all 5 spes\n";
	}
}

