#!/usr/bin/perl
use strict;


if(!(-e "./motivplot")) {
	print "folder motivplot not found\n";
	exit;
}
if(!(-e "./graphplot")) {
	print "folder graphplot not found\n";
	exit;
}


my $motifheader;
my $motifbody;
my $graphheader;
my $graphbody;
my $maxsymbolnr = 0;
my $maxscore = 0;
my @apps;







# Oeffne Grace Datei mit Graphen
open(FI,"<graphplot/all.grace") or die "error by opening input file";
foreach my $line (<FI>){
    
    my @linebroken = split(" ", $line);

    if($line !~ m/^@/) {
      if($maxscore < $linebroken[1]) {
	$maxscore = $linebroken[1];
      }
    }
}
close(FI);


# specifies how big the neg. part of the y axis shall be
# default is 3, depends on how big the y graph axis is. 
my $neg_axis_scaling = $maxscore / 5;


# Oeffne mracemotif/all.grace Datei
open(FI,"<motivplot/all.grace") or die "error by opening input file";

foreach my $line (<FI>){
    
    if($line =~ m/^@/) {
	
      # extract symbol nr. 
	
      my @linebroken = split(" ", $line);
      
      # get nr. of symbol
      my $symbolnr = substr($linebroken[1], 1,1);
      
      if($symbolnr > $maxsymbolnr) {
	$maxsymbolnr = $symbolnr;
      }
      
      # extract app name
      if($line =~ m/legend/) {
	my $appname = $linebroken[3];
	$appname =~ s/\"//g;
	push (@apps, $appname);
      }
      
      # Speicher motif header
      $motifheader .= $line;
    } else {

      if(! ($line =~ m/&/ ||  $line =~ m /\#/)) {

	my @linebroken = split(" ", $line);

	$line = $linebroken[0] . " -" . ($linebroken[1] * $neg_axis_scaling) . "\n";
      } 

      $motifbody .= $line;
    } 
}

close(FI);

# Oeffne Grace Datei mit Graphen
open(FI,"<graphplot/all.grace") or die "error by opening input file";


foreach my $line (<FI>){

    my $appfound = 0;
    my @linebroken = split(" ", $line);

    if($line =~ m/^@/) {

      my $symbolnr = substr($linebroken[1], 1, 1);

      if($line =~ m/legend/) {

	my $appname = $linebroken[3];
	$appname =~ s/\"//g;
	
	# look if the appname already is in apps list
	for(my $loop = 0; $loop < ($#apps + 1); $loop++) {
	 
	  if($appname =~ m/$apps[$loop]/) {
	    $appfound = 1;
	    last;
	  }
	}

	# if not found copy this "legend" line 
	if($appfound == 0) {
	  
	  my $newsymbolnr = $symbolnr + $maxsymbolnr + 1;

	  $line =~ s/s$symbolnr/s$newsymbolnr/;
	  $graphheader .= $line;
	}
      } else {
	
	  my $newsymbolnr = $symbolnr + $maxsymbolnr + 1;

	  $line =~ s/s$symbolnr/s$newsymbolnr/;
	  $graphheader .= $line;
      }
    } else {
      
      if($maxscore < $linebroken[1]) {
	$maxscore = $linebroken[1];
      }

      $graphbody .= $line;
    }
}






mkdir("fusionplot");

open(FO,">fusionplot/all.grace") or die "error by opening output file";

print FO $motifheader . $graphheader . $motifbody . $graphbody;
close(FO);

system("xmgrace fusionplot/all.grace -hardcopy -printfile fusionplot/all..ps");

