import os
from PIL import Image, ImageDraw

def parse_vector_font(file_path):
    with open(file_path, "rb") as f:
        data = list(f.read())

    horizontals = []
    verticals = []
    i = 0

    # Horizontal lines (until FF)
    while i + 2 < len(data) and data[i] != 0xFF:
        x1 = data[i]
        x2 = data[i+1]
        y = data[i+2]
        horizontals.append((x1, x2, y))
        i += 3

    if i < len(data) and data[i] == 0xFF:
        i += 1

    # Vertical lines (after FF)
    while i + 2 < len(data):
        x = data[i]
        y1 = data[i+1]
        y2 = data[i+2]
        verticals.append((x, y1, y2))
        i += 3

    # Calculate dimensions
    max_x = max(
        [max(x1, x2) for x1, x2, _ in horizontals] +
        [x for x, _, _ in verticals] +
        [0]
    ) + 1

    max_y = max(
        [y for _, _, y in horizontals] +
        [max(y1, y2) for _, y1, y2 in verticals] +
        [0]
    ) + 1

    img = Image.new("L", (max_x, max_y), 255)
    draw = ImageDraw.Draw(img)

    for x1, x2, y in horizontals:
        draw.line([(x1, y), (x2, y)], fill=0)

    for x, y1, y2 in verticals:
        draw.line([(x, y1), (x, y2)], fill=0)

    return img

def convert_all_vector_fonts(folder_path):
    for filename in os.listdir(folder_path):
        if filename.lower().endswith(".bin"):
            filepath = os.path.join(folder_path, filename)
            image = parse_vector_font(filepath)
            output_path = os.path.join(folder_path, filename[:-4] + ".png")
            image.save(output_path)
            print(f"✅ Saved: {output_path}")

convert_all_vector_fonts(".")