Added unit tests, massive refactoring