/************************************************************
*   共通一般ライブラリー									*
*		全モード対応 Tiff-Loader							*
*															*
*		 0 : 正常終了										*
*		-1 : エラー											*
*		＋ : 画像モード違い	モードビット数					*
*															*
*										OKOME System 2		*
************************************************************/

#include	<stdio.h>
#include	<string.h>
#include	<EGB.H>
#include	<tifflib.h>
#include	<normlib.h>

static int xx, xx4, yy;
static FILE *fp;

static int tlog(char *buf, int lof, int ls)
{
	egbput(xx,yy+lof,xx+xx4-1,yy+lof+ls-1,buf);
	return (0);
}

static int tlog2(char *buf, int lof, int ls)
{
	egbputc(xx,yy+lof,xx+xx4-1,yy+lof+ls-1,buf);
	return (0);
}

static int tfgs(char *buf, long sz)
{
	fread(buf, 1, sz, fp);
	return (0);
}

int tiffload(char *name, int xf, int yf)
{
	int x, y, comp, fill, cm, p, p0, p1;
	long strip, clut;
	char h[4096], ak[4096], tt[DECOMP_WORK_SIZE];
	xx = xf;
	yy = yf;
	if ((fp=fopen(name,"rb"))==NULL)
		return (-1);
	fread(h,1,4096,fp);
	if (TIFF_getHead(h,4096)==-1)
	{
		fclose(fp);
		return (-1);
	}
	cm = TIFF_checkMode( &x, &y, &comp, &fill, &strip, &clut);
	EGB_getResolution(&p0,&p1);
	p = (EGB_getWritePage( 0,0 ) == 0) ? p0 : p1 ;
	EGB_getModeInfo(p,NULL,NULL,NULL,NULL,&p0);
	xx4 = x;
	if (cm==1)
		TIFF_setLoadFunc(tlog2,tfgs);
	else if ((1<<cm)==p0 || (cm==16 && p0==32768))
		TIFF_setLoadFunc(tlog,tfgs);
	else {
		fclose(fp);
		return (cm);
	}
	p0 = (cm<8) ? (4096 / ((x + 7) / 8 * cm)) : (4096 * 8 / cm / x) ;
	TIFF_loadImage( cm, x, y, strip, fill, comp, ak, x, p0, tt );
	fclose(fp);
	return (0);
}
