#include "common.h"
#include "gfx.h"

extern SCENESWARM sceneswarm;

bool redraw = false;

void do_logic()
{
  redraw = false;
  sceneswarm.process();
  redraw = true;
}

bool init()
{
  /// randomise
  srand(time(NULL));

  //signal(11, shutdown_exception);
  //atexit(exiting);

  init_gfx();
  //SDL_SetTimer((6/10)*10), do_logic);
  
  cout << "Init complete." << endl;
}

int main(int argc, char **argv)
{
  init();
  //int prevTime;

  SDL_Event event;
  bool redraw = true;

  static double lastFrameTime = 0.0;
  static double cyclesLeftOver = 0.0;
  double currentTime;
  double updateIterations;

  while (1)
  {
    while(SDL_PollEvent(&event))
    {
      if(event.type == SDL_QUIT) {
          return 0;
      }
      else
      {
        currentTime = SDL_GetTicks();
        updateIterations = ((currentTime - lastFrameTime) + cyclesLeftOver);
        
        if (updateIterations > (MAX_CYCLES_PER_FRAME * UPDATE_INTERVAL))
        {
          updateIterations = (MAX_CYCLES_PER_FRAME * UPDATE_INTERVAL);
        }

        while (updateIterations > UPDATE_INTERVAL)
        {
          updateIterations -= UPDATE_INTERVAL;
          do_logic(); /* Update game state a variable number of times */
          redraw = true;
        }

        cyclesLeftOver = updateIterations;
        lastFrameTime = currentTime;
        
        if (redraw) do_gfx();
        redraw = false;
      }
    }
  }

  return 0;
}
