Some fixes (tests are broken now).
Some cleanup and refactoring.