#!/usr/bin/env python3
"""Flatten a Motorola S-record file into a raw binary, reporting coverage."""
import sys

def main(path, out=None):
    chunks = {}
    header = None
    with open(path, "rb") as f:
        for lineno, raw in enumerate(f, 1):
            line = raw.strip()
            if not line:
                continue
            if line[0:1] != b"S":
                raise SystemExit(f"{path}:{lineno}: not an S-record")
            rtype = line[1:2]
            count = int(line[2:4], 16)
            body = bytes.fromhex(line[4:4 + 2 * count].decode())
            data, csum = body[:-1], body[-1]
            if (~sum(bytes.fromhex(line[2:4].decode()) + data + bytes([0])) + 0) & 0xff != csum:
                if (0xff - (sum(body[:-1]) + count) & 0xff) != csum:
                    raise SystemExit(f"{path}:{lineno}: checksum mismatch")
            if rtype == b"0":
                header = data[2:].rstrip(b"\x00")
            elif rtype in (b"1", b"2", b"3"):
                alen = {b"1": 2, b"2": 3, b"3": 4}[rtype]
                addr = int.from_bytes(data[:alen], "big")
                chunks[addr] = data[alen:]
            elif rtype in (b"7", b"8", b"9"):
                pass  # start address record
            else:
                raise SystemExit(f"{path}:{lineno}: unhandled S{rtype.decode()}")
    lo = min(chunks)
    hi = max(a + len(d) for a, d in chunks.items())
    img = bytearray(b"\xff" * (hi - lo))
    covered = 0
    for a, d in sorted(chunks.items()):
        img[a - lo:a - lo + len(d)] = d
        covered += len(d)
    print(f"{path}")
    print(f"  header     : {header!r}")
    print(f"  range      : 0x{lo:08x} - 0x{hi - 1:08x}  ({hi - lo} bytes)")
    print(f"  covered    : {covered} bytes  gaps: {hi - lo - covered}")
    if out:
        with open(out, "wb") as f:
            f.write(img)
        print(f"  wrote      : {out}")

if __name__ == "__main__":
    main(*sys.argv[1:])
