New pagination algorithm

Implemented Tim's improved pagination algorithm.  Let me know if you
notice any bugs :)