added some logging and refactored code