bug fix and refactoring