# include "gastro.h"

/* filename has path to GSC, strip off path, use filename with CATDIR path */

int gptolemy (char *fullpath, SStars **stars, int *Nstars) {
  
  int i, Nsec, NSTARS, nstar;
  char filename[256], *fileroot, *filepath, *subdir;
  Catalog catalog;

  filepath = pathname (fullpath);
  fileroot = filebasename (fullpath);
  subdir = filebasename (filepath);
  sprintf (filename, "%s/%s/%s", CATDIR, subdir, fileroot);

  catalog.filename = filename;
  switch (lock_catalog (&catalog, LCK_SOFT)) {
  case 0:
  case 2:
    fprintf (stderr, "can't load catalog data\n");
    return (FALSE);
  case 1:
    break;
  }
  if (!load_catalog (&catalog, LOAD_AVES | LOAD_MEAS, FALSE)) {
    fprintf (stderr, "can't load catalog data\n");
    return (FALSE);
  }
  unlock_catalog (&catalog);

  nstar = *Nstars;
  NSTARS = *Nstars + catalog.Naverage;
  if (*Nstars == 0) {
    ALLOCATE (stars[0], SStars, NSTARS);
  } else {
    REALLOCATE (stars[0], SStars, NSTARS);
  }

  Nsec = catalog.Nsecfilt;

  /* select all entries, ignore magnitudes */
  for (i = 0; i < catalog.Naverage; i++, nstar++) {
    stars[0][nstar].X = catalog.average[i].R;
    stars[0][nstar].Y = catalog.average[i].D;
    stars[0][nstar].mag = 0.001*catalog.measure[catalog.average[i].offset].M;
  }

  /* select only entries with valid magnitudes */ 
# if (0)  
  for (i = 0; i < catalog.Naverage; i++, nstar++) {
    stars[0][nstar].X = catalog.average[i].R;
    stars[0][nstar].Y = catalog.average[i].D;
    GotIt = FALSE;
    if (catalog.average[i].M != NO_MAG) {
      stars[0][nstar].mag = 0.001*catalog.average[i].M;
      GotIt = TRUE;
    }
    for (j = 0; !GotIt && (j < Nsec); j++) {
      if (catalog.secfilt[i*Nsec + j].M != NO_MAG) {
	stars[0][nstar].mag = 0.001*catalog.secfilt[i*Nsec + j].M;
	GotIt = TRUE;
      }
    }
    if (!GotIt) nstar --; /* skip this star */
  }
# endif

  free (catalog.average);

  *Nstars = nstar;
  
  return (TRUE);
  
}

/* this function is still only occasionally used.  there is some trouble with the
   issue of magnitudes.  do we depend on the existence of an 'average.M' value, 
   or not?

   should this be selectable?

*/
