Refactoring and added some logging