Comments added and some optimizations applied