import subprocess
import os

NAR_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'NAR')

def spawnNAR():
    p = subprocess.Popen([NAR_PATH, 'shell'],
        stdin=subprocess.PIPE, stdout=subprocess.PIPE,
        stderr=subprocess.PIPE, universal_newlines=True)
    return p

def GetRawOutput(proc):
    proc.stdin.write('0\n')
    proc.stdin.flush()
    lines = []
    while True:
        line = proc.stdout.readline().strip()
        if 'done with 0 additional inference steps.' == line:
            break
        if line:
            lines.append(line)
    return lines

def AddInput(proc, narsese):
    proc.stdin.write(narsese + '\n')
    proc.stdin.flush()
    return GetRawOutput(proc)

def CycleSteps(proc, n):
    proc.stdin.write(str(n) + '\n')
    proc.stdin.flush()
    ret = []
    while True:
        line = proc.stdout.readline().strip()
        if line.startswith('done with') and 'additional inference steps' in line:
            break
        if line:
            ret.append(line)
    return ret
