Many cleanups and optimizations