local TICRATE = TICRATE or 35
local spinData = {}

addHook("PlayerThink", function(player)
    if not (player and player.mo and player.mo.valid) then 
        return 
    end
    
    if not spinData[player] then
        spinData[player] = {
            lastSpeed = 0
        }
    end
    
    local d = spinData[player]
    
    if player.pflags & PF_SPINNING then
        if d.lastSpeed > 0 then
            local currentSpeed = R_PointToDist2(0, 0, player.mo.momx, player.mo.momy)
            
            if currentSpeed < d.lastSpeed then
                local angle = R_PointToAngle2(0, 0, player.mo.momx, player.mo.momy)
                player.mo.momx = FixedMul(cos(angle), d.lastSpeed)
                player.mo.momy = FixedMul(sin(angle), d.lastSpeed)
            end
        end
    else
        local currentSpeed = R_PointToDist2(0, 0, player.mo.momx, player.mo.momy)
        
        if currentSpeed <= 50*FRACUNIT then
            d.lastSpeed = currentSpeed
        end
    end
end)

addHook("MapChange", function()
    spinData = {}
end)