import sys
import os.path
import re

# file_start_string = "#ifndef __HMC_CONFIG_H_\n" \
# 	"#define __HMC_CONFIG_H_\n\n" \
# 	"struct reg_t {\n" \
# 	"\tuint16_t reg_addr;\n" \
# 	"\tuint8_t reg_val;\n" \
# 	"};\n\n" \
# 	"struct reg_t hmc7044_configuration[] = {\n";

# file_end_string = "};\n\n#endif\n";

file_start_string = "#include <stdint.h>\n" \
	"\nstruct reg_t {\n" \
	"\tuint16_t reg_addr;\n" \
	"\tuint8_t reg_val;\n" \
	"};\n\n" \
	"struct reg_t hmc7044_configuration[] = {\n";

file_end_string = "};\n\n";

rd_only_regs = [
0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 
0x007d, 0x007e, 0x007f, 0x0082, 0x0083,
0x0084, 0x0085, 0x0086, 0x0087, 0x008c,
0x008c, 0x008d, 0x008e, 0x008f, 0x0090,
0x0091, 0x0096, 0x0097, 0x0098, 0x0099, 
0x009a, 0x009b, 0x009c, 0x009d, 0x009e, 
0x00a1, 0x00a2, 0x00a3, 0x00a4, 0x00a6, 
0x00a7, 0x00a9, 0x00aa, 0x00ab, 0x00ac, 
0x00ad, 0x00ae, 0x00af, 0x00b1, 0x00b2, 
0x00b3, 0x00b4, 0x00b5, 0x00b6, 0x00b7, 
0x00b8];

# Check whether there are 3 argumets
# script name, input file and output file
if len(sys.argv) > 3:
	print("Too many arguments!\n"); 
	exit();

if len(sys.argv) < 3:
	print("Not enough arguments!\n"); 
	exit();

# Get file names
infname = sys.argv[1];
outfname = sys.argv[2];
print("Input file: ", infname);
print("Output file: ", outfname);

# Check whether input file exists and
# Open output file
if not os.path.isfile(".\\" + infname):
	print("File .\\", infname, " doesn't exists\n");
	exit();
outfile = open(".\\" + outfname, 'w');

cnt = 0;

# Open file and find lines starting with "dut"
# Then from these lines extract register address 
# and values and store them into c structure
with open("./" + infname, 'r') as infile:
	lines = infile.readlines();
	outfile.write(file_start_string);
	for line in lines:
		if line.startswith("dut"):
			values = re.findall('0x[0-9A-F]+', line, re.I);
			addr = values[0];
			val = values[1];
			if int(addr, base=16) not in rd_only_regs:
				cnt += 1;
				outfile.write("\t{" + values[0] + "\t, " + values[1] + "\t},\n");
			# else:
				# print("Read only register " + addr + "\n");

	outfile.write(file_end_string);
	outfile.write("int hmc7044_configuration_regs_cnt = " + str(cnt) + ";\n\n");
