/* Copyright 1990 by Christopher A. Wichura.
   See file GIFMachine.doc for full description of rights.
*/

/* This function will take the gif screen we have read in and scale it to
   one half of its previous X size.

   What we do here is just a step above skipping every other pixel (like
   most routines I have seen do).  While we still put emphasis on the
   even pixels, we at least take account of the odds next to them by
   using a weighted average.

   This method is by no means the best way to do this.  If anyone wants
   to build a smarter one I would be very interested in seeing it.
*/

#include "GIFMachine.h"

extern struct GIFdescriptor gdesc;
EXTERNBITPLANE;

extern char *AbortMsg;

extern UWORD MasterColourTable[MAXCOLOURS];
extern UWORD TotalColours;

void DoXComp(void)
{
	register UWORD x1;
	register UWORD x2;
	register UWORD y;
	register UWORD ColourIndex;
	register UWORD num;
	UBYTE ColBuf[3];
	UWORD OldNumColours;
	UWORD NewWidth;

	NewWidth = gdesc.gd_Width >> 1;
	if (NewWidth & 1)
		NewWidth++;

	Printf("...Compressing width to %ld.\n......Line ", NewWidth);
	OldNumColours = TotalColours;

        for (y = 0; y < gdesc.gd_Height; y++) {
		Printf("%5ld", y);

		for (x1 = x2 = 0; x2 < gdesc.gd_Width; x1++, x2 += 2) {
			num = 4;
			ColourIndex = GetValue(x2, y);

			ColBuf[0] = GetRed(ColourIndex) * 4;
			ColBuf[1] = GetGreen(ColourIndex) * 4;
			ColBuf[2] = GetBlue(ColourIndex) * 4;

			if (x2 > 1) {
				num += 2;
				ColourIndex = GetValue((UWORD)(x2 - 1), y);

				ColBuf[0] += GetRed(ColourIndex) * 2;
				ColBuf[1] += GetGreen(ColourIndex) * 2;
				ColBuf[2] += GetBlue(ColourIndex) * 2;
			}

			if (x2 + 1 < gdesc.gd_Width) {
				num += 2;
				ColourIndex = GetValue((UWORD)(x2 + 1), y);

				ColBuf[0] += GetRed(ColourIndex) * 2;
				ColBuf[1] += GetGreen(ColourIndex) * 2;
				ColBuf[2] += GetBlue(ColourIndex) * 2;
			}

			ColBuf[0] = ((ColBuf[0] + num / 2) / num) << 4;
			ColBuf[1] = ((ColBuf[1] + num / 2) / num) << 4;
			ColBuf[2] = ((ColBuf[2] + num / 2) / num) << 4;

			ColourIndex = AddColour(ColBuf);

			PutValue(x1, y, ColourIndex);
		}

		PutValue(x1, y, gdesc.gd_BackGround);

		if (CheckAbort(NULL)) {
			Printf("\n%s\n", AbortMsg);
			XCEXIT(ABORTEXITVAL);
		}

		Printf("\x9B" "5D");
	}

	Puts("\x9B" "5DCompressed.");

	if (TotalColours > OldNumColours)
		Printf("......Total unique colours increased by %ld to %ld.\n",
			TotalColours - OldNumColours, TotalColours);

	gdesc.gd_Width = NewWidth;
}
