re-factor pagination and fix bugs