Significant refactoring, added test case.