Fixing tests and some refactoring