Added more robust error checking and handling