Major refactoring to reduce size and increase speed.