some refactorings and bug fixes