fixed serious bug and implemented semaphores