local timer = 0
local dying = false
local reduce = -1
local reset = 0
local map = 1
addHook("PlayerThink",function(p)
	//scripts dont run in special stages
	if p.mo and p.mo.valid and G_IsSpecialStage() == false then
		timer = timer + 1
		//decreases score by the reduce value every 35th of a second
		if timer > TICRATE/35 and p.score > 0 then
			P_AddPlayerScore(p,reduce)
			timer = 0
		end
		//kills the player if they have no score
		if p.score < reduce*-1 and dying == false and reduce < 0 then
			p.rings = 0
			p.powers[pw_shield] = 0
			p.powers[pw_invulnerability] = 0
			p.powers[pw_flashing] = 0
			P_SpawnMobjFromMobj(p.mo, 0, 0, 0, MT_CYBRAKDEMON_VILE_EXPLOSION)
			P_DamageMobj(p.mo, enemy, enemy, DMG_INSTAKILL)
			dying = true
		end
		
		//fixes integer underflow when dying
		if dying and p.score > 1 then
			p.score = 0
			p.recordscore = 0
		end
	end
end)

addHook("MapChange",function(currentmap)
	//difficulty (reduce) increases by 1 every 2 levels
	local num = currentmap - reset
	if num < 1 then
		num = 0
	end
	if num > 1 then
		reduce = (num+1)*-1/2
	else
		reduce = num*-1
	end
	map = currentmap
end)


addHook("PlayerSpawn", function(p)
	dying = false
	//if you spawn with no score it adds 300 score multiplied by the reduce value twice (you get more in the later levels to make up for the less enemies)
	if p.score == 0 then
		if reduce < -3 then
			P_AddPlayerScore(p,300*reduce*(reduce/3))
		else
			P_AddPlayerScore(p,300*reduce*reduce)
		end
	end
	p.recordscore = p.score
end)

//displays the difficulty
local function difficulty(p, field)
	print("the score difficulty for this level is "+tostring(reduce*-1)+"!")
end

//allows you to change the difficulty and reset it to 1
local function resetscore(p, field)
	if field == nil or tonumber(field) == false then
		//defaults to 1
		reset = map-1
		p.score = 300
		reduce = -1
	else
		//negative numbers get turned positive
		reset = map-abs(tonumber(field))
		//changes difficulty
		local num = abs(tonumber(field))
		if num > 1 then
			reduce = (num+1)*-1/2
		else
			reduce = num*-1
		end
		//changes score to match difficulty
		if reduce < -3 then
			p.score = 300*reduce*(reduce/3)
		else
			p.score = 300*reduce*reduce
		end
	end
	p.recordscore = p.score
	print("this is now level "+tostring(map-reset)+" and the difficulty is "+tostring(reduce*-1)+"!")
end


COM_AddCommand("scoredifficulty", difficulty)
COM_AddCommand("scorereset", resetscore)
