#!/usr/bin/python
#------------------------------------------------------------------------------
#		RAPIDTEX	version 0.3.0	October 22, 2003
#		A LateX Preprocessor for lazy people
#		by Maarten van Gompel (Proycon)
#
#		Licensed under GNU Public License (GPL)
#------------------------------------------------------------------------------

import sys, string, os, os.path,shutil,time
  
#------------------------------------------------------------------------------
#---------------------CONFIGURATION STARTS HERE--------------------------------
#------------------------------------------------------------------------------
confdir = os.path.expanduser("~/.rapidtex/")

defaultinclude = [confdir + "commands.rptex",confdir +  "symbols.rptex",confdir +"markers.rptex",confdir +"multilingual.rptex"]

#Internal rapidtex commands
hardcommands = []
hardcommands.append(['\\includetex ','include'])
hardcommands.append(['\\includehtml ','include'])
hardcommands.append(['\\include ','include'])
hardcommands.append(['======','chapter'])
hardcommands.append(['------','section'])
hardcommands.append(['- - -','subsection'])
hardcommands.append([' - - -','subsection'])
hardcommands.append(['*=====','chapter*'])
hardcommands.append(['*-----','section*'])
hardcommands.append(['* - -','subsection*'])
hardcommands.append(['*- - -','subsection*'])
hardcommands.append(['<TEXCOMMAND>','settexcommand'])
hardcommands.append(['</TEXCOMMAND>','endsettexcommand'])
hardcommands.append(['<HTMLCOMMAND>','sethtmlcommand'])
hardcommands.append(['</HTMLCOMMAND>','endsethtmlcommand'])
hardcommands.append(['\\begintexcommand','settexcommand'])
hardcommands.append(['\\endtexcommand','endsettexcommand'])
hardcommands.append(['\\beginhtmlcommand','sethtmlcommand'])
hardcommands.append(['\\endhtmlcommand','endsethtmlcommand'])
hardcommands.append(['\\settexsymbol','settexsymbol'])
hardcommands.append(['\\sethtmlsymbol','sethtmlsymbol'])
hardcommands.append(['\\setsymbolenv','setsymbolenv'])
hardcommands.append(['\\settexmarker','settexmarker'])
hardcommands.append(['\\sethtmlmarker','sethtmlmarker'])
hardcommands.append(['\\commandalias','commandalias'])
hardcommands.append(['\\symbolalias','symbolalias'])

hardcommands.append(['<BUFFER>','beginbuffer'])
hardcommands.append(['</BUFFER>','endbuffer'])
hardcommands.append(['\\beginbuffer','beginbuffer'])
hardcommands.append(['\\endbuffer','endbuffer'])
hardcommands.append(['\\insertbuffer','insertbuffer'])
hardcommands.append(['\\buffer','insertbuffer'])


hardcommands.append(['\\debuglist','debuglist'])
hardcommands.append(['<if>','condition'])
hardcommands.append(['<evaltovar>','evaltovar'])
hardcommands.append(['\\evaltovar','evaltovar'])
hardcommands.append(['<eval>','eval'])
hardcommands.append(['\\eval','eval'])
hardcommands.append(['<exec>','exec'])
hardcommands.append(['\\exec','exec'])
hardcommands.append(['<htmlimage>','beginhtmlimage'])
hardcommands.append(['</htmlimage>','endhtmlimage'])
hardcommands.append(['</>','endenv'])

#----------------------------------------------------------------------------
#---------------------CONFIGURATION ENDS HERE--------------------------------
#----------------------------------------------------------------------------

#----------------------------------------------------------------------------
#---------------------EXTRA FUNCTIONS START HERE-----------------------------
#----------------------------------------------------------------------------

def chop(s):
	return s[0:len(s)-1]

def shift(s):
	return s[1:9999]
		
#----------------------------------------------------------------------------
#---------------------EXTRA FUNCTIONS END HERE-------------------------------
#----------------------------------------------------------------------------


def nonl(s):
	s = string.strip(s)
	#if s[len(s) - 2] == '\r':
	#	return s[0:len(s) - 2]
	if len(s) == 0:
		return s
	if s[len(s) - 1] == '\n':
		return s[0:len(s) - 1]
	else:
		return s


def flatten(l):
	s = ""
	for item in l:
		s = s + item + '\n'
	return s

def unflatten(s):
	l = []
	begin = 0
	if s == "":
		return [s]
	if s[len(s) - 1] != '\n':
		s = s + '\n'
	for i in range(len(s)):
		if s[i] == '\n':
			l.append(s[begin:i])
			begin = i + 1
	return l		
			
	

def getblocks(s,args):
	l = []
	begin = 0 
	inblock = 0
	argcount = 0
	prev = ""
	args = args + 1 
	for i in range(len(s)):
		if inblock == 0:		
			if (s[i] == ' ') or (s[i] == ',') or (s[i] == '.'):
				if (string.strip(s[begin:i]) != ""):
					l.append(s[begin:i])
					begin = i + 1
					argcount = argcount + 1
					if argcount == args:
						l.append(s[i:9999])					
						break
			elif (i == len(s) - 1):
				if (string.strip(s[begin:i+1]) != ""):
					l.append(s[begin:i+1])
					break					
			if (s[i] == '{') and ((prev == ' ') or (prev == '}')):
				begin = i + 1
				inblock = 1
					
		elif inblock == 1:
			if (s[i] == '{'):
				inblock = 2
			if (s[i] == '}'):
				if (string.strip(s[begin:i]) != ""):					
					l.append(s[begin:i])
					i = i + 1
					begin = i + 1
					argcount = argcount + 1
					if argcount == args:
						l.append(s[i + 1:9999])
						break		
				inblock = 0	
			elif (i == len(s) - 1):
				if (string.strip(s[begin:i+1]) != ""):
					l.append(s[begin:i+1])
					break						
		elif inblock > 1:
			if (s[i] == '{'):
				inblock = inblock + 1
			if (s[i] == '}'):
				inblock = inblock - 1
			elif (i == len(s) - 1):
				if (string.strip(s[begin:i+1]) != ""):
					l.append(s[begin:i+1])
					break					
		prev = s[i]						
	return l
	
def insert(collection, item):
	num = 0 
	for col in collection:
		if len(col[0]) < len(item[0]):
			break
		num = num + 1
	collection.insert(num, item)
	


		
def striphtml(line):
	if string.find(line,'<') != -1:
		newline = ""
		begin = 0
		end = 0
		intag = 0
		for i in range(len(line)):
			if (line[i] == '<') and (intag == 0):		
				#begin found
				newline = newline + line[end:i]
				begin = i + 1
				intag = 1	
			elif (line[i] == '>') and (intag == 1):		
				#end found
				end = i + 1
				intag = 0	
		#Add the last part of the line as well						
		line = newline + line[end:len(line)]
	return line
	
def striplatex(line):
	if string.find(line,'\\') != -1:
		newline = ""
		begin = 0
		end = 0
		intag = 0
		for i in range(len(line)):
			if (line[i] == '\\') and (intag == 0):
				#begin found
				newline = newline + line[end:i]
				begin = i + 1
				intag = 1
			elif (line[i] == '{'):
				intag = intag + 1
			elif (line[i] == '}'):
				intag = intag - 1
			elif (line[i] == '['):
				intag = intag + 1
			elif (line[i] == ']'):
				intag = intag - 1
			elif ((line[i] == ' ') or (line[i] == ',') or (line[i] == ':') or (line[i] == ';') or (line[i] == '.')) and (intag == 1):
				#end found
				end = i
				intag = 0
		#Add the last part of the line as well

		line = newline + line[end:len(line)]
	return line

	

	
def processcommand(s, command):
	global COMMANDNAME
	global COMMANDARGS
	global TEXBODY
	global HTMLBODY
	global debug
	o = ""	
	if command[COMMANDARGS] > 0:
		args = getblocks(s, command[COMMANDARGS])
		args.append("")	
		trailer = args[command[COMMANDARGS] + 1]			
	else:
		args = []
		if s[0] == "<":
			args.append("<" + command[COMMANDNAME] + ">")
		elif s[0] == "\\":
			args.append("\\" + command[COMMANDNAME])
		trailer = s[len(command[COMMANDNAME]) + 2:9999]			
			
	if (('\\' + string.lower(command[COMMANDNAME]+' ') == string.lower(args[0]) + ' ') or (('<' + string.lower(command[COMMANDNAME] + '>')) ==  string.lower(args[0]) )):				
		if debug == 1:
			print "COMMAND: " + command[COMMANDNAME] + " (" + str(command[COMMANDARGS]) + ")"
		if mode == "latex":
			o = command[TEXBODY]
		elif mode == "html":
			o = command[HTMLBODY]	
		if command[COMMANDARGS] > 0:
			for i in range(1,command[COMMANDARGS] + 1):
				o = o.replace('$' + str(i), args[i])
		#print "O: " + flatten(unflatten(o))
		o = flatten(rapidtex(unflatten(o),0))	
		#print "O: " + o
	return nonl(o) + trailer

	
def processcommands(s):	
	global commands
	global COMMANDNAME
	global COMMANDARGS
	global TEXBODY
	global HTMLBODY
	for command in commands:
		if string.strip(command[COMMANDNAME]) != "":
			begin = 0
			commandindex = 0
			while (commandindex != -1):		
				commandindex = string.lower(s).find("\\" + string.lower(command[COMMANDNAME] +" "),begin,9999)
				if (commandindex == -1): 
					commandindex = string.lower(s).find("<" + string.lower(command[COMMANDNAME] +">"),begin,9999)
				if (commandindex != -1):
					end = commandindex
					s = s[0:end] + processcommand(s[end:9999], command)
					begin = commandindex + 1
	return s
		

def processsymbols(s):
	global envitemize
	global envenumerate
	global envtabular
	global envmath
	global tabulardelay
	global symbols
	global SYMBOLNAME
	global TEXSYMBOL
	global HTMLSYMBOL
	global REQUIREENV
	global vspace
	global currentcolumn
	global currentrow
	global closemulticol
	global firsthtmlcelloptions
	

	for symbol in symbols:
		if (s.find(symbol[SYMBOLNAME]) != -1):	
			processed = 0
		
			
			if (processed == 0) and (symbol[REQUIREENV][0:4] == 'lang'):
				if (getvar("lang") == symbol[REQUIREENV]):
					if mode == "latex":
						s.replace(symbol[SYMBOLNAME],symbol[TEXSYMBOL])
					elif mode == "html":
						s.replace(symbol[SYMBOLNAME],symbol[HTMLSYMBOL])
				processed = 1
			if (processed == 0) and (symbol[REQUIREENV] == 'itemize') and (getvar("envitemize") == "false"):	
				vspace = 0
				if mode == "latex":					
					s = "\\begin{itemize}\n" + s.replace(symbol[SYMBOLNAME],symbol[TEXSYMBOL])
				elif mode == "html":
					s = "<ul>\n" + s.replace(symbol[SYMBOLNAME],symbol[HTMLSYMBOL])
				setvar("envitemize","true")
				processed = 1
			if (processed == 0) and (symbol[REQUIREENV] == 'enumerate') and (getvar("envenumerate") == "false"):	
				vspace = 0
				if mode == "latex":
					s = "\\begin{enumerate}\n" + s.replace(symbol[SYMBOLNAME],symbol[TEXSYMBOL])
				elif mode == "html":
					s = "<ol>\n" + s.replace(symbol[SYMBOLNAME],symbol[HTMLSYMBOL])
				setvar("envenumerate","true")
				processed = 1
			if (processed == 0) and (symbol[REQUIREENV] == 'enumerate') and (getvar("envenumerate") == "true"):	
				if mode == "latex":
					s = s.replace(symbol[SYMBOLNAME],symbol[TEXSYMBOL])
				elif mode == "html":
					s = s.replace(symbol[SYMBOLNAME],symbol[HTMLSYMBOL])								
				processed = 1
			if (processed == 0) and (symbol[REQUIREENV] == 'itemize') and (getvar("envitemize") == "true"):	
				if mode == "latex":
					s = s.replace(symbol[SYMBOLNAME],symbol[TEXSYMBOL])
				elif mode == "html":
					s = s.replace(symbol[SYMBOLNAME],symbol[HTMLSYMBOL])					
				processed = 1
			if (processed == 0) and (symbol[REQUIREENV][0:7] == 'tabular') and (getvar("envtabular") == "false") and (mode == "latex"):	
				vspace = 0
				
				#Actual replacement gets done later for column separators
				if (symbol[REQUIREENV] != 'tabularcolumn'):
					s = s.replace(symbol[SYMBOLNAME],symbol[TEXSYMBOL])
				
				if (symbol[REQUIREENV] == "tabularline"):
					tabulardelay = tabulardelay + s
					s = ""
				else:
					#count columns
					colnum = string.count(s, ' | ')
					if getvar("tableborder") != "0":
						cols = "|"
					else:
						if getvar("columnindent") != "true":
							cols = "@{*}"
						else:
							cols = ""
					curcol = 0
					for i in range(colnum + 1):
						curcol = curcol + 1
						if getvar("column"+ str(curcol) + "rgb_latex") != "":
							if getvar("column"+ str(curcol) + "textrgb_latex") != "":
								cols = cols + ">{\color[rgb]{" + getvar("column"+ str(curcol) + "textrgb_latex") + "}\columncolor[rgb]{" + getvar("column"+ str(curcol) + "rgb_latex") + "}[" + getvar("column" + str(curcol) + "fill") + "\\tabcolsep]}"
							elif getvar("column"+ str(curcol) + "textcolor") != "":	
								cols = cols + ">{\color{" + getvar("column"+ str(curcol) + "textcolor") + "}\columncolor[rgb]{" + getvar("column"+ str(curcol) + "rgb_latex") + "}[" + getvar("column" + str(curcol) + "fill") + "\\tabcolsep]}"
							else:
								cols = cols + ">{\columncolor[rgb]{" + getvar("column"+ str(curcol) + "textrgb_latex") + "}[" + getvar("column" + str(curcol) + "fill") + "\\tabcolsep]}"						
						elif getvar("column"+ str(curcol) + "color") != "":
							if getvar("column"+ str(curcol) + "textrgb_latex") != "":
								cols = cols + ">{\color[rgb]{" + getvar("column"+ str(curcol) + "textrgb_latex") + "}\columncolor{" + getvar("column"+ str(curcol) + "color") + "}[" + getvar("column" + str(curcol) + "fill") + "\\tabcolsep]}"
							elif getvar("column"+ str(curcol) + "textcolor") != "":	
								cols = cols + ">{\color{" + getvar("column"+ str(curcol) + "textcolor") + "}\columncolor{" + getvar("column"+ str(curcol) + "color") + "}[" + getvar("column" + str(curcol) + "fill") + "\\tabcolsep]}"
							else:
								cols = cols + ">{\columncolor{" + getvar("column"+ str(curcol) + "color") + "}[" + getvar("column" + str(curcol) + "fill") + "\\tabcolsep]}"
						elif getvar("column"+ str(curcol) + "textrgb_latex") != "":
							cols = cols + ">{\color[rgb]{" + getvar("column"+ str(curcol) + "textrgb_latex") + "}}"
						elif getvar("column"+ str(curcol) + "textcolor") != "":
							cols = cols + ">{\color[rgb]{" + getvar("column"+ str(curcol) + "textcolor") + "}}"							
														
						if getvar("column"+ str(curcol) + "exactwidth") != "":
							cols = cols + "p{" + getvar("column"+ str(curcol) + "exactwidth") + "}"
						if getvar("tableborder") != "0":							
							if getvar("column" + str(curcol) + "border") == "single":
								bordertext = "|"
							elif getvar("column" + str(curcol) + "border") == "double":
								bordertext = "||"
							else:
								bordertext = ""
							if getvar("column"+ str(curcol) + "exactwidth") != "":
								cols = cols + bordertext
							else:
								cols = cols + getvar("column" + str(curcol) + "align")[0] + bordertext
						else:
							cols = cols + getvar("column" + str(curcol) + "align")[0]
					if cols[0] == "@":
						cols = cols + "@{*}"
					currentcolumn = 1
					currentrow = 1
					s =  "\\begin{" + getvar("tabularenv") + "}{" + cols + "}\n" + tabulardelay + "\n" +  s + "\\\\"
					tabulardelay = ""
					setvar("envtabular","true")
					processed = 0
			if (processed == 0) and (symbol[REQUIREENV][0:7] == 'tabular') and (getvar("envtabular") == "false") and (mode == "html"):
				vspace = 0
				s = s.replace(symbol[SYMBOLNAME],symbol[TEXSYMBOL])
				prepend = ""
				if getvar("tabularenv") == "longtable":
					prepend = "<center><br>"
				if getvar("htmltablewidth") != "":
					s = prepend + "<TABLE WIDTH=" + getvar("htmltablewidth") + " BORDER=" + getvar("tableborder") + ">\n" + s
				else:
					s = prepend + "<TABLE BORDER=" + getvar("tableborder") + ">\n" + s
                		setvar("envtabular","true")
				processed = 1
			if (processed == 0) and (symbol[REQUIREENV][0:7]== 'tabular') and (getvar("envtabular") == "true"):
				processed = 1
				if mode == "latex":					
					if symbol[REQUIREENV] == "tabularcolumn":
						if debug == 1:
							print "FOUND COLUMN SEPERATOR"
						olds = ""
						currentcolumn = 0
						while olds != s:
							olds = s
							currentcolumn = currentcolumn + 1								
							#print "COLUMN " + str(currentcolumn)
							skipcolumns = 0
							extra = ""
							leftborder = ""
							rightborder = ""
							if (getvar("column" + str(currentcolumn) + "border") == "single"):
								leftborder = "|"
								rightborder = "|"
							elif (getvar("column" + str(currentcolumn) + "border") == "double"):
								leftborder = "||"
								rightborder = "||"
							elif (getvar("column" + str(currentcolumn) + "border") == "none"):
								if (getvar("columnindent") != "true"):
									leftborder ="@{*}"
									rightborder ="@{*}"	
							#print getvar("column" + str(currentcolumn) + "span")
							if (getvar("column" + str(currentcolumn) + "span") == "0") or (getvar("column" + str(currentcolumn) + "span") == "1") or (getvar("column" + str(currentcolumn) + "span") == ""):								
								#print "column" + str(currentcolumn) + "exactwidth=[" + getvar("column" + str(currentcolumn) + "exactwidth") + "]"
								if (getvar("column" + str(currentcolumn) + "exactwidth") != ""):
									#print "IN"
									if (getvar("column" + str(currentcolumn) + "align") == "r"):
										extra = extra + "\raggedleft "
									elif (getvar("column" + str(currentcolumn) + "align") == "c"):
										extra = extra + "\centering "
							
							if (getvar("rowtextrgb_latex") != ""):
								extra = extra + " \\color[rgb]{"+getvar("rowtextrgb_latex")+"}"
							elif (getvar("rowtextcolor") != ""):
								extra = extra + " \\color{"+getvar("rowtextcolor")+"}"  
							
										
							if (getvar("column" + str(currentcolumn) + "span") == "2"):
								extra =  extra + "\multicolumn{2}{" + leftborder + getvar("multicolalign") + rightborder + "}{"
								skipcolumns = 1
							elif (getvar("column" + str(currentcolumn) + "span") == "3"):
								extra =  extra + "\multicolumn{3}{" + leftborder + getvar("multicolalign") + rightborder + "}{"
								skipcolumns = 2
							elif (getvar("column" + str(currentcolumn) + "span") == "4"):
								extra =  extra + "\multicolumn{4}{" + leftborder + getvar("multicolalign") + rightborder + "}{"
								skipcolumns = 3
							elif (getvar("column" + str(currentcolumn) + "span") == "5"):
								extra =  extra + "\multicolumn{5}{" + leftborder + getvar("multicolalign") + rightborder + "}{"
								skipcolumns = 4
							elif (getvar("column" + str(currentcolumn) + "span") == "6"):
								extra =  extra + "\multicolumn{6}{" + leftborder + getvar("multicolalign") + rightborder + "}{"
								skipcolumns = 5
							elif (getvar("column" + str(currentcolumn) + "span") == "7"):
								extra =  extra + "\multicolumn{7}{" + leftborder + getvar("multicolalign") + rightborder + "}{"
								skipcolumns = 6
							elif (getvar("column" + str(currentcolumn) + "span") == "8"):
								extra =  extra + "\multicolumn{8}{" + leftborder + getvar("multicolalign") + rightborder + "}{"
								skipcolumns = 7
							elif (getvar("column" + str(currentcolumn) + "span") == "9"):
								extra =  extra + "\multicolumn{9}{" + leftborder + getvar("multicolalign") + rightborder + "}{"
								skipcolumns = 8
							if currentcolumn == 1:
								#print "DID COLUMN 1"
								olds = ""
								s = extra + s
							else: 
								if closemulticol == 1:
									#print "PRE-REPLACE: " + s
									s = s.replace(symbol[SYMBOLNAME], "}" + symbol[TEXSYMBOL] + extra,1)
									#print "REPLACED 1 COLUMN"
									#print "POST-REPLACE: " + s
								else:
									#print "PRE-REPLACE: " + s
									s = s.replace(symbol[SYMBOLNAME],symbol[TEXSYMBOL] + extra,1)
									#print "REPLACED 1 COLUMN"
									#print "POST-REPLACE: " + s
							currentcolumn = currentcolumn + skipcolumns
							if s != olds:
								if skipcolumns > 0:
									closemulticol = 1
								else: 
									closemulticol = 0
					else:
						s = s.replace(symbol[SYMBOLNAME],symbol[TEXSYMBOL])							
				elif mode == "html":
					if symbol[REQUIREENV] == "tabularcolumn":
						olds = ""
						currentcolumn = 0
						while olds != s:
							olds = s
							currentcolumn = currentcolumn + 1
							htmlcelloptions = ""
							skipcolumns = 0
							if (getvar("column" + str(currentcolumn) + "span") == "") or  (getvar("column" + str(currentcolumn) + "span") == "0") or (getvar("column" + str(currentcolumn) + "span") == "1"):
								if (getvar("column" + str(currentcolumn) + "align")[0] == "l"):
									htmlcelloptions =  htmlcelloptions + " align=left "
								elif (getvar("column" + str(currentcolumn) + "align")[0] == "r"):
									htmlcelloptions =  htmlcelloptions + " align=right "
								elif (getvar("column" + str(currentcolumn) + "align")[0] == "c"):
									htmlcelloptions =  htmlcelloptions + " align=center "
								if (getvar("column" + str(currentcolumn) + "htmlwidth") != ""):
									htmlcelloptions =  htmlcelloptions + " width=" + getvar("column" + str(currentcolumn) + "htmlwidth") + " "
							else:
								if (getvar("multicolalign")[0] == "l"):
									htmlcelloptions =  htmlcelloptions + " align=left "
								elif (getvar("multicolalign")[0] == "r"):
									htmlcelloptions =  htmlcelloptions + " align=right "
								elif (getvar("multicolalign")[0] == "c"):
									htmlcelloptions =  htmlcelloptions + " align=center "																		
						
							restorehtmlfontcolor = ""
							if getvar("rowtextrgb_html") != "":
								restorehtmlfontcolor = getvar("htmlfontcolor")
								setvar("htmlfontcolor", getvar("rowtextrgb_html"))
							elif getvar("rowtextcolor") != "":
								restorehtmlfontcolor = getvar("htmlfontcolor")
								setvar("htmlfontcolor", getvar("rowtextcolor"))								
							elif getvar("column"+ str(currentcolumn) + "textrgb_html") != "":
								restorehtmlfontcolor = getvar("htmlfontcolor")
								setvar("htmlfontcolor", getvar("column"+ str(currentcolumn) + "textrgb_html"))
							elif getvar("column"+ str(currentcolumn) + "textcolor") != "":
								restorehtmlfontcolor = getvar("htmlfontcolor")
								setvar("htmlfontcolor",getvar("column"+ str(currentcolumn) + "textcolor"))
								#print "SET COLOR to " + getvar("column"+ str(currentcolumn) + "textcolor") + " for COLUMN " + str(currentcolumn)
							
								
							if getvar("rowrgb_html") != "":
								htmlcelloptions = htmlcelloptions + " BGCOLOR=" + getvar("rowrgb_html") + " "
							elif getvar("rowcolor") != "":
								htmlcelloptions = htmlcelloptions + " BGCOLOR=" + getvar("rowcolor") + " "
							elif getvar("column"+ str(currentcolumn) + "rgb_html") != "":
								htmlcelloptions = htmlcelloptions + " BGCOLOR=" + getvar("column"+ str(currentcolumn) + "rgb_html") + " "
							elif getvar("column"+ str(currentcolumn) + "color") != "":								
								htmlcelloptions = htmlcelloptions + " BGCOLOR=" + getvar("column"+ str(currentcolumn) + "color") + " "
								
								
								
										
							if (getvar("tableborder") != "0") and (getvar("column" + str(currentcolumn) + "border") == "none"):
								htmlcelloptions =  htmlcelloptions + " border=0 "
							elif (getvar("tableborder") != "0") and (getvar("column" + str(currentcolumn) + "border") == "double"):
								htmlcelloptions =  htmlcelloptions + " border=2 "
							
							if (getvar("column" + str(currentcolumn) + "css") != ""):
								htmlcelloptions =  htmlcelloptions + " style=" + getvar("column" + str(currentcolumn) + "css") + " "
							if (getvar("column" + str(currentcolumn) + "span") == "2"):
								htmlcelloptions =  htmlcelloptions + " colspan=2 "
								skipcolumns = 1
							elif (getvar("column" + str(currentcolumn) + "span") == "3"):
								htmlcelloptions =  htmlcelloptions + " colspan=3 "
								skipcolumns = 2
							elif (getvar("column" + str(currentcolumn) + "span") == "4"):
								htmlcelloptions =  htmlcelloptions + " colspan=4 "
								skipcolumns = 3
							elif (getvar("column" + str(currentcolumn) + "span") == "5"):
								htmlcelloptions =  htmlcelloptions + " colspan=5 "
								skipcolumns = 4
							elif (getvar("column" + str(currentcolumn) + "span") == "6"):
								htmlcelloptions =  htmlcelloptions + " colspan=6 "
								skipcolumns = 5
							elif (getvar("column" + str(currentcolumn) + "span") == "7"):
								htmlcelloptions =  htmlcelloptions + " colspan=7 "
								skipcolumns = 6
							elif (getvar("column" + str(currentcolumn) + "span") == "8"):
								htmlcelloptions =  htmlcelloptions + " colspan=8 "
								skipcolumns = 7
							elif (getvar("column" + str(currentcolumn) + "span") == "9"):
								htmlcelloptions =  htmlcelloptions + " colspan=9 "
								skipcolumns = 8
								
							if currentcolumn == 1:
								olds = ""	
								firsthtmlcelloptions = htmlcelloptions
							else: 
								s = s.replace(symbol[SYMBOLNAME],symbol[HTMLSYMBOL],1)
								s = s.replace("$htmlcelloptions",htmlcelloptions,1)
								s = s.replace("$htmlfontcolor",getvar("htmlfontcolor"),1)
							currentcolumn = currentcolumn + skipcolumns
							if restorehtmlfontcolor != "":
								#print "RESTORED COLOR to " + restorehtmlfontcolor + " after  COLUMN " + str(currentcolumn)
								setvar("htmlfontcolor", restorehtmlfontcolor)
					else:
						s = s.replace(symbol[SYMBOLNAME],symbol[HTMLSYMBOL])
			if (processed == 0) and (symbol[REQUIREENV] == 'math') and (mode == "latex"):
				processed = 1
				newline = ""
				begin = 0
				end = 0
				inmath = envmath
				for i in range(len(s)):											
					if (s[i] == '$') and (inmath == 0):	
						#newline = newline +  "INMATH"
						inmath = 1						
					elif (s[i] == '$') and (inmath == 1):						
						inmath = 0
					elif (s[i:i+ len(symbol[0])] == symbol[0]) and (inmath == 1):
						if mode == "latex":
							newline = newline + s[begin:i] + symbol[TEXSYMBOL] + ' '
						elif mode == "html": 
							newline = newline + s[begin:i] + symbol[HTMLSYMBOL] + ' '
						begin = i + len(symbol[0]) 
					elif (s[i:i+ len(symbol[0])] == symbol[0]) and (inmath == 0):
						if mode == "latex":
							newline = newline + s[begin:i ] + '$' + symbol[TEXSYMBOL] + '$'
						elif mode == "html":
							newline = newline + s[begin:i ] + '$' + symbol[HTMLSYMBOL] + '$'
						begin = i + len(symbol[0]) 						
				s = newline + s[begin:len(s)]			
			if (processed == 0) and (mode == "latex"):
				processed = 1
				symbol[TEXSYMBOL] = symbol[TEXSYMBOL].replace("\\{","{")
				symbol[TEXSYMBOL] = symbol[TEXSYMBOL].replace("\{","{")
				symbol[TEXSYMBOL] = symbol[TEXSYMBOL].replace("\}","}")
				symbol[TEXSYMBOL] = symbol[TEXSYMBOL].replace("\\}","}")
				if symbol[SYMBOLNAME][len(symbol[SYMBOLNAME]) - 1] == ">":
					s = s.replace(symbol[SYMBOLNAME],symbol[TEXSYMBOL])
				else:
					s = s.replace(symbol[SYMBOLNAME] + ' ',symbol[TEXSYMBOL] + ' ')
					s = s.replace(symbol[SYMBOLNAME] + '\\',symbol[TEXSYMBOL] + '\\')
					s = s.replace(symbol[SYMBOLNAME] + '<',symbol[TEXSYMBOL] + '<')
					s = s.replace(symbol[SYMBOLNAME] + '.',symbol[TEXSYMBOL] + '.')
					s = s.replace(symbol[SYMBOLNAME] + ',',symbol[TEXSYMBOL] + ',')
					s = s.replace(symbol[SYMBOLNAME] + '?',symbol[TEXSYMBOL] + '?')
					s = s.replace(symbol[SYMBOLNAME] + '!',symbol[TEXSYMBOL] + '!')
					s = s.replace(symbol[SYMBOLNAME] + ':',symbol[TEXSYMBOL] + ':')
					s = s.replace(symbol[SYMBOLNAME] + ';',symbol[TEXSYMBOL] + ';')
			if (processed == 0) and (mode == "html"):
				processed = 1
				if symbol[SYMBOLNAME][len(symbol[SYMBOLNAME]) - 1] == ">":
					s = s.replace(symbol[SYMBOLNAME],symbol[HTMLSYMBOL])
				else:			
					s = s.replace(symbol[SYMBOLNAME] + ' ',symbol[HTMLSYMBOL] + ' ')
					s = s.replace(symbol[SYMBOLNAME] + '\\',symbol[HTMLSYMBOL] + '\\')
					s = s.replace(symbol[SYMBOLNAME] + '<',symbol[HTMLSYMBOL] + '<')			
					s = s.replace(symbol[SYMBOLNAME] + '.',symbol[HTMLSYMBOL] + '.')
					s = s.replace(symbol[SYMBOLNAME] + ',',symbol[HTMLSYMBOL] + ',')
					s = s.replace(symbol[SYMBOLNAME] + '?',symbol[HTMLSYMBOL] + '?')
					s = s.replace(symbol[SYMBOLNAME] + '!',symbol[HTMLSYMBOL] + '!')
					s = s.replace(symbol[SYMBOLNAME] + ':',symbol[HTMLSYMBOL] + ':')
					s = s.replace(symbol[SYMBOLNAME] + ';',symbol[HTMLSYMBOL] + ';')				
	return s	

def processmarkers(s):
	global markers
	global MARKER
	global TEXBEGIN
	global TEXEND
	global HTMLBEGIN
	global HTMLEND
	global mode
	for marker in markers:
		mlen = len(marker[MARKER])
		if string.count(s,marker[MARKER]) >= 2:
			newline = ""
			begin = 0
			end = 0
			inmarker = 0
			for i in range(len(s)):
				if (s[i:i+mlen] == marker[MARKER]) and (inmarker == 0):		
					#begin found
					if mode == "latex":
						newline = newline + s[end:i] + marker[TEXBEGIN]
					elif mode == "html":
						newline = newline + s[end:i] + marker[HTMLBEGIN]	
					begin = i + mlen
					inmarker = 1						
				elif (s[i:i+mlen] == marker[MARKER]) and (inmarker == 1):		
					#end found
					if mode == "latex":
						newline = newline + s[begin:i] + marker[TEXEND]
					elif mode == "html":
						newline = newline + s[begin:i] + marker[HTMLEND]
					end = i + mlen
					inmarker = 0
			#Add the last part of the line as well						
			s = newline + s[end:len(s)]						
	return s

def processhardcommands(line):
	global envitemize
	global envenumerate
	global envtabular
	global envmath
	global tabulardelay
	global detectpspdf	
	global enabled
	global envchapter
	global envsection
	global envsubsection
	global doctype
	global envdoc
	global started
	global hardcommands
	global commands
	global numbered
	global symbols
	global markers
	global variables	
	global settexcommand
	global settexcommandbody
	global sethtmlcommand
	global sethtmlcommandbody
	global COMMANDNAME
	global COMMANDARGS
	global TEXBODY
	global HTMLBODY	
	global SYMBOLNAME
	global TEXSYMBOL
	global HTMLSYMBOL
	global REQUIREENV
	global MARKER
	global TEXBEGIN
	global TEXEND
	global HTMLBEGIN
	global HTMLEND
	global VARNAME
	global VARVALUE	
	global debug
	global mode
	global htmlwrap
	global incondition
	global conditionlevel
	global conditionresult
	global vspace
	global buffervar
	global buffercontent
	global htmlimage
	global htmlimagecontent
	global confdir
	global imagenum
	global rawadd
	
	#convert hard commands
	for command in hardcommands:
		if (string.lower(line[0:len(command[0])]) == string.lower(command[0])):
			if (command[1] == 'exec'):
				target = string.strip(line[len(command[0]):9999])
				target = processvariables(condition)
			if (command[1] == 'eval'):
				pythoncmd = string.strip(line[len(command[0]):9999])
				pythoncmd = processvariables(pythoncmd)
				line = eval(pythoncmd)
			if (command[1] == 'evaltovar'):
				pythoncmd = string.strip(line[len(command[0]):9999])
				pythoncmd = processvariables(pythoncmd)
				line = "$result={" + eval(pythoncmd) + "}"
			if (command[1] == 'include'):
				includefile = string.strip(line[len(command[0]):9999])
				includefile = processvariables(includefile)
				if os.path.exists(confdir + includefile):
					includefile = confdir + includefile
				f = open(includefile ,"r")
				includelines = f.readlines()
				f.close()
				for l in includelines:
					l = nonl(l)
				if (not(((os.path.splitext(includefile) == ".html") and (mode != "html")) or ((os.path.splitext(includefile) == ".tex") and (mode != "latex")))):
					oldvspace = vspace
					rawadd = rapidtex(includelines,0)
					vspace = oldvspace
				line = "-RAWADD-"
			if (command[1] == 'rawinclude'):
				includefile = string.strip(line[len(command[0]):9999])
				includefile = processvariables(includefile)
				if os.path.exists(confdir + includefile):
					includefile = confdir + includefile						
				f = open(includefile ,"r")
				f.close()
				if (not(((os.path.splitext(includefile) == ".html") and (mode != "html")) or ((os.path.splitext(includefile) == ".tex") and (mode != "latex")))):
					 rawadd = includelines
				line = "-RAWADD-"
			if (command[1] == 'debuglist'):
				if debug == 1:							
					print "DEBUG:\tCOMMAND LISTING:"
					for c in commands:
						if c[TEXBODY] != "":
							print "DEBUG:\tcommand " + c[COMMANDNAME] + " (" + str(c[COMMANDARGS]) + ") exists for LaTeX"
						if c[HTMLBODY] != "":
							print "DEBUG:\tcommand " + c[COMMANDNAME] + " (" + str(c[COMMANDARGS]) + ") exists for HTML"									
					print "DEBUG:	SYMBOL LISTING:"
					for s in symbols:
						print "DEBUG:\tsymbol " + s[SYMBOLNAME] + " maps to " + s[TEXSYMBOL] + " for LaTeX"
						print "DEBUG:\tsymbol " + s[SYMBOLNAME] + " maps to " + s[HTMLSYMBOL] + " for HTML"																
					print "DEBUG:	MARKER LISTING:"
					for m in markers:
						print "DEBUG:\tmarker " +  m[MARKER] + " results in " + m[TEXBEGIN] + "text" + m[TEXEND] + " for TeX"
						print "DEBUG:\tmarker " +  m[MARKER] + " results in " + m[HTMLBEGIN] + "text" + m[HTMLEND] + " for HTML"
				line = "-CUT-"
			if (command[1] == 'settexcommand'):
				settexcommand = string.strip(line[len(command[0]):9999])
				settexcommandbody = ""
				line = "-CUT-"
			if (command[1] == 'sethtmlcommand'):
				sethtmlcommand = string.strip(line[len(command[0]):9999])						
				sethtmlcommandbody = ""
				line = "-CUT-"
			if (command[1] == 'beginhtmlimage'):	
				if mode == "html":
					htmlimage = 1
					htmlimagecontent = []
					mode = "latex"
					line = "-CUT-"				
			if (command[1] == 'endhtmlimage'):	
				if ((htmlimage == 1)):
					mode = "html"
					imagenum = imagenum + 1
					htmlimage = 0
					#imagebody = rapidtex(htmlimagecontent,0)
					imagebody = htmlimagecontent
					imageheader = []
					imageheader.append("\\batchmode\n\\documentclass[12pt]{article}\n")
					imageheader.append(getvar("htmlimageheader"))
					inf = open(confdir + "htmlimage_header.tex","r")
					readlines = inf.readlines()
					inf.close()
					for l in readlines:
						imageheader.append(l)					 
					imageheader.append("\\begin{document}\n")
					inf = open(confdir + "htmlimage_document.tex","r")
					readlines = inf.readlines()
					inf.close()
					for l in readlines:
						imageheader.append(l)					 						
					imagefooter = []
					imagefooter.append("\\end{document}\n")
					imgf = open("/tmp/image" + str(imagenum) + ".tex","w+")
					for l in imageheader:
						imgf.write(l)
					imgf.write('\n{\\newpage\\clearpage\\lthtmlfigureA{htmlimage}%\n')
					for l in imagebody:
						if debug == 1:
							print "HTMLIMAGE: " + l
						imgf.write(l)
					imgf.write('\n\\lthtmlfigureZ\\lthtmlcheckvsize\\clearpage}')
					for l in imagefooter:
						imgf.write(l)												
					imgf.close()	
					time.sleep(1)				
					if debug == 1:
						print "RUNNING htmlimage.sh TO CREATE HTMLIMAGE"
					os.system(confdir + "htmlimage.sh " + str(imagenum))
					imgf.close()
					if debug == 1:
						print "IMPLEMENTING GENERATED HTMLIMAGEAGES"
					shutil.copyfile("/tmp/image" + str(imagenum) + ".png","image" + str(imagenum) + ".png")
					line = "<img src=\"image" + str(imagenum)  + ".png\" border=0>"
			if (command[1] == 'beginbuffer'):	
				buffervar = string.strip(line[len(command[0]):9999])
				buffercontent = ""
				line = "-CUT-"
			if (command[1] == 'insertbuffer'):	
				varvalue = string.strip(line[len(command[0]):9999])
				if varvalue[0] == '$': 
					varvalue = varvalue[1:9999]
				oldvspace = vspace
				line = flatten(rapidtex(unflatten(getvar(varvalue),0)))
				vspace = oldvspace
			if (command[1] == 'setsymbolenv'):
				args = getblocks(line, 2)
				found = 0
				for s in symbols:
					if (string.lower(s[SYMBOLNAME]) == string.lower(args[1])):
						found = 1
						s[REQUIREENV] = args[2]
						break
				line = "-CUT-"
			if (command[1] == 'settexsymbol'):
				args = getblocks(line, 2)
				found = 0
				for s in symbols:
					if (string.lower(s[SYMBOLNAME]) == string.lower(args[1])):
						found = 1
						s[TEXSYMBOL] = args[2]
						break
				if found == 0:
					insert(symbols,[args[1],args[2],args[1],'']) 
				line = "-CUT-"
			if (command[1] == 'sethtmlsymbol'):
				args = getblocks(line, 2)
				found = 0
				for s in symbols:
					if (string.lower(s[SYMBOLNAME]) == string.lower(args[1])):
						found = 1
						s[HTMLSYMBOL] = args[2]
						break
				if found == 0:
					insert(symbols,[args[1],args[1],args[2],'']) 						
				line = "-CUT-"
			if (command[1] == 'settexmarker'):
				args = getblocks(line, 3)
				found = 0
				for m in markers:
					if (m[MARKER] == args[1]):
						found = 1
						m[TEXBEGIN] = args[2]
						m[TEXEND] = args[3]
						break
				if found == 0:
					insert(markers,[args[1],args[2],args[3],'',''])		
				line = "-CUT-"
			if (command[1] == 'sethtmlmarker'):
				args = getblocks(line, 3)
				found = 0
				for m in markers:
					if (m[MARKER] == args[1]):
						found = 1
						m[HTMLBEGIN] = args[2]
						m[HTMLEND] = args[3]
						break
				if found == 0:
					insert(markers,[args[1],'','',args[2],args[3]])
				line = "-CUT-"
			if (command[1] == 'commandalias'):
				args = getblocks(line, 2)
				for c in commands:
					if string.lower(c[COMMANDNAME]) == string.lower(args[1]):
						insert(commands,[args[2],c[COMMANDARGS],c[TEXBODY],c[HTMLBODY]])			
						break
				line = "-CUT-"
			if (command[1] == 'symbolalias'):
				args = getblocks(line, 2)
				for s in symbols:
					if string.lower(s[SYMBOLNAME]) == string.lower(args[1]):
						insert(symbols,[args[2],s[TEXSYMBOL],s[HTMLSYMBOL],s[REQUIREENV]])															
						break
				line = "-CUT-"
			if (command[1] == 'condition'):
				condition = string.strip(line[len(command[0]):9999])
				condition = processvariables(condition)
				incondition = incondition + 1
				conditionlevel = incondition
				conditionresult[conditionlevel] = eval(condition)
				if debug == 1:
					print eval(condition)
					print "CONDITION " + condition + ": " +  str(conditionresult[conditionlevel])
				line = "-CUT-"
			if command[1] == 'beginheader':						
				started=1
				line = "-CUT-"
			if command[1] == 'endheader':						
				started=0	
				line = "-CUT-"
			if command[1] == 'chapter':
				line = ""
				numbered = 1
				envchapter = envchapter * -1
				if debug == 1:
					print "SECTIONING COMMAND"
			if command[1] == 'section':
				line = ""
				numbered = 1
				envsection = envsection * -1
				if debug == 1:
					print "SECTIONING COMMAND"
			if command[1] == 'subsection':
				line = ""
				numbered = 1
				envsubsection = envsubsection * -1	
				if debug == 1:
					print "SECTIONING COMMAND"
			if command[1] == 'chapter*':
				line = ""
				numbered = 0
				envchapter = envchapter * -1
				if debug == 1:
					print "SECTIONING COMMAND"
			if command[1] == 'section*':
				line = ""
				numbered = 0
				envsection = envsection * -1
				if debug == 1:
					print "SECTIONING COMMAND"
			if command[1] == 'subsection*':
				line = ""
				numbered = 0
				envsubsection = envsubsection * -1
				if debug == 1:
					print "SECTIONING COMMAND"
			if (command[1] == 'endenv') and (getvar("envitemize") == "true"):					
				if mode == "latex":
					line = "\end{itemize}"
				elif mode == "html":
					line = "</ul>"
				setvar("envitemize","false")
			elif (command[1] == 'endenv') and (getvar("envenumerate") == "true"):					
				if mode == "latex":
					line = "\end{enumerate}"
				elif mode == "html":
					line = "</ol>"
				setvar("envenumerate","false")
			elif (command[1] == 'endenv') and (getvar("envtabular") == "true"):					
				if mode == "html":
					if getvar("tabularenv") == "longtable":
						line = "</TABLE><br></center>"
					else: 
						line = "</TABLE>"
				elif mode == "latex":
					if getvar("tabularenv") == "longtable":
						line = "\end{longtable}"
					else:
						line = "\end{tabular}"
				setvar("envtabular","false")				
	return line


def processvariables(s):
	global variables
	global VARNAME
	global VARVALUE
	beginvar= 0
	beginvar2= 0
	varname=""
	assign=0	
	append=0
	inblock =0
	prev = ""
	restart = 1
	
	#for v in variables:
	#	s = s.replace("$" + v[VARNAME], v[VARVALUE])
	
	s2 = s
	#Assign variables
	while restart == 1:
		restart = 0
		s = s2
		for i in range(len(s)):
			if (assign == 0) and (s[i] == '$') and (prev != "\\"):
				beginvar = i + 1		
			if assign == -1:
				if s[i] == "+":
					assign = 1				
				else:
					s2 = s[0:beginvar - 1] + s[i:9999]
					setvar(varname,varvalue)
					varname=""
					varvalue=""
					assign=0
					beginvar = 0
					restart = 1
					break
			if assign == 1:
				if (s[i] == "{") and (prev != "\\"):
					inblock = inblock + 1
					if inblock > 1:
						varvalue=varvalue + s[i]									
				elif (s[i] == "}") and (prev != "\\"): 
					inblock = inblock - 1
					if inblock > 1:
						varvalue=varvalue + s[i]
				elif (s[i] == "$") and (prev != "\\"):
					beginvar2 = i + 1					
				elif (beginvar2 != 0) and (i > beginvar2) and ((s[i] == " ") or (s[i] == ",") or (s[i] == ".") or (s[i] == "-") or (s[i] == "\\") or (s[i] == "}") or (s[i] == "<") or (s[i] == ">")  or (s[i] == "'")  or (s[i] == "\"")):
					varname2 = s[beginvar:i]
					for v in variables:
						if v[VARNAME] == varname2:
							varvalue = varvalue + s[0:beginvar2 - 1] + v[VARVALUE]
							beginvar2 = 0
							break
					if (s[i] == "}"):
						inblock = inblock - 1
				else:
					varvalue=varvalue + s[i]
				if inblock == 0:
					if (s[i] == " ") or (s[i] == ",") or (s[i] == ".") or (s[i] == "-") or (s[i] == "\\") or (s[i] == "}") or (s[i] == "<") or (s[i] == ">")  or (s[i] == "'")  or (s[i] == "\""):
						assign=-1
			if (beginvar > 0) and (assign == 0):
				if (s[i] == '='):
					varname = s[beginvar:i]
					varvalue= ""	
					assign=1
				elif (s[i] == " ") or (s[i] == ",") or (s[i] == ".") or (s[i] == "-") or (s[i] == "\\") or (s[i] == "}") or (s[i] == "<") or (s[i] == ">")  or (s[i] == "'")  or (s[i] == "\""):
					varname = s[beginvar:i]
					for v in variables:
						if v[VARNAME] == varname:
							s2 = s[0:beginvar - 1] + v[VARVALUE] + s[i:9999]						
							beginvar = 0
							varname = ""
							assign = 0
							restart = 1
							s = s2
							break
					if restart == 1:
						break
			prev = s[i]				
	return s2
	
def setvar(varname,varvalue):
	global variables
	global VARNAME
	global VARVALUE
	global debug
	found = 0
	for v in variables:
		if v[VARNAME] == varname:
			found = 1
			if (string.upper(varvalue) == "[NONE]") or (string.upper(varvalue) == "-NONE-") or (string.upper(varvalue) == "-CUT-"):
				v[VARVALUE] = ""
			else:
				v[VARVALUE] = varvalue
			if debug == 1:
				print "MODIFYING VARIABLE " + varname + " with new value " + varvalue
	if found == 0:
		insert(variables,[varname,varvalue])
		if debug == 1:
			print "ADDING VARIABLE " + varname + " with value " + varvalue
	
def getvar(varname):
	global variables
	global VARNAME
	global VARVALUE
	global debug
	for v in variables:
		if v[VARNAME] == varname:
			return v[VARVALUE]
																		
def rapidtex(lines, doheaders):  
	global envitemize
	global envenumerate
	global envtabular
	global envmath
	global tabulardelay
	global detectpspdf	
	global enabled
	global envchapter
	global envsection
	global envsubsection
	global doctype
	global envdoc
	global started
	global hardcommands
	global commands
	global symbols
	global markers
	global variables
	global settexcommand
	global settexcommandbody
	global sethtmlcommand
	global sethtmlcommandbody
	global numbered
	global COMMANDNAME
	global COMMANDARGS
	global TEXBODY
	global HTMLBODY	
	global SYMBOLNAME
	global TEXSYMBOL
	global HTMLSYMBOL
	global REQUIREENV
	global MARKER
	global TEXBEGIN
	global TEXEND
	global HTMLBEGIN
	global HTMLEND
	global VARNAME
	global VARVALUE	
	global debug
	global mode
	global htmlwrap
	global incondition
	global conditionlevel
	global conditionresult
	global vspace
	global vout
	global buffervar
	global buffercontent	
	global processmode	
	global headerbuffer
	global rawadd
	global closemulticol
	global firsthtmlcelloptions
	
	outputlines = []
	vspace = 0
	

	#Go through lines:
	for line in lines:
		line = nonl(line) + ' '
		if debug == 1:
			print "IN:	" + line

		#Already process hardcommands related to buffers
		for command in hardcommands:
			if line[0:len(command[0])] == command[0]:
				if (command[1] == 'endsettexcommand') and (enabled == 1):
					args = 0
					for i in range(1,20):
						if settexcommandbody.find("$" + str(i)) == -1:
							args = i - 1
							break
					found = 0						
					for c in commands:
						if (string.lower(c[COMMANDNAME]) == string.lower(settexcommand)):
							found = 1
							if debug == 1:
								print "MODIFIYING COMMAND (TEX): " + settexcommand + " (" + str(c[COMMANDARGS]) + ")"								
							c[TEXBODY] = settexcommandbody
							break
					if found == 0:							
						if debug == 1:
							print "ADDING COMMAND (TEX): " + settexcommand + " (" + str(args) + ")"
						insert(commands, [settexcommand, args,  settexcommandbody, ''])								
					settexcommandbody = ""
					settexcommand = ""
					line = "-CUT-"
				if (command[1] == 'endsethtmlcommand') and (enabled == 1):
					args = 0
					for i in range(1,20):
						if sethtmlcommandbody.find("$" + str(i)) == -1:
							args = i - 1
							break
					found = 0						
					for c in commands:
						if (string.lower(c[COMMANDNAME]) ==	string.lower(sethtmlcommand)):
							found = 1
							if debug == 1:
								print "MODIFIYING COMMAND (HTML): " + sethtmlcommand + " (" + str(c[COMMANDARGS]) + ")"
							c[HTMLBODY] = sethtmlcommandbody
							break
					if found == 0:
						if debug == 1:
							print "ADDING COMMAND (HTML): " + sethtmlcommand + " (" + str(args) + ")"
						insert(commands,[sethtmlcommand, args, '',  sethtmlcommandbody])								
					sethtmlcommandbody = ""
					sethtmlcommand = ""
					line = "-CUT-"
				if (command[1] == "endbuffer") and (enabled == 1):
					args = 0
					if buffervar[0] == '$':
						buffervar = buffervar[1:9999]
					setvar(buffervar, buffercontent)
					if debug == 1:
							print "BUFFER TO VARIABLE: " + buffervar
					buffervar = ""
					buffercontent = ""
				


		#Enable or disable preprocessor based on conditions or buffers
		do = 1
		if ((incondition > 0) and (conditionresult[conditionlevel] == 0)):
			do = 0
		if (settexcommand != "") or (sethtmlcommand != ""):
			do = 0

					

		#Process preprocessor enable/disable commands
		if (settexcommand != "") or (sethtmlcommand != "") or (buffervar != ""):
			if debug == 1:
				print "TO BUFFER"
		elif (string.strip(line) == "<ENABLE>") or (string.strip(line) == "<ON>"):
			enabled = 1	
			line = "-CUT-"			
			if debug == 1:
				print "ENABLED PREPROCESSOR"			
		elif (string.strip(line) == "<DISABLE>") or (string.strip(line) == "<OFF>"):
			enabled = 0	
			line = "-CUT-"	
			if debug == 1:
				print "DISABLED PREPROCESSOR"			
		elif (string.strip(line) == "<TEXONLY>") or (string.strip(line) == "<LATEXONLY>"):
			line = "-CUT-"			
			processmode = "latex"
			if debug == 1:
				print "LATEX ONLY"						
		elif (string.strip(line) == "<HTMLONLY>"):
			line = "-CUT-"		
			processmode = "html"
			if debug == 1:
				print "HTML ONLY"			
		elif (string.strip(line) == "<ALL>") or (string.strip(line) == "<BOTH>"):
			line = "-CUT-"			
			processmode = "all"
			if debug == 1:
				print "HTML AND LATEX"
		#Deal with conditional statements
		elif (string.strip(line[0:6]) == "<else>") and (incondition == conditionlevel):
			line = "-CUT-"
			if conditionresult[conditionlevel] == 1:
				conditionresult[conditionlevel] = 0
				do = 0
			else:
				conditionresult[conditionlevel] = 1
				do = 1			
		elif (string.strip(line)[0:5] == "</fi>") or  (string.strip(line)[0:5] == "</if>"):
			line = "-CUT-"			
			incondition = incondition - 1
			if incondition == conditionlevel - 1:
				conditionlevel = conditionlevel - 1
				do = 1
		elif (string.strip(line)[0:4] == "<if>") and (incondition >= conditionlevel) and (incondition != 0):			
			incondition = incondition + 1
			line = "-CUT-"
		elif (incondition > 0) and (incondition >= conditionlevel) and (conditionresult[conditionlevel] == 0):
			line = "-CUT-"
			if debug == 1:
				print "SKIPPING DUE TO FALSE CONDITION (" + str(conditionlevel) +  ")"
		elif (line[0] == '%'):
			if mode == "html":
				line = "<!-- " + line[1:9999] + " -->"
		elif (line[0] == '#'):
			line = "-CUT-"
		elif (enabled == 1) and ((processmode == mode) or (processmode == "all")) and (do == 1):		
			
			#Detect vertical space
			if nonl(string.strip(line)) == '':
				vspace = vspace + 1
				if debug == 1:
					print "EMPTY LINE DETECTED"
																						
			#Process hardcommands
			line = processhardcommands(line)
													
			#Process commands
			line = processcommands(line)	
		
							
			#Process symbols		
			line = processsymbols(line)
			
			
			#Process Markers
			line = processmarkers(line)

			#Process Variables
			line = processvariables(line)
			

			
						
			
			
			if (mode == "html") and (settexcommand == "") and (sethtmlcommand == ""):
				#Undo Math environment before processing symbols
				prev = ""
				newline = ""
				for c in line:				
					if (c != '$'):
						newline = newline + c
					elif (prev == '\\'):
						newline = newline + c											
						prev = ""
				line = newline
				#Undo Tabular environment of \\ 
				if getvar("envtabular") == "true":
					line = line.replace("\\\\","");
				
			
			#Check certain environments for latex							 
			if mode == "latex":
				if (getvar("envtabular") == "true"):
					if (string.find(line,"\hline") == -1) and (string.find(line,"\\begin") == -1):
						if (string.strip(line) != "") and (not ((string.strip(line)[len(string.strip(line)) - 1] == '\\') and (string.strip(line)[len(string.strip(line)) - 2] == '\\'))):
							if closemulticol == 1:						
								line = line + '} \\\\'
							else:
								line = line + ' \\\\'
							breakpoint = 0
							for i in range(0,len(line)):
								if line[i] == "\n":
									breakpoint = i + 1
							if breakpoint == 0:
								prepend = ""
								postpend = line
							else:
								prepend = line[0:breakpoint]
								postpend = line[breakpoint:9999]
							if (getvar("rowrgb_latex") != ""):
								if (getvar("rowtextrgb_latex") != ""):
									line = prepend + "\\rowcolor[rgb]{" + getvar("rowrgb_latex") + "} \\color[rgb]{"+getvar("rowtextrgb_latex")+"}" + postpend
								elif (getvar("rowtextcolor") != ""):
									line = prepend + "\\rowcolor[rgb]{" + getvar("rowrgb_latex") + "} \\color{"+getvar("rowtextcolor")+"}" + postpend
								else:
									line = prepend + "\\rowcolor[rgb]{" + getvar("rowrgb_latex") + "} " + postpend
							elif (getvar("rowcolor") != ""):
								if (getvar("rowtextrgb_latex") != ""):
									line = prepend + "\\rowcolor{" + getvar("rowcolor") + "} \\color[rgb]{"+getvar("rowtextrgb_latex")+"}" + postpend
								elif (getvar("rowtextcolor") != ""):
									line = prepend + "\\rowcolor{" + getvar("rowcolor") + "} \\color{"+getvar("rowtextcolor")+"}" + postpend
								else:
									line = prepend + "\\rowcolor{" + getvar("rowcolor") + "} " + postpend
							
				if (envchapter == 1) and (line != ''):
					if mode == "latex":
						if numbered == 1:
							line = "\chapter{" + line + "}"
						else: 
							line = "\chapter*{" + line + "}"
				if (envsection == 1) and (line != ''):
					if mode == "latex":
						if numbered == 1:
							line = "\section{" + line + "}"
						else:
							line = "\section*{" + line + "}"
				if (envsubsection == 1) and (line != ''):
					if mode == "latex":
						if numbered == 1:
							line = "\subsection{" + line + "}"
						else:
							line = "\subsection*{" + line + "}"																		
			elif mode == "html":
			#Check certain environments for html	
			        if (getvar("envtabular") == "true"):
					#if (string.strip(line) != '') and (string.strip(line) != '[NONE]') and (string.strip(line) != '-CUT-') and (string.upper(string.strip(line)[0:3]) != '<TR') and (string.upper(string.strip(line)[0:3]) != '<TD') and (string.upper(string.strip(line))[0:6] != '<TABLE') :
					if (string.strip(line) != '') and (string.strip(line) != '[NONE]') and (string.strip(line) != '-CUT-') and (string.upper(string.strip(line)[0:3]) != '<TR') and (string.upper(string.strip(line)[0:3]) != '<TD') and (string.find(string.upper(line), '<TABLE') == -1):
						restorehtmlfontcolor = ""
						if getvar("rowtextrgb_html") != "":
							restorehtmlfontcolor = getvar("htmlfontcolor")
							setvar("htmlfontcolor", getvar("rowtextrgb_html"))
						elif getvar("rowtextcolor") != "":
							restorehtmlfontcolor = getvar("htmlfontcolor")
							setvar("htmlfontcolor", getvar("rowtextcolor"))								
						elif getvar("column"+ str(1) + "textrgb_html") != "":
							restorehtmlfontcolor = getvar("htmlfontcolor")
							setvar("htmlfontcolor", getvar("column"+ str(1) + "textrgb_html"))
						elif getvar("column"+ str(1) + "textcolor") != "":
							restorehtmlfontcolor = getvar("htmlfontcolor")
							setvar("htmlfontcolor",getvar("column"+ str(1) + "textcolor"))							
						line = "<TR><TD VALIGN=top " + firsthtmlcelloptions + "><font face=" + getvar("htmlfontface") + " size=" + getvar("htmlfontsize") + " color=" + getvar("htmlfontcolor") + ">" + line + "</font></TD></TR>"
						if restorehtmlfontcolor != "":
							setvar("htmlfontcolor",restorehtmlfontcolor)							
				if (envchapter == 1) and (line != ''):
					line = "<H1>" + line + "</H1>"				
				if (envsection == 1) and (line != ''):
					line = "<H2>" + line + "</H2>"				
				if (envsubsection == 1) and (line != ''):
					line = "<H3>" + line + "</H3>"
					

			#Output vertical space
			if (string.strip(line) != '') and (string.strip(line) != '\n') and (string.strip(line) != '-CUT-') and (vspace > 0) and (settexcommand == "") and (sethtmlcommand == ""):
				if mode == "html":
					if (envdoc == 1) and (envchapter != 1) and (envsection != 1) and (envsubsection != 1):
						line =  "\n<p>" + line 
					else: 						
						line = "\n" + line
				elif mode == "latex":
					line =  "\n" + line
				if debug == 1:
					print "EMPTY LINES RENDERED"
				vspace = 0						
					
					
					
			if (mode == "latex"):
				#Analyze header environments for LaTeX				
				if string.find(line,"\\begin{document}") != -1:
					envdoc = 1			
				elif string.find(line,"\\end{document}") != -1:
					envdoc = -1
				#Analyze non-header environments for LaTeX
				#if string.find(line,"\\begin{tabular}") != -1:
				#	envtabular = 1
				#	vspace = 0
				#elif string.find(line,"\\end{tabular}") != -1:
				#	envtabular = 0	
				if string.find(line,"$$") != -1:
					if envmath == 1:
						envmath = 0
					else:
						envmath = 1

				if vspace == 1: #There is a vertical spaces
					#Check if we we need to close a particular environment
					if getvar("envtabular") == "true":			
						line = "\\end{" + getvar("tabularenv") + "}\n" + line
						vspace = vspace - 2
						setvar("envtabular","false")
					if getvar("envitemize") == "true":			
						line = "\\end{itemize}\n" + line
						vspace = vspace - 2
						setvar("envitemize","false")
					if getvar("envenumerate") == "true":		
						line = "\\end{enumerate}\n" + line
						vspace = vspace - 2
						setvar("envenumerate","false")
				elif (vspace == 5) and (envdoc == 1):
					line = "\\bigskip\n" + line
			elif (mode == "html"):
				#Analyze header environments for HTML
				if doheaders == 1:
					if string.find(string.upper(line),"<HTML") != -1:
						htmlwrap = 1
					if string.find(string.upper(line),"</BODY>") != -1:
						envdoc = -1			
					if string.find(string.upper(line),"</HTML>") != -1:
						envdoc = -2		
					if string.find(string.upper(line),"<BODY") != -1:
				     		envdoc = 1
				#Analyze non-header environments for HTML
				#if string.find(string.upper(line),"<TABLE") != -1:
				#	envtabular = 1
				#elif string.find(string.upper(line),"</TABLE>") != -1:
				#	envtabular = 0
				if vspace == 1: #There is a vertical spaces
					#Check if we we need to close a particular environment
					if getvar("envtabular") == "true":
						if getvar("tabularenv") == "longtable":
							line = "</TABLE><br></center>" + line
						else: 
							line = "</TABLE>" + line
						vspace = vspace - 2
						setvar("envtabular","false")
					if getvar("envitemize") == "true":
						line = "</UL>" + line
						vspace = vspace - 2
						setvar("envitemize","false")
					if getvar("envenumerate") == "true":
						line = "</OL>" + line
						vspace = vspace - 2
						setvar("envenumerate","false")
				elif (vspace == 5) and (envdoc == 1):
					line = "<BR><BR><BR>" + line				



			if mode == "latex":
				#strip remaining HTML tags		
				line = striphtml(line)
			elif (mode == "html") and (htmlimage == 0):
				#strip remaining LaTeX tags		
				line = striplatex(line)
	
			#Remove [NONE] references
			line = line.replace("[NONE]", "")



	
		#Output command definitions to a certain buffer
		if (settexcommand != "") and (string.strip(line) != '') and (string.strip(line) != '-CUT-') and (enabled != -1):
			#Defining TeX command --> special buffer
			settexcommandbody = settexcommandbody + line + '\n'
		elif (sethtmlcommand != "") and (string.strip(line) != '') and (string.strip(line) != '-CUT-') and (enabled != -1):
			#Defining HTML command --> special buffer
			sethtmlcommandbody = sethtmlcommandbody + line  + '\n'									
		elif (buffervar != "") and (string.strip(line) != '-CUT-') and (enabled != -1):
			#Outputting to buffer instead
			buffercontent = buffercontent + line + '\n'
		elif (htmlimage == 1) and (string.strip(line) != '-CUT-') and (enabled != -1):
			#Outputting to buffer instead
			htmlimagecontent.append(line)
		elif (string.strip(line) == '-RAWADD-'):
			for l in rawadd:
				outputlines.append(l)				
			rawadd = []
		elif (string.strip(line) != '') and (string.strip(line[0]) != '#') and (string.strip(line) != '-CUT-') and (enabled != -1) and (settexcommand == "") and ((processmode == mode) or (processmode == "all")) and (sethtmlcommand == "") and (do == 1):
			#Output to main output buffer
			outputlines.append(vout + line)
			started = 1
			if envdoc == 0:
				#Add to headerbuffer
				headerbuffer.append(vout + line)
			if debug == 1:
				print "OUT:	" + line
			
				
		
		
		

				
	#Analyze the latest new line before printing
	if (doheaders == 1) and (mode == "latex"):
		if (envdoc == 0):
			outputlines.insert(0,"\documentclass[12pt]{article}\n\\usepackage{hyperref}\n\usepackage{graphicx}\n\usepackage{placeins}\n\\begin{document}\n")
		elif (envdoc == 1): 
			outputlines.append("\end{document}")
	elif (doheaders == 1) and (mode == "html"):
		if (envdoc == 0):
			outputlines.insert(0,"<HTML><BODY><FONT FACE=" + getvar("htmlfontface") + " SIZE=" + getvar("htmlfontsize") + " COLOR=" + getvar("htmlfontcolor") + ">")
		elif (htmlwrap == 0):
			outputlines.insert(0,"<HTML>")
		if (envdoc == 1): 
			outputlines.append("</FONT></BODY></HTML>")
		if (envdoc == -1): 
			outputlines.append("</HTML>")	
	
		
	return outputlines


		
	


#------------------------------------------------------------------------------
#---------------------INITIALIZATION OF VARIABLES/CONSTANTS--------------------
#------------------------------------------------------------------------------

enabled = 1
detectpspdf = 0
envchapter=-1
envsection=-1
envsubsection=-1
doctype=0
envdoc=0
envtabular=0
envitemize=0
envenumerate=0
envmath=0
started=0
debug=0
htmlwrap = 0


commands = []
symbols = []
markers = []
variables = []



COMMANDNAME = 0
COMMANDARGS = 1
TEXBODY = 2
HTMLBODY = 3

SYMBOLNAME = 0 
TEXSYMBOL = 1
HTMLSYMBOL = 2
REQUIREENV = 3

MARKER=0
TEXBEGIN=1
TEXEND=2
HTMLBEGIN=3
HTMLEND=4

VARNAME=0
VARVALUE=1

tabulardelay = ""
settexcommand = ""
settexcommandbody = ""
sethtmlcommand = ""
sethtmlcommandbody = ""

conditionresult = []
for i in range(100):
	conditionresult.append(0)		
conditionlevel = 0
incondition = 0

vspace = 0
vout = ""
buffervar = ""
buffercontent = ""

htmlimage = 0
htmlimagecontent = []
imagenum = 0

currentcolumn = 0
currentrow = 0
closemulticol = 0
firsthtmlcelloptions = ""

headerbuffer = []

rawadd = []

setvar("htmlfontsize","3")
setvar("htmlfontface","times")
setvar("htmlfontcolor","black")
setvar("babel","")
setvar("title","")
setvar("author","")
setvar("date","")
setvar("css","")
setvar("keywords","")
setvar("description","")
setvar("htmlimagetype",".jpg")
setvar("envitemize","false")
setvar("envtabular","false")
setvar("envenumerate","false")
setvar("quotecss","")
setvar("quotationcss","")
setvar("versecss","")
setvar("sansserifcss","")
setvar("serifcss","")
setvar("fixedcss","")
setvar("colorcss","")
setvar("highlightcss","")
setvar("htmlimageheader","\usepackage{hyperref}\usepackage{placeins}\usepackage{graphicx}\usepackage{unicodefonts}")
setvar("tableborder","1")
setvar("htmltablewidth","")
setvar("column1align","l")
setvar("column2align","l")
setvar("column3align","l")
setvar("column4align","l")
setvar("column5align","l")
setvar("column6align","l")
setvar("column7align","l")
setvar("column8align","l")
setvar("column9align","l")
setvar("column1htmlwidth","")
setvar("column2htmlwidth","")
setvar("column3htmlwidth","")
setvar("column4htmlwidth","")
setvar("column5htmlwidth","")
setvar("column6htmlwidth","")
setvar("column7htmlwidth","")
setvar("column8htmlwidth","")
setvar("column9htmlwidth","")
setvar("column1exactwidth","")
setvar("column2exactwidth","")
setvar("column3exactwidth","")
setvar("column4exactwidth","")
setvar("column5exactwidth","")
setvar("column6exactwidth","")
setvar("column7exactwidth","")
setvar("column8exactwidth","")
setvar("column9exactwidth","")
setvar("column1border","single") #single, double, none
setvar("column2border","single")
setvar("column3border","single")
setvar("column4border","single")
setvar("column5border","single")
setvar("column6border","single")
setvar("column7border","single")
setvar("column8border","single")
setvar("column9border","single")
setvar("column1css","")
setvar("column2css","")
setvar("column3css","")
setvar("column4css","")
setvar("column5css","")
setvar("column6css","")
setvar("column7css","")
setvar("column8css","")
setvar("column9css","")
setvar("column1span","1")
setvar("column2span","1")
setvar("column3span","1")
setvar("column4span","1")
setvar("column5span","1")
setvar("column6span","1")
setvar("column7span","1")
setvar("column8span","1")
setvar("column9span","1")
setvar("column1color","")
setvar("column2color","")
setvar("column3color","")
setvar("column4color","")
setvar("column5color","")
setvar("column6color","")
setvar("column7color","")
setvar("column8color","")
setvar("column9color","")
setvar("column1textcolor","")
setvar("column2textcolor","")
setvar("column3textcolor","")
setvar("column4textcolor","")
setvar("column5textcolor","")
setvar("column6textcolor","")
setvar("column7textcolor","")
setvar("column8textcolor","")
setvar("column9textcolor","")
setvar("column1textrgb_latex","")
setvar("column2textrgb_latex","")
setvar("column3textrgb_latex","")
setvar("column4textrgb_latex","")
setvar("column5textrgb_latex","")
setvar("column6textrgb_latex","")
setvar("column7textrgb_latex","")
setvar("column8textrgb_latex","")
setvar("column9textrgb_latex","")
setvar("column1textrgb_html","")
setvar("column2textrgb_html","")
setvar("column3textrgb_html","")
setvar("column4textrgb_html","")
setvar("column5textrgb_html","")
setvar("column6textrgb_html","")
setvar("column7textrgb_html","")
setvar("column8textrgb_html","")
setvar("column9textrgb_html","")
setvar("column1rgb_html","")
setvar("column2rgb_html","")
setvar("column3rgb_html","")
setvar("column4rgb_html","")
setvar("column5rgb_html","")
setvar("column6rgb_html","")
setvar("column7rgb_html","")
setvar("column8rgb_html","")
setvar("column9rgb_html","")
setvar("column1rgb_latex","")
setvar("column2rgb_latex","")
setvar("column3rgb_latex","")
setvar("column4rgb_latex","")
setvar("column5rgb_latex","")
setvar("column6rgb_latex","")
setvar("column7rgb_latex","")
setvar("column8rgb_latex","")
setvar("column9rgb_latex","")
setvar("column1fill","1")
setvar("column2fill","1")
setvar("column3fill","1")
setvar("column4fill","1")
setvar("column5fill","1")
setvar("column6fill","1")
setvar("column7fill","1")
setvar("column8fill","1")
setvar("column9fill","1")
setvar("columnindent","true")
setvar("rowcolor","")
setvar("rowtextcolor","")
setvar("rowrgb_latex","")
setvar("rowtextrgb_latex","")
setvar("rowrgb_html","")
setvar("rowtextrgb_html","")
setvar("tabularenv","longtable")
setvar("htmlcelloptions","")
setvar("multicolalign","c")
setvar("highlightbackcolor","yellow")
setvar("highlighttextcolor","red")



#------------------------------------------------------------------------------
#---------------------MAIN PROGRAM STARTS HERE--------------------------------
#------------------------------------------------------------------------------


try:
	filename = sys.argv[1]
except: 
	print "Usage: rapidtex sourcefile"
	sys.exit(1)

try:
	mode = sys.argv[2]
except: 
	mode = "latex"

processmode = "all"	
	
try:
	outputfile = sys.argv[4]
except: 
	outputfile = ""	
		


	
try:
	debugmode = sys.argv[3]
	if debugmode == "debug":
		debug = 1
except: 
	debug = 0 

#Read lines
f = open(filename ,"r")
lines = f.readlines()
f.close()


for incl in defaultinclude:
	lines.insert(0,"\\include " + incl + "\n")


lines = rapidtex(lines,1)
	
if outputfile != "":
	f = open(outputfile,"w")
	for line in lines:
		f.write(line)
	f.close()
else:		
	for line in lines:
		print line
	




