Optimizations. Some bug fixes