1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
//! Core. See ARCHITECTURE.adoc

// 1 digit:  continent
// 2 digits: country
// 3 digits: region
// 4 digits: city
// 5 digits: a small city
// 6 digits: few buildings
// 8 digits: a building or less
// 9 digits: room
//
use anyhow::{ensure, Result};
use bincode::Options;
use bitvec::array::BitArray;
use bitvec::order::Lsb0;
use bitvec::prelude::*;
use bytes::Bytes;
use geohash::Coord;
use kdam::format::size_of;
use kdam::BarIter;
use log::debug;
use log::kv::Source;
use rmp_serde::{Deserializer as MsgPackDeserializer, Serializer as MsgPackSerializer};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt::Pointer;
use std::fs::File;
use std::io::Read;
use std::io::{self, Write};
use std::{hash::Hash, ops::Deref};
use zstd::stream::{read::Decoder as ZstdDecoder, write::Encoder as ZstdEncoder};

/// Used during lookup to overlay one minimap from each emitter. The u8 counts
/// the number of matches (and u8 is big enough)
pub type MiniMap = HashMap<String, u8>;
// pub type MiniMap0 = HashSet<GeoToken0>;
pub type Mac = [u8; 6];
pub type GeoSegment = [u8; 2];

/// Single datapoint generated by a client detecting an emitter: coordinates of the phone (if any), macaddr, ssid
pub type Blip = (Coord, Mac, std::string::String);
pub type Blips = Vec<Blip>;
// TODO: add coords precision, support bluetooth and GSM, RSSI

/// This are lenghts of geohashes that the client is starting at each lookup step
pub const GEOHASH_DEPTHS: [usize; 4] = [0, 2, 4, 6];

/// Hash together latitude, longitude, WiFi MACaddr and SSID
/// Format: `1<shortened_geohash>-<shortened_hash>`
/// Returns: high-res geohash, fingerprint
pub fn generate_fingerprint_wifi_unused(geo: &str, macaddr: &Mac, ssid: &str) -> String {
    // A big enough "shortgeo" prevents following mobile APs
    // yet it should be short enough to allow looking up at city/block area granularity

    const SHORTGEO: usize = 5;
    const SHORTHASH: usize = 4;

    let mut h = blake3::Hasher::new();
    h.update(geo[..SHORTGEO].as_bytes());
    h.update(macaddr);
    h.update(ssid.as_bytes());

    let mut result = String::with_capacity(20);
    result.push('1');
    result.push_str(&geo[..SHORTGEO]);
    result.push('-');
    result.push_str(&h.finalize().to_hex()[..SHORTHASH]);
    result
}

pub fn parse_macaddr(mac: &str) -> Result<Mac> {
    let chunks: Vec<&str> = mac.split(':').collect();
    if chunks.len() != 6 {
        anyhow::bail!("Invalid MAC address {}", mac);
    }
    let mut out = [0u8; 6];
    for (i, part) in chunks.iter().enumerate() {
        out[i] = u8::from_str_radix(part, 16)?;
    }
    Ok(out)
}

/// Calculate distance in meters using Haversine formula
pub fn haversine_distance_coord(a: Coord, b: Coord) -> f64 {
    const EARTH_RADIUS: f64 = 6371000.0;
    let a_lat = a.y.to_radians();
    let b_lat = b.y.to_radians();
    let dlat = b_lat - a_lat;
    let dlon = b.x.to_radians() - a.x.to_radians();
    let a = (dlat / 2.0).sin().powi(2) + a_lat.cos() * b_lat.cos() * (dlon / 2.0).sin().powi(2);
    let c = 2.0 * a.sqrt().atan2((1.0 - a).sqrt());
    EARTH_RADIUS * c
}

/// Calculate distance in meters using Haversine formula
pub fn haversine_distance_gh(a: &Coord, gh_b: &str) -> f64 {
    let b = geohash::decode_bbox(gh_b).unwrap().center();

    let lat1_rad = a.y.to_radians();
    let lat2_rad = b.y.to_radians();

    // Haversine formula
    let dlat = lat2_rad - lat1_rad;
    let dlon = b.x.to_radians() - a.x.to_radians();
    let a =
        (dlat / 2.0).sin().powi(2) + lat1_rad.cos() * lat2_rad.cos() * (dlon / 2.0).sin().powi(2);
    let c = 2.0 * a.sqrt().atan2((1.0 - a).sqrt());
    let earth_radius_m = 6371000.0;

    earth_radius_m * c
}

// ----- Geohash -----

pub fn latlon_to_geohash(latitude: f64, longitude: f64) -> String {
    let c = Coord {
        x: longitude,
        y: latitude,
    };
    geohash::encode(c, 9usize).unwrap()
}

// pub type GeoHash = [char; 9];

// pub fn geohash(c: Coord) -> GeoHash {
//     let s = geohash::encode(c, 9usize).unwrap();
//     let mut out = [' '; 9];
//     let chars: Vec<char> = s.chars().take(9).collect();
//     out.copy_from_slice(&chars);
//     out
// }

pub fn coord_to_geohash(c: Coord) -> String {
    geohash::encode(c, 9usize).unwrap()
}

/// Location accuracy as standard deviation expressed in meters
type Lsm = f32;

/// Precision of geohash: from geohash length in chars to maximum error in km
const GEOHASH_PRECISION: [(usize, f32); 9] = [
    (1, 2500.0),
    (2, 156.0),
    (3, 20.0),
    (4, 2.4),
    (5, 0.61),
    (6, 0.076),
    (7, 0.019),
    (8, 0.0024),
    (9, 0.0006),
];

const GEOHASH_CONV_HACK: f32 = 1500.0;

/// Convert geohash len to location-stdev-meters
fn geohash_length_to_lsm(len: &usize) -> Lsm {
    match GEOHASH_PRECISION.get(*len) {
        Some((_, max_err_km)) => max_err_km * GEOHASH_CONV_HACK,
        None => f32::MAX,
    }
}

/// Convert geohash to Plocation
pub fn geohash_to_plocation(geohash: &str) -> Result<Plocation> {
    let loc = geohash::decode_bbox(geohash)?.center();
    let lsm = geohash_length_to_lsm(&geohash.len());
    Ok(Plocation { loc, lsm })
}

/// Convert location-stdev-meters to geohash len
fn lsm_to_geohash_length(stdev: Lsm) -> usize {
    // Doing binary division is probably not worth it
    for &(length, error_km) in GEOHASH_PRECISION.iter() {
        if stdev >= error_km * GEOHASH_CONV_HACK {
            return length - 1;
        }
    }
    GEOHASH_PRECISION.len()
}

/// A minimap represents locations in the world were at least a datapoint is found matching
/// a shortened hash.
///
/// The amount of full cells in each minimap is important:
/// if it is too high the minimap does not convey useful information for the client to
/// be able to find a certain location.
/// If it's too low it's leaking (modest) amounts of information about known nodes.

// During each step in the resolution process we increase the geohash resolution by
// 2 bytes (GEO_LEN0 then GEO_LEN1 then 2...)
// TODO: use variable len dynamically depending on coverage

// Depending on the number of cells in a map the server will return it or use a longer hash
// to select a more sparse map

// Minimaps work somewhat similarly to bloom filters and are indexed as key-value. This allows the
// backend to use fast and simple storage layers like LMDB and sled
// but also eventually-consistent, shardable databases

pub const FINGERPRINT_LEN: usize = 6;

const DENSITY_COMPRESSION: [usize; 3] = [2, 4, 6];

const _: () = {
    if (FINGERPRINT_LEN != DENSITY_COMPRESSION[DENSITY_COMPRESSION.len() - 1]) {
        panic!("Compile-time assertion failed: a is not less than b");
    }
};

pub fn generate_fingerprint_wifi(geohash: &str, macaddr: &Mac, ssid: &str) -> String {
    let mut h = blake3::Hasher::new();
    h.update(geohash.as_bytes());
    h.update(macaddr);
    h.update(ssid.as_bytes());

    let mut result = "".to_string();
    result.push_str(&h.finalize().to_hex()[..FINGERPRINT_LEN]);
    result
}

const GEOHASH_GRID_SIZE: usize = 32;
const BITSET_SIZE: usize = GEOHASH_GRID_SIZE * GEOHASH_GRID_SIZE;

// #[derive(Debug, Clone, Copy)]
pub struct GeoBitSet {
    data: [u128; BITSET_SIZE / 128],
}

impl GeoBitSet {
    fn new() -> Self {
        GeoBitSet {
            data: [0; BITSET_SIZE / 128],
        }
    }

    fn insert(&mut self, geosegment: &GeoSegment) {
        let idx = geosegment_to_index(geosegment);
        let (word, bit) = (idx / 128, idx % 128);
        self.data[word] |= 1 << bit;
    }

    fn contains(&self, geosegment: &GeoSegment) -> bool {
        let idx = geosegment_to_index(geosegment);
        let (word, bit) = (idx / 128, idx % 128);
        (self.data[word] & (1 << bit)) != 0
    }
}

// In-memory bloom struct that can be [de]serialized
// Uses the bit-vec library

pub type BloomHash = BitArray<[u8; 128], Lsb0>;

fn get_segments(b: &BloomHash) -> Vec<GeoSegment> {
    let mut out = vec![];
    for (i, bit) in b.iter().enumerate() {
        if *bit {
            out.push(index_to_geosegment(i));
        }
    }
    out
}

#[derive(Serialize, Deserialize, Debug)]
pub struct BloomHashStore {
    kv: HashMap<String, BloomHash>,
}

impl BloomHashStore {
    pub fn new() -> Self {
        Self { kv: HashMap::new() }
    }

    /// Insert a fingerprint -> geosegment datapoint
    fn insert_one(&mut self, fingerprint: &str, geosegment: &GeoSegment) {
        let pos = geosegment_to_index(geosegment);
        self.kv
            .entry(fingerprint.into())
            .or_insert(BloomHash::ZERO)
            .set(pos, true);
    }
    /// Insert a fingerprint -> geosegment datapoint creating multiple collision probabilities
    /// The fingerprint is shortened at different lengths to
    /// produce bloom filters with different densities to adapt to growing numbers of datapoints.
    /// TODO: this should become self-tuning over time.
    pub fn insert(&mut self, fingerprint: &str, geosegment: &GeoSegment) {
        let gpl = fingerprint.len();
        // TODO: tune this values based on metrics from the `extract` function
        for i in DENSITY_COMPRESSION {
            if fingerprint.len() < i {
                return;
            }
            self.insert_one(&fingerprint[0..i], geosegment)
        }
    }

    /// Insert raw datapoint/blip
    pub fn insert_datapoint(&mut self, lat: f64, lon: f64, mac: &Mac, ssid: &str) {
        let c = geohash::Coord { x: lon, y: lat };
        let geoh = coord_to_geohash(c);
        for s in GEOHASH_DEPTHS {
            // The same blip generates multiple fingerprints that as needed by clients
            // doing location at different geohash-depths
            let geopath = &geoh[..s];
            let fp = generate_fingerprint_wifi(geopath, mac, ssid);
            let b = geoh[s..s + 2].as_bytes();
            let geosegment: GeoSegment = [b[0], b[1]];
            self.insert(&fp, &geosegment)
        }
    }

    /// Merge whole datastore with another
    pub fn merge_store(&mut self, other: &BloomHashStore) {
        for (key, other_val) in &other.kv {
            if let Some(val) = self.kv.get_mut(key) {
                *val |= *other_val;
            } else {
                self.kv.insert(key.clone(), *other_val);
            }
        }
    }

    fn set(&mut self, key: String, bit_array: BitArray<[u8; 128], Lsb0>) {
        self.kv.insert(key, bit_array);
    }

    /// Extract the most useful bloomhash. See `insert`
    pub fn extract(&self, fingerprint: &str) -> &BloomHash {
        let mut last: Option<&BloomHash> = None;
        let mut prev: Option<&BloomHash> = None;
        for fp_len in DENSITY_COMPRESSION {
            if fingerprint.len() < fp_len {
                break;
            }
            if let Some(v) = self.kv.get(&fingerprint[0..fp_len]) {
                (prev, last) = (last, Some(v));
                let ones = v.count_ones();
                // Balance between privacy and usefulness
                // if ones < 256 {
                //     if ones > 2 {
                //         return v;
                //     }
                //     if let Some(p) = prev {
                //         // Low fill rate, better use the prev
                //         return p;
                //     }
                // }
            }
        }
        if let Some(v) = last {
            v
        } else {
            &BitArray::ZERO
        }
    }

    fn get_segments(&self, key: &str) -> Vec<GeoSegment> {
        if let Some(v) = self.kv.get(key) {
            get_segments(v)
        } else {
            vec![]
        }
    }

    // Serialize using msgpack and compress with zstd
    pub fn pack_then_compress(&self) -> Result<Vec<u8>> {
        let mut buf = Vec::new();
        self.serialize(&mut MsgPackSerializer::new(&mut buf))?;
        let out = zstd::stream::encode_all(&buf[..], 0)?;
        Ok(out)
    }

    pub fn decompress_and_unpack(buf: &[u8]) -> Result<Self> {
        let deco = zstd::stream::decode_all(buf)?;
        let mut x = MsgPackDeserializer::new(&deco[..]);
        let out = Self::deserialize(&mut x)?;
        Ok(out)
    }

    /// For debugging
    pub fn show(&self) -> Vec<(&str, Vec<GeoSegment>)> {
        let mut keys: Vec<&String> = self.kv.keys().collect();
        keys.sort();
        keys.into_iter()
            .map(|k| (k.as_str(), self.get_segments(k)))
            .collect()
    }
    pub fn stats(&self) -> String {
        use std::mem::size_of;
        let s = self.kv.len() * (size_of::<BloomHash>() + 4);
        format!("Number of keys {} Estimated bytes: {}", self.kv.len(), s)
    }

    pub fn key_count(&self) -> usize {
        self.kv.len()
    }

    fn create_and_insert(&mut self, key: String) -> &mut BitArray<[u8; 128], Lsb0> {
        self.kv.entry(key).or_insert(BitArray::ZERO)
    }
}

pub fn geosegment_to_string(segment: GeoSegment) -> String {
    let mut out = String::with_capacity(2);
    for &b in &segment {
        out.push(b as char);
    }
    out
}

/// "sum" bloom filters by counting the number of true values for each location
pub fn pile_up_blooms(blooms: Vec<BloomHash>) -> [u8; BITSET_SIZE] {
    let mut out: [u8; BITSET_SIZE] = [0; BITSET_SIZE];
    for b in blooms.iter() {
        for (i, bit) in b.iter().enumerate() {
            out[i] += *bit as u8;
        }
    }
    out
}

/// Select segment
pub fn pick_best_segment(bts: [u8; BITSET_SIZE]) -> (f32, GeoSegment) {
    //
    let mut highest_val: u32 = 0;
    let mut second_highest_val: u32 = 0;
    let mut best = 0;
    for (i, &v) in bts.iter().enumerate() {
        let v = v as u32;
        if v > highest_val {
            (second_highest_val, highest_val, best) = (highest_val, v, i);
            // second_highest_val = highest_val;
            // highest_val = v;
            // best = i
        }
    }
    let selectiveness = (highest_val - second_highest_val) as f32 / highest_val as f32;
    (selectiveness, index_to_geosegment(best))
}

fn geosegment_to_index(gs: &GeoSegment) -> usize {
    geohash_char_to_index(gs[0]) as usize * GEOHASH_GRID_SIZE
        + geohash_char_to_index(gs[1]) as usize
}

fn index_to_geosegment(i: usize) -> GeoSegment {
    [
        geohash_index_to_char(i / GEOHASH_GRID_SIZE),
        geohash_index_to_char(i % GEOHASH_GRID_SIZE),
    ]
}

pub fn lookup_step(kv: &BloomHashStore, blips: &Blips, geopath: &str) -> (f32, String) {
    let blooms: Vec<BloomHash> = blips
        .iter()
        .map(|(_, mac, ssid)| {
            let fingerprint = generate_fingerprint_wifi(geopath, mac, ssid);
            kv.extract(&fingerprint).clone()
        })
        .collect();

    let (selectiveness, b) = pick_best_segment(pile_up_blooms(blooms));
    (selectiveness, geosegment_to_string(b))
}

// Lookup

const GEOHASH_ALPHABET: [char; 32] = [
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k',
    'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
];

pub fn geohash_index_to_char(i: usize) -> u8 {
    debug_assert!(i <= 32);
    GEOHASH_ALPHABET[i] as u8
}

const fn build_lookup_table() -> [u8; 128] {
    let mut out = [u8::MIN; 128];
    let mut i = 0;
    while i < GEOHASH_ALPHABET.len() {
        let ch = GEOHASH_ALPHABET[i];
        out[ch as usize] = i as u8;
        i += 1;
    }
    out
}

const GEOHASH_LOOKUP_TABLE: [u8; 128] = build_lookup_table();

pub fn geohash_char_to_index(c: u8) -> u8 {
    GEOHASH_LOOKUP_TABLE[c as usize]
}

// ----- Client-server communication -----

/// Data sent from client to server using API
#[derive(Serialize, Deserialize, Clone)]
pub struct Upload {
    pub uuid: u32,
}

// ----- Client area -----

// Client: location gathering //

#[derive(Debug, Copy, Clone)]
pub struct Plocation {
    pub loc: Coord,
    pub lsm: Lsm,
}

type Plocations = Vec<Plocation>;

// Technically this would mean "everywhere" :D
pub const NOWHERE: Plocation = Plocation {
    loc: Coord { x: 0., y: 0. },
    lsm: f32::MAX,
};

pub fn load_previous_location() -> Plocation {
    // TODO
    NOWHERE
}

pub fn fetch_geoip_locations() -> Plocations {
    //TODO
    vec![]
}

pub fn fetch_wifi_bt_location(current_pl: &Plocation) -> Plocation {
    // TODO
    NOWHERE
}

// pub fn gather_location_sources(current_pl: &Plocation) -> Plocation {
//     // TODO: keep track of accuracy of different sources and poll them as needed
//     // asynchronously
//     let mut locs = vec![];
//     locs.push(load_previous_location());
//     locs.push(fetch_gps_location());
//     locs.push(fetch_gsm_country_code());
//     let mut out = fuse_location_sources(&locs);
//     if out.lsm.0 < 5. {
//         return out;
//     }

//     {
//         let new_locs = fetch_geoip_locations();
//         if !new_locs.is_empty() {
//             locs.extend(new_locs);
//             out = fuse_location_sources(&locs);
//             if out.lsm.0 < 5. {
//                 return out;
//             }
//         }
//     }

//     {
//         let new = fetch_wifi_bt_location(&out);
//         if new.lsm.0 < f32::MAX {
//             locs.push(new);
//             out = fuse_location_sources(&locs)
//         }
//     }
//     out
// }

// Location fusion //

// Pick percentiles p25 and p75
fn quartiles(mut values: Vec<f64>) -> (f64, f64) {
    values.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let q1_idx = (0.25 * (values.len() - 1) as f64) as usize;
    let q3_idx = (0.75 * (values.len() - 1) as f64) as usize;
    (values[q1_idx], values[q3_idx])
}

// Fuse together locations from different sources using weights
// Ignore obvious outliers
// weight = 0 means ignoring a source completely
pub fn fuse_location_sources(locations: Vec<Plocation>) -> Plocation {
    for p in locations {
        if p.lsm < 10000. {
            return p;
        }
    }
    todo!();

    // Extract quartiles on the 2 axis and filter out outliers using IQR
    // https://en.wikipedia.org/wiki/Interquartile_range
    let (q1_x, q3_x) = quartiles(locations.iter().map(|p| p.loc.x).collect());
    let (q1_y, q3_y) = quartiles(locations.iter().map(|p| p.loc.y).collect());
    let thresh_x = 1.5 * (q3_x - q1_x);
    let thresh_y = 1.5 * (q3_y - q1_y);

    let mut tot_x = 0.0;
    let mut tot_y = 0.0;
    let mut tot_weight = 0.0;

    for p in locations {
        // Skip locations like `NOWHERE` and outliers
        if p.lsm == f32::MAX
            || p.loc.x < q1_x - thresh_x
            || (p.loc.x > q3_x + thresh_x)
            || (p.loc.y < q1_y - thresh_y)
            || (p.loc.y > q3_y + thresh_y)
        {
            debug!("[fuse] ignoring {p:?}");
            continue;
        }

        // Weight:  inverse variance of `Lsm`. Accurate locations weight more.
        let weight = 1.0 / (p.lsm.powi(2) as f64);
        tot_x += p.loc.x * weight;
        tot_y += p.loc.y * weight;
        tot_weight += weight;
    }

    debug!("[fuse] tot w {tot_weight:?}");
    if tot_weight > 0.0 {
        let combined_lsm = (1.0 / tot_weight).sqrt() as f32;
        Plocation {
            loc: Coord {
                x: tot_x / tot_weight,
                y: tot_y / tot_weight,
            },
            lsm: combined_lsm,
        }
    } else {
        NOWHERE
    }
}

// Debugging //

pub fn draw_minimap_num(m: &MiniMap) {
    if m.is_empty() {
        println!("empty map!");
        return;
    }
    let max_v = m.values().max().unwrap();
    for c1 in GEOHASH_ALPHABET.iter() {
        for c2 in GEOHASH_ALPHABET.iter() {
            if let Some(v) = m.get(&format!("{}{}", c1, c2)) {
                let g = (255. * (1. - (*v as f32 / *max_v as f32))) as u8;
                print!("\x1b[38;2;{0};{0};{0}m{v}", g);
            } else {
                print!(" ")
            }
        }
        println!();
    }
    println!("\x1b[0m");
}

pub fn draw_minimap(m: &MiniMap) {
    if m.is_empty() {
        println!("empty map!");
        return;
    }
    let max_v = m.values().max().unwrap();
    for c1 in GEOHASH_ALPHABET.iter() {
        for c2 in GEOHASH_ALPHABET.iter() {
            if let Some(v) = m.get(&format!("{}{}", c1, c2)) {
                let g = (255. * (1. - (*v as f32 / *max_v as f32))) as u8;
                print!("\x1b[38;2;{0};{0};{0}m█", g);
            } else {
                print!(" ")
            }
        }
        // println!();
    }
    // mark the end
    println!("\x1b[0m(@)");
    // gini(m);
    println!("Filled cells: {}", m.len());
}

pub fn draw_minimap2d(m: &MiniMap) {
    if m.is_empty() {
        println!("empty map!");
        return;
    }
    let max_v = m.values().max().unwrap();
    for c1 in GEOHASH_ALPHABET.iter() {
        for c2 in GEOHASH_ALPHABET.iter() {
            if let Some(v) = m.get(&format!("{}{}", c1, c2)) {
                let g = (255. * (1. - (*v as f32 / *max_v as f32))) as u8;
                print!("\x1b[38;2;{0};{0};{0}m██", g);
            } else {
                print!("  ")
            }
        }
        // println!();
    }
    // mark the end
    println!("\x1b[0m(@)");
}

pub fn gini(map: &MiniMap) {
    let mut vals: Vec<u8> = map.values().cloned().collect();
    vals.sort();
    let n = vals.len() as f64;
    let total_sum: f64 = vals.iter().sum::<u8>() as f64;
    let mut cumulative_sum: f64 = 0.0;
    let mut cumulative_sum_ranks: f64 = 0.0;
    for (rank, &v) in vals.iter().enumerate() {
        cumulative_sum += v as f64;
        cumulative_sum_ranks += cumulative_sum / total_sum * (rank as f64 + 1.0);
    }
    let gini_coeff = (n + 1.0 - 2.0 * cumulative_sum_ranks / total_sum) / n;
    println!("Gini coefficient: {:.4}", gini_coeff);
}

// ---- legacy POST /v2/geosubmit JSON API ----

/// POST /v2/geosubmit JSON API
#[derive(Debug, Serialize, Deserialize)]
pub struct MLSGeoSubmit {
    pub items: Vec<MLSGeoSubItem>,
}
/// POST /v2/geosubmit JSON API
#[allow(dead_code, non_snake_case)]
#[derive(Debug, Serialize, Deserialize)]
pub struct MLSGeoSubItem {
    pub timestamp: Option<i64>,
    pub position: Option<Position>,
    pub bluetoothBeacons: Option<Vec<BluetoothBeacon>>,
    pub cellTowers: Option<Vec<CellTower>>,
    pub wifiAccessPoints: Option<Vec<WiFiAccessPoint>>,
}

/// POST /v2/geosubmit JSON API
#[allow(dead_code, non_snake_case)]
#[derive(Debug, Serialize, Deserialize)]
pub struct Position {
    pub latitude: f64,
    pub longitude: f64,
    pub accuracy: Option<f64>,
    pub age: Option<i64>,
    pub altitude: Option<f64>,
    pub altitudeAccuracy: Option<f64>,
    pub heading: Option<f64>,
    pub pressure: Option<f64>,
    pub speed: Option<f64>,
    pub source: Option<String>,
}

/// POST /v2/geosubmit JSON API
#[allow(dead_code, non_snake_case)]
#[derive(Debug, Serialize, Deserialize)]
struct BluetoothBeacon {
    macAddress: String,
    name: Option<String>,
    age: Option<i64>,
    signalStrength: Option<i64>,
}

/// POST /v2/geosubmit JSON API
#[allow(dead_code, non_snake_case)]
#[derive(Debug, Serialize, Deserialize)]
pub struct CellTower {
    pub radioType: String,
    pub mobileCountryCode: i32,
    pub mobileNetworkCode: i32,
    pub locationAreaCode: Option<i32>,
    pub cellId: i32,
    pub age: Option<i64>,
    pub asu: Option<i32>,
    pub primaryScramblingCode: Option<i32>,
    pub serving: Option<i32>,
    pub signalStrength: Option<i64>,
    pub timingAdvance: Option<i32>,
}

/// POST /v2/geosubmit JSON API
#[allow(dead_code, non_snake_case)]
#[derive(Debug, Serialize, Deserialize)]
pub struct WiFiAccessPoint {
    pub macAddress: String,
    pub age: Option<i64>,
    pub channel: Option<i32>,
    pub frequency: Option<i32>,
    pub radioType: Option<String>,
    pub signalToNoiseRatio: Option<i64>,
    pub signalStrength: Option<i64>,
    pub ssid: Option<String>,
}

// ----- testing -----

#[cfg(test)]
mod test {
    use crate::*;
    use geohash::Coord;

    #[test]
    fn test_geobitset() {
        for i in 0..32 {
            let c = geohash_index_to_char(i);
            let i2 = geohash_char_to_index(c);
            assert_eq!(i as u8, i2);
        }
    }

    #[test]
    fn test_geosegment_index() {
        assert_eq!(geosegment_to_index(&[b'0', b'0']), 0);
        assert_eq!(geosegment_to_index(&[b'0', b'z']), 31);
        assert_eq!(geosegment_to_index(&[b'z', b'0']), 992);
        assert_eq!(geosegment_to_index(&[b'z', b'z']), 1023);

        assert_eq!(index_to_geosegment(0), [b'0', b'0']);
        assert_eq!(index_to_geosegment(31), [b'0', b'z']);
        assert_eq!(index_to_geosegment(992), [b'z', b'0']);
        assert_eq!(index_to_geosegment(1023), [b'z', b'z']);
    }

    macro_rules! gss {
    ($($s:expr),* $(,)?) => {{
        let mut vec = Vec::new();
        $(
            let bytes = $s.as_bytes();
            assert_eq!(bytes.len(), 2);
            vec.push([bytes[0], bytes[1]]);
        )*
        vec
    }};
}

    #[test]
    fn test_bloomhashstore() {
        let mut a = BloomHashStore::new();
        a.insert("0bcdef", &[b'0', b'0']);
        println!("{:?}", a.show());
        assert_eq!(
            a.show(),
            [
                ("0b", vec![[b'0', b'0']]),
                ("0bcd", vec![[b'0', b'0']]),
                ("0bcdef", vec![[b'0', b'0']])
            ]
        );
        let mut b = BloomHashStore::new();
        b.insert("0bcdef", &[b'b', b'b']);
        a.merge_store(&b);
        assert_eq!(
            a.show(),
            [
                ("0b", vec![[b'0', b'0'], [b'b', b'b']]),
                ("0bcd", vec![[b'0', b'0'], [b'b', b'b']]),
                ("0bcdef", vec![[b'0', b'0'], [b'b', b'b']]),
            ]
        );

        a.insert("0bcdww", &[b'w', b'w']);

        assert_eq!(get_segments(a.extract("0bcdef0000")), gss!("00", "bb"));
        assert_eq!(get_segments(a.extract("0bcdef")), gss!("00", "bb"));
        assert_eq!(get_segments(a.extract("0bcd")), gss!("00", "bb", "ww"));
    }

    #[test]
    fn test_fuse_locations() {
        let w_locations = vec![
            Plocation {
                loc: Coord { x: 3.0, y: 5.0 },
                lsm: 3.,
            },
            Plocation {
                loc: Coord { x: 4.0, y: 4.5 },
                lsm: 2.,
            },
            Plocation {
                loc: Coord { x: 5.0, y: 4.0 },
                lsm: 1.,
            },
            Plocation {
                loc: Coord { x: 6.0, y: 3.5 },
                lsm: 1.,
            },
            NOWHERE,
        ];
        let out = fuse_location_sources(w_locations);
        assert_eq!(
            out.loc,
            Coord {
                x: 5.223529411764705,
                y: 3.888235294117647
            }
        );
        assert_eq!(out.lsm, 0.65079135);
    }

    #[test]
    fn lsm() {
        for geohash_len in 0..9 {
            let lsm = geohash_length_to_lsm(&geohash_len);
            let glen = lsm_to_geohash_length(lsm);
            assert_eq!(geohash_len, glen);
        }
        assert_eq!(lsm_to_geohash_length(1.), 8);
        assert_eq!(lsm_to_geohash_length(10.), 7);
        assert_eq!(lsm_to_geohash_length(100.), 6);
        assert_eq!(lsm_to_geohash_length(1_000.), 4);
        assert_eq!(lsm_to_geohash_length(10_000.), 3);
        assert_eq!(lsm_to_geohash_length(100_000.), 2);
        assert_eq!(lsm_to_geohash_length(1_000_000.), 1);
    }
}