Simplified code and added comments.