threading and memory-leak fixes