/*********************************************************************
*                                                                    *          
*                              FLY                                   *
*                           --E#Y#E--				                 *
*                         ===MUSCLE===                               *
*                                                                    *
*********************************************************************/
/* Header Files */
#include "texture.h"

PNG png1;

//---------------------------------------------------------------------------

/* Init PNG Reader */
void PNG::init_png(png_structp *png_ptr, png_infop *info_ptr)
{
	/* Read Struct */
	*png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
	if(*png_ptr == NULL)
	{
		*info_ptr = NULL;
		exit(0);
	}
	/* Create Struct */	
	*info_ptr = png_create_info_struct(*png_ptr);
	if(*info_ptr == NULL)
	{
		png_destroy_read_struct(png_ptr, NULL, NULL);
		exit(0);
	}
	/* Free Memory */
	if(setjmp(png_jmpbuf(*png_ptr))) 
	{
		png_destroy_read_struct(png_ptr, info_ptr, NULL);
		exit(0);
	}
}

//---------------------------------------------------------------------------

/* Read PNG Texture */
void PNG::read_png(const char *name, unsigned char **Data)
{
	/* PNG Init */	
	png_structp png_ptr;
	png_infop info_ptr;
	png_bytepp row_pointers;
	png_uint_32 width, height;
	int bit_depth, color_type, interlace_type;
	int pixel, row_bytes, row;
	FILE *fp;

	/* File Open */		
	fp = fopen(name, "rb");

	/* PNG Reader */
	png1.init_png(&png_ptr, &info_ptr);

	/* PNG Reader */
	png_init_io(png_ptr, fp);
	png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY  | 
		PNG_TRANSFORM_EXPAND | PNG_TRANSFORM_BGR ,NULL);
	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
       			&interlace_type, NULL, NULL);

	/* Row Bytes */
	pixel = 128;
	row_bytes = png_get_rowbytes(png_ptr, info_ptr);
	*Data = (unsigned char*) malloc(row_bytes * pixel);
	row_pointers = png_get_rows(png_ptr, info_ptr);	
	
	/* For Loop */
	for (row = 0; row < pixel; row++) 
	{
 		memcpy(*Data+(row_bytes*(pixel-1-row)),row_pointers[row],row_bytes);
	}

	/* Destroy Struct */
	png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
	
	/* File Close */
	fclose(fp);
}

//---------------------------------------------------------------------------

