# include "Ximage.h"

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

  int i;
  int dX, dY, dx, dy;
  int X, Y, Xmin, Ymin, Xmax, Ymax, Xrange, Yrange;
  double 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:
	XDrawLine (graphic[0].display, graphic[0].window, graphic[0].gc, X, Y, (X+dX), (Y+dY));
	break;
      case KII_OVERLAY_TEXT:
	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;
	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);
	XDrawArc (graphic[0].display, graphic[0].window, graphic[0].gc, (X - dx), (Y - dy), 2*dx, 2*dy, 0, 23040);
	break;
      default:
	fprintf (stderr, "skipping unknown object\n");
	break;
    }
  }
  
  XSetForeground (graphic[0].display, graphic[0].gc, graphic[0].fore);
  return;
}
