fade = {
	table={13,15,5,3,12,5,6,7,12,9,10,16,9,13,14},
	pal={},
	old_update=nil,
	wait=0,
	step=0,
	outin=false,

	init = function()
		for i=1,15 do
			local r,g,b=pal.color(i)
			fade.pal[i]={r,g,b}
		end
	end,

	getstep=function(num,steps)
		if steps==0 or num==16 then return num end
		for i=1,steps do
			num=fade.table[num]
			if num==16 then return num end
		end
		return num
	end,

	fadeout = function()
		--print("fading out")
		fade.old_update=game_update
		game_update=fade.update_fadeout
		fade.wait=0
		fade.step=0
	end,

	fadeoutin = function()
		--print("fading outin")
		fade.old_update=game_update
		game_update=fade.update_fadeout
		fade.wait=0
		fade.step=0
		fade.outin=true
	end,

	update_fadeout=function()
		--print("out")
		fade.wait=fade.wait+1
		if fade.wait==6 then
			fade.wait=0
			for i=1,15 do
				local v=fade.getstep(i,fade.step)
				--print(v)
				if v==16 then
					pal.color(i,0,0,0)
				else
					pal.color(i,fade.pal[v][1],fade.pal[v][2],fade.pal[v][3])
				end
			end
			fade.step=fade.step+1
			if fade.step==7 then
				game_update = fade.old_update
				if fade.outin then
					fade.outin=false;
					fade.fadein()
				end
			end
		end
	end,

	fadein = function()
		--print("fading in")
		fade.old_update=game_update
		game_update=fade.update_fadein
		fade.wait=0
		fade.step=6
		for i=1,15 do pal.color(i,0,0,0) end
	end,

	update_fadein=function()
		--print("in")
		fade.old_update()

		fade.wait=fade.wait+1
		if fade.wait==6 then
			fade.wait=0
			for i=1,15 do
				local v=fade.getstep(i,fade.step)
				--print(v)
				if v==16 then
					pal.color(i,0,0,0)
				else
					pal.color(i,fade.pal[v][1],fade.pal[v][2],fade.pal[v][3])
				end
			end
			fade.step=fade.step-1
			if fade.step<0 then
				game_update = fade.old_update
			end
		end
	end

}
