this logic seems very similar to lines 2318-2334. Can you factor out a function?