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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
/*-
 * SPDX-License-Identifier: BSD-2-Clause
 *
 * Copyright (c) 2020 NKI/AVL, Netherlands Cancer Institute
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "cif++.hpp"

#include <filesystem>
#include <fstream>
#include <iomanip>
#include <numeric>
#include <stack>

namespace fs = std::filesystem;

namespace cif::mm
{

// --------------------------------------------------------------------
// atom

void atom::atom_impl::moveTo(const point &p)
{
	if (m_symop != "1_555")
		throw std::runtime_error("Moving symmetry copy");

	auto r = row();

#if __cpp_lib_format
	r.assign("Cartn_x", std::format("{:.3f}", p.m_x), false, false);
	r.assign("Cartn_y", std::format("{:.3f}", p.m_y), false, false);
	r.assign("Cartn_z", std::format("{:.3f}", p.m_z), false, false);
#else
	r.assign("Cartn_x", cif::format("%.3f", p.m_x).str(), false, false);
	r.assign("Cartn_y", cif::format("%.3f", p.m_y).str(), false, false);
	r.assign("Cartn_z", cif::format("%.3f", p.m_z).str(), false, false);
#endif
	m_location = p;
}

// const compound *compound() const;

std::string atom::atom_impl::get_property(std::string_view name) const
{
	return row()[name].as<std::string>();
}

int atom::atom_impl::get_property_int(std::string_view name) const
{
	int result = 0;
	if (not row()[name].empty())
	{
		auto s = get_property(name);

		std::from_chars_result r = std::from_chars(s.data(), s.data() + s.length(), result);
		if ((bool)r.ec and VERBOSE > 0)
			std::cerr << "Error converting " << s << " to number for property " << name << '\n';
	}
	return result;
}

float atom::atom_impl::get_property_float(std::string_view name) const
{
	float result = 0;
	if (not row()[name].empty())
	{
		auto s = get_property(name);

		std::from_chars_result r = cif::from_chars(s.data(), s.data() + s.length(), result);
		if ((bool)r.ec and VERBOSE > 0)
			std::cerr << "Error converting " << s << " to number for property " << name << '\n';
	}
	return result;
}

void atom::atom_impl::set_property(const std::string_view name, const std::string &value)
{
	auto r = row();
	if (not r)
		throw std::runtime_error("Trying to modify a row that does not exist");
	r.assign(name, value, true, true);
}

// int atom::atom_impl::compare(const atom_impl &b) const
// {
// 	int d = m_asym_id.compare(b.m_asym_id);
// 	if (d == 0)
// 		d = m_seq_id - b.m_seq_id;
// 	if (d == 0)
// 		d = m_auth_seq_id.compare(b.m_auth_seq_id);
// 	if (d == 0)
// 		d = mAtom_id.compare(b.mAtom_id);

// 	return d;
// }

// bool atom::atom_impl::getAnisoU(float anisou[6]) const
// {
// 	bool result = false;

// 	auto cat = m_db.get("atom_site_anisotrop");
// 	if (cat)
// 	{
// 		for (auto r : cat->find(key("id") == m_id))
// 		{
// 			tie(anisou[0], anisou[1], anisou[2], anisou[3], anisou[4], anisou[5]) =
// 				r.get("U[1][1]", "U[1][2]", "U[1][3]", "U[2][2]", "U[2][3]", "U[3][3]");
// 			result = true;
// 			break;
// 		}
// 	}

// 	return result;
// }

int atom::atom_impl::get_charge() const
{
	auto formalCharge = row()["pdbx_formal_charge"].as<std::optional<int>>();

	if (not formalCharge.has_value())
	{
		auto c = cif::compound_factory::instance().create(get_property("label_comp_id"));

		if (c != nullptr and c->atoms().size() == 1)
			formalCharge = c->atoms().front().charge;
	}

	return formalCharge.value_or(0);
}

// const Compound *atom::atom_impl::compound() const
// {
// 	if (mCompound == nullptr)
// 	{
// 		std::string compID = get_property("label_comp_id");

// 		mCompound = compound_factory::instance().create(compID);
// 	}

// 	return mCompound;
// }

// const std::string atom::atom_impl::get_property(const std::string_view name) const
// {
// 	for (auto &&[item_name, ref] : mCachedRefs)
// 	{
// 		if (item_name == name)
// 			return ref.as<std::string>();
// 	}

// 	mCachedRefs.emplace_back(name, const_cast<Row &>(mRow)[name]);
// 	return std::get<1>(mCachedRefs.back()).as<std::string>();
// }

// void atom::atom_impl::set_property(const std::string_view name, const std::string &value)
// {
// 	for (auto &&[item_name, ref] : mCachedRefs)
// 	{
// 		if (item_name != name)
// 			continue;

// 		ref = value;
// 		return;
// 	}

// 	mCachedRefs.emplace_back(name, mRow[name]);
// 	std::get<1>(mCachedRefs.back()) = value;
// }

// const Row atom::getRowAniso() const
// {
// 	auto &db = m_impl->m_db;
// 	auto cat = db.get("atom_site_anisotrop");
// 	if (not cat)
// 		return {};
// 	else
// 		return cat->find1(key("id") == m_impl->m_id);
// }

// float atom::uIso() const
// {
// 	float result;

// 	if (not get_property<std::string>("U_iso_or_equiv").empty())
// 		result = get_property<float>("U_iso_or_equiv");
// 	else if (not get_property<std::string>("B_iso_or_equiv").empty())
// 		result = get_property<float>("B_iso_or_equiv") / static_cast<float>(8 * kPI * kPI);
// 	else
// 		throw std::runtime_error("Missing B_iso or U_iso");

// 	return result;
// }

// const Compound &atom::compound() const
// {
// 	auto result = impl().compound();

// 	if (result == nullptr)
// 	{
// 		if (VERBOSE > 0)
// 			std::cerr << "Compound not found: '" << get_property<std::string>("label_comp_id") << '\'' << '\n';

// 		throw std::runtime_error("no compound");
// 	}

// 	return *result;
// }

// std::string atom::labelEntityID() const
// {
// 	return get_property<std::string>("label_entity_id");
// }

// std::string atom::authAtom_id() const
// {
// 	return get_property<std::string>("auth_atom_id");
// }

// std::string atom::authCompID() const
// {
// 	return get_property<std::string>("auth_comp_id");
// }

// std::string atom::get_auth_asym_id() const
// {
// 	return get_property<std::string>("auth_asym_id");
// }

// std::string atom::get_pdb_ins_code() const
// {
// 	return get_property<std::string>("pdbx_PDB_ins_code");
// }

// std::string atom::pdbxAuthAltID() const
// {
// 	return get_property<std::string>("pdbx_auth_alt_id");
// }

// void atom::translate(point t)
// {
// 	auto loc = location();
// 	loc += t;
// 	location(loc);
// }

// void atom::rotate(quaternion q)
// {
// 	auto loc = location();
// 	loc.rotate(q);
// 	location(loc);
// }

// void atom::translate_and_rotate(point t, quaternion q)
// {
// 	auto loc = location();
// 	loc += t;
// 	loc.rotate(q);
// 	location(loc);
// }

// void atom::translate_rotate_and_translate(point t1, quaternion q, point t2)
// {
// 	auto loc = location();
// 	loc += t1;
// 	loc.rotate(q);
// 	loc += t2;
// 	location(loc);
// }

std::ostream &operator<<(std::ostream &os, const atom &atom)
{
	if (atom.is_water())
		os << atom.get_label_comp_id() << ' ' << atom.get_label_asym_id() << ':' << atom.get_auth_seq_id() << ' ' << atom.get_label_atom_id();
	else
	{
		os << atom.get_label_comp_id() << ' ' << atom.get_label_asym_id() << ':' << atom.get_label_seq_id() << ' ' << atom.get_label_atom_id();

		if (atom.is_alternate())
			os << '(' << atom.get_label_alt_id() << ')';
		if (atom.get_auth_asym_id() != atom.get_label_asym_id() or atom.get_auth_seq_id() != std::to_string(atom.get_label_seq_id()) or atom.get_pdb_ins_code().empty() == false)
			os << " [" << atom.get_auth_asym_id() << ':' << atom.get_auth_seq_id() << atom.get_pdb_ins_code() << ']';
	}

	return os;
}

// --------------------------------------------------------------------
// residue

residue::residue(structure &structure, const std::vector<atom> &atoms)
	: m_structure(&structure)
{
	if (atoms.empty())
		throw std::runtime_error("Empty list of atoms");
	
	auto &a = atoms.front();

	m_compound_id = a.get_label_comp_id();
	m_asym_id = a.get_label_asym_id();
	m_seq_id = a.get_label_seq_id();
	m_auth_asym_id = a.get_auth_asym_id();
	m_auth_seq_id = a.get_auth_seq_id();
	m_pdb_ins_code = a.get_pdb_ins_code();

	for (auto atom : atoms)
		m_atoms.push_back(atom);
}

std::string residue::get_entity_id() const
{
	std::string result;

	if (not m_atoms.empty())
		result = m_atoms.front().get_label_entity_id();
	else if (m_structure != nullptr and not m_asym_id.empty())
	{
		using namespace literals;

		auto &db = m_structure->get_datablock();
		result = db["struct_asym"].find1<std::string>("id"_key == m_asym_id, "entity_id");
	}

	return result;
}

EntityType residue::entity_type() const
{
	assert(m_structure);
	return m_structure->get_entity_type_for_entity_id(get_entity_id());
}

void residue::add_atom(atom &atom)
{
	m_atoms.push_back(atom);
}

std::vector<atom> residue::unique_atoms() const
{
	std::vector<atom> result;
	std::string firstAlt;

	for (auto &atom : m_atoms)
	{
		auto alt = atom.get_label_alt_id();
		if (alt.empty())
		{
			result.push_back(atom);
			continue;
		}

		if (firstAlt.empty())
			firstAlt = alt;
		else if (alt != firstAlt)
		{
			if (VERBOSE > 0)
				std::cerr << "skipping alternate atom " << atom << '\n';
			continue;
		}

		result.push_back(atom);
	}

	return result;
}

std::set<std::string> residue::get_alternate_ids() const
{
	std::set<std::string> result;

	for (auto a : m_atoms)
	{
		auto alt = a.get_label_alt_id();
		if (not alt.empty())
			result.insert(alt);
	}

	return result;
}

atom residue::get_atom_by_atom_id(const std::string &atom_id) const
{
	atom result;

	for (auto &a : m_atoms)
	{
		if (a.get_label_atom_id() == atom_id)
		{
			result = a;
			break;
		}
	}

	if (not result and VERBOSE > 1)
		std::cerr << "atom with atom_id " << atom_id << " not found in residue " << m_asym_id << ':' << m_seq_id << '\n';

	return result;
}

// residue is a single entity if the atoms for the asym with m_asym_id is equal
// to the number of atoms in this residue...  hope this is correct....
bool residue::is_entity() const
{
	auto &db = m_structure->get_datablock();

	auto a1 = db["atom_site"].find(key("label_asym_id") == m_asym_id);
	//	auto a2 = atoms();
	auto &a2 = m_atoms;

	return a1.size() == a2.size();
}

std::tuple<point, float> residue::center_and_radius() const
{
	std::vector<point> pts;
	for (auto &a : m_atoms)
		pts.push_back(a.get_location());

	auto center = centroid(pts);
	float radius = 0;

	for (auto &pt : pts)
	{
		float d = static_cast<float>(distance(pt, center));
		if (radius < d)
			radius = d;
	}

	return std::make_tuple(center, radius);
}

bool residue::has_alternate_atoms() const
{
	return std::find_if(m_atoms.begin(), m_atoms.end(), [](const atom &atom)
			   { return atom.is_alternate(); }) != m_atoms.end();
}

std::set<std::string> residue::get_atom_ids() const
{
	std::set<std::string> ids;
	for (auto a : m_atoms)
		ids.insert(a.get_label_atom_id());

	return ids;
}

std::vector<atom> residue::get_atoms_by_id(const std::string &atom_id) const
{
	std::vector<atom> atoms;
	for (auto a : m_atoms)
	{
		if (a.get_label_atom_id() == atom_id)
			atoms.push_back(a);
	}
	return atoms;
}

std::ostream &operator<<(std::ostream &os, const residue &res)
{
	os << res.get_compound_id() << ' ' << res.get_asym_id() << ':' << res.get_seq_id();

	if (res.get_auth_asym_id() != res.get_asym_id() or res.get_auth_seq_id() != std::to_string(res.get_seq_id()))
		os << " [" << res.get_auth_asym_id() << ':' << res.get_auth_seq_id() << ']';

	return os;
}

// --------------------------------------------------------------------
// monomer

monomer::monomer(const polymer &polymer, size_t index, int seqID, const std::string &authSeqID, const std::string &pdbInsCode, const std::string &compoundID)
	: residue(*polymer.get_structure(), compoundID, polymer.get_asym_id(), seqID, polymer.get_auth_asym_id(), authSeqID, pdbInsCode)
	, m_polymer(&polymer)
	, m_index(index)
{
}

monomer::monomer(monomer &&rhs)
	: residue(std::move(rhs))
	, m_polymer(rhs.m_polymer)
	, m_index(rhs.m_index)
{
	rhs.m_polymer = nullptr;
}

monomer &monomer::operator=(monomer &&rhs)
{
	residue::operator=(std::move(rhs));
	m_polymer = rhs.m_polymer;
	rhs.m_polymer = nullptr;
	m_index = rhs.m_index;

	return *this;
}

bool monomer::is_first_in_chain() const
{
	return m_index == 0;
}

bool monomer::is_last_in_chain() const
{
	return m_index + 1 == m_polymer->size();
}

bool monomer::has_alpha() const
{
	return m_index >= 1 and m_index + 2 < m_polymer->size();
}

bool monomer::has_kappa() const
{
	return m_index >= 2 and m_index + 2 < m_polymer->size();
}

float monomer::phi() const
{
	float result = 360;

	if (m_index > 0)
	{
		auto &prev = m_polymer->operator[](m_index - 1);
		if (prev.m_seq_id + 1 == m_seq_id)
		{
			auto a1 = prev.C();
			auto a2 = N();
			auto a3 = CAlpha();
			auto a4 = C();

			if (a1 and a2 and a3 and a4)
				result = dihedral_angle(a1.get_location(), a2.get_location(), a3.get_location(), a4.get_location());
		}
	}

	return result;
}

float monomer::psi() const
{
	float result = 360;

	if (m_index + 1 < m_polymer->size())
	{
		auto &next = m_polymer->operator[](m_index + 1);
		if (m_seq_id + 1 == next.m_seq_id)
		{
			auto a1 = N();
			auto a2 = CAlpha();
			auto a3 = C();
			auto a4 = next.N();

			if (a1 and a2 and a3 and a4)
				result = dihedral_angle(a1.get_location(), a2.get_location(), a3.get_location(), a4.get_location());
		}
	}

	return result;
}

float monomer::alpha() const
{
	float result = 360;

	try
	{
		if (m_index >= 1 and m_index + 2 < m_polymer->size())
		{
			auto &prev = m_polymer->operator[](m_index - 1);
			auto &next = m_polymer->operator[](m_index + 1);
			auto &nextNext = m_polymer->operator[](m_index + 2);

			result = static_cast<float>(dihedral_angle(prev.CAlpha().get_location(), CAlpha().get_location(), next.CAlpha().get_location(), nextNext.CAlpha().get_location()));
		}
	}
	catch (const std::exception &ex)
	{
		if (VERBOSE > 0)
			std::cerr << ex.what() << '\n';
	}

	return result;
}

float monomer::kappa() const
{
	float result = 360;

	try
	{
		if (m_index >= 2 and m_index + 2 < m_polymer->size())
		{
			auto &prevPrev = m_polymer->operator[](m_index - 2);
			auto &nextNext = m_polymer->operator[](m_index + 2);

			if (prevPrev.m_seq_id + 4 == nextNext.m_seq_id)
			{
				double ckap = cosinus_angle(CAlpha().get_location(), prevPrev.CAlpha().get_location(), nextNext.CAlpha().get_location(), CAlpha().get_location());
				double skap = std::sqrt(1 - ckap * ckap);
				result = static_cast<float>(std::atan2(skap, ckap) * 180 / kPI);
			}
		}
	}
	catch (const std::exception &ex)
	{
		if (VERBOSE > 0)
			std::cerr << "When trying to calculate kappa for " << m_asym_id << ':' << m_seq_id << ": "
					  << ex.what() << '\n';
	}

	return result;
}

float monomer::tco() const
{
	float result = 0.0;

	try
	{
		if (m_index > 0)
		{
			auto &prev = m_polymer->operator[](m_index - 1);
			if (prev.m_seq_id + 1 == m_seq_id)
				result = static_cast<float>(cosinus_angle(C().get_location(), O().get_location(), prev.C().get_location(), prev.O().get_location()));
		}
	}
	catch (const std::exception &ex)
	{
		if (VERBOSE > 0)
			std::cerr << "When trying to calculate tco for " << get_asym_id() << ':' << get_seq_id() << ": "
					  << ex.what() << '\n';
	}

	return result;
}

float monomer::omega() const
{
	float result = 360;

	try
	{
		if (not is_last_in_chain())
			result = omega(*this, m_polymer->operator[](m_index + 1));
	}
	catch (const std::exception &ex)
	{
		if (VERBOSE > 0)
			std::cerr << "When trying to calculate omega for " << get_asym_id() << ':' << get_seq_id() << ": "
					  << ex.what() << '\n';
	}

	return result;
}

const std::map<std::string, std::vector<std::string>> kChiAtomsMap = {
	{"ASP", {"CG", "OD1"}},
	{"ASN", {"CG", "OD1"}},
	{"ARG", {"CG", "CD", "NE", "CZ"}},
	{"HIS", {"CG", "ND1"}},
	{"GLN", {"CG", "CD", "OE1"}},
	{"GLU", {"CG", "CD", "OE1"}},
	{"SER", {"OG"}},
	{"THR", {"OG1"}},
	{"LYS", {"CG", "CD", "CE", "NZ"}},
	{"TYR", {"CG", "CD1"}},
	{"PHE", {"CG", "CD1"}},
	{"LEU", {"CG", "CD1"}},
	{"TRP", {"CG", "CD1"}},
	{"CYS", {"SG"}},
	{"ILE", {"CG1", "CD1"}},
	{"MET", {"CG", "SD", "CE"}},
	{"MSE", {"CG", "SE", "CE"}},
	{"PRO", {"CG", "CD"}},
	{"VAL", {"CG1"}}};

size_t monomer::nr_of_chis() const
{
	size_t result = 0;

	auto i = kChiAtomsMap.find(m_compound_id);
	if (i != kChiAtomsMap.end())
		result = i->second.size();

	return result;
}

float monomer::chi(size_t nr) const
{
	float result = 0;

	try
	{
		auto i = kChiAtomsMap.find(m_compound_id);
		if (i != kChiAtomsMap.end() and nr < i->second.size())
		{
			std::vector<std::string> atoms{"N", "CA", "CB"};

			atoms.insert(atoms.end(), i->second.begin(), i->second.end());

			// in case we have a positive chiral volume we need to swap atoms
			if (chiral_volume() > 0)
			{
				if (m_compound_id == "LEU")
					atoms.back() = "CD2";
				if (m_compound_id == "VAL")
					atoms.back() = "CG2";
			}

			auto atom_0 = get_atom_by_atom_id(atoms[nr + 0]);
			auto atom_1 = get_atom_by_atom_id(atoms[nr + 1]);
			auto atom_2 = get_atom_by_atom_id(atoms[nr + 2]);
			auto atom_3 = get_atom_by_atom_id(atoms[nr + 3]);

			if (atom_0 and atom_1 and atom_2 and atom_3)
				result = static_cast<float>(dihedral_angle(
					atom_0.get_location(),
					atom_1.get_location(),
					atom_2.get_location(),
					atom_3.get_location()));
		}
	}
	catch (const std::exception &e)
	{
		if (VERBOSE > 0)
			std::cerr << e.what() << '\n';
		result = 0;
	}

	return result;
}

bool monomer::is_cis() const
{
	bool result = false;

	if (m_index + 1 < m_polymer->size())
	{
		auto &next = m_polymer->operator[](m_index + 1);

		result = monomer::is_cis(*this, next);
	}

	return result;
}

bool monomer::is_complete() const
{
	int seen = 0;
	for (auto &a : m_atoms)
	{
		if (a.get_label_atom_id() == "CA")
			seen |= 1;
		else if (a.get_label_atom_id() == "C")
			seen |= 2;
		else if (a.get_label_atom_id() == "N")
			seen |= 4;
		else if (a.get_label_atom_id() == "O")
			seen |= 8;
		// else if (a.get_label_atom_id() == "OXT")		seen |= 16;
	}
	return seen == 15;
}

bool monomer::has_alternate_backbone_atoms() const
{
	bool result = false;

	for (auto &a : m_atoms)
	{
		if (not a.is_alternate())
			continue;

		auto atom_id = a.get_label_atom_id();
		if (atom_id == "CA" or atom_id == "C" or atom_id == "N" or atom_id == "O")
		{
			result = true;
			break;
		}
	}

	return result;
}

float monomer::chiral_volume() const
{
	float result = 0;

	if (m_compound_id == "LEU")
	{
		auto centre = get_atom_by_atom_id("CG");
		auto atom1 = get_atom_by_atom_id("CB");
		auto atom2 = get_atom_by_atom_id("CD1");
		auto atom3 = get_atom_by_atom_id("CD2");

		result = dot_product(atom1.get_location() - centre.get_location(),
			cross_product(atom2.get_location() - centre.get_location(), atom3.get_location() - centre.get_location()));
	}
	else if (m_compound_id == "VAL")
	{
		auto centre = get_atom_by_atom_id("CB");
		auto atom1 = get_atom_by_atom_id("CA");
		auto atom2 = get_atom_by_atom_id("CG1");
		auto atom3 = get_atom_by_atom_id("CG2");

		result = dot_product(atom1.get_location() - centre.get_location(),
			cross_product(atom2.get_location() - centre.get_location(), atom3.get_location() - centre.get_location()));
	}

	return result;
}

bool monomer::are_bonded(const monomer &a, const monomer &b, float errorMargin)
{
	bool result = false;

	try
	{
		point atoms[4] = {
			a.get_atom_by_atom_id("CA").get_location(),
			a.get_atom_by_atom_id("C").get_location(),
			b.get_atom_by_atom_id("N").get_location(),
			b.get_atom_by_atom_id("CA").get_location()};

		auto distanceCACA = distance(atoms[0], atoms[3]);
		double omega = dihedral_angle(atoms[0], atoms[1], atoms[2], atoms[3]);

		bool cis = std::abs(omega) <= 30.0;
		float maxCACADistance = cis ? 3.0f : 3.8f;

		result = std::abs(distanceCACA - maxCACADistance) < errorMargin;
	}
	catch (...)
	{
	}

	return result;
}

float monomer::omega(const monomer &a, const monomer &b)
{
	float result = 360;

	auto a1 = a.get_atom_by_atom_id("CA");
	auto a2 = a.get_atom_by_atom_id("C");
	auto a3 = b.get_atom_by_atom_id("N");
	auto a4 = b.get_atom_by_atom_id("CA");

	if (a1 and a2 and a3 and a4)
		result = static_cast<float>(dihedral_angle(
			a1.get_location(),
			a2.get_location(),
			a3.get_location(),
			a4.get_location()));

	return result;
}

bool monomer::is_cis(const monomer &a, const monomer &b)
{
	return std::abs(omega(a, b)) < 30.0f;
}

// --------------------------------------------------------------------
// polymer

polymer::polymer(structure &s, const std::string &entityID, const std::string &asym_id, const std::string &auth_asym_id)
	: m_structure(const_cast<structure *>(&s))
	, m_entity_id(entityID)
	, m_asym_id(asym_id)
	, m_auth_asym_id(auth_asym_id)
{
	using namespace cif::literals;

	std::map<size_t, size_t> ix;

	auto &poly_seq_scheme = s.get_datablock()["pdbx_poly_seq_scheme"];
	reserve(poly_seq_scheme.size());

	for (auto r : poly_seq_scheme.find("asym_id"_key == asym_id))
	{
		int seqID;
		std::optional<int> pdbSeqNum;
		std::string compoundID, authSeqID, pdbInsCode;
		cif::tie(seqID, authSeqID, compoundID, pdbInsCode, pdbSeqNum) = r.get("seq_id", "auth_seq_num", "mon_id", "pdb_ins_code", "pdb_seq_num");

		if (authSeqID.empty() and pdbSeqNum.has_value())
			authSeqID = std::to_string(*pdbSeqNum);

		size_t index = size();

		// store only the first
		if (not ix.count(seqID))
		{
			ix[seqID] = index;
			emplace_back(*this, index, seqID, authSeqID, pdbInsCode, compoundID);
		}
		else if (VERBOSE > 0)
		{
			monomer m{*this, index, seqID, authSeqID, pdbInsCode, compoundID};
			std::cerr << "Dropping alternate residue " << m << '\n';
		}
	}
}

// std::string polymer::chainID() const
// {
// 	return mPolySeq.front()["pdb_strand_id"].as<std::string>();
// }

// monomer &polymer::getBySeqID(int seqID)
// {
// 	for (auto &m : *this)
// 		if (m.get_seq_id() == seqID)
// 			return m;

// 	throw std::runtime_error("monomer with seqID " + std::to_string(seqID) + " not found in polymer " + m_asym_id);
// }

// const monomer &polymer::getBySeqID(int seqID) const
// {
// 	for (auto &m : *this)
// 		if (m.get_seq_id() == seqID)
// 			return m;

// 	throw std::runtime_error("monomer with seqID " + std::to_string(seqID) + " not found in polymer " + m_asym_id);
// }

// int polymer::Distance(const monomer &a, const monomer &b) const
// {
// 	int result = std::numeric_limits<int>::max();

// 	if (a.get_asym_id() == b.get_asym_id())
// 	{
// 		int ixa = std::numeric_limits<int>::max(), ixb = std::numeric_limits<int>::max();

// 		int ix = 0, f = 0;
// 		for (auto &m : *this)
// 		{
// 			if (m.get_seq_id() == a.get_seq_id())
// 				ixa = ix, ++f;
// 			if (m.get_seq_id() == b.get_seq_id())
// 				ixb = ix, ++f;
// 			if (f == 2)
// 			{
// 				result = std::abs(ixa - ixb);
// 				break;
// 			}
// 		}
// 	}

// 	return result;
// }

// --------------------------------------------------------------------

sugar::sugar(branch &branch, const std::string &compoundID,
	const std::string &asym_id, int authSeqID)
	: residue(branch.get_structure(), compoundID, asym_id, 0, asym_id, std::to_string(authSeqID), "")
	, m_branch(&branch)
{
}

sugar::sugar(sugar &&rhs)
	: residue(std::forward<residue>(rhs))
	, m_branch(rhs.m_branch)
{

}

sugar &sugar::operator=(sugar &&rhs)
{
	if (this != &rhs)
	{
		residue::operator=(std::forward<residue>(rhs));
		m_branch = rhs.m_branch;
	}

	return *this;
}

// bool sugar::hasLinkedSugarAtLeavingO(int leavingO) const
// {
// 	return false;
// }

// sugar &sugar::operator[](int leavingO)
// {
// 	throw std::logic_error("not implemented");
// }

// const sugar &sugar::operator[](int leavingO) const
// {
// 	throw std::logic_error("not implemented");
// }

std::string sugar::name() const
{
	std::string result;

	if (m_compound_id == "MAN")
		result += "alpha-D-mannopyranose";
	else if (m_compound_id == "BMA")
		result += "beta-D-mannopyranose";
	else if (m_compound_id == "NAG")
		result += "2-acetamido-2-deoxy-beta-D-glucopyranose";
	else if (m_compound_id == "NDG")
		result += "2-acetamido-2-deoxy-alpha-D-glucopyranose";
	else if (m_compound_id == "FUC")
		result += "alpha-L-fucopyranose";
	else if (m_compound_id == "FUL")
		result += "beta-L-fucopyranose";
	else
	{
		auto compound = compound_factory::instance().create(m_compound_id);
		if (compound)
			result += compound->name();
		else
			result += m_compound_id;
	}

	return result;
}

cif::mm::atom sugar::add_atom(row_initializer atom_info)
{
	auto &db = m_structure->get_datablock();
	auto &atom_site = db["atom_site"];

	auto atom_id = atom_site.get_unique_id("");

	atom_info.set_value({"group_PDB", "HETATM"});
	atom_info.set_value({"id", atom_id});
	atom_info.set_value({"label_entity_id", m_branch->get_entity_id()});
	atom_info.set_value({"label_asym_id", m_branch->get_asym_id()});
	atom_info.set_value({"label_comp_id", m_compound_id});
	atom_info.set_value({"label_seq_id", "."});
	atom_info.set_value({"label_alt_id", "."});
	atom_info.set_value({"auth_asym_id", m_branch->get_asym_id()});
	atom_info.set_value({"auth_comp_id", m_compound_id});
	atom_info.set_value({"auth_seq_id", m_auth_seq_id});
	atom_info.set_value({"occupancy", 1.0, 2});
	atom_info.set_value({"B_iso_or_equiv", 30.0, 2});
	atom_info.set_value({"pdbx_PDB_model_num", 1});

	auto row = atom_site.emplace(std::move(atom_info));
	auto result = m_structure->emplace_atom(db, row);

	residue::add_atom(result);

	return result;
}

branch::branch(structure &structure, const std::string &asym_id, const std::string &entity_id)
	: m_structure(&structure)
	, m_asym_id(asym_id)
	, m_entity_id(entity_id)
{
	using namespace literals;

	auto &db = structure.get_datablock();
	auto &struct_asym = db["struct_asym"];
	auto &branch_scheme = db["pdbx_branch_scheme"];
	auto &branch_link = db["pdbx_entity_branch_link"];

	for (const auto &asym_entity_id : struct_asym.find<std::string>("id"_key == asym_id, "entity_id"))
	{
		for (const auto &[comp_id, num] : branch_scheme.find<std::string, int>(
				 "asym_id"_key == asym_id, "mon_id", "pdb_seq_num"))
		{
			emplace_back(*this, comp_id, asym_id, num);
		}

		for (const auto &[num1, num2, atom1, atom2] : branch_link.find<size_t, size_t, std::string, std::string>(
				 "entity_id"_key == asym_entity_id, "entity_branch_list_num_1", "entity_branch_list_num_2", "atom_id_1", "atom_id_2"))
		{
			// if (not iequals(atom1, "c1"))
			// 	throw std::runtime_error("invalid pdbx_entity_branch_link");

			auto &s1 = at(num1 - 1);
			auto &s2 = at(num2 - 1);

			s1.set_link(s2.get_atom_by_atom_id(atom2));
		}

		break;
	}
}

void branch::link_atoms()
{
	if (not empty())
	{
		using namespace literals;

		auto &db = m_structure->get_datablock();
		auto &branch_link = db["pdbx_entity_branch_link"];

		auto entity_id = front().get_entity_id();

		for (const auto &[num1, num2, atom1, atom2] : branch_link.find<size_t, size_t, std::string, std::string>(
				"entity_id"_key == entity_id, "entity_branch_list_num_1", "entity_branch_list_num_2", "atom_id_1", "atom_id_2"))
		{
			// if (not iequals(atom1, "c1"))
			// 	throw std::runtime_error("invalid pdbx_entity_branch_link");

			auto &s1 = at(num1 - 1);
			auto &s2 = at(num2 - 1);

			s1.set_link(s2.get_atom_by_atom_id(atom2));
		}
	}
}

sugar &branch::get_sugar_by_num(int nr)
{
	auto i = find_if(begin(), end(), [nr](const sugar &s) { return s.num() == nr; });
	if (i == end())
		throw std::out_of_range("Sugar with num " + std::to_string(nr) + " not found in branch " + m_asym_id);
	
	return *i;
}

std::string branch::name() const
{
	return empty() ? "" : name(front());
}

sugar &branch::construct_sugar(const std::string &compound_id)
{
	auto &db = m_structure->get_datablock();

	auto compound = compound_factory::instance().create(compound_id);
	if (compound == nullptr)
		throw std::runtime_error("Trying to insert unknown compound " + compound_id + " (not found in CCD)");

	auto &chemComp = db["chem_comp"];
	auto r = chemComp.find(key("id") == compound_id);
	if (r.empty())
	{
		chemComp.emplace({
			{"id", compound_id},
			{"name", compound->name()},
			{"formula", compound->formula()},
			{"formula_weight", compound->formula_weight()},
			{"type", compound->type()}});
	}

	sugar &result = emplace_back(*this, compound_id, m_asym_id, static_cast<int>(size() + 1));

	db["pdbx_branch_scheme"].emplace({
		{"asym_id", result.get_asym_id()},
		{"entity_id", result.get_entity_id()},
		{"num", result.num()},
		{"mon_id", result.get_compound_id()},

		{"pdb_asym_id", result.get_asym_id()},
		{"pdb_seq_num", result.num()},
		{"pdb_mon_id", result.get_compound_id()},

		{"auth_asym_id", result.get_auth_asym_id()},
		{"auth_mon_id", result.get_compound_id()},
		{"auth_seq_num", result.get_auth_seq_id()},

		{"hetero", "n"}
	});

	return result;
}

sugar &branch::construct_sugar(const std::string &compound_id, const std::string &atom_id,
	int linked_sugar_nr, const std::string &linked_atom_id)
{
	auto &result = construct_sugar(compound_id);

	auto &linked = get_sugar_by_num(linked_sugar_nr);
	result.set_link(linked.get_atom_by_atom_id(linked_atom_id));

	auto &db = m_structure->get_datablock();

	auto &pdbx_entity_branch_link = db["pdbx_entity_branch_link"];
	auto linkID = pdbx_entity_branch_link.get_unique_id("");

	db["pdbx_entity_branch_link"].emplace({
		{ "link_id", linkID },
		{ "entity_id", get_entity_id() },
		{ "entity_branch_list_num_1", result.num() }, 
		{ "comp_id_1", compound_id }, 
		{ "atom_id_1", atom_id },
		{ "leaving_atom_id_1", "O1" }, 	/// TODO: Need to fix this!
		{ "entity_branch_list_num_2", linked.num() }, 
		{ "comp_id_2", linked.get_compound_id() }, 
		{ "atom_id_2", linked_atom_id }, 
		{ "leaving_atom_id_2", "." }, 
		{ "value_order", "sing" }
	});

	return result;
}

std::string branch::name(const sugar &s) const
{
	using namespace literals;

	std::string result;

	for (auto &sn : *this)
	{
		if (not sn.get_link() or sn.get_link().get_auth_seq_id() != s.get_auth_seq_id())
			continue;

		auto n = name(sn) + "-(1-" + sn.get_link().get_label_atom_id().substr(1) + ')';

		result = result.empty() ? n : result + "-[" + n + ']';
	}

	if (not result.empty() and result.back() != ']')
		result += '-';

	return result + s.name();
}

float branch::weight() const
{
	return std::accumulate(begin(), end(), 0.f, [](float sum, const sugar &s)
		{
		auto compound = compound_factory::instance().create(s.get_compound_id());
		if (compound)
			sum += compound->formula_weight();
		return sum; });
}

// --------------------------------------------------------------------
//	structure

structure::structure(file &p, size_t modelNr, StructureOpenOptions options)
	: structure(p.front(), modelNr, options)
{
}

structure::structure(datablock &db, size_t modelNr, StructureOpenOptions options)
	: m_db(db)
	, m_model_nr(modelNr)
{
	auto &atomCat = db["atom_site"];

	load_atoms_for_model(options);

	// Check to see if we should actually load another model?
	if (m_atoms.empty() and m_model_nr == 1)
	{
		std::optional<size_t> model_nr;
		cif::tie(model_nr) = atomCat.front().get("pdbx_PDB_model_num");
		if (model_nr and *model_nr != m_model_nr)
		{
			if (VERBOSE > 0)
				std::cerr << "No atoms loaded for model 1, trying model " << *model_nr << '\n';
			m_model_nr = *model_nr;
			load_atoms_for_model(options);
		}
	}

	if (m_atoms.empty())
	{
		if (VERBOSE >= 0)
			std::cerr << "Warning: no atoms loaded\n";
	}
	else
		load_data();
}

void structure::load_atoms_for_model(StructureOpenOptions options)
{
	using namespace literals;

	auto &atomCat = m_db["atom_site"];

	condition c = "pdbx_PDB_model_num"_key == null or "pdbx_PDB_model_num"_key == m_model_nr;
	if (options bitand StructureOpenOptions::SkipHydrogen)
		c = std::move(c) and ("type_symbol"_key != "H" and "type_symbol"_key != "D");

	for (auto id : atomCat.find<std::string>(std::move(c), "id"))
		emplace_atom(std::make_shared<atom::atom_impl>(m_db, id));
}

// structure::structure(const structure &s)
// 	: m_db(s.m_db)
// 	, m_model_nr(s.m_model_nr)
// {
// 	m_atoms.reserve(s.m_atoms.size());
// 	for (auto &atom : s.m_atoms)
// 		emplace_atom(atom.clone());

// 	load_data();
// }

// structure::~structure()
// {
// }

void structure::load_data()
{
	auto &polySeqScheme = m_db["pdbx_poly_seq_scheme"];

	for (const auto &[asym_id, auth_asym_id, entityID] : polySeqScheme.rows<std::string,std::string,std::string>("asym_id", "pdb_strand_id", "entity_id"))
	{
		if (m_polymers.empty() or m_polymers.back().get_asym_id() != asym_id or m_polymers.back().get_entity_id() != entityID)
			m_polymers.emplace_back(*this, entityID, asym_id, auth_asym_id);
	}

	auto &branchScheme = m_db["pdbx_branch_scheme"];

	for (const auto &[asym_id, entity_id] : branchScheme.rows<std::string,std::string>("asym_id", "entity_id"))
	{
		if (m_branches.empty() or m_branches.back().get_asym_id() != asym_id)
			m_branches.emplace_back(*this, asym_id, entity_id);
	}

	auto &nonPolyScheme = m_db["pdbx_nonpoly_scheme"];

	for (const auto&[asym_id, monID, pdbStrandID, pdbSeqNum, pdbInsCode] :
			nonPolyScheme.rows<std::string,std::string,std::string,std::string,std::string>("asym_id", "mon_id", "pdb_strand_id", "pdb_seq_num", "pdb_ins_code"))
		m_non_polymers.emplace_back(*this, monID, asym_id, 0, pdbStrandID, pdbSeqNum, pdbInsCode);

	// place atoms in residues

	using key_type = std::tuple<std::string, int, std::string>;
	std::map<key_type, residue *> resMap;

	for (auto &poly : m_polymers)
	{
		for (auto &res : poly)
			resMap[{res.get_asym_id(), res.get_seq_id(), res.get_auth_seq_id()}] = &res;
	}

	for (auto &res : m_non_polymers)
		resMap[{res.get_asym_id(), res.get_seq_id(), res.get_auth_seq_id()}] = &res;

	std::set<std::string> sugars;
	for (auto &branch : m_branches)
	{
		for (auto &sugar : branch)
		{
			resMap[{sugar.get_asym_id(), sugar.get_seq_id(), sugar.get_auth_seq_id()}] = &sugar;
			sugars.insert(sugar.get_compound_id());
		}
	}

	for (auto &atom : m_atoms)
	{
		key_type k(atom.get_label_asym_id(), atom.get_label_seq_id(), atom.get_auth_seq_id());
		auto ri = resMap.find(k);

		if (ri == resMap.end())
		{
			if (VERBOSE > 0)
				std::cerr << "Missing residue for atom " << atom << '\n';

			// see if it might match a non poly
			for (auto &res : m_non_polymers)
			{
				if (res.get_asym_id() != atom.get_label_asym_id())
					continue;

				res.add_atom(atom);
				break;
			}

			continue;
		}

		ri->second->add_atom(atom);
	}

	// what the ...
	m_branches.erase(std::remove_if(m_branches.begin(), m_branches.end(), [](const branch &b) { return b.empty(); }), m_branches.end());

	for (auto &branch : m_branches)
		branch.link_atoms();
}

EntityType structure::get_entity_type_for_entity_id(const std::string entityID) const
{
	using namespace literals;

	auto &entity = m_db["entity"];
	auto entity_type = entity.find1<std::string>("id"_key == entityID, "type");

	EntityType result;

	if (iequals(entity_type, "polymer"))
		result = EntityType::Polymer;
	else if (iequals(entity_type, "non-polymer"))
		result = EntityType::NonPolymer;
	else if (iequals(entity_type, "macrolide"))
		result = EntityType::Macrolide;
	else if (iequals(entity_type, "water"))
		result = EntityType::Water;
	else if (iequals(entity_type, "branched"))
		result = EntityType::Branched;
	else
		throw std::runtime_error("Unknown entity type " + entity_type);

	return result;
}

EntityType structure::get_entity_type_for_asym_id(const std::string asym_id) const
{
	using namespace literals;

	auto &struct_asym = m_db["struct_asym"];
	auto entityID = struct_asym.find1<std::string>("id"_key == asym_id, "entity_id");

	return get_entity_type_for_entity_id(entityID);
}

// std::vector<atom> structure::waters() const
// {
// 	using namespace literals;

// 	std::vector<atom> result;

// 	auto &db = datablock();

// 	// Get the entity id for water. Watch out, structure may not have water at all
// 	auto &entityCat = db["entity"];
// 	for (const auto &[waterEntityID] : entityCat.find<std::string>("type"_key == "water", "id"))
// 	{
// 		for (auto &a : m_atoms)
// 		{
// 			if (a.get_property("label_entity_id") == waterEntityID)
// 				result.push_back(a);
// 		}

// 		break;
// 	}

// 	return result;
// }

bool structure::has_atom_id(const std::string &id) const
{
	assert(m_atoms.size() == m_atom_index.size());

	bool result = false;

	int L = 0, R = static_cast<int>(m_atoms.size() - 1);
	while (L <= R)
	{
		int i = (L + R) / 2;

		const atom &atom = m_atoms[m_atom_index[i]];

		int d = atom.id().compare(id);

		if (d == 0)
		{
			result = true;
			break;
		}

		if (d < 0)
			L = i + 1;
		else
			R = i - 1;
	}

	return result;
}

atom structure::get_atom_by_id(const std::string &id) const
{
	assert(m_atoms.size() == m_atom_index.size());

	int L = 0, R = static_cast<int>(m_atoms.size() - 1);
	while (L <= R)
	{
		int i = (L + R) / 2;

		const atom &atom = m_atoms[m_atom_index[i]];

		int d = atom.id().compare(id);

		if (d == 0)
			return atom;

		if (d < 0)
			L = i + 1;
		else
			R = i - 1;
	}

	throw std::out_of_range("Could not find atom with id " + id);
}

atom structure::get_atom_by_label(const std::string &atom_id, const std::string &asym_id, const std::string &compID, int seqID, const std::string &altID)
{
	for (auto &a : m_atoms)
	{
		if (a.get_label_atom_id() == atom_id and
			a.get_label_asym_id() == asym_id and
			a.get_label_comp_id() == compID and
			a.get_label_seq_id() == seqID and
			a.get_label_alt_id() == altID)
		{
			return a;
		}
	}

	throw std::out_of_range("Could not find atom with specified label");
}

atom structure::get_atom_by_position(point p) const
{
	double dist = std::numeric_limits<double>::max();
	size_t index = std::numeric_limits<size_t>::max();

	for (size_t i = 0; i < m_atoms.size(); ++i)
	{
		auto &a = m_atoms.at(i);

		auto d = distance(a.get_location(), p);
		if (d < dist)
		{
			dist = d;
			index = i;
		}
	}

	if (index < m_atoms.size())
		return m_atoms.at(index);

	return {};
}

atom structure::get_atom_by_position_and_type(point p, std::string_view type, std::string_view res_type) const
{
	double dist = std::numeric_limits<double>::max();
	size_t index = std::numeric_limits<size_t>::max();

	for (size_t i = 0; i < m_atoms.size(); ++i)
	{
		auto &a = m_atoms.at(i);

		if (a.get_label_comp_id() != res_type)
			continue;

		if (a.get_label_atom_id() != type)
			continue;

		auto d = distance(a.get_location(), p);
		if (dist > d)
		{
			dist = d;
			index = i;
		}
	}

	if (index < m_atoms.size())
		return m_atoms.at(index);

	return {};
}

polymer &structure::get_polymer_by_asym_id(const std::string &asym_id)
{
	for (auto &poly : m_polymers)
	{
		if (poly.get_asym_id() != asym_id)
			continue;

		return poly;
	}

	throw std::runtime_error("polymer with asym id " + asym_id + " not found");
}

residue &structure::create_residue(const std::vector<atom> &atoms)
{
	return m_non_polymers.emplace_back(*this, atoms);
}

residue &structure::get_residue(const std::string &asym_id, int seqID, const std::string &authSeqID)
{
	if (seqID == 0)
	{
		for (auto &res : m_non_polymers)
		{
			if (res.get_asym_id() == asym_id and (authSeqID.empty() or res.get_auth_seq_id() == authSeqID))
				return res;
		}
	}

	for (auto &poly : m_polymers)
	{
		if (poly.get_asym_id() != asym_id)
			continue;

		for (auto &res : poly)
		{
			if (res.get_seq_id() == seqID)
				return res;
		}
	}

	for (auto &branch : m_branches)
	{
		if (branch.get_asym_id() != asym_id)
			continue;

		for (auto &sugar : branch)
		{
			if (sugar.get_asym_id() == asym_id and sugar.get_auth_seq_id() == authSeqID)
				return sugar;
		}
	}

	std::string desc = asym_id;

	if (seqID != 0)
		desc += "/" + std::to_string(seqID);
	
	if (not authSeqID.empty())
		desc += "-" + authSeqID;

	throw std::out_of_range("Could not find residue " + desc);
}

residue &structure::get_residue(const std::string &asym_id, const std::string &compID, int seqID, const std::string &authSeqID)
{
	if (seqID == 0)
	{
		for (auto &res : m_non_polymers)
		{
			if (res.get_asym_id() == asym_id and res.get_auth_seq_id() == authSeqID and res.get_compound_id() == compID)
				return res;
		}
	}

	for (auto &poly : m_polymers)
	{
		if (poly.get_asym_id() != asym_id)
			continue;

		for (auto &res : poly)
		{
			if (res.get_seq_id() == seqID and res.get_compound_id() == compID)
				return res;
		}
	}

	for (auto &branch : m_branches)
	{
		if (branch.get_asym_id() != asym_id)
			continue;

		for (auto &sugar : branch)
		{
			if (sugar.get_asym_id() == asym_id and sugar.get_auth_seq_id() == authSeqID and sugar.get_compound_id() == compID)
				return sugar;
		}
	}

	std::string desc = asym_id;

	if (seqID != 0)
		desc += "/" + std::to_string(seqID);
	
	if (not authSeqID.empty())
		desc += "-" + authSeqID;

	throw std::out_of_range("Could not find residue " + desc + " of type " + compID);
}

branch &structure::get_branch_by_asym_id(const std::string &asym_id)
{
	for (auto &branch : m_branches)
	{
		if (branch.get_asym_id() == asym_id)
			return branch;
	}

	throw std::runtime_error("branch not found for asym id " + asym_id);
}

std::string structure::insert_compound(const std::string &compoundID, bool is_entity)
{
	using namespace literals;

	auto compound = compound_factory::instance().create(compoundID);
	if (compound == nullptr)
		throw std::runtime_error("Trying to insert unknown compound " + compoundID + " (not found in CCD)");

	auto &chemComp = m_db["chem_comp"];
	auto r = chemComp.find(key("id") == compoundID);
	if (r.empty())
	{
		chemComp.emplace({
			{"id", compoundID},
			{"name", compound->name()},
			{"formula", compound->formula()},
			{"formula_weight", compound->formula_weight()},
			{"type", compound->type()}});
	}

	std::string entity_id;

	if (is_entity)
	{
		auto &pdbxEntityNonpoly = m_db["pdbx_entity_nonpoly"];

		entity_id = pdbxEntityNonpoly.find_first<std::string>("comp_id"_key == compoundID, "entity_id");

		if (entity_id.empty())
		{
			auto &entity = m_db["entity"];
			entity_id = entity.get_unique_id("");

			entity.emplace({
				{"id", entity_id},
				{"type", "non-polymer"},
				{"pdbx_description", compound->name()},
				{"formula_weight", compound->formula_weight()}});

			pdbxEntityNonpoly.emplace({
				{"entity_id", entity_id},
				{"name", compound->name()},
				{"comp_id", compoundID}});
		}
	}

	return entity_id;
}

// --------------------------------------------------------------------

atom &structure::emplace_atom(atom &&atom)
{
	int L = 0, R = static_cast<int>(m_atom_index.size() - 1);
	while (L <= R)
	{
		int i = (L + R) / 2;

		auto &ai = m_atoms[m_atom_index[i]];

		int d = ai.id().compare(atom.id());

		if (d == 0)
			throw std::runtime_error("Duplicate atom ID " + atom.id());

		if (d < 0)
			L = i + 1;
		else
			R = i - 1;
	}

	if (R == -1)	// msvc... 
		m_atom_index.insert(m_atom_index.begin(), m_atoms.size());
	else
		m_atom_index.insert(m_atom_index.begin() + R + 1, m_atoms.size());

	// make sure the atom_type is known
	auto &atom_type = m_db["atom_type"];
	std::string symbol = atom.get_property("type_symbol");

	using namespace cif::literals;
	if (not atom_type.contains("symbol"_key == symbol))
		atom_type.emplace({ { "symbol", symbol } });

	return m_atoms.emplace_back(std::move(atom));
}

void structure::remove_atom(atom &a, bool removeFromResidue)
{
	using namespace literals;

	auto &atomSite = m_db["atom_site"];

	if (a.is_water())
	{
		auto ra = atomSite.find1("id"_key == a.id());
		if (ra)
		{
			auto &nps = m_db["pdbx_nonpoly_scheme"];
			for (auto rnp : atomSite.get_children(ra, nps))
				nps.erase(rnp);
		}
	}
	else if (removeFromResidue)
	{
		try
		{
			auto &res = get_residue(a);
			res.m_atoms.erase(std::remove(res.m_atoms.begin(), res.m_atoms.end(), a), res.m_atoms.end());
		}
		catch (const std::exception &ex)
		{
			if (VERBOSE > 0)
				std::cerr << "Error removing atom from residue: " << ex.what() << '\n';
		}
	}

	for (auto ri : atomSite.find("id"_key == a.id()))
	{
		// also remove struct_conn records for this atom
		auto &structConn = m_db["struct_conn"];

		condition cond;

		for (std::string prefix : { "ptnr1_", "ptnr2_", "pdbx_ptnr3_" })
		{
			if (a.get_label_seq_id() == 0)
				cond = std::move(cond) or (
					cif::key(prefix + "label_asym_id") == a.get_label_asym_id() and
					cif::key(prefix + "label_seq_id") == null and
					cif::key(prefix + "auth_seq_id") == a.get_auth_seq_id() and
					cif::key(prefix + "label_atom_id") == a.get_label_atom_id()
				);
			else
				cond = std::move(cond) or (
					cif::key(prefix + "label_asym_id") == a.get_label_asym_id() and
					cif::key(prefix + "label_seq_id") == a.get_label_seq_id() and
					cif::key(prefix + "auth_seq_id") == a.get_auth_seq_id() and
					cif::key(prefix + "label_atom_id") == a.get_label_atom_id()
				);
		}

		if (cond)
			structConn.erase(std::move(cond));

		atomSite.erase(ri);
		break;
	}

	assert(m_atom_index.size() == m_atoms.size());

#ifndef NDEBUG
	bool removed = false;
#endif

	int L = 0, R = static_cast<int>(m_atom_index.size() - 1);
	while (L <= R)
	{
		int i = (L + R) / 2;

		const atom &atom = m_atoms[m_atom_index[i]];

		int d = atom.id().compare(a.id());

		if (d == 0)
		{
			m_atoms.erase(m_atoms.begin() + m_atom_index[i]);

			auto ai = m_atom_index[i];
			m_atom_index.erase(m_atom_index.begin() + i);

			for (auto &j : m_atom_index)
			{
				if (j > ai)
					--j;
			}
#ifndef NDEBUG
			removed = true;
#endif
			break;
		}

		if (d < 0)
			L = i + 1;
		else
			R = i - 1;
	}
#ifndef NDEBUG
	assert(removed);
#endif
}

void structure::swap_atoms(atom a1, atom a2)
{
	auto &atomSites = m_db["atom_site"];

	try
	{
		auto r1 = atomSites.find1(key("id") == a1.id());
		auto r2 = atomSites.find1(key("id") == a2.id());

		auto l1 = r1["label_atom_id"];
		auto l2 = r2["label_atom_id"];
		l1.swap(l2);

		auto l3 = r1["auth_atom_id"];
		auto l4 = r2["auth_atom_id"];
		l3.swap(l4);
	}
	catch (const std::exception &ex)
	{
		std::throw_with_nested(std::runtime_error("Failed to swap atoms"));
	}
}

void structure::move_atom(atom a, point p)
{
	a.set_location(p);
}

void structure::change_residue(residue &res, const std::string &newCompound,
	const std::vector<std::tuple<std::string, std::string>> &remappedAtoms)
{
	using namespace literals;

	std::string asym_id = res.get_asym_id();

	const auto compound = compound_factory::instance().create(newCompound);
	if (not compound)
		throw std::runtime_error("Unknown compound " + newCompound);

	// First make sure the compound is already known or insert it.
	// And if the residue is an entity, we must make sure it exists

	std::string entityID;
	if (res.is_entity())
	{
		// create a copy of the entity first
		auto &entity = m_db["entity"];

		entityID = entity.find_first<std::string>("type"_key == "non-polymer" and "pdbx_description"_key == compound->name(), "id");

		if (entityID.empty())
		{
			entityID = entity.get_unique_id("");
			entity.emplace({{"id", entityID},
				{"type", "non-polymer"},
				{"pdbx_description", compound->name()},
				{"formula_weight", compound->formula_weight()}});

			auto &pdbxEntityNonpoly = m_db["pdbx_entity_nonpoly"];
			pdbxEntityNonpoly.emplace({{"entity_id", entityID},
				{"name", compound->name()},
				{"comp_id", newCompound}});
		}

		auto &pdbxNonPolyScheme = m_db["pdbx_nonpoly_scheme"];
		for (auto nps : pdbxNonPolyScheme.find("asym_id"_key == asym_id))
		{
			nps.assign("mon_id", newCompound, true);
			nps.assign("pdb_mon_id", newCompound, true);
			nps.assign("auth_mon_id", newCompound, true);
			nps.assign("entity_id", entityID, true);
		}

		// create rest
		auto &chemComp = m_db["chem_comp"];
		if (not chemComp.contains(key("id") == newCompound))
		{
			chemComp.emplace({{"id", newCompound},
				{"name", compound->name()},
				{"formula", compound->formula()},
				{"formula_weight", compound->formula_weight()},
				{"type", compound->type()}});
		}

		// update the struct_asym for the new entity
		m_db["struct_asym"].update_value("id"_key == asym_id, "entity_id", entityID);
	}
	else
		insert_compound(newCompound, false);

	res.set_compound_id(newCompound);

	auto &atomSites = m_db["atom_site"];
	auto atoms = res.atoms();

	for (const auto &[a1, a2] : remappedAtoms)
	{
		auto i = find_if(atoms.begin(), atoms.end(), [id = a1](const atom &a)
			{ return a.get_label_atom_id() == id; });
		if (i == atoms.end())
		{
			if (VERBOSE >= 0)
				std::cerr << "Missing atom for atom ID " << a1 << '\n';
			continue;
		}

		auto r = atomSites.find(key("id") == i->id());

		if (r.size() != 1)
			continue;

		if (a2.empty() or a2 == ".")
		{
			i->set_property("label_comp_id", newCompound);
			remove_atom(*i);
		}
		else if (a1 != a2)
		{
			auto ra = r.front();
			ra["label_atom_id"] = a2;
			ra["auth_atom_id"] = a2;
			ra["type_symbol"] = atom_type_traits(compound->get_atom_by_atom_id(a2).type_symbol).symbol();
		}
	}

	for (auto a : atoms)
	{
		atomSites.update_value(key("id") == a.id(), "label_comp_id", newCompound);
		atomSites.update_value(key("id") == a.id(), "auth_comp_id", newCompound);
	}
}

void structure::remove_residue(const std::string &asym_id, int seq_id, const std::string &auth_seq_id)
{
	if (seq_id == 0)
	{
		for (auto &res : m_non_polymers)
		{
			if (res.get_asym_id() == asym_id and (auth_seq_id.empty() or res.get_auth_seq_id() == auth_seq_id))
			{
				remove_residue(res);
				return;
			}
		}
	}

	for (auto &poly : m_polymers)
	{
		if (poly.get_asym_id() != asym_id)
			continue;

		for (auto &res : poly)
		{
			if (res.get_seq_id() == seq_id)
			{
				remove_residue(res);
				return;
			}
		}
	}

	for (auto &branch : m_branches)
	{
		if (branch.get_asym_id() != asym_id)
			continue;

		for (auto &sugar : branch)
		{
			if (sugar.get_asym_id() == asym_id and sugar.get_auth_seq_id() == auth_seq_id)
			{
				remove_residue(sugar);
				return;
			}
		}
	}
}

void structure::remove_residue(residue &res)
{
	using namespace literals;

	auto atoms = res.atoms();

	switch (res.entity_type())
	{
		case EntityType::Polymer:
		{
			auto &m = dynamic_cast<monomer &>(res);

			m_db["pdbx_poly_seq_scheme"].erase(
				"asym_id"_key == res.get_asym_id() and
				"seq_id"_key == res.get_seq_id());

			for (auto &poly : m_polymers)
				poly.erase(std::remove(poly.begin(), poly.end(), m), poly.end());
			break;
		}

		case EntityType::NonPolymer:
			m_db["pdbx_nonpoly_scheme"].erase("asym_id"_key == res.get_asym_id());
			m_db["struct_asym"].erase("id"_key == res.get_asym_id());
			m_non_polymers.erase(std::remove(m_non_polymers.begin(), m_non_polymers.end(), res), m_non_polymers.end());
			break;

		case EntityType::Water:
			m_db["pdbx_nonpoly_scheme"].erase("asym_id"_key == res.get_asym_id());
			m_non_polymers.erase(std::remove(m_non_polymers.begin(), m_non_polymers.end(), res), m_non_polymers.end());
			break;

		case EntityType::Branched:
		{
			auto &s = dynamic_cast<sugar&>(res);

			remove_sugar(s);

			atoms.clear();
			break;
		}

		case EntityType::Macrolide:
			// TODO: Fix this?
			throw std::runtime_error("no support for macrolides yet");
	}

	for (auto atom : atoms)
		remove_atom(atom, false);
}

void structure::remove_sugar(sugar &s)
{
	using namespace literals;

	std::string asym_id = s.get_asym_id();
	branch &branch = get_branch_by_asym_id(asym_id);
	auto si = std::find(branch.begin(), branch.end(), s);
	if (si == branch.end())
		throw std::runtime_error("sugar not part of branch");
	size_t six = si - branch.begin();

	if (six == 0)	// first sugar, means the death of this branch
		remove_branch(branch);
	else
	{
		std::set<size_t> dix;
		std::stack<size_t> test;
		test.push(s.num());

		while (not test.empty())
		{
			auto tix = test.top();
			test.pop();

			if (dix.count(tix))
				continue;
			
			dix.insert(tix);

			for (auto &s2 : branch)
			{
				if (s2.get_link_nr() == tix)
					test.push(s2.num());
			}

			for (auto atom : branch[tix - 1].atoms())
				remove_atom(atom, false);
		}

		branch.erase(remove_if(branch.begin(), branch.end(), [dix](const sugar &s) { return dix.count(s.num()); }), branch.end());

		auto entity_id = create_entity_for_branch(branch);

		// Update the entity id of the asym
		auto &struct_asym = m_db["struct_asym"];
		auto r = struct_asym.find1("id"_key == asym_id);
		r["entity_id"] = entity_id;

		for (auto &sugar : branch)
		{
			for (auto atom : sugar.atoms())
				atom.set_property("label_entity_id", entity_id);
		}

		auto &pdbx_branch_scheme = m_db["pdbx_branch_scheme"];
		pdbx_branch_scheme.erase("asym_id"_key == asym_id);

		for (auto &sugar : branch)
		{
			pdbx_branch_scheme.emplace({
				{"asym_id", asym_id},
				{"entity_id", entity_id},
				{"num", sugar.num()},
				{"mon_id", sugar.get_compound_id()},

				{"pdb_asym_id", asym_id},
				{"pdb_seq_num", sugar.num()},
				{"pdb_mon_id", sugar.get_compound_id()},

				// TODO: need fix, collect from nag_atoms?
				{"auth_asym_id", asym_id},
				{"auth_mon_id", sugar.get_compound_id()},
				{"auth_seq_num", sugar.get_auth_seq_id()},

				{"hetero", "n"}
			});
		}
	}
}

void structure::remove_branch(branch &branch)
{
	using namespace literals;

	for (auto &sugar : branch)
	{
		auto atoms = sugar.atoms();
		for (auto atom : atoms)
			remove_atom(atom);
	}

	m_db["pdbx_branch_scheme"].erase("asym_id"_key == branch.get_asym_id());
	m_db["struct_asym"].erase("id"_key == branch.get_asym_id());
	m_db["struct_conn"].erase("ptnr1_label_asym_id"_key == branch.get_asym_id() or "ptnr2_label_asym_id"_key == branch.get_asym_id());

	m_branches.erase(remove(m_branches.begin(), m_branches.end(), branch), m_branches.end());
}

std::string structure::create_non_poly_entity(const std::string &comp_id)
{
	return insert_compound(comp_id, true);
}

std::string structure::create_non_poly(const std::string &entity_id, const std::vector<atom> &atoms)
{
	using namespace cif::literals;

	auto &struct_asym = m_db["struct_asym"];
	std::string asym_id = struct_asym.get_unique_id();

	struct_asym.emplace({
		{"id", asym_id},
		{"pdbx_blank_PDB_chainid_flag", "N"},
		{"pdbx_modified", "N"},
		{"entity_id", entity_id},
		{"details", "?"}
	});

	std::string comp_id = m_db["pdbx_entity_nonpoly"].find1<std::string>("entity_id"_key == entity_id, "comp_id");

	auto &atom_site = m_db["atom_site"];

	auto &res = m_non_polymers.emplace_back(*this, comp_id, asym_id, 0, asym_id, "1", "");

	for (auto &atom : atoms)
	{
		auto atom_id = atom_site.get_unique_id("");

		auto row = atom_site.emplace({
			{"group_PDB", atom.get_property("group_PDB")},
			{"id", atom_id},
			{"type_symbol", atom.get_property("type_symbol")},
			{"label_atom_id", atom.get_property("label_atom_id")},
			{"label_alt_id", atom.get_property("label_alt_id")},
			{"label_comp_id", comp_id},
			{"label_asym_id", asym_id},
			{"label_entity_id", entity_id},
			{"label_seq_id", "."},
			{"pdbx_PDB_ins_code", ""},
			{"Cartn_x", atom.get_property("Cartn_x")},
			{"Cartn_y", atom.get_property("Cartn_y")},
			{"Cartn_z", atom.get_property("Cartn_z")},
			{"occupancy", atom.get_property("occupancy")},
			{"B_iso_or_equiv", atom.get_property("B_iso_or_equiv")},
			{"pdbx_formal_charge", atom.get_property("pdbx_formal_charge")},
			{"auth_seq_id", 1},
			{"auth_comp_id", comp_id},
			{"auth_asym_id", asym_id},
			{"auth_atom_id", atom.get_property("label_atom_id")},
			{"pdbx_PDB_model_num", 1}
		});

		auto &newAtom = emplace_atom(std::make_shared<atom::atom_impl>(m_db, atom_id));
		res.add_atom(newAtom);
	}

	auto &pdbx_nonpoly_scheme = m_db["pdbx_nonpoly_scheme"];
	size_t ndb_nr = pdbx_nonpoly_scheme.find("asym_id"_key == asym_id and "entity_id"_key == entity_id).size() + 1;
	pdbx_nonpoly_scheme.emplace({
		{"asym_id", asym_id},
		{"entity_id", entity_id},
		{"mon_id", comp_id},
		{"ndb_seq_num", ndb_nr},
		{"pdb_seq_num", res.get_auth_seq_id()},
		{"auth_seq_num", res.get_auth_seq_id()},
		{"pdb_mon_id", comp_id},
		{"auth_mon_id", comp_id},
		{"pdb_strand_id", asym_id},
		{"pdb_ins_code", "."},
	});

	return asym_id;
}

std::string structure::create_non_poly(const std::string &entity_id, std::vector<row_initializer> atoms)
{
	using namespace literals;

	auto &struct_asym = m_db["struct_asym"];
	std::string asym_id = struct_asym.get_unique_id();

	struct_asym.emplace({
		{"id", asym_id},
		{"pdbx_blank_PDB_chainid_flag", "N"},
		{"pdbx_modified", "N"},
		{"entity_id", entity_id},
		{"details", "?"}
	});

	std::string comp_id = m_db["pdbx_entity_nonpoly"].find1<std::string>("entity_id"_key == entity_id, "comp_id");

	auto &atom_site = m_db["atom_site"];

	auto &res = m_non_polymers.emplace_back(*this, comp_id, asym_id, 0, asym_id, "1", "");

	for (auto &atom : atoms)
	{
		auto atom_id = atom_site.get_unique_id("");

		atom.set_value("id", atom_id);
		atom.set_value("label_asym_id", asym_id);
		atom.set_value("auth_asym_id", asym_id);
		atom.set_value("label_entity_id", entity_id);

		atom.set_value_if_empty({"group_PDB", "HETATM"});
		atom.set_value_if_empty({"label_comp_id", comp_id});
		atom.set_value_if_empty({"label_seq_id", "."});
		atom.set_value_if_empty({"auth_comp_id", comp_id});
		atom.set_value_if_empty({"auth_seq_id", 1});
		atom.set_value_if_empty({"pdbx_PDB_model_num", 1});
		atom.set_value_if_empty({"label_alt_id", ""});
		atom.set_value_if_empty({"occupancy", 1.0, 2});

		auto row = atom_site.emplace(atom.begin(), atom.end());

		auto &newAtom = emplace_atom(std::make_shared<atom::atom_impl>(m_db, atom_id));
		res.add_atom(newAtom);
	}

	auto &pdbx_nonpoly_scheme = m_db["pdbx_nonpoly_scheme"];
	size_t ndb_nr = pdbx_nonpoly_scheme.find("asym_id"_key == asym_id and "entity_id"_key == entity_id).size() + 1;
	pdbx_nonpoly_scheme.emplace({
		{"asym_id", asym_id},
		{"entity_id", entity_id},
		{"mon_id", comp_id},
		{"ndb_seq_num", ndb_nr},
		{"pdb_seq_num", res.get_auth_seq_id()},
		{"auth_seq_num", res.get_auth_seq_id()},
		{"pdb_mon_id", comp_id},
		{"auth_mon_id", comp_id},
		{"pdb_strand_id", asym_id},
		{"pdb_ins_code", "."},
	});

	return asym_id;
}

void structure::create_water(row_initializer atom)
{
	using namespace literals;

	auto entity_id = insert_compound("HOH", true);

	auto &struct_asym = m_db["struct_asym"];
	std::string asym_id;
	try
	{
		asym_id = struct_asym.find1<std::string>("entity_id"_key == entity_id, "id");
	}
	catch (const std::exception &)
	{
		asym_id = struct_asym.get_unique_id();

		struct_asym.emplace({
			{"id", asym_id},
			{"pdbx_blank_PDB_chainid_flag", "N"},
			{"pdbx_modified", "N"},
			{"entity_id", entity_id},
			{"details", "?"}
		});
	}
	
	auto &atom_site = m_db["atom_site"];
	auto auth_seq_id = atom_site.find_max<int>("auth_seq_id", "label_entity_id"_key == entity_id) + 1;
	if (auth_seq_id < 0)
		auth_seq_id = 1;

	auto atom_id = atom_site.get_unique_id("");

	atom.set_value("id", atom_id);
	atom.set_value("label_asym_id", asym_id);
	atom.set_value("auth_asym_id", asym_id);
	atom.set_value("label_entity_id", entity_id);
	atom.set_value("auth_seq_id", std::to_string(auth_seq_id));

	atom.set_value_if_empty({"group_PDB", "HETATM"});
	atom.set_value_if_empty({"label_comp_id", "HOH"});
	atom.set_value_if_empty({"label_seq_id", "."});
	atom.set_value_if_empty({"auth_comp_id", "HOH"});
	atom.set_value_if_empty({"pdbx_PDB_model_num", 1});
	atom.set_value_if_empty({"label_alt_id", ""});
	atom.set_value_if_empty({"occupancy", 1.0, 2});

	auto row = atom_site.emplace(atom.begin(), atom.end());

	emplace_atom(std::make_shared<atom::atom_impl>(m_db, atom_id));

	auto &pdbx_nonpoly_scheme = m_db["pdbx_nonpoly_scheme"];
	int ndb_nr = pdbx_nonpoly_scheme.find_max<int>("ndb_seq_num") + 1;
	pdbx_nonpoly_scheme.emplace({
		{"asym_id", asym_id},
		{"entity_id", entity_id},
		{"mon_id", "HOH"},
		{"ndb_seq_num", ndb_nr},
		{"pdb_seq_num", auth_seq_id},
		{"auth_seq_num", auth_seq_id},
		{"pdb_mon_id", "HOH"},
		{"auth_mon_id", "HOH"},
		{"pdb_strand_id", asym_id},
		{"pdb_ins_code", "."},
	});
}

branch &structure::create_branch()
{
	auto &entity = m_db["entity"];
	auto &struct_asym = m_db["struct_asym"];

	auto entity_id = entity.get_unique_id("");
	auto asym_id = struct_asym.get_unique_id();

	entity.emplace({
		{"id", entity_id},
		{"type", "branched"}
	});

	struct_asym.emplace({
		{"id", asym_id},
		{"pdbx_blank_PDB_chainid_flag", "N"},
		{"pdbx_modified", "N"},
		{"entity_id", entity_id},
		{"details", "?"}
	});

	return m_branches.emplace_back(*this, asym_id, entity_id);
}

// branch &structure::create_branch(std::vector<row_initializer> atoms)
// {
// // 	// sanity check
// // 	for (auto &nag_atom : atoms)
// // 	{
// // 		for (const auto &[name, value] : nag_atom)
// // 		{
// // 			if (name == "label_comp_id" and value != "NAG")
// // 				throw std::logic_error("The first sugar in a branch should be a NAG");
// // 		}
// // 	}

// // 	using namespace literals;

// // 	auto &branch = create_branch();
// // 	auto asym_id = branch.get_asym_id();
// // 	auto entity_id = branch.get_entity_id();

// // 	auto &sugar = branch.emplace_back(branch, "NAG", asym_id, 1);

// // 	auto &atom_site = m_db["atom_site"];

// // 	for (auto &atom : atoms)
// // 	{
// // 		auto atom_id = atom_site.get_unique_id("");

// // 		atom.set_value("id", atom_id);
// // 		atom.set_value("label_asym_id", asym_id);
// // 		atom.set_value("auth_asym_id", asym_id);
// // 		atom.set_value("label_entity_id", entity_id);
// // 		atom.set_value({ "auth_seq_id", 1 });

// // 		atom.set_value_if_empty({"group_PDB", "HETATM"});
// // 		atom.set_value_if_empty({"label_comp_id", "NAG"});
// // 		atom.set_value_if_empty({"label_seq_id", "."});
// // 		atom.set_value_if_empty({"auth_comp_id", "NAG"});
// // 		atom.set_value_if_empty({"pdbx_PDB_model_num", 1});
// // 		atom.set_value_if_empty({"label_alt_id", ""});

// // 		auto row = atom_site.emplace(atom.begin(), atom.end());

// // 		auto &newAtom = emplace_atom(std::make_shared<atom::atom_impl>(m_db, atom_id));
// // 		sugar.add_atom(newAtom);
// // 	}

// // 	// // now we can create the entity and get the real ID
// // 	// auto entity_id = create_entity_for_branch(branch);
// // 	// assert(not entity_id.empty());

// // 	for (auto &a : sugar.atoms())
// // 		a.set_property("label_entity_id", entity_id);

// // 	m_db["pdbx_branch_scheme"].emplace({
// // 		{"asym_id", asym_id},
// // 		{"entity_id", entity_id},
// // 		{"num", 1},
// // 		{"mon_id", "NAG"},

// // 		{"pdb_asym_id", asym_id},
// // 		{"pdb_seq_num", 1},
// // 		{"pdb_mon_id", "NAG"},

// // 		// TODO: need fix, collect from nag_atoms?
// // 		{"auth_asym_id", asym_id},
// // 		{"auth_mon_id", "NAG"},
// // 		{"auth_seq_num", 1},

// // 		{"hetero", "n"}
// // 	});

// // 	return branch;
// }

// branch &structure::extend_branch(const std::string &asym_id, std::vector<row_initializer> atom_info,
// 	int link_sugar, const std::string &link_atom)
// {
// // 	// sanity check
// // 	std::string compoundID;

// // 	for (auto &atom : atom_info)
// // 	{
// // 		for (const auto &[name, value] : atom)
// // 		{
// // 			if (name != "label_comp_id")
// // 				continue;

// // 			if (compoundID.empty())
// // 				compoundID = value;
// // 			else if (value != compoundID)
// // 				throw std::logic_error("All atoms should be of the same type");
// // 		}
// // 	}

// // 	using namespace literals;

// // 	// auto &branch = m_branches.emplace_back(*this, asym_id);
// // 	auto tmp_entity_id = m_db["entity"].get_unique_id("");

// // 	auto &atom_site = m_db["atom_site"];

// // 	auto bi = std::find_if(m_branches.begin(), m_branches.end(), [asym_id](branch &b)
// // 		{ return b.get_asym_id() == asym_id; });
// // 	if (bi == m_branches.end())
// // 		throw std::logic_error("Create a branch first!");

// // 	branch &branch = *bi;

// // 	int sugarNum = static_cast<int>(branch.size() + 1);

// // 	auto &sugar = branch.emplace_back(branch, compoundID, asym_id, sugarNum);

// // 	for (auto &atom : atom_info)
// // 	{
// // 		auto atom_id = atom_site.get_unique_id("");

// // 		atom.set_value("id", atom_id);
// // 		atom.set_value("label_asym_id", asym_id);
// // 		atom.set_value("auth_asym_id", asym_id);
// // 		atom.set_value("label_entity_id", tmp_entity_id);
// // 		atom.set_value({"auth_seq_id", sugarNum });

// // 		atom.set_value_if_empty({"group_PDB", "HETATM"});
// // 		atom.set_value_if_empty({"label_comp_id", compoundID});
// // 		atom.set_value_if_empty({"auth_comp_id", compoundID});
// // 		atom.set_value_if_empty({"pdbx_PDB_model_num", 1});
// // 		atom.set_value_if_empty({"label_alt_id", ""});

// // 		auto row = atom_site.emplace(atom.begin(), atom.end());

// // 		auto &newAtom = emplace_atom(std::make_shared<atom::atom_impl>(m_db, atom_id));
// // 		sugar.add_atom(newAtom);
// // 	}

// // 	sugar.set_link(branch.at(link_sugar - 1).get_atom_by_atom_id(link_atom));

// // 	auto entity_id = create_entity_for_branch(branch);

// // 	// Update the entity id of the asym
// // 	auto &struct_asym = m_db["struct_asym"];
// // 	auto r = struct_asym.find1("id"_key == asym_id);
// // 	r["entity_id"] = entity_id;

// // 	for (auto &s2 : branch)
// // 	{
// // 		for (auto atom : s2.atoms())
// // 			atom.set_property("label_entity_id", entity_id);
// // 	}

// // 	auto &pdbx_branch_scheme = m_db["pdbx_branch_scheme"];
// // 	pdbx_branch_scheme.erase("asym_id"_key == asym_id);

// // 	for (auto &s2 : branch)
// // 	{
// // 		pdbx_branch_scheme.emplace({
// // 			{"asym_id", asym_id},
// // 			{"entity_id", entity_id},
// // 			{"num", s2.num()},
// // 			{"mon_id", s2.get_compound_id()},

// // 			{"pdb_asym_id", asym_id},
// // 			{"pdb_seq_num", s2.num()},
// // 			{"pdb_mon_id", s2.get_compound_id()},

// // 			// TODO: need fix, collect from nag_atoms?
// // 			{"auth_asym_id", asym_id},
// // 			{"auth_mon_id", s2.get_compound_id()},
// // 			{"auth_seq_num", s2.get_auth_seq_id()},

// // 			{"hetero", "n"}
// // 		});
// // 	}

// // 	return branch;
// }

std::string structure::create_entity_for_branch(branch &branch)
{
	using namespace literals;

	std::string entityName = branch.name();

	auto &entity = m_db["entity"];

	std::string entityID = entity.find_first<std::string>("type"_key == "branched" and "pdbx_description"_key == entityName, "id");

	if (entityID.empty())
	{
		entityID = entity.get_unique_id("");

		if (VERBOSE)
			std::cout << "Creating new entity " << entityID << " for branched sugar " << entityName << '\n';

		entity.emplace({
			{"id", entityID},
			{"type", "branched"},
			{"src_method", "man"},
			{"pdbx_description", entityName},
			{"formula_weight", branch.weight()}});

		auto &pdbx_entity_branch_list = m_db["pdbx_entity_branch_list"];
		for (auto &sugar : branch)
		{
			pdbx_entity_branch_list.emplace({
				{"entity_id", entityID},
				{"comp_id", sugar.get_compound_id()},
				{"num", sugar.num()},
				{"hetero", "n"}
			});
		}

		auto &pdbx_entity_branch_link = m_db["pdbx_entity_branch_link"];
		for (auto &s1 : branch)
		{
			auto l2 = s1.get_link();

			if (not l2 or l2.get_auth_seq_id().empty())
				continue;

			auto &s2 = branch.at(stoi(l2.get_auth_seq_id()) - 1);
			auto l1 = s2.get_atom_by_atom_id("C1");

			pdbx_entity_branch_link.emplace({
				{"link_id", pdbx_entity_branch_link.get_unique_id("")},
				{"entity_id", entityID},
				{"entity_branch_list_num_1", s1.get_auth_seq_id()},
				{"comp_id_1", s1.get_compound_id()},
				{"atom_id_1", l1.get_label_atom_id()},
				{"leaving_atom_id_1", "O1"},
				{"entity_branch_list_num_2", s2.get_auth_seq_id()},
				{"comp_id_2", s2.get_compound_id()},
				{"atom_id_2", l2.get_label_atom_id()},
				{"leaving_atom_id_2", "H" + l2.get_label_atom_id()},
				{"value_order", "sing"}
			});
		}
	}

	return entityID;
}

void structure::cleanup_empty_categories()
{
	using namespace literals;

	auto &atomSite = m_db["atom_site"];

	// Remove chem_comp's for which there are no atoms at all
	auto &chem_comp = m_db["chem_comp"];
	std::vector<row_handle> obsoleteChemComps;

	for (auto chemComp : chem_comp)
	{
		std::string compID = chemComp["id"].as<std::string>();
		if (atomSite.contains("label_comp_id"_key == compID or "auth_comp_id"_key == compID))
			continue;

		obsoleteChemComps.push_back(chemComp);
	}

	for (auto chemComp : obsoleteChemComps)
		chem_comp.erase(chemComp);

	// similarly, remove entities not referenced by any atom

	auto &entities = m_db["entity"];
	std::vector<row_handle> obsoleteEntities;

	for (auto entity : entities)
	{
		std::string entityID = entity["id"].as<std::string>();
		if (atomSite.contains("label_entity_id"_key == entityID))
			continue;

		obsoleteEntities.push_back(entity);
	}

	for (auto entity : obsoleteEntities)
		entities.erase(entity);

	// the rest?

	for (const char *cat : {"pdbx_entity_nonpoly"})
	{
		auto &category = m_db[cat];

		std::vector<row_handle> empty;
		for (auto row : category)
		{
			if (not category.has_children(row) and not category.has_parents(row))
				empty.push_back(row);
		}

		for (auto row : empty)
			category.erase(row);
	}

	// count molecules
	for (auto entity : entities)
	{
		std::string type, id;
		cif::tie(type, id) = entity.get("type", "id");

		std::optional<size_t> count;
		if (type == "polymer")
			count = m_db["struct_asym"].find("entity_id"_key == id).size();
		else if (type == "non-polymer" or type == "water")
			count = m_db["pdbx_nonpoly_scheme"].find("entity_id"_key == id).size();
		else if (type == "branched")
		{
			// is this correct?
			std::set<std::string> asym_ids;
			for (const auto &asym_id : m_db["pdbx_branch_scheme"].find<std::string>("entity_id"_key == id, "asym_id"))
				asym_ids.insert(asym_id);
			count = asym_ids.size();
		}

		entity["pdbx_number_of_molecules"] = count.value_or(0);
	}
}

void structure::translate(point t)
{
	for (auto &a : m_atoms)
		a.translate(t);
}

void structure::rotate(quaternion q)
{
	for (auto &a : m_atoms)
		a.rotate(q);
}

void structure::translate_and_rotate(point t, quaternion q)
{
	for (auto &a : m_atoms)
		a.translate_and_rotate(t, q);
}

void structure::translate_rotate_and_translate(point t1, quaternion q, point t2)
{
	for (auto &a : m_atoms)
		a.translate_rotate_and_translate(t1, q, t2);
}

void structure::validate_atoms() const
{
	// validate order
	assert(m_atoms.size() == m_atom_index.size());
	for (size_t i = 0; i + i < m_atoms.size(); ++i)
		assert(m_atoms[m_atom_index[i]].id().compare(m_atoms[m_atom_index[i + 1]].id()) < 0);

	std::vector<atom> atoms = m_atoms;

	auto removeAtomFromList = [&atoms](const atom &a)
	{
		auto i = std::find(atoms.begin(), atoms.end(), a);
		assert(i != atoms.end());
		atoms.erase(i);
	};

	for (auto &poly : m_polymers)
	{
		for (auto &monomer : poly)
		{
			for (auto &atom : monomer.atoms())
				removeAtomFromList(atom);
		}
	}

	for (auto &branch : m_branches)
	{
		for (auto &sugar : branch)
		{
			for (auto &atom : sugar.atoms())
				removeAtomFromList(atom);
		}
	}

	for (auto &res : m_non_polymers)
	{
		for (auto &atom : res.atoms())
			removeAtomFromList(atom);
	}

	assert(atoms.empty());
}

} // namespace pdbx