Added logging and refactored.