some refactoring and fixes