Refactor selection code