a major bug fix and refactoring