Added test cases, some refactoring