More refactoring

All this needs testing over the next few days