import os
import sys

def write_ins(f, ins_list):
    """Write 24-bit instructions to the file in Big Endian format."""
    for ins in ins_list:
        f.write(bytes([(ins >> 16) & 0xFF, (ins >> 8) & 0xFF, ins & 0xFF]))

def gen_isa_test_rom():
    """Generates a test ROM with various ADSP-219x instruction types."""
    # Use path relative to the script's location
    base_dir = os.path.dirname(os.path.abspath(__file__))
    rom_p = os.path.join(base_dir, "test_roms", "isa_test.bin")
    
    os.makedirs(os.path.dirname(rom_p), exist_ok=True)
    
    instructions = [
        0x000000, 0x000215, 0xC00000, 0xCC9A55, 0x801234, 0x815678, 0x606800, 
        0x412340, 0x4ABCDD, 0x511110, 0x344440, 0x226810, 0x206800, 0x18100F, 
        0x1A2000, (0x1C1234 << 4), 0x16610F, 0x124000, 0x128010, 0x0F0050, 
        0x0EE000, 0x0D4400, 0x0C0001, 0x0C1000, 0x0B000F, 0x0A000F, 0x0A800F, 
        0x018000, 0x010100, 0x07E340, 0x120000, 0x038000, 0x03F000, 0x030000, 
        0x040010, 0x081050, 0x150040, 0x06D100, 0x06C200, 0x06000F, 0x123456, 0x077001
    ]
    
    try:
        with open(rom_p, "wb") as f:
            write_ins(f, instructions)
        print(f"Generated ISA test ROM with {len(instructions)} instructions at: {rom_p}")
    except OSError as e:
        print(f"Error writing ROM file: {e}", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    gen_isa_test_rom()
