Edited for multithreading.