These loops all look the same, can they be factored out into a common function?