Bunch of refactoring and tweaks