Improved pagination functionality.

Thanks @orarbel for his contribution to the pagination method.