refactored code, improved error handling