Pull deeply nested logic into functions