#! /usr/local/bin/perl

$stem = "";
$substem = "";
$tmax = 1e8;

while($ARGV[0] =~ /^-[domsh]/) {
  $_ = shift;
  if(/^-d/) {
    $delay = ($ARGV[0] =~ /^\d+$/) ? shift : 15;
  } elsif(/^-o/) {
    $stem = shift;
  } elsif(/^-m/) {
    $tmax = shift;
  } elsif(/^-s/) {
    $snapshot = 1;
  } elsif(/^-h/) {
    $html = 1;
  }
}

if(-t STDIN && ! -f $ARGV[0]) {
  print STDERR <<EOF;
Usage: $0 [-s] [-h] [-d delay] [-m tmax] [-o outstem] mtrace-outfile
Summarizes MBone loss statistics for display by gnuplot.
Reads the output of "mtrace -l", produces files to make gnuplot display
loss-ratio-as-a-function-of-time for each hop in the path being traced.
Writes files <stem>.data and <stem>.gplot, the latter being a file of
gnuplot commands to be read using the command
  load "<stem>.gplot"
The default <stem> is the name of the input file.
Options:
  -s Invoke gnuplot, and take GIF-format snapshot of it in <stem>.gif
  -h Write HTML summarizing results to standard output
  -d make gnuplot pause 'delay' seconds after plotting,
	so \"gnuplot <stem>.gplot\" doesn't immediately exit
  -m even if the trace runs longer, plot only first 'tmax' seconds of data
  -o Use outstem, rather than name of mtrace file, as the stem name
	for other output files.
EOF
  exit(1);
}

$stem = $ARGV[0] unless $stem;

($title = $stem) =~ s'.*/'';

print STDERR "Writing $stem.data, $stem.gplot\n";

(print STDERR "Can't create gnuplot-data file $stem.data: $!\n"), exit(1)
  unless open(MDATA, ">$stem.data");

(print STDERR "Can't create gnuplot-command file $stem.gplot: $!\n"), exit(1)
  unless open(MPLOT, ">$stem.gplot");


print MPLOT <<EOF;
# To display the data, run gnuplot, and type
#   load "$stem.gplot"

set data style linespoints
set xlabel "Time (secs)"
set ylabel "Loss(%)(in 10 sec)"
set title "$title"
EOF

while(<>) {
  if(/^Mtrace from/) {
    print MPLOT "# ", $_;

    print "<A NAME=\"$stem$substem\"><H2>$stem -- $_</H2></A>\n" if $html;
  } elsif(/Results after (\d+) seconds/) {
    $newt = $1;
    last if $newt > $tmax;

    &finishplot(1) if ($newt < $t);

    print MDATA join(" ", $t, @vals), "\n" if @vals;
    @vals = ();
    $t = sprintf("%4d", $newt);

  } elsif(/^\d+\.\S+\s+(\S+)/) {
    $router = $1;
    $_ = <>;	# Get next line -- it includes the incremental loss.
    ($pct) = (/([-\d+]+)%/);
    push(@vals, sprintf("%3d", $pct));

    if($routers[$#vals] ne "" && $routers[$#vals] ne $router) {
	print STDERR "Yow, path changed at t = $t seconds; ",$#vals,"'th hop was $routers[$#vals], now $router
Discarding previous data!\n";
    }
    $routers[$#vals] = $router;
    $min[$#vals] = $max[$#vals] = $pct unless defined($min[$#vals]);
    $min[$#vals] = $pct if $min[$#vals] > $pct;
    $max[$#vals] = $pct if $max[$#vals] < $pct;
    $range[$#vals] = $max[$#vals] - $min[$#vals];
  }
}



&finishplot(0);

sub finishplot {
  local($more) = @_;

  print "(<A HREF=\"raw/$stem\">raw data</A>, <A HREF=\"$stem.gplot\">GNUplot commands</A>, <A HREF=\"$stem$substem.data\">GNUplot data</A>.)<P>\n"
	if $html;

  print MDATA join(" ", $t, @vals), "\n" if @vals;

  $stuff = "Nodes, with loss variation (percent over mtrace -l's 10-second intervals):\n";
  print STDERR $stuff;
  print MPLOT "# ", $stuff;
  print $stuff if $html;

  
  print "<PRE>\n" if $html;
  foreach $_ (0..$#min) {
    $stuff = sprintf("Hop %2d  loss %2d..%2d%%  %s\n", $_, $min[$_],$max[$_], $routers[$_]);
    print STDERR $stuff;
    print MPLOT "# ", $stuff;
    print $stuff if $html;
  }
  print "</PRE>\n" if $html;
  print "<IMG SRC=\"$stem$substem.gif\">\n" if $html;
  print "<HR><P>\n";

  print MPLOT "\n";

  @sorted = sort { $max[$b]-$min[$b] <=> $max[$a]-$min[$a] } ( 0..$#min );
  $replot = "";
  foreach $_ (@sorted) {
    print MPLOT "set yrange [-20:60]\n";
    printf MPLOT "%splot \"%s%s.data\" using 1:%d title \"%s [hop %d]\"\n",
	$replot, $stem, $substem, $_+2, $routers[$_], $_;
    $replot = "re";
  }


  print MPLOT "! import -window Gnuplot $stem$substem.gif\n" if $snapshot;
  print MPLOT "pause $delay\n" if $delay;

  close(MDATA);

  @max = @min = @routers = @vals = ();

  if($more) {
    $re = "";
    $substem = ($substem =~ /-(\d+)$/) ? sprintf("-%d", $1+1) : "-2";
    open(MDATA, ">$stem$substem.data");
    ($title = $stem . $substem) =~ s'.*/'';
    print "<P><H3>Path changed during tracing...</H3>\n" if $html;
    print MPLOT "set title \"$title\"\n";
  } else {
    close(MPLOT);
  }
}


print STDERR "To show results, invoke gnuplot, and tell it to
	load \"$stem.gplot\"\n";

$| = 1; print "";

if(($delay || $snapshot) && $ENV{"DISPLAY"}) {
  exec "gnuplot", "$stem.gplot";
}

