Make it work with sorting etc.

This change makes the excellent pagination code work with sorting.