#!/usr/bin/perl

if($#ARGV == -1) {
    print "Bitte Argument angeben: Datei mit PWM Matrizen\n";
    exit;
}

my $matrixfile = $ARGV[0];
my $resultfile = $matrixfile . ".res.jaspar";
system("rm $resultfile");

my $postfile = "postfiletmp";
my $domain = "http://rulai.cshl.edu";

open(MATRIXFILE, '<', "$matrixfile");
my $postdata;


# Dies ist die Hauptschleife in der die Matrize(n) extrahiert und
# und an MatCompare geschickt werden. Die Resultate werden alle 
# an die Datei $resultfile rangehaengt. Nach dieser Schleife werden
# zum Abschluss alle Eintrage aus der Resultatsmenge nach der 
# Wahrscheinlichkeit (0.9) ausgesondert und in $resultfile  
# geschrieben.
while (<MATRIXFILE>) {

    if($_ =~ m/M./) {
    
	print "Matrize gefunden: $_\n";

	$postdata = "DB=JASPAR&TEST=chi2&SIZE=5&MATS=" . $_;
	
	while (<MATRIXFILE>) {
	    
	    if($_ =~ m/END/) {
		$postdata = $postdata . $_;
		last;
	    } else {
		$postdata = $postdata . $_;
	    }
	}

	# speicher Postdata zum versenden an Matcompare
	open(POSTFILE, '>', $postfile);
	print POSTFILE $postdata;
	close(POSTFILE);

	# schicke post
	system("rm matSubmit.cgi");
	system("wget --post-file $postfile http://rulai.cshl.edu/cgi-bin/MatCompare/plugin/compare2known/matSubmit.cgi");
	
	system("rm $postfile");

	# lese url mit jobid
	open(FILEIN, "<", "matSubmit.cgi");
	my @field;
	my $jobid;
	my $url;

	# extrahiere url
	while (<FILEIN>) {
	    if($_ =~ m/URL/) { 
		$url = $domain . substr($_, index($_, "URL") + 4, rindex($_, "\"") - rindex($_, "URL") - 4);
    		last;
	    }
	}

	# empfange jobid url und schau ob es nicht die refresh ist
	my $sleepmore = 1;
	while($sleepmore == 1) {

	    sleep(2);

	    $sleepmore = 0;

            system("wget '$url' -O outtmp");

	    # schau ob's die richtige datei ist (falls es kein Refresh tag enthalt) #

	    open(OUTTMP, "<outtmp");

	    while(<OUTTMP>) {
		if($_ =~ m/Refresh/) {
		    
		    $sleepmore = 1;
		    last;
		}
	    }
	    close(OUTTMP);
	}
	
	system("cat outtmp >> $resultfile");

    } # end if($_ =~ m/M./) #
}

system("rm outtmp");

open(RESULTFILE, "<$resultfile");
my @rbuffer;

while(<RESULTFILE>) {
    
    if($_ =~ m/^M./) {

	@fields = split(" ", $_);
	
	
	if ($fields[2] > 0.6) {
	    push(@rbuffer, $_); 
	}
    }
}


close(RESULTFILE);
system("cp $resultfile resbackup");
open(RESULTFILE, ">$resultfile");

print RESULTFILE @rbuffer; 

close(RESULTFILE);

exit;
