Turns out the line wrapping logic is kind of ugly. I think probably a couple of helper functions would make a big difference. But it appears to work and even handles the edge cases I've currently encountered.