#!/usr/bin/perl

my $memefile = $ARGV[0];
my $matrixfile = $ARGV[0] . ".data";
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/<TR><TH ALIGN=LEFT>NAME<TH>&nbsp;<TH>STRAND<TH>/)) {
			
	    $motifcount++;
		
		my $startflag = 0;
		my $data_region = "";			
		while($startflag < 1) {
			$line = <FILEIN>;
			
			
			if($line =~ m/^<\/TABLE>/) {
				$startflag = 1;	
				}
			else {
				$data_region.=$line;
				}
			}
		#$_ =~ s/<th.*>|<a.*>//gi;
				
		#$matrix_region =~ s/<th.*>|<a.*>//gi;
		my @mfield = split(/<TR>/, $data_region);
				
 		#print $mfield[1];
		my $linefield;
		foreach $linefield (@mfield) {
			#print "\n\n".$linefield."\n\n";
			if($linefield eq "") {
				#print "scheisse\n";
				next;
			}
			my $bla;			
			my @tokens = split(/<TD>/,$linefield);
			
			my $viech;
			my $strand;
			my $pos;
			my $score;
			my $sequence = "";
			
			my $flag = 0;
			foreach $bla (@tokens) {
				$bla =~ s/[\s]//g;
				
				#print $bla."\n\n";
				if($bla =~ /<TDALIGN=CENTER>(.*)/) {
					$strand = $1;
				}
				if(($bla =~ /<TDALIGN=RIGHT>(.*)/) && $flag == 0 ) {
					$pos= $1;
					$flag = 1;
	
				}
				if(($bla =~ /<TDALIGN=RIGHT>(.*)/) && $flag == 1 ) {
					$score = $1;

				}
				if($bla =~ /^<TDCLASS/) {
					my @blubb = split(/<\/B>/,$bla);
					my $tmp;
										
					foreach $tmp (@blubb) {
						$sequence.= chop($tmp);
				
					}
					chop($sequence);
				}
			}
			$viech = $tokens[1];
			
			$resultmat.= $pos;
			$resultmat.= "\t";
			$resultmat.= $pos+length($sequence)-1;	
			$resultmat.= "\t";
			$resultmat.= $score;
			$resultmat.= "\t";
			$resultmat.= $motifcount;
			$resultmat.= "\t";
			$resultmat.= $sequence;
			$resultmat.= "\t";
			$resultmat.= "meme";
			$resultmat.= "\t";
			if($strand eq "-") {
				$resultmat.= "0";
			} else {
				$resultmat.= "1";
			}
	
			$resultmat.= "\t";		
			$resultmat.= $viech;
			
			$resultmat.= "\n";
		
		
	

	   
			#print $resultmat;
			
			}
	
	   #print MATFILE "$resultmat";
	}
}
print MATFILE "$resultmat";
close(MATFILE);

exit;
