#ifndef KOKUDO_TIFF_H___
#define KOKUDO_TIFF_H___

typedef unsigned char BYTE;
typedef unsigned long ULONG;
typedef unsigned short USHORT;

#include <stdio.h>
struct TiffColorMap{
	USHORT r;
	USHORT g;
	USHORT b;
};

class KokudoTiff;
typedef void (*onTiffStripDataCallBack)(KokudoTiff *tiff, BYTE *data, ULONG dataLen, void *userParam);

struct IFDTag;
struct IFD;
class KokudoTiff
{
	friend struct IFDTag;
	friend struct IFD;
public:	
	void load(char *path, void *userParam, onTiffStripDataCallBack cbStripData);
	ULONG width;
	ULONG height;
	TiffColorMap *colorMap;
	USHORT bitPerPixel;
	
private:
	
	inline void swapEndian(unsigned short &s){
		if(fileEndian != machineEndian){
			char *p = (char*)&s;
			char tmp = p[0];
			p[0] = p[1];
			p[1] = tmp;
		}
	}
	
	inline void swapEndian(unsigned long &l){
		if(fileEndian != machineEndian){
			char *p = (char*)&l;
			char tmp = p[0];
			p[0] = p[3];
			p[3] = tmp;
			tmp = p[1];
			p[1] = p[2];
			p[2] = tmp;
		}
	}
	
	inline USHORT readShort(FILE *fp){
		USHORT ret;
		fread(&ret, 2, 1, fp);
		swapEndian(ret);
		return ret;
	}
	
	inline ULONG readLong(FILE *fp){
		ULONG ret;
		fread(&ret, 4, 1, fp);
		swapEndian(ret);
		return ret;
	}
	
	ULONG readRational(FILE *fp){
		ULONG numerator = readLong(fp);
		ULONG denominator = readLong(fp);
		return numerator / denominator;
	}

private:
	int fileEndian;
	static int machineEndian;
	void *userParam;
};


#endif
