fix paging bug and refactor code