#include <stdlib.h>
#include <png.h>
#include <stdio.h>

int generate_img(char *name, char *img, int width, int height)
{
	png_structp	png_ptr;
	png_infop	info_ptr;
	png_bytep	*image = NULL;
	int		ret = 0, i;
	FILE		*file = NULL;
	
	png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
		(png_voidp)NULL, NULL, NULL);
	if (png_ptr == NULL)
	{
		goto error;
	}

	info_ptr = png_create_info_struct(png_ptr);
	if (info_ptr == NULL)
	{
		png_destroy_write_struct(&png_ptr, NULL);
		goto error;
	}
	
	image = (png_bytep *)malloc(sizeof(png_bytep) * height);
	if (image == NULL)
	{
		goto error2;
	}

	for (i = 0; i < height; i++)
	{
		image[i] = (png_bytep)img + i * width;
	}
	
	file = fopen(name, "wb");
	if (file == NULL)
	{
		goto error3;
	}

	png_init_io(png_ptr, file);
	png_set_IHDR(png_ptr, info_ptr, width, height, 8,
			PNG_COLOR_TYPE_GRAY,
			PNG_INTERLACE_NONE,
			PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
	png_set_rows(png_ptr, info_ptr, image);
	png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
	png_destroy_write_struct(&png_ptr, &info_ptr);
	free(image);
	fclose(file);
	return ret;
error3:
	free(image);
error2:
	png_destroy_write_struct(&png_ptr, &info_ptr);
error:
	ret = -1;
	return ret;
}
