improved pagination logic