Can you split all this logic into a private method? It is getting quite huge