#include "Png_Funcs.h"

int Open_Convert_Legend(unsigned char *Image, char *filename){
	FILE *fp = fopen(filename, "rb");
	if(!fp){
		printf("Error opening file: %s\n", filename);
		return 1;
	}
	char header[8];
	fread(&header, 1, 8, fp);
	int is_png = !png_sig_cmp((png_bytep)&header, 0, 8);
	if(!is_png){
		return 1;
	}
	png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
	if(!png_ptr){
		printf("Error creating png read structure!\n");
		return 1;
	}
	png_infop info_ptr = png_create_info_struct(png_ptr);
	if(!info_ptr){
		printf("Error creating png info struct\n");
		png_destroy_read_struct(&png_ptr,(png_infopp)NULL, (png_infopp)NULL);
		return 1;
	}
	png_set_sig_bytes(png_ptr, 8);
	png_init_io(png_ptr, fp);
	png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
	png_uint_32 height = png_get_image_height( (png_structp)png_ptr, (png_infop)info_ptr);
	png_uint_32 width = png_get_image_width( (png_structp)png_ptr, (png_infop)info_ptr);
	png_destroy_read_struct(&png_ptr,(png_infopp)NULL, (png_infopp)NULL);
	fclose(fp);
	fp = fopen(filename, "rb");
	if(!fp){
		printf("Error opening file: %s\n", filename);
		return 1;
	}
	fread(&header, 1, 8, fp);
	is_png = !png_sig_cmp((png_bytep)&header, 0, 8);
	if(!is_png){
		return 1;
	}
	png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
	if(!png_ptr){
		printf("Error creating png read structure!\n");
		return 1;
	}
	info_ptr = png_create_info_struct(png_ptr);
	if(!info_ptr){
		printf("Error creating png info struct\n");
		png_destroy_read_struct(&png_ptr,(png_infopp)NULL, (png_infopp)NULL);
		return 1;
	}
	png_set_sig_bytes(png_ptr, 8);
	png_init_io(png_ptr, fp);
	const int pixel_size = 3;
	int i;

	if (height > PNG_UINT_32_MAX/sizeof(png_byte))
		png_error (png_ptr,"Image is too tall to process in memory");
	if (width > PNG_UINT_32_MAX/pixel_size)
		png_error (png_ptr,"Image is too wide to process in memory");
	png_bytepp row_pointers = png_malloc(png_ptr, height*sizeof(png_bytep) );
	for (i=0; i<height; i++)
		row_pointers[i]=&Image[i*width*3];
	png_set_rows(png_ptr, info_ptr, row_pointers);
	png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
	row_pointers = png_get_rows(png_ptr, info_ptr);
	free(row_pointers);
	printf("png loaded: w: %u h: %u\n\n", (unsigned int)width, (unsigned int)height);
	fclose(fp);
	return 0;
}
