#include <stdio.h>

int main(void)
{
    unsigned short buf[BUFSIZ];
    unsigned int i, j, x, y;
    unsigned short pixels;

    /* On gicle les 11 premiers octets (je sais pas ce que c'est) */
    fread(buf, 1, 11, stdin);

    /* On lit X et Y */
    fread(buf, 2, 2, stdin);
	x = buf[0];
    y = buf[1];

    //x = (x + 7) & ~7;
 //    x = x + 3;

    /* Je sais pas ce que c'est que cette merde */
    //fread(buf, 2, 4, stdin);


	// case grisée //
    //fread(buf, 2, 8, stdin);

	// suivant case grisée ...
	// fread(buf, 2, 1120, stdin);
	// fread(buf, 4, 1120, stdin);
	// fread(buf, 6, 1120, stdin);
	// fread(buf, 8, 1120, stdin);
	//
	// Pour la flame
	//fread(buf, 1, 780, stdin);
	//fread(buf, 2, 1120, stdin);

    /* TGA header (truecolor image) */
    fprintf(stdout, "%c%c%c", 0x0, 0x0, 0x02);
    /* Colormap (empty) */
    fprintf(stdout, "%c%c%c%c%c", 0x0, 0x0, 0x0, 0x0, 0x0);
    /* X and Y offsets (0) */
    fprintf(stdout, "%c%c", 0x0, 0x0);
    fprintf(stdout, "%c%c", 0x0, 0x0);
    /* X size, Y size */
    fprintf(stdout, "%c%c", x & 0xff, x >> 8);
    fprintf(stdout, "%c%c", y & 0xff, y >> 8);
    /* Colour depth (24) */
    fprintf(stdout, "%c", 0x18);
    /* Direction (upside-down) */
    fprintf(stdout, "%c", 0x20);

		fread(buf, 2, 1, stdin);
		fread(buf, 2, 1, stdin);

		fread(buf, 2, 1, stdin);
		fread(buf, 2, 1, stdin);

    for(j = y; j--; )
    {
		unsigned int interval, newx, longueur;
		newx=x;

        /* 6 octets qui servent à rien */
		fread(buf, 2, 1, stdin);
		interval=buf[0];

		fread(buf, 2, 1, stdin);
		fread(buf, 2, 1, stdin);
		longueur = buf[0];

		//printf("\n(%i,%i)\n",interval, longueur);

		for (i=interval;i--;)
		{
			unsigned int pixel;
			pixel=0;
			fwrite(&pixel, 1, 3, stdout);
		}
		newx=x-interval;

        for(i = longueur; i--; )
        {
            unsigned int red, green, blue, pixel;
            fread(buf, 2, 1, stdin);
            /* On convertit en 24 bits */
            red = buf[0] >> 11;
            green = (buf[0] >> 5) & 0x3f;
            blue = buf[0] & 0x1f;
            pixel = red << (16 + 3);
            pixel |= green << (8 + 2);
            pixel |= blue << (0 + 3);
            /* Only write 3 bytes from the int */
            fwrite(&pixel, 1, 3, stdout);
        }

		if (x-longueur-interval > 0)
			for (i=(x-longueur-interval);i--;)
			{
				unsigned int pixel;
				pixel=0;
				fwrite(&pixel, 1, 3, stdout);
			}
    }

    fflush(stdout);
}

