Add some tests and refactoring