Bug fix and small refactorings