Add Unit test and refactor some code