refactor search function