@matsko could you split this out into smaller functions so it's easier to understand what's going on?