Deep nesting indicates that this code should be split into a separate function.