# include "rgb.h"
# include <string.h>
# include <stdlib.h>
# include <graphics.h>
# include <stdio.h>

struct {
    unsigned char red, green, blue;
} color_table[16];


# define FIXCOLOR(num) ((int) num>>2)

void SRGP_loadColorTable (int startentry, int count, unsigned short *red, unsigned short *green, unsigned short *blue)
{
  struct palettetype pal;
  int r, g, b;
  int i, j;

  enter ("SRGP_loadColorTable");
  getpalette (&pal);
  for (i=startentry, j=0; j < count; j++, i++) {
      r = FIXCOLOR(red[j]);
      g = FIXCOLOR(green[j]);
      b = FIXCOLOR(blue[j]);
      color_table[startentry].red = red[j];
      color_table[startentry].green = green[j];
      color_table[startentry].blue = blue[j];
      setrgbpalette (pal.colors[startentry], r, g, b);
  }
  leave ("SRGP_loadColorTable");
}


int SRGP_find_color_name (const SRGP_common_color *key, const SRGP_common_color *datum)
{
   return (strcmp (key->name, datum->name));
}


void SRGP_loadSingleColor (int index, unsigned short red, unsigned short green,unsigned short blue)
{
   SRGP_loadColorTable (index, 1, &red, &green, &blue);
}


void SRGP_loadCommonColor (int entry, char *name)
{
   SRGP_common_color *color, key;

   strcpy (key.name, name);
   key.red = key.green = key.blue = 0;
   if ((color = (SRGP_common_color *) bsearch (&key, SRGP_colors,
		SRGP_NUM_COMMON_COLORS, sizeof(SRGP_common_color),
		(int(*) (const void *, const void *)) SRGP_find_color_name)) == NULL) {
     printf ("SRGP: unknown color \"%s\"\n", name);
     return;
   }
   SRGP_loadSingleColor (entry, color->red, color->green, color->blue);
}


void SRGP_inquireColorTable (int start, int cnt, unsigned short *r, unsigned short *g, unsigned short *b)
{
  int i, j;

  for (i=start, j=0; j < cnt; i++, j++) {
     r[j] = color_table[i].red;
     g[j] = color_table[i].green;
     b[j] = color_table[i].blue;
  }
}


