Some tests and big refactor