first iteration of multithreading and memory cleanup. WIP