/*
	tifck.c
	1995/01/24
	壁紙のチェック用なので
	画像ローダーのようなきびしいチェックはしていない
*/

#include <stdio.h>

#define byte   unsigned char
#define uint   unsigned int
#define ulong  unsigned long

struct tiff_head{
	byte id[4];
	ulong ifd;
	uint tagnum;
	struct {
		uint tagid;
		uint datatype;
		ulong datanum;
		ulong data;
	}tag[16];
	byte dumm[302];
	ulong x;
	ulong y;
};

const char *bpp[] = {
	"?","2","8?","16","256","32k","Full"
};

const char *cmp[] = {
	"?","-","lzw","W"
};

/*
参考: Oh!TOWNS '94-5.6 108p.
image width                0x100 short 1      x
image length               0x101 short 1      y
bits per sample            0x102 short 1/3    画像の色数
compression                0x103 short 1      1:非圧縮 5:lzw圧縮
photometric interpertation 0x106 short 1      3: color map あり
strip offset               0x111 long  1      画像データ位置
samples per pixel          0x115 short 1      3:full color 1:not full color
planer configuration       0x11c short 1      1:固定
color map                  0x140 shrot 48/768 パレットデータ
*/

int tifck( char *fn, byte p ){
/*
	fn : ファイルパス
	p  : 'p' で チェック出力
*/

	FILE *fp;
	struct tiff_head tifh;
	int i,x,y;
	int re,fc,c,b;

	re = fc = c = b = 0;

	fp = fopen( fn,"rb" );
	if( fp == NULL ){
		fputs("file open err.",stderr);
		return ( -1 );
	}
	fread(&tifh,sizeof(struct tiff_head),1,fp);
	fclose(fp);

/*
	printf("header size: %d\n",sizeof(struct tiff_head));
	printf("header id  : %02x%02x%02x%02x\n",
	tifh.id[0],tifh.id[1],tifh.id[2],tifh.id[3]);
*/
	if( tifh.id[0] != 0x49 || 
	    tifh.id[1] != 0x49 || 
	    tifh.id[2] != 0x2a || 
	    tifh.id[3] != 0x00 ||
	    tifh.ifd   != 0x08    ) {
		if( p == 'p' )
		printf("%s ... [%02x/%02x/%02x/%02x/%d] unknown type.\n",
			fn, tifh.id[0], tifh.id[1], tifh.id[2], tifh.id[3],
			tifh.ifd );
	    	return re;
	}

	for( i = 0 ; i < tifh.tagnum ; i++ ){
		switch (tifh.tag[i].tagid) {
		case 0x100:
			x = tifh.tag[i].data; break;
		case 0x101:
			y = tifh.tag[i].data; break;
		case 0x102:
			if(tifh.tag[i].datanum==3) b = 6 ;
			else
			switch (tifh.tag[i].data ) {
			case  1: b = 1 ; break; /*   2 */
			case  2: b = 2 ; break; /*  ?8 */
			case  4: b = 3 ; break; /*  16 */
			case  8: b = 4 ; break; /* 256 */
			case 16: b = 5 ; break; /* 32k */
			}
			break;
		case 0x103:
			switch (tifh.tag[i].data) {
			case 1: c = 1 ; break;
			case 5: c = 2 ; break;
			}
			break;
		case 0x115:
			fc = tifh.tag[i].data; break;
		case 0x104:
		default:
			;
		}
	}

	b = ( b == 6 && fc == 3 ) ? 6 : b ;

	/* 戻り値は、16色壁紙:1 32k色壁紙:2 それ以外:0 */
	re = ( c == 1 && fc == 1 ) ? (
		( x == 640 && y == 480 && b == 3 ) ? 1 : (
		( x == 320 && y == 240 && b == 5 ) ? 2 : 0
	     )) : 0 ;

	if( p == 'p' )
		printf("%s ... x:%d y:%d %s %s\n",
			fn, x, y, bpp[b], cmp[( re != 0 ? 3 : c )] );
	return re;
}
