I'd like to see tests for this, since there is so much opportunity to be wrong in the code below.  Can you write those first before we land this?