Optimized code, added comments