refactored code and added error checking