improved next-ptr function to use simple filters instead of recursion