Major refactor for performance.