This for-loop is repeated in a few places, maybe refactor into a function.