Fix several memory leaks and run some of the tests in valgrind
There were a number of memory leaks, including a severe one that caused tile data not to be freed.
Also, run some of the tests in valgrind, though admittedly this didn't catch any of the issues I fixed here.