There's a lot of repetition between these different loops. Can we consolidate the contents of them into a function?