refactoring and cleaning-up the code for changing context