Some bugs and memory laek fixes, remove duplicated codes.
- Memory leaks.
- Remove duplicated codes.
- More test cases.