#!/usr/bin/python

import os
import sys
import tty
import termios

KEYCODE_ESC = 27
SPACE = ord(' ')
KEYCODE_LBRACKET = ord('[')
PRINTABLE_CHARS = map(lambda x: chr(ord(' ')+x), range(95))




old = termios.tcgetattr(sys.stdin)
tty.setcbreak(sys.stdin)

# Initialize state machine
state = 0
input = 0
output = ''

outfd = None
if os.environ.has_key('RAWREAD_OUT'):
    outfd = open(os.environ['RAWREAD_OUT'], 'w')

# Run the state machine
while True:
    input = sys.stdin.read(1)

    #print ord(input)

    if state == 0 :
        if input in PRINTABLE_CHARS:
            sys.stdout.write(input)
            output += input
            state = 0
        if ord(input) == 10:
            sys.stdout.write(input)
            if outfd: 
                outfd.write(output)
                outfd.close()
            output = ''
        elif ord(input) == KEYCODE_ESC:
            state = 1

    elif state == 1:
        if input == '[':
           state = 2

    elif state == 2:
        if input == 'A':
            print 'UP ARROW'
        state = 0

    if(input == 'q'): 
        break

    '''
    if key in PRINTABLE_CHARS:
        if len(state) == 0:
            sys.stdout.write(key)
        state.append(ord(key))
    if ord(key) == KEYCODE_ESC:
        state.append(ord(key))
        continue
    if ord(key) == KEYCODE_LBRACKET:
        state.append(ord(key))
        continue
    if(key == 'q'): 
        break
    code = ord(key)
    '''

termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old)


