crude pagination and some refactoring