#!/usr/local/bin/perl
#                                      (C) Hans Wolfgang Loidl, November 1995
#############################################################################
# Time-stamp: <Sun Nov  5 1995 00:23:45 Stardate: [-31]6545.08 hwloidl>
#
# Usage: SN [options] <gr-file>
#
# Create a summary of spark names that occur in gr-file (only END events in 
# gr-file are necessary). Creates a gnuplot impulses graph (spark names by 
# number of threads) as summary.
#
# Options:
#  -h        ... help; print this text.
#  -v        ... verbose mode.
#
#############################################################################

$gran_dir = $ENV{'GRANDIR'};
if ( $gran_dir eq "" ) {
    print STDERR "SN: Warning: Env variable GRANDIR is undefined\n";
}

push(@INC, $gran_dir, $gran_dir . "/bin");
# print STDERR "INC: " . join(':',@INC) . "\n";

require "getopts.pl";
require "par-aux.pl";
require "stats.pl";

&Getopts('hv');  

do process_options();

if ( $opt_v ) { do print_verbose_message(); }

# ---------------------------------------------------------------------------
# Init
# ---------------------------------------------------------------------------

chop($date = `date`);
chop($stardate = `stardate`);

open (IN,"<$input") || die "$!: $input";
$n = 0;
$is_end=0;
while (<IN>) {
    $is_end = 1 if /END\s+(\w+).*SN\s+(\d+).*RT\s*(\d+)/;
    next unless $is_end;
    $n++;
    $sn = $2;
    $rt = $3;
    #$sn_dec = hex($sn);
    $num_sns{$sn}++;
    $rts_sns{$sn} += $rt;
    #do inc ($sn_dec);
    $is_end=0;
}
close (IN);

@sorted_keys=sort {$a<=>$b} keys(%num_sns);
#$max_val=&list_max(@sorted_keys);

open (SUM,">$summary") || die "$!: $summary";

print SUM "# Generated by SN at $date $stardate\n";
print SUM "# Input file: $input\n";
print SUM "#" . "-"x77 . "\n";
print SUM "Total number of threads: $n\n";
print SUM "# Format: SN: Spark Site N: Number of threads AVG: average RT\n";
# . "RTS: Sum of RTs ";

foreach $k (@sorted_keys) {
    $num = $num_sns{$k};
    $rts = $rts_sns{$k};
    $avg = $rts/$num;
    #print SUM "SN: $k \tN: $num \tRTS: $rts \tAVG: $avg\n";
    print SUM "$k \t$num \t$avg\n";
}
close (SUM);

open (OUT,">$output") || die "$!: $output";
print OUT "# Generated by SN at $date $stardate\n";
print OUT "# Input file: $input\n";
print OUT "#" . "-"x77 . "\n";

$max_val=0;
foreach $k (@sorted_keys) {
    $num = $num_sns{$k};
    $max_val = $num      if $num > $max_val;
    print OUT "$k\t$num\n";
}
close (OUT);

do write_gp($gp_file,$ps_file); 

print "Gnu plotting figures ...\n";
system "gnuplot $gp_file";

print "Extending thickness of impulses ...\n";
$ext_size = 100;
$gray = 0.3;
do gp_ext($ps_file);

exit (0);

# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

sub inc {
    local ($sn) = @_;
    local (@k);
    
    @k = keys(%num_sns);
    if ( &is_elem($sn, @k) ) { 
	$num_sns{$sn}++;
    } else {
	$num_sns{$sn} = 1;
    }
}

# ----------------------------------------------------------------------------

sub is_elem { 
    local ($x,@list) = @_;
    local ($found);

    for ($found = 0, $y = shift(@list); 
	 $#list == -1 || $found;  
	 $found = ($x == $y), $y = shift(@list)) {}

    return ($found);
}

# ----------------------------------------------------------------------------

# -----------------------------------------------------------------------------

sub process_options {

    if ( $opt_h ) {                      
	open(ME,$0) || die "Can't open myself ($0): $!\n";
	$n = 0;
	while (<ME>) {
	    last if $_ =~ /^$/;
	    print $_;
	    $n++;
	}
	close(ME);
	exit ;
    }
    
    if ( $opt_s ) {
	$opt_s =~ s/[\(\)\[\]]//g;
	@sparks = split(/[,;. ]+/, $opt_s);
    } else {
	@sparks = ( 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15);
    }

    if ( $#ARGV != 0 ) {
	print "Usage: $0 [options] <gr-file>\n;";
	print "Use -h option to get details\n";
	exit 1;
    }

    $input = $ARGV[0];
    ($ps_file = $input) =~ s/\.gr/-SN.ps/;
    ($gp_file = $input) =~ s/\.gr/-SN.gp/;
    ($summary = $input) =~ s/\.gr/-SN.sn/;

    #($basename = $gr_file) =~ s/\.gr//;
    #$rts_file = $basename . ".rts";        # "RTS";
    #$gran_file = "g.ps"; # $basename . ".ps";
    #$rts_file = $gr_file;
    #$rts_file =~ s/\.gr/.rts/g;

    if ( $opt_o ) {
	$output = $opt_o;
    } else {
	($output = $input) =~ s/\.gr/-SN.dat/;
    }

    if ( $opt_e ) {
	$ext_size = $opt_e; 
    } else {
	$ext_size = 100; 
    }
    
    if ( $opt_i ) {
	$gray = $opt_i; 
    } else {
	$gray = 0; 
    }
}

# -----------------------------------------------------------------------------

sub print_verbose_message {
    print "Input: $input \tOutput: $output\n";
}

# -----------------------------------------------------------------------------

# ToDo: Takes these from global module:

# ----------------------------------------------------------------------------

sub gp_ext {
    local (@file_names) = @_;
    local ($file_name);
    local ($ps_file_name);
    local ($prg);

    #$prg = system "which gp-ext-imp";
    #print "  Using script $prg for impuls extension\n";
    $prg = $ENV{GRANDIR} ? $ENV{GRANDIR} . "/bin/gp-ext-imp" 
	                 : $ENV{HOME} . "/bin/gp-ext-imp" ;
    if ( $opt_v ) {
	print "    (using script $prg)\n";
    }

    foreach $file_name (@file_names) {
	$ps_file_name = $file_name; # NB change to orig !!!!&dat2ps_name($file_name);
        system "$prg -w $ext_size -g $gray " . 
               $ps_file_name  . " " . 
               $ps_file_name . "2" ;
        system "mv " . $ps_file_name . "2 " . $ps_file_name;
    }
}

# ----------------------------------------------------------------------------

sub write_gp { 
    local ($gp_file,$ps_file) = @_;
    local ($str);

    $xsize = 1;
    $ysize = 1;
    $xlabel = "Spark sites";
    $ylabel = "Number of threads";
    $xstart = &list_min(@sorted_keys);
    $xend = &list_max(@sorted_keys);
    $ymax = $max_val; 
    $xtics = ""; "(" . join(',',@sorted_keys) . ")\n";
    $in_file = $output;
    $out_file = $ps_file;

    open (GP,">$gp_file") || die "$!: $gp_file";
    print GP "set term postscript \"Roman\" 20\n";

    # identical to the part in write_gp_record of RTS2gran

    $str = "set size " . $xsize . "," . $ysize . "\n" .
           "set xlabel \"" . $xlabel . "\"\n" .
           "set ylabel \"" . $ylabel . "\"\n" .
           ($xstart eq "" ? "" 
                          : "set xrange [" . int($xstart) .":" . int($xend) . "]\n") .
           ($opt_Y ? 
	      ("set yrange [" . (index($logaxes,"y") != -1 ? 1 : 0) . ":$opt_Y]\n") :
	      ($ymax eq "" ? "" 
                        : "set yrange [" . (index($logaxes,"y") != -1 ? 1 : 0) . 
                          ":" . &list_max(2,int($ymax+$ymax/5)) . "]\n")) .
           ($xtics ne "" ? "set xtics $xtics" : "") . 
	   "set tics out\n" .
           "set border\n" .
           ( $nPEs!=0 ? "set title \"$nPEs PEs\"\n" : "" ) .
	   "set nokey \n" .
           "set nozeroaxis\n" .
	   "set format xy \"%8.8g\"\n" .
           (index($logaxes,"x") != -1 ? 
               "set logscale x\n" : 
               "set nologscale x\n") .
           (index($logaxes,"y") != -1 ? 
               "set logscale y\n" : 
               "set nologscale y\n") .
           "set output \"" . $out_file . "\"\n" .
	   "plot \"" . $in_file . "\" with impulses\n\n";
    print GP $str;
    close (GP);
}

# ----------------------------------------------------------------------------
