#include "imgtex.h"

// Apple's annoying non-standard include locations
#if defined(__APPLE__) || defined(MACOSX)
#include <OpenGL/glu.h>
#include <CoreServices/CoreServices.h>
#include <QuickTime/QuickTime.h>
#else
#include <GL/glu.h>
#include <QuickTime.h>		// Untested: I have no clue if this is correct
#endif

#include <string>
#include <memory>

void loadIMG(std::string fname, int texUnit)
{
    // Create file spec
    FSRef fr;
    FSSpec fs;
    Boolean dir;
    if (FSPathMakeRef((const UInt8*)(fname.c_str()),&fr,&dir) != noErr ||
	dir ||
	FSGetCatalogInfo(&fr,kFSCatInfoNone,0,0,&fs,0) != noErr) {
	
	fprintf(stderr,"Error opening %s\n",fname.c_str());
	return;
    }

    // get file info
    GraphicsImportComponent gc;
    GetGraphicsImporterForFile(&fs, &gc);
    ImageDescriptionHandle id=(ImageDescriptionHandle)NewHandle(
	sizeof(ImageDescriptionHandle));
    GraphicsImportGetImageDescription(gc,&id);
    int w=(*id)->width;		// image width
    int h=(*id)->height;	// image height
    int c=((*id)->depth+7)/8;	// bytes per pixel

    // flip vertically
    Rect r = {w,h,0,0};
    GraphicsImportSetBounds(gc, &r);
    GraphicsImportSetQuality(gc,codecLosslessQuality);

    // create image block
    std::auto_ptr<char> imdata(new char[w*h*c]);
    GWorldPtr gw; Rect wr = {0,0,w,h};
    printf("%s:%d\n", __FILE__,__LINE__);

    // import
    printf("%s:%d\n", __FILE__,__LINE__);
    LockPixels(GetGWorldPixMap(gw));
    printf("%s:%d\n", __FILE__,__LINE__);
    GraphicsImportDraw(gc);
    printf("%s:%d\n", __FILE__,__LINE__);
    UnlockPixels(GetGWorldPixMap(gw));
    printf("%s:%d\n", __FILE__,__LINE__);

    // clean up
    DisposeGWorld(gw);
    printf("%s:%d\n", __FILE__,__LINE__);
    CloseComponent(gc);
    printf("%s:%d\n", __FILE__,__LINE__);
    SetGWorld(origPort, origDevice);
    printf("%s:%d\n", __FILE__,__LINE__);

    // load into texture
    GLenum formats[] = {0,GL_LUMINANCE,GL_LUMINANCE_ALPHA,GL_RGB,GL_RGBA};
    glActiveTexture(GL_TEXTURE0 + texUnit);
    glBindTexture(GL_TEXTURE_2D,texUnit+1);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    gluBuild2DMipmaps(GL_TEXTURE_2D,c,w,h,formats[c],
		      GL_UNSIGNED_BYTE, imdata.get());
    glEnable(GL_TEXTURE_2D);
}


void dumpIMG(std::string fname, int x, int y, int w, int h)
{
//     // get data
//     std::auto_ptr<png_byte> imdata(new png_byte[w*h*3]);
//     std::auto_ptr<png_byte*> imrow(new png_byte*[h]);
//     for(int i=0; i<h; ++i)
// 	imrow.get()[i] = imdata.get()+(h-1-i)*w*3;
//     glPixelStorei(GL_PACK_ALIGNMENT,1);
//     glReadPixels(x,y,w,h,GL_RGB,GL_UNSIGNED_BYTE,imdata.get());

//     // create file
//     FILE *fp = fopen(fname.c_str(), "wb");
//     if (!fp) {
// 	perror(fname.c_str());
// 	return;
//     }

//     // initialize stuff
//     png_structp imgp = png_create_write_struct(PNG_LIBPNG_VER_STRING,0,0,0);
//     png_infop infop = png_create_info_struct(imgp);
//     png_init_io(imgp, fp);
//     png_set_IHDR(imgp, infop, w, h,
// 		 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
// 		 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

//     // write file
//     png_write_info(imgp, infop);
//     png_write_image(imgp, imrow.get());
//     png_write_end(imgp, NULL);
//     fclose(fp);
}
