# include "Ximage.h"

/*************/
int CSaveOverlay (Graphic *graphic, Layout *layout) {

  char buffer[256], filename[256];
  int i, status, Nbytes, N;
  double ra, dec, ra1, dec1, x1, y1, dra, ddec;
  FILE *f;

  status = read (layout[0].Ximage, buffer, 16); 
  buffer[16] = 0; 
  sscanf (buffer, "%*s %d", &Nbytes); 
  status = read (layout[0].Ximage, buffer, Nbytes); 
  buffer[Nbytes] = 0; 
  sscanf (buffer, "%*s %d %s", &N, filename);
  
  f = fopen (filename, "w");
  if (f == NULL) {
    fprintf (stderr, "could not open %s\n", filename);
    return (TRUE);
  }

  for (i = 0; i < layout[0].overlay[N].Nobjects; i++) {
    if (!strcmp (layout[0].overlay[N].objects[i].type, "LINE")) {
      XY_to_RD (&ra, &dec, layout[0].overlay[N].objects[i].x, layout[0].overlay[N].objects[i].y, &layout[0].coords);
      x1 = layout[0].overlay[N].objects[i].x + layout[0].overlay[N].objects[i].dx;
      y1 = layout[0].overlay[N].objects[i].y + layout[0].overlay[N].objects[i].dy;
      XY_to_RD (&ra1, &dec1, x1, y1, &layout[0].coords);
      dra = (ra1 - ra);
      ddec = (dec1 - dec);
    } else {
      XY_to_RD (&ra, &dec, layout[0].overlay[N].objects[i].x, layout[0].overlay[N].objects[i].y, &layout[0].coords);
      x1 = layout[0].overlay[N].objects[i].x;
      y1 = layout[0].overlay[N].objects[i].y + layout[0].overlay[N].objects[i].dy;
      XY_to_RD (&ra1, &dec1, x1, y1, &layout[0].coords);
      ddec = fabs (dec1 - dec);
      x1 = layout[0].overlay[N].objects[i].x + layout[0].overlay[N].objects[i].dx;
      y1 = layout[0].overlay[N].objects[i].y;
      XY_to_RD (&ra1, &dec1, x1, y1, &layout[0].coords);
      dra = cos (dec*RAD_DEG) * fabs (ra1 - ra);
    }
    fprintf (f, "%s %lf %lf %lf %lf\n", layout[0].overlay[N].objects[i].type, ra, dec, dra, ddec);
   }
  fclose (f);
  return (TRUE);
}


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

