Re-factored pagination logic.