Final bug fix and refactoring