#!/usr/local/bin/perl
#
# mlfilter.pl
# 2006.07.28 by OGAWA Noriaki
# 2008.02.20 last updated by OGAWA Noriaki
#

$mlname = "soronyi";
$mladdress = "soronyi\@yukawa.kyoto-u.ac.jp";

$appendstr = "[$mlname %03d] ";
$appendstrreg = "\\[$mlname [[:digit:]]+\\] ";

$HOME = $ENV{'HOME'};
$mlnumfile = "$HOME/.mlnum";
$mlfooterfile = "$HOME/.mlfooter";

open NUM, "+<$mlnumfile";
flock(NUM, 2);
$mlnum = <NUM>;
$mlnum ++;
truncate(NUM, 0);
seek(NUM, 0, 0);
print NUM $mlnum;
close NUM;

$nosubject = 1;

while(<>) # header
{
	if(/^$/) { # end of the header.
		if($nosubject) {
			printf "Subject: $appendstr\n", $mlnum;
		}
		printf "Reply-To: %s\n", $mladdress;
		print "\n";
		last;
	}
	elsif(/^Subject: (.*)$/) {
		$nosubject = 0;
		$_ = $1;
		$replyregex = "^(((RE:|Re:|re:|FW:|Fw:|fw:)\\s*)*)$appendstrreg(.*)\$";
		if(/$replyregex/) {
			printf "Subject: $appendstr", $mlnum;
			print "$1$+\n";
		}
		else {
			printf "Subject: $appendstr", $mlnum;
			print "$_\n";
		}
	}
	elsif(/^Reply-To: (.*)$/) {
	}
	else {
		print;
	}
}

while(<>) # content
{
	print;
}

# add footer
if(!open(FT, "<$mlfooterfile")) {
	exit 0;
}
flock(FT, 1);
while(<FT>) {
	print;
}
close FT;
