diff --git a/src/modules/image/image.c b/src/modules/image/image.c
index 714e0386423858611e1b8fecdec522a65fcb97af..c3304167d885f52396c1c4fabf820490350a0cf3 100644
--- a/src/modules/image/image.c
+++ b/src/modules/image/image.c
@@ -1546,6 +1546,43 @@ void image_threshold(INT32 args)
    push_object(o);
 }
 
+void image_distancesq(INT32 args)
+{
+   INT32 i;
+   rgb_group *s,*d,rgb;
+   struct object *o;
+   struct image *img;
+
+   if (!THIS->img) error("no image\n");
+
+   getrgb(THIS,0,args,"image->threshold()");
+
+   o=clone(image_program,0);
+   img=(struct image*)o->storage;
+   *img=*THIS;
+   if (!(img->img=malloc(sizeof(rgb_group)*THIS->xsize*THIS->ysize+1)))
+   {
+      free_object(o);
+      error("Out of memory\n");
+   }
+
+   d=img->img;
+   s=THIS->img;
+   rgb=THIS->rgb;
+
+   i=img->xsize*img->ysize;
+   while (i--)
+   {
+#define DISTANCE(A,B) \
+   (sq((long)(A).r-(B).r)+sq((long)(A).g-(B).g)+sq((long)(A).b-(B).b))
+      d->r=d->g=d->b=testrange(DISTANCE(*s,rgb)/255);
+      d++; s++;
+   }
+
+   pop_n_elems(args);
+   push_object(o);
+}
+
 void image_apply_matrix(INT32 args)
 {
    int width,height,i,j;
@@ -2044,6 +2081,8 @@ void init_image_programs()
 		"function("RGB_TYPE":object)",0);
    add_function("threshold",image_threshold,
 		"function("RGB_TYPE":object)",0);
+   add_function("distancesq",image_distancesq,
+		"function("RGB_TYPE":object)",0);
 
    add_function("apply_matrix",image_apply_matrix,
                 "function(array(array(int|array(int))):object)",0);
diff --git a/src/modules/image/quant.c b/src/modules/image/quant.c
index 21884642a1814a184d743939780d34e3e9351a1f..0a2a8b546ec2436859c5a791be8a805676e1a26f 100644
--- a/src/modules/image/quant.c
+++ b/src/modules/image/quant.c
@@ -23,8 +23,9 @@ David K
 
 /*
 #define QUANT_DEBUG
-#define QUANT_CHRONO
+#define QUANT_DEBUG_DEEP
 */
+#define QUANT_CHRONO
 
 /**********************************************************************/
 
@@ -334,9 +335,9 @@ static void sort_tbl(rgb_hashtbl *ht,
       }
 
       g1=gap>>1;
-      if (pos+1<g1) g1=pos+1;
-      else if (len-pos-1<gap-g1) g1=pos+1;
-      g2=gap-g1;
+      if (pos+1<g1) g1=pos+1,g2=gap-g1;
+      else if (len-pos-1<gap-g1) g2=(len-pos)+1,g1=gap-g2;
+      else g2=gap-g1;
 
       sort_tbl(ht,start,pos+1,
 	       level+1,idx,g1,dir,