added comments and optimized code