#!/usr/bin/perl

my $infile = $ARGV[0];
my $outfile = "test";

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

my $line;
my @mfield;
my @fields;
my @resultline;
my @resultfirst, @resultsecond, @result;
my $motifcount = 0;
my $linecount = 0;
my $finalmat;
my $help;
my $zeichen;
my $a, $c, $g, $t;
my $hoxnumber;
my %hoxhash;
my $von, $bis, $rev;
my $seq;
my $score;
my @merkehox;
mkdir("data");

while(<FILEIN>) {

	
	if( ($_ =~ m/^Input/)) {
	
		$line = <FILEIN>;
		
		while( ($line =~ m/^\#/)) {
			
			@hoxfields = split(" ", $line);
			my $key = substr($hoxfields[0], 1, 2);
			$hoxhash{ $key } = "$hoxfields[1]";
			$line = <FILEIN>;
		
		}
		
		#print $hoxhash{1};
		#exit;
		
	}
	
	


	if( ($_ =~ m/^Motif/)) {
	
		$linecount = 0;
		$motifcount++;	
	    	$line = <FILEIN>;
				
	    
	   	while(!($line =~ m/^\*/)) {
	    
	    		$linecount++;
			@fields = split(" ", $line);
			$hoxnumber = $fields[1];
			$von = $fields[2];
			$bis = $von + length($fields[0]) -1;
			$seq = $fields[0];
			$rev = $fields[3];
			$merkehox[$linecount] = $hoxhash{ $hoxnumber };
			$resultfirst[$linecount] = $von . "\t" . $bis . "\t";
			$resultsecond[$linecount] = $motifcount . "\t" . $seq . "\t" . "AlignACE" . "\t" . $rev . "\t" . $hoxhash{ $hoxnumber } . "\t" . $hoxnumber . "\n";
			
			#@mfield[$linecount] = $fields[0] . "\n";
		
			$line = <FILEIN>;
		
		}
		
		
	
	}
		
	if( ($_ =~ m/^MAP/)) {
	
		@fields = split(" ", $_);
		$score = $fields[2];
		
		for(my $i = 1; $i <= $linecount; $i++) {
	
			$result[$i] = $resultfirst[$i] . $score . "\t" . $resultsecond[$i];
		
		}
		
		for(my $i = 1; $i <= $linecount; $i++) {
			
			
			$outfile = "data/".$merkehox[$i] . ".ACE.data";
		
			open (OUTFILE, '>>', $outfile) or die "Kann nisch offnen  \'$outfile\' zum schreiben!";
			print OUTFILE $result[$i];
		
		}
	
	}
	
	
	
}


close(OUTFILE);

exit;
