#! /usr/bin/perl

use strict;
use warnings;

sub wilson_interval {
	my ($x, $n) = @_;
	my $z = 1.96;  # 95% confidence interval

	my $p = $x / $n;
	my $min = ($p + $z * $z / (2 * $n) - $z * sqrt($p * (1 - $p) / $n + $z * $z / (4 * $n * $n))) / (1 + $z * $z / $n);
	my $max = ($p + $z * $z / (2 * $n) + $z * sqrt($p * (1 - $p) / $n + $z * $z / (4 * $n * $n))) / (1 + $z * $z / $n);

	$min = 0 if ($min < 0);

	return ($min, $max);
}

my %buckets = ();

while (<>) {
	chomp;
	my (@x) = split /\s+/, $_;

	my $num_packets = scalar @x;
	my $num_drops = grep { /\*/ } @x;

	$buckets{$num_packets}->{'num_bursts'}++;
	$buckets{$num_packets}->{'num_drops'} += $num_drops;
	if ($num_drops > 0) {
		$buckets{$num_packets}->{'bursts_with_drops'}++;
	}
}

for my $n (sort { $a <=> $b } keys %buckets) {
	my $num_bursts = $buckets{$n}->{'num_bursts'} // 0;
	my $num_drops = $buckets{$n}->{'num_drops'} // 0;
	my $bursts_with_drops = $buckets{$n}->{'bursts_with_drops'} // 0;

	my $drop_rate = $num_drops / ($n * $num_bursts);
	my $drop_event_rate = $bursts_with_drops / $num_bursts;

	my ($drop_rate_min, $drop_rate_max) = wilson_interval($num_drops, $n * $num_bursts);
	my ($drop_event_rate_min, $drop_event_rate_max) = wilson_interval($bursts_with_drops, $num_bursts);

	printf "%3d: drop_rate %.5f  95%%ci = [%.5f, %.5f] (%4d/%8d)   drop_event_rate %.5f  95%%ci = [%.5f, %.5f] (%3d/%4d)\n",
		$n,
		$drop_rate, $drop_rate_min, $drop_rate_max, $num_drops, $n * $num_bursts,
		$drop_event_rate, $drop_event_rate_min, $drop_event_rate_max, $bursts_with_drops, $num_bursts;
}
