Added comments, and made some performance optimizations