Fixed tests and minor refactoring