# include "Ximage.h"

void PSOverlay (KapaImageWidget *image, int N, FILE *f, int extra) {

  int i;
  double X, Y, dX, dY;
  int Xmin, Ymin, Xmax, Ymax;
  double expand, X0, Y0;
 
  expand = 1.0;
  if (image[0].picture.expand > 0) {
    expand = 1 / (1.0*image[0].picture.expand);
  }
  if (image[0].picture.expand < 0) {
    expand = fabs((double)image[0].picture.expand);
  }

  Image_to_Screen (&X0, &Y0, 0.0, 0.0, &image[0].picture);
  X0 -= image[0].picture.x;
  Y0 -= image[0].picture.y;

  Xmin = 0;
  Ymin = 0;
  Xmax = image[0].picture.dx;
  Ymax = 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 =  Ymax - (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;
    
    switch (image[0].overlay[N].objects[i].type) {
      case KII_OVERLAY_LINE:
	if (((X < Xmin) && (X + dX < Xmin)) || ((X > Xmax) && (X + dX > Xmax)) ||
	    ((Y < Ymin) && (Y + dY < Ymin)) || ((Y > Ymax) && (Y + dY > Ymax))) {
	  break;
	}
	fprintf (f, " %6.1f %6.1f %6.1f %6.1f L\n", X + extra, Y + extra, (X+dX + extra), (Y-dY + extra));
	break;
      case KII_OVERLAY_TEXT:
	if (((X < Xmin) && (X + dX < Xmin)) || ((X > Xmax) && (X + dX > Xmax)) ||
	    ((Y < Ymin) && (Y + dY < Ymin)) || ((Y > Ymax) && (Y + dY > Ymax))) {
	  break;
	}
	fprintf (f, "(%s) %6.1f %6.1f T\n", image[0].overlay[N].objects[i].text, X + extra, Y + extra); 
	break;
      case KII_OVERLAY_BOX:
	if (((X - 0.5*dX < Xmin) && (X + 0.5*dX < Xmin)) || ((X - 0.5*dX > Xmax) && (X + 0.5*dX > Xmax)) ||
	    ((Y - 0.5*dY < Ymin) && (Y + 0.5*dY < Ymin)) || ((Y - 0.5*dY > Ymax) && (Y + 0.5*dY > Ymax))) {
	  break;
	}
	fprintf (f, " %6.1f %6.1f %6.1f %6.1f B\n", (dX + 2*extra), (dY + 2*extra), (X - 0.5*dX - extra), (Y - 0.5*dY - extra));
	break;
      case KII_OVERLAY_CIRCLE:
	if (((X - dX < Xmin) && (X + dX < Xmin)) || ((X - dX > Xmax) && (X + dX > Xmax)) ||
	    ((Y - dY < Ymin) && (Y + dY < Ymin)) || ((Y - dY > Ymax) && (Y + dY > Ymax))) {
	  break;
	}
	// XXX add in the rotated ellipse version (rotate in PS space)
	fprintf (f, " %6.1f %6.1f %6.1f C\n", X, Y, fabs(dX + extra));
	break;
      default:
	fprintf (stderr, "skipping unknown object\n");
	break;
    }
  }
}
