#!/usr/bin/env ruby

require 'RMagick'

FONT_HEIGHT=12

def redden_image(img)
    greyscale = img.quantize(256, Magick::GRAYColorspace)
    red_image = greyscale.colorize(0.0, 1.0, 1.0, "red")
end


def load_font
    $chars = {}

    for i in 0..127
        filename = sprintf("font/free/font%03i.png", i)

        if File.exists?(filename)
            img = Magick::Image::read(filename).first
            img = redden_image(img)

            $chars[i] = img
        end
    end
end

def text_width(str)
    result = 0

    str.upcase.each_byte do |c|
        if $chars[c] != nil
            result += $chars[c].columns - 1
        end
    end

    result + 1
end

def gen_text(str)

    if $chars == nil
        load_font
    end

    result = Magick::Image.new(text_width(str), FONT_HEIGHT)

    drawobj = Magick::Draw.new
    x = 0

    drawobj.fill("#00ffff")

    drawobj.rectangle(0, 0, result.columns, result.rows)
    str.upcase.each_byte do |c|
        if $chars[c] != nil
            drawobj.composite(x, 0, 0, 0, $chars[c])
            x += $chars[c].columns - 1
            drawobj.rectangle(x + 1, 0, result.columns, result.rows)
        end
    end

    drawobj.draw(result)

    result
end

