refactoring and logging improved