Added logic to handle wrapping around the board