Optimizations and fix memory leaks