More bug fix and refactoring