#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>

#include <jpeglib.h>

#if defined(_WIN32)
#define M_PI 3.14159
#endif

void jpegRead(char *jpegName, int *width, int *height,
    unsigned char **pixels)
{
    FILE *jpegFile;
    struct jpeg_error_mgr jerr;
    struct jpeg_decompress_struct dcinfo;
    JSAMPROW rowPtr[1];
    unsigned int i, j;
    unsigned char *imgBytes;

    jpegFile = fopen(jpegName, "rb");
    if(jpegFile == NULL) {
	fprintf(stderr, "can't open \"%s\" for reading\n", jpegName);
	exit(1);
    }

    /* create error handler */
    dcinfo.err = jpeg_std_error(&jerr);

    /* set dcinfo for compression */
    jpeg_create_decompress(&dcinfo);

    /* 3 and RGB space corresponds to GL_RGB */
    dcinfo.output_components = 3;
    dcinfo.out_color_space = JCS_RGB;

    /* use jpegFile for reading image */
    jpeg_stdio_src(&dcinfo, jpegFile);

    /* read JFIF header */
    jpeg_read_header(&dcinfo, TRUE);

    jpeg_start_decompress(&dcinfo);

    imgBytes = (unsigned char *)
        malloc(dcinfo.image_height * dcinfo.image_width * 3);

    *width = dcinfo.image_width;
    *height = dcinfo.image_height;
    *pixels = imgBytes;

    if(imgBytes == NULL) {
	fprintf(stderr, "Couldn't allocate %d bytes for image data\n",
	    dcinfo.image_height * dcinfo.image_width * 3);
	exit(1);
    }


    /* read JPEG image rows */
    for(i = 0; i < dcinfo.image_height; i++) {

	/* we go bottom up because we use texcoord t=0 at bottom, t=1 at top */
	/* (could easily load top down and just reverse texcoord t's) */
	rowPtr[0] = imgBytes + (dcinfo.image_height - 1 - i) *
	    dcinfo.image_width * 3;

	if(jpeg_read_scanlines(&dcinfo, rowPtr, 1) != 1) {
	    fprintf(stderr, "Failed reading row %d\n", i);
	    exit(1);
	}
    } 

    /* If you pass in a too-big image, not sure whether Build will
      downscale as necessary or just choke... */

    jpeg_finish_decompress(&dcinfo);

    jpeg_destroy_decompress(&dcinfo);

    fclose(jpegFile);
}
