#!/usr/local/bin/python
# $Id: loutwr.py,v 1.2 1997/05/22 19:40:08 connolly Exp $
#

import regex

BOL='\n'
INDENT='    '
LB = '{'
RB = '}'

spaceDFA = regex.compile('[ \t\n]+')
nospaceDFA = regex.compile('[^ \t\n"\\]+')
wordsDFA = regex.compile('[^/|&{}#@^~\\\"\n\t]+')

class T:
    def __init__(self, target):
	self.t = target
	self.q = 0
	self.bol = 1

    def newline(self):
	if not self.bol:
	    self.t.write("\n")
	    self.bol = 1

    def unq(self):
	if self.q:
	    self.t.write('"')
	    self.q = 0
	    self.bol = 0

    def sym(self, sym):
	"""assumes sym is a lout symbol in the current context"""
	#@# should keep track of whether we just wrote a space or not!
	self.unq()
	if not self.bol: self.t.write(' ')
	self.t.write(sym + ' ')
	self.bol = 0

    def char(self, c):
	self.unq()
	self.t.write(c)
	self.bol = 0

    def do(self, item):
	if item is BOL:
	    self.newline()
	elif item is INDENT:
	    if not self.bol: raise ValueError, 'must be at BOL to indent'
	    self.t.write(INDENT)
	    self.bol = 0
	elif item is LB or item is RB:
	    self.sym(item)
	else:
	    #@# could check that this is a symbol
	    self.sym(item)

    def text(self, txt):
	while len(txt) > 0:
	    if self.q:
		i = nospaceDFA.match(txt)
		if i > 0:
		    self.t.write(txt[:i])
		    txt = txt[i:]
		    self.bol = 0
		else:
		    i = spaceDFA.match(txt)
		    if i > 0:
			spc = txt[:i]
			if "\n" in spc:
			    self.t.write('"\n')
			    self.bol = 1
			else:
			    self.t.write('" ')
			    self.bol = 0
			self.q = 0
		    else:
			self.t.write('\\' + txt[0])
			self.bol = 0
			txt = txt[1:]
	    else:
		if self.bol and spaceDFA.match(txt) > 0:
		    txt = txt[spaceDFA.regs[0][1]:]
		elif wordsDFA.match(txt) > 0:
		    i = wordsDFA.regs[0][1]
		    self.t.write(txt[:i])
		    txt = txt[i:]
		    self.bol = 0
		elif txt[0] == "\n":
		    if not self.bol: self.t.write("\n")
		    self.bol = 1
		    txt = txt[1:]
		elif txt[0] == "\t":
		    self.t.write(' ') #@# compress spaces?
		    self.bol = 0
		    txt = txt[1:]
		else:
		    self.t.write('"')
		    self.bol = 0
		    self.q = 1

if __name__ == '__main__':
    import sys
    l = T(sys.stdout)
    l.text(sys.stdin.read())
