KRACOEUS-7847 and KRACOEUS-7282

Please review this PR, some more work pending, don't merge it just yet.
Can we break this into smaller methods please? The indentation is too deep here.