Deep nesting, should be split into separate function.