Cleaned and added some error-checking