added some comments and optimizations