Added logging and more error handling