refactored and added error handling