# include "dvoshell.h"

int gcat (int argc, char **argv) {
  
  int i, N;
  struct stat filestat;
  double Ra, Dec, Radius;
  SkyTable *sky;
  SkyList *skylist;

  int ShowFile = FALSE;
  if ((N = get_argument (argc, argv, "-file"))) {
    remove_argument (N, &argc, argv);
    ShowFile = TRUE;
  }
  int ShowHost = FALSE;
  if ((N = get_argument (argc, argv, "-host"))) {
    remove_argument (N, &argc, argv);
    ShowHost = TRUE;
  }
  int ShowBackup = FALSE;
  if ((N = get_argument (argc, argv, "-backup"))) {
    remove_argument (N, &argc, argv);
    ShowBackup = TRUE;
  }
  int ShowFlags = FALSE;
  if ((N = get_argument (argc, argv, "-flags"))) {
    remove_argument (N, &argc, argv);
    ShowFlags = TRUE;
  }

  if ((argc != 3) && (argc != 4)) {
    gprint (GP_ERR, "USAGE: gcat RA DEC [Radius] [-host] [-backup] [-flags]\n");
    return (FALSE);
  }

  /* load sky from correct table */
  Ra = atof (argv[1]);
  Dec = atof (argv[2]);
  if (argc == 4) 
    Radius = atof(argv[3]);
  else 
    Radius = 0.0001;

  sky = GetSkyTable ();
  skylist = SkyListByRadius (sky, -1, Ra, Dec, Radius);

  HostTable *table = NULL;  
  char *CATDIR = GetCATDIR();
  if (HostTableExists (CATDIR, sky->hosts)) {
    table = HostTableLoad (CATDIR, sky->hosts);
    if (!table) {
      gprint (GP_ERR, "ERROR: failure reading Host Table %s for parallel database %s\n", sky->hosts, CATDIR);
      return FALSE;
    }    
  }

  // prepare to handle interrupt signals
  struct sigaction *old_sigaction = SetInterrupt();

  for (i = 0; (i < skylist[0].Nregions) && !interrupt; i++) {
    SkyRegion *region = skylist[0].regions[i];

    char hostfile[1024];
    if (table) {
      int hostID = (region->hostFlags & DATA_USE_BCK) ? region->backupID : region->hostID;
      int index = table->index[hostID];
      snprintf (hostfile, 1024, "%s/%s.cpt", table->hosts[index].pathname, region->name);
    } else {
      strcpy (hostfile, skylist[0].filename[i]);
    }

    if (ShowFile) {
      gprint (GP_ERR, "%3d %s", i, hostfile);
    } else {
      gprint (GP_ERR, "%3d %s", i, region->name);
    }

    if (stat (hostfile, &filestat) != -1) {
      gprint (GP_ERR, " *");
    } else {
      gprint (GP_ERR, "  ");
    } 
    if (ShowHost) {
      gprint (GP_ERR, "  %3d", region->hostID);
    } else {
      gprint (GP_ERR, "     ");
    }
    if (ShowBackup) {
      gprint (GP_ERR, "  %3d", region->backupID);
    } else {
      gprint (GP_ERR, "     ");
    }
    if (ShowFlags) {
      gprint (GP_ERR, "  0x%04x", region->hostFlags);
    } else {
      gprint (GP_ERR, "        ");
    }
    gprint (GP_ERR, "\n");
    set_str_variable ("CATNAME", hostfile);
  }
  ClearInterrupt (old_sigaction);

  return (TRUE);
  SkyListFree (skylist);
}
