Some refactoring and more logging