#!/usr/bin/perl

my $memefile = $ARGV[0];
my $matrixfile = $ARGV[0] . ".mat";
my $tataname = substr($ARGV[0], 0, index($ARGV[0], "."));

open(FILEIN, "<$memefile") || die ("kann net offnen datei.");

my $line;
my @mfield;
my @fields;
my $resultmat, $resulthead;
my $motifcount = 0;


open (MATFILE, '>>', $matrixfile) or die "Kann nisch offnen  \'$filename\' zum schreiben!";


while(<FILEIN>) {


	if( ($_ =~ m/^MATRIX/)) {
			
	    $motifcount++;
		
		my $count = 0;
		my $matrix_region = "";			
		while($count < 6) {
			$line = <FILEIN>;
			$count++;			
			}
		$mfield[0] = $line;
		$mfield[1] = <FILEIN>;
		$mfield[2] = <FILEIN>;
		$mfield[3] = <FILEIN>;
		
		#$matrix_region =~ s/<th.*>|<a.*>//gi;
		#my @mfield = split(/<TR>/, $matrix_region);			
 		
		for(my $a=0;$a<4;$a++) {
			$mfield[$a] =~ s/.*\|//g;
			$mfield[$a] =~ s/[\s]//g;
			#print $mfield[$a]."\n";
						
			}
		
		
	

	    $resulthead = "M." . $tataname . "_motif_" . $motifcount . "\n";
		
	    $resultmat = "";
		
	    for(my $i = 0; $i < length($mfield[0]); $i++ ) {
		
		    $resultmat = $resultmat . substr($mfield[0],$i, 1) . " "; 
		    $resultmat = $resultmat . substr($mfield[1],$i, 1) . " "; 
		    $resultmat = $resultmat . substr($mfield[2],$i, 1) . " "; 
		    $resultmat = $resultmat . substr($mfield[3],$i, 1) . "\n"; 
		 
		}
		
	    $resultmat = $resultmat . "END\n"; 	    
	    $resultmat =~ s/:/0/g;
	    $resultmat =~ s/a/10/g;
	    $resultmat =~ s/b/11/g;
	    $resultmat =~ s/c/12/g;
	    $resultmat =~ s/d/13/g;
	    $resultmat =~ s/e/14/g;
	    $resultmat =~ s/f/15/g;
	    
	    $resultmat = $resulthead . $resultmat . "\n";
	   #print $resultmat;
	
	    print MATFILE "$resultmat";
	}
}

close(MATFILE);

exit;
