More refactoring, added first tests, fixes