#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "SDL.h"
#include "SDL_image.h"

#define WIDTH 640
#define HEIGHT 480
#define RESOLUTION 16
#define TITLE "Bouncy Ball"
#define CHECKNULL(x) if (x == NULL) {  fprintf (stderr, "Error: Func returned NULL, %s\n",SDL_GetError()); exit(-1); } ;


SDL_Surface *loadImage(char *file);

SDL_Surface *screen;
SDL_Surface *bitmap;

SDL_Event event;

int       x[3] = { 0, 15, 25 };	/* Some random x,y coordinates */
int       y[3] = { 0, 37, 42 };

int       xvel[3] = { 5, 10, 15 };	/* An array of X and Y Velocities */
int       yvel[3] = { 15, 10, 5 };

int main()
{
	SDL_Rect  dest;
	int       i;


	if (SDL_Init(SDL_INIT_VIDEO) < 0) {	/* Initialize the SDL Video only, exit on error */
		fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
		exit(-1);
	}

	atexit(SDL_Quit);


	screen = SDL_SetVideoMode(WIDTH, HEIGHT, RESOLUTION, SDL_HWSURFACE | SDL_DOUBLEBUF);	/* Create a Hardware, Double Buffered, Window  */
	CHECKNULL(screen);	/* Check screen for NULL and exit if so */

	SDL_WM_SetCaption(TITLE, NULL);	/* Set our Window Title */


	bitmap = loadImage("mefile.png");
	while (1) {

		/* Clear Screen to 0,0,0 - Black */
		SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0, 0, 0));
		dest.w = bitmap->w;
		dest.h = bitmap->h;


		for (i = 0; i < 3; i++) {	/* Looks kinda nasty , but it just loops 3 times and blits the circle to the screen 3 times with different coordinates */


			dest.x = x[i];
			dest.y = y[i];

			SDL_BlitSurface(bitmap, NULL, screen, &dest);

			x[i] = x[i] + xvel[i];
			y[i] = y[i] + yvel[i];

			if ((x[i] + bitmap->w) > WIDTH || x[i] < 0) {	/* If we are about to draw the ball off the screen, negate the velocity (looks like it bounces ) */
				xvel[i] = -1 * xvel[i];
				x[i] = x[i] + xvel[i];
			}
			if ((y[i] + bitmap->h) > HEIGHT || y[i] < 0) {	/* Same here */
				yvel[i] = -1 * yvel[i];
				y[i] = y[i] + yvel[i];
			}
		}





		SDL_Flip(screen);
		while (SDL_PollEvent(&event)) {
			switch (event.type) {
			case SDL_KEYDOWN:
				switch (event.key.keysym.sym) {
				case SDLK_ESCAPE:
					exit(0);
					break;

				default:
					break;
				}
				break;

			case SDL_QUIT:
				exit(0);
			}
		}


	}

	return 0;
}

SDL_Surface *loadImage(char *file)
{
	SDL_Surface *bitmap;

	bitmap = IMG_Load(file);

	if (bitmap == NULL) {
		fprintf(stderr, "Can't load %s: %s\n", file, SDL_GetError());
		exit(1);
	}

	return bitmap;
}
