Add code that fixes tests and refactor quite a lot of the existing code