Refactoring a bit

Lots to extract/refactor but it's a start.