simplified code and improved error handling