#!/usr/bin/python

from fontforge import font as ff_font
from fontforge import open as ff_open
from psMat import scale


def read_glyphs(handle):
    return [handle.read(8) for _ in range(512)]


def read_mapping(handle):
    handle.seek(0x0a92)
    return handle.read(256)


def draw_pixel(pen, x, y):
    width = 5
    height = 8
    pen.moveTo((width * x, height * (6 - y)))
    pen.lineTo((width * (x + 1), height * (6 - y)))
    pen.lineTo((width * (x + 1), height * (5 - y)))
    pen.lineTo((width * x, height * (5 - y)))
    pen.closePath()


def make_character(font, code, glyph):
    char = font.createChar(code)
    char.width = 5

    pen = char.glyphPen()
    for y in range(8):
        for x in range(8):
            if glyph[y] & (1 << x):
                draw_pixel(pen, x, y)


def make_font(cgrom_handle, monitor_handle, ttf_file):
    font = ff_open("/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf")
    font.fontname = 'SharpMZ'
    font.familyname = 'SharpMZ'
    font.fullname = 'SharpMZ'
    font.em = 64
    font.ascent = 34

    glyphs = read_glyphs(cgrom_handle)
    mapping = read_mapping(monitor_handle)

    # Normal charset.
    offset = 0xe000
    for code in range(0x100):
        make_character(font, offset + code, glyphs[mapping[code]])

    # Alternate charset.
    offset = 0xe100
    for code in range(0x100):
        make_character(font, offset + code, glyphs[0x100 + mapping[code]])

    # Normal charset without control characters.
    offset = 0xe200
    for code in range(0x100):
        make_character(font, offset + code, glyphs[code])

    # Alternate charset without control characters.
    offset = 0xe300
    for code in range(0x100):
        make_character(font, offset + code, glyphs[0x100 + code])

    font.generate(ttf_file)
