#!/usr/bin/perl -w
use strict;

sub fastant ($);

my %totals = ();

while (<>) {
  s/#.*$//;
  s/^\s+//;
  next if ($_ eq '');

  if (/(\S+)\s+                # Experiment
       (\S+)\s+                # Frequency
       (\S+)\s+                # Stations
       (\d+)\s+(\d\d)(\d\d)\s+ # start
       (\d+)\s+(\d\d)(\d\d)\s+ # end
       (\S+)           # PI
      /x) {      
    my $exper = $1;
    my $freq = $2;
    my $stations = $3;
    my $start = $4*24+$5+$6/60;
    my $end = $7*24+$8+$9/60;
    my $pi = $10;

    next if ($pi=~/check/);
    my $evlbi = 0;
    $evlbi = 1 if ($pi=~/eVLBI/);

    my @stations = split /-/, $stations;
    if (@stations<2) {
      @stations = $stations =~ /(.{1,2})/g;
    }

    my $rate = undef;
    my $bandwidth = undef;
    if ($freq=~/(\d)p-(\d)IF\/(\d+)/) {
      $rate = $1*$2*$3*2*2; # Mbps
      $bandwidth = $3;
    } elsif ($freq=~/(\d)p-(\d)IF-(\d+)/) {
      $rate = $1*$2*$3*2*2; # Mbps
      $bandwidth = $3;
    } elsif ($freq=~/-(\d)p-(\d)IF/) {
      $rate = $1*$2*16*2*2; # Mbps
      $bandwidth = 16;
    } elsif ($freq=~/1Gbps/) {
      $rate = 1024;
      $bandwidth = 'Mixed';
    } else {
      warn "Skipping mode $freq\n";
    }

    my $length = $end-$start;

    printf "%-7s", $exper;

    if (defined $rate) {
      printf "%4d Mbps", $rate;
    } else {
      print " Unknown ";
    }

    printf " %4.1f hrs", $length;

    if ($evlbi) {
      print "  eVLBI\n";
    } else {
      print "\n";
      if (defined $rate) {
	foreach (@stations) {
	  my $thisrate = $rate;
	  if (! fastant($_)) {
	    $thisrate/=2 if ($rate>512);
	    $thisrate/=2 if ($rate==512 && $bandwidth<64);
	  }
	  my $usage = $length*60*60*$thisrate/8/1e6;
	  printf "  %2s %.1f TBytes\n", $_, $usage;
	  if (exists $totals{$_}) {
	    $totals{$_} += $usage;
	  } else {
	    $totals{$_} = $usage;
	  }
	}
      }
    }
  } elsif (/Version/) {
    # Ignore
  } elsif (/Basedate/) {
    # Ignore
  } elsif (/^\s*Start/) {
    # Ignore
  } elsif (/^\s*Stop/) {
    # Ignore
  } else {
    warn "Skipping $_";
  }
}

print "\nStation Totals:\n";

while (my ($ant,$usage) = each %totals) {
  printf("$ant  %4.1f TBytes\n", $usage);
}



sub fastant ($) {
  my $ant = shift;
  return 0 if ($ant eq 'Td');
  return 1;
}
