refactoring and minor bug fixes