Some refactoring and adding better logging