fixed race conditions, tidied things up