Bunch of refactoring and optimization