Simplify the top or bottom detection code