whoops. fix memory leak, and fix bug in nicer way