#!/usr/bin/env python2
from sys import argv, exit

if len(argv) != 3:
    print "Usage:", argv[0], "xml_element input_file"
    print "\nxml_element is given without angle brackets (<>)"
    print "input_file must be a file containing a list of paragraphs,"
    print "each separated by an empty newline. For example:"
    print "\n\tThis is paragraph one. It contains only one line."
    print "\n\tThis is paragraph two, it is preceded by an empty line,"
    print "\tand contains multiple lines. Paragraphs can be any number"
    print "\tof lines, as long as individual paragraphs are separated by"
    print "\tan empty line."
    print "\nExample, surrounding every paragraph with <p></p> tags:"
    print "\t" + argv[0], "p file1 > output"

    exit(1)

element = argv[1]
filename = argv[2]

element_open = "<" + element + ">"
element_close = "</" + element + ">"

count = 0
line_list = []
paragraph_list = []
with open(filename) as fh:
    for line in fh:
        line = line.strip()
        if line:
            # build the list of lines in this paragraph
            line_list.append(line);
        else:
            # add element to the beginning of the first line
            #print line_list
            first_line = line_list[0]
            first_line = element_open + first_line
            line_list[0] = first_line

            # add element to the end of the last line
            last_line = line_list[-1]
            last_line = last_line + element_close
            line_list[-1] = last_line

            # join the lines back together and reset the line list
            paragraph_list.append('\n'.join(line_list))
            line_list = []

for p in paragraph_list:
    print p
