Added better error handling and logging.