refactor search and sort code