Many optimizations and cleanup