"""
blisp   -  The best lisp implementation in the world!
by Brendan O'Connor

This file, main.py, is the big mish-mash of stuff that hasn't been
modularized yet.  It's what you run to start the interpreter.

"""
from __future__ import generators
from Parser import ParseString, ParenCount
from lisp_excs import *
from debug import dbgs


######################################

import interpreter

def ProcessString(s):
    eval_lisparg  = ParseString( "%s" %s )
    print>>dbgs, "Processing: ",eval_lisparg
    eval_lispargs = [eval_lisparg]
    return interpreter.the_interper.builtin_functions['eval'].Call( eval_lispargs )

def Unparse(ls):
    if isinstance(ls, str): return ls
    if not isinstance(ls, list): return repr(ls)
    if len(ls) >= 2 and ls[0] == 'quote':
        return "'" + Unparse(ls[1])
    ret = ['(']
    for elem in ls:
        ret += Unparse(elem)
        ret += [' ']
    ret.pop() #kills the last space
    ret += [')']
    return str.join('', ret)

def IILoop():
    "Interactive Interpreter loop"

    import traceback
    try: import readline
    except ImportError: pass

    print """
This is blisp.
               
By Brendan O'Connor.  Positively the best LISP ever!
'q' to quit."""
    while 1:
        s = raw_input("*** blisp :-)  ")
        
        if s == "" or s[0] == ";": continue
        if s == 'q': return

        while ParenCount(s) > 0:
            s += '\n' + raw_input("......... :-P  ")
            
        try:
            print Unparse(ProcessString(s))
        except LispException:
            print "Oops, a Lisp error! Here's the Python traceback:"
            traceback.print_exc()
        except:
            print "Interpreter error!"
            traceback.print_exc()
            
            

if __name__=='__main__':
    interpreter.init()
    interpreter.readopts()
    IILoop()                      

