remove duplicate code, and fix global leak