refactoring and better logging