/* color management */


#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/Xatom.h>

#include <stdio.h>


#define BLACK       0    /* from graph_primi.h */
#define WHITE       1
#define GRAY        2
#define LIGHTGRAY   3
#define NAVYBLUE    4
#define SKYBLUE     5
#define RED         6
#define PINK        7
#define LIGHTGREEN  8
#define YELLOW      9


#define COLORS 10

char *colornames[] = {
  "black", "white", "Gray", "LightGray", "NavyBlue",
  "DeepSkyBlue", "red1", "LightPink", "OliveDrab2",
  "yellow1"
};

    

extern Display *display;
extern int screen_num;

Colormap colormap;

int extended = 0;

unsigned long plane_masks[2];
unsigned long pixels[10];


unsigned long pixel (int i)
{
  return pixels[i];
}


unsigned long plane_mask (int i)
{
  return plane_masks[i];
}


unsigned long blackpix()
{
  if (extended)
    return pixels[0];
  else
    return BlackPixel (display, screen_num);
}


unsigned long whitepix()
{
  if (extended)
    return pixels[1];
  else
    return WhitePixel (display, screen_num); 
}



int extendedcolor()
{
    return extended;
}


void initcolor(GC *gc)
{
  int i;
  Status result;
  XColor cdefs[COLORS];

  extended = 0;

  /* try to allocate color cells */

  colormap = DefaultColormap (display, screen_num);

  result = XAllocColorCells  (display, colormap, False, plane_masks, 2,
			      pixels, COLORS);

  if (result)   /* no error */
    {
      extended = 1;
      /* get actual color values from server */

      for (i=0; i<COLORS; i++)
	{
	  if (!XParseColor (display, colormap, colornames[i], &cdefs[i]))
	    fprintf (stderr, "Color not found in database: %s\n", colornames[i]);
	  else
	    cdefs[i].flags = DoRed | DoGreen | DoBlue;
	}

      /* Step 1: write basic colors */

      for (i=0; i<COLORS; i++)
	{
	  cdefs[i].pixel = pixels[i];
	}
      XStoreColors (display, colormap, cdefs, COLORS);


      /* Step 2: write colors for CTRs (pink: R=255 G:182 B:193*/

      for (i=0; i<COLORS; i++)
	{
	  cdefs[i].green = (int) cdefs[i].green * 182 / 255;
	  cdefs[i].blue  = (int) cdefs[i].blue  * 193 / 255;
	  cdefs[i].pixel = pixels[i] | plane_masks[0];
	}
      XStoreColors (display, colormap, cdefs, COLORS);


      /* Step 3: make black plane */

      for (i=0; i<COLORS; i++)
	{
	  cdefs[i].red = cdefs[i].green = cdefs[i].blue = 0;
	  cdefs[i].pixel = pixels[i] | plane_masks[1];
	}
      XStoreColors (display, colormap, cdefs, COLORS);

      for (i=0; i<COLORS; i++)
	{
	  cdefs[i].red = cdefs[i].green = cdefs[i].blue = 0;
	  cdefs[i].pixel = pixels[i] | plane_masks[0] | plane_masks[1];
	}
      XStoreColors (display, colormap, cdefs, COLORS);

      extended = 1;
    }

  return;
}



void freecolor (GC *gc)
{
  if (extended)
    XFreeColors (display, colormap, pixels, COLORS, plane_masks[0]);
}






