Cleaned up code in view of multithreading