Refactoring

And more refactoring work. These are the last changes (for now).