added more error checking, and a better way of limiting the search