More refactoring and improvements to the context switching implementation