Refactoring and some dead code removal