added logging and some refactoring