Slight modifications
Multithreaded version which works.