Merging refactored code.

Lots of bugs, but on our way to being multithreaded.