Final refactoring, fixes