from __future__ import print_function, unicode_literals
import sys, io, struct
import scx

def get_raw_text(data, index):
	ptr = struct.unpack_from('<I', data.content, data.strings_table + index * 4)[0]
	begin = ptr
	while data.content[ptr] != 0xFF:
		if data.content[ptr] & 0x80:
			ptr += 2
		elif data.content[ptr] in (4,21):
			ptr = scx.skip_expr(data.content, ptr + 1)
		elif data.content[ptr] in (12,17,18):
			ptr += 3
		else:
			ptr += 1
	return data.content[begin:ptr+1]

data_original = scx.ScxData('script/' + sys.argv[1])
data_translated = scx.ScxData('translated_script/' + sys.argv[1])

if data_original.num_strings() != data_translated.num_strings():
	print("Mismatch in strings count", file=sys.stderr)
	sys.exit(1)

with io.open(sys.argv[2], 'rb') as f:
	strings_table = f.read()
strings_offsets = list(struct.unpack_from('<' + str(struct.unpack_from('<I', strings_table, 0)[0] // 4) + 'I', strings_table))
num_baseline_strings = len(strings_offsets)

already_written = {}
for i in range(data_original.num_strings()):
	original = bytes(get_raw_text(data_original, i))
	translated = bytes(get_raw_text(data_translated, i))
	if original != translated:
		if translated not in already_written:
			already_written[translated] = len(strings_offsets)
			strings_offsets.append(len(strings_table))
			strings_table += translated
		print('        "%d": %d,' % (i, already_written[translated]))

delta = 4 * (len(strings_offsets) - num_baseline_strings)
strings_offsets = [x + delta for x in strings_offsets]

with io.open(sys.argv[3], 'wb') as f:
	f.write(struct.pack('<' + str(len(strings_offsets)) + 'I', *strings_offsets))
	f.write(strings_table[num_baseline_strings*4:])
