Major refactoring and optimization.