Added more robust error checking