#!/pkg/perl-5.6.1/bin/perl

use strict;
use warnings;
use Mail::Util qw(read_mbox);
use Mail::Internet;


my $folder = $ARGV[0] || die "Must specify a folder\n";
die "File not found: $folder" unless -e $folder;

my @messages = read_mbox($folder);
my %letter_hist;
my %from_hist;
my $total_size = 0;
my $count = 0;

handle_message($_) for (@messages);

report();

sub handle_message {
  my $message = $_[0];
  my $mi = Mail::Internet->new($message);

  $count++;
  $total_size += length $mi->as_string;
  letter_histogram( $mi->as_string );
  from_histogram( $mi->head->get("From:") );
}

sub pairify {
  my @out;
  while (my($k,$v) = each %{$_[0]}) {
    push @out,[$k,$v];
  }
  @out;
}

sub report {
  print "Messages : $count\n";
  print "Total Size : $total_size\n";
  print "Average Size : ", int($total_size/$count),"\n";
  my @sortedchar =
    sort { $a->[1] <=> $b->[1] }
      grep { $_->[1] > 1 }
        pairify \%letter_hist;
  print "Most Common Characters:\n";
  for (reverse @sortedchar[-5..-1]) {
    print "$_->[0] : $_->[1]\n";
  }
  print "Least Common Characters:\n";
  for (reverse @sortedchar[0..5]) {
    print "$_->[0] : $_->[1]\n";
  }
  my @sortedfrom = sort { $a->[1] <=> $b->[1] }
    pairify \%from_hist;

  print "Most Common Domains:\n";
  for (reverse @sortedfrom[-5..-1]) {
    print "$_->[0] : $_->[1]\n";
  }
}


sub from_histogram {
  my ($dom) = $_[0] =~ /\@(?:.+\.)?([\w-]+\.\w+)/;
  $from_hist{$dom}++;

}


sub letter_histogram {
  my $strdex = (length $_[0])-1;
  $letter_hist{substr($_[0],$_,1)}++     for (0..$strdex);
}

