#include <stdio.h>
#include "img.h"

int
load_img_file(char *fileName, HNImage *hImg, int dpi_override)
{
	HNImage hImage;
	HNImage hGrayscale;
	NResult ret;
	NFloat hres;
	NFloat vres;

	// Load image of supported type (type determined by file name extension)
	ret = NImageCreateFromFile(fileName, NULL, &hImage);
	if (NFailed(ret))
	{
		printf("NImageCreateFromFile() failed: %d\n", ret);
		return -1;
	}

	if (dpi_override > 0)
	{
		// Use specified DPI
		hres = (NFloat)dpi_override;
		vres = (NFloat)dpi_override;
	}
	else
	{
		// Use DPI from file
		ret = NImageGetHorzResolution(hImage, &hres);
		if (NFailed(ret))
		{
			printf("NImageGetHorzResolution() failed %d\n", ret);
			NImageFree(hImage);
			return -1;
		}

		ret = NImageGetVertResolution(hImage, &vres);
		if (NFailed(ret))
		{
			printf("NImageGetHorzResolution() failed %d\n", ret);
			NImageFree(hImage);
			return -1;
		}

		if (hres < 250)
		{
			printf("Bad horizontal resolution %f dpi\n", hres);
			return -1;
		}

		if (vres < 250)
		{
			printf("Bad vertical resolution %f dpi\n", vres);
			return -1;
		}
	}

	// Convert Image to grayscale
	//	ret = NImageCreateFromImage(npfGrayscale, 0, hImage, &hGrayscale);

	// Convert image to grayscale (with overrided resolution)
	ret = NImageCreateFromImageEx(npfGrayscale, 0, hres, vres, hImage, &hGrayscale);
	if (NFailed(ret))
	{
		printf("NImageCreateFromImgeEx() failed: %d\n", ret);
		NImageFree(hImage);
		return -1;
	}

	NImageFree(hImage);


	*hImg = hGrayscale;
	return 0;
}
