import sys
import os

def read_dat_file(filename):
    with open(filename, "rb") as f:
        data = f.read()

    if len(data) < 2:
        print("The file is too small or empty.")
        return []

    first_offset = int.from_bytes(data[0:2], 'little')
    if first_offset == 0 or first_offset > len(data):
        print("Invalid first offset.")
        return []

    count = first_offset // 2
    offsets = [int.from_bytes(data[i*2:i*2+2], 'little') for i in range(count)]

    strings = []
    for offset in offsets:
        if offset == 0:
            strings.append("")
            continue

        # Read until the first null byte
        end = data.find(b'\x00', offset)
        if end == -1:
            end = len(data)

        raw_bytes = data[offset:end]
        try:
            strings.append(raw_bytes.decode("windows-1251"))
        except UnicodeDecodeError:
            strings.append(raw_bytes.decode("latin1"))

    return strings

def save_strings(strings, base_filename):
    txt_filename = os.path.splitext(base_filename)[0] + ".txt"
    with open(txt_filename, "w", encoding="utf-8") as f:
        for line in strings:
            f.write(line + "\n")
    print(f"Saved to: {txt_filename}")

def main():
    if len(sys.argv) != 2:
        print("Usage: python script.py <file.dat>")
        return

    filename = sys.argv[1]
    if not os.path.isfile(filename):
        print(f"File not found: {filename}")
        return

    strings = read_dat_file(filename)
    save_strings(strings, filename)

if __name__ == "__main__":
    main()