import sys

def extract_strings_from_exe(file_path, start_offset, end_offset):
    with open(file_path, 'rb') as f:
        f.seek(start_offset)
        data = f.read(end_offset - start_offset)
        strings = []
        current_string = []
        for byte in data:
            if byte == 0:
                if current_string:
                    strings.append(''.join(current_string))
                current_string = []
            else:
                current_string.append(chr(byte))
        return strings

def insert_strings_into_exe(file_path, strings, start_offset, end_offset):
    with open(file_path, 'r+b') as f:
        f.seek(start_offset)
        data = f.read(end_offset - start_offset)
        parts = data.split(b'\x00')
        for i in range(min(len(parts), len(strings))):
            original_length = len(parts[i])
            new_string = strings[i].replace('/n', '\x0A').replace('/r', '\x0D').encode('CP852')
            new_string_length = len(new_string)
            if new_string_length > original_length:
                print(f"Warning: The string '{strings[i]}' is too long by {new_string_length - original_length} bytes and will be truncated.")
                new_string = new_string[:original_length]
            parts[i] = new_string.ljust(original_length, b'\x00')
        new_data = b'\x00'.join(parts)
        f.seek(start_offset)
        f.write(new_data)

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python insert_strings.py <path_to_exe> <path_to_txt>")
        sys.exit(1)

    file_path = sys.argv[1]
    txt_path = sys.argv[2]

    ranges = [(0xa872, 0xa944, 4), (0xaa77, 0xaa7c, 1), (0xaa8f, 0xaa96, 1), (0xaaa9, 0xaab3, 1), (0xaac6, 0xaaf5, 5), (0xab09, 0xabe1, 9), (0xac76, 0xaf73, 1), (0xb51f, 0xb52e, 1), (0xb541, 0xb57a, 3), (0xe9a6, 0xefe8, 141), (0xf124, 0xf7fe, 20)]

    with open(txt_path, 'r', encoding='CP852') as f:
        strings = [line.rstrip('\n') for line in f]

    start_index = 0
    for start, end, num_lines in ranges:
        range_strings = strings[start_index:start_index + num_lines]
        if len(range_strings) != num_lines:
            print(f"Warning: Expected {num_lines} strings for range {start}-{end}, but got {len(range_strings)}.")
        insert_strings_into_exe(file_path, range_strings, start, end)
        start_index += num_lines

    print(f"Strings from {txt_path} have been inserted into {file_path}.")