further refactoring and fixed tests