Add unit tests and refactor