Unpack given Motorola S-Record record into variables.

def unpack_srec(record):
    """Unpack given Motorola S-Record record into variables.

    """

    # Minimum STSSCC, where T is type, SS is size and CC is crc.
    if len(record) < 6:
        raise Error("record '{}' too short".format(record))

    if record[0] != 'S':
        raise Error(
            "record '{}' not starting with an 'S'".format(record))

    size = int(record[2:4], 16)
    type_ = record[1:2]

    if type_ in '0159':
        width = 4
    elif type_ in '268':
        width = 6
    elif type_ in '37':
        width = 8
    else:
        raise Error(
            "expected record type 0..3 or 5..9, but got '{}'".format(type_))

    data_offset = (4 + width)
    crc_offset = (4 + 2 * size - 2)

    address = int(record[4:data_offset], 16)
    data = binascii.unhexlify(record[data_offset:crc_offset])
    actual_crc = int(record[crc_offset:], 16)
    expected_crc = crc_srec(record[2:crc_offset])

    if actual_crc != expected_crc:
        raise Error(
            "expected crc '{:02X}' in record {}, but got '{:02X}'".format(
                expected_crc,
                record,
                actual_crc))

    return (type_, address, size - 1 - width // 2, data)