# include "addstar.h"
# define BYTES_STAR 23
# define BLOCK 1000
# define DNSTARS 1000

static short GSC_M;
static SkyTable *sky = NULL;

Stars *getgsc (SkyRegion *patch, int *NSTARS) {
  
  int i, Ngsc, Nstars; 
  Stars *gsc;
  Stars *stars;
  SkyList *skylist;

  NAMED_PHOTCODE (GSC_M, "GSC");

  /* load regions from GSC table, restrict to patch */
  if (!sky) {
    sky = SkyTableFromGSC (GSCFILE, SKY_DEPTH_HST, VERBOSE);
    SkyTableSetFilenames (sky, GSCDIR, "cpt");
  }
  skylist = SkyListByPatch (sky, -1, patch);
  
  Nstars = 0;
  ALLOCATE (stars, Stars, 1);
  
  for (i = 0; i < skylist[0].Nregions; i++) {
    gsc = rd_gsc (skylist[0].filename[i], &Ngsc);

    REALLOCATE (stars, Stars, MAX (1, Nstars + Ngsc));
    memcpy (&stars[Nstars], gsc, Ngsc*sizeof(Stars));
    Nstars += Ngsc;

    free (gsc);
  }
  
  // XXX don't free because we only load it once and save it
  SkyListFree (skylist);
  // SkyTableFree (sky);

  if (VERBOSE) fprintf (stderr, "%d stars from HST GSC\n", Nstars);
  *NSTARS = Nstars;
  return (stars);
}  

Stars *rd_gsc (char *filename, int *nstars) {
  
  int i, NSTARS, Nstars, Nbytes, nbytes, Nline, Nbyte;
  char *buffer;
  FILE *f;
  Stars *stars;

  Nstars = 0;
  NSTARS = 1000;
  ALLOCATE (stars, Stars, NSTARS);

  f = fopen (filename, "r");
  if (f == NULL) {
    fprintf (stderr, "ERROR: can't find catalog file %s\n", filename);
    exit (2);
  }
  
  Nbytes = BLOCK*BYTES_STAR;
  ALLOCATE (buffer, char, Nbytes);
  while ((nbytes = fread (buffer, 1, Nbytes, f)) > 0) {
    Nline = nbytes / BYTES_STAR;
    for (i = 0; i < Nline; i++) {
      Nbyte = i*BYTES_STAR;
      dparse (&stars[Nstars].R, 1, &buffer[Nbyte]);
      dparse (&stars[Nstars].D, 2, &buffer[Nbyte]);
      if (stars[Nstars].R < UserPatch.Rmin) continue;
      if (stars[Nstars].R > UserPatch.Rmax) continue;
      if (stars[Nstars].D < UserPatch.Dmin) continue;
      if (stars[Nstars].D > UserPatch.Dmax) continue;

      dparse (&stars[Nstars].M, 3, &buffer[Nbyte]);
      stars[Nstars].dM 	  = NAN;
      stars[Nstars].t  	  = 0;
      stars[Nstars].code  = GSC_M;
      stars[Nstars].found = -1;

      stars[Nstars].detID   = 0;
      stars[Nstars].imageID = 0;

      Nstars ++;
      CHECK_REALLOCATE (stars, Stars, NSTARS, Nstars, 1000);
    }
  }
  fclose (f);
  free (buffer);
  REALLOCATE (stars, Stars, Nstars);
  *nstars = Nstars;
  return (stars);
}
