+void AdjustLastToggleCycles(uint64 elapsedCycles)
+{
+#if 0
+ if (!soundInitialized)
+ return;
+
+ SDL_mutexP(mutex2);
+ lastToggleCycles += elapsedCycles;
+ SDL_mutexV(mutex2);
+
+// We should also fill the buffer here as well, even if the speaker
+// didn't toggle... !!! FIX !!!
+#else
+/*
+BOOKKEEPING
+
+We need to know the following:
+
+ o Where in the sound buffer the base or "zero" time is
+ o At what CPU timestamp the speaker was last toggled
+ NOTE: we keep things "right" by advancing this number every frame, even
+ if nothing happened! That way, we can keep track without having
+ to detect whether or not several frames have gone by without any
+ activity.
+
+How to do it:
+
+Every time the speaker is toggled, we move the base or "zero" time to the
+current spot in the buffer. We also backfill the buffer up to that point with
+the old toggle value. The next time the speaker is toggled, we measure the
+difference in time between the last time it was toggled (the "zero") and now,
+and repeat the cycle.
+
+We handle dead spots by backfilling the buffer with the current toggle value
+every frame--this way we don't have to worry about keeping current time and
+crap like that. So, we have to move the "zero" the right amount, just like
+in ToggleSpeaker(), and backfill only without toggling.
+*/
+#warning "This is VERY similar to ToggleSpeaker(); merge into common function. !!! FIX !!!"
+ if (!soundInitialized)
+ return;
+
+#ifdef DEBUG
+printf("SOUND: AdjustLastToggleCycles() start...\n");
+#endif
+ // Step 1: Calculate delta time
+ uint64 deltaCycles = elapsedCycles - lastToggleCycles;
+
+ // Step 2: Calculate new buffer position
+ uint32 currentPos = (uint32)((double)deltaCycles / CYCLES_PER_SAMPLE);
+
+ // Step 3: Make sure there's room for it
+ // We need to lock since we touch both soundBuffer and soundBufferPos
+ SDL_mutexP(mutex2);
+ while ((soundBufferPos + currentPos) > (SOUND_BUFFER_SIZE - 1))
+ {
+ // Hm.
+ // This might not empty the buffer enough, causing hash and trash. !!! FIX !!! [DONE]
+ SDL_mutexV(mutex2);//Release it so sound thread can get it,
+ SDL_CondWait(conditional, mutex);//Sleep/wait for the sound thread
+ SDL_mutexP(mutex2);//Re-lock it until we're done with it...
+
+//HMM, this doesn't need to lock or recalculate this value
+// currentPos = (uint32)((double)deltaCycles / CYCLES_PER_SAMPLE);
+ }
+
+ // Step 4: Backfill and adjust lastToggleCycles
+ // currentPos is position from "zero" or soundBufferPos...
+ currentPos += soundBufferPos;
+
+ // Backfill with current toggle state
+ while (soundBufferPos < currentPos)
+ soundBuffer[soundBufferPos++] = (uint8)sample;
+
+ SDL_mutexV(mutex2);
+ lastToggleCycles = elapsedCycles;
+#ifdef DEBUG
+printf("SOUND: AdjustLastToggleCycles() end...\n");
+#endif
+#endif
+}
+