/* 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;

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

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

	MyPrintf("...Compressing width to %ld.\n......Line ", NewWidth);

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

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

			ColBuf[0] = BitPlane[y][x2].rgb_Red * 4;
			ColBuf[1] = BitPlane[y][x2].rgb_Green * 4;
			ColBuf[2] = BitPlane[y][x2].rgb_Blue * 4;

			if (x2 > 1) {
				num += 2;

				ColBuf[0] += BitPlane[y][x2 - 1].rgb_Red * 2;
				ColBuf[1] += BitPlane[y][x2 - 1].rgb_Green * 2;
				ColBuf[2] += BitPlane[y][x2 - 1].rgb_Blue * 2;
			}

			if (x2 + 1 < gdesc.gd_Width) {
				num += 2;

				ColBuf[0] += BitPlane[y][x2 + 1].rgb_Red * 2;
				ColBuf[1] += BitPlane[y][x2 + 1].rgb_Green * 2;
				ColBuf[2] += BitPlane[y][x2 + 1].rgb_Blue * 2;
			}

			BitPlane[y][x1].rgb_Red   = ((ColBuf[0] + num / 2) / num);
			BitPlane[y][x1].rgb_Green = ((ColBuf[1] + num / 2) / num);
			BitPlane[y][x1].rgb_Blue  = ((ColBuf[2] + num / 2) / num);
		}

		BitPlane[y][x1].rgb_Red = BitPlane[y][x1].rgb_Green = BitPlane[y][x1].rgb_Blue = 0;

		if (SetSignal(0L, SIGBREAKF_CTRL_C) & SIGBREAKF_CTRL_C) {
			MyPrintf("\n%s", AbortMsg);
			MyExit(ABORTEXITVAL);
		}

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

	PutStr("\x9B" "5DCompressed.\n");

	gdesc.gd_Width = NewWidth;
}
