This loop code could be shared with the function above.