#!/usr/bin/perl
#
#
# Write mboxes based on a year.  
#
# Note: very sloppy with globals and such
#
#

use Mail::MboxParser;

$inbox = shift(@ARGV) or die "Usage: $0 <mbox file> [year]\n";
$from_date = shift(@ARGV);

if (!($from_date =~ /[0-9]+/)) {
	print "Year to grab:\n";
	$from_date = <STDIN>;
	chomp $from_date;
}

my $tot = 0;
my $mtot = 0;
my $curr_pos = 0;
my $last_pos = 0;

open(MAIL,"$inbox");
open(OUT,">/tmp/$$.out");

# MboxParser for grabbing From lines
my $mb = Mail::MboxParser->new("$inbox",
								decode => 'ALL',
								newline => 'AUTO');
my $msg = $mb->next_message;

while($msg = $mb->next_message) {
	my $from = $msg->from_line();

	if ($from =~ /(?:^From.*\s$from_date)/) {
		my $size = write_msg($from);

		# seek stuff, but doesn't work very well
		$last_pos = $curr_pos;
		$curr_pos = tell(MAIL);
		$diff = $curr_pos-$last_pos;
		#print "$last_pos -> $curr_pos : $diff\n";
	}
}

close(OUT);
close(MAIL);

print "Wrote $mtot messages ($tot bytes) to file /tmp/$$.out\n";

exit;

sub write_msg {

	my $from = shift;
	my $test = 0;
	my $msg = "";

	# see pos always stays the same after the first?
	#seek(MAIL,$last_pos,0);
	seek(MAIL,0,0);

	# look for our From field
	while (<MAIL>) {
		if (/^From / && /$from/) {
			$msg = $_;
			while (<MAIL>) {
				last if /^From /;	# Hit the end of the message
				$msg .= $_;
			}
		}
	}

	# Looks like we've got it.  Write it.
	print OUT $msg;
	$mtot++;
	$tot += length($msg);
	#print "Wrote ".length($msg)." bytes to file /tmp/$$.out\n";

	return length($msg);

}



