150596be83
Previous attempt in c958269 had a number of issues, this is a full
rewrite, complete with improved unit tests.
Fixes github issue #1402