Fixed some test cases and done some refactoring