Refactoring and improved logging