optimized code and added comments