#!/usr/bin/env python3

import sys
import struct

MAGIC='MROF'.encode()
FILENAME_LEN=40
HEADER_FMT = "<i"
STRUCT_FMT = "<ii%ds" % FILENAME_LEN

def make_headers(files, contents):
    headers = []

    offset = (len(MAGIC) + struct.calcsize(HEADER_FMT) +
              struct.calcsize(STRUCT_FMT) * len(files))
    for filename, data in zip(files, contents):
        headers += [(offset, len(data), filename.encode())]
        offset += len(data)

    return headers

def output(f, headers, contents):
    f.write(MAGIC)
    f.write(struct.pack(HEADER_FMT, len(headers)))
    for header in headers:
        f.write(struct.pack(STRUCT_FMT, *header))
    for data in contents:
        f.write(data)

def main(args):
    if args[1] == '-o':
        target = args[2]
        files = args[3:]
    else:
        target = None
        files = args[1:]
    files.sort()

    contents = [open(s, "rb").read() for s in files]
    headers = make_headers(files, contents)

    out = open(target, "wb") if target else sys.stdout.buffer
    output(out, headers, contents)
    out.close()

if __name__ == '__main__':
    sys.exit(main(sys.argv))
