/* tobw.c       convert a gif to Black and White by converting everything */
/*              which is not index 0 into index one, and making index */
/*              zero = Black, and index one = White */

#include <stdio.h>
#include "gd.h"
#include "gdfontl.h"
#include "gdfonts.h"

int main(int argc, char **argv) 
{
  /* Input and output files */
     FILE *in;
     FILE *out;
   int grey,c;
   char inname[80] = "demoin.gif";

    /* Input image */
    gdImagePtr im;

 /* Color indexes */
    int white, black;           /* it's a binary world */
    int x,y;

	if (argc != 3) {
	  fprintf(stderr,"Usage: tobw <filein> <fileout>\n");
	  exit(1);
	}
	strcpy(inname,argv[1]);
	in = fopen(inname, "rb");
	if (!in) {
		fprintf(stderr, "Can't load source image.\n");
		exit(1);
	}

	im = gdImageCreateFromGif(in);
	fclose(in);
	
	/* First color allocated is background. */
	black = gdImageColorAllocate(im, 0, 0, 0);
	white = gdImageColorAllocate(im, 255, 255, 255);
	black = 0;
	white = 1;


	for (x=0;x<gdImageSX(im);x++) {
	 for (y=0;y<gdImageSY(im);y++) {
	   c = gdImageGetPixel(im,x,y);
	   grey = gdImageRed(im,c)+ 2*gdImageGreen(im,c)+ gdImageBlue(im,c);
/*           printf("%d ",color); */
	   if (grey < 512)
	      gdImageSetPixel(im,x,y,0);
	   else
	      gdImageSetPixel(im,x,y,1);
	 }
	 /* printf("\n"); */
	}

	im->red[0]=0;      /* set index 0 to black */
	im->green[0]=0;
	im->blue[0]=0;

	im->red[1]=255;      /* set index 1 to white */
	im->green[1]=255;
	im->blue[1]=255;

	out = fopen(argv[2], "wb");
	
	/* Write GIF */
	gdImageGif(im, out);
	fclose(out);
	gdImageDestroy(im);
	return(0);
}

