#!/usr/bin/perl
use strict;
my ($a, $sender, $subject, @senders, @subjects, %atts, $msg, $read, $dead);

format main::STDOUT =
@>>> @@ @<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$a, $read, $dead, $sender, $subject
.

main: {
    my $maildir = shift @ARGV;
    die "usage: mdscan maildir" unless $maildir;
    chdir $maildir or die "can't chdir to $maildir";
    my @msgnums = @ARGV;

    # Read a list of the new messages.
    opendir NEW, "./new" or die "can't open ./new";
    my @msgs = grep {
	$_ = "./new/$_"; /^\.\/new\/[^.]/ && -f "$_"
    } readdir(NEW);
    closedir NEW;

    # Move the messages to the "cur" directory
    foreach my $file (@msgs) {
	my $newfile = $file;
	$newfile =~ s:^./new/(.*)$:./cur/$1:;
	rename "$file", "$newfile" or die "Can't rename $file to $newfile";
    }

    # Read in file list
    opendir CUR, "./cur" or die "can't open ./cur";
    @msgs = grep {
	$_ = "./cur/$_"; /^\.\/cur\/[^.]/ && -f "$_"
	} readdir(CUR);
    closedir CUR;
    @msgs = sort @msgs;

    # Set more attributes
    my $time = time();
    foreach $msg (@msgs) {
	my @stats   = stat("$msg");
	if (($time - $stats[9]) < 10800) {$atts{$msg}->{"N"} = 1;}
	if (($time - $stats[9]) <   600) {$atts{$msg}->{"N"} = 2;}
	$sender  = `822field from < "$msg"`; push @senders, $sender;
	$subject = `822field subject < "$msg"`; push @subjects, $subject;

	next unless $msg =~ /.*:1,(.*)$/;
	my $attlist = $1;
	if ($attlist=~/T/) {$atts{$msg}->{"T"} = 1;}
      	if ($attlist=~/S/) {$atts{$msg}->{"S"} = 1;}
    }

    # Now read out the data
    if (@msgnums) {
	foreach $msg (sort @msgnums) {
	    $read = $dead = $sender = $subject = "";
	    $sender  = $senders[$msg-1];
	    $subject = $subjects[$msg-1];
	    $read = 'R' if $atts{$msgs[$msg-1]}->{"S"};
	    $dead = 'n' if $atts{$msgs[$msg-1]}->{"N"} == 1;
	    $dead = 'N' if $atts{$msgs[$msg-1]}->{"N"} == 2;
	    $dead = 'K' if $atts{$msgs[$msg-1]}->{"T"};
	    $a = $msg;
	    write;
	}
    }
    else {
	$a = 1;
	foreach $msg (@msgs) {
	    $read = $dead = $sender = $subject = "";
	    $sender  = $senders[$a-1];
	    $subject = $subjects[$a-1];
	    $read    = 'R' if $atts{$msg}->{"S"};
	    $dead    = 'n' if $atts{$msg}->{"N"} == 1;
	    $dead    = 'N' if $atts{$msg}->{"N"} == 2;
	    $dead    = 'K' if $atts{$msg}->{"T"};
	    write;
	    $a++;
	}
    } 
}
