#! /usr/bin/perl -w

# Copyright (C) 2008 Paul Kuliniewicz <paul@kuliniewicz.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA.

use strict;

use Getopt::Std;

my %opts;
getopts('n:', \%opts);
my $alphabets = $opts{'n'} || 1;

my @counts = ();
my @totals = ();
my $i = 0;
while (<>)
{
	my @letters = grep /[A-Za-z]/, map lc, split //;
	foreach (@letters)
	{
		++$counts[$i]{$_};
		++$totals[$i];
		$i = ($i + 1) % $alphabets;
	}
}

my @ics = ();
foreach my $i (0 .. $alphabets - 1)
{
	foreach (values %{$counts[$i]})
	{
		$ics[$i] += $_ * ($_ - 1) if $_ > 0;
	}
	$ics[$i] /= $totals[$i] * ($totals[$i] - 1) / 26;
}

foreach ('a' .. 'z')
{
	print "$_\t";
	foreach my $i (0 .. $alphabets - 1)
	{
		printf "%7d\t", $counts[$i]{$_} || 0;
	}
	print "\n";
}

printf "\n";

print "Total:\t";
foreach my $i (0 .. $alphabets - 1)
{
	printf "%7d\t", $totals[$i];
}
printf "\n";

print "IC:\t";
foreach my $i (0 .. $alphabets - 1)
{
	printf "%.5f\t", $ics[$i];
}
printf "\n";

exit 0;
