FYI I've replaced this implementation with a more elegant solution. The change is in a local branch I'll submit a PR for once this PR is merged.