Massive refactoring and fixup of threading issues.