local timer = 0
local dying = false
local reduce = -1
local reset = 0
local map = 1
local freeze = 0
local freezetimer = 0
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 and freeze < 1 then
			P_AddPlayerScore(p,reduce)
			timer = 0
		end
		
		//the freeze timer
		if freeze > 0 then
			freezetimer = freezetimer + 1
			if freezetimer > freeze then
				freezetimer = 0
				freeze = 0
			end
		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
		
		//resets difficulty when you get close to dying
		if p.score < 100 and reduce < -1 and reset == 0 then
			reduce = -1
		end
		
	end
end)


local function addfreeze(target, inflictor, source)
	for p in players.iterate
		if p.mo ~= source
			return
		end
		//adds 3/4 of a second to the freeze timer when you kill an enemy
		freeze = freeze + TICRATE/4*3
	end
end
addHook("MobjDamage", addfreeze)

addHook("MapChange",function(currentmap)
	//difficulty (reduce) is set to score / 1000 when you start the level
    for p in players.iterate
        reduce = (p.score/-1000)-1
    end
	reset = 0
	map = currentmap
	
end)


addHook("PlayerSpawn", function(p)
	dying = false
	//if you spawn with no score it adds 500 score
	if p.score == 0 then
			P_AddPlayerScore(p,500)
	end
	//difficulty (reduce) is set to score / 500 when you start the level
	if reset == 0 then
		reduce = (p.score/-1000)-1
	else
		reduce = reset
	end
	
	p.recordscore = p.score
end)

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

//allows you to change the difficulty or reset it back to the default
local function resetscore(p, field)
	if field == nil or tonumber(field) == false then
		//defaults to 0 and resets the difficulty
		reset = 0
		reduce = (p.score/-1000)-1
		print("Difficulty reset back to default ("+tostring(reduce*-1)+")")
		
	else
		//all numbers are negative
		reset = abs(tonumber(field))*-1
		reduce = reset
		print("The score difficulty for this level is now "+tostring(reset*-1)+"!")
	end
end


COM_AddCommand("showdifficulty", difficulty)
COM_AddCommand("changedifficulty", resetscore)
