#!/usr/bin/env python
import sys
import time
import telnetlib
import string

# For a SYM at 4800 baud on the local network
timewait = 0.02 # NetBSD makes this into a scheduler tick regardless!
timewaitnl = 0.7


def check_printable(message, printable=string.printable):
    return "".join(char for char in message if char in printable)


def read_everything(tn):
    global timewait
    buf = ""
    chrin = tn.read_until(" ",timewait)
    if chrin != '':
        buf = buf + chrin
        sys.stdout.write(check_printable(chrin))
        sys.stdout.flush()
    return buf


def slow_write(tn, outstring):
    readed = ""
    for ch in list(outstring):
        if ch == '\n':
            ch = '\r'
        tn.write(ch)
        time.sleep(timewait)
        if ch == '\r':
            time.sleep(timewaitnl)
        readed = readed + read_everything(tn)
    readed = readed + read_everything(tn)
    return readed


def transmit_records_reliably(linerecords):
    try:
        tn = telnetlib.Telnet("challenger", 2000)
    except:
        exit("telnet: couldn't contact the SYM-1")
    slow_write(tn,'\n\n')
    print "\n***",len(linerecords),"records to transmit"
    linecount = 1

    while len(linerecords) > 0:
        print "\n*** Line", linecount
        rec = linerecords[0]
        r = rec + "\n"
        readed = slow_write(tn,r)
        del linerecords[0]
        linecount = linecount + 1


def read_file(myfile):
    records = []
    inputfile = open(myfile,"r")
    while 1:
        l = inputfile.readline()
        if l == "":             # EOF
            break
        records = records + [l.rstrip()]
    inputfile.close()
    return records


if __name__ == '__main__':
    try:
        if (sys.argv[1] == "-h") or (sys.argv[1] == "--help"):
            print "Usage:\n ./symforthload dumpblkfile\nMake certain FORTH is on, and the line editor loaded"
            exit
        myfile = sys.argv[1]
    except:
        exit("first argument: no file provided (\"-h\" for help)")

    records = read_file(myfile)

    transmit_records_reliably(records)
