bug fix and code refactoring