Fix memory leak, and clean up a bit