-- Font loading/rendering stuff. Don't mess with it.
-- We differentiate 'detail' textures here for smaller lettering.
font = {}

local FACE = {"PBM","WIDTH","HEIGHT","MAP"}
for k,v in ipairs(FACE)
	FACE[v] = k
end

local function InitFontMap(font)
	local map = {}
	for i=1,#font
		map[font:sub(i,i)] = i-1
	end
	return map
end

local function GlyphPos(font,glyph)
	if not glyph
		return 0,0
	end
	local w = font[FACE.PBM]:w() * font[FACE.PBM]:detail() -- Use the real width
	local x = (glyph * font[FACE.WIDTH])
	local y = math.floor(x / w) * font[FACE.HEIGHT]
	x = x % w

	x = x / font[FACE.PBM]:detail()
	y = y / font[FACE.PBM]:detail()
	return x,y
end

local function GlyphWidth(font,glyph)
	if not glyph
		return (font[FACE.WIDTH] - 2) / font[FACE.PBM]:detail()
	end
	if font[FACE.MAP][glyph]
		return font[FACE.MAP][glyph]
	end
	local x,y = GlyphPos(font,glyph)
	local pixmap = font[FACE.PBM]:getPixels(x,y)
	for x = font[FACE.WIDTH]-1,0,-1
		for y = 0,font[FACE.HEIGHT]-1
			if pixmap:getColorIndex(x,y) ~= 0
				pixmap:finish()
				font[FACE.MAP][glyph] = (x + 1) / font[FACE.PBM]:detail()
				return (x + 1) / font[FACE.PBM]:detail()
			end
		end
	end
	pixmap:finish()
	font[FACE.MAP][glyph] = 0
	return 0
end

local function DrawGlyph(screen,font,glyph,x,y)
	if not glyph
		return
	end
	local sheet_x,sheet_y = GlyphPos(font,glyph)
	screen.draw(font[FACE.PBM],{sheet_x,sheet_y,font[FACE.WIDTH]/font[FACE.PBM]:detail(),font[FACE.HEIGHT]/font[FACE.PBM]:detail()},{x,y})
end

function font:init()
	console.debug("Initializing font map and loading font faces.")
	font.map = InitFontMap("!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~©×")
	font.face = {}
	font.face["thin"] = {pbm.load("ThinFont"),4,7,{}}
	font.face["normal"] = {pbm.load("Font"),5,7,{}}
	font.face["hd"] = {pbm.load("LargeFont",2),7,9,{}}
end

function font.draw_string(screen,text,x,y,face,spacing)
	face = font.face[face]
	--x = math.floor(x*2/face[FACE.PBM]:scale())
	--y = math.floor(y*2/face[FACE.PBM]:scale())
	for i = 1,#text
		local glyph = font.map[text:sub(i,i)]
		if spacing
			DrawGlyph(screen,face,glyph,x+math.floor(spacing/2)-math.floor(GlyphWidth(face,glyph)/2),y)
			x = x + spacing
		else
			DrawGlyph(screen,face,glyph,x,y)
			x = x + GlyphWidth(face,glyph) + 1
		end
	end
end
