Replaced the snippet in the comment above with a gist, I think this diff makes the code much clearer wrt its intentions. Test suite passes without problem.