I'm working on a bugfix in this area, and it took me quite a while to
understand the logic. So I added a bunch of comments, renamed a few
things and split off a few smaller functions.
@Bastien Montagne (mont29), just wanted to check that you are ok with these name changes
since this is not my area.