#include "project.h"

void JPG_LoadJPG3(char *filename, JPG_File* image)
{
	unsigned char *JPG_FileBuffer;
	unsigned long JPG_FileBufferSize;
	JPEG_CORE_PROPERTIES *jcprops;

	jcprops = new JPEG_CORE_PROPERTIES;
	memset(jcprops,0,sizeof(jcprops));
	if (image==NULL) image = new JPG_File;
	memset(image,0,sizeof(JPG_File));

	if (ijlInit(jcprops)!=IJL_OK) 
	{
		MessageBox(NULL,"ijlInit error","Error",MB_OK);
		exit(1);
	}

	FILE *infile;
	infile=fopen(filename,"rb");

	if (infile == NULL)
	{
		char errstr[256];
		sprintf(errstr,"Error while loading textures!\n\'%s\' not found!",filename);
		MessageBox(NULL,errstr,"ERROR",MB_OK);
		exit(1);
	}

	JPG_FileBufferSize=GetFileSize(filename);
	JPG_FileBuffer=(unsigned char*)malloc(JPG_FileBufferSize);
	fread(JPG_FileBuffer,JPG_FileBufferSize,1,infile);
	fclose(infile);

	jcprops->JPGBytes=JPG_FileBuffer;
	jcprops->JPGSizeBytes=JPG_FileBufferSize;
	if (ijlRead(jcprops,IJL_JBUFF_READPARAMS)!=IJL_OK) 
	{
		MessageBox(NULL,"ijlRead error","Error",MB_OK);
		exit(1);
	}

	image->width=jcprops->JPGWidth;
	image->height=jcprops->JPGHeight;

	if (jcprops->JPGChannels!=3)
	{
		char s[256];
		sprintf(s,"Error while loading %s!\nImage BPP is not suitable!\nRequired BPP: 24bpp",filename);
		MessageBox(NULL,s,"Error",MB_OK);
		exit(1);
	}

	if (image->image!=NULL) delete [] image->image;
	image->image=(unsigned char*)malloc(image->width*image->height*3);
	if (image->image==NULL)
	{
		MessageBox(NULL,"malloc error","Error",MB_OK);
		exit(1);
	}
	jcprops->DIBColor=IJL_RGB;
	jcprops->JPGColor=IJL_YCBCR;

	jcprops->UseJPEGPROPERTIES=0;
	jcprops->DIBBytes=(unsigned char*)image->image;
	jcprops->DIBWidth=jcprops->JPGWidth;
	jcprops->DIBHeight=jcprops->JPGHeight;
	jcprops->DIBPadBytes=0;
	jcprops->DIBChannels=jcprops->JPGChannels;

	if (ijlRead(jcprops,IJL_JBUFF_READWHOLEIMAGE)!=IJL_OK) 
	{
		MessageBox(NULL,"ijlRead error","Error",MB_OK);
		exit(1);
	}

	if (ijlFree(jcprops)!=IJL_OK) 
	{
		MessageBox(NULL,"ijlFree error","Error",MB_OK);
		exit(1);
	}

	free(JPG_FileBuffer);

	delete jcprops;
}

void JPG_LoadJPG4(char *f_image, char *f_alpha, JPG_File* image)
{
	JPG_File prgb,pa;
	JPG_LoadJPG3(f_image,&prgb);
	JPG_LoadJPG3(f_alpha,&pa);
	image->width=prgb.width;
	image->height=prgb.height;
	image->image=new byte [image->width*image->height*4];
	tx_CreateRGBA(prgb.image,pa.image,image->image,prgb.width,prgb.height);
}

unsigned int JPG_UploadJPG3(char filename[])
{
	unsigned int ret;
	JPG_File img;
	JPG_LoadJPG3(filename,&img);
	ret=tx_UploadTexture3(img.image,img.width,img.height);
	delete [] img.image;
	return ret;
}

unsigned int JPG_UploadJPG4(char pic[], char alpha[])
{
	JPG_File img;
	JPG_LoadJPG4(pic,alpha,&img);
	return tx_UploadTexture4(img.image,img.width,img.height);
}