#!/bin/python
# 
# Experimental converter from Hex-Intel to TMS7000 format. 
# version 0.9
# fjkraan@electrickery.nl 2026-01-27

import sys

if len(sys.argv) == 1:
   print("Usage: python hexIntel2t7kDump.py <HexIntelFile>")
   exit()
if len(sys.argv) > 1:
    hexFile = sys.argv[1]

address = 0
nextAddress = -1
twoByteBlockTag = 'B'
oneByteBlockTag = '*'
checksumTag = '7'
endTag = 'F'
byteCount = 0
sumChk = 0

def format2Hex(value):
    return "{:02X}".format(value)

def format4Hex(value):
    return "{:04X}".format(value)
    
def asciiSum(line):
    sum = 0
    for char in line:
        if char >= ' ' and char <= '~':
#            print(char, end='')
            sum += ord(char)
#        else:
#            print("'"+char+"'")
#    print()
    return sum % 0x10000

def processDataBlocks(hexData):
#    print("pdb: " + hexData)
    t7kLine = ''
    prefix = ''
    procLine = hexData
    while procLine:
        procLineLen = len(procLine)
        if procLineLen > 2:
            data = procLine[0:4]
            procLine = procLine[4:]
            prefix = twoByteBlockTag
        else:
            data = procLine[0:2]
            procLine = procLine[2:]
            prefix = oneByteBlockTag
        t7kLine = t7kLine + prefix + data
#        print("pdb: " + procLine + " / " + t7kLine + " len: " + format2Hex(procLineLen))
    return t7kLine

def processHexIntelLine(line):
    global address
    global nextAddress
    addressBlock = ''
    dataBlocks = ''
    if line[0] != ':':
        next
    dataSize = int(line[1:3], 16)
    calcAddress = address + dataSize
#    print("> '" + line[1:3] + "' " + hex(dataSize) + "  na: " + format4Hex(nextAddress) + ", a+d: " + format4Hex(calcAddress))
    address = int(line[3:7], 16)
    if nextAddress != (calcAddress):
        addressBlock = '9' + line[3:7]
    else:
        addressBlock = ''
    nextAddress = address + dataSize
    recordType = line[7:9]  # not used, but illustrated record structure, could check for '00'
    dataBlocks += processDataBlocks(line[9:-2])
#    hiCheckSum = line[-2:]
#    print("hic: " + hiCheckSum)
    noChecksumBlock = addressBlock + dataBlocks
    t7kCalcSum = 0x10000 - asciiSum(checksumTag + noChecksumBlock) % 0x10000
    t7kDumpLine = noChecksumBlock + checksumTag + format4Hex(t7kCalcSum) + endTag
    return t7kDumpLine


file = open(hexFile, 'r')
lines = file.readlines()
file.close()

print("K0000PROGRAM ", end='')

for line in lines:
    lineStrip = line.strip()
    if len(lineStrip) == 0:
        break
#    print (lineStrip)
    recType = lineStrip[7:9]
    if recType == '01':
#        print("Done.")
        break
    t7kDumpLine = processHexIntelLine(lineStrip)
#    print("t7kdl: " + t7kDumpLine)
#    print()
    print(t7kDumpLine)



# hex-intel
# :ccaaaatthhhhhhhh....hhhhss
# ss = binary two's complement of cc, tt, aaaa, hh..hh
# tt = 00 for data, 01 for end record
