Code cleanups and optimizations