improved error handling; simplified code