#!/usr/bin/env python

# Cleverly run Mathematica with the benefit of readline, which
# is something the usual commercial mathematica doesn't provide!
# See
#    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/363500

import sys, signal, subprocess
import readline
from six.moves import input

def child_exited(*args):
    global child
    status = child.poll()
    if status is not None:
        sys.exit(status)

signal.signal(signal.SIGCHLD, child_exited)

child = subprocess.Popen('math', shell=True, stdin=subprocess.PIPE)
pipe = child.stdin
while True:
    try:
        line = input()
        pipe.write(line + '\n')
        pipe.flush()
    except KeyboardInterrupt:
        pipe.close()
    except EOFError:
        break
sys.stdout.write('\n')
