refactoring, fixes and tests