Add tests and refactor the main source code