General refactoring and cleanup