Bug fixes and several refactorings