Multithreaded and fixed memory leaks in BuildDatabase