# generation of single resultfiles for each TF


#output format: tf, "\t", matrix, "\t", score, "\t", strand, "\t", sourceindex, "\t",  fileindex, "\n"
# sourceindex=to link back to ENCODE/Exon file
#fileindex: for comparison to neg file

use strict; 

my $filename; 

ReadFile("inputfile", "database",'case');
#database: hPDI/JASPAR/HT-SELEX, #case: positive or negative
my %file_open=();

sub ReadFile {
	my ($infile,$database,$case)= @_;
	die unless $infile and $database and $case;
	open (TESTin,'<',$infile) || die ($!);	
	my ($last_tf)=();
	my $current_matrix='1';
	while (<TESTin>) {
		chomp;
		#s /\W+$//;
		s /"//g;
		s /'//g;
				
		my ($fileindex, $current_sourceindex, $current_tf, $current_score, $current_matrix, $strand) = split/\t/;
		
		my $filename="d:/daniela_tfbs/testset/MotifDBTest/$database/reverse/$case/$case".'_'.$current_tf.'.txt';
		if ($current_tf ne $last_tf) {
			close TESTout;
			if ($file_open{$filename}) {
				open (TESTout, ">>", $filename) or die ($!);
			}
			else {
				open (TESTout, ">", $filename) or die ($!);
				print TESTout join ("\t", "tf", "matrix", "score", "strand", "sourceindex", "fileindex"), "\n"; 
				$file_open{$filename}=1;
			}
			$last_tf=$current_tf;
		}
		print TESTout $current_tf, "\t", $current_matrix, "\t", $current_score, "\t", $strand, "\t", $current_sourceindex, "\t",  $fileindex, "\n";
	}
	close TESTin;
	close TESTout;	
}	
	
	
