Added additional error checking and logging.