Updated with optimized code.