some fixes plus refactoring