search code refactored for easier testability and reusability