Fixed code to handle some failed cases