Improve terminal selection code