Fix recent pull by refactoring the code a bit and fixing failing tests.