title = {}
local title_mode = false

title.version = "1.0.0.6"
title.copygfx = "PIXEL"

title.char = {
	-- Menu character graphics & animation
	sheet = graphics[MyChar],
	{0,16,16,16},
	{16,16,16,16},
	{0,16,16,16},
	{32,16,16,16}
}

title.menu = {
	start = {136,128},
	add = 20,
	{graphics[Title],{144,0,48,16}}, -- New
	{graphics[Title],{144,16,48,16}} -- Load
}

function title.mode(set)
	title_mode = set
	if set
		title.copyright = pbm.load(title.copygfx)
	else
		title.copyright = nil
	end
	title.char.frame = 1
	title.char.ticks = 0
	title.char.pos = 0
	title.reset()
end

function title.reset()
	if title.leaving
		title.leaving = nil
		title.mode(false)
	end
	if not title_mode
		return
	end
	fade.off()
	bk.color = 0x212021
end

function title.think()
	if not title_mode
		return
	end
	local ch = title.char
	ch.ticks = ch.ticks + 1
	if ch.ticks > 10
		ch.ticks = 0
		ch.frame = ch.frame + 1
		if not ch[ch.frame]
			ch.frame = 1
		end
	end
	if input.btn_start & 1<<BTN.UP ~= 0
		ch.pos = ch.pos - 1
		if not title.menu[ch.pos+1]
			ch.pos = #title.menu-1
		end
	end
	if input.btn_start & 1<<BTN.DOWN ~= 0
		ch.pos = ch.pos + 1
		if not title.menu[ch.pos+1]
			ch.pos = 0
		end
	end
	if input.btn_start & 1<<BTN.OK ~= 0
		title.leaving = true
		net.send_title(ch.pos)
	end
end

function title.draw(screen)
	if not title_mode
		return
	end
	local num = '0'
	num = num:bin(1)
	screen.draw(graphics[TextBox],{152,80,56,8},{100,216}) -- Version
	screen.draw(graphics[TextBox],{152,88,56,8},{156,216}) -- . . . .
	for i = 1,#title.version,2
		screen.draw(graphics[TextBox],{8*(title.version:bin(i)-num),56,8,8},{156+8*i,216}) -- numbers from title.version
	end
	screen.draw(title.copyright,{0,0,160,16},{80,192})
	for i = 1,#title.menu
		screen.draw(title.menu[i][1],title.menu[i][2],{title.menu.start[1],title.menu.start[2]+title.menu.add*(i-1)}) -- Menu items
	end
	screen.draw(title.char.sheet,title.char[title.char.frame],{title.menu.start[1]-title.menu.add,title.menu.start[2]-1+title.menu.add*title.char.pos}) -- Menu Character
	screen.draw(graphics[Title],{0,0,144,40},{88,40}) -- Cave Story title
end
