// Utilities for converting image format
//

#include "stdafx.h"
#include "FreeImage.h"

#include <stdio.h>
#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <malloc.h>

int errmsg(const char* msg, int val)
{
//	fprintf(stderr, "%s\n", msg);
	return val;
}

FREE_IMAGE_FORMAT image_Format_for_Name(const char* fname)
{// get image format from its extend filename
	char ename[8];
	size_t len, k;
	
	len = strlen(fname);
	k = len - 1;
	while( (k>0) && (fname[k] != '.') ) k--;
	if( k == 0 )
	{
//		fprintf(stderr, "Invalid image filename!\n");
		return FIF_UNKNOWN;
	}

	memset(ename, 0, 8);
	strncpy(ename, fname+k+1, 7);
	strlwr(ename);
	
	if( strcmp(ename, "bmp") == 0 ) return FIF_BMP;
	if( strcmp(ename, "jpg") == 0 ) return FIF_JPEG;
	if( strcmp(ename, "jpeg") == 0 ) return FIF_JPEG;
	if( strcmp(ename, "gif") == 0 ) return FIF_GIF;
	if( strcmp(ename, "png") == 0 ) return FIF_PNG;
	if( strcmp(ename, "psd") == 0 ) return FIF_PSD;
	if( strcmp(ename, "tiff") == 0 ) return FIF_TIFF;
	if( strcmp(ename, "jng") == 0 ) return FIF_JNG;
	if( strcmp(ename, "iff") == 0 ) return FIF_IFF;
	if( strcmp(ename, "ico") == 0 ) return FIF_ICO;
	if( strcmp(ename, "wbmp") == 0 ) return FIF_WBMP;

	return FIF_UNKNOWN;
}

char* changeExtName(const char* fname, const char* ext)
{
	size_t len, k;
	char *tmp;

	len = strlen(fname);
	k = len - 1;
	while( (k>0) && (fname[k] != '.') ) k--;
	if( k == 0 )
	{
//		fprintf(stderr, "Invalid image filename!\n");
		return NULL;
	}

	len = k + strlen(ext) + 2;
	tmp = (char*)malloc( len );
	memset(tmp, 0, len);
	strncpy(tmp, fname, k);
	strcat(tmp, ".");
	strcat(tmp, ext);
	return tmp;
}

int ismatched(const char* fname, const char* ffmt)
{
	size_t k, n;

	n = strlen(ffmt);
	for(k=0; k<16; k++)
	{
		if(fname[k] != ffmt[0]) continue;
		if( strncmp(fname+k, ffmt, n) ) continue;
		return 1;
	}

	return 0;
}

FREE_IMAGE_FORMAT image_Format_for_Data(const char* fname)
{
	char ident[16];
	int fd;

	memset(ident, 0, 16);
	fd = open(fname, O_RDONLY|O_BINARY);
	if( fd > 0 ) read(fd, ident, 15);
	else return FIF_UNKNOWN;
	close(fd);

	if( ismatched(ident, "WBM") ) return FIF_WBMP;
	if( ismatched(ident, "BM") ) return FIF_BMP;
	if( ismatched(ident, "JFIF") ) return FIF_JPEG;
	if( ismatched(ident, "GIF") ) return FIF_GIF;
	if( ismatched(ident, "PNG") ) return FIF_PNG;
	if( ismatched(ident, "PSD") ) return FIF_PSD;
	if( ismatched(ident, "TIFF") ) return FIF_TIFF;
	if( ismatched(ident, "JNG") ) return FIF_JNG;
	if( ismatched(ident, "IFF") ) return FIF_IFF;
	if( ismatched(ident, "ICO") ) return FIF_ICO;

	return FIF_UNKNOWN;
}
