re-wrote some emaphore code and added mutexes