Working, non multithreaded version. Refactored.