Bug fix and a bit of refactoring