
def is_opcode(line):
	return line.startswith('#define') and 'OPCODE' not in line

def get_filename_for_op(op):
	return op.split("_")[0]

def get_function_name_for_op(op):
	return "op_{}".format(op)




outfiles = {}
opfilenames = []
opmap = {}
ops = []

f = open("opcodes.h")

for line in f:
	if is_opcode(line):
		tokens = line.split()[1:]
		ops.append(tokens)




headerfile = """
// AUTOGENERATED FILE
// It's not meant to be pretty.

#ifndef __6502_OPFUNCS__
#define __6502_OPFUNCS__

#include "opcodes.h"
#include "opfuncs.c"

typedef void (*instruction)();


$__OP_ARRAYS_DEFS__$

$__OP_NAMES__$

#endif
"""

opfuncheaderfile = open("ops.h", "w+")



# Generated op array information
op_array_defs = """
instruction opfuncs[256] = {
"""

for op in ops:
	opmap[str(int(op[1], 16))] = op[0]




for i in range(256):
	if str(i) in opmap:
		o = opmap[str(i)]
		funcname = get_function_name_for_op(o)
		op_array_defs += "\t&{},\n".format(funcname)
	else:
		op_array_defs += "\t&op_NOP,\n"

op_array_defs += "};"
	


op_names_defs = """
const char *opnames[256] = {
"""

for op in ops:
	opmap[str(int(op[1], 16))] = op[0]




for i in range(256):
	if str(i) in opmap:
		o = opmap[str(i)]
		op_names_defs += "\t\"{}\",\n".format(o)
	else:
		op_names_defs += "\t\"NOP\",\n"

op_names_defs += "};"

headerfile = headerfile.replace("$__OP_ARRAYS_DEFS__$", op_array_defs)
headerfile = headerfile.replace("$__OP_NAMES__$", op_names_defs)


opfuncheaderfile.write(headerfile)

