This function is long, and somewhat hard to read. Would it make sense to break it up into small functions? For readability, more than for code reuse? 

If you disagree, that's fine. I'll merge because the change looks good otherwise. My comment is more personal preference than anything else.