freeslot("SPR2_BUND","S_PLAY_BOUND")

states[S_PLAY_BOUND] = {SPR_PLAY, SPR2_BUND, -1, nil, 0, 0, S_PLAY_BOUND}

addHook("PlayerThink",function(p)
	
	if P_PlayerInPain(p)
	or p.powers[pw_carry] > 0
	or p.exiting
	or P_IsObjectInGoop(p.mo)
	or p.playerstate == PST_DEAD
	or p.pflags & PF_SLIDING
	or p.mo.state == S_PLAY_GASP
	or p.pflags & PF_THOKKED
	or p.pflags & PF_SHIELDABILITY
		p.bouncing = false
		p.bouncecount = 0
		p.rebounding = false
	end

	if p.bouncing == nil
		p.bouncing = false
		p.rebounding = false
	end
	if p.bouncecount == nil
		p.bouncecount = 0
	end
	if p.bouncing
		p.bouncecount = $+3
		if not p.powers[pw_super]
			if p.bouncecount >= 15
				p.bouncecount = 15
			end
		end
	end
	
	if P_IsObjectOnGround(p.mo)
	and p.rebounding == true
		p.rebounding = false
	end
	
	if p.mo.skin == "sonic"
		if not P_PlayerInPain(p)
		and p.powers[pw_carry] < 1
		and not p.exiting
		and not P_IsObjectInGoop(p.mo)
		and p.playerstate == PST_LIVE
		and not (p.pflags & PF_SLIDING)
		and p.mo.state != S_PLAY_GASP
		and not (p.pflags & PF_SHIELDABILITY)
		and not (p.pflags & PF_THOKKED)
			if p.bouncing == true
				if not P_IsObjectOnGround(p.mo)
					P_SetObjectMomZ(p.mo,-40*FRACUNIT,false)
					p.mo.state = S_PLAY_BOUND
				end
				
				if p.mo.eflags & MFE_JUSTHITFLOOR
				or P_IsObjectOnGround(p.mo)
					if p.mo.eflags & MFE_UNDERWATER
						P_SetObjectMomZ(p.mo,FRACUNIT*((p.bouncecount/3)*2),false)
					else
						P_SetObjectMomZ(p.mo,FRACUNIT*p.bouncecount,false)
					end
					p.rebounding = true
					p.pflags = $|PF_JUMPED
					p.mo.state = S_PLAY_ROLL
					p.bouncing = false
					p.bouncecount = 0
					
					S_StartSound(p.mo,sfx_s3k44)
					
					if p.mo.eflags & MFE_SPRUNG
						p.mo.momz = $/2 * 3
						S_StartSound(p.mo,sfx_sprong)
					end
				end
			end
		end
		if p.rebounding
			local g = P_SpawnGhostMobj(p.mo)
			g.fuse = 3
			g.colorised = true
			g.color = p.mo.color
		end
	end
end)

addHook("AbilitySpecial", function(p)
	if p.mo.skin == "sonic"
		p.bouncing = true
		return true
	end
end)

local function CheckAndCrumble2(mo, sec)
  for fof in sec.ffloors()
    if not (fof.flags & FF_EXISTS) continue end -- Does it exist?
    if not (fof.flags & FF_BUSTUP) continue end -- Is it bustable?
    
    if mo.z + mo.momz + mo.height < fof.bottomheight continue end -- Are we too low?
    if mo.z + mo.momz > fof.topheight continue end -- Are we too high?

    -- Check for whatever else you may want to    

    EV_CrumbleChain(fof) -- Crumble
  end
end

addHook("PlayerThink", function(p)
  if not p.mo return end
  if p.mo.skin != "sonic" return end
  if p.bouncing == false return end
	CheckAndCrumble2(p.mo, p.mo.subsector.sector)
end)