function initialize()
	-- PAGES:
	-- 0 = dice
	-- 1 = HP
	-- 2 = Stats roller
	-- 3 = Names generator
	-- 4 = Treasure generator (not implemented)
	-- 5 = Monster generator (not implemented)
	
	number, result, modifier, half, full, page = 0, 0, 0, 0, 0, 0
	
	white = Color.new(255,255,255)
	blue = Color.new(0,0,255)
	red = Color.new(255,0,0)
	green = Color.new(0,255,0)
	numdice = 1
	index = 1
	rolled = "Rolled:"
	
	-- Make sure maxhp gets initialized even if there's no file
	maxhp = 0
	curhp = maxhp
	gethp()
	tempmaxhp = maxhp
	hpadjust = 1
	
	stats1, stats2, stats3, stats4, stats5, stats6, stats7, stats8 = "", "", "", "", "", "", "", ""
	stats9, stats10, stats11, stats12, method, action = "", "", "", "", "", ""
	
	diceSound = Sound.load("dice.wav",false)
	
	smallfont = Font.createMonoSpaced()
	smallfont:setPixelSizes(0,10)
	mediumsmallfont = Font.createMonoSpaced()
	mediumsmallfont:setPixelSizes(0,14)
	mediumfont = Font.createMonoSpaced()
	mediumfont:setPixelSizes(0,18)
	mediumlargefont = Font.createMonoSpaced()
	mediumlargefont:setPixelSizes(0,40)
	largefont = Font.createMonoSpaced()
	largefont:setPixelSizes(0,75)
	
	
	dice = {}
		dice[1] = {sides = 2, name = "d2"}
		dice[2] = {sides = 4, name = "d4"}
		dice[3] = {sides = 6, name = "d6"}
		dice[4] = {sides = 8, name = "d8"}
		dice[5] = {sides = 10, name = "d10"}
		dice[6] = {sides = 12, name = "d12"}
		dice[7] = {sides = 20, name = "d20"}
		dice[8] = {sides = 100, name = "d100"}
	
	background = Image.load("0.png")
	
	
	repeatdelay = 5 -- CHANGE THIS TO A VALUE THAT YOU ARE COMFORTABLE WITH, LOWER IS FASTER
	
	upHeld, downHeld, leftHeld, rightHeld = 0,0,0,0
	lHeld, rHeld = 0,0
	
	first1, last1 = "", ""
	first2, last2 = "", ""
	first3, last3 = "", ""
	first4, last4 = "", ""
	first5, last5 = "", ""
	
	-- Types of names
	-- To add additional name types:
	-- 	Add a line nametypes[x] = {name = "Type", info = "Short Description", malenames = 0, femalenames = 0, lastnames = 0}
	--	Create three files: names-Type-male-first.txt, names-Type-female-first.txt, names-Type-last.txt
	nametypes = {}
		nametypes[1] = {name = "Common", info = "Common names database from the internet", malenames = 0, femalenames = 0, lastnames = 0}
		nametypes[2] = {name = "Actor", info = "Names from list of Actors, use male, not seperated by gender", malenames = 0, femalenames = 0, lastnames = 0}
		nametypes[3] = {name = "Movies", info = "Names from movie characters, use male, no last names", malenames = 0, femalenames = 0, lastnames = 0}
		
	nameindex = 1
	maxnameindex = table.maxn(nametypes)	
	
	
end

function gethp()
	curhpfile = io.open("curhp","r")
	if curhpfile then
		curhp = curhpfile:read("*n")
		curhpfile:close()
	end
	maxhpfile = io.open("maxhp","r")	
	if maxhpfile then
		maxhp = maxhpfile:read("*n")
		maxhpfile:close()
	end
	if type(curhp) ~= "number" then
		curhp = 0
	end	
	if type(maxhp) ~= "number" then
		maxhp = 0
	end

end

function writehp()
	curhpfile = io.open("curhp","w")
	if curhpfile then
		curhpfile:write(curhp)
		curhpfile:close()
	end
	maxhpfile = io.open("maxhp","w")	
	if maxhpfile then
		maxhpfile:write(maxhp)
		maxhpfile:close()
	end
end

function generate4d6droplowest()
	stats1, stats2, stats3, stats4, stats5, stats6 = fourd6droplowest(), fourd6droplowest(), fourd6droplowest(), fourd6droplowest(), fourd6droplowest(), fourd6droplowest()
	stats7, stats8, stats9, stats10, stats11, stats12 = fourd6droplowest(), fourd6droplowest(), fourd6droplowest(), fourd6droplowest(), fourd6droplowest(), fourd6droplowest()
	method = "Method: 4d6, drop the lowest"
end

function fourd6droplowest()

	mystats = {}
	mystats[1] = math.random(1,6)
	mystats[2] = math.random(1,6)
	mystats[3] = math.random(1,6)
	mystats[4] = math.random(1,6)
	
	-- find the lowest
	
	lowest = mystats[1]
	if mystats[2] < lowest then
		lowest = mystats[2]
	end
	if mystats[3] < lowest then
		lowest = mystats[3]
	end
	if mystats[4] < lowest then
		lowest = mystats[4]
	end
	sum = mystats[1] + mystats[2] + mystats[3] + mystats[4] - lowest
	
	return mystats[1] .. "," .. mystats[2] .. "," .. mystats[3] .. "," .. mystats[4] .. "=" .. sum
end

function generate5d6droplowest()
	stats1, stats2, stats3, stats4, stats5, stats6 = fived6droplowest(), fived6droplowest(), fived6droplowest(), fived6droplowest(), fived6droplowest(), fived6droplowest()
	stats7, stats8, stats9, stats10, stats11, stats12 = fived6droplowest(), fived6droplowest(), fived6droplowest(), fived6droplowest(), fived6droplowest(), fived6droplowest()
	method = "Method: 5d6, drop the two lowest"
end

function fived6droplowest()

	mystats = {}
	mystats[1] = math.random(1,6)
	mystats[2] = math.random(1,6)
	mystats[3] = math.random(1,6)
	mystats[4] = math.random(1,6)
	mystats[5] = math.random(1,6)
	
	-- find the lowest
	
	first = 1
	if mystats[2] < mystats[first] then
		first = 2
	end
	if mystats[3] < mystats[first] then
		first = 3
	end
	if mystats[4] < mystats[first] then
		first = 4
	end
	if mystats[5] < mystats[first] then
		first = 5
	end
	
	-- find second lowest
	second = 1
	if first == 1 then
		second = 2
	end
	if mystats[2] < mystats[second] and first ~= 2 then
		second = 2
	end
	if mystats[3] < mystats[second] and first ~= 3 then
		second = 3
	end
	if mystats[4] < mystats[second] and first ~= 4 then
		second = 4
	end
	if mystats[5] < mystats[second] and first ~= 5 then
		second = 5
	end

	sum = mystats[1] + mystats[2] + mystats[3] + mystats[4] +mystats[5] - mystats[first] - mystats[second]
	
	return mystats[1] .. "," .. mystats[2] .. "," .. mystats[3] .. "," .. mystats[4] .. "," .. mystats[5] .. "=" .. sum
end


		
function roll(sides,multiplier,modif)
	rolled = "Rolled " .. multiplier .. "d" .. sides .. "+" .. modif .. ": " 
	number = 0
	-- play sound
	local sound = diceSound
	voice = sound:play()
	for i = 1, multiplier do
		number2 = math.random(1,sides)
		rolled = rolled .. number2 .. ","
		number = number + number2
	end
	rolled = rolled .. "+" .. modif
	return number + modif
end

function getname(type, gender)
	-- Files are in the format "names-Type-mender-first.txt" or "names-Type-last.txt"
	lastnamefile = "names-" .. type.name .. "-last.txt"
	
	if gender == "male" then
		firstnamefile = "names-" .. type.name .."-male-first.txt"
	else
		firstnamefile = "names-" .. type.name .."-female-first.txt"
	end


	--------------------------------------
	-- Get first names
	--------------------------------------
	local first1num, first2num, first3num, first4num, first5num
	if gender == "male" then
		if type.malenames == 0 then
			local namelines = 0
			for line in io.lines(firstnamefile) do
				namelines = namelines + 1
			end
			type.malenames = namelines
		end
		first1num = math.random(1,type.malenames)
		first2num = math.random(1,type.malenames)
		first3num = math.random(1,type.malenames)
		first4num = math.random(1,type.malenames)
		first5num = math.random(1,type.malenames)
	else
		if type.femalenames == 0 then
			local namelines = 0
			for line in io.lines(firstnamefile) do
				namelines = namelines + 1
			end
			type.femalenames = namelines
		end
		first1num = math.random(1,type.femalenames)
		first2num = math.random(1,type.femalenames)
		first3num = math.random(1,type.femalenames)
		first4num = math.random(1,type.femalenames)
		first5num = math.random(1,type.femalenames)
	end

	local first1found, first2found, first3found, first4found, first5found = false,false,false,false,false
	local curline = 0

	-- Go through the entire file, selecting the lines as we encounter them.
	-- When all the needed lines are found, exit
	for line in io.lines(firstnamefile) do
		curline = curline + 1
		if curline == first1num then
			first1 = line
			first1found = true
		end
		if curline == first2num then
			first2 = line
			first2found = true
		end
		if curline == first3num then
			first3 = line
			first3found = true
		end
		if curline == first4num then
			first4 = line
			first4found = true
		end
		if curline == first5num then
			first5 = line
			first5found = true
		end
		--if first1found and first2found and first3found and first4found and first5found then
		--	break
		--end
	end
	--------------------------------------
	-- Get last names
	--------------------------------------
	-- Count lines in the file, if we don't have a count already
	if type.lastnames == 0 then
		local namelines = 0
		for line in io.lines(lastnamefile) do
			namelines = namelines + 1
		end
		type.lastnames = namelines
	end
		
	-- Select 5 random lines
	local last1num = math.random(1,type.lastnames)
	local last2num = math.random(1,type.lastnames)
	local last3num = math.random(1,type.lastnames)
	local last4num = math.random(1,type.lastnames)
	local last5num = math.random(1,type.lastnames)


	local last1found, last2found, last3found, last4found, last5found = false,false,false,false,false
	local curline = 0
	
	-- Go through the entire file, selecting the lines as we encounter them.
	-- When all the needed lines are found, exit
	for line in io.lines(lastnamefile) do

		curline = curline + 1
		if curline == last1num then
			last1 = line
			last1found = true
		end
		if curline == last2num then
			last2 = line
			last2found = true
		end
		if curline == last3num then
			last3 = line
			last3found = true
		end
		if curline == last4num then
			last4 = line
			last4found = true
		end
		if curline == last5num then
			last5 = line
			last5found = true
		end
		--if last1found and last2found and last3found and last4found and last5found then
		--	next
		--end

	end
	
end
	

function changepage(direction)

	page = page + direction
	
	if page < 0 then
		page = 3
	elseif page > 3 then
		page = 0
	end
	
	background = Image.load(page .. ".png")
end

function repeatup()
	-- If its a new button press (!= to old pad), true, otherwise wait for the delay to increase before returning true
	if pad:up() ~= oldpad:up() then
		upHeld = 0
		return true
	else
		upHeld = upHeld + 1
		if upHeld > repeatdelay then
			return true
		else
			return false
		end
	end
end

function repeatdown()
	if pad:down() ~= oldpad:down() then
		downHeld = 0
		return true
	else
		downHeld = downHeld + 1
		if downHeld > repeatdelay then
			return true
		else
			return false
		end
	end
end

function repeatleft()
	if pad:left() ~= oldpad:left() then
		leftHeld = 0
		return true
	else
		leftHeld = leftHeld + 1
		if leftHeld > repeatdelay then
			return true
		else
			return false
		end
	end
end

function repeatright()
	if pad:right() ~= oldpad:right() then
		rightHeld = 0
		return true
	else
		rightHeld = rightHeld + 1
		if rightHeld > repeatdelay then
			return true
		else
			return false
		end
	end
end

function repeatl()
	if pad:l() ~= oldpad:l() then
		lHeld = 0
		return true
	else
		lHeld = lHeld + 1
		if lHeld > repeatdelay then
			return true
		else
			return false
		end
	end
end

function repeatr()
	if pad:r() ~= oldpad:r() then
		rHeld = 0
		return true
	else
		rHeld = rHeld + 1
		if rHeld > repeatdelay then
			return true
		else
			return false
		end
	end
end

function page0controls()
	if pad:up() then
		if repeatup() then
			index = index + 1
		end			
	end

	if pad:down() then
		if repeatdown() then
			index = index - 1
		end
	end
	
	if pad:left() then
		if repeatleft() then
			numdice = numdice - 1
		end
		if numdice < 1 then
			numdice = 1
		end
	end
	
	if pad:right() then
		if repeatright() then
			numdice = numdice + 1
		end
	end	
		
	if pad:r() then
		if repeatr() then
			modifier = modifier + 1
		end
	end		
	
	if pad:l() then
		if repeatl() then
			modifier = modifier - 1
		end
	end		
	
	if pad:square() and oldpad:square() ~= pad:square() then
		result = roll(20,1,0)
	end
	
	if pad:circle() and oldpad:circle() ~= pad:circle() then
		result = roll(8,1,0)
	end
	
	if pad:triangle() and oldpad:triangle() ~= pad:triangle() then
		result = roll(6,1,0)
	end		
	
	if pad:cross() and oldpad:cross() ~=pad:cross() then
		result = roll(dice[index].sides,numdice,modifier)
	end
	if index == 0 then
	index = 8
	end
	
	if index == 9 then
		index = 1
	end
end

function page0display()
	-- Title/die info	
	screen:fontPrint(mediumfont,140,30,"Dice to Roll: " .. numdice .. dice[index].name .. " +" .. modifier, white)
	screen:fontPrint(smallfont,0,70,rolled, red)
	
	-- Labels around the button image
	screen:fontPrint(smallfont,408,225, "Roll",blue)
	screen:fontPrint(smallfont,367,182, "d20",blue)
	screen:fontPrint(smallfont,455,182, "d8",blue)
	screen:fontPrint(smallfont,413,140, "d6",blue)
	
	-- Centered result
	length = string.len(result)
	resultx = 240 - ((length*38)/2)
	screen:fontPrint(largefont,resultx,140, result, red)
	
	screen:fontPrint(smallfont,0,220, "Change Die Type: Up/Down", blue)
	screen:fontPrint(smallfont,0,235, "Change Modifier: L/R Trigger", blue)
	screen:fontPrint(smallfont,0,250, "Number of Dice:  Left/Right", blue)
	screen:fontPrint(smallfont,0,265, "Change Screen: Start/Select", blue)
end

function page1controls()

	if pad:up() then
		if repeatup() then
			tempmaxhp = tempmaxhp + 1
		end			
	end
		
	if pad:down() then
		if repeatdown() then
			tempmaxhp = tempmaxhp - 1
		end
	end
	
	if pad:square() and oldpad:square() ~= pad:square() then
		curhp = curhp - hpadjust
		action = "Subtracted " .. hpadjust
		writehp()
		
	end
	
	if pad:circle() and oldpad:circle() ~= pad:circle() then
		curhp = curhp + hpadjust
		action = "Added " .. hpadjust
		writehp()
	end
	
	if pad:cross() and oldpad:cross() ~= pad:cross() then
		action = "Fully healed from " .. curhp .. " to " .. maxhp
		curhp = maxhp
		writehp()
	end
	
	if pad:left() and repeatleft() then
		hpadjust = hpadjust - 1
		if hpadjust < 1 then
			hpadjust = 1
		end
	end
	
	if pad:right() and repeatright() then
		hpadjust = hpadjust + 1
	end
	
	
	if pad:triangle() and oldpad:triangle() ~=pad:triangle() then
		maxhp = tempmaxhp
		writehp()
	end
		end

function page1display()
	-- Title info	
	screen:fontPrint(mediumfont,100,30,"Adjust by: " .. hpadjust .. "   New Max HP: " .. tempmaxhp, white)
	
	-- Labels around the button image
	screen:fontPrint(smallfont,395,225, "Full Heal",blue)
	screen:fontPrint(smallfont,347,182, "Subtract",blue)
	screen:fontPrint(smallfont,452,182, "Add",blue)
	screen:fontPrint(smallfont,380,140, "Save New Max HP",blue)
	
	screen:fontPrint(mediumlargefont,10,120, "Current: " .. curhp .. "/" .. maxhp, red)
	screen:fontPrint(smallfont,10,150,action,red)
	
	screen:fontPrint(smallfont,0,220, "Change Max HP: Up/Down", blue)
	screen:fontPrint(smallfont,0,235, "Change HP Adjustment:  Left/Right", blue)
	screen:fontPrint(smallfont,0,250, "HP is automatically saved every time you change it", blue)
end

function page2controls()
	if pad:square() and oldpad:square() ~= pad:square() then
		generate5d6droplowest()		
	end
	
	if pad:circle() and oldpad:circle() ~= pad:circle() then
		
	end
	
	if pad:cross() and oldpad:cross() ~= pad:cross() then
		generate4d6droplowest()
	end
	if pad:triangle() and oldpad:triangle() ~=pad:triangle() then
	end
end

function page2display()
	-- Title info	
	screen:fontPrint(mediumfont,100,30,"Roll a new character:", white)
	
	
	screen:fontPrint(mediumfont,10,60, method, red)	
	screen:fontPrint(mediumfont,10,100,stats1,red)
	screen:fontPrint(mediumfont,10,120,stats2,red)
	screen:fontPrint(mediumfont,10,140,stats3,red)
	screen:fontPrint(mediumfont,10,160,stats4,red)
	screen:fontPrint(mediumfont,10,180,stats5,red)
	screen:fontPrint(mediumfont,10,200,stats6,red)	
	screen:fontPrint(mediumfont,180,100,stats7,red)
	screen:fontPrint(mediumfont,180,120,stats8,red)
	screen:fontPrint(mediumfont,180,140,stats9,red)
	screen:fontPrint(mediumfont,180,160,stats10,red)
	screen:fontPrint(mediumfont,180,180,stats11,red)
	screen:fontPrint(mediumfont,180,200,stats12,red)			
	screen:fontPrint(smallfont,0,220, "Cross: 4d6 drop the lowest", blue)
	screen:fontPrint(smallfont,0,235, "Square: 5d6 drop 2 lowest", blue)
end

function page3controls()

	if pad:right() then
		if repeatright() then
			nameindex = nameindex + 1
		end			
	end
	
	if pad:left() then
		if repeatleft() then
			nameindex = nameindex - 1
		end			
	end	
	
	if nameindex < 1 then
		nameindex = maxnameindex
	end
	if nameindex > maxnameindex then
		nameindex = 1
	end

	if pad:square() and oldpad:square() ~= pad:square() then
		first = getname(nametypes[nameindex], "female")	
	end
	
	if pad:circle() and oldpad:circle() ~= pad:circle() then
		
	end
	
	if pad:cross() and oldpad:cross() ~= pad:cross() then
		first = getname(nametypes[nameindex], "male")
	end
	if pad:triangle() and oldpad:triangle() ~=pad:triangle() then
	end
	


end

function page3display()
	-- Title info	
	screen:fontPrint(mediumfont,120,20,"Name Type: " .. nametypes[nameindex].name, white)
	screen:fontPrint(mediumsmallfont,120,40,nametypes[nameindex].info, blue)
	
	
	screen:fontPrint(mediumfont,10,80,first1 .. " " .. last1,red)
	screen:fontPrint(mediumfont,10,100,first2 .. " " .. last2,red)
	screen:fontPrint(mediumfont,10,120,first3 .. " " .. last3,red)
	screen:fontPrint(mediumfont,10,140,first4 .. " " .. last4,red)
	screen:fontPrint(mediumfont,10,160,first5 .. " " .. last5,red)
	
	screen:fontPrint(smallfont,0,220, "Left/Right: Change Name Type", blue)
	screen:fontPrint(smallfont,0,235, "Cross: Male Names", blue)
	screen:fontPrint(smallfont,0,250, "Square: Female Names", blue)
end

-----------------------------------------------------------------
-- BEGIN MAIN SCRIPT
-----------------------------------------------------------------
initialize()

while true  do
	pad = Controls.read()
	screen:clear()
	screen:blit(0, 0, background)

	-- DEBUG
	if pad:hold() then
		intentionallycrash()
	end
	
	if pad:select() and oldpad:select() ~=pad:select() then
		changepage(-1)
	end
	
	if pad:start() and oldpad:start() ~=pad:start() then
		changepage(1)
	end


	if page == 0 then
		page0controls()
		page0display()	
	elseif page == 1 then
		page1controls()
		page1display()
	elseif page == 2 then
		page2controls()
		page2display()
	elseif page == 3 then
		page3controls()
		page3display()
	end
	
	oldpad = pad
	screen.waitVblankStart()
	screen.flip()
end

