Improved the code with changing modes support