# include "Ximage.h"
# define INFRONT 4

static char name[4][16] = {"red", "green", "blue", "yellow"};

void bDrawOverlay (KapaImageWidget *image, int N) {

  int i;
  int dX, dY, dx, dy;
  int X, Y, Xmin, Ymin, Xmax, Ymax, Xrange, Yrange;
  double expand, X0, Y0;
  bDrawColor color;
 
  /* translate color to bDrawColors : image[0].overlay[N].color */
  color = KapaColorByName (name[N]);
  bDrawSetStyle (color, 0, 0);
  
  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);
  X0 -= image[0].picture.x;
  Y0 -= image[0].picture.y;

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

  for (i = 0; i < image[0].overlay[N].Nobjects; i++) {
    if (N == INFRONT) {
      X  = image[0].overlay[N].objects[i].x * Xrange;
      Y  = image[0].overlay[N].objects[i].y * Yrange;
      dX = image[0].overlay[N].objects[i].dx * Xrange;
      dY = image[0].overlay[N].objects[i].dy * Yrange;
    } else {
      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:
	bDrawLine (X, Y, (X+dX), (Y+dY));
	break;
      case KII_OVERLAY_TEXT:
	bDrawRotText (X, Y, image[0].overlay[N].objects[i].text, 8, 0.0);
	break;
      case KII_OVERLAY_BOX:
	dx = MAX (abs(dX),2) / 2;
	dy = MAX (abs(dY),2) / 2;
	bDrawRectOpen ((X-dx), (Y-dy), (X+dx), (Y+dy));
	// bDrawRectOpen ((X-dx), (Y-dy), (X), (Y));
	break;
      case KII_OVERLAY_CIRCLE:
	dx = MAX (abs(dX),2);
	dy = MAX (abs(dY),2);
	bDrawArc (X, Y, dx, dy, 0, 360);
	break;
      default:
	fprintf (stderr, "skipping unknown object\n");
	break;
    }
  }
  
  /* translate color to bDrawColors : image[0].overlay[N].color */
  bDrawSetStyle (color, 0, 0);
}

/* this routine is independent of the number of overlays */

