separated context switching logic