Refactoring and minor fixes