Refactoring, new tests and corrections