# include <dvo.h>

/* several dvo-specific sorting functions used in a number of locations */

/* values are ave[i].R, ave[i].D, ave[i].M */
void sortave (Average *ave, off_t N) {

# define SWAPFUNC(A,B){ Average tmp; tmp = ave[A]; ave[A] = ave[B]; ave[B] = tmp; }
# define COMPARE(A,B)(ave[A].R < ave[B].R)

  OHANA_SORT (N, COMPARE, SWAPFUNC);

# undef SWAPFUNC
# undef COMPARE

}

/* sort subset by image[subset[i]].tzero */
void sort_image_subset (Image *image, off_t *subset, off_t N) {

# define SWAPFUNC(A,B){ int tmp; tmp = subset[A]; subset[A] = subset[B]; subset[B] = tmp; }
# define COMPARE(A,B)(image[subset[A]].tzero < image[subset[B]].tzero)

  OHANA_SORT (N, COMPARE, SWAPFUNC);

# undef SWAPFUNC
# undef COMPARE

}

/* sort a coordinate pair (X,Y) and the associated index (S) */
void sort_coords_index (double *X, double *Y, off_t *S, off_t N) {
  
# define SWAPFUNC(A,B){ double dtmp; off_t itmp; \
  dtmp = X[A]; X[A] = X[B]; X[B] = dtmp; \
  dtmp = Y[A]; Y[A] = Y[B]; Y[B] = dtmp; \
  itmp = S[A]; S[A] = S[B]; S[B] = itmp; \
}
# define COMPARE(A,B)(X[A] < X[B])

  OHANA_SORT (N, COMPARE, SWAPFUNC);

# undef SWAPFUNC
# undef COMPARE

}

void sort_regions (SkyRegion *region, off_t N) {

# define SWAPFUNC(A,B){ SkyRegion tmp; tmp = region[A]; region[A] = region[B]; region[B] = tmp; }
# define COMPARE(A,B)(region[A].Dmin < region[B].Dmin)

  OHANA_SORT (N, COMPARE, SWAPFUNC);

# undef SWAPFUNC
# undef COMPARE

}
