#!/usr/bin/env python3

import os, os.path
import sys

from typing import *

def eprint(s: str):
    sys.stderr.write(s if isinstance(s, str) else str(s))
    sys.stderr.write('\n')

def writebinat(dest: bytearray, src: bytes, off: int):
    for i in range(0, len(src)): dest[off + i] = src[i]

def calcsum(data: bytearray, start: int, end: int) -> int:
    r = 0
    for i in range(start, end+1):
        r = r - data[i]
        r = (r - 0x19) & 0xFF

    return r

def shred(data: bytearray) -> bytearray:
    while data[-1] == 0: del data[-1]

    return data

def assert_ok(data: bytearray) -> bytearray:
    assert data[0xB2] == 0x96

    if len(data) > 0x100:
        eprint("len is " + str(len(data)) + ", above 256b!")
    else:
        eprint("size ok: " + str(len(data)))

data = bytearray(sys.stdin.buffer.read())
imghdr = open('./nintendo.bin', 'rb').read()

writebinat(data, imghdr, 0x04)
data[0xBD] = calcsum(data, 0xA0, 0xBC)
data = shred(data)

assert_ok(data)
sys.stdout.buffer.write(data)

