# include "data.h"

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

  char buffer[40], string[20], key;
  int i, N, Nsource, Source, IsImage, oldsignal;
  double X, Y, R, D, Z;
  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)) {
    fprintf (stderr, "USAGE: cursor [Npts] [-n window] [-g | -i]\n");
    return (FALSE);
  }
  
  buf = NULL;
  if (IsImage) buf = SelectBuffer (GetImageName(), OLDBUFFER, FALSE);
  
  sprintf (string, "CURS");
  write (Source, string, 4); /* ask Source to look for the keystrokes */
  
  oldsignal = (int) signal (SIGINT, handle_interrupt);
  interrupt = FALSE;
  Z = -1.0;
  for (i = 0; ((i < N) || (N == 0)) && !interrupt; i++) {
    bzero (buffer, 20);
    read (Source, buffer, 32);
    buffer[32] = 0;
    sscanf (buffer, "%c %lf %lf", &key, &X, &Y);

    sprintf (string, "X%1c", key);
    set_variable (string, X);
    sprintf (string, "Y%1c", key);
    set_variable (string, Y);
    sprintf (string, "%c", key);
    set_str_variable ("KEY", string);
    
    if (IsImage && (buf != NULL)) 
      Z = fits_get_matrix_value (&buf[0].matrix, (int)X, (int)Y);

    if (!IsImage) {
      XY_to_RD (&R, &D, X, Y, &graphmode.coords);
      sprintf (string, "R%1c", key);
      set_variable (string, R);
      sprintf (string, "D%1c", key);
      set_variable (string, D);
    }

    /* I still don't like this, but I have to decide which to print... */
    if (IsImage) {
      fprintf (GetOutfile(), "%c %f %f  %f\n", key, X, Y, Z);
    } else {
      fprintf (GetOutfile(), "%c %f %f\n", key, X, Y);
    }

    if ((key == 'q') || (key == 'Q')) {
      signal (SIGINT, (void *) oldsignal);
      write (Source, "NCUR", 4); /* ask Source to stop looking for the keystrokes */
      return (TRUE);
    }

  }

  signal (SIGINT, (void *) oldsignal);
  write (Source, "NCUR", 4); /* ask Source to look for the keystrokes */
  return (TRUE);
      
}
