Fix a few races

Fixes several race conditions and cleans up the code a bit.

Apologies for the bulk indentation fixes, but the old code had rather inconsistent indentation and thus was quite difficult to read.