Refactoried code and added more tests.