/* Copyright (c) 2010 MJ Rutter 
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2
 * as published by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA  02110-1301, USA.
 */ 

/* Examine an unpaletted 24-bit image, and count the unique colours.
 * If find >256, exit.
 * If find <=256, convert the image to paletted at a suitable depth
 */

#include<stdio.h>
#include<stdlib.h>

#include "bmp2eps.h"

void colour_count(struct bitmap *image){
  int ncols,i,j,colour,debug;
  unsigned size;
  int palette[257];
  unsigned char *p;

  size=image->height*image->width;
  ncols=0;
  p=image->data;
  debug=image->flags&DEBUG_MASK;

  for(i=0;i<size;i++){
    colour=(((int)*p)<<16)+(((int)*(p+1))<<8)+*(p+2);
    p+=3;
    for(j=0;j<ncols;j++)
      if (colour==palette[j]) break;
    if (j==ncols){
      palette[ncols++]=colour;
      if (ncols==257) break;
    }
  }

  if (ncols==257){
    if (debug) fprintf(stderr,"More than 256 colours\n");
    return;
  }
  
  if (debug) fprintf(stderr,"%d colours: reducing to paletted\n",ncols);

  /* Reduce to paletted if possible */

  image->palette=malloc(3*ncols);
  if (!image->palette){
    fprintf(stderr,"Malloc error\n");
    exit(1);
  }
  for(i=0;i<ncols;i++){
    image->palette[3*i]=(palette[i]&0xff0000)>>16;
    image->palette[3*i+1]=(palette[i]&0xff00)>>8;
    image->palette[3*i+2]=(palette[i]&0xff);
  }
  p=image->data;
  for(i=0;i<size;i++){
    colour=(((int)p[3*i])<<16)+(((int)p[3*i+1])<<8)+p[3*i+2];
    for(j=0;j<ncols;j++)
      if (colour==palette[j]) break;
    p[i]=j;
  }
  if (image->trans){
    colour=(((int)image->trans[0])<<16)+(((int)image->trans[1])<<8)+
           image->trans[2];
    for(j=0;j<ncols;j++)
      if (colour==palette[j]) break;
    *image->trans=j;
  }

  p=realloc(image->data,size);
  if (p) image->data=p;

  image->data_len=size;
  image->depth=8;
  image->colour=PALETTE;
  image->type=PALETTE;
  image->pal_len=ncols;

}
