Added more complete error handling