Major rewriting. Tests are still broken, but things are under control :)