Bug fix and refactor