1#!/usr/bin/perl
2
3sub countmsgs {
4  return -1 unless open(M, "<$mbox");
5  my $inhdr = 0;
6  my $cl = undef;
7  my $msgread = 0;
8  my $count = 0;
9  while(<M>) {
10    if (!$inhdr && /^From\s+\S+\s+(?i:sun|mon|tue|wed|thu|fri|sat)\s+(?i:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s+\d+\s/) {
11      $inhdr = 1;
12      $msgread = 0;
13      undef $cl;
14      next;
15    }
16    if ($inhdr) {
17      if (/^content-length:\s+(\d+)/i) {
18	$cl = 0+$1;
19	next;
20      }
21      if (/^status:\s+(\S)/i) {
22	$msgread = 1 unless $1 eq 'N' || $1 eq 'U';
23	next;
24      }
25      if ($_ eq "\n") {
26	$count++ if !$msgread;
27	seek(M, $cl, 1) if defined $cl;
28	$inhdr = 0;
29      }
30    }
31  }
32  close M;
33  return $count;
34}
35
36$| = 1;
37$mbox = $ARGV[0] || $ENV{'MAIL'};
38$oldfmt = $ARGV[1] || "%4d ";
39$newfmt = $ARGV[2] || "\005{Rk}%4d \005{-}";
40
41@oldstat = stat($mbox);
42if (!@oldstat) {
43  print "\005{Rk} ??? \005{-}\n";
44  exit 1;
45}
46$oldcount = 0;
47while(1) {
48  $count = countmsgs($mbox);
49  if ($count == -1) {
50    print "\005{Rk} ??? \005{-}\n";
51  } elsif ($count < $oldcount || $count == 0) {
52    printf "$oldfmt\n", $count;
53  } else {
54    printf "$newfmt\n", $count;
55  }
56  $oldcount = $count;
57  while (1) {
58    @newstat = stat($mbox);
59    if (!@newstat) {
60      print "\005{Rk} ??? \005{-}\n";
61      exit 1;
62    }
63    last if $newstat[7] != $oldstat[7] || $newstat[9] != $oldstat[9];
64    sleep 1;
65  }
66  @oldstat = @newstat;
67}
68