Unit tests and overall refactoring