Clean up code and add multithreading.