Rearrange final loop to (hopefully) avoid race condition