Code cleanup and improved logging.