import os
import struct
from PIL import Image

# Path to folder with files
folder_path = 'images/CAFE/h'
palette_path = os.path.join(folder_path, 'cafe.pal')

# Read palette
def read_palette(palette_path):
    with open(palette_path, 'rb') as f:
        data = f.read()
    return [tuple(data[i:i+3]) for i in range(0, len(data), 3)]

# Decode a single RLE file
def decode_rle_image(rle_path, palette):
    with open(rle_path, 'rb') as f:
        width, height = struct.unpack('<HH', f.read(4))
        file_size = struct.unpack('<H', f.read(2))[0]

        image = Image.new('RGB', (width, height))
        pixels = image.load()

        for y in range(height):
            black_count = struct.unpack('<B', f.read(1))[0]
            color_count = struct.unpack('<B', f.read(1))[0]
            color_indices = list(f.read(color_count))

            x = 0
            for _ in range(black_count):
                pixels[x, y] = (0, 0, 0)
                x += 1
            for idx in color_indices:
                pixels[x, y] = palette[idx]
                x += 1
            while x < width:
                pixels[x, y] = (0, 0, 0)
                x += 1

    return image

# Main processing
palette = read_palette(palette_path)
converted_files = []

for filename in os.listdir(folder_path):
    if filename.lower().endswith('.dbe'):
        rle_path = os.path.join(folder_path, filename)
        output_path = os.path.join(folder_path, filename + '.png')
        image = decode_rle_image(rle_path, palette)
        image.save(output_path)
        converted_files.append(output_path)

print("Decoded files:")
for f in converted_files:
    print(f)