# include "gastro2.h"

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

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

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

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

  nstar = 0;
  *Nstars = catalog.Naverage;
  if (catalog.Naverage == 0) return ((GSCdata *)NULL);

  ALLOCATE (stars, GSCdata, *Nstars);

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

  free (catalog.average);

  *Nstars = nstar;
  REALLOCATE (stars, GSCdata, *Nstars);
  
  return (stars);

}
