#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <io.h>
#include <set>
#include <map>
#include <iostream>

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

using namespace std;

void stripExtension(string& filename)
{
	filename.erase(filename.size()-1,1);
	filename.erase(filename.size()-1,1);
	filename.erase(filename.size()-1,1);
	filename.erase(filename.size()-1,1);
}

void readFiles(set<string> &textures, set<string> &pixels, string extension)
{
	struct _finddata_t file;
	intptr_t hFile;

	if( (hFile = _findfirst( ("textures/*." + extension).c_str(), &file )) != -1L ) {
		do {
			string filename(file.name);
			stripExtension(filename);
			string end = filename.substr(filename.size() - 2,2);
			if(end == "_p") {				
				filename.erase(filename.size()-1,1);
				filename.erase(filename.size()-1,1);
				pixels.insert(filename);
			}
			else 
				textures.insert(filename);
		}
		while( _findnext( hFile, &file ) == 0 );

		_findclose( hFile );
	}
}

void checkCollisions(map<Uint32,string> &colors, set<string> &pixels, string extension, SDL_PixelFormat *&fmt)
{
	for(set<string>::iterator filename = pixels.begin(); filename != pixels.end(); filename++) {
		// http://manuals.thexdershome.com/SDL-1.2.5/html/sdlpixelformat.html
		SDL_Surface* surface = IMG_Load(("textures/" + *filename + "_p." + extension).c_str());
		Uint32 pixel;

		fmt=surface->format;
		SDL_LockSurface(surface);
		pixel=*((Uint32*)surface->pixels);
		SDL_UnlockSurface(surface);

		if(colors.find(pixel) != colors.end())
			cerr << "Collision found: " << ("textures/" + (*colors.find(pixel)).second + "_p." + extension + " and ")
										<< ("textures/" + *filename + "_p." + extension + "\n");
		else 
			colors[pixel] = *filename;
		SDL_FreeSurface(surface);
	}
}



int main(int argc,char *argv[])
{

	set<string> texturesPNG;
	set<string> pixelsPNG;
	set<string> texturesBMP;
	set<string> pixelsBMP;

	readFiles(texturesPNG,pixelsPNG,"png");
	readFiles(texturesBMP,pixelsBMP,"bmp");

	map<Uint32,string> colors;
	SDL_PixelFormat *fmt = NULL;

	checkCollisions(colors,pixelsPNG,"png",fmt);
	checkCollisions(colors,pixelsBMP,"bmp",fmt);

	return 1;
}


