There's still a lot of overlap between these 3 loops. Can we consolidate the content of those loops into a function?