Lots of cleanup and optimizations