/*
 * gcc exrconv.c -Wall -I/usr/local/include/ -L/usr/local/lib -lIlmImf -pthread -ggdb -lgd -lpng -DTEST
 */

#include <stdio.h>
#include <string.h>
#include <OpenEXR/ImfCRgbaFile.h>


typedef struct
{ 
	int width;
	int height;
	ImfRgba *pixels;
} ExrData;


ExrData *load_exr(const char *fn)
{
	ImfInputFile *img;
	ImfRgba *buf;
	const ImfHeader *header;
	int xmin, xmax, ymax, ymin, y;
	ExrData *d;

	d = malloc(sizeof(ExrData));

	img = ImfOpenInputFile(fn);
	header = ImfInputHeader(img);
	ImfHeaderDataWindow(header, &xmin, &ymin, &xmax, &ymax);
	d->width = xmax - xmin + 1;
	d->height = ymax - ymin + 1;

	buf = malloc(d->width * sizeof(ImfRgba));
	d->pixels = calloc(d->width * d->height, sizeof(ImfRgba));

	for (y = 0; y < d->height; y++)
	{
		ImfInputSetFrameBuffer(img, buf - (y * d->width), 1, d->width);
		ImfInputReadPixels(img, y, y);
		memcpy((void *)&d->pixels[y * d->width], (const void *)buf, d->width * sizeof(ImfRgba));
	}

	free(buf);
	ImfCloseInputFile(img);

	return d;
}
	

#ifdef TEST
#include <gd.h>

#define F(x)	(((x) * 255) / 65536)

int main(int argc, char **argv)
{
	ImfRgba *p;
	gdImagePtr im;
	FILE *fp;
	int white, x, y;
	ExrData *d;
	
	d = load_exr(argv[1]);
	printf("%s: %d x %d\n", argv[1], d->width, d->height);

	im = gdImageCreateTrueColor(d->width, d->height);
	white = gdImageColorAllocate(im, 255, 255, 255);
	gdImageFilledRectangle(im, 0, 0, d->width, d->height, white);

	for (y = 0; y < d->height; y++)
	{
		for (x = 0; x < d->width; x++)
		{
			p = &d->pixels[y * d->width + x];
			gdImageSetPixel(im, x, y, gdImageColorAllocate(im, F(p->r), F(p->g), F(p->b)));
		}
	}

	fp = fopen("exr-test-out.png", "w");
	gdImagePng(im, fp);
	fclose(fp);
	gdImageDestroy(im);
	
	free(d->pixels);
	free(d);

	return 0;
}
#endif

