Added comments, optimized code