refactored code
added error check