Lots of debugging and new unit tests, results in something which seems
to perform as specified.