bug fix and refactaring