# include "Ximage.h"

void PaintOverlay (Graphic *graphic, KapaImageWidget *image, int N) {

  int i;
  int dX, dY, dx, dy;
  int x, y, X, Y, Xmin, Ymin, Xmax, Ymax, Xrange, Yrange;
  double t, expand, X0, Y0;
 
  XSetForeground (graphic[0].display, graphic[0].gc, image[0].overlay[N].color);
  
  expand = 1.0;
  if (image[0].expand > 0) {
    expand = 1 / (1.0*image[0].expand);
  }
  if (image[0].expand < 0) {
    expand = fabs((double)image[0].expand);
  }

  Image_to_Screen (&X0, &Y0, 0.0, 0.0, image);

  Xmin = image[0].picture.x;
  Ymin = image[0].picture.y;
  Xmax = image[0].picture.x + image[0].picture.dx;
  Ymax = image[0].picture.y + image[0].picture.dy;
  Xrange = image[0].picture.dx;
  Yrange = image[0].picture.dy;

  for (i = 0; i < image[0].overlay[N].Nobjects; i++) {
    X  = image[0].overlay[N].objects[i].x/expand + X0;
    Y =  image[0].overlay[N].objects[i].y/expand + Y0;
    dX = image[0].overlay[N].objects[i].dx/expand;
    dY = image[0].overlay[N].objects[i].dy/expand;
    if ((X + dX < Xmin) || (X - dX > Xmax) ||
	(Y + dY < Ymin) || (Y - dY > Ymax)) {
      continue;
    }

    /* for a LINE, (x, y) is the start, (dx, dy) is the distance to end
       for a CIRCLE (x, y) is the center, (dx, dy) is the radius 
       for a BOX (x, y) is the center, (dx, dy) is the width */

    switch (image[0].overlay[N].objects[i].type) {
      case KII_OVERLAY_LINE:
	// the angle makes no sense for a line...
	XDrawLine (graphic[0].display, graphic[0].window, graphic[0].gc, X, Y, (X+dX), (Y+dY));
	break;
      case KII_OVERLAY_TEXT:
	// XXX currently we ignore the rectangle angle
	XDrawString (graphic[0].display, graphic[0].window, graphic[0].gc, X, Y, image[0].overlay[N].objects[i].text, strlen(image[0].overlay[N].objects[i].text));
	break;
      case KII_OVERLAY_BOX:
	dx = MAX (abs(dX),2) / 2;
	dy = MAX (abs(dY),2) / 2;
	// XXX currently we ignore the rectangle angle
	XDrawRectangle (graphic[0].display, graphic[0].window, graphic[0].gc, (X - dx), (Y - dy), 2*dx, 2*dy);
	break;
      case KII_OVERLAY_CIRCLE:
	dx = MAX (abs(dX),2);
	dy = MAX (abs(dY),2);
	if (image[0].overlay[N].objects[i].angle == 0.0) {
	  XDrawArc (graphic[0].display, graphic[0].window, graphic[0].gc, (X - dx), (Y - dy), 2*dx, 2*dy, 0, 23040);
	} else {
	  // very stupid rotate ellipse drawing:
	  double angle = image[0].overlay[N].objects[i].angle * RAD_DEG;
	  double cs = cos(angle);
	  double sn = sin(angle);
	  // XXX dt should be based on the size of the ellipse...
	  for (t = 0; t < 2*M_PI; t+=0.05) {
	    x = X + dx*cos(t)*cs + dy*sin(t)*sn;
	    y = Y - dx*cos(t)*sn + dy*sin(t)*cs;
	    XDrawPoint (graphic[0].display, graphic[0].window, graphic[0].gc, x, y);
	  }
	}
	break;
      default:
	fprintf (stderr, "skipping unknown object\n");
	break;
    }
  }
  
  XSetForeground (graphic[0].display, graphic[0].gc, graphic[0].fore);
  return;
}
