Small bug fix and refactoring