# include "astro.h"
# define D_NSTARS 1000
# define NFIELD 4

Stars *get_stars (file, Nstars) 
char file[];
int *Nstars;
{

  FILE *f;
  int n, i, type, NSTARS;
  Stars *stars;
  double tmp;

  f = fopen (file, "r");
  if (f == NULL) {
    fprintf (stderr, "could not find object file %s\n", file);
    exit(0);
  }

  NSTARS = D_NSTARS;
  ALLOCATE (stars, Stars, NSTARS);
  i = 0;
  while ((n = fscanf (f, "%*f%d%lf%lf%lf%*f%*f%*f%*f%*f%*f%*f%*f%*f%*f", 
		     &type, &stars[i].X, 
		     &stars[i].Y, &stars[i].mag)) == NFIELD) {
    if (ROTATE) {
      tmp = stars[i].X;
      stars[i].X = stars[i].Y;
      stars[i].Y = tmp;
    }
    i++;
    if (type != 1)
     i--;
    if (i == NSTARS - 1) {
      NSTARS += D_NSTARS;
      REALLOCATE (stars, Stars, NSTARS);
    }
  }
  fclose(f);
  if ((n != EOF) && (i < *Nstars))
    fprintf (stderr, "error reading in file %s\n", file);
  fprintf (stderr, " %d stars read from %s, ", i, file);
  NSTARS = i;

  sort_stars (stars, NSTARS);
  
  NSTARS = *Nstars = MIN (NSTARS, *Nstars);
  REALLOCATE (stars, Stars, NSTARS);
  fprintf (stderr, "using %5d\n", NSTARS);
  
  return (stars);
}

sort_stars (stars, N) 
Stars *stars;
int N;
{
  int l,j,ir,i;
  int temp;
  Stars tempstar;
  
  l = N >> 1;
  ir = N - 1;
  for (;;) {
    if (l > 0) {
      tempstar = stars[--l];
    }
    else {
      tempstar = stars[ir];
      stars[ir] = stars[0];
      if (--ir == 0) {
	stars[0] = tempstar;
	return;
      }
    }
    i = l;
    j = (l << 1) + 1;
    while (j <= ir) {
      if (j < ir && stars[j].mag < stars[j+1].mag) ++j;
      if (tempstar.mag < stars[j].mag) {
	stars[i] = stars[j];
	j += (i=j) + 1;
      }
      else j = ir + 1;
    }
    stars[i] = tempstar;
  }
}


