and here.

is there possibly a way to write a function that can mop up all of this copy-pasted code into a single run through with a bunch of input variables? I feel like you could cut a fair number of lines for these 4 instances by combining them.