I get a feeling it's time to split this code into smaller bits.  It's getting hard to understand.