/* X graphics routines to display the slice */
/* This code currently does not work, but is included because
	the errors should be relatively minor and have not yet
	been found */

#include "xgraphics.h"

static Display  *D;
static Visual   *V;
static Colormap C;
int      S,Loop,Point;
static Window   W;
static GC       Gc,GcRev;
static XColor   Colors[NCOLORS];
static XSetWindowAttributes Attr;
static XVisualInfo Info;


float    x,y,r,z;
int      i,j;
double alpha;
char readme[100];
char * sp;
char *sp2;
int val;
int SIZE, WIDTH, HEIGHT, NPTS;

void
initialize_graphics() {
	
   /* Set up the basics */

  SIZE = WIDTH = HEIGHT = NPTS;
  D = XOpenDisplay("");
  S = DefaultScreen(D);
  if (XMatchVisualInfo(D,S,DEPTH,PseudoColor,&Info) == 0) {
    printf("Display can not handle %d bit pseudo color\n",DEPTH);
    return;
  }
  V = Info.visual;


  /* Allocate some colors */
  
  for (i = 0; i < NCOLORS; ++i) {
    Colors[i].pixel = i;
    Colors[i].red = sqrt(i)*16*255;
    Colors[i].green = sqrt(i)*16*255;
    Colors[i].blue = sqrt(i)*16*255;
    Colors[i].flags = DoRed | DoGreen | DoBlue; 
  }
  
  C = XCreateColormap(D,RootWindow(D,S),V,AllocAll);
  if(C == NULL)
    fprintf(stderr, "Damnit\n");
  XStoreColors(D,C,Colors,NCOLORS); 
  Attr.colormap = C;
  Attr.background_pixel = WhitePixel(D,S);
  Attr.border_pixel = BlackPixel(D,S);
  W = XCreateWindow(D,DefaultRootWindow (D),0,0,WIDTH,HEIGHT,100,
		    DEPTH,InputOutput,V,CWColormap|CWBackPixel|CWBorderPixel,&Attr);
  XStoreName(D, W, "ximage output");
  XMapRaised(D, W);
  Gc = XCreateGC (D, W, 0L, (XGCValues *) 0);
}

void
update_image (char **data) {
	static XImage   *I;
	static int created = 0;

	if(!created){
		I = XCreateImage(D, V, DEPTH, ZPixmap, 0, data, WIDTH, HEIGHT, DEPTH, 0);
	}

	XPutImage(D,W,Gc,I,0,0,0,0,NPTS,NPTS);
}

int get_mouse_x() {
  Window *rr, *cr;
  int *rx, *ry;
  int *wx, *wy;
  unsigned int *mask;
  XQueryPointer(D,W,rr,cr,rx,ry,wx,wy,mask);
  return *wx;
}
