#!/usr/bin/env python

# Datecode decoder for Palm devices.  The logic in here is based on me
# spending a bunch of time looking at serial numbers and dates of release
# and discontinuation.

import sys

def main():
    # The month and day appear to be encoded in "base 34" with I and O
    # excluded to avoid confusion with 0 and 1. 0 appears to not be used
    # (since January is month 1 and the first day of a month is 1, not 0).
    digit_string = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZ'
    serialnum = sys.argv[1]

    try:
        month = digit_string.index(serialnum[5].upper())
    except ValueError:
        print("Couldn't decode month '%s'" % serialnum[5])
        sys.exit(1)

    try:
        day = digit_string.index(serialnum[6].upper())
    except ValueError:
        print("Couldn't decode day '%s'" % serialnum[6])
        sys.exit(1)

    try:
        year = int(serialnum[7])
    except ValueError:
        print("Couldn't decode year '%s'" % serialnum[7])
        sys.exit(1)

    # Sliding window logic for years. Once I figure out how/if models
    # are represented we can replace this with a lookup by release and
    # discontinuation dates.
    if year < 6:
        year = year + 2000
    else:
        year = year + 1990

    # Sanity-check day of month based on number of days in the month.
    numdays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if day > numdays[month]:
        if not (month == 2 and day == 29 and (year % 4 == 0)):
            print("Warning: Date appears to not make sense")

    print('Probable Date of Manufacture: %d/%d/%d' % (month, day, year))

if __name__ == "__main__":
    main()
