#
# Try to read Microsoft OE mail files (.dbx format)
#
import sys
import struct
f = open("Inbox.dbx", "rb")
content = f.read(32768)

def visitTbl(f, p, l, m):
    # raw_input("Visit table at %d: " %p)
    #
    # Move to table header and read in table
    #
    f.seek(p)
    Header = f.read(24)
    (FilePos, Unknown1, PrevIndex, NextIndex, Count, Unknown2) = \
    	struct.unpack("llllll", Header)
    # print "Count bottom 8:", Count & 0xff
    Count = Count >> 8
    print "-------------------------------"
    print "FilePos:   ", FilePos
    print "Unknown1:  ", Unknown1
    print "PrevIndex: ", PrevIndex
    print "NextIndex: ", NextIndex
    print "Count:     ", Count
    print "Unknown2   ", Unknown2
    print "Table Entries:"
    e = f.read(12 * Count)
    unread = []
    for i in range(Count):
        (Msg, Cptr, Unknown) = struct.unpack("lll", e[:12])
        if Msg in m:
            print "Duplicate message:", Msg
        else:
            # print "Message %d:  %d, Children %d, Unknown %d" % (i, Msg, Cptr, Unknown)
            m.append(Msg)
        if Cptr:
            unread.append(Cptr)
        e = e[12:]
    sys.stdout.flush()
    for tbl in unread + [NextIndex, PrevIndex]:
        if tbl <> 0 and tbl not in l:
            l.append(tbl)
            visitTbl(f, tbl, l, m)

#
# Get offset of first table
#
tblpos, nhdrs= struct.unpack("48xl144xl", content[:200])

print "First table at:", tblpos
print "Number of headers:", nhdrs
msgs = []

visitTbl(f, tblpos, [], msgs)

print "Found", len(msgs), "messages"

while 1:
    m = raw_input("Message Number: ")
    if not m:
        break
    m = msgs[int(m)]
    f.seek(m)
    s = f.read(1024)
    (pos, dlen, c1,c2,c3,c4, c5,c6,c7,c8) = struct.unpack("llcccccccc", s[:16])
    (pos, dlen, x, x) = struct.unpack("llll", s[:16])
    (x, x, fcnt, hlen) = struct.unpack(">llll", s[:16])
    #hlen = hlen >> 8
    fcnt = fcnt >> 8
    print "pos: ", pos
    print "dlen:", dlen
    print "hlen:", hlen
    print "fcnt:", fcnt
    print "Chars:", ord(c1), ord(c2), ord(c3), ord(c4), ord(c5), ord(c6), ord(c7), ord(c8)
    #s = s[16:]
    for i in range(40):
        flg, = struct.unpack("l", s[:4])
        print "Flag Id: %02x, val %08x" % (flg & 0xff, flg >> 8)
        s = s[4:]
