#!/usr/bin/perl -w

@sep=("-----Original Message-----");
$msg=0;

while(<>){
    chomp;s/\r$//;
    $trunc=$_;
    $trunc=~s/^\s+//;
    $trunc=~s/\s+$//;
    if(in($trunc,@sep)){
        ++$msg;
    }else{
        push @{$msg[$msg]},$_;
    }
}
++$msg;

for($i=0;$i<$msg;++$i){
    unshift @{$msg[$i]},(getdate(@{$msg[$i]}),$i);
}

@msg=sort {
    ($da,$ia)=@$a;
    ($db,$ib)=@$b;
    if($da ne "" && $db ne ""){
        return $da<=>$db;
    }
    return $ib<=>$ia;
} @msg;

foreach $m (@msg){
    shift @$m;
    shift @$m;
    --$msg;
    $maxlen=0;
    foreach (@$m){
        s/\s+$//;
        $maxlen=length($_) if length($_)>$maxlen;
    }

    $hashdr=($$m[0]=~/^From:/i);

    $first=1;
    foreach (@$m){
        if($hashdr||$maxlen<80){
            print '>'x$msg,"$_\n";
        }else{
            print '>'x$msg,"\n" unless $first;
            $first=0;
            wrap('>'x$msg,$_);
        }
        $hashdr=0 if $_ eq "";
    }
    print "\n" if $msg;
}

sub wrap{
    my($pre,$line)=@_;
    my $w=79-length($pre);
    while(length($line)>79-length($pre)){
        if($line=~s/^(.{0,$w})\s+//){
            print "$pre$1\n";
        }else{
            $line=~s/^(\S+)\s*//;
            print "$pre$1\n";
        }
    }
    print "$pre$line\n" unless $line eq "";
}

sub in{
    my $x=shift @_;
    my $t;
    foreach $t (@_){
        return 1 if $x eq $t;
    }
    return 0;
}

sub getdate{
    my $l;
    foreach $l (@_){
        return "" if $l=~/^\s*$/;
        next unless $l=~/^Sent:\s*/i;
        my ($day,$mon,$year,$hour,$min);
        if($l=~/^Sent:\s*(?:(?:[a-zA-Z]*day|Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s*)?(\d+),?\s+(\S+),?\s+(\d{4}),?\s+(\d+):(\d+)\s*([ap]m)?/i){
            ($day,$mon,$year,$hour,$min)=($1,$2,$3,$4,$5);
            if(defined $6){
                $hour=0 if $hour==12;
                $hour+=12 if lc($6) eq "pm";
            }
        }elsif($l=~/^Sent:\s*(?:(?:[a-zA-Z]*day|Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s*)?(\S+),?\s+(\d+),?\s+(\d{4}),?\s+(\d+):(\d+)([ap]m)?/i){
            ($mon,$day,$year,$hour,$min)=($1,$2,$3,$4,$5);
            if(defined $6){
                $hour=0 if $hour==12;
                $hour+=12 if lc($6) eq "pm";
            }
        }else{
            die "Can't parse date: $l\n";
        }
        if($mon!~/\d/){
            $mon=lc substr($mon,0,3) unless $mon=~/\d/;
            my %mon=(
                "jan"=>1,
                "feb"=>2,
                "mar"=>3,
                "apr"=>4,
                "may"=>5,
                "jun"=>6,
                "jul"=>7,
                "aug"=>8,
                "sep"=>9,
                "oct"=>10,
                "nov"=>11,
                "dec"=>12);
            $mon=$mon{$mon};
            die "Can't parse month $mon: $l\n" unless defined $mon;
        }
        return sprintf("%04d%02d%02d%02d%02d",$year,$mon,$day,$hour,$min);
    }
    return "";
}
