#!/usr/bin/env python

import rfc822
import sys
import dbhash
import time
import string
import os
import re

latin1_qp = re.compile ("^=\?iso-8859-(1|15)\?Q\?(.*)\?=", re.IGNORECASE)
# TODO: handle Base64 (B instead of Q)

# Various routines stolen from standard module quopri

def decode (string):
	ESCAPE = '='
	HEX = '0123456789ABCDEF'
	new = ''
	i, n = 0, len(string)
        while i < n:
            c = string[i]
            if c != ESCAPE:
                new = new + c; i = i+1
            elif i+1 == n and not partial:
                partial = 1; break
            elif i+1 < n and string[i+1] == ESCAPE:
                new = new + ESCAPE; i = i+2
            elif i+2 < n and ishex(string[i+1]) and ishex(string[i+2]):
                new = new + chr(unhex(string[i+1:i+3])); i = i+3
            else: # Bad escape sequence -- leave it in
                new = new + c; i = i+1
	return new

def ishex(c):
    """Return true if the character 'c' is a hexadecimal digit."""
    return '0' <= c <= '9' or 'a' <= c <= 'f' or 'A' <= c <= 'F'

def unhex(s):
    """Get the integer value of a hexadecimal number."""
    bits = 0
    for c in s:
        if '0' <= c <= '9':
            i = ord('0')
        elif 'a' <= c <= 'f':
            i = ord('a')-10
        elif 'A' <= c <= 'F':
            i = ord('A')-10
        else:
            break
        bits = bits*16 + (ord(c) - i)
    return bits

# End of stolen routines

	
	
def register(field):
    (name, address) = msg.getaddr (field)
    if not address:
        return
    match = latin1_qp.search (name)
    if match:	
	name = decode (match.group(2))
    full_address = name + ' <' + address + '>'
    if db.has_key (full_address):
        (counter, date) = string.split (db[full_address], '-')
        counter = int(counter) + 1
    else:
        counter = 1
    db[full_address] = str(counter) + '-' + str(time.time())

msg = rfc822.Message (sys.stdin)
db = dbhash.open (os.environ['HOME'] + '/' + '.mail-addresses', 'c')
date = time.time()
register ("from")
register ("reply-to")
db.close ()
sys.exit(0)







