Bug fixes. Small refactoring.