#define STB_IMAGE_IMPLEMENTATION
#define STBI_ONLY_PNG
#include "thirdparty/stb_image.h"

#include "../platform/platform.h"
#include "image.h"


#define  PIXEL_COMPONENTS  3


SurfaceT *imageLoad(char *filename) {
	int            w;  // These unspecified ints are intentional.
	int            h;
	int            n;
	int32_t        r;
	int32_t        x;
	int32_t        y;
	SurfaceT      *i = NULL;
	SurfaceT      *t = videoSurfaceGet();
	unsigned char *raw = NULL;

	r = stbi_info(filename, &w, &h, &n);
	if (r) {
		raw = stbi_load(filename, &w, &h, &n, PIXEL_COMPONENTS);
		if (raw) {
			i = videoSurfaceCreate(w, h);
			videoSurfaceSet(i);
			n = 0;
			for (y=0; y<h; y++) {
				for (x=0; x<w; x++) {
					videoSurfacePixelSet(x, y, videoColorMake(raw[n], raw[n + 1], raw[n + 2]));
					n += PIXEL_COMPONENTS;
				}
			}
			videoSurfaceSet(t);
			stbi_image_free(raw);
		}
	}

	return i;
}
