improved switching logic, first actually working version