Add unit tests, code refacotring