#!/usr/bin/perl
# sucht s∽mltliche Motive der Transfac Datenbank unter /shomes/biertank/praktikum/RANSFAC/
# in einer ◯bergebenen fasta Datei und schreibt ins $PWD mit der Endung .pwmatch das Ergenis im Tab format
# wie es von den xmgrace tools verarbeitet werden kann

if(@ARGV == 0) {
	print "Dieses Tool sucht Transfac Motive in dieser Sequenz\nBitte Fasta Datei angeben!\n";
	exit;
}

my $seq_file = $ARGV[0];
#my $pwmatch_file = $ARGV[0] . ".pwmatch";


# Lese Dateiennamen der Motif DB ein
my $transen = `ls /homes/biertank/praktikum/TRANSFAC/M*`;
$transen =~ s/.*pwm\n//g;
my @transenhaufen = split(/\n/,$transen);


# Open the fasta file and read out each entry
# save each entry to tmp file and pass to pwmatch

open(FASTAFILE, "<$seq_file") || die ("Kann die input datei nisch offnen.\n");

my $nextline;
my $fastadata;
my $tmpfile = "pwm2data.tmp";

while (<FASTAFILE>) {

    if(($_ =~ m/^>/) || ($nextline =~ m/>/)) {
    
	if($nextline =~ m/>/) {

	    $fastadata = $nextline;
	    $fastadata .= $_;

	    $label = $nextline;
	    $label =~ s/(>| |\n)//g;

	} else {

	    $fastadata = $_;
	    $label = $_;
	    $label =~ s/(>| |\n)//g;
	}

	while (<FASTAFILE>) {
	    
	    if(($_ =~ m/^>/) || (length($_) == 1)) {
		$nextline = $_;
		last;
	    } else {
		$fastadata = $fastadata . $_;
	    }
	}

	# speicher Postdata zum versenden an TFSearch
	open(TMPFILE, ">$tmpfile");
	print TMPFILE $fastadata;
	close(TMPFILE);

	# Starte pwmatch command

	print "$label";

	foreach $transe (@transenhaufen) {
	    open(FILEIN, "<$transe") || die ("kann net offnen datei.");
	    my $line = <FILEIN>;
	    close(FILEIN);

	    $line =~ s/[\s]//g;
	    my $length = length($line);
	    if($length>0) {
		my $score = ((0.6*$length));
		my $befehl = "/homes/biertank/praktikum/bin/pwmatch $score $transe $tmpfile 2> /dev/null";		
		
		my @result = `$befehl`;
				
		if(!($result[0] =~ /0 matches found/)) {
		    
		    my $pos;
		    my $score;			

		    open(OUTPUT, ">>$label.data");
		    
		    for(my $i = 0; $i < $#result; $i++) {
						
			if($result[$i] =~ /pos (.*) weight (.*)\n/) {
			    $pos = $1;
			    $score = sprintf("%.5f", $2);
			    
			    print ".";
			    my $motif = `basename $transe`;
			    chop($motif);
			    print OUTPUT $pos."\t".(($pos+$length-1)) . "\t$score\t$motif\tNA\tpwm\t1\t$label\n";
			
			}
		    }

		    close(OUTPUT);
		}
	    }
	}
	print("\n");
    } 
}


close(FASTAFILE);

if(-e $tmpfile) {
    system("rm $tmpfile");
}

exit;




