#include "stdafx.h"
#include "FreeImage.h"
#include "utilities.h"
#include "bmp2gba.h"
#include <direct.h>
#include <io.h>

#include <stdlib.h>
#include <string.h>

int img2gba(const char* image_name, const char* srcpath, const char* dstpath)
{
	FREE_IMAGE_FORMAT Img_Format = FIF_UNKNOWN;
	FIBITMAP *fimg_ptr = NULL;
	FIBITMAP *fimg_res = NULL;
	char *BmpName = NULL;
	unsigned int width, height;
	double f_width, f_height, f_scale;


	if( image_name == NULL ) return errmsg("No image filename!", -1);
	
	if( chdir(srcpath) ) return errmsg("Error file path", -1);

//	Img_Format = image_Format_for_Data(image_name);
	Img_Format = FreeImage_GetFileType(image_name);
	
	if( Img_Format == FIF_UNKNOWN ) return -2;	//errmsg("Unkown image format for the filename!", -1);
	
	fimg_ptr = FreeImage_Load(Img_Format, image_name, 0);

	fimg_ptr = FreeImage_ConvertTo24Bits(fimg_ptr);

	width = FreeImage_GetWidth(fimg_ptr);
	height = FreeImage_GetHeight(fimg_ptr);
//	fprintf(stderr, "width = %d, height = %d\n", width, height);
	if( (width > 480) || (height > 320) )
	{
		f_width = width;
		f_height = height;
		f_scale = 1.50;
		f_scale = ((f_width / height) >= f_scale) ? f_width/480 : f_height/320;
		f_width = f_width/f_scale;
		f_height = f_height/f_scale;
		fimg_res = FreeImage_Rescale(fimg_ptr, (unsigned int)f_width, (unsigned int)f_height, FILTER_BOX);
	//	fprintf(stderr, "Rescale to %d * %d\n", (unsigned int)f_width, (unsigned int)f_height);
	}else fimg_res = fimg_ptr;

	BmpName = changeExtName(image_name, "bmp");

	if( chdir(dstpath) ) return 2;	//errmsg("Error file path", -1);

	FreeImage_Save(FIF_BMP, fimg_res, BmpName, 0);
	int ret;
	ret = bmp2gba(BmpName);
	
	unlink(BmpName);
	
	return ret;
}
