Add test case and refactor codes