# include "addstar.h"

void sort_stars_ra (Stars *stars, int N) {

# define SWAPFUNC(A,B){ Stars tmp; tmp = stars[A]; stars[A] = stars[B]; stars[B] = tmp; }
# define COMPARE(A,B)(stars[A].average.R < stars[B].average.R)

  OHANA_SORT (N, COMPARE, SWAPFUNC);

# undef SWAPFUNC
# undef COMPARE

}

SkyList *SkyListForStars (SkyTable *table, int depth, Stars *stars, unsigned 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 == -2) continue;
    here = SkyRegionByPoint (table, depth, stars[i].average.R, stars[i].average.D);
    stars[i].found = -2;
    /* search forward for all contained stars */
    for (j = i; j < Nstars; j++) {
      if (stars[j].average.R >= here[0].regions[0][0].Rmax) break;
      if (stars[j].average.R <  here[0].regions[0][0].Rmin) break;
      if (stars[j].average.D <  here[0].regions[0][0].Dmin) continue;
      if (stars[j].average.D >= here[0].regions[0][0].Dmax) continue;
      stars[j].found = -2;
    }
    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

*/
