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

open(OUT,">99.02best_hit.txt");
my @spes=("best","qb","ina","nat","spi","sc");

open(LEN168,"Bacillus_subtilis_subsp_subtilis_str_168.GCA_000009045.1.17.pep.all.fa");
my %len;
my $seqhu=new Bio::SeqIO(-file=>"Bacillus_subtilis_subsp_subtilis_str_168.GCA_000009045.1.17.pep.all.fa",-format=>"fasta");
while(my $this_seq=$seqhu->next_seq){
	$len{$this_seq->id}=$this_seq->length;
}

open(GENE,"99.00hotmut.txt");
my %gene;
while(my $line=<GENE>){
	chomp $line;
	my @data=split("\t",$line);
	$gene{$data[0]}=1;
}

my %orth;
foreach my $tspe(@spes){
	open(TEM1,"99.01168_".$tspe.".txt");	
	while(my $line=<TEM1>){
		chomp $line;
		my @data=split("\t",$line);#AEH52061	CAB11777	79.91	448	87	2	51	497	1	446	0.0	 744
#1 	qseqid 	Query Seq-id (ID of your sequence)
#2 	sseqid 	Subject Seq-id (ID of the database hit)
#3 	pident 	Percentage of identical matches
#4 	length 	Alignment length
#5 	mismatch 	Number of mismatches
#6 	gapopen 	Number of gap openings
#7 	qstart 	Start of alignment in query
#8 	qend 	End of alignment in query
#9 	sstart 	Start of alignment in subject (database hit)
#10 	send 	End of alignment in subject (database hit)
#11 	evalue 	Expectation value (E-value)
#12 	bitscore 	Bit score
		if(exists $gene{$data[1]} and $data[2]>80 and $data[3]/$len{$data[1]}>0.80){
			if(exists $orth{$data[1]}->{$tspe}){
				my @data2=split("\t",$orth{$data[1]}->{$tspe});
				if($data[10]<$data2[1]){
					$orth{$data[1]}->{$tspe}=$data[0]."\t".$data[10];
				}
			}	
			else{
				$orth{$data[1]}->{$tspe}=$data[0]."\t".$data[10];
			}
		}
	}
}


foreach my $tgene (keys %orth){
	print OUT $tgene;	
	foreach my $tspe(@spes){
		if($orth{$tgene}->{$tspe} ne ""){
			my @data=split("\t",$orth{$tgene}->{$tspe});
			print OUT "\t".$data[0];	
		}
	}
	print OUT "\n";
}
