Minor refactoring, fix potential memory leak