#include <EDK.h>
#include "General.h"
#include "Sound.h"


// constructor
NoSound::NoSound(int iC64ClockFrequency) {

  // calculate number of PC clocks per C64 clock
  LARGE_INTEGER PCClocks;
  win(QueryPerformanceFrequency(&PCClocks));
  assert(PCClocks.HighPart == 0);
  dPCClocksPerC64Clock = (double)PCClocks.LowPart / (double)iC64ClockFrequency;

  // get current times for C64 and PC
  extern Clock* gpClock;
  iC64Clocks = gpClock->GetClocks();
  win(QueryPerformanceCounter(&PCClocks));
  iPCClocks = PCClocks.LowPart;

}


// synchronize to 100% and tell whether to display the next frame or not
flag NoSound::Synchronize() { 

  // calculate expected PC time
  extern Clock* gpClock;
  int iNewC64Clocks = gpClock->GetClocks();
  iPCClocks += (int)((iNewC64Clocks - iC64Clocks) * dPCClocksPerC64Clock);
  iC64Clocks = iNewC64Clocks;

  // get real PC time
  LARGE_INTEGER PCClocks;
  win(QueryPerformanceCounter(&PCClocks));

  // calculate clock difference
  int iDelta = iPCClocks - PCClocks.LowPart;

  // wait on fast computers
  if (iDelta > 70000) {
    do {
      Sleep(0);
      QueryPerformanceCounter(&PCClocks);
    } while (iPCClocks - (int)PCClocks.LowPart > 70000);

  // limit time for reaching 100% again after temporary delays
  } else if (iDelta < -50000) {
    iPCClocks = PCClocks.LowPart - 50000;
  }

  // display the next frame or not
  return iDelta > 0;

}

// get description for display
const char* NoSound::GetDescription() {
  return "NoSound";
}
