There's a huge amount of repetition in this function. Please come up with an implementation that doesn't rely on copy/paste.