#!/usr/sbin/perl
#
# header.pl     ver.1.1         Y.Sakazume
#
# usage: header.pl <list_name> <number_file>
#
########################################################################

$Domain      = "";	# Set Mail Domainname if you need Reply-To: header.
$ForceReplyTo = 0;	# If ForceReplayTo is set to 1, Reply-To: header
			# is replaced whether it already exist.

			# Domain = NULL and ForceReplyTo = 0, Reply-To: header
			# removed.

my ($prefix, $index, $result, $replyto, $subject);

$prefix = $ARGV[0];
if (-e $ARGV[1]) {
    open(INDEX, "+<" . $ARGV[1]);
    chop($index = <INDEX>);
    close(INDEX);
    $index =~ s/:.*//;
    $index++;
}

while (<STDIN>) {
    chop;
    if (/^$/) { # escape if end of header
        last;
    }
    if (s/^Subject:\s*//) {
        s/^((RE|Re|re|FW|Fw|fw):\s)+/Re: /;	# RE:|Re:|re:|FW:|Fw:|fw: -> Re:
        s/^(Re: )*\[$prefix\s*\d+\]\s*/$1/;	# remove prefix
        print "Subject: [$prefix $index]" . $_ . "\n";
    }
    elsif(s/^Reply-[Tt]o:\s//i){
        $replyto = $_;
        unless($ForceReplyTo){
            print "Reply-To: " . $replyto . "\n";
        }
    }
    else {
        print; print "\n";
    }
}

if($Domain){
    if($ForceReplyTo eq 1) {
        print "Reply-To: " . $prefix . "@" . $Domain . "\n";
    }
    if($ForceReplyTo eq 0 && $replyto eq '') {
        print "Reply-To: " . $prefix . "@" . $Domain . "\n";
    }
}

print "\n";     # end of header
print <STDIN>;
exit(0);
