This is a lot of logic to pack into one method pipeline; it would be good to extract this out into a helper method and rework it to be more readable.