Clamping horizontal camera angles

Need help clamping the player’s horizontal camera angle relative to the direction the character is facing.

This is what I have so far:


		local function normalizeang(X)
			return (X >= math.pi and X - 2*math.pi) or (X <= -math.pi and 2*math.pi + X ) or X
		end

		--clamp x rotation :DDD
		local _, y = Root.CFrame:ToOrientation()
		y = -y
		local rR = y + math.pi/2
		local rL = y - math.pi/2
		local rRnorm = normalizeang(rR)
		local rLnorm = normalizeang(rL)
		
		--if not, find closest bound and camera to said bound
		if not ((X <= rRnorm and X >= rL) or (X >= rLnorm and X <= rR) or (X >= rRnorm and X <= rLnorm)) then
			X = (math.abs(X - rR) < math.pi/2 and rRnorm or rLnorm)
		end

		X = normalizeang(X)

This almost works, however it experiences false positives when the camera and character rotates beyond 180 degrees. Any ideas on how I could restrict the angle?