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

unsigned char* buf;
unsigned char tmp[100];
unsigned long int pal[256];
int w, h;
int pos;
int bytepos;

int main() {
	int count, val, i;
	bytepos=0;

	read(0, tmp, 8);
	bytepos+=8;

	if(strncmp((char*)tmp, "SpidyGfx", 8) != 0) {
		fprintf(stderr, "Bad header\n");
		return 1;
	}
	if(read(0, tmp, 4)!=4) {
		fprintf(stderr, "Bad read\n");
		return 2;
	}
	bytepos+=4;

	w=tmp[0]+tmp[1]*256;
	h=tmp[2]+tmp[3]*256;

	fprintf(stderr, "Dimensions: %d x %d\n", w, h);

	buf=calloc(w*h,1);
	pos=0;

	while(pos<w*h) {
		if(read(0, tmp, 1)!=1) return 3;
		bytepos++;
		if(tmp[0]<0xC0) {
			count=1;
			val=tmp[0];
		} else {
			count=tmp[0]-0xC0;
			if(read(0, tmp, 1)!=1) return 4;
			bytepos++;
			val=tmp[0];
		}
		for(i=0; i<count && pos<w*h; i++) buf[pos++]=val;
		if(i<count) {
			fprintf(stderr, "Ouch, hit end of image buffer\n");
			return 5;
		}
	}
	fprintf(stderr, "Read all image data, now on pos %d\n", bytepos);


	if(read(0, tmp, 1)!=1) return 7;
	bytepos++;
	fprintf(stderr, "Mystery byte: %d\n", tmp[0]);

	for(i=0; i<256; i++) {
		if(read(0, tmp, 3)!=3) return 8;
		bytepos+=3;

		pal[i]=tmp[0]*65536L+tmp[1]*256+tmp[2];
	}

	printf("P6\n");
	printf("%d %d\n", w, h);
	printf("255\n"); 
	fflush(stdout);

	pos=0;

	while(pos<w*h) {
		tmp[0] = (pal[buf[pos]]>>16)&0xFF;
		tmp[1] = (pal[buf[pos]]>> 8)&0xFF;
		tmp[2] = (pal[buf[pos]]>> 0)&0xFF;
		i=write(1, tmp, 3);
		if(i!=3) {
			perror("Writing buffer");
			return 6; 
		}
		pos++;
	}

	return 0;
}


