Refactored to support multithreading.