Added some unit test and did some refactoring in the process