multithreaded, some refactoring, still needs more refactoring