Added comments. Several stuff needs to be optimized even further, but this should be good enough.