# include <kapa_internal.h>

# define NOVERLAY_TYPE 5
static char KiiOverlayTypeName[NOVERLAY_TYPE][16] = {
  "NONE",
  "TEXT", 
  "BOX", 
  "LINE",
  "CIRCLE", 
};

int KiiOverlayTypeByName (char *overname) {

  int i;

  for (i = 1; i < NOVERLAY_TYPE; i++) {
    if (!strcasecmp (overname, KiiOverlayTypeName[i])) return (i);
  }
  return (0);
}

char *KiiOverlayTypeByNumber (int n) {

  if ((n < 0) || (n >= NOVERLAY_TYPE)) return NULL;
  return (KiiOverlayTypeName[n]);
}

int KiiSelectOverlay (char *overname, int *number) {

  *number = -1;
  if (!strcmp (overname, "red") || !strcmp (overname, "0")) {
    *number = 0;
    return (TRUE);
  }
  if (!strcmp (overname, "green") || !strcmp (overname, "1")) {
    *number = 1;
    return (TRUE);
  }
  if (!strcmp (overname, "blue") || !strcmp (overname, "2")) {
    *number = 2;
    return (TRUE);
  }
  if (!strcmp (overname, "yellow") || !strcmp (overname, "3")) {
    *number = 3;
    return (TRUE);
  }

  fprintf (stderr, "valid overlays may be: red (0), green (1), blue (2), yellow (3)\n");
  return (FALSE);
}

int KiiLoadOverlay (int fd, KiiOverlay *overlay, int Noverlay, char *overname) {

  int i, n, Nline;
  char *buffer, *type;

  KiiSelectOverlay (overname, &n);

  KiiSendCommand (fd, 4, "LOAD");
  KiiSendCommand (fd, 16, "OVER %9d ", n);

  Nline = 0;
  ALLOCATE (buffer, char, 65536);  /* space for 512 lines of 128 bytes */
  bzero (buffer, 65536);

  for (i = 0; i < Noverlay; i++) {
    type = KiiOverlayTypeByNumber(overlay[i].type);
    if (overlay[i].type == KII_OVERLAY_TEXT) {
      snprintf (&buffer[Nline*128], 128, "%15s %20.10f %20.10f %s ", type, overlay[i].x, overlay[i].y, overlay[i].text);
    } else {
      snprintf (&buffer[Nline*128], 128, "%15s %20.10f %20.10f %20.10f %20.10f ", type, overlay[i].x, overlay[i].y, overlay[i].dx, overlay[i].dy);
    }
    Nline ++;
    if (Nline == 512) {
      KiiSendCommand (fd, 16, "NLINES  %7d ", Nline);
      write (fd, buffer, Nline*128);
      bzero (buffer, 65536);
      Nline = 0;
    }
  }
  KiiSendCommand (fd, 16, "NLINES  %7d ", Nline);
  write (fd, buffer, Nline*128);
  KiiSendCommand (fd, 16, "DONE");

  free (buffer);

  /* this is very inefficient: 128 bytes per object vs 17 as binary, plus the
     conversions back and forth
  */
  return (TRUE);
}

int KiiEraseOverlay (int fd, char *overname) {

  int n;

  KiiSelectOverlay (overname, &n);
    
  KiiSendCommand (fd, 4, "ERAS");
  KiiSendCommand (fd, 16, "OVERLAY %7d ", n);

  return (TRUE);
}

int KiiSaveOverlay (int fd, int celestial, char *overname, char *file) {

  int n;

  KiiSelectOverlay (overname, &n);
    
  if (celestial) {
    KiiSendCommand (fd, 4, "CSVE");
  } else {
    KiiSendCommand (fd, 4, "SAVE");
  }

  KiiSendMessage (fd, "FILE: %d %s", n, file);
  return (TRUE);
}
