#!/usr/bin/perl -w
use strict;
use Bio::DB::GenBank;
use Bio::SeqIO;
use Bio::Perl;
use Bio::SearchIO;
use Bio::SeqFeature::SimilarityPair;
use Bio::AlignIO;
use Bio::Align::AlignI;
use Bio::SimpleAlign ;
use Bio::SeqIO::fasta;
use Bio::SearchIO::blasttable;
use Bio::Search::Result::GenericResult;
use Bio::Search::Hit::GenericHit;
use Bio::Search::HSP::HSPI;

##############I get a ddbb for each sequence from fasta file and I do a blast run between them ##############
my $input1="outfile.txt"; ##### fasta file
my  @gens;
	my $in  = Bio::SeqIO->new(-file => $input1 , '-format' => 'fasta');
	my $count=0;
	while ( my $seq = $in->next_seq() ) {
		my $secuencia = $seq->seq();
		push (@gens, $secuencia);
		
		}
		#~ print $gens[0],"\n";
		foreach my $seq (@gens){
			$count++;
		open OUT1 , ">$count.fa"; ###### Each sequence in a independent file to get 
		print   OUT1">$count","\n",$seq,"\n";
			system ("formatdb -i $count.fa -p T -n $count.database");
			system ("for file in `ls *.fa`; do blastall -p blastp -d $count.database -i \$file -e 0.001 -m7 >> all_over_all; done"); ####Blast of each sequence. XML output
			
		close OUT1;
		}	


	    
    
 ########Parse XML output ##################
open OUT2, ">all_over_all_hits.txt";
my $file="all_over_all";
my $input2 = Bio::SearchIO->new(-file   => $file,
                                 -format => 'blastxml');
				 #~ print $parser;
			
	while( my $result = $input2->next_result ) {
		my $query = $result->query_name();
		#~ print $query,"\n";
			my $id = $result->query_name();
		while (my $hit = $result->next_hit){
			my $hit_name = $hit->name();
				#~ print $hit_name,"\n"
			while( my $hsp = $hit->next_hsp){
					my $percentid = $hsp->percent_identity(); ##### Blast identity
					#~ print $percentid,"\n";
					if ($percentid < 95){
						print OUT2 $hit_name,"\t", $query,"\n"; ######### Sequences <95 % homologous ###########
					}
				}
		}
	}		
close OUT2;
