import sys
import os

def write_dat_file(strings, filename):
    encoded_strings = []
    offsets = []
    current_offset = 2 * len(strings)  # offset table

    for s in strings:
        if s == "":
            encoded_strings.append(b"")  # nothing to add
            offsets.append(0)  # zero offset
        else:
            encoded = s.encode("windows-1251", errors="replace") + b'\x00'
            encoded_strings.append(encoded)
            offsets.append(current_offset)
            current_offset += len(encoded)

    # Build byte data
    data = b''.join(offset.to_bytes(2, 'little') for offset in offsets)
    data += b''.join(encoded_strings)

    with open(filename, "wb") as f:
        f.write(data)
    print(f"File saved as: {filename}")

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

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

    # Read raw bytes, split by 0A0D
    with open(txt_filename, "rb") as f:
        raw_data = f.read()

    split_marker = b'\x0D\x0A'
    raw_lines = raw_data.split(split_marker)

    # Decode each line from UTF-8
    strings = []
    for line in raw_lines:
        try:
            decoded = line.decode("utf-8")
        except UnicodeDecodeError:
            decoded = line.decode("utf-8", errors="replace")
        strings.append(decoded)

    dat_filename = os.path.splitext(txt_filename)[0] + ".raw"
    write_dat_file(strings, dat_filename)

if __name__ == "__main__":
    main()