Got rid of a couple race conditions and cleaned up the code