added lot of error checking and fail safes