Patch Set 5:

Woo hoo, I managed to sneak away to work on this for a little bit! :)

This should fix all of the style issues Shawn mentioned in the previous one.  I'm still relatively confident that the basic algorithm in this version will work right, but I'd really appreciate some review on that--there are a lot of weird edge cases.