Added comments, optimized code, and fixed typos