#! /usr/bin/perl -w
use diagnostics;
use strict;
use Date::Parse;

my $message;
my ($fromdate, $date);
my @messages;
my %dates;

while (<>)
{
	chomp;
	if (/^From /)
	{
		if (defined $message)
		{
			push @messages, ($message);
			$dates{$message} = defined $date ? $date : $fromdate;
		}
		$message = "$_\n";
		/^From [^ ]* (.*)/;
		$fromdate = $1;
		$fromdate =~ s/ +/ /g;
		$fromdate = str2time $fromdate;
		$date = undef;
	}
	elsif (!(defined $date) && /^Date: (.*)/)
	{
		$message .= "$_\n";
		$date = str2time $1;
	}
	else
	{
		$message .= "$_\n";
	}
}

if (defined $message)
{
	push @messages, ($message);
	$dates{$message} = defined $date ? $date : $fromdate;
}

print (sort { $dates{$a} <=> $dates{$b} } @messages);

