#!/usr/bin/env python3

# parameters
# 1 - output filename for combined data file
# 2,3 - input filename, output index record filename
# 4,5 - ""
# 6,7... in pairs

import os.path
import sys

if __name__ == "__main__":
    output_file = sys.argv[1]
    offset = os.path.getsize(output_file)
    data = []
    index_records = []
    # read and aggregate all input files, and generate index records
    for input_file in sys.argv[2::2]:
        with open(input_file, 'rb') as input_handle:
            data.append(input_handle.read())
        size = len(data[-1])
        index_records.append(f""";
; Index record for {input_file}
;
; This file is automatically generated
;
         !byte 0
         !be24 {offset:>9}
         !le16 {size:>8}
""")
        offset += size

    # write out index records to specified files
    for index_file, record in zip(sys.argv[3::2], index_records):
        with open(index_file, 'w') as index_handle:
            index_handle.write(record)

    # write out combined data
    with open(output_file, 'ab') as output_handle:
        output_handle.write(b''.join(data))
