Added maxiumum number of search retries and better protection from infinite loops