#!/usr/bin/perl -w
use strict;

#
# Wandelt die tba.maf in *.fasta
# wendet 'clustalw' auf die berechneten *.fasta an
#

if ($#ARGV != 0) {die "ERROR: need 1 parameters: \n".
                     "       maf input file \n"; }

my $MIN_LENGTH = 20;
my $MAX_LENGTH = 3000;
my  $maf_file = $ARGV[0];
print "read file ".$maf_file."\n";
open (FILE,"<".$maf_file) or die " File ".$maf_file." not found.\n";
	my @all=<FILE>;
close(FILE);
print "ready. \n";

my $blocks=0;
my @seq; my $i;
for ($i=0;$i<($#all);$i++){ 
	my $line = $all[$i];
	if (index($line,"a score=")==0) {$blocks++;}
	if (index($line,'#')<0){
		push(@seq,$line);
	}
	
}
print "Gefundene Bloecke: ".$blocks."\n";

my @bon;
$blocks=0;
for ($i=0;$i<($#seq);$i++){ 

	my $line = $seq[$i];
	if (index($line,"a score=")==0) {
		my @erg=split('=',$line);	

		#Pruefe auf pos. Score
		if (($erg[$#erg]>0.0) ){
			$blocks++;
			push(@bon,$line);
			
			$i++;
			while (index($seq[$i],"s")==0){
				my $Sequ=$seq[$i];
				my @SequA=split(' ',$Sequ);
				my $SequDNA=$SequA[$#SequA];
				$SequDNA =~ s/-//g;
				if (length($SequDNA)>=$MIN_LENGTH) {
					push(@bon,$seq[$i]);
				}
				$i++;
			}
			push(@bon,"\n");
			
		}
	}
}

print "Gefundene pos. Score Bloecke: ".$blocks."\n";

my $isPosBlock=0;
$blocks=0;
my @bon1;
for ($i=0;$i<($#bon);$i++){ 
	my $line = $bon[$i];
	
	
	if ((index($line,"a score=")==0) ){
		if((index($bon[$i+1],'s')==0) && 
			(index($bon[$i+2],'s')==0) && 
			(index($bon[$i+3],'s')==0)){
				$isPosBlock=1;
				$blocks++;
		}else{
				$isPosBlock=0;
		}
	}
	if ($isPosBlock==1){
		
		push(@bon1,$line);
	
	}

	
}

print "Anzahl(Gefundene pos. Score Bloecke)>=3: ".$blocks."\n";

#FASTA Dateien schreiben:

my $seqID=0;

for ($i=0;$i<($#bon1);$i++){ 
	my $line = $bon1[$i];
	if (index($line,"a score=")==0) {
		my @erg=split('=',$line);	
		my $score=$erg[$#erg];
		$i++;
		my $FileN="Bacillus_".$seqID."_".substr($score,0,length($score)-3).".fasta";
		open (FILE,">".$FileN);
			while(index($bon1[$i],"s")==0){
				my @lines=split(' ',$bon1[$i]);
				print FILE ">".
				 substr($lines[1],0,index($lines[1],'.')).".".
				 $lines[2].".".
				 $lines[4].".".
				 $lines[5]."\n";
				my $counter=0;
				$lines[6]=~ s/-//g;
				print FILE $lines[6];
				print FILE "\n";
				
				$i++;
			}
		close(FILE);
		system("clustalw $FileN");
		$seqID++;
	}
}
