Tried to improve error handling.