Code cleanup and minor optimizations