Good comment, but I think you're trying to be clever.  Create a callback function that does this top chunk of function and then goes on to call a separate function containing the remaining bit of `get_associated_primary_public_ids`.  Ideally, separate out the IMPI list management from the per-IMPI function.  Maybe it's best to discuss?