Cleanups, refactoring and optimizations.