Added tests, and refactoring