#!/usr/bin/python
# A small script to process e-mail messages containing Life patterns.
#
# Upon execution, all Life patterns within the given message are stored
# in separate files named "/ /.life"
# The message body is saved in its own file ("contents.txt")
# with Life inclusions replaced with references like "<12.life>".
#
# The message should be fed into script's stdin;
# the 1st command-line argument (if present) is used
# as the "base" directory (default ".").
import os
import sys
from email.Parser import Parser
from email.Utils import parsedate_tz, mktime_tz
from time import gmtime, strftime
base = "."
if len (sys.argv) > 1: base = sys.argv[1]
header = Parser ().parse (sys.stdin, headersonly = 1)
subject = header["subject"]
date = header["date"]
sender = header["from"]
alt_subject = subject.replace ("/", "[slash]").replace ("\n", "[wrap]").replace ("\t", "[tab]")
alt_date = strftime ("%F %T", gmtime (mktime_tz (parsedate_tz (date))))
dir = "%s/%s %s" % (base, alt_date, alt_subject)
os.mkdir (dir, 0775)
f = file ("%s/contents.txt" % dir, "w")
f.write ("Subject: %s\nDate: %s\nFrom: %s\n\n" % (subject, date, sender))
n = 0
try:
while 1:
line = raw_input ()
s = line.strip (" ")
is_rle = line.startswith ("#") or line.startswith ("x =")
is_life105 = (s and s.count (".") + s.count ("*") == len (s))
is_bell = (s and s.count (".") + s.count ("o") == len (s))
if is_rle or is_life105 or is_bell:
fn = "%02d.life" % n
f.write ("<%s>\n" % fn)
g = file ("%s/%s" % (dir, fn), "w")
if is_life105:
g.write ("#Life 1.05\n")
elif is_bell:
g.write ("! \"main\"\n")
quit = 0
while line.strip (" ") and not quit:
g.write ("%s\n" % line)
quit = (line.find ("!") >= 0) and not line.startswith ("#")
line = raw_input ()
g.close ()
n += 1
f.write ("%s\n" % line)
except EOFError:
pass
f.close ()