#include "SDL.h"
#include <stdlib.h>

int x_off = -512;
int y_off = -384;
int c = 1;
int handle_key(SDLKey k){
  switch(k) {
  case SDLK_ESCAPE:
    return 1;
  case SDLK_DOWN:
    y_off--;
    break;
  case SDLK_UP:
    y_off++;
    break;
  case SDLK_LEFT:
    x_off--;
    break;
  case SDLK_RIGHT:
    x_off++;
    break;
  }
  return 0;
}

void draw(SDL_Surface * screen) {
  int x, y;
  int index=0;
  int * pixels;
  /* locking the surface gives us access to 
     surface->pixels, which can be thought of as an array.
     Since the res is 1024*768, and 32 bpp,
     treating it as an int* (32 bits) gives us a the
     pixel for x,y at [y*1024+x].
  */
  SDL_LockSurface(screen);
  pixels = screen->pixels;
  for(y=0;y<768;y++) {
    for(x=0;x<1024;x++) {
      pixels[index] = (x+x_off) * ((y+y_off)) *c;
      index++;
    }
  }
  /* When we are done drawing, its
     very important to unlock the surface 
  */
  SDL_UnlockSurface(screen);
}

void eventLoop(SDL_Surface * screen) {
  SDL_Event event;
  while(1) {
    /* This function returns 0 if no
       events are pending, 1 (and fills in event)
       if one is*/
    while (SDL_PollEvent(&event)) {
      switch (event.type) {
	/* We only care about key presses for this */
      case SDL_KEYDOWN:
	if(handle_key(event.key.keysym.sym)){
	  return;
	}
	break;

      }
    
    }/* input event loop*/
    c++;
    draw(screen);
    /* since its double buffered, make
       the changes show up*/
    SDL_Flip(screen);
    /* Wait 10 ms between frames*/
    SDL_Delay(10);
  }

}



int main(void) {
  /* Initalize SDL - for this demo,
     we only are using the video stuff..
     if you are doing sound, you would do
     SDL_INIT_VIDEO | SDL_INIT_AUDIO
     you can also do timers, cdrom, joystick-
     see man page :)
  */
  SDL_Init(SDL_INIT_VIDEO );
  /* Set the screen resolution: 1024x768, 32 bpp
     We also want to do full screen, double-buffered,
     and have the surface in video hardware */
  SDL_Surface * screen = SDL_SetVideoMode(1024, 
					  768, 
					  32, 
					  SDL_HWSURFACE |
					  SDL_DOUBLEBUF |
					  SDL_FULLSCREEN);
  /* make it so that holding down a key repeats it*/
  SDL_EnableKeyRepeat(10,10);
  
  if(screen == NULL) {
    fprintf(stderr, "Can't inialtize video\n");
    SDL_Quit();
    return EXIT_FAILURE;
  }
  eventLoop(screen);
  /* cleanup SDL- return to normal screen mode,
     etc */
  SDL_Quit();
  return EXIT_SUCCESS;
}

