# include "addstar.h"

void sort_stars (Stars *stars, int N) {

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

void sort_regions (SkyRegion *region, int N) {

  int l,j,ir,i;
  SkyRegion tmp;
  
  l = N >> 1;
  ir = N - 1;
  for (;;) {
    if (l > 0) {
      l--;
      tmp = region[l];
    } else {
      tmp = region[ir];
      region[ir] = region[0];
      if (--ir == 0) {
	region[0] = tmp;
	return;
      }
    }
    i = l;
    j = (l << 1) + 1;
    while (j <= ir) {
      if (j < ir && region[j].Dmin < region[j+1].Dmin) j++;
      if (tmp.Dmin < region[j].Dmin) {
	region[i] = region[j];
	j += (i=j) + 1;
      }
      else j = ir + 1;
    }
    region[i] = tmp;
  }
}

void sort_lists (float *X, float *Y, int *S, int N) {

  int l,j,ir,i;
  double tX, tY, tS;
  
  l = N >> 1;
  ir = N - 1;
  for (;;) {
    if (l > 0) {
      l--;
      tX = X[l];
      tY = Y[l];
      tS = S[l];
    } else {
      tX = X[ir];
      X[ir] = X[0];
      tY = Y[ir];
      Y[ir] = Y[0];
      tS = S[ir];
      S[ir] = S[0];
      if (--ir == 0) {
	X[0] = tX;
	Y[0] = tY;
	S[0] = tS;
	return;
      }
    }
    i = l;
    j = (l << 1) + 1;
    while (j <= ir) {
      if (j < ir && X[j] < X[j+1]) j++;
      if (tX < X[j]) {
	X[i] = X[j];
	Y[i] = Y[j];
	S[i] = S[j];
	j += (i=j) + 1;
      }
      else j = ir + 1;
    }
    X[i] = tX;
    Y[i] = tY;
    S[i] = tS;
  }
}

void fsort (float *X, int N) {

  int l,j,ir,i;
  float tX;
  
  l = N >> 1;
  ir = N - 1;
  for (;;) {
    if (l > 0) {
      l--;
      tX = X[l];
    } else {
      tX = X[ir];
      X[ir] = X[0];
      if (--ir == 0) {
	X[0] = tX;
	return;
      }
    }
    i = l;
    j = (l << 1) + 1;
    while (j <= ir) {
      if (j < ir && X[j] < X[j+1]) j++;
      if (tX < X[j]) {
	X[i] = X[j];
	j += (i=j) + 1;
      }
      else j = ir + 1;
    }
    X[i] = tX;
  }
}

void fsort2 (float *X, float *Y, int N) {

  int l,j,ir,i;
  float tX, tY;
  
  l = N >> 1;
  ir = N - 1;
  for (;;) {
    if (l > 0) {
      l--;
      tX = X[l];
      tY = Y[l];
    }
    else {
      tX = X[ir];
      tY = Y[ir];
      X[ir] = X[0];
      Y[ir] = Y[0];
      if (--ir == 0) {
	X[0] = tX;
	Y[0] = tY;
	return;
      }
    }
    i = l;
    j = (l << 1) + 1;
    while (j <= ir) {
      if (j < ir && X[j] < X[j+1]) j++;
      if (tX < X[j]) {
	X[i] = X[j];
	Y[i] = Y[j];
	j += (i=j) + 1;
      }
      else j = ir + 1;
    }
    X[i] = tX;
    Y[i] = tY;
  }
}
