#!/usr/bin/perl
#
# Plot the outputs of a dccp_probe test run
# The slowdown in comparison to running gnuplot directly is about 1.4 ... 6 seconds
#---------------------------------------------------------------------------------------
$out="/tmp/dccp_probe.out"; 
our (@plots,$title,$ylabel,$print_pic,$pic_name,$extras);

use Getopt::Std;

# SUBROUTINES -----------------------------------------------------------------------------
# show a plot of the results regarding the count of years
sub do_plot { 
  my $plotcmd = "plot ";

  open (OUT,"| gnuplot -persist") || die "Can not popen to gnuplot: $!\n";
  print OUT  "set data style linespoints\n";
  print OUT  "set terminal png; set output \"${pic_name}.png\"\n" if $print_pic;
  print OUT  "set title \"$title (s=$len bytes)\"\n";
  print OUT  "set xlabel \"time (seconds)\"\n";  
  print OUT  "set ylabel \'$ylabel\'\n";   
  print OUT  "f(x) = x*8/1000000\n";			# conversion routine      		
  print OUT  "$extras\n";				# additional pre-plot cmds
  print OUT  "plot ";					# plot starts here
  for (0..$#plots) {
	print OUT "\"$out\" using   $plots[$_]->{'using'} " .
	          "title \"$plots[$_]->{'title'}\"" .  ($_ == $#plots? "\n" : ", ");
  }
  close OUT;
}

#---------------------------------------------------------------------------------------
# FIELD USAGE:
# 1           2          3           4     5  6     7   8        9        10   11
# sec.usec   src:sport   dst:dport   ccid  s  rtt   p   X_calc   X_recv   X    t_ipi
#---------------------------------------------------------------------------------------
sub x_recv() {
 $pic_name = "X_recv";
 $ylabel   = "Mbits/sec";
 push(@plots, { 'using' => '1:(f($9))',  'title' => "X_recv" }); 
}

sub x_calc() {
 $pic_name = "X_calc";
 $ylabel   = "Mbits/sec";
 push(@plots, { 'using' => '1:(f($8))',  'title' => "X_calc" }); 
}

sub x() {
 $pic_name = "X";
 $ylabel   = "Mbits/sec";
 push(@plots, { 'using' => '1:(f($10))', 'title' => "X" }); 
}
# all three of the above
sub transmit_rate() {
 $pic_name = "transmit_rate";
 $ylabel   = "Transmission rate in Mbits/sec";
 $extras   = "#set yrange [0:20]";
 push(@plots, { 'using' => '1:(f($8))',  'title' => "X_calc" }); 
 push(@plots, { 'using' => '1:(f($9))',  'title' => "X_recv" }); 
 push(@plots, { 'using' => '1:(f($10))', 'title' => "X" }); 
}

sub t_ipi() {
 $pic_name = "t_ipi";
 $ylabel   = "microseconds";
 $extras   = "set logscale y";
 push(@plots, { 'using' => '1:11', 'title' => "t_ipi"}); 
}

sub loss_rate() {
 $pic_name = "loss_rate";
 $ylabel   = "%";  
 #$extras   = "set yrange [0:100]";
 $extras   = "set logscale y";			# not advisable with p = 0
 push(@plots, { 'using' => '1:($7/10000)', 'title' => "loss event rate p"}); 
}

sub rtt() {
 $pic_name = "rtt";	
 $ylabel   = "milliseconds";
 push(@plots, { 'using' => '1:($6/1e3)', 'title' => "RTT"}); 
}

#- MAIN SCRIPT -------------------------------------------------------------------------
foreach (@ARGV) {
	@plots = ();
	eval $_ && do_plot;
}
