added comments and improved error handling
error handling