# script for getting maxscores from PSSM matching.
# Input: result file from PSSM matching.

use strict;

# FORMAT OUTPUT
# 'fileindex' \t 'sourceindex'\t 'tf'\t 'score'\t 'matrix'\t 'strand'

#INPUT: Result file from PSSM matching

FindMaxScores("input.txt","output.txt");

sub FindMaxScores {
	my ($infile,$outfile)=@_;
	open (TESTin,'<',$infile) || die ($!);
	open (TESTout,'>',$outfile) || die ($!);
	print TESTout join("\t", 'negindex', 'tf', 'score', 'matrix', 'strand'), "\n"; 
	my $last_start=0;
	my $max_score=0;
	my $last_tf=0;
	my $last_index=0;
	my $last_matrix=0;
	my $max_strand=0;
	my $last_posindex=0; 
	my $count=1;   
	while (<TESTin>) {
		chomp;
		s /"//g;
		s /'//g;
	
		my ($current_index, $current_tf, $current_matrix, $start, $end, $current_score,  $current_strand) = split/\t/;
			 
		next if $current_score =~ /score/;
		 
		if ($current_matrix != $last_matrix || $current_index != $last_index) {
			if ($max_score) {
				print TESTout $last_index, "\t",$last_tf,"\t",$max_score, "\t", $last_matrix, "\t", $max_strand, "\n";
				$count++;
			}
			$max_score = $current_score;
			$max_strand=$current_strand;
			
		}		
		elsif(eof) {
				print TESTout $last_index, "\t",$last_tf,"\t",$max_score, "\t", $last_matrix, "\t", $max_strand, "\n";
			}
		else {
			if ($current_score>$max_score){
				$max_score = $current_score ;
				$max_strand=$current_strand ;
			}
			
		}	
		$last_tf=$current_tf;
		$last_index=$current_index; 
		$last_matrix=$current_matrix;
		
		#last if $.>5000;
		}
	close TESTin;
	close TESTout;
}


