import sys
import re
import codecs

white = ur'([\d+-/\s\[\]:.?!(){}*])'

def replSym(f, t, st):
	return re.sub(white + f + white, ur'\1' + t + ur'\2', st)

def formatSpan(symbols, format, mode):
	if mode:
		return "<span style=\"" + format + "\">" + symbols + "</span>"
	else:
		return symbols

def format(text, mode):
	if mode:
		text = re.sub(ur"\*(.*?)\*", ur'<b>'+ur'\1'+ur'</b>', text)	# *xxx* -> <br>xxx</br>
		text = re.sub(ur"//(.*?)//", ur'<i style="color: MidnightBlue ;">'+ur'\1'+ur'</i>', text)	# *xxx* -> <br>xxx</br>
		text = re.sub(ur"//(.*)", ur'<i style="color: MidnightBlue ;">'+ur'\1'+ur'</i>', text)
	return text

#--------------------------- Main: ---------------------------------

if len(sys.argv)<=1:
	print "call with parameters: input_file_name [output_file_name]"
	exit(0)
src_file_name = sys.argv[1]

if len(sys.argv[2])>=3:
	dst_file_name = sys.argv[2]
else:
	dst_file_name = "to_print_" + src_file_name

html_mode = dst_file_name.endswith(".htm") or dst_file_name.endswith(".html")

dst = codecs.open(dst_file_name, "w", "utf-8")

if html_mode:
	dst.write("""<html><head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<script type="text/javascript" src="mktree.js"></script>
<link rel="stylesheet" href="mktree.css" type="text/css">
</head><body>""")

prev_indend = -1
dont_close = 1
for line in codecs.open(src_file_name, "r", "utf-8"):
	line = replSym('t', u'\u2663', line)
	line = replSym('k', formatSpan(u'\u2666', "color:red;", html_mode), line)
	line = replSym('c', formatSpan(u'\u2665', "color:red;", html_mode), line)
	line = replSym('p', u'\u2660', line)
	line = format(line, html_mode)
	if html_mode:
		indent = 0
		while indent < len(line) and line[indent] in " \t":
			indent = indent + 1

		line = line.strip()
		if line == "":
			continue

		if indent <= prev_indend:		#end branch
			if not dont_close:
				dst.write("</li>\n")		#close prevoius point
			if indent < prev_indend:
				dst.write("</li></ul>\n" * (prev_indend - indent))

		if indent > prev_indend:		#bigger indent
			if indent == 0:
				dst.write("<ul class=\"mktree\">" )
			else:
				dst.write("<ul>" )		#new list

		if indent == 0:			#we are in tree
			h = 0
			while line.startswith("=") and line.endswith("="):
				line = line[1:-1]
				h = h + 1
			if h > 0:
				line = "<h" + str(h) + ">" + line.strip() + "</h" + str(h) + ">"
				dont_close = 1
			else:
				line = "<li>" + "<span style=\"padding-bottom: 10px;\">" + line + "</span>"
				dont_close = 0
		else:
			line = "<li>" + line
			dont_close = 0

		prev_indend = indent
    	dst.write(line)
if html_mode:
	dst.write("</li></ul>\n" * (prev_indend+1))	#close tags
	dst.write("</body>\n</html>")
