Add some tests and refactor