Optimizations and code cleanup