# -*- coding: utf-8 -*-

"""
This program inject the content of (xml) files into a json file [1]
The nome of output json file is taken from the second argument [2]
The xml to inject must be declared into del inpout file by a tag like "<<XML=file_name>>"
The tags recognized by the program will be entirely replaced by the content of the related xml file
"""

import sys


inputfile = sys.argv[1]
outputfile = sys.argv[2]


# read the content of the injecting file into a string, trimming spaces and newline. double quotes are escaped.
def decode_xml(filename):
    sj = ''
    with open(filename) as ifile:
        line = ifile.readline()
        while line:
            sj += line.strip().replace('"', '\\"')
            line = ifile.readline()
    return sj


# does the job
with open(outputfile, 'w') as ofile:
    with open(inputfile) as ifile:
        line = ifile.readline()
        while line:
            while True:
                begin = line.find("<<XML=")
                if (begin < 0):
                    break
                end = line.find(">>", begin)
                if (end < 0):
                    break
                tag = line[begin:end+2]
                filename = line[begin+6:end]
                line = line.replace(tag, decode_xml(filename))
            ofile.write(line)
            line = ifile.readline()