getting really deeply nested here, would it make sense to move part of the processing to a separate func?