Added logging and better error handling.