redid script, more efficiency,  error handling