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

static short GSC_M;

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

  NAMED_PHOTCODE (GSC_M, "GSC_M");

  /* load regions from GSC table, restrict to patch */
  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);
  }
  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 	  = NO_ERR;
      stars[Nstars].t  	  = 0;
      stars[Nstars].code  = GSC_M;
      stars[Nstars].found = -1;
      Nstars ++;
      CHECK_REALLOCATE (stars, Stars, NSTARS, Nstars, 1000);
    }
  }
  free (buffer);
  REALLOCATE (stars, Stars, Nstars);
  *nstars = Nstars;
  return (stars);
}
