Remove excessive looping. Move check for out-of-bounds coordinates.