# 2/5/03 change to .owlconf that uses this to incorporate splitting
# out spam by the server

# This now uses imapfolder so it can work on folders other than INBOX too

my %mail;
# This is a two dimentional hash sorted by folder (instance) then id.

sub mail_get_message_number_from_server ($) {
    my ($folder) = @_;
    my $out = `/afs/athena.mit.edu/user/i/n/int18/bin/imapfolder +$folder`;
    # example value:
    # INBOX+ has     28 messages (1-28); cur=28.
    my ($msg_num) = $out =~ m/ (\d+) /;
    return $msg_num;
}

sub mail_counter_clear () {
    # keep track of which ones were mail, but throw away the message numbers for them
    for my $id (keys %{$mail{"INBOX"}}) {
	undef $mail{"INBOX"}{$id};
    }
}

# associate the passed id with its message number on the imap server
# and return the message number
sub mail_get_message_number ($) {
    my ($m) = @_;
    my ($id) = $m->id;
    my ($folder) = $m->instance;
    my ($msg_num);
    if (!$m->is_mail) {
	# not a mail message
	return;
    } elsif (exists $mail{$folder}{$id}) {
	# if it already was looked up use the old value
	$msg_num = $mail{$folder}{$id};
    } elsif ($mail{$folder}{"last"}) {
	# if it's a new message and we know what the last one was numbered
	$msg_num = ++$mail{$folder}{"last"};
	$mail{$folder}{$id} = $msg_num;
    } else {
        $msg_num = mail_get_message_number_from_server($folder);
	$mail{$folder}{$id} = $msg_num;
	$mail{$folder}{"last"} = $msg_num;
    }
    return $msg_num;
}

sub mail_get_header ($) {
    my ($message) = @_;
    my ($current, %header);
    foreach (split m/\s*\n\s*/, $message) {
        if (m/^(\w+):\s*(.*)$/) {
            $current = lc($1);
            $header{$current} = $2;
        } elsif ($current) {
            $header{$current} .= " $_";
        }
    }
    return %header;
}

 
1;

# echo 'David =?iso-8859-1?Q?Andr=E9?= Bron' | perl -pe  's/\=\?iso-8859-1\?Q\?(.*?)\?\=/\1/;s/\=([A-F0-9][A-F0-9])/pack("c",hex($1))/eg'
D
# echo 'Subject: =?ISO-8859-3?B?amRhbmllbCwzMCBkYXkgc2FtcGxlIG9mIEhHSC0gJDQ5Ljk1IHZhbHVlIQ==?=' | perl -pe  's/\=\?iso-8859-3\?B\?(.*?)==\?\=/\1/;s/\=([A-F0-9][A-F0-9])/pack("c",hex($1))/eg'

# | perl -pe  's/\=\?iso-8859-1\?Q\?(.*?)\?\=/\1/;s/\=([A-F0-9][A-F0-9])/pack("c",hex($1))/eg'

# MIME::Words
