# 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, unsigned int *NSTARS) {
  
  unsigned 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, unsigned 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++) {

      InitStar (&stars[Nstars]);

      Nbyte = i*BYTES_STAR;
      dparse (&stars[Nstars].average.R, 1, &buffer[Nbyte]);
      dparse (&stars[Nstars].average.D, 2, &buffer[Nbyte]);

      if (stars[Nstars].average.R < UserPatch.Rmin) continue;
      if (stars[Nstars].average.R > UserPatch.Rmax) continue;
      if (stars[Nstars].average.D < UserPatch.Dmin) continue;
      if (stars[Nstars].average.D > UserPatch.Dmax) continue;

      fparse (&stars[Nstars].measure.M, 3, &buffer[Nbyte]);
      stars[Nstars].measure.dM 	      = NAN;
      stars[Nstars].measure.photcode  = GSC_M;
      stars[Nstars].measure.t  	      = 0;

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