udpated with documentation and some optimizations