Large refactor and code cleanup.