Massive refactoring to reduce code.