refactoring and minor bug fix