Refactor search function