Source

pv200_avrcore / fix_hex_file.py

import sys

if len(sys.argv) == 1:
    width = 2
    wordcount = 2048
else:
    width = int(sys.argv[1])
    wordcount = int(sys.argv[2])

mem = [0] * width * wordcount

for lineno, line in enumerate(sys.stdin):
    line = line[1:-1]
    data = [int(line[i:i+2], 16) for i in xrange(0, len(line), 2)]
    
    if data[0] != len(data) - 5:
        print >>sys.stderr, 'Corrupted record on line ', lineno + 1

    if data[3] == 1: # EOF
        break

    if data[3] != 0:
        print >>sys.stderr, 'Unsupported record type (line', lineno + 1, ')'

    address = data[1] * 256 + data[2]
    mem[address:address+data[0]] = data[4:-1]

new_mem = [0] * wordcount
for i in xrange(wordcount):
    val = 0
    for j in reversed(xrange(i*width, i*width+width)):
        val = val * 256 + mem[j]
    new_mem[i] = val

for i, val in enumerate(new_mem):
    chksum = width + i + i // 256
    for j in xrange(width):
        chksum += val // (256**j)
    print ':%0.2X%0.4X00%0.*X%0.2X' % (width, i, 2*width, val, (256 - chksum % 256) % 256)
print ':00000001FF'