Some of the logic wasn't very clear from just looking at the code and some of it also wasn't very optimal. So I added some comments and optimized some stuff to make it better.