Fixed error handling and added comments.