#!/usr/bin/env python
# nb. requires python2.4 for string templating
#
# Usage: merge.py output template code
#
# merge the code in 'code' into 'template', writing out to 'output'
# 
# Anything between lines __begin_name__ and __end_name__ in 'code'
# gets inserted into $name in 'template'.
#
# Ian Wienand <ianw@gelato.unsw.edu.au>
#
import os
import sys
from string import Template

if len(sys.argv) != 4:
    print "Usage: %s output template code" % sys.argv[0]
    sys.exit(2)

print "Merging %s and template %s to %s" % (sys.argv[2], sys.argv[3], sys.argv[1])

# bring the code file into a dictionary
# anything between lines __begin_name__ and __end_name__ goes into
# a dictionary entry of name
template_dictionary = {}
am_processing = False
current_template = ""
current_template_name = ""
for line in open(sys.argv[3], 'r').readlines():

    if am_processing:
        # if this line is the end, stop
        # XXX check this end is actually the name we are processing
        if line[:6] == "__end_":
            template_dictionary[current_template_name] = current_template
            am_processing = False
            print "... done"
            continue
        # otherwise, add this line to the current template
        current_template += line
        continue
    # if we got here, we are not processing
    if line[:8] == "__begin_":
        am_processing = True
        current_template_name = line[8:-3] #newline
        print "Processing %s" % (current_template_name),
        current_template = ""
        continue
    # this is some random line
    continue

#now open the file where we put these templates
template = Template(open(sys.argv[2],'r').read())

#finally, substitute them all in
output = open(sys.argv[1],'w')
output.write(template.substitute(template_dictionary))
