Code cleanup and optimizations