Some refactoring, add some checks, fix some tests