#include <X11/Xos.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
  
#define NCOLORS 256  

/* color map creation, initialization */
cmc(image, pal, palsize, cmap, dpy, window, visual)
     char *image, *pal;
     int palsize;
     Colormap *cmap;
     Display *dpy;
     Window window; 
     Visual *visual;
{
  XColor color[NCOLORS];
  unsigned long plane_mask[NCOLORS];
  unsigned long plane_mask_return[NCOLORS];
  unsigned long pixels_return[NCOLORS];
  unsigned int nplanes;
  Status stat;
  int i, ncolors;
  char *pc;

  if (palsize > NCOLORS)
    printf("Look out, palsize > NCOLORS  (%d, %d)\n",palsize,NCOLORS);
  pc = pal;
  nplanes = 0;
  
  *cmap = XCreateColormap(dpy, window, visual, AllocAll);
  XSetWindowColormap(dpy, window, *cmap); 

  stat = XAllocColorCells(dpy,*cmap,False,plane_mask,0,pixels_return,palsize); 
  if (stat == 0) 
    { 
/*      *cmap =  XCopyColormapAndFree(dpy, *cmap);  */
/*      stat = XAllocColorCells(dpy,*cmap,False,plane_mask,0,pixels_return,palsize);  */
/*      if (stat == 0)  */
/* 	printf("XAllocColorCells failed, palsize = %d\n",palsize);  */
    } 
  
  for (i=0; i < palsize; i++)
    {
      color[i].pixel = i;
      color[i].flags = DoRed | DoGreen | DoBlue;
      color[i].red   = (u_short) *pc++ << 8;
      color[i].green = (u_short) *pc++ << 8;
      color[i].blue  = (u_short) *pc++ << 8;
    }  
  XStoreColors (dpy, *cmap, color, palsize);
}
