Added guards against spurious wakeup and fixed a bug.