# include "addstar.h"

SkyList *SkyListForStars (SkyTable *table, int depth, Stars *stars, int Nstars) {
  
  int i, j, Nr, NR;
  SkyList *here;
  SkyList *list;
  
  Nr = 0;
  NR = 10;
  ALLOCATE (list, SkyList, 1);
  ALLOCATE (list[0].regions,  SkyRegion *, NR);
  ALLOCATE (list[0].filename, char *, NR);
  list[0].Nregions = Nr;
  list[0].ownElements = FALSE; // free these elements when freeing the list

  sort_stars_ra (stars, Nstars); /* sort by RA */
  for (i = 0; i < Nstars; i++) {
    if (stars[i].found) continue;
    here = SkyRegionByPoint (table, depth, stars[i].R, stars[i].D);
    stars[i].found = TRUE;
    /* search forward for all contained stars */
    for (j = i; j < Nstars; j++) {
      if (stars[j].R >= here[0].regions[0][0].Rmax) break;
      if (stars[j].R <  here[0].regions[0][0].Rmin) break;
      if (stars[j].D <  here[0].regions[0][0].Dmin) continue;
      if (stars[j].D >= here[0].regions[0][0].Dmax) continue;
      stars[j].found = TRUE;
    }
    list[0].regions[Nr] = here[0].regions[0];
    list[0].filename[Nr] = here[0].filename[0];
    SkyListFree (here); 
    Nr ++;
    if (Nr >= NR) {
	NR += 32;
	REALLOCATE (list[0].regions, SkyRegion *, NR);
	REALLOCATE (list[0].filename, char *, NR);
    }
    list[0].Nregions = Nr;
  }

  /* reset to -1 for all stars: required start for find_match_refstars */
  for (i = 0; i < Nstars; i++) stars[i].found = -1; 
  return (list);
}

/* given a list of stars, find all region files which contain them 

   - sort by ra
   - loop over stars
     - find region file which contains star
     - go forwards until ra > Rmax
       - mark all stars in this region file
     
   - use DEC band information?
   - would like to minimize the number of disk reads

*/
