Fix memory problems so that all tests pass. Deal with leaks later.