Fixed most of the memory leaks and started working on correctly exiting the thread