refactoring and minor fixes