Multiple changes to make program multi-threaded. This isn't working yet,
but the single-threaded version of the code is ok.