That last bit of the tids being assigned *outside* the if loop (so existing, not only created ones, get used) is key.
As we move this function in from custom code.