General refactoring and clean up