Various fixes from profiling, memory leaks and optimizations.