#!/bin/python

''''
Script to convert TRS-80 Model 1 Level 2 BASIC to ASCII text

fjkraan@electrickery.nl, 2025-05-04

header:
0xff

per line:
  <AddrLSB> <AddMSBr> <lineNoLSB> <lineNoMSB> .... <0x00>
    (A line consists of ASCII (0x20 - 0x7E) and tokens (0x80 - 0xFF)
    The token table is imported from the token file)

end:
  0x0A

'''

import sys


if len(sys.argv) > 2:
    tokenFile = sys.argv[1]
    basicFile = sys.argv[2]
else:
    print("Usage: python basicTokenDecode.py <tokenFile> <basicFile>)")
    sys.exit()

tokenTable = {}

def printHex(bin):
    print("0x%02x " % bin, end='')
    
def printChar(bin):
    print(bin.decode("utf-8"), end='')

with open(tokenFile, "r") as tf:
    tokenLines = tf.readlines()
    for tokenLine in tokenLines:
#        print(tokenLine.strip());
        splitLine =  tokenLine.strip().split();
        if splitLine[0].startswith("#"):
            continue
        if len(splitLine) > 2 :
#            print(splitLine[0] + " / " + splitLine[2])
            tokenTable[int(splitLine[0], base=16)] = splitLine[2]
            
#    print(tokenTable)
tf.close()

with open(basicFile, "rb") as bf:
    header = ord(bf.read(1))
#    printHex(header)
#    print()
    while (True):
        addrL = ord(bf.read(1))
#        printHex(addrL)
        addrM = ord(bf.read(1))
#        printHex(addrM)
        addr = addrL + addrM * 256
        if addr == 0x00:
            break
#        print("0x%04x " % addr, end='')
        
        lineNoL = ord(bf.read(1))
        lineNoM = ord(bf.read(1))
        lineNo = lineNoL + lineNoM * 256
        print("%5d " % lineNo,end='')
        while (char := bf.read(1)):
            token = ord(char)
            if token == 0x00 or token == 0x0A:
                break
            if token > 0x7F:
                print(tokenTable[ord(char)], end='')
            else:
                printChar(char)
        print()

print()
 
bf.close()
'''

'''
