# include "data.h"

int cursor (int argc, char **argv) {

  char string[20], key[20];
  int i, N, Nsource, Source, IsImage;
  double X, Y, R, D, Z;
  void *oldsignal;
  Graphdata graphmode;
  Buffer *buf;

  Nsource = -1;
  if ((N = get_argument (argc, argv, "-n"))) {
    remove_argument (N, &argc, argv);
    Nsource = atof (argv[N]);
    remove_argument (N, &argc, argv);
  }
  if ((N = get_argument (argc, argv, "-g"))) {
    remove_argument (N, &argc, argv);
    SetImageDevice (FALSE);
  }  
  if ((N = get_argument (argc, argv, "-i"))) {
    remove_argument (N, &argc, argv);
    SetImageDevice (TRUE);
  }  
  IsImage = GetCurrentDevice ();
  if (IsImage) {
    if (!GetImage (&Source, &Nsource)) return (FALSE);
  } else {
    if (!GetGraph (&graphmode, &Source, &Nsource)) return (FALSE);
  }

  N = 0;
  if (argc == 2) N = atof (argv[1]);

  if ((argc != 1) && (argc != 2)) {
    gprint (GP_ERR, "USAGE: cursor [Npts] [-n window] [-g | -i]\n");
    return (FALSE);
  }
  
  buf = NULL;
  if (IsImage) buf = SelectBuffer (GetImageName(), OLDBUFFER, FALSE);
  
  KiiCursorOn (Source);
  
  oldsignal = signal (SIGINT, handle_interrupt);
  interrupt = FALSE;
  Z = -1.0;
  for (i = 0; ((i < N) || (N == 0)) && !interrupt; i++) {
    KiiCursorRead (Source, &X, &Y, key);

    sprintf (string, "X%s", key);
    set_variable (string, X);
    sprintf (string, "Y%s", key);
    set_variable (string, Y);
    set_str_variable ("KEY", key);
    
    if (IsImage) {
      if (buf != NULL) { 
	Z = gfits_get_matrix_value (&buf[0].matrix, (int) X, (int) Y);
      }
      gprint (GP_LOG, "%s %f %f  %f\n", key, X, Y, Z);
    } else {
      XY_to_RD (&R, &D, X, Y, &graphmode.coords);
      sprintf (string, "R%s", key);
      set_variable (string, R);
      sprintf (string, "D%s", key);
      set_variable (string, D);
      gprint (GP_LOG, "%s %f %f\n", key, X, Y);
    }
    if (!strcasecmp (key, "Q")) break;
  }

  signal (SIGINT, oldsignal);
  KiiCursorOff (Source);
  return (TRUE);
}
