# include "Ximage.h"

void CreateColorbar (Layout *layout, Graphic *graphic) {

  int i, j, dx, dy, extra, start;
  unsigned long  pixvalue;
  unsigned int  *out24;
  unsigned char *out8;

  dx = layout[0].cmapbar.dx;
  dy = layout[0].cmapbar.dy;

  /* create the cmap scale */
  switch (graphic[0].Nbits) {
  case 8:
    REALLOCATE (layout[0].cmapbar.data, char, dx*dy);
    out8 = (unsigned char *) layout[0].cmapbar.data;
    for (i = 0; i < dx; i++) {
      pixvalue = layout[0].cmap[(int)(i*layout[0].Npixels/dx)].pixel;
      for (j = 0; j < dy; j++) {
	out8[j*dx + i] = pixvalue;
      }
    }
    layout[0].cmapbar.pix = XCreateImage (graphic[0].display, graphic[0].visual, graphic[0].depth, ZPixmap, 0, 
					  layout[0].cmapbar.data, dx, dy, 8, 0);
    break;

  case 16:
    REALLOCATE (layout[0].cmapbar.data, char, 2*dy*dx);
    out8 = (unsigned char *) layout[0].cmapbar.data;
    for (i = 0; i < dx; i++) {
      pixvalue = layout[0].cmap[(int)(i*layout[0].Npixels/dx)].pixel;
      for (j = 0; j < dy; j++) {
	start = 2*j*dx + 2*i;
	out8[start + 0] = 0x0000ff & pixvalue;
	out8[start + 1] = 0x0000ff & (pixvalue >> 8);
      }
    }
    layout[0].cmapbar.pix = XCreateImage (graphic[0].display, graphic[0].visual, graphic[0].depth, ZPixmap, 0, 
					  layout[0].cmapbar.data, dx, dy, 16, 0);
    break;

  case 24:
    extra = 4 - (dx * 3) % 4;
    REALLOCATE (layout[0].cmapbar.data, char, dy*(3*dx + extra));
    out8 = (unsigned char *) layout[0].cmapbar.data;
    for (i = 0; i < dx; i++) {
      pixvalue = layout[0].cmap[(int)(i*layout[0].Npixels/dx)].pixel;
      for (j = 0; j < dy; j++) {
	start = j*(3*dx+extra) + 3*i;
	out8[start + 0] = 0x0000ff & pixvalue;
	out8[start + 1] = 0x0000ff & (pixvalue >> 8);
	out8[start + 2] = 0x0000ff & (pixvalue >> 16);
      }
    }
    layout[0].cmapbar.pix = XCreateImage (graphic[0].display, graphic[0].visual, graphic[0].depth, ZPixmap, 0, 
					  layout[0].cmapbar.data, dx, dy, 32, 0);
    break;

  case 32:
    REALLOCATE (layout[0].cmapbar.data, char, 4*dx*dy);
    out24 = (unsigned int *) layout[0].cmapbar.data;
    for (i = 0; i < dx; i++) {
      pixvalue = layout[0].cmap[(int)(i*layout[0].Npixels/dx)].pixel;
      for (j = 0; j < dy; j++) {
	out24[j*dx + i] = pixvalue;
      }
    }
    layout[0].cmapbar.pix = XCreateImage (graphic[0].display, graphic[0].visual, graphic[0].depth, ZPixmap, 0, 
					  layout[0].cmapbar.data, dx, dy, 32, 0);
    break;
  }
}
