#!/usr/bin/env python

import re
import sys

def outline():
    exec txt
    if msgstr:
        sys.stdout.write("'''%s''':\n'''%s''',\n" % (msgid.replace("'", r"\'"),
                                                     msgstr.replace("'", r"\'")))


encoding = ''
reCharset = re.compile(r'"content-type:.*charset=(.*?)(\\n)?"', re.I)

filename = sys.argv[1]
fp = open(filename, 'r')

for line in fp:
    line = line.strip()
    if line:
        if not encoding:
            r = reCharset.match(line)
            if r:
                encoding = r.group(1)
    else:
        break

assert encoding

sys.stdout.write('''# -*- coding: %s -*-
# Automatically generated - DO NOT EDIT, edit %s instead!
text = {
''' % (encoding, filename))

state = 0
msgid = ''
msgstr = ''
for line in fp:
    line = line.strip()
    if not line:
        if state:
            outline()
            state = 0
            msgid = ''
            msgstr = ''
    elif line[0] != '#':
        if not state:
            txt = '# -*- coding: %s -*-\n' % encoding
            state = 1
        if line[:5] == 'msgid':
            txt += '\nmsgid=' + line[5:]
        elif line[:6] == 'msgstr':
            txt += '\nmsgstr=' + line[6:]
        else:
            txt += '+' + line

fp.close()

if state:
    outline()

sys.stdout.write('}\n')
