bug fix and refactor