optimizations and code cleanup