#! /usr/bin/perl
use warnings;
use strict;
use FindBin;

# This helper script determines the average ram size from the package's
# point of view.  It computes the crowding average.  For example, in
#
#   --------------
#   0001 RAM X (1)
#   --------------
#   pkg-x1
#
#   --------------
#   0002 RAM Y (3)
#   --------------
#   pkg-y1
#   pkg-y2
#   pkg-y3
#
#   --------------
#   0003 RAM Z (6)
#   --------------
#   pkg-z1
#   pkg-z2
#   pkg-z3
#   pkg-z4
#   pkg-z5
#   pkg-z6
#
#   --------------
#   0004 RAM Q (0)
#   --------------
#
# the average ram size is
#
#   ( 1*1 + 3*3 + 6*6 + 0*0 ) / ( 1 + 3 + 6 + 0 )
#     = 46 / 10 = 4.60 packages.
#
# Notice that the average size is as seen from the package's not the
# ram's point of view.  In particular, notice that the empty
# ram [0004 RAM Q] fails to reduce the average at all, because no
# package is there to see its emptiness.  Empty rams do not influence
# this average, because they do not relieve package crowding.  One can
# only reduce the crowding average by actually splitting the crowded
# rams up.
#
# This script counts actual listed packages.  It ignores the number in
# parentheses at each title-line's end.
#
#   usage: avg-crowd { debram.txt }
#
# If no debram.txt file is named, the script examines the main
# debram.txt file in this script's parent directory.
#
#

our $debram    = @ARGV ? shift(@ARGV)
  : "${FindBin::RealBin}/../debram.txt";
our $ndig      =  4;
our $mark      = "THE RAMIFICATION\n";
our $fmt_n_pkg = "%5d";
our $fmt_n_ram = "%3d";
our $fmt_avg   = "%6.2f";

# Count.
my @n;
open F, '<', $debram;
1 while <F> ne $mark;
{
  my $n;
  my $intitle = 0;
  while ( 1 ) {
    local $_ = <F>;
    if ( /^-----/ ) {
      push @n, $n if !$intitle && defined($n);
      $n = 0;
      $intitle = !$intitle;
    }
    elsif ( $intitle ) {
      last if $intitle && !( defined() && /^\d{$ndig}/o )
    }
    else {
      ++$n if /\S/;
    }
  }
}
close F;

# Calculate.
my $crowd = 0;
my $n_pkg = 0;
$crowd   += $_*$_, $n_pkg += $_ for @n;
my $avg   = $crowd / $n_pkg;

# Output.
printf "A total of $fmt_n_pkg packages "
  . "spread over $fmt_n_ram branches.\n"
  . "The average package crowd is $fmt_avg in number.\n",
  $n_pkg, scalar(@n), $avg;

