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

open(OUT,">99.03avalible_sites.txt");

my %seq;
open(SPE,"99.00species.txt");
while(my $line=<SPE>){
	chomp $line;
	my $seqhu=new Bio::SeqIO(-file=>$line,-format=>"fasta");
	while(my $this_seq=$seqhu->next_seq){
		$seq{$this_seq->id}=$this_seq->seq;
	}
}

my %orth;
open(ORTH,"99.00orth.txt");
while(my $line=<ORTH>){
	chomp $line;
	my @data=split("\t",$line);
	foreach my $i(1..4){
		$orth{$data[0]}->{$data[$i]}=1;
	}
}


open(BEST,"99.02best_hit.txt");
while(my $line=<BEST>){
	chomp $line;
	my @data=split("\t",$line);
	if(scalar(@data)>1){
	my $temfile=$data[0].".txt";
	my $alnfile=$data[0].".aln";
	open(TEM,">".$temfile);
	my $i=100;
	foreach my $j (1..(scalar(@data)-1)){
		print TEM ">".$i."\n".$seq{$data[$j]}."\n";
		$i+=1;
	}
	my $i=1;
	my $hashdata=$orth{$data[0]};
	foreach my $torth (keys %$hashdata){
		print TEM ">".$i."\n".$seq{$torth}."\n";
		$i+=1;
	}
	print TEM ">".$i."\n".$seq{$data[0]}."\n";
	close TEM;
	system<clustalw $temfile>;
	my $alnfilein=Bio::AlignIO->new('-file'=>$alnfile);
	my $aln=$alnfilein->next_aln();
	my $alngaps=$aln->gap_col_matrix();
	my @match=split("",$aln->match_line);
	my $num_unmat=0;
	my $i=0;#frist and last aa cound
	while($i<scalar(@match)){
		if ($match[$i] ne "*"){
			my $tgap=0;
			my $hashdata=$alngaps->[$i];
			foreach my $tgene (keys %$hashdata){
				if($tgene<100 and $alngaps->[$i]->{$tgene}==1){
					$tgap+=1;
				}
			}
			if($tgap==0){
				$num_unmat+=1;
			}
		}
		$i+=1;
	}
	print OUT $data[0]."\t".$num_unmat."\n";
	}
}

