1 /*
2  # This file is part of the Astrometry.net suite.
3  # Licensed under a 3-clause BSD style license - see LICENSE
4  */
5 
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <math.h>
10 #include <assert.h>
11 
12 // for compare_floats_asc
13 #include "permutedsort.h"
14 // for QSORT_R
15 #include "os-features.h"
16 
17 #ifdef SIMPLEXY_REENTRANT
18 
19 // this is slower, because each call needs to malloc, but it is reentrant
dselip(unsigned long k,unsigned long n,const float * arr)20 float dselip(unsigned long k, unsigned long n, const float *arr) {
21     float* sorted_data = malloc(sizeof(float) * n);
22     memcpy(sorted_data, arr, sizeof(float)*n);
23     QSORT_R(sorted_data, n, sizeof(float), NULL, compare_floats_asc_r);
24     float kth_item = sorted_data[k];
25     free(sorted_data);
26     return kth_item;
27 }
28 
dselip_cleanup()29 void dselip_cleanup() {
30 }
31 
32 #else
33 
34 static int high_water_mark = 0;
35 static float* past_data = NULL;
36 
dselip(unsigned long k,unsigned long n,float * arr)37 float dselip(unsigned long k, unsigned long n, float *arr) {
38     if (n > high_water_mark) {
39         free(past_data);
40         past_data = malloc(sizeof(float) * n);
41         high_water_mark = n;
42         //printf("dselip watermark=%lu\n",n);
43     }
44     memcpy(past_data, arr, sizeof(float) * n);
45     qsort(past_data, n, sizeof(float), compare_floats_asc);
46     return past_data[k];
47 }
48 
dselip_cleanup()49 void dselip_cleanup() {
50     free(past_data);
51     past_data = NULL;
52     high_water_mark = 0;
53 }
54 
55 #endif
56