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
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
//! # cjval: a validator for CityJSON
//!
//! A library to validate the syntax of CityJSON objects (CityJSON +
//! [CityJSONFeatures](https://www.cityjson.org/specs/#text-sequences-and-streaming-with-cityjsonfeature)).
//!
//! It validates against the [CityJSON schemas](https://www.cityjson.org/schemas) and additional functions have been implemented
//! (because these can't be expressed with [JSON Schema](https://json-schema.org/)).
//!
//! The following is error checks are performed:
//!
//!   1. *JSON syntax*: is the file a valid JSON file?
//!   1. *CityJSON schemas*: validation against the schemas (CityJSON v1.0 or v1.1)
//!   1. *Extension schemas*: validate against the extra schemas if there's an Extension in the input file
//!   1. *parents_children_consistency*: if a City Object references another in its `children`, this ensures that the child exists. And that the child has the parent in its `parents`
//!   1. *wrong_vertex_index*: checks if all vertex indices exist in the list of vertices
//!   1. *semantics_array*: checks if the arrays for the semantics in the geometries have the same shape as that of the geometry and if the values are consistent
//!   1. *textures*: checks if the arrays for the textures are coherent (if the vertices exist + if the texture linked to exists)
//!   1. *materials*: checks if the arrays for the materials are coherent with the geometry objects and if material linked to exists

//!
//! It also verifies the following, these are not errors since the file is still considered valid and usable, but they can make the file larger and some parsers might not understand all the properties:
//!
//!   1. *extra_root_properties*: if CityJSON has extra root properties, these should be documented in an Extension. If not this warning is returned
//!   1. *duplicate_vertices*: duplicated vertices in `vertices` are allowed, but they take up spaces and decreases the topological relationships explicitly in the file. If there are any, [cjio](https://github.com/cityjson/cjio) has the operator `clean` to fix this automatically.
//!   1. *unused_vertices*: vertices that are not referenced in the file, they take extra space. If there are any, [cjio](https://github.com/cityjson/cjio) has the operator `clean` to fix this automatically.
//!
//! ## Library + 3 binaries
//!
//! `cjval` is a library and has 3 different binaries:
//!
//!   1. `cjval` to validate a CityJSON file (it downloads automatically Extensions)
//!   2. `cjfval` to validate a stream of CityJSONFeature (from stdin)
//!   3. `cjvalext` to validate a [CityJSON Extension file](https://www.cityjson.org/specs/#the-extension-file)
//!
//!
//! ## Example use
//!
//! ```rust
//! extern crate cjval;
//!
//! fn main() {
//!     let s1 = std::fs::read_to_string("/Users/hugo/projects/cjval/data/cube.city.json")
//!         .expect("Couldn't read CityJSON file");
//!     let v = cjval::CJValidator::from_str(&s1);
//!     let re = v.validate();
//!     for (criterion, sum) in re.iter() {
//!         println!("=== {} ===", criterion);
//!         println!("{}", sum);
//!     }
//! }
//! ```
//!
//! ## Installation/compilation
//!
//! ### To install the binaries on your system easily
//!
//! 1. install the [Rust compiler](https://www.rust-lang.org/learn/get-started)
//! 2. `cargo install cjval --features build-binary`
//!
//!

use anyhow::{anyhow, Result};
use indexmap::IndexMap;
use jsonschema::{Draft, JSONSchema};
use serde::{Deserialize, Serialize};
use serde_json::json;
use serde_json::Value;
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt;

// #-- ERRORS
//  # schema
//  # extensions
//  # parents_children_consistency
//  # wrong_vertex_index
//  # semantics_arrays
//  # textures
//  # materials
//
// #-- WARNINGS
//  # extra_root_properties
//  # duplicate_vertices
//  # unused_vertices

static EXTENSION_FIXED_NAMES: [&str; 6] = [
    "type",
    "name",
    "url",
    "version",
    "versionCityJSON",
    "description",
];

/// Summary of a validation. It is possible that a validation check has not
/// been performed because other checks returned errors (we do not want to
/// have cascading errors).
#[derive(Debug)]
pub struct ValSummary {
    status: Option<bool>,
    errors: Vec<String>,
    warning: bool,
}

impl ValSummary {
    fn new() -> ValSummary {
        let l: Vec<String> = Vec::new();
        ValSummary {
            status: None,
            errors: l,
            warning: false,
        }
    }
    fn set_validity(&mut self, b: bool) {
        self.status = Some(b);
    }
    fn set_as_warning(&mut self) {
        self.warning = true;
    }
    /// Returns true if it's a warning (and not an error)
    pub fn is_warning(&self) -> bool {
        self.warning
    }
    /// Returns true if valid, false if not (and also false if not performed)
    pub fn is_valid(&self) -> bool {
        if self.status == Some(true) {
            return true;
        } else {
            return false;
        }
    }
    /// Returns true if errors are present
    pub fn has_errors(&self) -> bool {
        match self.status {
            Some(s) => {
                if s == true {
                    return false;
                } else {
                    return true;
                }
            }
            None => return false,
        }
    }
    fn add_error(&mut self, e: String) {
        self.errors.push(e);
        self.set_validity(false);
    }
}

impl fmt::Display for ValSummary {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self.status {
            Some(s) => {
                if s == true {
                    fmt.write_str("ok")?;
                } else {
                    fmt.write_str(&format!("{}", self.errors.join("\n")))?;
                }
            }
            None => (),
        }
        Ok(())
    }
}

static CITYJSON_V10_VERSION: &str = "1.0.3";

#[derive(Serialize, Deserialize, Debug)]
struct GeomMPo {
    boundaries: Vec<usize>,
}
#[derive(Serialize, Deserialize, Debug)]
struct GeomMLS {
    boundaries: Vec<Vec<usize>>,
}
#[derive(Serialize, Deserialize, Debug)]
struct GeomMSu {
    boundaries: Vec<Vec<Vec<usize>>>,
}
#[derive(Serialize, Deserialize, Debug)]
struct GeomSol {
    boundaries: Vec<Vec<Vec<Vec<usize>>>>,
}
#[derive(Serialize, Deserialize, Debug)]
struct GeomMSol {
    boundaries: Vec<Vec<Vec<Vec<Vec<usize>>>>>,
}
#[derive(Serialize, Deserialize, Debug)]
struct TextureMSu {
    values: Vec<Vec<Vec<Option<usize>>>>,
}
#[derive(Serialize, Deserialize, Debug)]
struct TextureSol {
    values: Vec<Vec<Vec<Vec<Option<usize>>>>>,
}
#[derive(Serialize, Deserialize, Debug)]
struct TextureMSol {
    values: Vec<Vec<Vec<Vec<Vec<Option<usize>>>>>>,
}

#[allow(non_snake_case)]
#[derive(Deserialize, PartialEq)]
struct Doc {
    #[serde(with = "::serde_with::rust::maps_duplicate_key_is_error")]
    CityObjects: HashMap<String, Value>,
}

pub fn get_cityjson_schema_all_versions() -> Vec<String> {
    let mut l: Vec<String> = Vec::new();
    //-- v1.0
    l.push(CITYJSON_V10_VERSION.to_string());
    //-- v1.1
    let schema_str = include_str!("../schemas/11/cityjson.min.schema.json");
    let schema: Value = serde_json::from_str(schema_str).unwrap();
    let vs = &schema["$id"].to_string();
    l.push(vs.get(34..39).unwrap().to_string());
    //-- v2.0
    let schema_str = include_str!("../schemas/20/cityjson.min.schema.json");
    let schema: Value = serde_json::from_str(schema_str).unwrap();
    let vs = &schema["$id"].to_string();
    l.push(vs.get(34..39).unwrap().to_string());
    l
}

/// A validator for CityJSON and CityJSONFeature
#[derive(Debug)]
pub struct CJValidator {
    cjfeature: bool,
    j: Value,
    jschema_cj: Value,
    jschema_cjf: Value,
    jexts: Vec<Value>,
    // valsum: IndexMap<String, ValSummary>,
    json_syntax_error: Option<String>,
    duplicate_keys: bool,
    is_cityjson: bool,
    version_file: i32,
    version_schema: String,
}

impl CJValidator {
    /// Creates a CJValidator from a &str.
    /// Will not return an error here if the &str is not a JSON,
    /// only when validate() is called can you see that error.
    /// ```rust
    /// use cjval::CJValidator;
    /// let s1 = std::fs::read_to_string("./data/cube.city.json")
    ///         .expect("Couldn't read CityJSON file");
    /// let v = CJValidator::from_str(&s1);
    /// ```
    pub fn from_str(str_dataset: &str) -> Self {
        let l: Vec<Value> = Vec::new();
        let mut v = CJValidator {
            cjfeature: false,
            j: json!(null),
            jschema_cj: json!(null),
            jschema_cjf: json!(null),
            jexts: l,
            json_syntax_error: None,
            duplicate_keys: false,
            is_cityjson: true,
            version_file: 0,
            version_schema: "-1".to_string(),
        };
        //-- parse the dataset and convert to JSON
        let re = serde_json::from_str(&str_dataset);
        match re {
            Ok(j) => {
                v.j = j;
                // TODO: what is j.is_null() is true?
            }
            Err(e) => v.json_syntax_error = Some(e.to_string()),
        }
        //-- check the type
        if v.j["type"] == "CityJSON" {
            //-- check cityjson version
            if v.j["version"] == "2.0" {
                v.version_file = 20;
                let schema_str = include_str!("../schemas/20/cityjson.min.schema.json");
                v.jschema_cj = serde_json::from_str(schema_str).unwrap();
                let vs = &v.jschema_cj["$id"].to_string();
                v.version_schema = vs.get(34..39).unwrap().to_string();
                //-- for CityJSONFeature
                let schemaf_str = include_str!("../schemas/20/cityjsonfeature.min.schema.json");
                v.jschema_cjf = serde_json::from_str(schemaf_str).unwrap();
            } else if v.j["version"] == "1.1" {
                v.version_file = 11;
                let schema_str = include_str!("../schemas/11/cityjson.min.schema.json");
                v.jschema_cj = serde_json::from_str(schema_str).unwrap();
                let vs = &v.jschema_cj["$id"].to_string();
                v.version_schema = vs.get(34..39).unwrap().to_string();
                //-- for CityJSONFeature
                let schemaf_str = include_str!("../schemas/11/cityjsonfeature.min.schema.json");
                v.jschema_cjf = serde_json::from_str(schemaf_str).unwrap();
            } else if v.j["version"] == "1.0" {
                v.version_file = 10;
                let schema_str = include_str!("../schemas/10/cityjson.min.schema.json");
                v.jschema_cj = serde_json::from_str(schema_str).unwrap();
                v.version_schema = "1.0.3".to_string();
            }
        } else {
            v.is_cityjson = false;
        }
        //-- check for duplicate keys in CO object, Doc is the struct above
        //-- used for identifying duplicate keys
        if v.json_syntax_error.is_none() {
            let re: Result<Doc, _> = serde_json::from_str(&str_dataset);
            if re.is_err() {
                v.duplicate_keys = true;
            }
        }
        v
    }

    pub fn from_str_cjfeature(&mut self, str_cjf: &str) -> Result<(), String> {
        //-- parse the cjf and convert to JSON
        let re: Result<Value, _> = serde_json::from_str(&str_cjf);
        if re.is_err() {
            return Err(re.err().unwrap().to_string());
        }
        let j: Value = re.unwrap();
        if j["type"] != "CityJSONFeature" {
            return Err("Not a CityJSONFeature object".to_string());
        }
        self.j = j;
        self.cjfeature = true;
        // println!("{:?}", self.version_file);
        // if self.version == "2.0" {
        //     v.version_file = 20;
        //     let schema_str = include_str!("../schemas/20/cityjsonfeature.min.schema.json");
        //     self.jschema = serde_json::from_str(schema_str).unwrap();
        //     let vs = &v.jschema["$id"].to_string();
        //     self.version_schema = vs.get(34..39).unwrap().to_string();
        // } else if v.version == "1.1" {
        //     self.version_file = 11;
        //     let schema_str = include_str!("../schemas/11/cityjsonfeature.min.schema.json");
        //     v.jschema = serde_json::from_str(schema_str).unwrap();
        //     let vs = &v.jschema["$id"].to_string();
        //     v.version_schema = vs.get(34..39).unwrap().to_string();
        // }

        Ok(())
    }

    /// Add the content (&str) of an Extension.
    /// The library cannot download automatically the Extensions.
    /// ```rust
    /// use cjval::CJValidator;
    /// let sdata = std::fs::read_to_string("./data/cube.city.json")
    ///         .expect("Couldn't read CityJSON file");
    /// let sext = std::fs::read_to_string("./data/generic.ext.json")
    ///         .expect("Couldn't read JSON file");
    /// let mut val = CJValidator::from_str(&sdata);
    /// let re = val.add_one_extension_from_str(&sext);
    /// ```
    pub fn add_one_extension_from_str(&mut self, ext_schema_str: &str) -> Result<()> {
        let re: Result<Value, _> = serde_json::from_str(ext_schema_str);
        if re.is_err() {
            return Err(anyhow!(re.err().unwrap().to_string()));
        }
        self.jexts.push(re.unwrap());
        Ok(())
    }

    /// Returns true if the CityJSON/Feature does not contain errors.
    /// False otherwise.
    pub fn is_valid(&self) -> bool {
        let valsumm = self.validate();
        if valsumm["json_syntax"].has_errors() {
            return false;
        }
        if valsumm["schema"].has_errors() {
            return false;
        }
        if valsumm["extensions"].has_errors() {
            return false;
        }
        if valsumm["parents_children_consistency"].has_errors() {
            return false;
        }
        if valsumm["wrong_vertex_index"].has_errors() {
            return false;
        }
        if valsumm["semantics_arrays"].has_errors() {
            return false;
        }
        if valsumm["materials"].has_errors() {
            return false;
        }
        if valsumm["textures"].has_errors() {
            return false;
        }
        true
    }

    /// The function to performs all the checks (errors+warnings).
    /// Return a IndexMap (a HashMap where keys are ordered) containing
    /// the check name and a ValSummary.
    /// ```rust
    /// use cjval::CJValidator;
    /// let s1 = std::fs::read_to_string("./data/many.json")
    ///     .expect("Couldn't read CityJSON file");
    /// let v = CJValidator::from_str(&s1);
    /// let re = v.validate();
    /// for (criterion, sum) in re.iter() {
    ///     println!("=== {} ===", criterion);
    ///     println!("{}", sum);
    /// }
    /// ```
    pub fn validate(&self) -> IndexMap<String, ValSummary> {
        let mut w1 = ValSummary::new();
        w1.set_as_warning();
        let mut w2 = ValSummary::new();
        w2.set_as_warning();
        let mut w3 = ValSummary::new();
        w3.set_as_warning();
        let mut vsum = IndexMap::from([
            ("json_syntax".to_string(), ValSummary::new()),
            ("schema".to_string(), ValSummary::new()),
            ("extensions".to_string(), ValSummary::new()),
            (
                "parents_children_consistency".to_string(),
                ValSummary::new(),
            ),
            ("wrong_vertex_index".to_string(), ValSummary::new()),
            ("semantics_arrays".to_string(), ValSummary::new()),
            ("textures".to_string(), ValSummary::new()),
            ("materials".to_string(), ValSummary::new()),
            ("extra_root_properties".to_string(), w1),
            ("duplicate_vertices".to_string(), w2),
            ("unused_vertices".to_string(), w3),
        ]);

        //-- json_syntax
        match &self.json_syntax_error {
            Some(e) => {
                vsum.get_mut("json_syntax")
                    .unwrap()
                    .add_error(e.to_string());
                return vsum;
            }
            None => vsum.get_mut("json_syntax").unwrap().set_validity(true),
        }

        //-- schema
        let mut re = self.schema();
        match re {
            Ok(_) => vsum.get_mut("schema").unwrap().set_validity(true),
            Err(errs) => {
                for err in errs {
                    vsum.get_mut("schema").unwrap().add_error(err);
                }
                return vsum;
            }
        }
        if self.duplicate_keys == true {
            vsum.get_mut("schema")
                .unwrap()
                .add_error("Duplicate keys in 'CityObjects'".to_string());
            return vsum;
        }

        //-- extensions
        re = self.validate_extensions();
        match re {
            Ok(_) => vsum.get_mut("extensions").unwrap().set_validity(true),
            Err(errs) => {
                for err in errs {
                    vsum.get_mut("extensions").unwrap().add_error(err);
                }
                return vsum;
            }
        }

        //-- parents_children_consistency
        re = self.parents_children_consistency();
        match re {
            Ok(_) => vsum
                .get_mut("parents_children_consistency")
                .unwrap()
                .set_validity(true),
            Err(errs) => {
                for err in errs {
                    vsum.get_mut("parents_children_consistency")
                        .unwrap()
                        .add_error(err);
                }
            }
        }
        //-- wrong_vertex_index
        re = self.wrong_vertex_index();
        match re {
            Ok(_) => vsum
                .get_mut("wrong_vertex_index")
                .unwrap()
                .set_validity(true),
            Err(errs) => {
                for err in errs {
                    vsum.get_mut("wrong_vertex_index").unwrap().add_error(err);
                }
            }
        }
        //-- semantics_arrays
        re = self.semantics_arrays();
        match re {
            Ok(_) => vsum.get_mut("semantics_arrays").unwrap().set_validity(true),
            Err(errs) => {
                for err in errs {
                    vsum.get_mut("semantics_arrays").unwrap().add_error(err);
                }
            }
        }
        //-- textures
        re = self.textures();
        match re {
            Ok(_) => vsum.get_mut("textures").unwrap().set_validity(true),
            Err(errs) => {
                for err in errs {
                    vsum.get_mut("textures").unwrap().add_error(err);
                }
            }
        }
        //-- materials
        re = self.materials();
        match re {
            Ok(_) => vsum.get_mut("materials").unwrap().set_validity(true),
            Err(errs) => {
                for err in errs {
                    vsum.get_mut("materials").unwrap().add_error(err);
                }
            }
        }

        //-- warnings : only do if no errors so far
        for (_c, summ) in vsum.iter() {
            if summ.has_errors() == true {
                return vsum;
            }
        }
        //-- extra_root_properties
        re = self.extra_root_properties();
        match re {
            Ok(_) => vsum
                .get_mut("extra_root_properties")
                .unwrap()
                .set_validity(true),
            Err(errs) => {
                for err in errs {
                    vsum.get_mut("extra_root_properties")
                        .unwrap()
                        .add_error(err);
                }
            }
        }
        //-- duplicate_vertices
        re = self.duplicate_vertices();
        match re {
            Ok(_) => vsum
                .get_mut("duplicate_vertices")
                .unwrap()
                .set_validity(true),
            Err(errs) => {
                for err in errs {
                    vsum.get_mut("duplicate_vertices").unwrap().add_error(err);
                }
            }
        }
        //-- unused_vertices
        re = self.unused_vertices();
        match re {
            Ok(_) => vsum.get_mut("unused_vertices").unwrap().set_validity(true),
            Err(errs) => {
                for err in errs {
                    vsum.get_mut("unused_vertices").unwrap().add_error(err);
                }
            }
        }
        return vsum;
    }

    pub fn get_extensions_urls(&self) -> Option<Vec<String>> {
        let mut re: Vec<String> = Vec::new();
        let v = self.j.as_object().unwrap();
        if v.contains_key("extensions") {
            let exts = self.j.get("extensions").unwrap().as_object().unwrap();
            for key in exts.keys() {
                re.push(exts[key]["url"].as_str().unwrap().to_string());
            }
        }
        if re.is_empty() {
            None
        } else {
            Some(re)
        }
    }

    pub fn is_cityjsonfeature(&self) -> bool {
        self.cjfeature
    }

    pub fn get_input_cityjson_version(&self) -> i32 {
        self.version_file
    }

    pub fn get_cityjson_schema_version(&self) -> String {
        self.version_schema.to_owned()
    }

    fn schema(&self) -> Result<(), Vec<String>> {
        let mut ls_errors: Vec<String> = Vec::new();
        //-- if type == CityJSON
        if self.is_cityjson == false {
            let s: String = format!("Not a CityJSON file");
            return Err(vec![s]);
        }
        if self.cjfeature == false {
            //-- which cityjson version
            if self.version_file == 0 {
                let s: String = format!(
                    "CityJSON version {} not supported (or missing) [only \"1.0\", \"1.1\", \"2.0\"]",
                    self.j["version"]
                );
                return Err(vec![s]);
            }
        }

        if self.cjfeature == false {
            let compiled = JSONSchema::options()
                .with_draft(Draft::Draft7)
                .compile(&self.jschema_cj)
                .expect("A valid schema");
            let result = compiled.validate(&self.j);
            if let Err(errors) = result {
                for error in errors {
                    let s: String = format!("{} [path:{}]", error, error.instance_path);
                    ls_errors.push(s);
                }
            }
        } else {
            let compiled = JSONSchema::options()
                .with_draft(Draft::Draft7)
                .compile(&self.jschema_cjf)
                .expect("A valid schema");
            let result = compiled.validate(&self.j);
            if let Err(errors) = result {
                for error in errors {
                    let s: String = format!("{} [path:{}]", error, error.instance_path);
                    ls_errors.push(s);
                }
            }
        }
        if ls_errors.is_empty() {
            Ok(())
        } else {
            Err(ls_errors)
        }
    }

    fn validate_ext_extracityobjects(&self, jext: &Value) -> Result<(), Vec<String>> {
        let mut ls_errors: Vec<String> = Vec::new();
        //-- 1. build the schema file from the Extension file
        let v = jext.get("extraCityObjects").unwrap().as_object().unwrap();
        let jexto = jext.as_object().unwrap();
        for eco in v.keys() {
            // println!("==>{:?}", eco);
            let mut schema = jext["extraCityObjects"][eco].clone();
            schema["$schema"] = json!("http://json-schema.org/draft-07/schema#");
            if self.version_file == 11 {
                schema["$id"] = json!("https://www.cityjson.org/schemas/1.1.0/tmp.json");
            } else if self.version_file == 20 {
                schema["$id"] = json!("https://www.cityjson.org/schemas/2.0.0/tmp.json");
            }
            for each in jexto.keys() {
                let ss = each.as_str();
                if EXTENSION_FIXED_NAMES.contains(&ss) == false {
                    schema[ss] = jext[ss].clone();
                }
            }
            // println!("=>{}", serde_json::to_string(&schema).unwrap());
            let compiled = self.get_compiled_schema_extension(&schema).unwrap();
            //-- 2. fetch the CO
            let cos = self.j.get("CityObjects").unwrap().as_object().unwrap();
            for co in cos.keys() {
                let tmp = cos.get(co).unwrap().as_object().unwrap();
                if tmp["type"].as_str().unwrap() == eco {
                    // println!("here");
                    let result = compiled.validate(&self.j["CityObjects"][co]);
                    if let Err(errors) = result {
                        for error in errors {
                            let s: String = format!("{} [path:{}]", error, error.instance_path);
                            ls_errors.push(s);
                        }
                    }
                }
            }
        }
        if ls_errors.is_empty() {
            Ok(())
        } else {
            Err(ls_errors)
        }
    }

    fn validate_ext_extrarootproperties(&self, jext: &Value) -> Result<(), Vec<String>> {
        let mut ls_errors: Vec<String> = Vec::new();
        //-- 1. build the schema file from the Extension file
        let v = jext
            .get("extraRootProperties")
            .unwrap()
            .as_object()
            .unwrap();
        let jexto = jext.as_object().unwrap();
        for rp in v.keys() {
            // println!("==>{:?}", eco);
            let mut schema = jext["extraRootProperties"][rp].clone();
            schema["$schema"] = json!("http://json-schema.org/draft-07/schema#");
            if self.version_file == 11 {
                schema["$id"] = json!("https://www.cityjson.org/schemas/1.1.0/tmp.json");
            } else if self.version_file == 20 {
                schema["$id"] = json!("https://www.cityjson.org/schemas/2.0.0/tmp.json");
            }
            for each in jexto.keys() {
                let ss = each.as_str();
                if EXTENSION_FIXED_NAMES.contains(&ss) == false {
                    schema[ss] = jext[ss].clone();
                }
            }
            let compiled = self.get_compiled_schema_extension(&schema).unwrap();

            for k in self.j.as_object().unwrap().keys() {
                if k == rp {
                    let result = compiled.validate(&self.j[k]);
                    if let Err(errors) = result {
                        for error in errors {
                            let s: String = format!("{} [path:{}]", error, error.instance_path);
                            ls_errors.push(s);
                        }
                    }
                }
            }
        }
        if ls_errors.is_empty() {
            Ok(())
        } else {
            Err(ls_errors)
        }
    }

    fn validate_ext_extraattributes(&self, jext: &Value) -> Result<(), Vec<String>> {
        let mut ls_errors: Vec<String> = Vec::new();
        //-- 1. build the schema file from the Extension file
        let v = jext.get("extraAttributes").unwrap().as_object().unwrap();
        let jexto = jext.as_object().unwrap();
        for cotype in v.keys() {
            //-- for each CityObject type
            for eatt in jext["extraAttributes"][cotype].as_object().unwrap().keys() {
                let mut schema = jext["extraAttributes"][cotype][eatt.as_str()].clone();
                schema["$schema"] = json!("http://json-schema.org/draft-07/schema#");
                if self.version_file == 11 {
                    schema["$id"] = json!("https://www.cityjson.org/schemas/1.1.0/tmp.json");
                } else if self.version_file == 20 {
                    schema["$id"] = json!("https://www.cityjson.org/schemas/2.0.0/tmp.json");
                }
                for each in jexto.keys() {
                    let ss = each.as_str();
                    if EXTENSION_FIXED_NAMES.contains(&ss) == false {
                        schema[ss] = jext[ss].clone();
                    }
                }
                let compiled = self.get_compiled_schema_extension(&schema).unwrap();
                let cos = self.j.get("CityObjects").unwrap().as_object().unwrap();
                for oneco in cos.keys() {
                    let tmp = cos.get(oneco).unwrap().as_object().unwrap();
                    if tmp["type"].as_str().unwrap() == cotype
                        && tmp.contains_key("attributes")
                        && tmp["attributes"].as_object().unwrap().contains_key(eatt)
                    {
                        let result =
                            compiled.validate(&self.j["CityObjects"][oneco]["attributes"][eatt]);
                        if let Err(errors) = result {
                            for error in errors {
                                let s: String = format!("{} [path:{}]", error, error.instance_path);
                                ls_errors.push(s);
                            }
                        }
                    }
                }
            }
        }
        if ls_errors.is_empty() {
            Ok(())
        } else {
            Err(ls_errors)
        }
    }

    fn validate_ext_extrasemanticsurfaces(&self, jext: &Value) -> Result<(), Vec<String>> {
        let mut ls_errors: Vec<String> = Vec::new();
        //-- 0. check if "extraSemanticSurfaces" is in the file, if not then all good
        let t = jext["extraSemanticSurfaces"].as_object();
        if t.is_none() {
            return Ok(());
        }
        //-- 1. build the schema file from the Extension file
        let v = jext
            .get("extraSemanticSurfaces")
            .unwrap()
            .as_object()
            .unwrap();
        let jexto = jext.as_object().unwrap();
        for semsurf in v.keys() {
            let mut schema = jext["extraSemanticSurfaces"][semsurf].clone();
            schema["$schema"] = json!("http://json-schema.org/draft-07/schema#");
            if self.version_file == 11 {
                schema["$id"] = json!("https://www.cityjson.org/schemas/1.1.0/tmp.json");
            } else if self.version_file == 20 {
                schema["$id"] = json!("https://www.cityjson.org/schemas/2.0.0/tmp.json");
            }
            for each in jexto.keys() {
                let ss = each.as_str();
                if EXTENSION_FIXED_NAMES.contains(&ss) == false {
                    schema[ss] = jext[ss].clone();
                }
            }
            let compiled = self.get_compiled_schema_extension(&schema).unwrap();
            let cos = self.j.get("CityObjects").unwrap().as_object().unwrap();
            for key in cos.keys() {
                //-- check geometry
                let x = self.j["CityObjects"][key]["geometry"].as_array();
                if x.is_some() {
                    for (i, g) in x.unwrap().iter().enumerate() {
                        let surfs = g["semantics"]["surfaces"].as_array();
                        if surfs.is_some() {
                            for (j, surf) in surfs.unwrap().iter().enumerate() {
                                let tmp = surf.as_object().unwrap();
                                if tmp["type"].as_str().unwrap() == semsurf {
                                    let result = compiled.validate(
                                        &self.j["CityObjects"][key]["geometry"][i]["semantics"]
                                            ["surfaces"][j],
                                    );
                                    if let Err(errors) = result {
                                        for error in errors {
                                            let s: String =
                                                format!("{} [path:{}]", error, error.instance_path);
                                            ls_errors.push(s);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if ls_errors.is_empty() {
            Ok(())
        } else {
            Err(ls_errors)
        }
    }

    fn get_compiled_schema_extension(&self, schema: &Value) -> Option<JSONSchema> {
        if self.version_file == 11 {
            let s_1 = include_str!("../schemas/11/cityobjects.schema.json");
            let s_2 = include_str!("../schemas/11/geomprimitives.schema.json");
            let s_3 = include_str!("../schemas/11/appearance.schema.json");
            let s_4 = include_str!("../schemas/11/geomtemplates.schema.json");
            let schema_1 = serde_json::from_str(s_1).unwrap();
            let schema_2 = serde_json::from_str(s_2).unwrap();
            let schema_3 = serde_json::from_str(s_3).unwrap();
            let schema_4 = serde_json::from_str(s_4).unwrap();
            let compiled = JSONSchema::options()
                .with_draft(Draft::Draft7)
                .with_document(
                    "https://www.cityjson.org/schemas/1.1.0/cityobjects.schema.json".to_string(),
                    schema_1,
                )
                .with_document(
                    "https://www.cityjson.org/schemas/1.1.0/geomprimitives.schema.json".to_string(),
                    schema_2,
                )
                .with_document(
                    "https://www.cityjson.org/schemas/1.1.0/appearance.schema.json".to_string(),
                    schema_3,
                )
                .with_document(
                    "https://www.cityjson.org/schemas/1.1.0/geomtemplates.schema.json".to_string(),
                    schema_4,
                )
                .compile(&schema)
                .expect("A valid schema");
            return Some(compiled);
        } else if self.version_file == 20 {
            let s_1 = include_str!("../schemas/20/cityobjects.schema.json");
            let s_2 = include_str!("../schemas/20/geomprimitives.schema.json");
            let s_3 = include_str!("../schemas/20/appearance.schema.json");
            let s_4 = include_str!("../schemas/20/geomtemplates.schema.json");
            let schema_1 = serde_json::from_str(s_1).unwrap();
            let schema_2 = serde_json::from_str(s_2).unwrap();
            let schema_3 = serde_json::from_str(s_3).unwrap();
            let schema_4 = serde_json::from_str(s_4).unwrap();
            let compiled = JSONSchema::options()
                .with_draft(Draft::Draft7)
                .with_document(
                    "https://www.cityjson.org/schemas/2.0.0/cityobjects.schema.json".to_string(),
                    schema_1,
                )
                .with_document(
                    "https://www.cityjson.org/schemas/2.0.0/geomprimitives.schema.json".to_string(),
                    schema_2,
                )
                .with_document(
                    "https://www.cityjson.org/schemas/2.0.0/appearance.schema.json".to_string(),
                    schema_3,
                )
                .with_document(
                    "https://www.cityjson.org/schemas/2.0.0/geomtemplates.schema.json".to_string(),
                    schema_4,
                )
                .compile(&schema)
                .expect("A valid schema");
            return Some(compiled);
        } else {
            return None;
        }
    }

    fn validate_extensions(&self) -> Result<(), Vec<String>> {
        let mut ls_errors: Vec<String> = Vec::new();
        for ext in &self.jexts {
            //-- 0. check the version of CityJSON
            let mut v: String = self.version_file.to_string();
            v.insert(1, '.');
            if ext["versionCityJSON"] != v {
                let s: String = format!(
                    "Extension 'versionCityJSON' != CityJSON version of file [{} != {}]",
                    ext["versionCityJSON"].as_str().unwrap(),
                    v
                );
                ls_errors.push(s);
            }
            //-- 1. extraCityObjects
            let mut re = self.validate_ext_extracityobjects(&ext);
            if re.is_err() {
                ls_errors.append(&mut re.err().unwrap());
            }
            //-- 2. extraRootProperties
            re = self.validate_ext_extrarootproperties(&ext);
            if re.is_err() {
                ls_errors.append(&mut re.err().unwrap());
            }
            //-- 3. extraAttributes
            re = self.validate_ext_extraattributes(&ext);
            if re.is_err() {
                ls_errors.append(&mut re.err().unwrap());
            }
            if self.version_file >= 20 {
                //-- 4. extraSemanticSurfaces
                re = self.validate_ext_extrasemanticsurfaces(&ext);
                if re.is_err() {
                    ls_errors.append(&mut re.err().unwrap());
                }
            }
        }
        //-- 5. check if there are CityObjects that do not have a schema
        let mut re = self.validate_ext_co_without_schema();
        if re.is_err() {
            ls_errors.append(&mut re.err().unwrap());
        }
        //-- 6. check if there are extra root properties that do not have a schema
        re = self.validate_ext_rootproperty_without_schema();
        if re.is_err() {
            ls_errors.append(&mut re.err().unwrap());
        }
        //-- 7. check for the extra attributes w/o schemas
        re = self.validate_ext_attribute_without_schema();
        if re.is_err() {
            ls_errors.append(&mut re.err().unwrap());
        }
        //-- 8. check for the semsurfs w/o schemas
        if self.version_file >= 20 {
            re = self.validate_ext_semsurf_without_schema();
            if re.is_err() {
                ls_errors.append(&mut re.err().unwrap());
            }
        }

        if ls_errors.is_empty() {
            Ok(())
        } else {
            Err(ls_errors)
        }
    }

    fn validate_ext_semsurf_without_schema(&self) -> Result<(), Vec<String>> {
        let mut ls_errors: Vec<String> = Vec::new();
        let mut newss: Vec<String> = Vec::new();
        for jext in &self.jexts {
            let re = jext.get("extraSemanticSurfaces");
            if re.is_some() {
                let v = re.unwrap().as_object().unwrap();
                for ess in v.keys() {
                    newss.push(ess.to_string());
                }
            }
        }
        //-- fetch the COs
        let cos = self.j.get("CityObjects").unwrap().as_object().unwrap();
        for key in cos.keys() {
            let x = self.j["CityObjects"][key]["geometry"].as_array();
            if x.is_some() {
                for g in x.unwrap() {
                    let surfs = g["semantics"]["surfaces"].as_array();
                    if surfs.is_some() {
                        for surf in surfs.unwrap() {
                            let tmp = surf.as_object().unwrap();
                            let thetype = tmp["type"].as_str().unwrap().to_string();
                            if &thetype[0..1] == "+" && newss.contains(&thetype) == false {
                                let s: String =
                                    format!("Semantic Surface '{}' doesn't have a schema", thetype);
                                ls_errors.push(s);
                            }
                        }
                    }
                }
            }
        }

        if ls_errors.is_empty() {
            Ok(())
        } else {
            Err(ls_errors)
        }
    }

    fn validate_ext_attribute_without_schema(&self) -> Result<(), Vec<String>> {
        let mut ls_errors: Vec<String> = Vec::new();
        let mut ls_plusattrs: HashSet<String> = HashSet::new();
        let cos = self.j.get("CityObjects").unwrap().as_object().unwrap();
        for theid in cos.keys() {
            let co = cos.get(theid).unwrap().as_object().unwrap();
            if co.contains_key("attributes") {
                let attrs = co.get("attributes").unwrap().as_object().unwrap();
                for attr in attrs.keys() {
                    let sattr = attr.as_str();
                    if &sattr[0..1] == "+" {
                        // println!("attr: {:?}", sattr);
                        let a = format!("{}/{}", co.get("type").unwrap().as_str().unwrap(), sattr);
                        ls_plusattrs.insert(a);
                    }
                }
            }
        }
        // println!("{:?}", ls_plusattrs);
        for each in ls_plusattrs {
            for jext in &self.jexts {
                let s = format!("/extraAttributes/{}", each);
                let re = jext.pointer(s.as_str());
                if re.is_none() {
                    let s: String = format!("Attribute '{}' doesn't have a schema", each);
                    ls_errors.push(s);
                }
            }
        }
        if ls_errors.is_empty() {
            Ok(())
        } else {
            Err(ls_errors)
        }
    }

    fn validate_ext_co_without_schema(&self) -> Result<(), Vec<String>> {
        let mut ls_errors: Vec<String> = Vec::new();
        let mut newcos: Vec<String> = Vec::new();
        for jext in &self.jexts {
            let v = jext.get("extraCityObjects").unwrap().as_object().unwrap();
            for eco in v.keys() {
                newcos.push(eco.to_string());
            }
        }
        //-- fetch the COs
        let cos = self.j.get("CityObjects").unwrap().as_object().unwrap();
        for co in cos.keys() {
            let tmp = cos.get(co).unwrap().as_object().unwrap();
            let thetype = tmp["type"].as_str().unwrap().to_string();
            if &thetype[0..1] == "+" && newcos.contains(&thetype) == false {
                let s: String = format!("CityObject '{}' doesn't have a schema", thetype);
                ls_errors.push(s);
            }
        }
        if ls_errors.is_empty() {
            Ok(())
        } else {
            Err(ls_errors)
        }
    }

    fn validate_ext_rootproperty_without_schema(&self) -> Result<(), Vec<String>> {
        let mut ls_errors: Vec<String> = Vec::new();
        let mut newrps: Vec<String> = Vec::new();
        for jext in &self.jexts {
            let v = jext
                .get("extraRootProperties")
                .unwrap()
                .as_object()
                .unwrap();
            for erp in v.keys() {
                newrps.push(erp.to_string());
            }
        }
        let t = self.j.as_object().unwrap();
        for each in t.keys() {
            let s = each.to_string();
            if &s[0..1] == "+" && (newrps.contains(&s) == false) {
                let s: String = format!("Extra root property '{}' doesn't have a schema", s);
                ls_errors.push(s);
            }
        }
        if ls_errors.is_empty() {
            Ok(())
        } else {
            Err(ls_errors)
        }
    }

    fn extra_root_properties(&self) -> Result<(), Vec<String>> {
        if self.cjfeature {
            return Ok(());
        };
        let mut ls_warnings: Vec<String> = Vec::new();
        let rootproperties: [&str; 9] = [
            "type",
            "version",
            "extensions",
            "transform",
            "metadata",
            "CityObjects",
            "vertices",
            "appearance",
            "geometry-templates",
        ];
        let t = self.j.as_object().unwrap();
        for each in t.keys() {
            let s = each.to_string();
            if &s[0..1] != "+" && (rootproperties.contains(&s.as_str()) == false) {
                let s: String = format!("Root property '{}' is not in CityJSON schema, might be ignored by some parsers", s);
                ls_warnings.push(s);
            }
        }
        if ls_warnings.is_empty() {
            Ok(())
        } else {
            Err(ls_warnings)
        }
    }

    // parents_children_consistency
    fn parents_children_consistency(&self) -> Result<(), Vec<String>> {
        let mut ls_errors: Vec<String> = Vec::new();
        let cos = self.j.get("CityObjects").unwrap().as_object().unwrap();
        //-- do children have the parent too?
        for key in cos.keys() {
            let co = cos.get(key).unwrap().as_object().unwrap();
            if co.contains_key("children") {
                let thechildrenkeys = co.get("children").unwrap().as_array().unwrap();
                for ckey in thechildrenkeys {
                    if !cos.contains_key(ckey.as_str().unwrap()) {
                        let s = format!(
                            "CityObject #{} doesn't exist (referenced by #{})",
                            ckey.as_str().unwrap(),
                            key
                        );
                        ls_errors.push(s);
                    } else {
                        if (!cos
                            .get(ckey.as_str().unwrap())
                            .unwrap()
                            .as_object()
                            .unwrap()
                            .contains_key("parents"))
                            || (!cos
                                .get(ckey.as_str().unwrap())
                                .unwrap()
                                .as_object()
                                .unwrap()
                                .get("parents")
                                .unwrap()
                                .as_array()
                                .unwrap()
                                .contains(&json!(key)))
                        {
                            let s = format!(
                                "CityObject #{} doesn't reference correct parent (#{})",
                                ckey.as_str().unwrap(),
                                key
                            );
                            ls_errors.push(s);
                        }
                    }
                }
            }
        }
        //-- are there orphans?
        for key in cos.keys() {
            let co = cos.get(key).unwrap().as_object().unwrap();
            if co.contains_key("parents") {
                let theparentkeys = co.get("parents").unwrap().as_array().unwrap();
                for pkey in theparentkeys {
                    if !cos.contains_key(pkey.as_str().unwrap()) {
                        let s = format!(
                            "CityObject #{} is an orphan (parent #{} doesn't exist)",
                            key,
                            pkey.as_str().unwrap()
                        );
                        ls_errors.push(s);
                    }
                }
            }
        }
        if ls_errors.is_empty() {
            Ok(())
        } else {
            Err(ls_errors)
        }
    }

    fn duplicate_vertices(&self) -> Result<(), Vec<String>> {
        let mut ls_errors: Vec<String> = Vec::new();
        let vs = self.j.get("vertices").unwrap().as_array().unwrap();
        // use all vertices as keys in a hashmap
        let mut uniques = HashSet::new();
        for i in 0..vs.len() {
            let v = vs[i].as_array().unwrap();
            let s: String = format!(
                "{}{}{}",
                v[0].to_string(),
                v[1].to_string(),
                v[2].to_string()
            );
            if !uniques.contains(&s) {
                uniques.insert(s);
            } else {
                ls_errors.push(format!("Vertex ({}, {}, {}) duplicated", v[0], v[1], v[2]));
            }
        }
        if ls_errors.is_empty() {
            Ok(())
        } else {
            Err(ls_errors)
        }
    }

    fn materials(&self) -> Result<(), Vec<String>> {
        let mut max_index: usize = 0;
        let x = self.j["appearance"]["materials"].as_array();
        if x.is_some() {
            max_index = x.unwrap().len();
        }
        let mut ls_errors: Vec<String> = Vec::new();
        let cos = self.j.get("CityObjects").unwrap().as_object().unwrap();
        for theid in cos.keys() {
            //-- check geometry
            let x = self.j["CityObjects"][theid]["geometry"].as_array();
            if x.is_some() {
                let gs = x.unwrap();
                let mut gi = 0;
                for g in gs {
                    if g.get("material").is_none() {
                        continue;
                    }
                    if g["type"] == "MultiSurface" || g["type"] == "CompositeSurface" {
                        let bs = g["boundaries"].as_array().unwrap().len();
                        let gm = g["material"].as_object().unwrap();
                        for m_name in gm.keys() {
                            let gmv = g["material"][m_name]["values"].as_array();
                            if gmv.is_some() {
                                let x = gmv.unwrap();
                                if x.len() != bs {
                                    ls_errors.push(format!(
                                        "Material \"values\" not same dimension as \"boundaries\"; #{} / geom-#{} / material-\"{}\"", theid, gi, m_name
                                    ));
                                }
                                for each in x {
                                    if (each.as_u64().is_some())
                                        && (each.as_u64().unwrap() > (max_index - 1) as u64)
                                    {
                                        ls_errors.push(format!(
                                            "Reference in material \"values\" overflows (max={}); #{} and geom-#{} / material-\"{}\"",
                                            (max_index-1),theid, gi, m_name
                                        ));
                                    }
                                }
                            } else {
                                let ifvalue = g["material"][m_name]["value"].as_u64();
                                if ifvalue.is_some() {
                                    if ifvalue.unwrap() > (max_index - 1) as u64 {
                                        ls_errors.push(format!(
                                        "Material \"value\" overflow; #{} / geom-#{} / material-\"{}\"", theid, gi, m_name
                                        ));
                                    }
                                }
                            }
                        }
                    } else if g["type"] == "Solid" {
                        //-- length of the sem-surfaces == # of surfaces
                        let mut bs: Vec<usize> = Vec::new();
                        let shells = g["boundaries"].as_array().unwrap();
                        for shell in shells {
                            bs.push(shell.as_array().unwrap().len());
                        }
                        let gm = g["material"].as_object().unwrap();
                        for m_name in gm.keys() {
                            let mut vs: Vec<usize> = Vec::new();
                            let gmv = g["material"][m_name]["values"].as_array();
                            if gmv.is_some() {
                                let x = gmv.unwrap();
                                for each in x {
                                    let xa = each.as_array().unwrap();
                                    vs.push(xa.len());
                                    for each2 in xa {
                                        if (each2.as_u64().is_some())
                                            && (each2.as_u64().unwrap() > (max_index - 1) as u64)
                                        {
                                            ls_errors.push(format!(
                                                "Reference in material \"values\" overflows (max={}); #{} and geom-#{} / material-\"{}\"",
                                                (max_index-1),theid, gi, m_name
                                            ));
                                        }
                                    }
                                }
                            }
                            let ifvalue = g["material"][m_name]["value"].as_u64();
                            if ifvalue.is_some() {
                                if ifvalue.unwrap() > (max_index - 1) as u64 {
                                    ls_errors.push(format!(
                                    "Material \"value\" overflow; #{} / geom-#{} / material-\"{}\"", theid, gi, m_name
                                ));
                                }
                            } else {
                                if bs.iter().eq(vs.iter()) == false {
                                    ls_errors.push(format!(
                                    "Material \"values\" not same dimension as \"boundaries\"; #{} / geom-#{} / material-\"{}\"", theid, gi, m_name
                                ));
                                }
                            }
                        }
                    } else if g["type"] == "MultiSolid" || g["type"] == "CompositeSolid" {
                        //-- length of the sem-surfaces == # of surfaces
                        let mut bs: Vec<Vec<usize>> = Vec::new();
                        let solids = g["boundaries"].as_array().unwrap();
                        for solid in solids {
                            let asolid = solid.as_array().unwrap();
                            let mut tmp: Vec<usize> = Vec::new();
                            for surface in asolid {
                                tmp.push(surface.as_array().unwrap().len());
                            }
                            bs.push(tmp);
                        }
                        // println!("ms-bs: {:?}", bs);
                        let gm = g["material"].as_object().unwrap();
                        for m_name in gm.keys() {
                            let mut vs: Vec<Vec<usize>> = Vec::new();
                            let gmv = g["material"][m_name]["values"].as_array();
                            if gmv.is_some() {
                                let x = gmv.unwrap();
                                for a1 in x {
                                    let y = a1.as_array().unwrap();
                                    let mut vs2: Vec<usize> = Vec::new();
                                    for a2 in y {
                                        let xa = a2.as_array().unwrap();
                                        vs2.push(xa.len());
                                        for each2 in xa {
                                            if (each2.as_u64().is_some())
                                                && (each2.as_u64().unwrap()
                                                    > (max_index - 1) as u64)
                                            {
                                                ls_errors.push(format!(
                                                    "Reference in material \"values\" overflows (max={}); #{} and geom-#{} / material-\"{}\"",
                                                    (max_index-1),theid, gi, m_name
                                                ));
                                            }
                                        }
                                    }
                                    vs.push(vs2);
                                }
                            }
                            let ifvalue = g["material"][m_name]["value"].as_u64();
                            if ifvalue.is_some() {
                                if ifvalue.unwrap() > (max_index - 1) as u64 {
                                    ls_errors.push(format!(
                                    "Material \"value\" overflow; #{} / geom-#{} / material-\"{}\"", theid, gi, m_name
                                ));
                                }
                            } else {
                                if bs.iter().eq(vs.iter()) == false {
                                    ls_errors.push(format!(
                                    "Material \"values\" not same dimension as \"boundaries\"; #{} / geom-#{} / material-\"{}\"", theid, gi, m_name
                                ));
                                }
                            }
                        }
                    }
                    gi += 1;
                }
            }
        }
        if ls_errors.is_empty() {
            Ok(())
        } else {
            Err(ls_errors)
        }
    }

    fn textures(&self) -> Result<(), Vec<String>> {
        let mut max_i_tex: usize = 0;
        let mut x = self.j["appearance"]["textures"].as_array();
        if x.is_some() {
            max_i_tex = x.unwrap().len();
        }
        let mut max_i_v: usize = 0;
        x = self.j["appearance"]["vertices-texture"].as_array();
        if x.is_some() {
            max_i_v = x.unwrap().len();
        }
        let mut ls_errors: Vec<String> = Vec::new();
        let cos = self.j.get("CityObjects").unwrap().as_object().unwrap();
        for theid in cos.keys() {
            //-- check geometry
            let x = self.j["CityObjects"][theid]["geometry"].as_array();
            if x.is_some() {
                let gs = x.unwrap();
                let mut gi = 0;
                for g in gs {
                    if g.get("texture").is_none() {
                        continue;
                    }
                    if g["type"] == "MultiSurface" || g["type"] == "CompositeSurface" {
                        let gs: GeomMSu = serde_json::from_value(g.clone()).unwrap();
                        let mut l: Vec<Vec<i64>> = Vec::new();
                        for x in gs.boundaries {
                            let mut l4: Vec<i64> = Vec::new();
                            for y in x {
                                l4.push(y.len() as i64);
                            }
                            l.push(l4);
                        }
                        let tex = g["texture"].as_object().unwrap();
                        for m_name in tex.keys() {
                            let ts: TextureMSu =
                                serde_json::from_value(g["texture"][m_name].clone()).unwrap();
                            let mut l2: Vec<Vec<i64>> = Vec::new();
                            for x in ts.values {
                                let mut l3: Vec<i64> = Vec::new();
                                for mut y in x {
                                    if y[0].is_none() {
                                        l3.push(-1);
                                    } else {
                                        l3.push(y.len() as i64 - 1);
                                    }
                                    if y.len() > 1 {
                                        if y[0].unwrap() > (max_i_tex - 1) {
                                            ls_errors.push(format!(
                                                    "/texture/values/ \"{}\" overflows for texture reference; #{} and geom-#{}",
                                                    y[0].unwrap(), theid, gi
                                                ));
                                        }
                                        y.remove(0);
                                        for each in y {
                                            if each.unwrap() > (max_i_v - 1) {
                                                ls_errors.push(format!(
                                                        "/texture/values/ \"{}\" overflows for texture-vertices (max={}); #{} and geom-#{}",
                                                        each.unwrap(), (max_i_v - 1), theid, gi
                                                    ));
                                            }
                                        }
                                    }
                                }
                                l2.push(l3);
                            }
                            if l != l2 {
                                for (i, _e) in l.iter().enumerate() {
                                    if l[i] != l2[i] && l2[i][0] != -1 {
                                        ls_errors.push(format!(
                                            "/texture/values/ not same structure as /boundaries; #{} and geom-#{} and surface-#{}", theid, gi, i
                                        ));
                                    }
                                }
                            }
                        }
                    } else if g["type"] == "Solid" {
                        let gs: GeomSol = serde_json::from_value(g.clone()).unwrap();
                        let mut l: Vec<Vec<i64>> = Vec::new();
                        for x in gs.boundaries {
                            for y in x {
                                let mut l4: Vec<i64> = Vec::new();
                                for z in y {
                                    l4.push(z.len() as i64);
                                }
                                l.push(l4);
                            }
                        }
                        let tex = g["texture"].as_object().unwrap();
                        for m_name in tex.keys() {
                            let ts: TextureSol =
                                serde_json::from_value(g["texture"][m_name].clone()).unwrap();
                            let mut l2: Vec<Vec<i64>> = Vec::new();
                            for x in ts.values {
                                for y in x {
                                    let mut l3: Vec<i64> = Vec::new();
                                    for mut z in y {
                                        if z[0].is_none() {
                                            l3.push(-1);
                                        } else {
                                            l3.push(z.len() as i64 - 1);
                                        }
                                        if z.len() > 1 {
                                            if z[0].unwrap() > (max_i_tex - 1) {
                                                ls_errors.push(format!(
                                                "/texture/values/ \"{}\" overflows for texture reference; #{} and geom-#{}",
                                                z[0].unwrap(), theid, gi
                                            ));
                                            }
                                            z.remove(0);
                                            for each in z {
                                                if each.unwrap() > (max_i_v - 1) {
                                                    ls_errors.push(format!(
                                                    "/texture/values/ \"{}\" overflows for texture-vertices (max={}); #{} and geom-#{}",
                                                    each.unwrap(), (max_i_v - 1), theid, gi
                                                ));
                                                }
                                            }
                                        }
                                    }
                                    l2.push(l3);
                                }
                            }
                            if l != l2 {
                                for (i, _e) in l.iter().enumerate() {
                                    if l[i] != l2[i] && l2[i][0] != -1 {
                                        ls_errors.push(format!(
                                            "/texture/values/ not same structure as /boundaries; #{} and geom-#{} and surface-#{}", theid, gi, i
                                        ));
                                    }
                                }
                            }
                        }
                    } else if g["type"] == "MultiSolid" || g["type"] == "CompositeSolid" {
                        let gs: GeomMSol = serde_json::from_value(g.clone()).unwrap();
                        let mut l: Vec<Vec<i64>> = Vec::new();
                        for x in gs.boundaries {
                            for y in x {
                                for z in y {
                                    let mut l4: Vec<i64> = Vec::new();
                                    for w in z {
                                        l4.push(w.len() as i64);
                                    }
                                    l.push(l4);
                                }
                            }
                        }
                        let tex = g["texture"].as_object().unwrap();
                        for m_name in tex.keys() {
                            let ts: TextureMSol =
                                serde_json::from_value(g["texture"][m_name].clone()).unwrap();
                            let mut l2: Vec<Vec<i64>> = Vec::new();
                            for x in ts.values {
                                for y in x {
                                    for z in y {
                                        let mut l3: Vec<i64> = Vec::new();
                                        for mut w in z {
                                            if w[0].is_none() {
                                                l3.push(-1);
                                            } else {
                                                l3.push(w.len() as i64 - 1);
                                            }
                                            if w.len() > 1 {
                                                if w[0].unwrap() > (max_i_tex - 1) {
                                                    ls_errors.push(format!(
                                                    "/texture/values/ \"{}\" overflows for texture reference; #{} and geom-#{}",
                                                    w[0].unwrap(), theid, gi
                                                ));
                                                }
                                                w.remove(0);
                                                for each in w {
                                                    if each.unwrap() > (max_i_v - 1) {
                                                        ls_errors.push(format!(
                                                        "/texture/values/ \"{}\" overflows for texture-vertices (max={}); #{} and geom-#{}",
                                                        each.unwrap(), (max_i_v - 1), theid, gi
                                                    ));
                                                    }
                                                }
                                            }
                                        }
                                        l2.push(l3);
                                    }
                                }
                            }
                            if l != l2 {
                                for (i, _e) in l.iter().enumerate() {
                                    if l[i] != l2[i] && l2[i][0] != -1 {
                                        ls_errors.push(format!(
                                            "/texture/values/ not same structure as /boundaries; #{} and geom-#{} and surface-#{}", theid, gi, i
                                        ));
                                    }
                                }
                            }
                        }
                    }
                    gi += 1;
                }
            }
        }
        if ls_errors.is_empty() {
            Ok(())
        } else {
            Err(ls_errors)
        }
    }

    fn wrong_vertex_index(&self) -> Result<(), Vec<String>> {
        let max_index: usize = self.j.get("vertices").unwrap().as_array().unwrap().len();
        let mut ls_errors: Vec<String> = Vec::new();
        let cos = self.j.get("CityObjects").unwrap().as_object().unwrap();
        for key in cos.keys() {
            //-- check geometry
            let x = self.j["CityObjects"][key]["geometry"].as_array();
            if x.is_some() {
                for g in x.unwrap() {
                    if g["type"] == "MultiPoint" {
                        let a: GeomMPo = serde_json::from_value(g.clone()).unwrap();
                        for each in a.boundaries {
                            if each >= max_index {
                                let s2 = format!("Vertices {} don't exist", each);
                                ls_errors.push(s2);
                            }
                        }
                    } else if g["type"] == "MultiLineString" {
                        let a: GeomMLS = serde_json::from_value(g.clone()).unwrap();
                        for l in a.boundaries {
                            for each in l {
                                if each >= max_index {
                                    let s2 = format!("Vertices {} don't exist", each);
                                    ls_errors.push(s2);
                                }
                            }
                        }
                    } else if g["type"] == "MultiSurface" || g["type"] == "CompositeSurface" {
                        let a: GeomMSu = serde_json::from_value(g.clone()).unwrap();
                        let re = above_max_index_msu(&a.boundaries, max_index);
                        if re.is_err() {
                            ls_errors.push(re.err().unwrap());
                        }
                    } else if g["type"] == "Solid" {
                        let a: GeomSol = serde_json::from_value(g.clone()).unwrap();
                        let re = above_max_index_sol(&a.boundaries, max_index);
                        if re.is_err() {
                            ls_errors.push(re.err().unwrap());
                        }
                    } else if g["type"] == "MultiSolid" || g["type"] == "CompositeSolid" {
                        let a: GeomMSol = serde_json::from_value(g.clone()).unwrap();
                        let re = above_max_index_msol(&a.boundaries, max_index);
                        if re.is_err() {
                            ls_errors.push(re.err().unwrap());
                        }
                    } else if g["type"] == "GeometryInstance" {
                        let a: GeomMPo = serde_json::from_value(g.clone()).unwrap();
                        for each in a.boundaries {
                            if each >= max_index {
                                let s2 = format!("Vertex {} doesn't exist (in #{})", each, key);
                                ls_errors.push(s2);
                            }
                        }
                    }
                }
            }
            //-- check address
            if self.j["CityObjects"][key]["type"] == "Building"
                || self.j["CityObjects"][key]["type"] == "BuildingPart"
                || self.j["CityObjects"][key]["type"] == "BuildingUnit"
                || self.j["CityObjects"][key]["type"] == "Bridge"
                || self.j["CityObjects"][key]["type"] == "BridgePart"
            {
                let x = self.j["CityObjects"][key]["address"].as_array();
                if x.is_some() {
                    for ad in x.unwrap() {
                        let t = ad.pointer("/location/boundaries");
                        if t.is_some() {
                            let i = t.unwrap().get(0).unwrap().as_u64().unwrap();
                            if (i as usize) >= max_index {
                                let s2 = format!("Vertices {} don't exist", i);
                                ls_errors.push(s2);
                            }
                        }
                    }
                }
            }
        }
        if ls_errors.is_empty() {
            Ok(())
        } else {
            Err(ls_errors)
        }
    }

    fn unused_vertices(&self) -> Result<(), Vec<String>> {
        let mut ls_errors: Vec<String> = Vec::new();
        let mut uniques: HashSet<usize> = HashSet::new();
        let cos = self.j.get("CityObjects").unwrap().as_object().unwrap();
        for key in cos.keys() {
            //-- check geometry
            let x = self.j["CityObjects"][key]["geometry"].as_array();
            if x.is_some() {
                let gs = x.unwrap();
                for g in gs {
                    if g["type"] == "MultiPoint" {
                        let a: GeomMPo = serde_json::from_value(g.clone()).unwrap();
                        for each in a.boundaries {
                            uniques.insert(each);
                        }
                    } else if g["type"] == "MultiLineString" {
                        let a: GeomMLS = serde_json::from_value(g.clone()).unwrap();
                        for l in a.boundaries {
                            for each in l {
                                uniques.insert(each);
                            }
                        }
                    } else if g["type"] == "MultiSurface" || g["type"] == "CompositeSurface" {
                        let gv: GeomMSu = serde_json::from_value(g.clone()).unwrap();
                        collect_indices_msu(&gv.boundaries, &mut uniques);
                    } else if g["type"] == "Solid" {
                        let gv: GeomSol = serde_json::from_value(g.clone()).unwrap();
                        collect_indices_sol(&gv.boundaries, &mut uniques);
                    } else if g["type"] == "MultiSolid" || g["type"] == "CompositeSolid" {
                        let gv: GeomMSol = serde_json::from_value(g.clone()).unwrap();
                        collect_indices_msol(&gv.boundaries, &mut uniques);
                    } else if g["type"] == "GeometryInstance" {
                        let a: GeomMPo = serde_json::from_value(g.clone()).unwrap();
                        for each in a.boundaries {
                            uniques.insert(each);
                        }
                    }
                }
            }
            //-- check address
            if self.j["CityObjects"][key]["type"] == "Building"
                || self.j["CityObjects"][key]["type"] == "BuildingPart"
                || self.j["CityObjects"][key]["type"] == "BuildingUnit"
                || self.j["CityObjects"][key]["type"] == "Bridge"
                || self.j["CityObjects"][key]["type"] == "BridgePart"
            {
                let x = self.j["CityObjects"][key]["address"].as_array();
                if x.is_some() {
                    for ad in x.unwrap() {
                        let t = ad.pointer("/location/boundaries");
                        if t.is_some() {
                            let i = t.unwrap().get(0).unwrap().as_u64().unwrap();
                            uniques.insert(i as usize);
                        }
                    }
                }
            }
        }
        let noorphans = self.j["vertices"].as_array().unwrap().len() - uniques.len();
        if noorphans > 0 {
            if noorphans > 5 {
                ls_errors.push(format!("{} vertices are unused", noorphans));
            } else {
                let total = self.j["vertices"].as_array().unwrap().len();
                for each in 0..total {
                    if !uniques.contains(&each) {
                        ls_errors.push(format!("Vertex #{} is unused", each));
                    }
                }
            }
        }
        if ls_errors.is_empty() {
            Ok(())
        } else {
            Err(ls_errors)
        }
    }

    fn semantics_arrays(&self) -> Result<(), Vec<String>> {
        let mut ls_errors: Vec<String> = Vec::new();
        let cos = self.j.get("CityObjects").unwrap().as_object().unwrap();
        for theid in cos.keys() {
            let x = self.j["CityObjects"][theid]["geometry"].as_array();
            if x.is_some() {
                let gs = x.unwrap();
                let mut gi = 0;
                for g in gs {
                    if g.get("semantics").is_none() {
                        continue;
                    }
                    if g["type"] == "MultiPoint"
                        || g["type"] == "MultiLineString"
                        || g["type"] == "MultiSurface"
                        || g["type"] == "CompositeSurface"
                    {
                        //-- length of the sem-surfaces == # of surfaces
                        if g["boundaries"].as_array().unwrap().len()
                            != g["semantics"]["values"].as_array().unwrap().len()
                        {
                            ls_errors.push(format!(
                                "Semantic \"values\" not same dimension as \"boundaries\"; #{} and geom-#{}", theid, gi
                            ));
                        }
                        //-- values in "values"
                        let a = g["semantics"]["surfaces"].as_array().unwrap().len();
                        for i in g["semantics"]["values"].as_array().unwrap() {
                            if i.is_null() {
                                continue;
                            }
                            if i.as_u64().unwrap() > (a - 1) as u64 {
                                ls_errors.push(format!(
                                    "Reference in semantic \"values\" overflows; #{} and geom-#{}",
                                    theid, gi
                                ));
                            }
                        }
                    }
                    if g["type"] == "Solid" {
                        //-- length of the sem-surfaces == # of surfaces
                        let mut bs: Vec<usize> = Vec::new();
                        let shells = g["boundaries"].as_array().unwrap();
                        for surface in shells {
                            bs.push(surface.as_array().unwrap().len());
                        }
                        // println!("bs: {:?}", bs);
                        let mut vs: Vec<usize> = Vec::new();
                        let tmp = g["semantics"]["values"].as_array().unwrap();
                        for each in tmp {
                            vs.push(each.as_array().unwrap().len());
                        }
                        // println!("vs: {:?}", vs);
                        // println!("eq: {:?}", bs.iter().eq(vs.iter()));
                        if bs.iter().eq(vs.iter()) == false {
                            ls_errors.push(format!(
                                "Semantic \"values\" not same dimension as \"boundaries\"; #{} and geom-#{}", theid, gi
                            ));
                        }
                        //-- values in "values"
                        let a = g["semantics"]["surfaces"].as_array().unwrap().len();
                        for i in g["semantics"]["values"].as_array().unwrap() {
                            let ai = i.as_array().unwrap();
                            for j in ai {
                                if j.is_null() {
                                    continue;
                                }
                                if j.as_u64().unwrap() > (a - 1) as u64 {
                                    ls_errors.push(format!(
                                        "Reference in semantic \"values\" overflows; #{} and geom-#{}",
                                        theid, gi
                                    ));
                                }
                            }
                        }
                    }
                    if g["type"] == "MultiSolid" || g["type"] == "CompositeSolid" {
                        //-- length of the sem-surfaces == # of surfaces
                        let mut bs: Vec<Vec<usize>> = Vec::new();
                        let solids = g["boundaries"].as_array().unwrap();
                        for solid in solids {
                            let asolid = solid.as_array().unwrap();
                            let mut tmp: Vec<usize> = Vec::new();
                            for surface in asolid {
                                tmp.push(surface.as_array().unwrap().len());
                            }
                            bs.push(tmp);
                        }
                        // println!("ms-bs: {:?}", bs);
                        let mut vs: Vec<Vec<usize>> = Vec::new();
                        let a = g["semantics"]["values"].as_array().unwrap();
                        for i in a {
                            let mut tmp: Vec<usize> = Vec::new();
                            let b = i.as_array().unwrap();
                            for j in b {
                                tmp.push(j.as_array().unwrap().len());
                            }
                            vs.push(tmp);
                        }
                        // println!("ms-vs: {:?}", vs);
                        // println!("eq: {:?}", bs.iter().eq(vs.iter()));
                        if bs.iter().eq(vs.iter()) == false {
                            ls_errors.push(format!(
                                "Semantic \"values\" not same dimension as \"boundaries\"; #{} and geom-#{}", theid, gi
                            ));
                        }
                        //-- values in "values"
                        let a = g["semantics"]["surfaces"].as_array().unwrap().len();
                        for i in g["semantics"]["values"].as_array().unwrap() {
                            let ai = i.as_array().unwrap();
                            for j in ai {
                                let aj = j.as_array().unwrap();
                                for k in aj {
                                    if k.is_null() {
                                        continue;
                                    }
                                    if k.as_u64().unwrap() > (a - 1) as u64 {
                                        ls_errors.push(format!(
                                        "Reference in semantic \"values\" overflows; #{} and geom-#{}",
                                        theid, gi
                                    ));
                                    }
                                }
                            }
                        }
                    }
                    gi += 1;
                }
            }
        }
        if ls_errors.is_empty() {
            Ok(())
        } else {
            Err(ls_errors)
        }
    }
}

fn collect_indices_msu(a: &Vec<Vec<Vec<usize>>>, uniques: &mut HashSet<usize>) {
    for x in a {
        for y in x {
            for z in y {
                uniques.insert(*z);
            }
        }
    }
}

fn collect_indices_sol(a: &Vec<Vec<Vec<Vec<usize>>>>, uniques: &mut HashSet<usize>) {
    for x in a {
        for y in x {
            for z in y {
                for w in z {
                    uniques.insert(*w);
                }
            }
        }
    }
}

fn collect_indices_msol(a: &Vec<Vec<Vec<Vec<Vec<usize>>>>>, uniques: &mut HashSet<usize>) {
    for x in a {
        for y in x {
            for z in y {
                for w in z {
                    for q in w {
                        uniques.insert(*q);
                    }
                }
            }
        }
    }
}

fn above_max_index_msu(a: &Vec<Vec<Vec<usize>>>, max_index: usize) -> Result<(), String> {
    let mut r: Vec<usize> = vec![];
    for x in a {
        for y in x {
            for z in y {
                if z >= &max_index {
                    r.push(*z);
                }
            }
        }
    }
    if r.is_empty() {
        Ok(())
    } else {
        let mut s: String = "".to_string();
        for each in r {
            s += "#";
            s += &each.to_string();
            s += "/";
        }
        let s2 = format!("Vertices {} don't exist", s);
        Err(s2)
    }
}

fn above_max_index_sol(a: &Vec<Vec<Vec<Vec<usize>>>>, max_index: usize) -> Result<(), String> {
    let mut r: Vec<usize> = vec![];
    for x in a {
        for y in x {
            for z in y {
                for w in z {
                    if w >= &max_index {
                        r.push(*w);
                    }
                }
            }
        }
    }
    if r.is_empty() {
        Ok(())
    } else {
        let mut s: String = "".to_string();
        for each in r {
            s += "#";
            s += &each.to_string();
            s += "/";
        }
        let s2 = format!("Vertices {} don't exist", s);
        Err(s2)
    }
}

fn above_max_index_msol(
    a: &Vec<Vec<Vec<Vec<Vec<usize>>>>>,
    max_index: usize,
) -> Result<(), String> {
    let mut r: Vec<usize> = vec![];
    for x in a {
        for y in x {
            for z in y {
                for w in z {
                    for q in w {
                        if q >= &max_index {
                            r.push(*q);
                        }
                    }
                }
            }
        }
    }
    if r.is_empty() {
        return Ok(());
    } else {
        let mut s: String = "".to_string();
        for each in r {
            s += "#";
            s += &each.to_string();
            s += "/";
        }
        let s2 = format!("Vertices {} don't exist", s);
        return Err(s2);
    }
}