refactor search loop