Added more error checking and fixes