# include "display.h"
# include "shell.h"
# define DEBUG 0

/* we have space for several kii windows */
# define NXIMAGE 5

static int       Active;
static int       Ximage[NXIMAGE];  
static char      Ximbuffer[NXIMAGE][512];
static double    Xzero[NXIMAGE];
static double    Xrange[NXIMAGE];

void QuitImage () {

  int i;
  
  for (i = 0; i < NXIMAGE; i++) {
    KiiClose (Ximage[i]);
  }
}

void InitImage () {

  int i;

  Active = 0;
  for (i = 0; i < NXIMAGE; i++) {
    Ximage[i] = -1;
    Xzero[i] = 0;
    Xrange[i] = 1024;
    strcpy (Ximbuffer[i], "none");
  }
}

/* set SIGPIPE to this function to close cleanly */ 
void XImageDead (int input) {
  signal (SIGPIPE, XImageDead);
  gprint (GP_ERR, "kii is dead, must restart\n");
  Ximage[Active] = -1;
}

/** start socketed connection */
int open_image (int N) {

  int fd;
  char *kii_exec, name[16];

  kii_exec = get_variable ("KII");
  if (kii_exec == (char *) NULL) {
    gprint (GP_ERR, "variable KII not found\n");
    return (FALSE);
  }

  snprintf (name, 16, "[%d]", N);
  fd = KiiOpen (kii_exec, name);
  free (kii_exec);

  if (fd < 0) {
    gprint (GP_ERR, "error starting kii\n");
    return (FALSE);
  } 

  Ximage[N] = fd;
  return (TRUE);
}

int close_image (int N) {

  if (N <  0) return (FALSE);
  if (N >= NXIMAGE) return (FALSE);

  KiiClose (Ximage[N]); 
  Ximage[N] = -1;
  return (TRUE);
}

/* return pointers for current Ximage, set if desired, test, open if needed */
int GetImage (int *socket, int *N) {

  int i, n;
  char buffer[70];

  SetImageDevice (TRUE);
  if (N == (int *) NULL) {
    n = Active;
  } else {
    if (*N >= NXIMAGE) {
      gprint (GP_ERR, "invalid Ximage window %d\n", *N); 
      return (FALSE);
    }
    if (*N < 0) {
      *N = n = Active;
    } else {
      Active = n = *N;
    }
  }
  
  /* test Ximage[0], flush junk from pipe */
  signal (SIGPIPE, XImageDead);
  fcntl (Ximage[n], F_SETFL,  O_NONBLOCK); 
  for (i = 0; (read (Ximage[n], buffer, 64) > 0) && (i < 20); i++);
  fcntl (Ximage[n], F_SETFL, !O_NONBLOCK); 
  
  if (Ximage[n] < 1) {
    if (!open_image(n)) {
      return (FALSE);
    }
  }

  if (socket != (int *) NULL) *socket = Ximage[n];

  return (TRUE);

}

void SetImageName (char *name) {
  strcpy (Ximbuffer[Active], name);
}

char *GetImageName () {
  return (Ximbuffer[Active]);
}
 
// leave this information on kapa, request when needed? 
void SetImageScale (double zero, double range) {
  Xzero[Active] = zero;
  Xrange[Active] = range;
}
void GetImageScale (double *zero, double *range) {
  *zero = Xzero[Active];
  *range = Xrange[Active];
}
