/*****************************************************************************
*   "Gif-Lib" - Yet another gif library.				     *
*									     *
* Written by:  Gershon Elber				Ver 0.1, Jul. 1989   *
******************************************************************************
* Program to resize GIF by given factors horizontally and vertically.	     *
* Options:								     *
* -s n : resize both x & y direction by factor n.			     *
* -x n : resize the x direction (horizontally) by factor n.		     *
* -y n : resize the y direction (vertically) by factor n.		     *
* -u : set up instead of down (default) by factor n.			     *
* -d : scale down (default).						     *
* -h : on line help.							     *
******************************************************************************
* History:								     *
* 4 Jul 89 - Version 1.0 by Gershon Elber.				     *
* 22 Dec 89 - Fix minor bag in discarding last line of input (Version 1.1).  *
*****************************************************************************/

#ifdef __MSDOS__
#include <stdlib.h>
#include <alloc.h>
#endif /* __MSDOS__ */

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "gif_lib.h"
#include "getarg.h"

#define PROGRAM_NAME	"GifRSize"

#define MAX_SCALE	16			  /* Maximum scaling factor. */

#ifdef __MSDOS__
extern unsigned int
    _stklen = 16384;			     /* Increase default stack size. */
#endif /* __MSDOS__ */

#ifdef SYSV
static char *VersionStr =
        "Gif library module,\t\tGershon Elber\n\
	(C) Copyright 1989 Gershon Elber, Non commercial use only.\n";
static char
    *CtrlStr = "GifRSize s%-Scale!d x%-XScale!d y%-YScale!d u%- d%- h%- GifFile!*s";
#else
static char
    *VersionStr =
	PROGRAM_NAME
	GIF_LIB_VERSION
	"	Gershon Elber,	"
	__DATE__ ",   " __TIME__ "\n"
	"(C) Copyright 1989 Gershon Elber, Non commercial use only.\n";
static char
    *CtrlStr =
	PROGRAM_NAME
	" s%-Scale!d x%-XScale!d y%-YScale!d u%- d%- h%- GifFile!*s";
#endif /* SYSV */

/* Make some variables global, so we could access them faster: */
static GifPixelType
    BackGroundColor = 0;
static int
    XScale = 2,
    YScale = 2,
    ScaleDown = TRUE;

static void Average(GifRowType LineIn[], GifRowType LineOut[], int OutLineLen);
static void QuitGifError(GifFileType *GifFileIn, GifFileType *GifFileOut);

/******************************************************************************
* Interpret the command line and scan the given GIF file.		      *
******************************************************************************/
void main(int argc, char **argv)
{
    int	i, j, Error, NumFiles, ExtCode, ImageNum = 0, Scale, InCount,
	ScaleFlag = FALSE, XScaleFlag = FALSE, YScaleFlag = FALSE,
	UpFlag = FALSE, DownFlag = FALSE, HelpFlag = FALSE;
    GifRecordType RecordType;
    char s[80];
    GifByteType *Extension;
    GifRowType LineIn[MAX_SCALE], LineOut[MAX_SCALE];
    char **FileName = NULL;
    GifFileType *GifFileIn = NULL, *GifFileOut = NULL;

    if ((Error = GAGetArgs(argc, argv, CtrlStr, &ScaleFlag, &Scale,
		&XScaleFlag, &XScale, &YScaleFlag, &YScale, &UpFlag, &DownFlag,
		&HelpFlag, &NumFiles, &FileName)) != FALSE ||
		(NumFiles > 1 && !HelpFlag)) {
	if (Error)
	    GAPrintErrMsg(Error);
	else if (NumFiles > 1)
	    GIF_MESSAGE("Error in command line parsing - one GIF file please.");
	GAPrintHowTo(CtrlStr);
	exit(1);
    }

    if (HelpFlag) {
	fprintf(stderr, VersionStr);
	GAPrintHowTo(CtrlStr);
	exit(0);
    }

    /* Decide if we scale up or down: */
    if (UpFlag) ScaleDown = FALSE;
    if (DownFlag) ScaleDown = TRUE;

    /* If specific direction was set, set other direction to 1: */
    if (!XScaleFlag && YScaleFlag) XScale = 1;
    if (!YScaleFlag && XScaleFlag) YScale = 1;

    /* If the specific direction was not set, but global one did use it: */
    if (!XScaleFlag && ScaleFlag) XScale = Scale;
    if (!YScaleFlag && ScaleFlag) YScale = Scale;
    if (XScale > MAX_SCALE) {
	sprintf(s, "XScale too big, maximum scale selected instead (%d).",
								MAX_SCALE);
	GIF_MESSAGE(s);
	XScale = MAX_SCALE;
    }
    if (YScale > MAX_SCALE) {
	sprintf(s, "YScale too big, maximum scale selected instead (%d).",
								MAX_SCALE);
	GIF_MESSAGE(s);
	YScale = MAX_SCALE;
    }

    if (NumFiles == 1) {
	if ((GifFileIn = DGifOpenFileName(*FileName)) == NULL)
	    QuitGifError(GifFileIn, GifFileOut);
    }
    else {
	/* Use the stdin instead: */
	if ((GifFileIn = DGifOpenFileHandle(0)) == NULL)
	    QuitGifError(GifFileIn, GifFileOut);
    }
    BackGroundColor = GifFileIn -> SBackGroundColor;

    /* As at this time we know the Screen size of the input gif file, and as */
    /* all image(s) in file must be less/equal to it, we can allocate the    */
    /* scan lines for the input file, and output file. The number of lines   */
    /* to allocate for each is set by ScaleDown & XScale & YScale:	     */
    if (ScaleDown) {
	/* Output is smaller than input so we need only one output scanline: */
	LineOut[0] = (GifRowType) malloc(GifFileIn -> SWidth / XScale *
							sizeof(GifPixelType));
	for (i = 0; i < YScale; i++) LineIn[i] =
	    (GifRowType) malloc(GifFileIn -> SWidth * sizeof(GifPixelType));
	if (LineIn[YScale - 1] == NULL)
	    GIF_EXIT("Failed to allocate memory required, aborted.");
    }
    else {
	/* Input is smaller than output so we need only one input scanline:  */
	LineIn[0] = (GifRowType) malloc(GifFileIn -> SWidth *
							sizeof(GifPixelType));
	for (i = 0; i < YScale; i++) LineOut[i] =
	    (GifRowType) malloc(GifFileIn -> SWidth * XScale * sizeof(GifPixelType));
	if (LineOut[YScale - 1] == NULL)
	    GIF_EXIT("Failed to allocate memory required, aborted.");
    }

    /* Open stdout for the output file: */
    if ((GifFileOut = EGifOpenFileHandle(1)) == NULL)
	QuitGifError(GifFileIn, GifFileOut);

    /* And dump out its new scaled screen information: */
    if (EGifPutScreenDesc(GifFileOut,
	ScaleDown ? GifFileIn -> SWidth / XScale :
		    GifFileIn -> SWidth * XScale,
	ScaleDown ? GifFileIn -> SHeight / YScale :
		    GifFileIn -> SHeight * YScale,
	GifFileIn -> SColorResolution, GifFileIn -> SBackGroundColor,
	GifFileIn -> SBitsPerPixel, GifFileIn -> SColorMap) == GIF_ERROR)
	QuitGifError(GifFileIn, GifFileOut);


    /* Scan the content of the GIF file and load the image(s) in: */
    do {
	if (DGifGetRecordType(GifFileIn, &RecordType) == GIF_ERROR)
	    QuitGifError(GifFileIn, GifFileOut);

	switch (RecordType) {
	    case IMAGE_DESC_RECORD_TYPE:
		if (DGifGetImageDesc(GifFileIn) == GIF_ERROR)
		    QuitGifError(GifFileIn, GifFileOut);
		/* Put the image descriptor to out file: */
		if (EGifPutImageDesc(GifFileOut,
		    ScaleDown ? GifFileIn -> ILeft / XScale :
				GifFileIn -> ILeft * XScale,
		    ScaleDown ? GifFileIn -> ITop / YScale :
				GifFileIn -> ITop * YScale,
		    ScaleDown ? GifFileIn -> IWidth / XScale :
				GifFileIn -> IWidth * XScale,
		    ScaleDown ? GifFileIn -> IHeight / YScale :
				GifFileIn -> IHeight * YScale,
		    GifFileIn -> IInterlace, GifFileIn -> IBitsPerPixel,
		    GifFileIn -> IColorMap) == GIF_ERROR)
		    QuitGifError(GifFileIn, GifFileOut);

		if (GifFileIn -> IInterlace) {
		    GIF_EXIT("Cannt average4 interlaced images - use GifInter first.");
		}
		else {
		    fprintf(stderr, "\n%s: Image %d at (%d, %d) [%dx%d]:     ",
			PROGRAM_NAME, ++ImageNum,
			GifFileOut -> ILeft, GifFileOut -> ITop,
			GifFileOut -> IWidth, GifFileOut -> IHeight);
		    InCount = 0;
		    if (ScaleDown) {
			/* For each line of output, read YScale input lines, */
			/* average them, and dump result out:		     */
			for (i = 0; i < GifFileOut -> IHeight; i++) {
			    fprintf(stderr, "\b\b\b\b%-4d", i);
			    for (j = 0; j < YScale; j++)
				if (DGifGetLine(GifFileIn, LineIn[j],
						GifFileIn -> IWidth) == GIF_ERROR)
				    QuitGifError(GifFileIn, GifFileOut);
			    InCount += YScale;
			    Average(LineIn, LineOut, GifFileOut -> IWidth);
			    if (EGifPutLine(GifFileOut, LineOut[0],
						GifFileOut -> IWidth) == GIF_ERROR)
				QuitGifError(GifFileIn, GifFileOut);
			}
			/* If scale is not dividable - discard last lines: */
			for (i = InCount; i < GifFileIn -> IHeight; i++)
			    DGifGetLine(GifFileIn, LineIn[0],
							GifFileIn -> IWidth);
		    }
		    else {
			/* For each line of input, output YScale lines,	     */
			/* by averaging up this line to YScale lines:	     */
			for (i = 0; i < GifFileIn -> IHeight; i++) {
			    fprintf(stderr, "\b\b\b\b%-4d", i * YScale);
			    if (DGifGetLine(GifFileIn, LineIn[0],
						GifFileIn -> IWidth) == GIF_ERROR)
				QuitGifError(GifFileIn, GifFileOut);
			    Average(LineIn, LineOut, GifFileOut -> IWidth);
			    for (j = 0; j < YScale; j++)
				if (EGifPutLine(GifFileOut, LineOut[j],
						GifFileOut -> IWidth) == GIF_ERROR)
				    QuitGifError(GifFileIn, GifFileOut);
			}
		    }
		}
		break;
	    case EXTENSION_RECORD_TYPE:
		/* Skip any extension blocks in file: */
		if (DGifGetExtension(GifFileIn, &ExtCode, &Extension) == GIF_ERROR)
		    QuitGifError(GifFileIn, GifFileOut);
		if (EGifPutExtension(GifFileOut, ExtCode, Extension[0],
							Extension) == GIF_ERROR)
		    QuitGifError(GifFileIn, GifFileOut);

		/* No support to more than one extension blocks, so discard: */
		while (Extension != NULL) {
		    if (DGifGetExtensionNext(GifFileIn, &Extension) == GIF_ERROR)
			QuitGifError(GifFileIn, GifFileOut);
		}
		break;
	    case TERMINATE_RECORD_TYPE:
		break;
	    default:		    /* Should be traps by DGifGetRecordType. */
		break;
	}
    }
    while (RecordType != TERMINATE_RECORD_TYPE);

    if (DGifCloseFile(GifFileIn) == GIF_ERROR)
	QuitGifError(GifFileIn, GifFileOut);
    if (EGifCloseFile(GifFileOut) == GIF_ERROR)
	QuitGifError(GifFileIn, GifFileOut);
}

/******************************************************************************
* Average routine - scale given lines as follows:			      *
*   ScaleDown: for each YScale lines, for each box of size XScale by YScale   *
* pick a pixel in it (usually upper left). If that pixel is equal to	      *
* background color, and there is in that square, none background pixel, pick  *
* that instead. Use result pixel as output averaged pixel		      *
*   ScaleUp: each input pixel, is expanded both in X and in Y by the factors  *
* XScale & YScale respectively.						      *
******************************************************************************/
static void Average(GifRowType LineIn[], GifRowType LineOut[], int OutLineLen)
{
    int i, j, k, o;
    GifPixelType Color;


    if (ScaleDown) {
	/* For each XScale by YScale pixels in a box, pick the top left one  */
	/* if not background color, otherwise pick any non background from   */
	/* other pixels in box if one exists.				     */
	for (i = 0, o = 0; o < OutLineLen; i += XScale, o++) {
	    if ((Color = LineIn[0][i]) == BackGroundColor) {
		/* Scan all pixels to find non background color if exists: */
		for (j = i; j < i + XScale && Color == BackGroundColor; j++)
		    for (k = 0; k<YScale && Color == BackGroundColor; k++)
			if (LineIn[k][j] != BackGroundColor)
			    Color = LineIn[k][j];
	    }
	    LineOut[0][o] = Color;
	}
    }
    else {
	/* Make each input pixel a box of size XScale bu YScale: */
	for (i = 0, o = 0; o < OutLineLen; i++, o+=XScale) {
	    /* Prepare first line. */
	    for (j = 0; j < XScale; j++) LineOut[0][o+j] = LineIn[0][i];
        }
	/* And duplicate the other lines from first one: */
	for (i = 1; i < YScale; i++) memcpy(LineOut[i], LineOut[0],
					OutLineLen * sizeof(GifPixelType));
    }
}

/******************************************************************************
* Close both input and output file (if open), and exit.			      *
******************************************************************************/
static void QuitGifError(GifFileType *GifFileIn, GifFileType *GifFileOut)
{
    PrintGifError();
    if (GifFileIn != NULL) DGifCloseFile(GifFileIn);
    if (GifFileOut != NULL) EGifCloseFile(GifFileOut);
    exit(1);
}
