Refactor tab selection code