#!/usr/bin/perl
use strict;



my $usage= << "JUS";
 usage: motivplot.pl [options] list-of-files

    The list-of-files is a space separated list of files in the .data format. 
    Wildcards can be used too. Commonly files with ending .merged should be 
    passed. The output is a xmgrace directory that contains .grace and .ps files.

  Options:
    -s   If specified the y-axis will be the score of a motiv. Otherwise the graph 
         just shows if a motiv appears or not. 

    -t   In case data is used that was originally derived from AlignAce, this option
         will delete the AlignAce typical "stairs".

    -p   This forces to draw the program names into the graph legend. Default is
         drawing of hox names. 

JUS

my @options = grep {substr($_, 0, 1) eq '-'} @ARGV;
my @infiles  = grep {substr($_, 0, 1) =~ /^[^-]/} @ARGV;

die "$usage\n" unless scalar(@infiles) != 0;


my $mit_score = 0;
my $grill = 0;
my $tierein = 1;

# Choose options
foreach my $option (@options){
  if    ($option eq '-s')               { $mit_score = 1  }
  if    ($option eq '-t')               { $grill = 1   }
  if    ($option eq '-p')               { $tierein = 0 }
}

my $outdir = "graphplot";

if(!(-e $outdir)) { mkdir($outdir)};

my $score_file;
my $out;
my $outdatei;
my $reihenfolge;
my $color = 2; 


foreach $score_file (@infiles){

	my @dateiname;
	@dateiname = split(/\./,$score_file);

	$out ="@    s0 legend  \"".$dateiname[0]."\"\n";
	pop(@dateiname); push(@dateiname,"grace");

	$outdatei = join('.',@dateiname);
	open(FI,"< $score_file") or die "error by opening input file";

	
	# Errechne scores
	$out = &scorecalc($out);

	open(FO,">" . $outdir . "/" . $outdatei) or die "error by opening output file";

	print FO $out;

	system("xmgrace $outdir/$outdatei -hardcopy -printfile " . $outdir . "/" . $outdatei . ".ps");
	close(FI);
	close(FO);
}

&mehrere;
&vergleichen;


sub scorecalc{

	my $out = $_[0];
	my @cwlines = <FI>;
	chop @cwlines;
	my @start;
	my @stop;
	my @score;
	my %dubletten=();
	my $cwline;
	my $j = 0;
	my $prog;
	my $tier;

	foreach $cwline (@cwlines){
		$dubletten{$cwline}++;
		#this entdfernd dubledden ;o)
		if($dubletten{$cwline} > 1){
			print "dubledden weg\n";
			next;
		}
		my @zwischen = split(/\t/,$cwline);
		$start[$j] = $zwischen[0];
		#print $start[$j]."\n";
		$stop[$j] = $zwischen[1];
		$prog = $zwischen[5];
		$tier = $zwischen[7];
		$score[$j] = $zwischen[2];


		if($prog =~ /meme/i){ #  Logaritmus
		  
		  if($zwischen[2] !~ m/e/) {
		    $score[$j] = $zwischen[2];
		  }else {
		    $score[$j] = (((substr($zwischen[2],-2,2)) * 10));
		}
		  $reihenfolge = 2;
		}
		if($prog =~ /alignace/i){
			#$score[$j] = $zwischen[2];
			$score[$j] = (sprintf("%.0f", $zwischen[2]));
			$reihenfolge = 0;
		}
		if($prog =~ /biop/i){
			#$score[$j] = (($zwischen[2] * 1000)-1950);
			#neue webinterface bioprospector
			#$score[$j] = (($zwischen[2] * 1000)-2400);
			$reihenfolge = 1;
		}
		if($prog =~ /pwmatch/i){
			#$score[$j] = ($zwischen[2] * 10);
			$score[$j] = (int($zwischen[2] * 10));
			$reihenfolge = 5;
		}
		if($prog =~ /tfsearch/i){
			$score[$j] = ($zwischen[2] * 7);
			$reihenfolge = 4;
		}
		if($prog =~ /ymf/i){
			$score[$j] = ((sprintf("%.0f", $zwischen[2]))*3);
			$reihenfolge = 3;
		}
		$j++;
	}

	# Grillen von Treppen
	if($prog =~ /alignace/i && $grill == 1) {
		my %intervall = ();
		my %score_hash = ();

		for(my $l=0;$l<=@start;$l++)  {
			# mit Motivl�ge
			#if($intervall{$start[$l]} < $stop[$l]) {

			# mit Score
			if($score_hash{$start[$l]} < $score[$l]) {
				$intervall {$start[$l]} = $stop[$l];
				$score_hash {$start[$l]} = $score[$l];
			}

		}
		@start = ();
		@stop = ();
		@score = ();
		my $m =0;
		foreach my $hashkey (keys(%intervall)) {
			$start[$m] = $hashkey;
			$stop[$m] = $intervall{$hashkey};
			$score[$m] = $score_hash{$hashkey};
			#print "key: $hashkey, value: $intervall{$hashkey}\n";
			$m++;
		}

	}
	$out .= "#".$prog."\t".$tier."\n";
	$out .= "&\n";
	my $length = @start;
	my $k;
	for(my $i=0; $i <= 500; $i++){
		my $tempscore = 0;
		for($k = 0; $k < $length; $k++){
			if($start[$k] <= $i && $stop[$k] >= $i){
				if($mit_score == 1){
					$tempscore += $score[$k];
				}
				else{$tempscore++;}
			}
		}
		$out .= $i." ".$tempscore."\n";
	}
	return $out;
}
sub mehrere{
	$out = "";
	my @data_datein = glob "*.data";
	my $outanf = "";
	my $k = 0;
	my $prog;
	my $tier;

	my @grace_datein = glob "$outdir/*.grace";

	foreach my $file (@grace_datein){
	  
	  if($file !~ m/all.grace/) {

	    open(FI,"< $file") or die "error by opening input file";
	    open(FO,"> " . $outdir . "/all.grace") or die "error by opening output file";
	    my @lines = <FI>; chop @lines; my $line;
	    foreach $line (@lines){
	      if($line =~ /#/){
		 my @z = split(/\t/,$line);
		 $prog = substr($z[0],1,10);
		 $tier = $z[1];
		 $tier = substr($tier, 0 , index($tier,'.'));
		 print $tier."\n";
		 if($tierein == 1){
		   $outanf .= "@    s".$k." legend  \"".$tier."\"\n";
		 }
		 else{
		   $outanf .= "@    s".$k." legend  \"".$prog."\"\n";
		 }
		 $outanf .= "@\t\ts".$k." line color $color\n";
		 $color++;
		 
		 # Vermeide Farbe 5 (gelb)
		 if($color == 5) {
		   $color++;
		 }
		 $k++;
	       }
	      if($line =~ /@/){
	      }
	      else{
		$out .= $line."\n";
	      }
	    }
	  }
	}
	$out = $outanf.$out;
	print FO $out;
	close(FO);
	system("xmgrace $outdir/all.grace -hardcopy -printfile $outdir/all.ps");
}

sub vergleichen{
	open(FI,"<" . $outdir . "/all.grace") or die "error by opening input file";
	open(FO,">" . $outdir . "/vergleich.grace") or die "error by opening output file";
	$out = "";
	my @array;
	foreach my $text (<FI>){
		chomp($text);
		my $sub = substr($text,0,1);
		if($sub ne "#" && $_ ne "&" && $sub ne "@"){
			my @zahl = split(/ /, $text);
			$array[$zahl[0]] += $zahl[1];
		}
	}
	for(my $i = 0; $i <=500; $i++){
		$out .= $i." ".$array[$i]."\n";
	}
	print FO $out;
	close(F0);
	close(FI);
	system("xmgrace $outdir/vergleich.grace -hardcopy -printfile $outdir/vergleich.ps");
}
