Rewrite of pagination logic to be easier to follow and faster