Initial code refactoring.
Trying to fix threading issues on multi-CPU computers.