diff --git a/src/p_map.c b/src/p_map.c
index d26b1707d3a301f6e7182e8ba9fa2740cd9b46d6..c2e028472559dad9c75f4c4173689270cf90dcb6 100644
--- a/src/p_map.c
+++ b/src/p_map.c
@@ -5024,9 +5024,9 @@ fixed_t P_CeilingzAtPos(fixed_t x, fixed_t y, fixed_t z, fixed_t height)
 
 			if (rover->flags & FF_QUICKSAND)
 			{
-				if (z < topheight && bottomheight < thingtop)
+				if (thingtop > bottomheight && topheight > z)
 				{
-					if (ceilingz < z)
+					if (ceilingz > z)
 						ceilingz = z;
 				}
 				continue;
@@ -5034,7 +5034,7 @@ fixed_t P_CeilingzAtPos(fixed_t x, fixed_t y, fixed_t z, fixed_t height)
 
 			delta1 = z - (bottomheight + ((topheight - bottomheight)/2));
 			delta2 = thingtop - (bottomheight + ((topheight - bottomheight)/2));
-			if (bottomheight > ceilingz && abs(delta1) < abs(delta2))
+			if (bottomheight < ceilingz && abs(delta1) > abs(delta2))
 				ceilingz = bottomheight;
 		}
 	}