f530d4
diff --git a/src/extra/gd/Makefile.am b/src/extra/gd/Makefile.am
f530d4
index 3fb9330..14bda8c 100644
f530d4
--- a/src/extra/gd/Makefile.am
f530d4
+++ b/src/extra/gd/Makefile.am
f530d4
@@ -22,7 +22,7 @@ libgd_la_SOURCES = gd.c gd_gd.c gd_gd2.c gd_io.c gd_io_dp.c \
f530d4
 		gd_io_file.c gd_ss.c gd_io_ss.c gd_png.c gd_jpeg.c gdxpm.c \
f530d4
 		gdfontt.c gdfonts.c gdfontmb.c gdfontl.c gdfontg.c \
f530d4
 		gdtables.c gdft.c gdcache.c gdkanji.c wbmp.c \
f530d4
-		gd_wbmp.c gdhelpers.c gd_topal.c gd_clip.c
f530d4
+		gd_wbmp.c gdhelpers.c gd_clip.c
f530d4
 
f530d4
 gddir = $(includedir)/libwmf/gd
f530d4
 
f530d4
diff --git a/src/extra/gd/Makefile.gd b/src/extra/gd/Makefile.gd
f530d4
index 3cd876f..b90e4ac 100644
f530d4
--- a/src/extra/gd/Makefile.gd
f530d4
+++ b/src/extra/gd/Makefile.gd
f530d4
@@ -145,7 +145,7 @@ LIBOBJS=gd.o gd_gd.o gd_gd2.o gd_io.o gd_io_dp.o \
f530d4
 		gd_io_file.o gd_ss.o gd_io_ss.o gd_png.o gd_jpeg.o gdxpm.o \
f530d4
 		gdfontt.o gdfonts.o gdfontmb.o gdfontl.o gdfontg.o \
f530d4
 		gdtables.o gdft.o gdcache.o gdkanji.o wbmp.o \
f530d4
-		gd_wbmp.o gdhelpers.o gd_topal.o 
f530d4
+		gd_wbmp.o gdhelpers.o
f530d4
 
f530d4
 #Shared library. This should work fine on any ELF platform (Linux, etc.) with
f530d4
 #GNU ld or something similarly intelligent. To avoid the chicken-and-egg
f530d4
diff --git a/src/extra/gd/Makefile.in b/src/extra/gd/Makefile.in
f530d4
index edb5c90..8cf93a6 100644
f530d4
--- a/src/extra/gd/Makefile.in
f530d4
+++ b/src/extra/gd/Makefile.in
f530d4
@@ -107,7 +107,7 @@ am_libgd_la_OBJECTS = gd.lo gd_gd.lo gd_gd2.lo gd_io.lo gd_io_dp.lo \
f530d4
 	gd_io_file.lo gd_ss.lo gd_io_ss.lo gd_png.lo gd_jpeg.lo \
f530d4
 	gdxpm.lo gdfontt.lo gdfonts.lo gdfontmb.lo gdfontl.lo \
f530d4
 	gdfontg.lo gdtables.lo gdft.lo gdcache.lo gdkanji.lo wbmp.lo \
f530d4
-	gd_wbmp.lo gdhelpers.lo gd_topal.lo gd_clip.lo
f530d4
+	gd_wbmp.lo gdhelpers.lo gd_clip.lo
f530d4
 libgd_la_OBJECTS = $(am_libgd_la_OBJECTS)
f530d4
 AM_V_lt = $(am__v_lt_@AM_V@)
f530d4
 am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@)
f530d4
@@ -370,7 +370,7 @@ libgd_la_SOURCES = gd.c gd_gd.c gd_gd2.c gd_io.c gd_io_dp.c \
f530d4
 		gd_io_file.c gd_ss.c gd_io_ss.c gd_png.c gd_jpeg.c gdxpm.c \
f530d4
 		gdfontt.c gdfonts.c gdfontmb.c gdfontl.c gdfontg.c \
f530d4
 		gdtables.c gdft.c gdcache.c gdkanji.c wbmp.c \
f530d4
-		gd_wbmp.c gdhelpers.c gd_topal.c gd_clip.c
f530d4
+		gd_wbmp.c gdhelpers.c gd_clip.c
f530d4
 
f530d4
 gddir = $(includedir)/libwmf/gd
f530d4
 gd_HEADERS = $(HDRGDINST)
f530d4
@@ -472,7 +472,6 @@ distclean-compile:
f530d4
 @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gd_jpeg.Plo@am__quote@
f530d4
 @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gd_png.Plo@am__quote@
f530d4
 @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gd_ss.Plo@am__quote@
f530d4
-@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gd_topal.Plo@am__quote@
f530d4
 @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gd_wbmp.Plo@am__quote@
f530d4
 @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gdcache.Plo@am__quote@
f530d4
 @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gdfontg.Plo@am__quote@
f530d4
diff --git a/src/extra/gd/gd.c b/src/extra/gd/gd.c
f530d4
index 6296472..dc6a9a7 100644
f530d4
--- a/src/extra/gd/gd.c
f530d4
+++ b/src/extra/gd/gd.c
f530d4
@@ -1995,7 +1995,7 @@ gdImageCopyResized (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX
f530d4
 			  else
f530d4
 			    {
f530d4
 			      /* Find or create the best match */
f530d4
-			      mapTo = gdImageColorResolveAlpha (dst,
f530d4
+			      nc = gdImageColorResolveAlpha (dst,
f530d4
 						      gdTrueColorGetRed (c),
f530d4
 						    gdTrueColorGetGreen (c),
f530d4
 						     gdTrueColorGetBlue (c),
f530d4
diff --git a/src/extra/gd/gd.h b/src/extra/gd/gd.h
f530d4
index 619ddd3..8c19354 100644
f530d4
--- a/src/extra/gd/gd.h
f530d4
+++ b/src/extra/gd/gd.h
f530d4
@@ -308,24 +308,6 @@ int gdImageColorResolveAlpha(gdImagePtr im, int r, int g, int b, int a);
f530d4
 
f530d4
 void gdImageColorDeallocate(gdImagePtr im, int color);
f530d4
 
f530d4
-/* Converts a truecolor image to a palette-based image,
f530d4
-	using a high-quality two-pass quantization routine
f530d4
-	which attempts to preserve alpha channel information
f530d4
-	as well as R/G/B color information when creating
f530d4
-	a palette. If ditherFlag is set, the image will be
f530d4
-	dithered to approximate colors better, at the expense
f530d4
-	of some obvious "speckling." colorsWanted can be
f530d4
-	anything up to 256. If the original source image
f530d4
-	includes photographic information or anything that
f530d4
-	came out of a JPEG, 256 is strongly recommended.
f530d4
-
f530d4
-	Better yet, don't use this function -- write real
f530d4
-	truecolor PNGs and JPEGs. The disk space gain of
f530d4
-        conversion to palette is not great (for small images
f530d4
-        it can be negative) and the quality loss is ugly. */
f530d4
-
f530d4
-void gdImageTrueColorToPalette(gdImagePtr im, int ditherFlag, int colorsWanted);
f530d4
-
f530d4
 /* Specifies a color index (if a palette image) or an
f530d4
 	RGB color (if a truecolor image) which should be
f530d4
 	considered 100% transparent. FOR TRUECOLOR IMAGES,
f530d4
diff --git a/src/extra/gd/gd_gd2.c b/src/extra/gd/gd_gd2.c
f530d4
index 602b869..05d8dcb 100644
f530d4
--- a/src/extra/gd/gd_gd2.c
f530d4
+++ b/src/extra/gd/gd_gd2.c
f530d4
@@ -361,7 +361,7 @@ gdImageCreateFromGd2Ctx (gdIOCtxPtr in)
f530d4
 		  xhi = im->sx;
f530d4
 		};
f530d4
 	      /*GD2_DBG(printf("y=%d: ",y)); */
f530d4
-	      if (fmt == GD2_FMT_RAW)
f530d4
+	      if (fmt != GD2_FMT_COMPRESSED)
f530d4
 		{
f530d4
 		  for (x = xlo; x < xhi; x++)
f530d4
 		    {
f530d4
@@ -617,7 +617,7 @@ gdImageCreateFromGd2PartCtx (gdIOCtx * in, int srcx, int srcy, int w, int h)
f530d4
 
f530d4
 	      for (x = xlo; x < xhi; x++)
f530d4
 		{
f530d4
-		  if (fmt == GD2_FMT_RAW)
f530d4
+		  if (fmt != GD2_FMT_COMPRESSED)
f530d4
 		    {
f530d4
 		      if (im->trueColor)
f530d4
 			{
f530d4
diff --git a/src/extra/gd/gd_png.c b/src/extra/gd/gd_png.c
f530d4
index b37fc2c..c7f3aa0 100644
f530d4
--- a/src/extra/gd/gd_png.c
f530d4
+++ b/src/extra/gd/gd_png.c
f530d4
@@ -131,7 +131,6 @@ gdImageCreateFromPngCtx (gdIOCtx * infile)
f530d4
   gdImagePtr im = NULL;
f530d4
   int i, j, *open;
f530d4
   volatile int transparent = -1;
f530d4
-  volatile int palette_allocated = FALSE;
f530d4
 
f530d4
   /* Make sure the signature can't match by dumb luck -- TBB */
f530d4
   memset (sig, 0, sizeof (sig));
f530d4
@@ -177,6 +176,7 @@ gdImageCreateFromPngCtx (gdIOCtx * infile)
f530d4
     }
f530d4
 #endif
f530d4
   open = NULL;
f530d4
+  palette = NULL;
f530d4
 
f530d4
   png_set_sig_bytes (png_ptr, 8);	/* we already read the 8 signature bytes */
f530d4
 
f530d4
@@ -254,7 +254,6 @@ gdImageCreateFromPngCtx (gdIOCtx * infile)
f530d4
 	  gdImageDestroy(im);
f530d4
 	  return NULL;
f530d4
 	}
f530d4
-      palette_allocated = TRUE;
f530d4
       if (bit_depth < 8)
f530d4
 	{
f530d4
 	  num_palette = 1 << bit_depth;
f530d4
@@ -321,8 +320,7 @@ gdImageCreateFromPngCtx (gdIOCtx * infile)
f530d4
       fprintf (stderr, "gd-png error: cannot allocate image data\n");
f530d4
       png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
f530d4
       gdImageDestroy(im);
f530d4
-      if (palette_allocated)
f530d4
-        gdFree (palette);
f530d4
+      gdFree(palette);
f530d4
       return NULL;
f530d4
     }
f530d4
   if ((row_pointers = (png_bytepp) gdMalloc (height * sizeof (png_bytep))) == NULL)
f530d4
@@ -331,8 +329,7 @@ gdImageCreateFromPngCtx (gdIOCtx * infile)
f530d4
       png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
f530d4
       gdFree (image_data);
f530d4
       gdImageDestroy(im);
f530d4
-      if (palette_allocated)
f530d4
-        gdFree (palette);
f530d4
+      gdFree(palette);
f530d4
       return NULL;
f530d4
     }
f530d4
 
f530d4
@@ -429,8 +426,7 @@ gdImageCreateFromPngCtx (gdIOCtx * infile)
f530d4
     }
f530d4
 #endif
f530d4
 
f530d4
-  if (palette_allocated)
f530d4
-    gdFree (palette);
f530d4
+  gdFree (palette);
f530d4
   gdFree (image_data);
f530d4
   gdFree (row_pointers);
f530d4
 
f530d4
diff --git a/src/extra/gd/gd_topal.c b/src/extra/gd/gd_topal.c
f530d4
deleted file mode 100644
f530d4
index 4ca86c9..0000000
f530d4
--- a/src/extra/gd/gd_topal.c
f530d4
+++ /dev/null
f530d4
@@ -1,1698 +0,0 @@
f530d4
-
f530d4
-
f530d4
-/*
f530d4
- * gd_topal.c 
f530d4
- * 
f530d4
- * This code is adapted pretty much entirely from jquant2.c,
f530d4
- * Copyright (C) 1991-1996, Thomas G. Lane. That file is
f530d4
- * part of the Independent JPEG Group's software. Conditions of
f530d4
- * use are compatible with the gd license. See the gd license 
f530d4
- * statement and README-JPEG.TXT for additional information.
f530d4
- *
f530d4
- * This file contains 2-pass color quantization (color mapping) routines.
f530d4
- * These routines provide selection of a custom color map for an image,
f530d4
- * followed by mapping of the image to that color map, with optional
f530d4
- * Floyd-Steinberg dithering.
f530d4
- *
f530d4
- * It is also possible to use just the second pass to map to an arbitrary
f530d4
- * externally-given color map.
f530d4
- *
f530d4
- * Note: ordered dithering is not supported, since there isn't any fast
f530d4
- * way to compute intercolor distances; it's unclear that ordered dither's
f530d4
- * fundamental assumptions even hold with an irregularly spaced color map.
f530d4
- *
f530d4
- * SUPPORT FOR ALPHA CHANNELS WAS HACKED IN BY THOMAS BOUTELL, who also
f530d4
- * adapted the code to work within gd rather than within libjpeg, and
f530d4
- * may not have done a great job of either. It's not Thomas G. Lane's fault.
f530d4
- */
f530d4
-
f530d4
-#include "gd.h"
f530d4
-#include "gdhelpers.h"
f530d4
-#include <string.h>
f530d4
-
f530d4
-/*
f530d4
- * This module implements the well-known Heckbert paradigm for color
f530d4
- * quantization.  Most of the ideas used here can be traced back to
f530d4
- * Heckbert's seminal paper
f530d4
- *   Heckbert, Paul.  "Color Image Quantization for Frame Buffer Display",
f530d4
- *   Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
f530d4
- *
f530d4
- * In the first pass over the image, we accumulate a histogram showing the
f530d4
- * usage count of each possible color.  To keep the histogram to a reasonable
f530d4
- * size, we reduce the precision of the input; typical practice is to retain
f530d4
- * 5 or 6 bits per color, so that 8 or 4 different input values are counted
f530d4
- * in the same histogram cell.
f530d4
- *
f530d4
- * Next, the color-selection step begins with a box representing the whole
f530d4
- * color space, and repeatedly splits the "largest" remaining box until we
f530d4
- * have as many boxes as desired colors.  Then the mean color in each
f530d4
- * remaining box becomes one of the possible output colors.
f530d4
- * 
f530d4
- * The second pass over the image maps each input pixel to the closest output
f530d4
- * color (optionally after applying a Floyd-Steinberg dithering correction).
f530d4
- * This mapping is logically trivial, but making it go fast enough requires
f530d4
- * considerable care.
f530d4
- *
f530d4
- * Heckbert-style quantizers vary a good deal in their policies for choosing
f530d4
- * the "largest" box and deciding where to cut it.  The particular policies
f530d4
- * used here have proved out well in experimental comparisons, but better ones
f530d4
- * may yet be found.
f530d4
- *
f530d4
- * In earlier versions of the IJG code, this module quantized in YCbCr color
f530d4
- * space, processing the raw upsampled data without a color conversion step.
f530d4
- * This allowed the color conversion math to be done only once per colormap
f530d4
- * entry, not once per pixel.  However, that optimization precluded other
f530d4
- * useful optimizations (such as merging color conversion with upsampling)
f530d4
- * and it also interfered with desired capabilities such as quantizing to an
f530d4
- * externally-supplied colormap.  We have therefore abandoned that approach.
f530d4
- * The present code works in the post-conversion color space, typically RGB.
f530d4
- *
f530d4
- * To improve the visual quality of the results, we actually work in scaled
f530d4
- * RGBA space, giving G distances more weight than R, and R in turn more than
f530d4
- * B.  Alpha is weighted least. To do everything in integer math, we must 
f530d4
- * use integer scale factors. The 2/3/1 scale factors used here correspond 
f530d4
- * loosely to the relative weights of the colors in the NTSC grayscale 
f530d4
- * equation. 
f530d4
- */
f530d4
-
f530d4
-#ifndef TRUE
f530d4
-#define TRUE 1
f530d4
-#endif /* TRUE */
f530d4
-
f530d4
-#ifndef FALSE
f530d4
-#define FALSE 0
f530d4
-#endif /* FALSE */
f530d4
-
f530d4
-#define R_SCALE 2		/* scale R distances by this much */
f530d4
-#define G_SCALE 3		/* scale G distances by this much */
f530d4
-#define B_SCALE 1		/* and B by this much */
f530d4
-#define A_SCALE 4		/* and alpha by this much. This really
f530d4
-				   only scales by 1 because alpha
f530d4
-				   values are 7-bit to begin with. */
f530d4
-
f530d4
-/* Channel ordering (fixed in gd) */
f530d4
-#define C0_SCALE R_SCALE
f530d4
-#define C1_SCALE G_SCALE
f530d4
-#define C2_SCALE B_SCALE
f530d4
-#define C3_SCALE A_SCALE
f530d4
-
f530d4
-/*
f530d4
- * First we have the histogram data structure and routines for creating it.
f530d4
- *
f530d4
- * The number of bits of precision can be adjusted by changing these symbols.
f530d4
- * We recommend keeping 6 bits for G and 5 each for R and B.
f530d4
- * If you have plenty of memory and cycles, 6 bits all around gives marginally
f530d4
- * better results; if you are short of memory, 5 bits all around will save
f530d4
- * some space but degrade the results.
f530d4
- * To maintain a fully accurate histogram, we'd need to allocate a "long"
f530d4
- * (preferably unsigned long) for each cell.  In practice this is overkill;
f530d4
- * we can get by with 16 bits per cell.  Few of the cell counts will overflow,
f530d4
- * and clamping those that do overflow to the maximum value will give close-
f530d4
- * enough results.  This reduces the recommended histogram size from 256Kb
f530d4
- * to 128Kb, which is a useful savings on PC-class machines.
f530d4
- * (In the second pass the histogram space is re-used for pixel mapping data;
f530d4
- * in that capacity, each cell must be able to store zero to the number of
f530d4
- * desired colors.  16 bits/cell is plenty for that too.)
f530d4
- * Since the JPEG code is intended to run in small memory model on 80x86
f530d4
- * machines, we can't just allocate the histogram in one chunk.  Instead
f530d4
- * of a true 3-D array, we use a row of pointers to 2-D arrays.  Each
f530d4
- * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
f530d4
- * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries.  Note that
f530d4
- * on 80x86 machines, the pointer row is in near memory but the actual
f530d4
- * arrays are in far memory (same arrangement as we use for image arrays).
f530d4
- */
f530d4
-
f530d4
-#define MAXNUMCOLORS  (gdMaxColors)	/* maximum size of colormap */
f530d4
-
f530d4
-#define HIST_C0_BITS  5		/* bits of precision in R histogram */
f530d4
-#define HIST_C1_BITS  6		/* bits of precision in G histogram */
f530d4
-#define HIST_C2_BITS  5		/* bits of precision in B histogram */
f530d4
-#define HIST_C3_BITS  3		/* bits of precision in A histogram */
f530d4
-
f530d4
-/* Number of elements along histogram axes. */
f530d4
-#define HIST_C0_ELEMS  (1<
f530d4
-#define HIST_C1_ELEMS  (1<
f530d4
-#define HIST_C2_ELEMS  (1<
f530d4
-#define HIST_C3_ELEMS  (1<
f530d4
-
f530d4
-/* These are the amounts to shift an input value to get a histogram index. */
f530d4
-#define C0_SHIFT  (8-HIST_C0_BITS)
f530d4
-#define C1_SHIFT  (8-HIST_C1_BITS)
f530d4
-#define C2_SHIFT  (8-HIST_C2_BITS)
f530d4
-/* Beware! Alpha is 7 bit to begin with */
f530d4
-#define C3_SHIFT  (7-HIST_C3_BITS)
f530d4
-
f530d4
-
f530d4
-typedef unsigned short histcell;	/* histogram cell; prefer an unsigned type */
f530d4
-
f530d4
-typedef histcell *histptr;	/* for pointers to histogram cells */
f530d4
-
f530d4
-typedef histcell hist1d[HIST_C3_ELEMS];		/* typedefs for the array */
f530d4
-typedef hist1d *hist2d;		/* type for the 2nd-level pointers */
f530d4
-typedef hist2d *hist3d;		/* type for third-level pointer */
f530d4
-typedef hist3d *hist4d;		/* type for top-level pointer */
f530d4
-
f530d4
-
f530d4
-/* Declarations for Floyd-Steinberg dithering.
f530d4
-
f530d4
- * Errors are accumulated into the array fserrors[], at a resolution of
f530d4
- * 1/16th of a pixel count.  The error at a given pixel is propagated
f530d4
- * to its not-yet-processed neighbors using the standard F-S fractions,
f530d4
- *              ...     (here)  7/16
f530d4
- *              3/16    5/16    1/16
f530d4
- * We work left-to-right on even rows, right-to-left on odd rows.
f530d4
- *
f530d4
- * We can get away with a single array (holding one row's worth of errors)
f530d4
- * by using it to store the current row's errors at pixel columns not yet
f530d4
- * processed, but the next row's errors at columns already processed.  We
f530d4
- * need only a few extra variables to hold the errors immediately around the
f530d4
- * current column.  (If we are lucky, those variables are in registers, but
f530d4
- * even if not, they're probably cheaper to access than array elements are.)
f530d4
- *
f530d4
- * The fserrors[] array has (#columns + 2) entries; the extra entry at
f530d4
- * each end saves us from special-casing the first and last pixels.
f530d4
- * Each entry is three values long, one value for each color component.
f530d4
- *
f530d4
- */
f530d4
-
f530d4
-typedef signed short FSERROR;	/* 16 bits should be enough */
f530d4
-typedef int LOCFSERROR;		/* use 'int' for calculation temps */
f530d4
-
f530d4
-typedef FSERROR *FSERRPTR;	/* pointer to error array */
f530d4
-
f530d4
-/* Private object */
f530d4
-
f530d4
-typedef struct
f530d4
-  {
f530d4
-    hist4d histogram;		/* pointer to the histogram */
f530d4
-    int needs_zeroed;		/* TRUE if next pass must zero histogram */
f530d4
-
f530d4
-    /* Variables for Floyd-Steinberg dithering */
f530d4
-    FSERRPTR fserrors;		/* accumulated errors */
f530d4
-    int on_odd_row;		/* flag to remember which row we are on */
f530d4
-    int *error_limiter;		/* table for clamping the applied error */
f530d4
-    int *error_limiter_storage;	/* gdMalloc'd storage for the above */
f530d4
-    int transparentIsPresent;	/* TBB: for rescaling to ensure that */
f530d4
-    int opaqueIsPresent;	/* 100% opacity & transparency are preserved */
f530d4
-  }
f530d4
-my_cquantizer;
f530d4
-
f530d4
-typedef my_cquantizer *my_cquantize_ptr;
f530d4
-
f530d4
-/*
f530d4
- * Prescan the pixel array. 
f530d4
- * 
f530d4
- * The prescan simply updates the histogram, which has been
f530d4
- * initialized to zeroes by start_pass.
f530d4
- *
f530d4
- */
f530d4
-
f530d4
-static void
f530d4
-prescan_quantize (gdImagePtr im, my_cquantize_ptr cquantize)
f530d4
-{
f530d4
-  register histptr histp;
f530d4
-  register hist4d histogram = cquantize->histogram;
f530d4
-  int row;
f530d4
-  int col;
f530d4
-  int *ptr;
f530d4
-  int width = im->sx;
f530d4
-
f530d4
-  for (row = 0; row < im->sy; row++)
f530d4
-    {
f530d4
-      ptr = im->tpixels[row];
f530d4
-      for (col = width; col > 0; col--)
f530d4
-	{
f530d4
-	  /* get pixel value and index into the histogram */
f530d4
-	  int r, g, b, a;
f530d4
-	  r = gdTrueColorGetRed (*ptr) >> C0_SHIFT;
f530d4
-	  g = gdTrueColorGetGreen (*ptr) >> C1_SHIFT;
f530d4
-	  b = gdTrueColorGetBlue (*ptr) >> C2_SHIFT;
f530d4
-	  a = gdTrueColorGetAlpha (*ptr);
f530d4
-	  /* We must have 100% opacity and transparency available
f530d4
-	     in the color map to do an acceptable job with alpha 
f530d4
-	     channel, if opacity and transparency are present in the
f530d4
-	     original, because of the visual properties of large
f530d4
-	     flat-color border areas (requiring 100% transparency) 
f530d4
-	     and the behavior of poorly implemented browsers 
f530d4
-	     (requiring 100% opacity). Test for the presence of
f530d4
-	     these here, and rescale the most opaque and transparent
f530d4
-	     palette entries at the end if so. This avoids the need
f530d4
-	     to develop a fuller understanding I have not been able
f530d4
-	     to reach so far in my study of this subject. TBB */
f530d4
-	  if (a == gdAlphaTransparent)
f530d4
-	    {
f530d4
-	      cquantize->transparentIsPresent = 1;
f530d4
-	    }
f530d4
-	  if (a == gdAlphaOpaque)
f530d4
-	    {
f530d4
-	      cquantize->opaqueIsPresent = 1;
f530d4
-	    }
f530d4
-	  a >>= C3_SHIFT;
f530d4
-	  histp = &histogram[r][g][b][a];
f530d4
-	  /* increment, check for overflow and undo increment if so. */
f530d4
-	  if (++(*histp) <= 0)
f530d4
-	    (*histp)--;
f530d4
-	  ptr++;
f530d4
-	}
f530d4
-    }
f530d4
-}
f530d4
-
f530d4
-
f530d4
-/*
f530d4
- * Next we have the really interesting routines: selection of a colormap
f530d4
- * given the completed histogram.
f530d4
- * These routines work with a list of "boxes", each representing a rectangular
f530d4
- * subset of the input color space (to histogram precision).
f530d4
- */
f530d4
-
f530d4
-typedef struct
f530d4
-{
f530d4
-  /* The bounds of the box (inclusive); expressed as histogram indexes */
f530d4
-  int c0min, c0max;
f530d4
-  int c1min, c1max;
f530d4
-  int c2min, c2max;
f530d4
-  int c3min, c3max;
f530d4
-  /* The volume (actually 2-norm) of the box */
f530d4
-  int volume;
f530d4
-  /* The number of nonzero histogram cells within this box */
f530d4
-  long colorcount;
f530d4
-}
f530d4
-box;
f530d4
-
f530d4
-typedef box *boxptr;
f530d4
-
f530d4
-static boxptr
f530d4
-find_biggest_color_pop (boxptr boxlist, int numboxes)
f530d4
-/* Find the splittable box with the largest color population */
f530d4
-/* Returns NULL if no splittable boxes remain */
f530d4
-{
f530d4
-  register boxptr boxp;
f530d4
-  register int i;
f530d4
-  register long maxc = 0;
f530d4
-  boxptr which = NULL;
f530d4
-
f530d4
-  for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++)
f530d4
-    {
f530d4
-      if (boxp->colorcount > maxc && boxp->volume > 0)
f530d4
-	{
f530d4
-	  which = boxp;
f530d4
-	  maxc = boxp->colorcount;
f530d4
-	}
f530d4
-    }
f530d4
-  return which;
f530d4
-}
f530d4
-
f530d4
-
f530d4
-static boxptr
f530d4
-find_biggest_volume (boxptr boxlist, int numboxes)
f530d4
-/* Find the splittable box with the largest (scaled) volume */
f530d4
-/* Returns NULL if no splittable boxes remain */
f530d4
-{
f530d4
-  register boxptr boxp;
f530d4
-  register int i;
f530d4
-  register int maxv = 0;
f530d4
-  boxptr which = NULL;
f530d4
-
f530d4
-  for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++)
f530d4
-    {
f530d4
-      if (boxp->volume > maxv)
f530d4
-	{
f530d4
-	  which = boxp;
f530d4
-	  maxv = boxp->volume;
f530d4
-	}
f530d4
-    }
f530d4
-  return which;
f530d4
-}
f530d4
-
f530d4
-
f530d4
-static void
f530d4
-update_box (my_cquantize_ptr cquantize, boxptr boxp)
f530d4
-/* Shrink the min/max bounds of a box to enclose only nonzero elements, */
f530d4
-/* and recompute its volume and population */
f530d4
-{
f530d4
-  hist4d histogram = cquantize->histogram;
f530d4
-  histptr histp;
f530d4
-  int c0, c1, c2, c3;
f530d4
-  int c0min, c0max, c1min, c1max, c2min, c2max, c3min, c3max;
f530d4
-  int dist0, dist1, dist2, dist3;
f530d4
-  long ccount;
f530d4
-
f530d4
-  c0min = boxp->c0min;
f530d4
-  c0max = boxp->c0max;
f530d4
-  c1min = boxp->c1min;
f530d4
-  c1max = boxp->c1max;
f530d4
-  c2min = boxp->c2min;
f530d4
-  c2max = boxp->c2max;
f530d4
-  c3min = boxp->c3min;
f530d4
-  c3max = boxp->c3max;
f530d4
-
f530d4
-  if (c0max > c0min)
f530d4
-    {
f530d4
-      for (c0 = c0min; c0 <= c0max; c0++)
f530d4
-	{
f530d4
-	  for (c1 = c1min; c1 <= c1max; c1++)
f530d4
-	    {
f530d4
-	      for (c2 = c2min; c2 <= c2max; c2++)
f530d4
-		{
f530d4
-		  histp = &histogram[c0][c1][c2][c3min];
f530d4
-		  for (c3 = c3min; c3 <= c3max; c3++)
f530d4
-		    {
f530d4
-		      if (*histp++ != 0)
f530d4
-			{
f530d4
-			  boxp->c0min = c0min = c0;
f530d4
-			  goto have_c0min;
f530d4
-			}
f530d4
-		    }
f530d4
-		}
f530d4
-	    }
f530d4
-	}
f530d4
-    }
f530d4
-have_c0min:
f530d4
-  if (c0max > c0min)
f530d4
-    {
f530d4
-      for (c0 = c0max; c0 >= c0min; c0--)
f530d4
-	{
f530d4
-	  for (c1 = c1min; c1 <= c1max; c1++)
f530d4
-	    {
f530d4
-	      for (c2 = c2min; c2 <= c2max; c2++)
f530d4
-		{
f530d4
-		  histp = &histogram[c0][c1][c2][c3min];
f530d4
-		  for (c3 = c3min; c3 <= c3max; c3++)
f530d4
-		    {
f530d4
-		      if (*histp++ != 0)
f530d4
-			{
f530d4
-			  boxp->c0max = c0max = c0;
f530d4
-			  goto have_c0max;
f530d4
-			}
f530d4
-		    }
f530d4
-		}
f530d4
-	    }
f530d4
-	}
f530d4
-    }
f530d4
-have_c0max:
f530d4
-  if (c1max > c1min)
f530d4
-    for (c1 = c1min; c1 <= c1max; c1++)
f530d4
-      for (c0 = c0min; c0 <= c0max; c0++)
f530d4
-	{
f530d4
-	  for (c2 = c2min; c2 <= c2max; c2++)
f530d4
-	    {
f530d4
-	      histp = &histogram[c0][c1][c2][c3min];
f530d4
-	      for (c3 = c3min; c3 <= c3max; c3++)
f530d4
-		if (*histp++ != 0)
f530d4
-		  {
f530d4
-		    boxp->c1min = c1min = c1;
f530d4
-		    goto have_c1min;
f530d4
-		  }
f530d4
-	    }
f530d4
-	}
f530d4
-have_c1min:
f530d4
-  if (c1max > c1min)
f530d4
-    for (c1 = c1max; c1 >= c1min; c1--)
f530d4
-      for (c0 = c0min; c0 <= c0max; c0++)
f530d4
-	{
f530d4
-	  for (c2 = c2min; c2 <= c2max; c2++)
f530d4
-	    {
f530d4
-	      histp = &histogram[c0][c1][c2][c3min];
f530d4
-	      for (c3 = c3min; c3 <= c3max; c3++)
f530d4
-		if (*histp++ != 0)
f530d4
-		  {
f530d4
-		    boxp->c1max = c1max = c1;
f530d4
-		    goto have_c1max;
f530d4
-		  }
f530d4
-	    }
f530d4
-	}
f530d4
-have_c1max:
f530d4
-  /* The original version hand-rolled the array lookup a little, but
f530d4
-     with four dimensions, I don't even want to think about it. TBB */
f530d4
-  if (c2max > c2min)
f530d4
-    for (c2 = c2min; c2 <= c2max; c2++)
f530d4
-      for (c0 = c0min; c0 <= c0max; c0++)
f530d4
-	for (c1 = c1min; c1 <= c1max; c1++)
f530d4
-	  for (c3 = c3min; c3 <= c3max; c3++)
f530d4
-	    if (histogram[c0][c1][c2][c3] != 0)
f530d4
-	      {
f530d4
-		boxp->c2min = c2min = c2;
f530d4
-		goto have_c2min;
f530d4
-	      }
f530d4
-have_c2min:
f530d4
-  if (c2max > c2min)
f530d4
-    for (c2 = c2max; c2 >= c2min; c2--)
f530d4
-      for (c0 = c0min; c0 <= c0max; c0++)
f530d4
-	for (c1 = c1min; c1 <= c1max; c1++)
f530d4
-	  for (c3 = c3min; c3 <= c3max; c3++)
f530d4
-	    if (histogram[c0][c1][c2][c3] != 0)
f530d4
-	      {
f530d4
-		boxp->c2max = c2max = c2;
f530d4
-		goto have_c2max;
f530d4
-	      }
f530d4
-have_c2max:
f530d4
-  if (c3max > c3min)
f530d4
-    for (c3 = c3min; c3 <= c3max; c3++)
f530d4
-      for (c0 = c0min; c0 <= c0max; c0++)
f530d4
-	for (c1 = c1min; c1 <= c1max; c1++)
f530d4
-	  for (c2 = c2min; c2 <= c2max; c2++)
f530d4
-	    if (histogram[c0][c1][c2][c3] != 0)
f530d4
-	      {
f530d4
-		boxp->c3min = c3min = c3;
f530d4
-		goto have_c3min;
f530d4
-	      }
f530d4
-have_c3min:
f530d4
-  if (c3max > c3min)
f530d4
-    for (c3 = c3max; c3 >= c3min; c3--)
f530d4
-      for (c0 = c0min; c0 <= c0max; c0++)
f530d4
-	for (c1 = c1min; c1 <= c1max; c1++)
f530d4
-	  for (c2 = c2min; c2 <= c2max; c2++)
f530d4
-	    if (histogram[c0][c1][c2][c3] != 0)
f530d4
-	      {
f530d4
-		boxp->c3max = c3max = c3;
f530d4
-		goto have_c3max;
f530d4
-	      }
f530d4
-have_c3max:
f530d4
-  /* Update box volume.
f530d4
-   * We use 2-norm rather than real volume here; this biases the method
f530d4
-   * against making long narrow boxes, and it has the side benefit that
f530d4
-   * a box is splittable iff norm > 0.
f530d4
-   * Since the differences are expressed in histogram-cell units,
f530d4
-   * we have to shift back to 8-bit units to get consistent distances; 
f530d4
-   * after which, we scale according to the selected distance scale factors.
f530d4
-   * TBB: alpha shifts back to 7 bit units. That was accounted for in the
f530d4
-   * alpha scale factor. 
f530d4
-   */
f530d4
-  dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
f530d4
-  dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
f530d4
-  dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
f530d4
-  dist3 = ((c3max - c3min) << C3_SHIFT) * C3_SCALE;
f530d4
-  boxp->volume = dist0 * dist0 + dist1 * dist1 + dist2 * dist2 + dist3 * dist3;
f530d4
-
f530d4
-  /* Now scan remaining volume of box and compute population */
f530d4
-  ccount = 0;
f530d4
-  for (c0 = c0min; c0 <= c0max; c0++)
f530d4
-    for (c1 = c1min; c1 <= c1max; c1++)
f530d4
-      for (c2 = c2min; c2 <= c2max; c2++)
f530d4
-	{
f530d4
-	  histp = &histogram[c0][c1][c2][c3min];
f530d4
-	  for (c3 = c3min; c3 <= c3max; c3++, histp++)
f530d4
-	    if (*histp != 0)
f530d4
-	      {
f530d4
-		ccount++;
f530d4
-	      }
f530d4
-	}
f530d4
-  boxp->colorcount = ccount;
f530d4
-}
f530d4
-
f530d4
-
f530d4
-static int
f530d4
-median_cut (my_cquantize_ptr cquantize,
f530d4
-	    boxptr boxlist, int numboxes,
f530d4
-	    int desired_colors)
f530d4
-/* Repeatedly select and split the largest box until we have enough boxes */
f530d4
-{
f530d4
-  int n, lb;
f530d4
-  int c0, c1, c2, c3, cmax;
f530d4
-  register boxptr b1, b2;
f530d4
-
f530d4
-  while (numboxes < desired_colors)
f530d4
-    {
f530d4
-      /* Select box to split.
f530d4
-       * Current algorithm: by population for first half, then by volume.
f530d4
-       */
f530d4
-      if (numboxes * 2 <= desired_colors)
f530d4
-	{
f530d4
-	  b1 = find_biggest_color_pop (boxlist, numboxes);
f530d4
-	}
f530d4
-      else
f530d4
-	{
f530d4
-	  b1 = find_biggest_volume (boxlist, numboxes);
f530d4
-	}
f530d4
-      if (b1 == NULL)		/* no splittable boxes left! */
f530d4
-	break;
f530d4
-      b2 = &boxlist[numboxes];	/* where new box will go */
f530d4
-      /* Copy the color bounds to the new box. */
f530d4
-      b2->c0max = b1->c0max;
f530d4
-      b2->c1max = b1->c1max;
f530d4
-      b2->c2max = b1->c2max;
f530d4
-      b2->c3max = b1->c3max;
f530d4
-      b2->c0min = b1->c0min;
f530d4
-      b2->c1min = b1->c1min;
f530d4
-      b2->c2min = b1->c2min;
f530d4
-      b2->c3min = b1->c3min;
f530d4
-      /* Choose which axis to split the box on.
f530d4
-       * Current algorithm: longest scaled axis.
f530d4
-       * See notes in update_box about scaling distances.
f530d4
-       */
f530d4
-      c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
f530d4
-      c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
f530d4
-      c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
f530d4
-      c3 = ((b1->c3max - b1->c3min) << C3_SHIFT) * C3_SCALE;
f530d4
-      /* We want to break any ties in favor of green, then red, then blue, 
f530d4
-         with alpha last. */
f530d4
-      cmax = c1;
f530d4
-      n = 1;
f530d4
-      if (c0 > cmax)
f530d4
-	{
f530d4
-	  cmax = c0;
f530d4
-	  n = 0;
f530d4
-	}
f530d4
-      if (c2 > cmax)
f530d4
-	{
f530d4
-	  cmax = c2;
f530d4
-	  n = 2;
f530d4
-	}
f530d4
-      if (c3 > cmax)
f530d4
-	{
f530d4
-	  n = 3;
f530d4
-	}
f530d4
-      /* Choose split point along selected axis, and update box bounds.
f530d4
-       * Current algorithm: split at halfway point.
f530d4
-       * (Since the box has been shrunk to minimum volume,
f530d4
-       * any split will produce two nonempty subboxes.)
f530d4
-       * Note that lb value is max for lower box, so must be < old max.
f530d4
-       */
f530d4
-      switch (n)
f530d4
-	{
f530d4
-	case 0:
f530d4
-	  lb = (b1->c0max + b1->c0min) / 2;
f530d4
-	  b1->c0max = lb;
f530d4
-	  b2->c0min = lb + 1;
f530d4
-	  break;
f530d4
-	case 1:
f530d4
-	  lb = (b1->c1max + b1->c1min) / 2;
f530d4
-	  b1->c1max = lb;
f530d4
-	  b2->c1min = lb + 1;
f530d4
-	  break;
f530d4
-	case 2:
f530d4
-	  lb = (b1->c2max + b1->c2min) / 2;
f530d4
-	  b1->c2max = lb;
f530d4
-	  b2->c2min = lb + 1;
f530d4
-	  break;
f530d4
-	case 3:
f530d4
-	  lb = (b1->c3max + b1->c3min) / 2;
f530d4
-	  b1->c3max = lb;
f530d4
-	  b2->c3min = lb + 1;
f530d4
-	  break;
f530d4
-	}
f530d4
-      /* Update stats for boxes */
f530d4
-      update_box (cquantize, b1);
f530d4
-      update_box (cquantize, b2);
f530d4
-      numboxes++;
f530d4
-    }
f530d4
-  return numboxes;
f530d4
-}
f530d4
-
f530d4
-
f530d4
-static void
f530d4
-compute_color (gdImagePtr im, my_cquantize_ptr cquantize,
f530d4
-	       boxptr boxp, int icolor)
f530d4
-/* 
f530d4
-   Compute representative color for a box, put it in 
f530d4
-   palette index icolor */
f530d4
-{
f530d4
-  /* Current algorithm: mean weighted by pixels (not colors) */
f530d4
-  /* Note it is important to get the rounding correct! */
f530d4
-  hist4d histogram = cquantize->histogram;
f530d4
-  histptr histp;
f530d4
-  int c0, c1, c2, c3;
f530d4
-  int c0min, c0max, c1min, c1max, c2min, c2max, c3min, c3max;
f530d4
-  long count;
f530d4
-  long total = 0;
f530d4
-  long c0total = 0;
f530d4
-  long c1total = 0;
f530d4
-  long c2total = 0;
f530d4
-  long c3total = 0;
f530d4
-
f530d4
-  c0min = boxp->c0min;
f530d4
-  c0max = boxp->c0max;
f530d4
-  c1min = boxp->c1min;
f530d4
-  c1max = boxp->c1max;
f530d4
-  c2min = boxp->c2min;
f530d4
-  c2max = boxp->c2max;
f530d4
-  c3min = boxp->c3min;
f530d4
-  c3max = boxp->c3max;
f530d4
-
f530d4
-  for (c0 = c0min; c0 <= c0max; c0++)
f530d4
-    {
f530d4
-      for (c1 = c1min; c1 <= c1max; c1++)
f530d4
-	{
f530d4
-	  for (c2 = c2min; c2 <= c2max; c2++)
f530d4
-	    {
f530d4
-	      histp = &histogram[c0][c1][c2][c3min];
f530d4
-	      for (c3 = c3min; c3 <= c3max; c3++)
f530d4
-		{
f530d4
-		  if ((count = *histp++) != 0)
f530d4
-		    {
f530d4
-		      total += count;
f530d4
-		      c0total += ((c0 << C0_SHIFT) + ((1 << C0_SHIFT) >> 1)) * count;
f530d4
-		      c1total += ((c1 << C1_SHIFT) + ((1 << C1_SHIFT) >> 1)) * count;
f530d4
-		      c2total += ((c2 << C2_SHIFT) + ((1 << C2_SHIFT) >> 1)) * count;
f530d4
-		      c3total += ((c3 << C3_SHIFT) + ((1 << C3_SHIFT) >> 1)) * count;
f530d4
-		    }
f530d4
-		}
f530d4
-	    }
f530d4
-	}
f530d4
-    }
f530d4
-  if (total)
f530d4
-  {
f530d4
-    im->red[icolor] = (int) ((c0total + (total >> 1)) / total);
f530d4
-    im->green[icolor] = (int) ((c1total + (total >> 1)) / total);
f530d4
-    im->blue[icolor] = (int) ((c2total + (total >> 1)) / total);
f530d4
-    im->alpha[icolor] = (int) ((c3total + (total >> 1)) / total);
f530d4
-  }
f530d4
-  else
f530d4
-  {
f530d4
-    im->red[icolor] = 255;
f530d4
-    im->green[icolor] = 255;
f530d4
-    im->blue[icolor] = 255;
f530d4
-    im->alpha[icolor] = 255;
f530d4
-  }
f530d4
-  im->open[icolor] = 0;
f530d4
-  if (im->colorsTotal <= icolor)
f530d4
-    {
f530d4
-      im->colorsTotal = icolor + 1;
f530d4
-    }
f530d4
-}
f530d4
-
f530d4
-static void
f530d4
-select_colors (gdImagePtr im, my_cquantize_ptr cquantize, int desired_colors)
f530d4
-/* Master routine for color selection */
f530d4
-{
f530d4
-  boxptr boxlist;
f530d4
-  int numboxes;
f530d4
-  int i;
f530d4
-
f530d4
-  /* Allocate workspace for box list */
f530d4
-  boxlist = (boxptr) gdMalloc (desired_colors * sizeof (box));
f530d4
-  /* Initialize one box containing whole space */
f530d4
-  numboxes = 1;
f530d4
-  /* Note maxval for alpha is different */
f530d4
-  boxlist[0].c0min = 0;
f530d4
-  boxlist[0].c0max = 255 >> C0_SHIFT;
f530d4
-  boxlist[0].c1min = 0;
f530d4
-  boxlist[0].c1max = 255 >> C1_SHIFT;
f530d4
-  boxlist[0].c2min = 0;
f530d4
-  boxlist[0].c2max = 255 >> C2_SHIFT;
f530d4
-  boxlist[0].c3min = 0;
f530d4
-  boxlist[0].c3max = gdAlphaMax >> C3_SHIFT;
f530d4
-  /* Shrink it to actually-used volume and set its statistics */
f530d4
-  update_box (cquantize, &boxlist[0]);
f530d4
-  /* Perform median-cut to produce final box list */
f530d4
-  numboxes = median_cut (cquantize, boxlist, numboxes, desired_colors);
f530d4
-  /* Compute the representative color for each box, fill colormap */
f530d4
-  for (i = 0; i < numboxes; i++)
f530d4
-    compute_color (im, cquantize, &boxlist[i], i);
f530d4
-  /* TBB: if the image contains colors at both scaled ends
f530d4
-     of the alpha range, rescale slightly to make sure alpha 
f530d4
-     covers the full spectrum from 100% transparent to 100% 
f530d4
-     opaque. Even a faint distinct background color is 
f530d4
-     generally considered failure with regard to alpha. */
f530d4
-
f530d4
-  im->colorsTotal = numboxes;
f530d4
-  gdFree (boxlist);
f530d4
-}
f530d4
-
f530d4
-
f530d4
-/*
f530d4
- * These routines are concerned with the time-critical task of mapping input
f530d4
- * colors to the nearest color in the selected colormap.
f530d4
- *
f530d4
- * We re-use the histogram space as an "inverse color map", essentially a
f530d4
- * cache for the results of nearest-color searches.  All colors within a
f530d4
- * histogram cell will be mapped to the same colormap entry, namely the one
f530d4
- * closest to the cell's center.  This may not be quite the closest entry to
f530d4
- * the actual input color, but it's almost as good.  A zero in the cache
f530d4
- * indicates we haven't found the nearest color for that cell yet; the array
f530d4
- * is cleared to zeroes before starting the mapping pass.  When we find the
f530d4
- * nearest color for a cell, its colormap index plus one is recorded in the
f530d4
- * cache for future use.  The pass2 scanning routines call fill_inverse_cmap
f530d4
- * when they need to use an unfilled entry in the cache.
f530d4
- *
f530d4
- * Our method of efficiently finding nearest colors is based on the "locally
f530d4
- * sorted search" idea described by Heckbert and on the incremental distance
f530d4
- * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
f530d4
- * Gems II (James Arvo, ed.  Academic Press, 1991).  Thomas points out that
f530d4
- * the distances from a given colormap entry to each cell of the histogram can
f530d4
- * be computed quickly using an incremental method: the differences between
f530d4
- * distances to adjacent cells themselves differ by a constant.  This allows a
f530d4
- * fairly fast implementation of the "brute force" approach of computing the
f530d4
- * distance from every colormap entry to every histogram cell.  Unfortunately,
f530d4
- * it needs a work array to hold the best-distance-so-far for each histogram
f530d4
- * cell (because the inner loop has to be over cells, not colormap entries).
f530d4
- * The work array elements have to be INT32s, so the work array would need
f530d4
- * 256Kb at our recommended precision.  This is not feasible in DOS machines.
f530d4
- *
f530d4
- * To get around these problems, we apply Thomas' method to compute the
f530d4
- * nearest colors for only the cells within a small subbox of the histogram.
f530d4
- * The work array need be only as big as the subbox, so the memory usage
f530d4
- * problem is solved.  Furthermore, we need not fill subboxes that are never
f530d4
- * referenced in pass2; many images use only part of the color gamut, so a
f530d4
- * fair amount of work is saved.  An additional advantage of this
f530d4
- * approach is that we can apply Heckbert's locality criterion to quickly
f530d4
- * eliminate colormap entries that are far away from the subbox; typically
f530d4
- * three-fourths of the colormap entries are rejected by Heckbert's criterion,
f530d4
- * and we need not compute their distances to individual cells in the subbox.
f530d4
- * The speed of this approach is heavily influenced by the subbox size: too
f530d4
- * small means too much overhead, too big loses because Heckbert's criterion
f530d4
- * can't eliminate as many colormap entries.  Empirically the best subbox
f530d4
- * size seems to be about 1/512th of the histogram (1/8th in each direction).
f530d4
- *
f530d4
- * Thomas' article also describes a refined method which is asymptotically
f530d4
- * faster than the brute-force method, but it is also far more complex and
f530d4
- * cannot efficiently be applied to small subboxes.  It is therefore not
f530d4
- * useful for programs intended to be portable to DOS machines.  On machines
f530d4
- * with plenty of memory, filling the whole histogram in one shot with Thomas'
f530d4
- * refined method might be faster than the present code --- but then again,
f530d4
- * it might not be any faster, and it's certainly more complicated.
f530d4
- */
f530d4
-
f530d4
-
f530d4
-/* log2(histogram cells in update box) for each axis; this can be adjusted */
f530d4
-#define BOX_C0_LOG  (HIST_C0_BITS-3)
f530d4
-#define BOX_C1_LOG  (HIST_C1_BITS-3)
f530d4
-#define BOX_C2_LOG  (HIST_C2_BITS-3)
f530d4
-#define BOX_C3_LOG  (HIST_C3_BITS-3)
f530d4
-
f530d4
-#define BOX_C0_ELEMS  (1<
f530d4
-#define BOX_C1_ELEMS  (1<
f530d4
-#define BOX_C2_ELEMS  (1<
f530d4
-#define BOX_C3_ELEMS  (1<
f530d4
-
f530d4
-#define BOX_C0_SHIFT  (C0_SHIFT + BOX_C0_LOG)
f530d4
-#define BOX_C1_SHIFT  (C1_SHIFT + BOX_C1_LOG)
f530d4
-#define BOX_C2_SHIFT  (C2_SHIFT + BOX_C2_LOG)
f530d4
-#define BOX_C3_SHIFT  (C3_SHIFT + BOX_C3_LOG)
f530d4
-
f530d4
-
f530d4
-/*
f530d4
- * The next three routines implement inverse colormap filling.  They could
f530d4
- * all be folded into one big routine, but splitting them up this way saves
f530d4
- * some stack space (the mindist[] and bestdist[] arrays need not coexist)
f530d4
- * and may allow some compilers to produce better code by registerizing more
f530d4
- * inner-loop variables.
f530d4
- */
f530d4
-
f530d4
-static int
f530d4
-find_nearby_colors (gdImagePtr im,
f530d4
-		int minc0, int minc1, int minc2, int minc3, int colorlist[])
f530d4
-/* Locate the colormap entries close enough to an update box to be candidates
f530d4
- * for the nearest entry to some cell(s) in the update box.  The update box
f530d4
- * is specified by the center coordinates of its first cell.  The number of
f530d4
- * candidate colormap entries is returned, and their colormap indexes are
f530d4
- * placed in colorlist[].
f530d4
- * This routine uses Heckbert's "locally sorted search" criterion to select
f530d4
- * the colors that need further consideration.
f530d4
- */
f530d4
-{
f530d4
-  int numcolors = im->colorsTotal;
f530d4
-  int maxc0, maxc1, maxc2, maxc3;
f530d4
-  int centerc0, centerc1, centerc2, centerc3;
f530d4
-  int i, x, ncolors;
f530d4
-  int minmaxdist, min_dist, max_dist, tdist;
f530d4
-  int mindist[MAXNUMCOLORS];	/* min distance to colormap entry i */
f530d4
-
f530d4
-  /* Compute true coordinates of update box's upper corner and center.
f530d4
-   * Actually we compute the coordinates of the center of the upper-corner
f530d4
-   * histogram cell, which are the upper bounds of the volume we care about.
f530d4
-   * Note that since ">>" rounds down, the "center" values may be closer to
f530d4
-   * min than to max; hence comparisons to them must be "<=", not "<".
f530d4
-   */
f530d4
-  maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
f530d4
-  centerc0 = (minc0 + maxc0) >> 1;
f530d4
-  maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
f530d4
-  centerc1 = (minc1 + maxc1) >> 1;
f530d4
-  maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
f530d4
-  centerc2 = (minc2 + maxc2) >> 1;
f530d4
-  maxc3 = minc3 + ((1 << BOX_C3_SHIFT) - (1 << C3_SHIFT));
f530d4
-  centerc3 = (minc3 + maxc3) >> 1;
f530d4
-
f530d4
-  /* For each color in colormap, find:
f530d4
-   *  1. its minimum squared-distance to any point in the update box
f530d4
-   *     (zero if color is within update box);
f530d4
-   *  2. its maximum squared-distance to any point in the update box.
f530d4
-   * Both of these can be found by considering only the corners of the box.
f530d4
-   * We save the minimum distance for each color in mindist[];
f530d4
-   * only the smallest maximum distance is of interest.
f530d4
-   */
f530d4
-  minmaxdist = 0x7FFFFFFFL;
f530d4
-
f530d4
-  for (i = 0; i < numcolors; i++)
f530d4
-    {
f530d4
-      /* We compute the squared-c0-distance term, then add in the other three. */
f530d4
-      x = im->red[i];
f530d4
-      if (x < minc0)
f530d4
-	{
f530d4
-	  tdist = (x - minc0) * C0_SCALE;
f530d4
-	  min_dist = tdist * tdist;
f530d4
-	  tdist = (x - maxc0) * C0_SCALE;
f530d4
-	  max_dist = tdist * tdist;
f530d4
-	}
f530d4
-      else if (x > maxc0)
f530d4
-	{
f530d4
-	  tdist = (x - maxc0) * C0_SCALE;
f530d4
-	  min_dist = tdist * tdist;
f530d4
-	  tdist = (x - minc0) * C0_SCALE;
f530d4
-	  max_dist = tdist * tdist;
f530d4
-	}
f530d4
-      else
f530d4
-	{
f530d4
-	  /* within cell range so no contribution to min_dist */
f530d4
-	  min_dist = 0;
f530d4
-	  if (x <= centerc0)
f530d4
-	    {
f530d4
-	      tdist = (x - maxc0) * C0_SCALE;
f530d4
-	      max_dist = tdist * tdist;
f530d4
-	    }
f530d4
-	  else
f530d4
-	    {
f530d4
-	      tdist = (x - minc0) * C0_SCALE;
f530d4
-	      max_dist = tdist * tdist;
f530d4
-	    }
f530d4
-	}
f530d4
-
f530d4
-      x = im->green[i];
f530d4
-      if (x < minc1)
f530d4
-	{
f530d4
-	  tdist = (x - minc1) * C1_SCALE;
f530d4
-	  min_dist += tdist * tdist;
f530d4
-	  tdist = (x - maxc1) * C1_SCALE;
f530d4
-	  max_dist += tdist * tdist;
f530d4
-	}
f530d4
-      else if (x > maxc1)
f530d4
-	{
f530d4
-	  tdist = (x - maxc1) * C1_SCALE;
f530d4
-	  min_dist += tdist * tdist;
f530d4
-	  tdist = (x - minc1) * C1_SCALE;
f530d4
-	  max_dist += tdist * tdist;
f530d4
-	}
f530d4
-      else
f530d4
-	{
f530d4
-	  /* within cell range so no contribution to min_dist */
f530d4
-	  if (x <= centerc1)
f530d4
-	    {
f530d4
-	      tdist = (x - maxc1) * C1_SCALE;
f530d4
-	      max_dist += tdist * tdist;
f530d4
-	    }
f530d4
-	  else
f530d4
-	    {
f530d4
-	      tdist = (x - minc1) * C1_SCALE;
f530d4
-	      max_dist += tdist * tdist;
f530d4
-	    }
f530d4
-	}
f530d4
-
f530d4
-      x = im->blue[i];
f530d4
-      if (x < minc2)
f530d4
-	{
f530d4
-	  tdist = (x - minc2) * C2_SCALE;
f530d4
-	  min_dist += tdist * tdist;
f530d4
-	  tdist = (x - maxc2) * C2_SCALE;
f530d4
-	  max_dist += tdist * tdist;
f530d4
-	}
f530d4
-      else if (x > maxc2)
f530d4
-	{
f530d4
-	  tdist = (x - maxc2) * C2_SCALE;
f530d4
-	  min_dist += tdist * tdist;
f530d4
-	  tdist = (x - minc2) * C2_SCALE;
f530d4
-	  max_dist += tdist * tdist;
f530d4
-	}
f530d4
-      else
f530d4
-	{
f530d4
-	  /* within cell range so no contribution to min_dist */
f530d4
-	  if (x <= centerc2)
f530d4
-	    {
f530d4
-	      tdist = (x - maxc2) * C2_SCALE;
f530d4
-	      max_dist += tdist * tdist;
f530d4
-	    }
f530d4
-	  else
f530d4
-	    {
f530d4
-	      tdist = (x - minc2) * C2_SCALE;
f530d4
-	      max_dist += tdist * tdist;
f530d4
-	    }
f530d4
-	}
f530d4
-
f530d4
-      x = im->alpha[i];
f530d4
-      if (x < minc3)
f530d4
-	{
f530d4
-	  tdist = (x - minc3) * C3_SCALE;
f530d4
-	  min_dist += tdist * tdist;
f530d4
-	  tdist = (x - maxc3) * C3_SCALE;
f530d4
-	  max_dist += tdist * tdist;
f530d4
-	}
f530d4
-      else if (x > maxc3)
f530d4
-	{
f530d4
-	  tdist = (x - maxc3) * C3_SCALE;
f530d4
-	  min_dist += tdist * tdist;
f530d4
-	  tdist = (x - minc3) * C3_SCALE;
f530d4
-	  max_dist += tdist * tdist;
f530d4
-	}
f530d4
-      else
f530d4
-	{
f530d4
-	  /* within cell range so no contribution to min_dist */
f530d4
-	  if (x <= centerc3)
f530d4
-	    {
f530d4
-	      tdist = (x - maxc3) * C3_SCALE;
f530d4
-	      max_dist += tdist * tdist;
f530d4
-	    }
f530d4
-	  else
f530d4
-	    {
f530d4
-	      tdist = (x - minc3) * C3_SCALE;
f530d4
-	      max_dist += tdist * tdist;
f530d4
-	    }
f530d4
-	}
f530d4
-
f530d4
-      mindist[i] = min_dist;	/* save away the results */
f530d4
-      if (max_dist < minmaxdist)
f530d4
-	minmaxdist = max_dist;
f530d4
-    }
f530d4
-
f530d4
-  /* Now we know that no cell in the update box is more than minmaxdist
f530d4
-   * away from some colormap entry.  Therefore, only colors that are
f530d4
-   * within minmaxdist of some part of the box need be considered.
f530d4
-   */
f530d4
-  ncolors = 0;
f530d4
-  for (i = 0; i < numcolors; i++)
f530d4
-    {
f530d4
-      if (mindist[i] <= minmaxdist)
f530d4
-	colorlist[ncolors++] = i;
f530d4
-    }
f530d4
-  return ncolors;
f530d4
-}
f530d4
-
f530d4
-
f530d4
-static void
f530d4
-find_best_colors (gdImagePtr im,
f530d4
-		  int minc0, int minc1, int minc2, int minc3,
f530d4
-		  int numcolors, int colorlist[], int bestcolor[])
f530d4
-/* Find the closest colormap entry for each cell in the update box,
f530d4
- * given the list of candidate colors prepared by find_nearby_colors.
f530d4
- * Return the indexes of the closest entries in the bestcolor[] array.
f530d4
- * This routine uses Thomas' incremental distance calculation method to
f530d4
- * find the distance from a colormap entry to successive cells in the box.
f530d4
- */
f530d4
-{
f530d4
-  int ic0, ic1, ic2, ic3;
f530d4
-  int i, icolor;
f530d4
-  register int *bptr;		/* pointer into bestdist[] array */
f530d4
-  int *cptr;			/* pointer into bestcolor[] array */
f530d4
-  int dist0, dist1, dist2;	/* initial distance values */
f530d4
-  register int dist3 = 0;	/* current distance in inner loop */
f530d4
-  int xx0, xx1, xx2;		/* distance increments */
f530d4
-  register int xx3 = 0;
f530d4
-  int inc0, inc1, inc2, inc3;	/* initial values for increments */
f530d4
-  /* This array holds the distance to the nearest-so-far color for each cell */
f530d4
-  int bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS * BOX_C3_ELEMS];
f530d4
-
f530d4
-  /* Initialize best-distance for each cell of the update box */
f530d4
-  bptr = bestdist;
f530d4
-  for (i = BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS * BOX_C3_ELEMS - 1; i >= 0; i--)
f530d4
-    *bptr++ = 0x7FFFFFFFL;
f530d4
-
f530d4
-  /* For each color selected by find_nearby_colors,
f530d4
-   * compute its distance to the center of each cell in the box.
f530d4
-   * If that's less than best-so-far, update best distance and color number.
f530d4
-   */
f530d4
-
f530d4
-  /* Nominal steps between cell centers ("x" in Thomas article) */
f530d4
-#define STEP_C0  ((1 << C0_SHIFT) * C0_SCALE)
f530d4
-#define STEP_C1  ((1 << C1_SHIFT) * C1_SCALE)
f530d4
-#define STEP_C2  ((1 << C2_SHIFT) * C2_SCALE)
f530d4
-#define STEP_C3  ((1 << C3_SHIFT) * C3_SCALE)
f530d4
-
f530d4
-  for (i = 0; i < numcolors; i++)
f530d4
-    {
f530d4
-      icolor = colorlist[i];
f530d4
-      /* Compute (square of) distance from minc0/c1/c2 to this color */
f530d4
-      inc0 = (minc0 - (im->red[icolor])) * C0_SCALE;
f530d4
-      dist0 = inc0 * inc0;
f530d4
-      inc1 = (minc1 - (im->green[icolor])) * C1_SCALE;
f530d4
-      dist0 += inc1 * inc1;
f530d4
-      inc2 = (minc2 - (im->blue[icolor])) * C2_SCALE;
f530d4
-      dist0 += inc2 * inc2;
f530d4
-      inc3 = (minc3 - (im->alpha[icolor])) * C3_SCALE;
f530d4
-      dist0 += inc3 * inc3;
f530d4
-      /* Form the initial difference increments */
f530d4
-      inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
f530d4
-      inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
f530d4
-      inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
f530d4
-      inc3 = inc3 * (2 * STEP_C3) + STEP_C3 * STEP_C3;
f530d4
-      /* Now loop over all cells in box, updating distance per Thomas method */
f530d4
-      bptr = bestdist;
f530d4
-      cptr = bestcolor;
f530d4
-      xx0 = inc0;
f530d4
-      for (ic0 = BOX_C0_ELEMS - 1; ic0 >= 0; ic0--)
f530d4
-	{
f530d4
-	  dist1 = dist0;
f530d4
-	  xx1 = inc1;
f530d4
-	  for (ic1 = BOX_C1_ELEMS - 1; ic1 >= 0; ic1--)
f530d4
-	    {
f530d4
-	      dist2 = dist1;
f530d4
-	      xx2 = inc2;
f530d4
-	      for (ic2 = BOX_C2_ELEMS - 1; ic2 >= 0; ic2--)
f530d4
-		{
f530d4
-		  for (ic3 = BOX_C3_ELEMS - 1; ic3 >= 0; ic3--)
f530d4
-		    {
f530d4
-		      if (dist3 < *bptr)
f530d4
-			{
f530d4
-			  *bptr = dist3;
f530d4
-			  *cptr = icolor;
f530d4
-			}
f530d4
-		      dist3 += xx3;
f530d4
-		      xx3 += 2 * STEP_C3 * STEP_C3;
f530d4
-		      bptr++;
f530d4
-		      cptr++;
f530d4
-		    }
f530d4
-		  dist2 += xx2;
f530d4
-		  xx2 += 2 * STEP_C2 * STEP_C2;
f530d4
-		}
f530d4
-	      dist1 += xx1;
f530d4
-	      xx1 += 2 * STEP_C1 * STEP_C1;
f530d4
-	    }
f530d4
-	  dist0 += xx0;
f530d4
-	  xx0 += 2 * STEP_C0 * STEP_C0;
f530d4
-	}
f530d4
-    }
f530d4
-}
f530d4
-
f530d4
-
f530d4
-static void
f530d4
-fill_inverse_cmap (gdImagePtr im, my_cquantize_ptr cquantize,
f530d4
-		   int c0, int c1, int c2, int c3)
f530d4
-/* Fill the inverse-colormap entries in the update box that contains */
f530d4
-/* histogram cell c0/c1/c2/c3.  (Only that one cell MUST be filled, but */
f530d4
-/* we can fill as many others as we wish.) */
f530d4
-{
f530d4
-  hist4d histogram = cquantize->histogram;
f530d4
-  int minc0, minc1, minc2, minc3;	/* lower left corner of update box */
f530d4
-  int ic0, ic1, ic2, ic3;
f530d4
-  register int *cptr;		/* pointer into bestcolor[] array */
f530d4
-  register histptr cachep;	/* pointer into main cache array */
f530d4
-  /* This array lists the candidate colormap indexes. */
f530d4
-  int colorlist[MAXNUMCOLORS];
f530d4
-  int numcolors;		/* number of candidate colors */
f530d4
-  /* This array holds the actually closest colormap index for each cell. */
f530d4
-  int bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS * BOX_C3_ELEMS];
f530d4
-
f530d4
-  /* Convert cell coordinates to update box ID */
f530d4
-  c0 >>= BOX_C0_LOG;
f530d4
-  c1 >>= BOX_C1_LOG;
f530d4
-  c2 >>= BOX_C2_LOG;
f530d4
-  c3 >>= BOX_C3_LOG;
f530d4
-
f530d4
-  /* Compute true coordinates of update box's origin corner.
f530d4
-   * Actually we compute the coordinates of the center of the corner
f530d4
-   * histogram cell, which are the lower bounds of the volume we care about.
f530d4
-   */
f530d4
-  minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
f530d4
-  minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
f530d4
-  minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
f530d4
-  minc3 = (c3 << BOX_C3_SHIFT) + ((1 << C3_SHIFT) >> 1);
f530d4
-  /* Determine which colormap entries are close enough to be candidates
f530d4
-   * for the nearest entry to some cell in the update box.
f530d4
-   */
f530d4
-  numcolors = find_nearby_colors (im, minc0, minc1, minc2, minc3, colorlist);
f530d4
-
f530d4
-  /* Determine the actually nearest colors. */
f530d4
-  find_best_colors (im, minc0, minc1, minc2, minc3, numcolors, colorlist,
f530d4
-		    bestcolor);
f530d4
-
f530d4
-  /* Save the best color numbers (plus 1) in the main cache array */
f530d4
-  c0 <<= BOX_C0_LOG;		/* convert ID back to base cell indexes */
f530d4
-  c1 <<= BOX_C1_LOG;
f530d4
-  c2 <<= BOX_C2_LOG;
f530d4
-  c3 <<= BOX_C3_LOG;
f530d4
-  cptr = bestcolor;
f530d4
-  for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++)
f530d4
-    {
f530d4
-      for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++)
f530d4
-	{
f530d4
-	  for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++)
f530d4
-	    {
f530d4
-	      cachep = &histogram[c0 + ic0][c1 + ic1][c2 + ic2][c3];
f530d4
-	      for (ic3 = 0; ic3 < BOX_C3_ELEMS; ic3++)
f530d4
-		{
f530d4
-		  *cachep++ = (histcell) ((*cptr++) + 1);
f530d4
-		}
f530d4
-	    }
f530d4
-	}
f530d4
-    }
f530d4
-}
f530d4
-
f530d4
-
f530d4
-/*
f530d4
- * Map some rows of pixels to the output colormapped representation.
f530d4
- */
f530d4
-
f530d4
-static void
f530d4
-pass2_no_dither (gdImagePtr im, my_cquantize_ptr cquantize)
f530d4
-/* This version performs no dithering */
f530d4
-{
f530d4
-  hist4d histogram = cquantize->histogram;
f530d4
-  register int *inptr;
f530d4
-  register unsigned char *outptr;
f530d4
-  register histptr cachep;
f530d4
-  register int c0, c1, c2, c3;
f530d4
-  int row;
f530d4
-  int col;
f530d4
-  int width = im->sx;
f530d4
-  int num_rows = im->sy;
f530d4
-  for (row = 0; row < num_rows; row++)
f530d4
-    {
f530d4
-      inptr = im->tpixels[row];
f530d4
-      outptr = im->pixels[row];
f530d4
-      for (col = 0; col < width; col++)
f530d4
-	{
f530d4
-	  int r, g, b, a;
f530d4
-	  /* get pixel value and index into the cache */
f530d4
-	  r = gdTrueColorGetRed (*inptr);
f530d4
-	  g = gdTrueColorGetGreen (*inptr);
f530d4
-	  b = gdTrueColorGetBlue (*inptr);
f530d4
-	  a = gdTrueColorGetAlpha (*inptr++);
f530d4
-	  c0 = r >> C0_SHIFT;
f530d4
-	  c1 = g >> C1_SHIFT;
f530d4
-	  c2 = b >> C2_SHIFT;
f530d4
-	  c3 = a >> C3_SHIFT;
f530d4
-	  cachep = &histogram[c0][c1][c2][c3];
f530d4
-	  /* If we have not seen this color before, find nearest colormap entry */
f530d4
-	  /* and update the cache */
f530d4
-	  if (*cachep == 0)
f530d4
-	    {
f530d4
-#if 0
f530d4
-	      /* TBB: quick and dirty approach for use when testing
f530d4
-	         fill_inverse_cmap for errors */
f530d4
-	      int i;
f530d4
-	      int best = -1;
f530d4
-	      int mindist = 0x7FFFFFFF;
f530d4
-	      for (i = 0; (i < im->colorsTotal); i++)
f530d4
-		{
f530d4
-		  int rdist = (im->red[i] >> C0_SHIFT) - c0;
f530d4
-		  int gdist = (im->green[i] >> C1_SHIFT) - c1;
f530d4
-		  int bdist = (im->blue[i] >> C2_SHIFT) - c2;
f530d4
-		  int adist = (im->alpha[i] >> C3_SHIFT) - c3;
f530d4
-		  int dist = (rdist * rdist) * R_SCALE +
f530d4
-		  (gdist * gdist) * G_SCALE +
f530d4
-		  (bdist * bdist) * B_SCALE +
f530d4
-		  (adist * adist) * A_SCALE;
f530d4
-		  if (dist < mindist)
f530d4
-		    {
f530d4
-		      best = i;
f530d4
-		      mindist = dist;
f530d4
-		    }
f530d4
-		}
f530d4
-	      *cachep = best + 1;
f530d4
-#endif
f530d4
-	      fill_inverse_cmap (im, cquantize, c0, c1, c2, c3);
f530d4
-	    }
f530d4
-	  /* Now emit the colormap index for this cell */
f530d4
-	  *outptr++ = (*cachep - 1);
f530d4
-	}
f530d4
-    }
f530d4
-}
f530d4
-
f530d4
-/* We assume that right shift corresponds to signed division by 2 with
f530d4
- * rounding towards minus infinity.  This is correct for typical "arithmetic
f530d4
- * shift" instructions that shift in copies of the sign bit.  But some
f530d4
- * C compilers implement >> with an unsigned shift.  For these machines you
f530d4
- * must define RIGHT_SHIFT_IS_UNSIGNED.
f530d4
- * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
f530d4
- * It is only applied with constant shift counts.  SHIFT_TEMPS must be
f530d4
- * included in the variables of any routine using RIGHT_SHIFT.
f530d4
- */
f530d4
-
f530d4
-#ifdef RIGHT_SHIFT_IS_UNSIGNED
f530d4
-#define SHIFT_TEMPS	INT32 shift_temp;
f530d4
-#define RIGHT_SHIFT(x,shft)  \
f530d4
-	((shift_temp = (x)) < 0 ? \
f530d4
-	 (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
f530d4
-	 (shift_temp >> (shft)))
f530d4
-#else
f530d4
-#define SHIFT_TEMPS
f530d4
-#define RIGHT_SHIFT(x,shft)	((x) >> (shft))
f530d4
-#endif
f530d4
-
f530d4
-
f530d4
-static void
f530d4
-pass2_fs_dither (gdImagePtr im, my_cquantize_ptr cquantize)
f530d4
-
f530d4
-/* This version performs Floyd-Steinberg dithering */
f530d4
-{
f530d4
-  hist4d histogram = cquantize->histogram;
f530d4
-  register LOCFSERROR cur0, cur1, cur2, cur3;	/* current error or pixel value */
f530d4
-  LOCFSERROR belowerr0, belowerr1, belowerr2, belowerr3;	/* error for pixel below cur */
f530d4
-  LOCFSERROR bpreverr0, bpreverr1, bpreverr2, bpreverr3;	/* error for below/prev col */
f530d4
-  register FSERRPTR errorptr;	/* => fserrors[] at column before current */
f530d4
-  int *inptr;			/* => current input pixel */
f530d4
-  unsigned char *outptr;	/* => current output pixel */
f530d4
-  histptr cachep;
f530d4
-  int dir;			/* +1 or -1 depending on direction */
f530d4
-  int dir4;			/* 4*dir, for advancing errorptr */
f530d4
-  int row;
f530d4
-  int col;
f530d4
-  int width = im->sx;
f530d4
-  int num_rows = im->sy;
f530d4
-  int *error_limit = cquantize->error_limiter;
f530d4
-  int *colormap0 = im->red;
f530d4
-  int *colormap1 = im->green;
f530d4
-  int *colormap2 = im->blue;
f530d4
-  int *colormap3 = im->alpha;
f530d4
-  SHIFT_TEMPS
f530d4
-
f530d4
-    for (row = 0; row < num_rows; row++)
f530d4
-    {
f530d4
-      inptr = im->tpixels[row];
f530d4
-      outptr = im->pixels[row];
f530d4
-      if (cquantize->on_odd_row)
f530d4
-	{
f530d4
-	  /* work right to left in this row */
f530d4
-	  inptr += (width - 1);	/* so point to rightmost pixel */
f530d4
-	  outptr += width - 1;
f530d4
-	  dir = -1;
f530d4
-	  dir4 = -4;
f530d4
-	  errorptr = cquantize->fserrors + (width + 1) * 4;	/* => entry after last column */
f530d4
-	  cquantize->on_odd_row = FALSE;	/* flip for next time */
f530d4
-	}
f530d4
-      else
f530d4
-	{
f530d4
-	  /* work left to right in this row */
f530d4
-	  dir = 1;
f530d4
-	  dir4 = 4;
f530d4
-	  errorptr = cquantize->fserrors;	/* => entry before first real column */
f530d4
-	  cquantize->on_odd_row = TRUE;		/* flip for next time */
f530d4
-	}
f530d4
-      /* Preset error values: no error propagated to first pixel from left */
f530d4
-      cur0 = cur1 = cur2 = cur3 = 0;
f530d4
-      /* and no error propagated to row below yet */
f530d4
-      belowerr0 = belowerr1 = belowerr2 = belowerr3 = 0;
f530d4
-      bpreverr0 = bpreverr1 = bpreverr2 = bpreverr3 = 0;
f530d4
-
f530d4
-      for (col = width; col > 0; col--)
f530d4
-	{
f530d4
-	  int a;
f530d4
-	  /* curN holds the error propagated from the previous pixel on the
f530d4
-	   * current line.  Add the error propagated from the previous line
f530d4
-	   * to form the complete error correction term for this pixel, and
f530d4
-	   * round the error term (which is expressed * 16) to an integer.
f530d4
-	   * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
f530d4
-	   * for either sign of the error value.
f530d4
-	   * Note: errorptr points to *previous* column's array entry.
f530d4
-	   */
f530d4
-	  cur0 = RIGHT_SHIFT (cur0 + errorptr[dir4 + 0] + 8, 4);
f530d4
-	  cur1 = RIGHT_SHIFT (cur1 + errorptr[dir4 + 1] + 8, 4);
f530d4
-	  cur2 = RIGHT_SHIFT (cur2 + errorptr[dir4 + 2] + 8, 4);
f530d4
-	  cur3 = RIGHT_SHIFT (cur3 + errorptr[dir4 + 3] + 8, 4);
f530d4
-	  /* Limit the error using transfer function set by init_error_limit.
f530d4
-	   * See comments with init_error_limit for rationale.
f530d4
-	   */
f530d4
-	  cur0 = error_limit[cur0];
f530d4
-	  cur1 = error_limit[cur1];
f530d4
-	  cur2 = error_limit[cur2];
f530d4
-	  cur3 = error_limit[cur3];
f530d4
-	  /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
f530d4
-	   * The maximum error is +- MAXJSAMPLE (or less with error limiting);
f530d4
-	   * but we'll be lazy and just clamp this with an if test (TBB).
f530d4
-	   */
f530d4
-	  cur0 += gdTrueColorGetRed (*inptr);
f530d4
-	  cur1 += gdTrueColorGetGreen (*inptr);
f530d4
-	  cur2 += gdTrueColorGetBlue (*inptr);
f530d4
-	  /* Expand to 8 bits for consistency with dithering algorithm -- TBB */
f530d4
-	  a = gdTrueColorGetAlpha (*inptr);
f530d4
-	  cur3 += (a << 1) + (a >> 6);
f530d4
-	  if (cur0 < 0)
f530d4
-	    {
f530d4
-	      cur0 = 0;
f530d4
-	    }
f530d4
-	  if (cur0 > 255)
f530d4
-	    {
f530d4
-	      cur0 = 255;
f530d4
-	    }
f530d4
-	  if (cur1 < 0)
f530d4
-	    {
f530d4
-	      cur1 = 0;
f530d4
-	    }
f530d4
-	  if (cur1 > 255)
f530d4
-	    {
f530d4
-	      cur1 = 255;
f530d4
-	    }
f530d4
-	  if (cur2 < 0)
f530d4
-	    {
f530d4
-	      cur2 = 0;
f530d4
-	    }
f530d4
-	  if (cur2 > 255)
f530d4
-	    {
f530d4
-	      cur2 = 255;
f530d4
-	    }
f530d4
-	  if (cur3 < 0)
f530d4
-	    {
f530d4
-	      cur3 = 0;
f530d4
-	    }
f530d4
-	  if (cur3 > 255)
f530d4
-	    {
f530d4
-	      cur3 = 255;
f530d4
-	    }
f530d4
-	  /* Index into the cache with adjusted pixel value */
f530d4
-	  cachep = &histogram
f530d4
-	    [cur0 >> C0_SHIFT]
f530d4
-	    [cur1 >> C1_SHIFT]
f530d4
-	    [cur2 >> C2_SHIFT]
f530d4
-	    [cur3 >> (C3_SHIFT + 1)];
f530d4
-	  /* If we have not seen this color before, find nearest colormap */
f530d4
-	  /* entry and update the cache */
f530d4
-	  if (*cachep == 0)
f530d4
-	    fill_inverse_cmap (im, cquantize,
f530d4
-		       cur0 >> C0_SHIFT, cur1 >> C1_SHIFT, cur2 >> C2_SHIFT,
f530d4
-			       cur3 >> (C3_SHIFT + 1));
f530d4
-	  /* Now emit the colormap index for this cell */
f530d4
-	  {
f530d4
-	    register int pixcode = *cachep - 1;
f530d4
-	    *outptr = pixcode;
f530d4
-	    /* Compute representation error for this pixel */
f530d4
-	    cur0 -= colormap0[pixcode];
f530d4
-	    cur1 -= colormap1[pixcode];
f530d4
-	    cur2 -= colormap2[pixcode];
f530d4
-	    cur3 -= ((colormap3[pixcode] << 1) + (colormap3[pixcode] >> 6));
f530d4
-	  }
f530d4
-	  /* Compute error fractions to be propagated to adjacent pixels.
f530d4
-	   * Add these into the running sums, and simultaneously shift the
f530d4
-	   * next-line error sums left by 1 column.
f530d4
-	   */
f530d4
-	  {
f530d4
-	    register LOCFSERROR bnexterr, delta;
f530d4
-
f530d4
-	    bnexterr = cur0;	/* Process component 0 */
f530d4
-	    delta = cur0 * 2;
f530d4
-	    cur0 += delta;	/* form error * 3 */
f530d4
-	    errorptr[0] = (FSERROR) (bpreverr0 + cur0);
f530d4
-	    cur0 += delta;	/* form error * 5 */
f530d4
-	    bpreverr0 = belowerr0 + cur0;
f530d4
-	    belowerr0 = bnexterr;
f530d4
-	    cur0 += delta;	/* form error * 7 */
f530d4
-	    bnexterr = cur1;	/* Process component 1 */
f530d4
-	    delta = cur1 * 2;
f530d4
-	    cur1 += delta;	/* form error * 3 */
f530d4
-	    errorptr[1] = (FSERROR) (bpreverr1 + cur1);
f530d4
-	    cur1 += delta;	/* form error * 5 */
f530d4
-	    bpreverr1 = belowerr1 + cur1;
f530d4
-	    belowerr1 = bnexterr;
f530d4
-	    cur1 += delta;	/* form error * 7 */
f530d4
-	    bnexterr = cur2;	/* Process component 2 */
f530d4
-	    delta = cur2 * 2;
f530d4
-	    cur2 += delta;	/* form error * 3 */
f530d4
-	    errorptr[2] = (FSERROR) (bpreverr2 + cur2);
f530d4
-	    cur2 += delta;	/* form error * 5 */
f530d4
-	    bpreverr2 = belowerr2 + cur2;
f530d4
-	    belowerr2 = bnexterr;
f530d4
-	    cur2 += delta;	/* form error * 7 */
f530d4
-	    bnexterr = cur3;	/* Process component 3 */
f530d4
-	    delta = cur3 * 2;
f530d4
-	    cur3 += delta;	/* form error * 3 */
f530d4
-	    errorptr[3] = (FSERROR) (bpreverr3 + cur3);
f530d4
-	    cur3 += delta;	/* form error * 5 */
f530d4
-	    bpreverr3 = belowerr3 + cur3;
f530d4
-	    belowerr3 = bnexterr;
f530d4
-	    cur3 += delta;	/* form error * 7 */
f530d4
-	  }
f530d4
-	  /* At this point curN contains the 7/16 error value to be propagated
f530d4
-	   * to the next pixel on the current line, and all the errors for the
f530d4
-	   * next line have been shifted over.  We are therefore ready to move on.
f530d4
-	   */
f530d4
-	  inptr += dir;		/* Advance pixel pointers to next column */
f530d4
-	  outptr += dir;
f530d4
-	  errorptr += dir4;	/* advance errorptr to current column */
f530d4
-	}
f530d4
-      /* Post-loop cleanup: we must unload the final error values into the
f530d4
-       * final fserrors[] entry.  Note we need not unload belowerrN because
f530d4
-       * it is for the dummy column before or after the actual array.
f530d4
-       */
f530d4
-      errorptr[0] = (FSERROR) bpreverr0;	/* unload prev errs into array */
f530d4
-      errorptr[1] = (FSERROR) bpreverr1;
f530d4
-      errorptr[2] = (FSERROR) bpreverr2;
f530d4
-      errorptr[3] = (FSERROR) bpreverr3;
f530d4
-    }
f530d4
-}
f530d4
-
f530d4
-
f530d4
-/*
f530d4
- * Initialize the error-limiting transfer function (lookup table).
f530d4
- * The raw F-S error computation can potentially compute error values of up to
f530d4
- * +- MAXJSAMPLE.  But we want the maximum correction applied to a pixel to be
f530d4
- * much less, otherwise obviously wrong pixels will be created.  (Typical
f530d4
- * effects include weird fringes at color-area boundaries, isolated bright
f530d4
- * pixels in a dark area, etc.)  The standard advice for avoiding this problem
f530d4
- * is to ensure that the "corners" of the color cube are allocated as output
f530d4
- * colors; then repeated errors in the same direction cannot cause cascading
f530d4
- * error buildup.  However, that only prevents the error from getting
f530d4
- * completely out of hand; Aaron Giles reports that error limiting improves
f530d4
- * the results even with corner colors allocated.
f530d4
- * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
f530d4
- * well, but the smoother transfer function used below is even better.  Thanks
f530d4
- * to Aaron Giles for this idea.
f530d4
- */
f530d4
-
f530d4
-static int
f530d4
-init_error_limit (my_cquantize_ptr cquantize)
f530d4
-/* Allocate and fill in the error_limiter table */
f530d4
-{
f530d4
-  int *table;
f530d4
-  int in, out;
f530d4
-
f530d4
-  cquantize->error_limiter_storage = (int *) gdMalloc ((255 * 2 + 1) * sizeof (int));
f530d4
-  if (!cquantize->error_limiter_storage)
f530d4
-    {
f530d4
-      return 0;
f530d4
-    }
f530d4
-  /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
f530d4
-  cquantize->error_limiter = cquantize->error_limiter_storage + 255;
f530d4
-  table = cquantize->error_limiter;
f530d4
-#define STEPSIZE ((255+1)/16)
f530d4
-  /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
f530d4
-  out = 0;
f530d4
-  for (in = 0; in < STEPSIZE; in++, out++)
f530d4
-    {
f530d4
-      table[in] = out;
f530d4
-      table[-in] = -out;
f530d4
-    }
f530d4
-  /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
f530d4
-  for (; in < STEPSIZE * 3; in++, out += (in & 1) ? 0 : 1)
f530d4
-    {
f530d4
-      table[in] = out;
f530d4
-      table[-in] = -out;
f530d4
-    }
f530d4
-  /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
f530d4
-  for (; in <= 255; in++)
f530d4
-    {
f530d4
-      table[in] = out;
f530d4
-      table[-in] = -out;
f530d4
-    }
f530d4
-#undef STEPSIZE
f530d4
-  return 1;
f530d4
-}
f530d4
-
f530d4
-static void
f530d4
-zeroHistogram (hist4d histogram)
f530d4
-{
f530d4
-  int i;
f530d4
-  int j;
f530d4
-  /* Zero the histogram or inverse color map */
f530d4
-  for (i = 0; i < HIST_C0_ELEMS; i++)
f530d4
-    {
f530d4
-      for (j = 0; j < HIST_C1_ELEMS; j++)
f530d4
-	{
f530d4
-	  memset (histogram[i][j],
f530d4
-		  0,
f530d4
-		  HIST_C2_ELEMS * HIST_C3_ELEMS * sizeof (histcell));
f530d4
-	}
f530d4
-    }
f530d4
-}
f530d4
-
f530d4
-/* Here we go at last. */
f530d4
-void
f530d4
-gdImageTrueColorToPalette (gdImagePtr im, int dither, int colorsWanted)
f530d4
-{
f530d4
-  my_cquantize_ptr cquantize = 0;
f530d4
-  int i;
f530d4
-  size_t arraysize;
f530d4
-  if (!im->trueColor)
f530d4
-    {
f530d4
-      /* Nothing to do! */
f530d4
-      return;
f530d4
-    }
f530d4
-  if (colorsWanted > gdMaxColors)
f530d4
-    {
f530d4
-      colorsWanted = gdMaxColors;
f530d4
-    }
f530d4
-  im->pixels = gdCalloc (sizeof (unsigned char *), im->sy);
f530d4
-  if (!im->pixels)
f530d4
-    {
f530d4
-      /* No can do */
f530d4
-      goto outOfMemory;
f530d4
-    }
f530d4
-  for (i = 0; (i < im->sy); i++)
f530d4
-    {
f530d4
-      im->pixels[i] = (unsigned char *) gdCalloc (sizeof (unsigned char), im->sx);
f530d4
-      if (!im->pixels[i])
f530d4
-	{
f530d4
-	  goto outOfMemory;
f530d4
-	}
f530d4
-    }
f530d4
-  cquantize = (my_cquantize_ptr) gdCalloc (sizeof (my_cquantizer), 1);
f530d4
-  if (!cquantize)
f530d4
-    {
f530d4
-      /* No can do */
f530d4
-      goto outOfMemory;
f530d4
-    }
f530d4
-  /* Allocate the histogram/inverse colormap storage */
f530d4
-  cquantize->histogram = (hist4d) gdMalloc (HIST_C0_ELEMS * sizeof (hist3d));
f530d4
-  for (i = 0; i < HIST_C0_ELEMS; i++)
f530d4
-    {
f530d4
-      int j;
f530d4
-      cquantize->histogram[i] = (hist3d) gdCalloc (HIST_C1_ELEMS,
f530d4
-						   sizeof (hist2d));
f530d4
-      if (!cquantize->histogram[i])
f530d4
-	{
f530d4
-	  goto outOfMemory;
f530d4
-	}
f530d4
-      for (j = 0; (j < HIST_C1_ELEMS); j++)
f530d4
-	{
f530d4
-	  cquantize->histogram[i][j] = (hist2d) gdCalloc (HIST_C2_ELEMS * HIST_C3_ELEMS,
f530d4
-							  sizeof (histcell));
f530d4
-	  if (!cquantize->histogram[i][j])
f530d4
-	    {
f530d4
-	      goto outOfMemory;
f530d4
-	    }
f530d4
-	}
f530d4
-    }
f530d4
-  cquantize->fserrors = (FSERRPTR) gdMalloc (4 * sizeof (FSERROR));
f530d4
-  init_error_limit (cquantize);
f530d4
-  arraysize = (size_t) ((im->sx + 2) *
f530d4
-			(4 * sizeof (FSERROR)));
f530d4
-  /* Allocate Floyd-Steinberg workspace. */
f530d4
-  cquantize->fserrors = gdCalloc (arraysize, 1);
f530d4
-  if (!cquantize->fserrors)
f530d4
-    {
f530d4
-      goto outOfMemory;
f530d4
-    }
f530d4
-  cquantize->on_odd_row = FALSE;
f530d4
-
f530d4
-  /* Do the work! */
f530d4
-  zeroHistogram (cquantize->histogram);
f530d4
-  prescan_quantize (im, cquantize);
f530d4
-  select_colors (im, cquantize, 256);
f530d4
-  /* TBB HACK REMOVE */
f530d4
-  {
f530d4
-    FILE *out = fopen ("palettemap.png", "wb");
f530d4
-    int i;
f530d4
-    gdImagePtr im2 = gdImageCreateTrueColor (256, 256);
f530d4
-    for (i = 0; (i < 256); i++)
f530d4
-      {
f530d4
-	gdImageFilledRectangle (im2, (i % 16) * 16, (i / 16) * 16,
f530d4
-				(i % 16) * 16 + 15, (i / 16) * 16 + 15,
f530d4
-				gdTrueColorAlpha (im->red[i], im->green[i],
f530d4
-						im->blue[i], im->alpha[i]));
f530d4
-      }
f530d4
-    gdImagePng (im2, out);
f530d4
-    fclose (out);
f530d4
-    gdImageDestroy (im2);
f530d4
-  }
f530d4
-  zeroHistogram (cquantize->histogram);
f530d4
-  if (dither)
f530d4
-    {
f530d4
-      pass2_fs_dither (im, cquantize);
f530d4
-    }
f530d4
-  else
f530d4
-    {
f530d4
-      pass2_no_dither (im, cquantize);
f530d4
-    }
f530d4
-  if (cquantize->transparentIsPresent)
f530d4
-    {
f530d4
-      int mt = -1;
f530d4
-      for (i = 0; (i < im->colorsTotal); i++)
f530d4
-	{
f530d4
-	  if (im->alpha[i] > mt)
f530d4
-	    {
f530d4
-	      mt = im->alpha[i];
f530d4
-	    }
f530d4
-	}
f530d4
-      for (i = 0; (i < im->colorsTotal); i++)
f530d4
-	{
f530d4
-	  if (im->alpha[i] == mt)
f530d4
-	    {
f530d4
-	      im->alpha[i] = gdAlphaTransparent;
f530d4
-	    }
f530d4
-	}
f530d4
-    }
f530d4
-  if (cquantize->opaqueIsPresent)
f530d4
-    {
f530d4
-      int mo = 128;
f530d4
-      int moIndex = -1;
f530d4
-      for (i = 0; (i < im->colorsTotal); i++)
f530d4
-	{
f530d4
-	  if (im->alpha[i] < mo)
f530d4
-	    {
f530d4
-	      moIndex = i;
f530d4
-	      mo = im->alpha[i];
f530d4
-	    }
f530d4
-	}
f530d4
-      for (i = 0; (i < im->colorsTotal); i++)
f530d4
-	{
f530d4
-	  if (im->alpha[i] == mo)
f530d4
-	    {
f530d4
-	      im->alpha[i] = gdAlphaOpaque;
f530d4
-	    }
f530d4
-	}
f530d4
-    }
f530d4
-  /* Success! Get rid of the truecolor image data. */
f530d4
-  im->trueColor = 0;
f530d4
-  /* Junk the truecolor pixels */
f530d4
-  for (i = 0; i < im->sy; i++)
f530d4
-    {
f530d4
-      gdFree (im->tpixels[i]);
f530d4
-    }
f530d4
-  gdFree (im->tpixels);
f530d4
-  im->tpixels = 0;
f530d4
-  /* Tediously free stuff. */
f530d4
-outOfMemory:
f530d4
-  if (im->trueColor)
f530d4
-    {
f530d4
-      if (im->pixels)
f530d4
-	{
f530d4
-          /* On failure only */
f530d4
-          for (i = 0; i < im->sy; i++)
f530d4
-	    {
f530d4
-	      if (im->pixels[i])
f530d4
-	        {
f530d4
-	          gdFree (im->pixels[i]);
f530d4
-	        }
f530d4
-	    }
f530d4
-	  gdFree (im->pixels);
f530d4
-	}
f530d4
-      im->pixels = 0;
f530d4
-    }
f530d4
-
f530d4
-  if (!cquantize)
f530d4
-    return;
f530d4
-
f530d4
-  for (i = 0; i < HIST_C0_ELEMS; i++)
f530d4
-    {
f530d4
-      if (cquantize->histogram[i])
f530d4
-	{
f530d4
-	  int j;
f530d4
-	  for (j = 0; j < HIST_C1_ELEMS; j++)
f530d4
-	    {
f530d4
-	      if (cquantize->histogram[i][j])
f530d4
-		{
f530d4
-		  gdFree (cquantize->histogram[i][j]);
f530d4
-		}
f530d4
-	    }
f530d4
-	  gdFree (cquantize->histogram[i]);
f530d4
-	}
f530d4
-    }
f530d4
-  if (cquantize->histogram)
f530d4
-    {
f530d4
-      gdFree (cquantize->histogram);
f530d4
-    }
f530d4
-  if (cquantize->fserrors)
f530d4
-    {
f530d4
-      gdFree (cquantize->fserrors);
f530d4
-    }
f530d4
-  if (cquantize->error_limiter_storage)
f530d4
-    {
f530d4
-      gdFree (cquantize->error_limiter_storage);
f530d4
-    }
f530d4
-  gdFree (cquantize);
f530d4
-}
f530d4
diff --git a/src/extra/gd/gd_wbmp.c b/src/extra/gd/gd_wbmp.c
f530d4
index 5281337..f1258da 100644
f530d4
--- a/src/extra/gd/gd_wbmp.c
f530d4
+++ b/src/extra/gd/gd_wbmp.c
f530d4
@@ -105,7 +105,10 @@ gdImageWBMPCtx (gdImagePtr image, int fg, gdIOCtx * out)
f530d4
 
f530d4
   /* create the WBMP */
f530d4
   if ((wbmp = createwbmp (gdImageSX (image), gdImageSY (image), WBMP_WHITE)) == NULL)
f530d4
-    fprintf (stderr, "Could not create WBMP\n");
f530d4
+    {
f530d4
+      fprintf (stderr, "Could not create WBMP\n");
f530d4
+      return;
f530d4
+    }
f530d4
 
f530d4
   /* fill up the WBMP structure */
f530d4
   pos = 0;
f530d4
diff --git a/src/extra/gd/gdcache.c b/src/extra/gd/gdcache.c
f530d4
index e4770f5..ff65b97 100644
f530d4
--- a/src/extra/gd/gdcache.c
f530d4
+++ b/src/extra/gd/gdcache.c
f530d4
@@ -1,5 +1,6 @@
f530d4
 #include "gd.h"
f530d4
 #include "gdhelpers.h"
f530d4
+#include <assert.h>
f530d4
 
f530d4
 #ifdef HAVE_LIBTTF
f530d4
 #define NEED_CACHE 1
f530d4
@@ -130,7 +131,9 @@ gdCacheGet (gdCache_head_t * head, void *keydata)
f530d4
   else
f530d4
     {				/* cache full - replace least-recently-used */
f530d4
       /* preveprev becomes new end of list */
f530d4
-      prevprev->next = NULL;
f530d4
+      assert (prevprev);
f530d4
+      if (prevprev)
f530d4
+        prevprev->next = NULL;
f530d4
       elem = prev;
f530d4
       (*(head->gdCacheRelease)) (elem->userdata);
f530d4
     }
f530d4
diff --git a/src/extra/gd/gdft.c b/src/extra/gd/gdft.c
f530d4
index b1e9414..33430f6 100644
f530d4
--- a/src/extra/gd/gdft.c
f530d4
+++ b/src/extra/gd/gdft.c
f530d4
@@ -574,6 +574,7 @@ gdft_draw_bitmap (gdImage * im, int fg, FT_Bitmap bitmap, int pen_x, int pen_y)
f530d4
 
f530d4
       for (col = 0; col < bitmap.width; col++, pc++)
f530d4
 	{
f530d4
+	  const int trueColor = im->trueColor;
f530d4
 	  if (bitmap.pixel_mode == ft_pixel_mode_grays)
f530d4
 	    {
f530d4
 	      /*
f530d4
@@ -603,7 +604,7 @@ gdft_draw_bitmap (gdImage * im, int fg, FT_Bitmap bitmap, int pen_x, int pen_y)
f530d4
 	      if (x >= im->sx || x < 0)
f530d4
 		continue;
f530d4
 	      /* get pixel location in gd buffer */
f530d4
-	      if (im->trueColor)
f530d4
+	      if (trueColor)
f530d4
 		{
f530d4
 		  tpixel = &im->tpixels[y][x];
f530d4
 		}
f530d4
@@ -614,7 +615,7 @@ gdft_draw_bitmap (gdImage * im, int fg, FT_Bitmap bitmap, int pen_x, int pen_y)
f530d4
 	      if (tc_key.pixel == NUMCOLORS)
f530d4
 		{
f530d4
 		  /* use fg color directly */
f530d4
-		  if (im->trueColor)
f530d4
+		  if (trueColor)
f530d4
 		    {
f530d4
 		      *tpixel = fg;
f530d4
 		    }
f530d4
@@ -625,23 +626,17 @@ gdft_draw_bitmap (gdImage * im, int fg, FT_Bitmap bitmap, int pen_x, int pen_y)
f530d4
 		}
f530d4
 	      else
f530d4
 		{
f530d4
+		  tc_elem = (tweencolor_t *) gdCacheGet (tc_cache, &tc_key);
f530d4
+		  if (!tc_elem) return tc_cache->error;
f530d4
 		  /* find antialised color */
f530d4
-		  if (im->trueColor)
f530d4
+		  if (trueColor)
f530d4
 		    {
f530d4
 		      tc_key.bgcolor = *tpixel;
f530d4
-		    }
f530d4
-		  else
f530d4
-		    {
f530d4
-		      tc_key.bgcolor = *pixel;
f530d4
-		    }
f530d4
-		  tc_elem = (tweencolor_t *) gdCacheGet (
f530d4
-							  tc_cache, &tc_key);
f530d4
-		  if (im->trueColor)
f530d4
-		    {
f530d4
 		      *tpixel = tc_elem->tweencolor;
f530d4
 		    }
f530d4
 		  else
f530d4
 		    {
f530d4
+		      tc_key.bgcolor = *pixel;
f530d4
 		      *pixel = tc_elem->tweencolor;
f530d4
 		    }
f530d4
 		}
f530d4
diff --git a/src/extra/gd/testac.c b/src/extra/gd/testac.c
f530d4
index 55a5434..47d466d 100644
f530d4
--- a/src/extra/gd/testac.c
f530d4
+++ b/src/extra/gd/testac.c
f530d4
@@ -115,13 +115,6 @@ testDrawing (
f530d4
      Otherwise the file would typically be slightly larger. */
f530d4
   gdImageSaveAlpha (im_out, !blending);
f530d4
 
f530d4
-  /* If requested, convert from truecolor to palette. */
f530d4
-  if (palette)
f530d4
-    {
f530d4
-      /* Dithering, 256 colors. */
f530d4
-      gdImageTrueColorToPalette (im_out, 1, 256);
f530d4
-    }
f530d4
-
f530d4
   gdImagePng (im_out, out);
f530d4
   fclose (out);
f530d4
 
f530d4
diff --git a/src/extra/trio/strio.c b/src/extra/trio/strio.c
f530d4
index 0e7196c..c6796af 100644
f530d4
--- a/src/extra/trio/strio.c
f530d4
+++ b/src/extra/trio/strio.c
f530d4
@@ -20,8 +20,6 @@
f530d4
  * - StrToLongDouble
f530d4
  */
f530d4
  
f530d4
-static const char rcsid[] = "@(#)$Id: strio.c,v 1.1 2001/06/07 08:23:02 fjfranklin Exp $";
f530d4
-
f530d4
 #if defined(unix) || defined(__xlC__)
f530d4
 # define PLATFORM_UNIX
f530d4
 #elif defined(WIN32) || defined(_WIN32)
f530d4
diff --git a/src/extra/trio/trio.c b/src/extra/trio/trio.c
f530d4
index 83a2ce9..930e210 100644
f530d4
--- a/src/extra/trio/trio.c
f530d4
+++ b/src/extra/trio/trio.c
f530d4
@@ -41,8 +41,6 @@
f530d4
  *    immediately followed by an 's'.
f530d4
  */
f530d4
 
f530d4
-static const char rcsid[] = "@(#)$Id: trio.c,v 1.1 2001/06/07 08:23:02 fjfranklin Exp $";
f530d4
-
f530d4
 #if defined(unix) || defined(__xlC__) /* AIX xlC workaround */
f530d4
 # define PLATFORM_UNIX
f530d4
 #elif defined(AMIGA) && defined(__GNUC__)
f530d4
diff --git a/src/font.c b/src/font.c
f530d4
index b3927c9..6b88499 100644
f530d4
--- a/src/font.c
f530d4
+++ b/src/font.c
f530d4
@@ -535,6 +535,8 @@ static void ipa_font_add_api (wmfAPI* API,char* name)
f530d4
 float wmf_ipa_font_stringwidth (wmfAPI* API,wmfFont* font,char* str)
f530d4
 {	FT_Face face = WMF_FONT_FTFACE (font);
f530d4
 
f530d4
+	if (!face) return 0.0;
f530d4
+
f530d4
 	FT_Vector delta;
f530d4
 
f530d4
 	FT_Bool use_kerning;
f530d4
@@ -592,6 +594,8 @@ float wmf_ipa_font_stringwidth (wmfAPI* API,wmfFont* font,char* str)
f530d4
 static float ipa_char_position (wmfFont* font,char* str,char* last)
f530d4
 {	FT_Face face = WMF_FONT_FTFACE (font);
f530d4
 
f530d4
+	if (!face) return 0.0;
f530d4
+
f530d4
 	FT_Vector delta;
f530d4
 
f530d4
 	FT_Bool use_kerning;
f530d4
@@ -1218,14 +1222,19 @@ static char* ipa_font_gs_readline (wmfAPI* API,FILE* in)
f530d4
 		line = more;
f530d4
 
f530d4
 		if (line == 0)
f530d4
-		{	fContinue = wmf_false;
f530d4
+		{
f530d4
 			break;
f530d4
 		}
f530d4
 	}
f530d4
 
f530d4
 	if (line == 0) return (0);
f530d4
 
f530d4
-	if (fReadExtra) while (buf[strlen(buf)-1] != '\n') fgets (buf,128,in);
f530d4
+	if (fReadExtra)
f530d4
+	{
f530d4
+		while (buf[strlen(buf)-1] != '\n')
f530d4
+			if (fgets (buf,128,in) == 0)
f530d4
+				break;
f530d4
+	}
f530d4
 
f530d4
 	/* Strip the string */
f530d4
 
f530d4
diff --git a/src/ipa/ipa/bmp.h b/src/ipa/ipa/bmp.h
f530d4
index 568d26e..94a1a17 100644
f530d4
--- a/src/ipa/ipa/bmp.h
f530d4
+++ b/src/ipa/ipa/bmp.h
f530d4
@@ -947,8 +947,8 @@ static int DecodeImage (wmfBMP* bmp,BMPSource* src,unsigned int compression,unsi
f530d4
 		}
f530d4
 /* ?? TODO 	if (QuantumTick (y,image->rows)) MagickMonitor (LoadImageText,y,image->rows); */
f530d4
 	}
f530d4
-	byte = ReadBlobByte (src);  /* end of line */
f530d4
-	byte = ReadBlobByte (src);
f530d4
+	ReadBlobByte (src);  /* end of line */
f530d4
+	ReadBlobByte (src);
f530d4
 
f530d4
 	return 1;
f530d4
 }
f530d4
diff --git a/src/ipa/svg.c b/src/ipa/svg.c
f530d4
index 0692296..9c4adf7 100644
f530d4
--- a/src/ipa/svg.c
f530d4
+++ b/src/ipa/svg.c
f530d4
@@ -156,7 +156,6 @@ static void wmf_svg_draw_text (wmfAPI* API,wmfDrawText_t* draw_text)
f530d4
 	svgPoint pt;
f530d4
 
f530d4
 	float font_height;
f530d4
-	float font_ratio;
f530d4
 
f530d4
 	float sin_theta;
f530d4
 	float cos_theta;
f530d4
@@ -172,8 +171,6 @@ static void wmf_svg_draw_text (wmfAPI* API,wmfDrawText_t* draw_text)
f530d4
 	pt = svg_translate (API,draw_text->pt);
f530d4
 
f530d4
 	font_height = svg_height (API,(float)  draw_text->font_height);
f530d4
-	font_ratio  = svg_width  (API,(float) (draw_text->font_height * draw_text->font_ratio));
f530d4
-	font_ratio /= font_height;
f530d4
 
f530d4
 	theta = - WMF_TEXT_ANGLE (draw_text->dc->font);
f530d4
 
f530d4
diff --git a/src/ipa/xgd/font.h b/src/ipa/xgd/font.h
f530d4
index 79b5d87..5b15e57 100644
f530d4
--- a/src/ipa/xgd/font.h
f530d4
+++ b/src/ipa/xgd/font.h
f530d4
@@ -157,10 +157,6 @@ static void gd_draw_ftbitmap (wmfAPI* API,FT_Bitmap* bitmap,gdPoint pt,wmfRGB* f
f530d4
 
f530d4
 	fg_pixel = gdImageColorResolve (gd->image,fg->r,fg->g,fg->b);
f530d4
 
f530d4
-	if (bitmap->pixel_mode == ft_pixel_mode_mono)
f530d4
-	{	color = fg_pixel;
f530d4
-	}
f530d4
-
f530d4
 	for (row = 0; row < rows; row++)
f530d4
 	{	buffer = bitmap->buffer + row * bitmap->pitch;
f530d4
 
f530d4
diff --git a/src/meta.c b/src/meta.c
f530d4
index cf046a5..ea14f94 100644
f530d4
--- a/src/meta.c
f530d4
+++ b/src/meta.c
f530d4
@@ -441,7 +441,6 @@ static void write_b64 (wmfAPI * API, const unsigned char * buffer, unsigned long
f530d4
 		b32 = (b32 << 16);
f530d4
 		*ptr++ = B64[(b32 >> 18)       ];
f530d4
 		*ptr++ = B64[(b32 >> 12) & 0x3f];
f530d4
-		remaining -= 1;
f530d4
 	}
f530d4
 
f530d4
 	*ptr++ = '\n';
f530d4
diff --git a/src/player.c b/src/player.c
f530d4
index 9b66eb7..813a2bf 100644
f530d4
--- a/src/player.c
f530d4
+++ b/src/player.c
f530d4
@@ -554,7 +554,7 @@ static wmf_error_t WmfPlayMetaFile (wmfAPI* API)
f530d4
 
f530d4
 		case META_SETVIEWPORTORG:
f530d4
 			SCAN_DIAGNOSTIC (API,"New Record: SETVIEWPORTORG");
f530d4
-			changed = meta_orgext (API,&Record);
f530d4
+			meta_orgext (API,&Record);
f530d4
 			if (SCAN (API)) wmf_write (API, Size, Function, "setviewportorg",
f530d4
 					atts->atts, Record.parameter, Record.size * 2);
f530d4
 			SCAN_DIAGNOSTIC (API,"\n");
f530d4
diff --git a/src/player/meta.h b/src/player/meta.h
f530d4
index d656dfd..b9762e3 100644
f530d4
--- a/src/player/meta.h
f530d4
+++ b/src/player/meta.h
f530d4
@@ -412,16 +412,12 @@ static int meta_arc (wmfAPI* API,wmfRecord* Record)
f530d4
 				d_pt.y = c_pt.y;
f530d4
 				D_Coord_Register (API,d_pt,scope);
f530d4
 				/* fallthrough */
f530d4
+			default:
f530d4
 			case '2':
f530d4
 				d_pt.x = c_pt.x;
f530d4
 				d_pt.y = drawarc.TL.y;
f530d4
 				D_Coord_Register (API,d_pt,scope);
f530d4
 			break;
f530d4
-
f530d4
-			default:
f530d4
-				WMF_ERROR (API,"Glitch!");
f530d4
-				API->err = wmf_E_Glitch;
f530d4
-			break;
f530d4
 			}
f530d4
 		break;
f530d4
 
f530d4
@@ -445,16 +441,12 @@ static int meta_arc (wmfAPI* API,wmfRecord* Record)
f530d4
 				d_pt.y = drawarc.BR.y;
f530d4
 				D_Coord_Register (API,d_pt,scope);
f530d4
 				/* fallthrough */
f530d4
+			default:
f530d4
 			case '3':
f530d4
 				d_pt.x = drawarc.TL.x;
f530d4
 				d_pt.y = c_pt.y;
f530d4
 				D_Coord_Register (API,d_pt,scope);
f530d4
 			break;
f530d4
-
f530d4
-			default:
f530d4
-				WMF_ERROR (API,"Glitch!");
f530d4
-				API->err = wmf_E_Glitch;
f530d4
-			break;
f530d4
 			}
f530d4
 		break;
f530d4
 
f530d4
@@ -478,20 +470,17 @@ static int meta_arc (wmfAPI* API,wmfRecord* Record)
f530d4
 				d_pt.y = c_pt.y;
f530d4
 				D_Coord_Register (API,d_pt,scope);
f530d4
 				/* fallthrough */
f530d4
+			default:
f530d4
 			case '4':
f530d4
 				d_pt.x = c_pt.x;
f530d4
 				d_pt.y = drawarc.BR.y;
f530d4
 				D_Coord_Register (API,d_pt,scope);
f530d4
 			break;
f530d4
-
f530d4
-			default:
f530d4
-				WMF_ERROR (API,"Glitch!");
f530d4
-				API->err = wmf_E_Glitch;
f530d4
-			break;
f530d4
 			}
f530d4
 		break;
f530d4
 
f530d4
 		case '4':
f530d4
+		default:
f530d4
 			switch (Qe)
f530d4
 			{
f530d4
 			case '4':
f530d4
@@ -511,23 +500,14 @@ static int meta_arc (wmfAPI* API,wmfRecord* Record)
f530d4
 				d_pt.y = drawarc.TL.y;
f530d4
 				D_Coord_Register (API,d_pt,scope);
f530d4
 				/* fallthrough */
f530d4
+			default:
f530d4
 			case '1':
f530d4
 				d_pt.x = drawarc.BR.x;
f530d4
 				d_pt.y = c_pt.y;
f530d4
 				D_Coord_Register (API,d_pt,scope);
f530d4
 			break;
f530d4
-
f530d4
-			default:
f530d4
-				WMF_ERROR (API,"Glitch!");
f530d4
-				API->err = wmf_E_Glitch;
f530d4
-			break;
f530d4
 			}
f530d4
 		break;
f530d4
-
f530d4
-		default:
f530d4
-			WMF_ERROR (API,"Glitch!");
f530d4
-			API->err = wmf_E_Glitch;
f530d4
-		break;
f530d4
 		}
f530d4
 
f530d4
 		return (changed);
f530d4
@@ -2428,7 +2408,7 @@ static int meta_dc_color (wmfAPI* API,wmfRecord* Record,wmfAttributes* attrlist)
f530d4
 		hash[5] = hex[(color.b >> 4) & 0x0f];
f530d4
 		hash[6] = hex[ color.b       & 0x0f];
f530d4
 		hash[7] = 0;
f530d4
-		value = wmf_attr_add (API, attrlist, "color", hash);
f530d4
+		wmf_attr_add (API, attrlist, "color", hash);
f530d4
 	}
f530d4
 
f530d4
 	if (SCAN (API)) wmf_ipa_color_add (API,&color;;
f530d4
@@ -3152,7 +3132,7 @@ static int meta_pen_create (wmfAPI* API,wmfRecord* Record,wmfAttributes* attrlis
f530d4
 		hash[5] = hex[(color.b >> 4) & 0x0f];
f530d4
 		hash[6] = hex[ color.b       & 0x0f];
f530d4
 		hash[7] = 0;
f530d4
-		value = wmf_attr_add (API, attrlist, "color", hash);
f530d4
+		wmf_attr_add (API, attrlist, "color", hash);
f530d4
 	}
f530d4
 
f530d4
 	WMF_PEN_SET_COLOR (pen,&color;;
f530d4
@@ -3254,7 +3234,7 @@ static int meta_brush_create (wmfAPI* API,wmfRecord* Record,wmfAttributes* attrl
f530d4
 		hash[5] = hex[(color.b >> 4) & 0x0f];
f530d4
 		hash[6] = hex[ color.b       & 0x0f];
f530d4
 		hash[7] = 0;
f530d4
-		value = wmf_attr_add (API, attrlist, "color", hash);
f530d4
+		wmf_attr_add (API, attrlist, "color", hash);
f530d4
 	}
f530d4
 
f530d4
 	WMF_BRUSH_SET_COLOR (brush,&color;;
f530d4
diff --git a/src/recorder.c b/src/recorder.c
f530d4
index b5e6431..ff371a7 100644
f530d4
--- a/src/recorder.c
f530d4
+++ b/src/recorder.c
f530d4
@@ -48,6 +48,9 @@ static void s_rbox_set (wmfAPI * API, wmfConstruct * construct,
f530d4
     {
f530d4
       WMF_ERROR (API, "Hmm. Record out of range...");
f530d4
       API->err = wmf_E_Glitch;
f530d4
+      rbox->start = NULL;
f530d4
+      rbox->end   = NULL;
f530d4
+      rbox->ptr   = NULL;
f530d4
       return;
f530d4
     }
f530d4
   rbox->start = construct->buffer + construct->rec_offset[n  ];