# include "astro.h"

enum {NONE, SKY, PIXEL};

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

  int mode, N, Quiet;
  double X, Y, R, D;
  char *MOSAIC;
  Coords coords, moscoords;
  Buffer *buf, *mosbuffer;

  MOSAIC = NULL;
  if ((N = get_argument (argc, argv, "-mosaic"))) {
    remove_argument (N, &argc, argv);
    MOSAIC = strcreate (argv[N]);
    remove_argument (N, &argc, argv);
  }

  Quiet = FALSE;
  if ((N = get_argument (argc, argv, "-q"))) {
    Quiet = TRUE;
    remove_argument (N, &argc, argv);
  }
  if ((N = get_argument (argc, argv, "-quiet"))) {
    Quiet = TRUE;
    remove_argument (N, &argc, argv);
  }

  mode = NONE;
  if ((N = get_argument (argc, argv, "-p"))) {
    remove_argument (N, &argc, argv);
    X = atof(argv[N]);
    remove_argument (N, &argc, argv);
    Y = atof(argv[N]);
    remove_argument (N, &argc, argv);
    mode = SKY;
  }
  if ((N = get_argument (argc, argv, "-c"))) {
    if (mode == SKY) goto syntax;
    remove_argument (N, &argc, argv);
    R = atof(argv[N]);
    remove_argument (N, &argc, argv);
    D = atof(argv[N]);
    remove_argument (N, &argc, argv);
    mode = PIXEL;
  }
  if (mode == NONE) goto syntax;
  if (argc != 2) goto syntax;

  if ((buf = SelectBuffer (argv[1], OLDBUFFER, TRUE)) == NULL) goto escape;
  GetCoords (&coords, &buf[0].header);
  if (!strcmp(&coords.ctype[4], "-WRP")) {
    if (MOSAIC == NULL) {
      gprint (GP_ERR, "must supply mosaic for WRP coords\n");
      return (FALSE);
    }
    if ((mosbuffer = SelectBuffer (MOSAIC, OLDBUFFER, TRUE)) == NULL) goto escape;
    GetCoords (&moscoords, &mosbuffer[0].header);
    RegisterMosaic (&moscoords);
  }
  
  if (mode == SKY) {
    XY_to_RD (&R, &D, X, Y, &coords);
    if (!Quiet) gprint (GP_LOG, "%10.6f %10.6f\n", R, D);
    set_variable ("RA", R);
    set_variable ("DEC", D);
    return (TRUE);
  }
    
  if (mode == PIXEL) {
    RD_to_XY (&X, &Y, R, D, &coords);
    if (!Quiet) gprint (GP_LOG, "%7.2f %7.2f\n", X, Y);
    set_variable ("Xc", X);
    set_variable ("Yc", Y);
    return (TRUE);
  }
  return (FALSE);

 syntax:
  gprint (GP_ERR, "USAGE: coords [buffer] (-c R D) / (-p X Y)\n");
  gprint (GP_ERR, "only one of -p or -c can be used\n");
 escape:
  if (MOSAIC != NULL) free (MOSAIC);
  return (FALSE);
}
