Refactored the code to make it compitable with multiple threads.