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

#include "GIFMachine.h"

extern struct GIFdescriptor gdesc;
EXTERNBITPLANE;

extern char *AbortMsg;

extern int NoBorderLineThresh;

extern UWORD MasterColourTable[MAXCOLOURS];

static UWORD BorderCol;

#define BorderCheck(a, b) (GetValue(a, b) != BorderCol)

void StripBorder(void)
{
	register UWORD x;
	register UWORD y;
	register int thresh;
	register BOOL breakout;
	UWORD LeftEdge, TopEdge;
	UWORD Width, Height;
	int WidthThresh, HeightThresh;

	Puts("...Removing border.");

	BorderCol = GetValue(0, 0);

	WidthThresh  = NoBorderLineThresh * gdesc.gd_Width  / 100;
	HeightThresh = NoBorderLineThresh * gdesc.gd_Height / 100;

	for (breakout = y = 0; (y < gdesc.gd_Height) && !breakout; y++) {
		for (thresh = x = 0; x < gdesc.gd_Width; x++)
			if (BorderCheck(x, y))
				if (++thresh > WidthThresh) {
					breakout = TRUE;
					break;
				}

		if (CheckAbort(NULL)) {
			Puts(AbortMsg);
			XCEXIT(ABORTEXITVAL);
		}
	}

	TopEdge = y - 1;

	for (breakout = 0, y = gdesc.gd_Height - 1; y >= 0 && !breakout; y--) {
		for (thresh = x = 0; x < gdesc.gd_Width; x++)
			if (BorderCheck(x, y))
				if (++thresh > WidthThresh) {
					breakout = TRUE;
					break;
				}

		if (CheckAbort(NULL)) {
			Puts(AbortMsg);
			XCEXIT(ABORTEXITVAL);
		}
	}

	Height = y - TopEdge + 2;

	for (breakout = x = 0; (x < gdesc.gd_Width) && !breakout; x++) {
		for (thresh = y = 0; y < gdesc.gd_Height; y++)
			if (BorderCheck(x, y))
				if (++thresh > HeightThresh) {
					breakout = TRUE;
					break;
				}

		if (CheckAbort(NULL)) {
			Puts(AbortMsg);
			XCEXIT(ABORTEXITVAL);
		}
	}

	LeftEdge = x - 1;

	for (breakout = 0, x = gdesc.gd_Width - 1; x >= 0 && !breakout; x--) {
		for (thresh = y = 0; y < gdesc.gd_Height; y++)
			if (BorderCheck(x, y))
				if (++thresh > HeightThresh) {
					breakout = TRUE;
					break;
				}

		if (CheckAbort(NULL)) {
			Puts(AbortMsg);
			XCEXIT(ABORTEXITVAL);
		}
	}

	Width = x - LeftEdge + 2;

	if ((Width != gdesc.gd_Width) || (Height != gdesc.gd_Height)) {
		if (Width < 5 || Height < 5) {
			Puts("......Too much of picture would be removed.  Not modified.");
			return;
		}

		for (y = 0; y < Height; y++) {
			for (x = 0; x < Width; x++)
				PutValue(x, y,
				   GetValue((UWORD)(LeftEdge + x),
					    (UWORD)(TopEdge + y)));

			PutValue(x, y, gdesc.gd_BackGround);

			if (CheckAbort(NULL)) {
				Puts(AbortMsg);
				XCEXIT(ABORTEXITVAL);
			}
		}

		if (Width & 1)
			Width++;

		Printf("......New width = %ld, New height = %ld\n", Width, Height);
		gdesc.gd_Width = Width;
		gdesc.gd_Height = Height;
	}
}
