Bug fix and refactoring