#include <stdio.h>
#include <malloc.h>
/* The SuSE 7.3 copy of jpeglib.h is missing the extern "C" !! */
extern "C" {
#include <jpeglib.h>
}
#include "dms/JPEGImage.h"

namespace dms
{

JPEGImage::JPEGImage(char *filename)
    {
    if (filename)
        loadFile(filename);
    }


void JPEGImage::loadFile(char *filename)
    {
    FILE * fp = fopen(filename, "r");
    if (!fp)
        perror(filename);
    else
        {
        unsigned long * data;
        GLsizei width, height;
        struct jpeg_decompress_struct cinfo;
        struct jpeg_error_mgr jerr;
        int buffersize, i;
        JSAMPARRAY buffer;
        cinfo.err = jpeg_std_error(&jerr);
        jpeg_create_decompress(&cinfo);
        jpeg_stdio_src(&cinfo, fp);
        jpeg_read_header(&cinfo, TRUE);
        cinfo.out_color_space = JCS_RGB;
        jpeg_start_decompress(&cinfo);
        width = cinfo.output_width;
        height = cinfo.output_height;
        data = (unsigned long *) malloc(width * height * sizeof(unsigned long));
        if (!data)
            {
            perror("JPEGImage::loadFile(): malloc");
            return;
            }
        buffersize = cinfo.output_width * cinfo.output_components;
        buffer = (*(cinfo.mem->alloc_sarray))
                    ((j_common_ptr) &cinfo, JPOOL_IMAGE, buffersize, 1);
        while (cinfo.output_scanline < cinfo.output_height)
            {
            jpeg_read_scanlines(&cinfo, buffer, 1);
            for (i=0; i < cinfo.output_width; i++)
                {
                data[i+cinfo.output_scanline*width] =
                        (*buffer)[i*3] | ((*buffer)[i*3+1] << 8) |
                        ((*buffer)[i*3+2] << 16) | 0xff000000;
                }
            }
        jpeg_finish_decompress(&cinfo);
        jpeg_destroy_decompress(&cinfo);
        fclose(fp);

        setSize(width, height);
        setData(data);
        }
    }

}
