fixed bugs, some refactorings