I don't have time to go insane today, so I have tried not to look at the code directly. But, "hundreds of distinct cases" would cause me to reach for a data-directed method using a lookup table or other decision-tree data structure.
The way I'm reading this code is that the cases aren't that distinct. Look at lines 4367 to 4390 and you see 23 distinct cases that could be handled by a range and Mod 3.