Fix memory leaks and refactor some code
Allow zero-length value contents