Fixing tests and refactoring