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

// #define DEBUG

#define	readmsb(buffer) ((buffer)[1]+256*(buffer)[0])
#define	readlsb(buffer) ((buffer)[0]+256*(buffer)[1])

void ProccessGIF(void);
void ProccessPNG(void);
void ProccessJPG(void);

FILE *file;
int width=0, height=0, quant, offset;
unsigned char buffer[32], letter, verstring[19]="$VER:img2html v0.1";

void main(argc, argv)

char *argv[];

{
	int loopcnt;

	if (argc==1) {
		printf("%s (C) Risto Mäki-Petäys\n",(verstring+5));
		printf("Usage: %s file1 [file2] [file3] ...\n",argv[0]);
		exit(0);
	}

	for(loopcnt=1;loopcnt<argc;loopcnt++) {

		#ifdef DEBUG
			printf("%s",argv[loopcnt]);
		#endif

		file=fopen(argv[loopcnt],"rb");
		if (file==NULL)
		{
			#ifdef DEBUG
				printf(": couldn't open file!\n");
			#endif
			exit(10);
		}

		// Header

		(void)fread((void *)buffer,10,1,file);
		if (!(strncmp((char *)buffer,"GIF",3))) ProccessGIF();
		if (!(strncmp((char *)buffer+1,"PNG",3))) ProccessPNG();
		if (!(strncmp((char *)buffer+6,"JFIF",4))) ProccessJPG();

		printf("<IMG SRC=\"%s\" WIDTH=%d HEIGHT=%d>\n",argv[loopcnt], width, height);

		fclose(file);
	}

	exit(0);
}

void ProccessGIF(void)
{
	#ifdef DEBUG
		printf(" seems to be GIF.\n");
	#endif

	fseek(file, 6L, SEEK_SET);
	(void)fread((void *)buffer,7,1,file);
	if(buffer[4]&0x80) {
		offset=2<<(buffer[4]&0x7);
		fseek(file, offset*3, SEEK_CUR);
	}
	do {
		(void)fread((void *)buffer,1,1,file);
		if (buffer[0] == 0x2c) {
			(void)fread((void *)(buffer+1),9,1,file);
			width=readlsb(buffer+5);
			height=readlsb(buffer+7);
		}
	} while (buffer[0]!=0x3b&&!feof(file)&&width==NULL);
}

void ProccessPNG(void)
{
	#ifdef DEBUG
		printf(" seems to be PNG.\n");
	#endif

	fseek(file, 0L, SEEK_SET);
	do {
		(void)fread((void *)buffer,1,1,file);
		if (buffer[0] == 'I') {
			(void)fread((void *)(buffer+1),3,1,file);
			if (!(strncmp((char *)buffer,"IHDR",4))) {
				(void)fread((void *)buffer,8,1,file);
				width=readmsb(buffer+2);
				height=readmsb(buffer+6);
			}
		}
	} while (!feof(file)&&width==NULL);
}

void ProccessJPG(void)
{
	#ifdef DEBUG
		printf(" seems to be JPEG.\n");
	#endif

	fseek(file, 163L, SEEK_SET);
	(void)fread((void *)buffer,4,1,file);
	height=readmsb(buffer);
	width=readmsb(buffer+2);
}

/*
JPEG:	$6, $4A464946	MSB Height $00A3  word	Width  $00A5  word
GIF:	$0, $47494638	LSB Width  $0312  word	Height $0314  word
PNG:	$0, $89504E47	MSB Width  IHDR+0 long	Height IHDR+4 long
*/
