Cleanup code and several optimizations