
---- A fast Bitmap font class ----
-------------------------------------------------------------------------------

Font = {
	image = nil,
	hSize = 8, -- horizontal size of a char
	lSpace = 4, -- line spacing
	vPos = {0, 10, 21}, -- vertical positions of the lines
	vSize = {10, 10, 10}, -- vertical size of the lines
	LEFT = nil, CENTER = 1, RIGHT = 2, -- for alignment 
	dest = screen -- where to draw
}

function Font:new(file, tab)
	f = tab or {}
	setmetatable(f, self)
	self.__index = self
	f.image = Image.load(file)
	return f
end

function Font:width(text, start)
	local w
	w = string.find(text, "\n", start)
	if w then w = w-1
	else w = string.len(text) end
	if start then w = w - start + 1 end
	return w * self.hSize
end

function Font:height(text)
	local nl = 1
	for _ in string.gfind(text, "\n") do nl = nl +1 end
	return nl * (self.vSize[1]+ self.lSpace)
end

function Font:setDest(d)
	d = d or screen
	self.dest = d
end

function Font:print(text, x, y, align, color)
	color = color or colors.white
	local ox = x
	if align == self.CENTER then x = ox - self:width(text)/2 end
	
	local d, hm, hs, vp1, vp2, vp3, vs1, vs2, vs3 =
		self.dest, self.hSize, self.hSize,
		self.vPos[1], self.vPos[2], self.vPos[3], 
		self.vSize[1], self.vSize[2], self.vSize[3]
	local istart, iend, istep, b = 1, string.len(text), 1, 0
	
	if align == self.RIGHT then
		hm, istart, iend, istep = -hm, iend, istart, -istep
	end
	
	screen:setTint(color)
	for i=istart, iend, istep do
		b = string.byte(text, i)
		if b >= 97 then
			b = b - 97
			d:blit(x, y+1, self.image, b*hs, vp2, hs, vs2)
		elseif b >= 65 then
			b = b - 65
			d:blit(x, y, self.image, b*hs, vp1, hs, vs1)
		elseif b >= 33 then
			b = b - 33
			d:blit(x, y, self.image, b*hs, vp3, hs, vs3)
		elseif b == 10 then -- newline
			y = y + vs1 + self.lSpace
			x = (align == self.CENTER) and (ox - self:width(text, i+1) / 2 - hs) or ox
		end
		x = x + hm
	end
	screen:setTint()
end

Vera = Font:new("imgs/veramono.png")

Crystal = Font:new("imgs/crystalfont.png", 
	{hSize = 16, lSpace = 6, vPos = {0, 22, 44}, vSize = {21, 22, 20}})
