#!/usr/bin/perl

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

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

my $line;
my @hoxfields, @helpfields;
my $start, $end, $score, $motifnr, $seq;
my $programm = "consensus";
my $rev = 1;
my $name;
my $result;



while(<FILEIN>) {

	if( ($_ =~ m/^\*\*\*\*\* Sequence information from file/)) {
	
		$line = <FILEIN>;
		
		while( ($line =~ m/^sequence/)) {
			
			@hoxfields = split(" ", $line);
			my $key = substr($hoxfields[1], 0, 1);
			$hoxhash{ $key } = "$hoxfields[2]";
			$line = <FILEIN>;
			$line = <FILEIN>;
		
		}
		
	}

	if( ($_ =~ m/^MATRIX/)) {
		$count = 0;			
		while($count < 4) {
			$line = <FILEIN>;
			$count++;			
			}
		@helpfields = split(" ",$line);
		$score = @helpfields[5];
		
		while($count < 10) {
			$line = <FILEIN>;
			$count++;			
			}
		$count = 0;
		while($count < 7) {
			$count ++;
			@hoxfields = split(" ",$line);
			$motifnr = substr(@hoxfields[2],0,1);
			$start = substr(@hoxfields[2],2,length(@hoxfields[2]));
			$end = $start + 10;
			$seq = @hoxfields[3];
			$name = $hoxhash{ $motifnr };
		
			$result = $start . "\t" . $end . "\t" . $score . "\t" . $motifnr . "\t" . $seq . "\t" . $programm . "\t" . $rev . "\t" . $name . "\n";	
			$line = <FILEIN>;
			
			open (MATFILE, '>>', "$name.cons.data") or die "Kann nisch offnen  \'$name.data\' zum schreiben!";
			
			print MATFILE "$result";

			close (MATFILE);
		}
	}
}



exit;
