File: MarvinDefs.cpp

package info (click to toggle)
rdkit 202503.1-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 220,160 kB
  • sloc: cpp: 399,240; python: 77,453; ansic: 25,517; java: 8,173; javascript: 4,005; sql: 2,389; yacc: 1,565; lex: 1,263; cs: 1,081; makefile: 580; xml: 229; fortran: 183; sh: 105
file content (4281 lines) | stat: -rw-r--r-- 142,683 bytes parent folder | download | duplicates (2)
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
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
//
//  Copyright (C) 2022-2023 Tad Hurst, Greg Landrum and other RDKit contributors
//
//   @@ All Rights Reserved @@
//  This file is part of the RDKit.
//  The contents are covered by the terms of the BSD license
//  which is included in the file license.txt, found at the root
//  of the RDKit source tree.
//

#include <RDGeneral/RDLog.h>
#include "MarvinDefs.h"
#include <RDGeneral/BoostStartInclude.h>
#include <boost/algorithm/string.hpp>
#include <RDGeneral/BoostEndInclude.h>

namespace RDKit {

std::string getDoubleAsText(double val, unsigned int precision = 6) {
  // this is left here for backwards compatibility
  if (precision == 6 && fabs(val) < 0.00001) {
    return "0.00000";
  }

  std::ostringstream valstr;
  valstr << std::setprecision(precision) << val;
  return valstr.str();
}

std::string MarvinArrow::toString() const {
  std::ostringstream out;
  out << "<arrow type=\"" << type << "\" x1=\"" << x1 << "\" y1=\"" << y1
      << "\" x2=\"" << x2 << "\" y2=\"" << y2 << "\"/>";

  return out.str();
}

ptree MarvinMolBase::toPtree() const {
  ptree out;
  out.put("<xmlattr>.molID", molID);

  if (parent != nullptr) {
    out.put("<xmlattr>.id", id);
    out.put("<xmlattr>.role", role());
  }
  if (this->hasAtomBondBlocks()) {
    for (auto atom : atoms) {
      out.add_child("atomArray.atom", atom->toPtree(this->coordinatePrecision));
    }

    for (auto bond : bonds) {
      out.add_child("bondArray.bond", bond->toPtree());
    }
  }

  return out;
}

void MarvinMolBase::addSgroupsToPtree(ptree &out) const {
  for (auto &sgroup : sgroups) {
    out.add_child("molecule", sgroup->toPtree());
  }
}

template <typename T>
bool getCleanNumber(std::string strToParse, T &outVal) {
  if (boost::algorithm::trim_copy(strToParse) !=
      strToParse) {  // should be no white space
    return false;
  }
  try {
    outVal = boost::lexical_cast<T>(strToParse);
  } catch (const std::exception &e) {
    return false;
  }

  return true;
}

void MarvinMolBase::parseAtomsAndBonds(ptree &molTree) {
  boost::property_tree::ptree atomArray = molTree.get_child("atomArray");

  // there are two types of atom arrays:
  // <atomArray atomID="a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11" elementType="C
  // C C C C C Cl C N O O" formalCharge="0 0 0 0 0 0 0 0 1 0 -1"
  // lonePair="0 0 0 0 0 0 3 0 0 2 3" x2="-4.3334 -5.6670 -5.6670 -4.3334
  // -2.9997 -2.9997 -4.3335 -1.6660 -7.0007 -1.6660 -0.3323" y2="1.7693
  // 0.9993 -0.5409 -1.3109 -0.5409 0.9993 3.3093 -1.3109 -1.3109 -2.8509
  // -0.5410"></atomArray>
  //  AND
  // <atomArray>
  //       <atom id="a1" elementType="C" x2="-9.4583" y2="1.9358"
  //       mrvStereoGroup="and1"/> <atom id="a2" elementType="C"
  //       x2="-10.7921" y2="1.1658"/> <atom id="a3" elementType="C"
  //       x2="-10.7921" y2="-0.3744"/> <atom id="a8" elementType="O"
  //       x2="-12.1257" y2="-1.1444" lonePair="2"/>
  //   </atomArray>

  // See which one we have

  std::string atomID =
      atomArray.get<std::string>("<xmlattr>.atomID", "UseLongForm");
  if (atomID == "UseLongForm") {
    // long form - each atom on a line

    for (auto &v : molTree.get_child("atomArray")) {
      if (v.first != "atom") {
        continue;
      }

      auto *mrvAtom = new MarvinAtom();
      this->pushOwnedAtom(mrvAtom);
      this->atoms.push_back(mrvAtom);

      mrvAtom->id = v.second.get<std::string>("<xmlattr>.id", "");
      mrvAtom->elementType =
          v.second.get<std::string>("<xmlattr>.elementType", "");

      if (mrvAtom->id == "" || mrvAtom->elementType == "") {
        throw FileParseException(
            "Expected id, elementType for an atom definition in MRV file");
      }

      std::string x2 = v.second.get<std::string>("<xmlattr>.x2", "");
      std::string y2 = v.second.get<std::string>("<xmlattr>.y2", "");

      // x2 and y2 are doubles

      if (x2 != "" && y2 != "" &&
          (!getCleanNumber(x2, mrvAtom->x2) ||
           !getCleanNumber(y2, mrvAtom->y2))) {
        throw FileParseException(
            "The values x2 and y2 must be large floats in MRV file");
      }

      std::string x3 = v.second.get<std::string>("<xmlattr>.x3", "");
      std::string y3 = v.second.get<std::string>("<xmlattr>.y3", "");
      std::string z3 = v.second.get<std::string>("<xmlattr>.z3", "");

      // x3, y3, and z3 are doubles

      if (x3 != "" && y3 != "" && z3 != "" &&
          (!getCleanNumber(x3, mrvAtom->x3) ||
           !getCleanNumber(y3, mrvAtom->y3) ||
           !getCleanNumber(z3, mrvAtom->z3))) {
        throw FileParseException(
            "The values x3, y3,  and z2 must be large floats in MRV file");
      }

      std::string formalCharge =
          v.second.get<std::string>("<xmlattr>.formalCharge", "");
      if (formalCharge != "") {
        if (!getCleanNumber(formalCharge, mrvAtom->formalCharge)) {
          throw FileParseException(
              "The value for formalCharge must be an integer in MRV file");
        }
      } else {
        mrvAtom->formalCharge = 0;
      }

      mrvAtom->radical = v.second.get<std::string>("<xmlattr>.radical", "");
      if (mrvAtom->radical != "") {
        if (std::find(marvinRadicalVals.begin(), marvinRadicalVals.end(),
                      mrvAtom->radical) == marvinRadicalVals.end()) {
          std::ostringstream err;
          err << "The value for radical must be one of "
              << boost::algorithm::join(marvinRadicalVals, ", ")
              << " in MRV file";
          throw FileParseException(err.str());
        }
      } else {
        mrvAtom->radical = "";
      }

      std::string isotopeStr =
          v.second.get<std::string>("<xmlattr>.isotope", "");
      if (isotopeStr != "") {
        if (!getCleanNumber(isotopeStr, mrvAtom->isotope) ||
            mrvAtom->isotope <= 0) {
          throw FileParseException(
              "The value for isotope must be a positive number in MRV file");
        }
      } else {
        mrvAtom->isotope = 0;
      }

      std::string valenceStr =
          v.second.get<std::string>("<xmlattr>.mrvValence", "");
      if (valenceStr != "") {
        if (!getCleanNumber(valenceStr, mrvAtom->mrvValence) ||
            mrvAtom->mrvValence < 0) {
          throw FileParseException(
              "The value for mrvValence must be a positive number in MRV file");
        }
      } else {
        mrvAtom->mrvValence = -1;
      }

      std::string hCountStr =
          v.second.get<std::string>("<xmlattr>.hydrogenCount", "");
      if (hCountStr != "") {
        if (!getCleanNumber(hCountStr, mrvAtom->hydrogenCount) ||
            mrvAtom->hydrogenCount < 0) {
          throw FileParseException(
              "The value for hydrogenCount must be a non-negative number in MRV file");
        }
      } else {
        mrvAtom->hydrogenCount = -1;
      }

      mrvAtom->mrvAlias = v.second.get<std::string>("<xmlattr>.mrvAlias", "");

      mrvAtom->rgroupRef = v.second.get<int>("<xmlattr>.rgroupRef", -1);

      mrvAtom->mrvStereoGroup =
          v.second.get<std::string>("<xmlattr>.mrvStereoGroup", "");
      if (mrvAtom->mrvStereoGroup == "0") {
        mrvAtom->mrvStereoGroup = "";
      }

      std::string mrvMap = v.second.get<std::string>("<xmlattr>.mrvMap", "");
      if (mrvMap != "") {
        if (!getCleanNumber(mrvMap, mrvAtom->mrvMap) || mrvAtom->mrvMap <= 0) {
          throw FileParseException(
              "The value for mrvMap must be an non-=negative integer in MRV file");
        }
      } else {
        mrvAtom->mrvMap = 0;
      }

      mrvAtom->sgroupRef = v.second.get<std::string>("<xmlattr>.sgroupRef", "");

      mrvAtom->sgroupAttachmentPoint =
          v.second.get<std::string>("<xmlattr>.sgroupAttachmentPoint", "");
    }
  } else  // single line form of atoms
  {
    // <atomArray atomID="a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11"
    // elementType="C C C C C C Cl C N O O" formalCharge="0 0 0 0 0 0 0 0
    // 1 0 -1" lonePair="0 0 0 0 0 0 3 0 0 2 3" x2="-4.3334 -5.6670
    // -5.6670 -4.3334 -2.9997 -2.9997 -4.3335 -1.6660 -7.0007 -1.6660
    // -0.3323" y2="1.7693 0.9993 -0.5409 -1.3109 -0.5409 0.9993 3.3093
    // -1.3109 -1.3109 -2.8509 -0.5410"></atomArray>

    std::vector<std::string> atomIds;
    size_t atomCount;
    if (atomID == "") {
      atomCount = 0;
    } else {
      boost::algorithm::split(atomIds, atomID, boost::algorithm::is_space());
      atomCount = atomIds.size();
    }

    std::vector<std::string> elementTypes;
    std::string elementType =
        atomArray.get<std::string>("<xmlattr>.elementType", "");
    boost::algorithm::split(elementTypes, elementType,
                            boost::algorithm::is_space());

    std::vector<std::string> x2s;
    std::string x2 = atomArray.get<std::string>("<xmlattr>.x2", "");
    boost::algorithm::split(x2s, x2, boost::algorithm::is_space());

    std::vector<std::string> y2s;
    std::string y2 = atomArray.get<std::string>("<xmlattr>.y2", "");
    boost::algorithm::split(y2s, y2, boost::algorithm::is_space());

    std::vector<std::string> formalCharges;
    std::string formalCharge =
        atomArray.get<std::string>("<xmlattr>.formalCharge", "");
    boost::algorithm::split(formalCharges, formalCharge,
                            boost::algorithm::is_space());

    std::vector<std::string> isotopes;
    std::string isotope = atomArray.get<std::string>("<xmlattr>.isotope", "");
    boost::algorithm::split(isotopes, isotope, boost::algorithm::is_space());

    std::vector<std::string> radicals;
    std::string radical = atomArray.get<std::string>("<xmlattr>.radical", "");
    boost::algorithm::split(radicals, radical, boost::algorithm::is_space());

    std::vector<std::string> hydrogenCounts;
    std::string hydrogenCount =
        atomArray.get<std::string>("<xmlattr>.hydrogenCount", "");
    boost::algorithm::split(hydrogenCounts, hydrogenCount,
                            boost::algorithm::is_space());

    std::vector<std::string> mrvValences;
    std::string mrvValence =
        atomArray.get<std::string>("<xmlattr>.mrvValence", "");
    boost::algorithm::split(mrvValences, mrvValence,
                            boost::algorithm::is_space());

    std::vector<std::string> mrvAliases;
    std::string mrvAlias = atomArray.get<std::string>("<xmlattr>.mrvAlias", "");
    boost::algorithm::split(mrvAliases, mrvAlias, boost::algorithm::is_space());

    std::vector<std::string> rgroupRefs;
    std::string rgroupRef =
        atomArray.get<std::string>("<xmlattr>.rgroupRef", "");
    boost::algorithm::split(rgroupRefs, rgroupRef,
                            boost::algorithm::is_space());

    std::vector<std::string> mrvStereoGroups;
    std::string mrvStereoGroup =
        atomArray.get<std::string>("<xmlattr>.mrvStereoGroup", "");
    boost::algorithm::split(mrvStereoGroups, mrvStereoGroup,
                            boost::algorithm::is_space());

    std::vector<std::string> mrvMaps;
    std::string mrvMap = atomArray.get<std::string>("<xmlattr>.mrvMap", "");
    boost::algorithm::split(mrvMaps, mrvMap, boost::algorithm::is_space());

    std::vector<std::string> sgroupRefs;
    std::string sgroupRef =
        atomArray.get<std::string>("<xmlattr>.sgroupRef", "");
    boost::algorithm::split(sgroupRefs, sgroupRef,
                            boost::algorithm::is_space());

    std::vector<std::string> sgroupAttachmentPoints;
    std::string sgroupAttachmentPoint =
        atomArray.get<std::string>("<xmlattr>.sgroupAttachmentPoint", "");
    boost::algorithm::split(sgroupAttachmentPoints, sgroupAttachmentPoint,
                            boost::algorithm::is_space());

    if (atomID != "") {
      if (elementType == "") {
        throw FileParseException(
            "Expected an elementType array for an atomArray definition in MRV file");
      }
      if (elementTypes.size() < atomCount) {
        throw FileParseException(
            "There must be an element type for each atom id");
      }
    }

    for (size_t i = 0; i < atomCount; ++i) {
      auto *mrvAtom = new MarvinAtom();
      this->pushOwnedAtom(mrvAtom);

      this->atoms.push_back(mrvAtom);

      mrvAtom->id = atomIds[i];

      mrvAtom->elementType = elementTypes[i];

      if (x2 != "" && y2 != "" && x2s.size() > i && y2s.size() > i) {
        if (!getCleanNumber(x2s[i], mrvAtom->x2) ||
            !getCleanNumber(y2s[i], mrvAtom->y2)) {
          throw FileParseException(
              "The values x2 and y2 must be large floats in MRV file");
        }
      }

      if (formalCharge != "" && formalCharges.size() > i) {
        if (!getCleanNumber(formalCharges[i], mrvAtom->formalCharge)) {
          throw FileParseException(
              "The value for formalCharge must be an integer in MRV file");
        }
      } else {
        mrvAtom->formalCharge = 0;
      }

      if (isotope != "" && isotopes.size() > i) {
        if (!getCleanNumber(isotopes[i], mrvAtom->isotope)) {
          throw FileParseException(
              "The value for formalCharge must be an integer in MRV file");
        }
      } else {
        mrvAtom->isotope = 0;
      }

      if (mrvValence != "" && mrvValences.size() > i) {
        if (mrvValences[i] == "-") {
          mrvAtom->mrvValence = -1;
        } else if (!getCleanNumber(mrvValences[i], mrvAtom->mrvValence)) {
          throw FileParseException(
              "The value for mrvValences must be an integer in MRV file");
        }
      } else {
        mrvAtom->mrvValence = -1;
      }

      if (hydrogenCount != "" && hydrogenCounts.size() > i) {
        if (hydrogenCounts[i] != "-" &&
            !getCleanNumber(hydrogenCounts[i], mrvAtom->hydrogenCount)) {
          throw FileParseException(
              "The value for hydrogenCount must be an integer in MRV file");
        }
      } else {
        mrvAtom->hydrogenCount = -1;
      }

      if (radical != "" && radicals.size() > i && radicals[i] != "0") {
        mrvAtom->radical = radicals[i];
        if (std::find(marvinRadicalVals.begin(), marvinRadicalVals.end(),
                      mrvAtom->radical) == marvinRadicalVals.end()) {
          std::ostringstream err;
          err << "The value for radical must be one of "
              << boost::algorithm::join(marvinRadicalVals, ", ")
              << " in MRV file";
          throw FileParseException(err.str());
        }
      } else {
        mrvAtom->radical = "";
      }

      if (mrvAlias != "" && mrvAliases.size() > i) {
        mrvAtom->mrvAlias = mrvAliases[i];
      } else {
        mrvAtom->mrvAlias = "";
      }

      if (rgroupRef != "" && rgroupRefs.size() > i) {
        if (!getCleanNumber(rgroupRefs[i], mrvAtom->rgroupRef)) {
          throw FileParseException(
              "rgroupRef value must be an integer in MRV file");
        }
      } else {
        mrvAtom->rgroupRef = -1;
      }

      if (mrvStereoGroup != "" && mrvStereoGroups.size() > i &&
          mrvStereoGroups[i] != "0")  // "0" is NOT a stereo group
      {
        mrvAtom->mrvStereoGroup = mrvStereoGroups[i];
      } else {
        mrvAtom->mrvStereoGroup = "";
      }

      if (mrvMap != "" && mrvMaps.size() > i) {
        if (!getCleanNumber(mrvMaps[i], mrvAtom->mrvMap) ||
            mrvAtom->mrvMap < 0) {
          throw FileParseException(
              "The value for mrvMap must be an non-negative integer in MRV file");
        }
      } else {
        mrvAtom->mrvMap = 0;
      }

      if (sgroupRef != "" && sgroupRefs.size() > i && sgroupRefs[i] != "0") {
        mrvAtom->sgroupRef = sgroupRefs[i];
      } else {
        mrvAtom->sgroupRef = "";
      }

      if (sgroupAttachmentPoint != "" && sgroupAttachmentPoints.size() > i &&
          sgroupAttachmentPoints[i] != "0") {
        mrvAtom->sgroupAttachmentPoint = sgroupAttachmentPoints[i];
      } else {
        mrvAtom->sgroupAttachmentPoint = "";
      }
    }
  }

  auto bondArray = molTree.get_child_optional("bondArray");
  if (bondArray) {
    for (auto &v : molTree.get_child("bondArray")) {
      if (v.first != "bond") {
        continue;
      }

      auto *mrvBond = new MarvinBond();
      this->pushOwnedBond(mrvBond);
      this->bonds.push_back(mrvBond);

      mrvBond->id = v.second.get<std::string>("<xmlattr>.id", "");
      if (mrvBond->id == "") {
        throw FileParseException(
            "Expected id for an bond definition in MRV file");
      }

      std::string atomRefs2 =
          v.second.get<std::string>("<xmlattr>.atomRefs2", "");

      std::vector<std::string> atomRefs2s;
      boost::algorithm::split(atomRefs2s, atomRefs2,
                              boost::algorithm::is_space());
      mrvBond->atomRefs2[0] = atomRefs2s[0];
      mrvBond->atomRefs2[1] = atomRefs2s[1];
      if (atomRefs2s.size() != 2 ||
          std::find_if(atoms.begin(), atoms.end(),
                       [mrvBond](auto a) {
                         return a->id == mrvBond->atomRefs2[0];
                       }) == atoms.end() ||
          std::find_if(atoms.begin(), atoms.end(), [mrvBond](auto a) {
            return a->id == mrvBond->atomRefs2[1];
          }) == atoms.end()) {
        throw FileParseException(
            "atomRefs2 must contain two atom refs that must appear in the atoms array in MRV file");
      }

      mrvBond->order = v.second.get<std::string>("<xmlattr>.order", "");
      if (mrvBond->order != "") {
        if (std::find(marvinBondOrders.begin(), marvinBondOrders.end(),
                      mrvBond->order) == marvinBondOrders.end()) {
          std::ostringstream err;
          err << "Expected one of  "
              << boost::algorithm::join(marvinBondOrders, ", ")
              << " for order for an bond definition in MRV file";
          throw FileParseException(err.str());
        }
      }

      mrvBond->queryType = v.second.get<std::string>("<xmlattr>.queryType", "");
      if (mrvBond->queryType != "") {
        if (std::find(marvinQueryBondsTypes.begin(),
                      marvinQueryBondsTypes.end(),
                      mrvBond->queryType) == marvinQueryBondsTypes.end()) {
          std::ostringstream err;
          err << "Expected one of  "
              << boost::algorithm::join(marvinQueryBondsTypes, ", ")
              << " for queryType for an bond definition in MRV file";
          throw FileParseException(err.str());
        }
      }

      mrvBond->convention =
          v.second.get<std::string>("<xmlattr>.convention", "");
      if (mrvBond->convention != "") {
        if (std::find(marvinConventionTypes.begin(),
                      marvinConventionTypes.end(),
                      mrvBond->convention) == marvinConventionTypes.end()) {
          std::ostringstream err;
          err << "Expected one of  "
              << boost::algorithm::join(marvinConventionTypes, ", ")
              << " for convention for an bond definition in MRV file";
          throw FileParseException(err.str());
        }
      }

      int bondStereoDeclCount = 0;
      mrvBond->bondStereo.value = v.second.get<std::string>("bondStereo", "");
      if (mrvBond->bondStereo.value != "") {
        bondStereoDeclCount++;
        if (boost::algorithm::to_lower_copy(mrvBond->bondStereo.value) == "w" ||
            boost::algorithm::to_lower_copy(mrvBond->bondStereo.value) == "h") {
          // do nothing  - this is OK
        } else if (boost::algorithm::to_lower_copy(mrvBond->bondStereo.value) ==
                       "c" ||
                   boost::algorithm::to_lower_copy(mrvBond->bondStereo.value) ==
                       "t") {
          mrvBond->bondStereo.value = "";  // cis and trans are ignored
        } else {
          throw FileParseException(
              "The value for bondStereo must be \"H\", \"W\", \"C\" or \"T\" in MRV file (\"C\" and \"T\" are ignored)");
        }
      }

      // see if bondstereo has a dictRef or convention

      auto bondStereoItem = v.second.get_child_optional("bondStereo");
      if (bondStereoItem) {
        for (auto &ww : v.second) {
          mrvBond->bondStereo.convention =
              ww.second.get<std::string>("<xmlattr>.convention", "");
          if (mrvBond->bondStereo.convention != "") {
            bondStereoDeclCount++;
            if (mrvBond->bondStereo.convention != "MDL") {
              throw FileParseException(
                  "Expected MDL as value for the bond convention attribute");
            }
            mrvBond->bondStereo.conventionValue =
                ww.second.get<std::string>("<xmlattr>.conventionValue", "");
            if (std::find(marvinStereoConventionTypes.begin(),
                          marvinStereoConventionTypes.end(),
                          mrvBond->bondStereo.conventionValue) ==
                marvinStereoConventionTypes.end()) {
              std::ostringstream err;
              err << "Expected one of  "
                  << boost::algorithm::join(marvinStereoConventionTypes, ", ")
                  << " for a bond convention for an bond stereo def";
              throw FileParseException(err.str());
            }
          }

          mrvBond->bondStereo.dictRef =
              ww.second.get<std::string>("<xmlattr>.dictRef", "");
          if (mrvBond->bondStereo.dictRef != "") {
            bondStereoDeclCount++;
            if (std::find(marvinStereoDictRefTypes.begin(),
                          marvinStereoDictRefTypes.end(),
                          mrvBond->bondStereo.dictRef) ==
                marvinStereoDictRefTypes.end()) {
              std::ostringstream err;
              err << "Expected one of  "
                  << boost::algorithm::join(marvinStereoDictRefTypes, ", ")
                  << " for a discRef value for an bond stereo def";
              throw FileParseException(err.str());
            }
          }
        }
      }

      // check that there were not too many different declarations

      if (bondStereoDeclCount > 1) {
        throw FileParseException(
            "bondStereo can either have only one of: a value, dictRef, or convention value");
      }
    }
  }
}

ptree MarvinArrow::toPtree() const {
  ptree out;
  out.put("<xmlattr>.type", type);
  out.put("<xmlattr>.x1", getDoubleAsText(x1));
  out.put("<xmlattr>.y1", getDoubleAsText(y1));
  out.put("<xmlattr>.x2", getDoubleAsText(x2));
  out.put("<xmlattr>.y2", getDoubleAsText(y2));

  return out;
}

std::string MarvinPlus::toString() const {
  std::ostringstream out;

  out << "<MReactionSign id=\"" << id
      << "\" toptions=\"NOROT\" fontScale=\"14.0\" halign=\"CENTER\" valign=\"CENTER\" autoSize=\"true\">"
         "<Field name=\"text\"><![CDATA[ {D font=SansSerif,size=18,bold}+]]></Field>"
         "<MPoint x=\""
      << x1 << "\" y=\"" << y1
      << "\"/>"
         "<MPoint x=\""
      << x2 << "\" y=\"" << y1
      << "\"/>"
         "<MPoint x=\""
      << x2 << "\" y=\"" << y2
      << "\"/>"
         "<MPoint x=\""
      << x1 << "\" y=\"" << y2
      << "\"/>"
         "</MReactionSign>";

  return out.str();
}

ptree MarvinPlus::toPtree() const {
  ptree out;

  out.put("<xmlattr>.id", id);
  out.put("<xmlattr>.toptions", "NOROT");
  out.put("<xmlattr>.fontScale", "14.0");
  out.put("<xmlattr>.halign", "CENTER");
  out.put("<xmlattr>.valign", "CENTER");
  out.put("<xmlattr>.autoSize", "true");
  ptree field;
  field.put("<xmlattr>.name", "text");

  field.put_value("{D font=SansSerif,size=18,bold}+");

  out.put_child("Field", field);

  ptree p1, p2, p3, p4;
  p1.put("<xmlattr>.x", getDoubleAsText(x1));
  p1.put("<xmlattr>.y", getDoubleAsText(y1));
  out.add_child("MPoint", p1);

  p2.put("<xmlattr>.x", getDoubleAsText(x2));
  p2.put("<xmlattr>.y", getDoubleAsText(y1));
  out.add_child("MPoint", p2);

  p3.put("<xmlattr>.x", getDoubleAsText(x2));
  p3.put("<xmlattr>.y", getDoubleAsText(y2));
  out.add_child("MPoint", p3);

  p4.put("<xmlattr>.x", getDoubleAsText(x1));
  p4.put("<xmlattr>.y", getDoubleAsText(y2));
  out.add_child("MPoint", p4);

  return out;
}

std::string MarvinCondition::toString() const {
  std::ostringstream out;

  out << "<MTextBox id=\"" << id << "\" toption=\"NOROT\" halign=\"" << halign
      << "\" valign=\"" << valign << "\" autoSize=\"true\"";
  if (fontScale > 0) {
    out << " fontScale=\"" << fontScale << "\"";
  }

  out << ">"
         "<Field name=\"text\">"
      << text
      << "</Field>"
         "<MPoint x=\""
      << x << "\" y=\"" << y
      << "\"/>"
         "<MPoint x=\""
      << x << "\" y=\"" << y
      << "\"/>"
         "<MPoint x=\""
      << x << "\" y=\"" << y
      << "\"/>"
         "<MPoint x=\""
      << x << "\" y=\"" << y
      << "\"/>"
         "</MTextBox>";

  return out.str();
}

ptree MarvinCondition::toPtree() const {
  ptree out;

  out.put("<xmlattr>.id", id);
  if (fontScale > 0) {
    out.put("<xmlattr>.fontScale", fontScale);
  }
  out.put("<xmlattr>.toption", "NOROT");
  out.put("<xmlattr>.halign", halign);
  out.put("<xmlattr>.valign", valign);
  out.put("<xmlattr>.autoSize", "true");
  ptree field;
  field.put("<xmlattr>.name", "text");

  field.put_value("![CDATA[ {D font=SansSerif,size=18,bold}+]]");

  out.put_child("Field", field);

  // add four points

  std::ostringstream xstr, ystr;
  xstr << x;
  ystr << y;

  for (int i = 0; i < 4; ++i) {
    ptree p1;
    p1.put("<xmlattr>.x", xstr.str());
    p1.put("<xmlattr>.y", ystr.str());
    out.add_child("MPoint", p1);
  }

  return out;
}

std::string MarvinAttachmentPoint::toString() const {
  std::ostringstream out;

  out << "<attachmentPoint atom=\"" << atom << "\" order=\"" << order
      << "\" bond=\"" << bond << "\"/>";

  return out.str();
}

ptree MarvinAttachmentPoint::toPtree() const {
  ptree out;

  out.put("<xmlattr>.atom", atom);
  out.put("<xmlattr>.order", order);
  out.put("<xmlattr>.bond", bond);

  return out;
}

MarvinAtom::MarvinAtom()
    : x2(DBL_MAX),
      y2(DBL_MAX),
      x3(DBL_MAX),
      y3(DBL_MAX),
      z3(DBL_MAX),
      formalCharge(0),
      mrvValence(-1),
      hydrogenCount(-1),
      mrvMap(0),
      sGroupRefIsSuperatom(false),
      rgroupRef(-1)  // indicates that it was not specified

{}

MarvinAtom::MarvinAtom(const MarvinAtom &atomToCopy, std::string newId)
    : id(newId),
      elementType(atomToCopy.elementType),
      x2(atomToCopy.x2),
      y2(atomToCopy.y2),
      x3(atomToCopy.x3),
      y3(atomToCopy.y3),
      z3(atomToCopy.z3),
      formalCharge(atomToCopy.formalCharge),
      radical(atomToCopy.radical),
      isotope(atomToCopy.isotope),
      mrvValence(atomToCopy.mrvValence),
      hydrogenCount(atomToCopy.hydrogenCount),
      mrvAlias(atomToCopy.mrvAlias),
      mrvStereoGroup(atomToCopy.mrvStereoGroup),
      mrvMap(atomToCopy.mrvMap),
      sgroupRef(atomToCopy.sgroupRef),
      sGroupRefIsSuperatom(atomToCopy.sGroupRefIsSuperatom),
      sgroupAttachmentPoint(atomToCopy.sgroupAttachmentPoint),
      rgroupRef(atomToCopy.rgroupRef)  // indicates that it was not specified
{}

bool MarvinAtom::operator==(const MarvinAtom &rhs) const {
  return this->id == rhs.id;
}

bool MarvinAtom::operator==(const MarvinAtom *rhs) const {
  return this->id == rhs->id;
}

bool MarvinAtom::isElement() const {
  return this->elementType != "R" && this->elementType != "*";
}

std::string MarvinAtom::toString() const {
  // <atom id="a7" elementType="C" x2="15.225" y2="-8.3972"
  // sgroupAttachmentPoint="1"/>

  std::ostringstream out;
  out << "<atom id=\"" << id << "\" elementType=\"" << elementType << "\"";

  if (x2 != DBL_MAX && y2 != DBL_MAX) {
    out << " x2=\"" << x2 << "\" y2=\"" << y2 << "\"";
  }

  if (x3 != DBL_MAX && y3 != DBL_MAX && z3 != DBL_MAX) {
    out << " x3=\"" << x3 << "\" y3=\"" << y3 << "\" z3=\"" << z3 << "\"";
  }

  if (formalCharge != 0) {
    out << " formalCharge=\"" << formalCharge << "\"";
  }

  if (radical != "") {
    out << " radical=\"" << radical << "\"";
  }

  if (isElement() && isotope != 0) {
    out << " isotope=\"" << isotope << "\"";
  }

  if (mrvAlias != "") {
    out << " mrvAlias=\"" << mrvAlias << "\"";
  }

  if (mrvValence >= 0) {
    out << " mrvValence=\"" << mrvValence << "\"";
  }

  if (hydrogenCount > 0) {
    out << " hydrogenCount=\"" << hydrogenCount << "\"";
  }

  if (mrvStereoGroup != "") {
    out << " mrvStereoGroup=\"" << mrvStereoGroup << "\"";
  }

  if (mrvMap != 0) {
    out << " mrvMap=\"" << mrvMap << "\"";
  }

  if (sgroupRef != "") {
    out << " sgroupRef=\"" << sgroupRef << "\"";
  }

  if (rgroupRef >= 0) {
    out << " rgroupRef=\"" << rgroupRef << "\"";
  }

  if (sgroupAttachmentPoint != "") {
    out << " sgroupAttachmentPoint=\"" << sgroupAttachmentPoint << "\"";
  }

  out << "/>";

  return out.str();
}

ptree MarvinAtom::toPtree(unsigned int coordinatePrecision) const {
  ptree out;

  out.put("<xmlattr>.id", id);
  out.put("<xmlattr>.elementType", elementType);

  if (x2 != DBL_MAX && y2 != DBL_MAX) {
    out.put("<xmlattr>.x2", getDoubleAsText(x2, coordinatePrecision));
    out.put("<xmlattr>.y2", getDoubleAsText(y2, coordinatePrecision));
  }

  if (x3 != DBL_MAX && y3 != DBL_MAX && z3 != DBL_MAX) {
    out.put("<xmlattr>.x3", getDoubleAsText(x3, coordinatePrecision));
    out.put("<xmlattr>.y3", getDoubleAsText(y3, coordinatePrecision));
    out.put("<xmlattr>.z3", getDoubleAsText(z3, coordinatePrecision));
  }

  if (formalCharge != 0) {
    out.put("<xmlattr>.formalCharge", formalCharge);
  }

  if (radical != "") {
    out.put("<xmlattr>.radical", radical);
  }

  if (isElement() && isotope != 0) {
    out.put("<xmlattr>.isotope", isotope);
  }

  if (mrvAlias != "") {
    out.put("<xmlattr>.mrvAlias", mrvAlias);
  }

  if (mrvValence >= 0) {
    out.put("<xmlattr>.mrvValence", mrvValence);
  }

  if (hydrogenCount > 0) {
    out.put("<xmlattr>.hydrogenCount", hydrogenCount);
  }

  if (mrvStereoGroup != "") {
    out.put("<xmlattr>.mrvStereoGroup", mrvStereoGroup);
  }

  if (mrvMap != 0) {
    out.put("<xmlattr>.mrvMap", mrvMap);
  }

  if (sgroupRef != "") {
    out.put("<xmlattr>.sgroupRef", sgroupRef);
  }

  if (rgroupRef >= 0) {
    out.put("<xmlattr>.rgroupRef", rgroupRef);
  }

  if (sgroupAttachmentPoint != "") {
    out.put("<xmlattr>.sgroupAttachmentPoint", sgroupAttachmentPoint);
  }

  return out;
}

MarvinBond::MarvinBond(const MarvinBond &bondToCopy, std::string newId,
                       std::string atomRef1, std::string atomRef2)
    : id(newId),
      order(bondToCopy.order),
      bondStereo(bondToCopy.bondStereo),
      queryType(bondToCopy.queryType),
      convention(bondToCopy.convention) {
  atomRefs2[0] = atomRef1;
  atomRefs2[1] = atomRef2;
}

const std::string MarvinBond::getBondType() const {
  std::string tempQueryType = boost::algorithm::to_upper_copy(queryType);
  std::string tempOrder = boost::algorithm::to_upper_copy(order);
  std::string tempConvention = boost::algorithm::to_upper_copy(convention);

  if (tempQueryType != "") {
    if (tempQueryType == "SD" || tempQueryType == "SA" ||
        tempQueryType == "DA" || tempQueryType == "ANY") {
      return tempQueryType;
    } else {
      std::ostringstream err;
      err << "unrecognized query bond type " << queryType << " in MRV File ";
      throw FileParseException(err.str());
    }
  } else if (tempConvention != "")  // if no query type, check for convention
  {
    if (tempConvention == "CXN:COORD") {
      return "DATIVE";
    } else {
      std::ostringstream err;
      err << "unrecognized convention " << convention << " in MRV File ";
      throw FileParseException(err.str());
    }
  } else if (tempOrder !=
             "")  // if no query type not convention,  so check for order
  {
    if (tempOrder == "1" || tempOrder == "2" || tempOrder == "3" ||
        tempOrder == "A") {
      return tempOrder;
    } else {
      std::ostringstream err;
      err << "unrecognized bond type " << order << " in MRV File ";
      throw FileParseException(err.str());
    }
  } else {
    throw FileParseException(
        "bond must have one of:  order, queryType, or convention in MRV File ");
  }
}

bool MarvinBond::isEqual(const MarvinAtom &other) const {
  return this->id == other.id;
}

bool MarvinBond::operator==(const MarvinAtom &rhs) const {
  return this->isEqual(rhs);
}

std::string MarvinBond::toString() const {
  // <bond id="b8" atomRefs2="a1 a7" order="1">

  std::ostringstream out;

  out << "<bond id=\"" << id << "\" atomRefs2=\"" << atomRefs2[0] << " "
      << atomRefs2[1] << "\"";

  if (order != "") {
    out << " order=\"" << order << "\"";
  }

  if (queryType != "") {
    out << " queryType=\"" << queryType << "\"";
  }

  if (convention != "") {
    out << " convention=\"" << convention << "\"";
  }

  if (bondStereo.value != "" || bondStereo.dictRef != "" ||
      (bondStereo.convention != "" && bondStereo.conventionValue != "")) {
    out << "><bondStereo";
    if (bondStereo.value != "") {
      out << ">" << bondStereo.value << "</bondStereo>";
    } else if (bondStereo.dictRef != "") {
      out << " dictRef=\"" << bondStereo.dictRef << "\"/>";
    } else {
      out << " convention=\"" << bondStereo.convention
          << "\" conventionValue=\"" << bondStereo.conventionValue << "\"/>";
    }
    out << "</bond>";
  } else {
    out << "/>";  // just end the bond
  }
  return out.str();
}

ptree MarvinBond::toPtree() const {
  ptree out;

  out.put("<xmlattr>.id", id);
  out.put("<xmlattr>.atomRefs2", atomRefs2[0] + " " + atomRefs2[1]);

  if (order != "") {
    out.put("<xmlattr>.order", order);
  }

  if (queryType != "") {
    out.put("<xmlattr>.queryType", queryType);
  }

  if (convention != "") {
    out.put("<xmlattr>.convention", convention);
  }

  if (bondStereo.value != "" || bondStereo.dictRef != "" ||
      (bondStereo.convention != "" && bondStereo.conventionValue != "")) {
    ptree bondStereoPt;

    if (bondStereo.value != "") {
      bondStereoPt.put_value(bondStereo.value);
    } else if (bondStereo.dictRef != "") {
      bondStereoPt.put("<xmlattr>.dictRef", bondStereo.dictRef);
    } else {
      bondStereoPt.put("<xmlattr>.convention", bondStereo.convention);
      bondStereoPt.put("<xmlattr>.conventionValue", bondStereo.conventionValue);
    }

    out.put_child("bondStereo", bondStereoPt);
  }
  return out;
}

MarvinMolBase::~MarvinMolBase() {}

int MarvinMolBase::getAtomIndex(std::string id) const {
  auto atomIter =
      find_if(atoms.begin(), atoms.end(),
              [id](const MarvinAtom *arg) { return arg->id == id; });
  if (atomIter != atoms.end()) {
    return atomIter - atoms.begin();
  } else {
    return -1;
  }
}

void MarvinMolBase::pushOwnedAtom(MarvinAtom *atom) {
  PRECONDITION(atom, "bad atom");
  PRECONDITION(this->parent, "only sgroups should call the base class version");
  this->parent->pushOwnedAtom(atom);
}

void MarvinMolBase::pushOwnedBond(MarvinBond *bond) {
  PRECONDITION(bond, "bad bond");
  PRECONDITION(this->parent, "only sgroups should call the base class version");
  this->parent->pushOwnedBond(std::move(bond));
}

void MarvinMolBase::removeOwnedAtom(MarvinAtom *atom) {
  PRECONDITION(this->parent, "only sgroups should call the base class version");
  this->parent->removeOwnedAtom(atom);
}

void MarvinMolBase::removeOwnedBond(MarvinBond *bond) {
  PRECONDITION(this->parent, "only sgroups should call the base class version");
  this->parent->removeOwnedBond(bond);
}

int MarvinMolBase::getBondIndex(std::string id) const {
  auto bondIter =
      find_if(bonds.begin(), bonds.end(),
              [id](const MarvinBond *arg) { return arg->id == id; });
  if (bondIter != bonds.end()) {
    return bondIter - bonds.begin();
  } else {
    return -1;
  }
}

MarvinAtom *MarvinMolBase::findAtomByRef(std::string atomId) {
  auto atomIter =
      find_if(this->atoms.begin(), this->atoms.end(),
              [atomId](const MarvinAtom *arg) { return arg->id == atomId; });
  if (atomIter != this->atoms.end()) {
    return *atomIter;
  }

  // try the parent if there is one

  if (this->parent != nullptr) {
    return this->parent->findAtomByRef(atomId);
  }

  return nullptr;
}

MarvinBond *MarvinMolBase::findBondByRef(std::string bondId) {
  auto bondIter =
      find_if(this->bonds.begin(), this->bonds.end(),
              [bondId](const MarvinBond *arg) { return arg->id == bondId; });
  if (bondIter != this->bonds.end()) {
    return *bondIter;
  }

  // try the parent if there is one

  if (this->parent != nullptr) {
    return this->parent->findBondByRef(bondId);
  }

  return nullptr;
}

const std::vector<std::string> MarvinMolBase::getBondList() const {
  std::vector<std::string> bondList;
  for (auto bond : bonds) {
    bondList.push_back(bond->id);
  }

  return bondList;
}

const std::vector<std::string> MarvinMolBase::getAtomList() const {
  std::vector<std::string> atomList;
  for (auto atom : atoms) {
    atomList.push_back(atom->id);
  }

  return atomList;
}

bool MarvinMolBase::has2dCoords() const {
  for (auto atom : atoms) {
    if (atom->x2 == DBL_MAX || atom->y2 == DBL_MAX) {
      return false;
    }
  }

  return true;
}

bool MarvinMolBase::has3dCoords() const {
  for (auto atom : atoms) {
    if (atom->x3 == DBL_MAX || atom->y3 == DBL_MAX || atom->z3 == DBL_MAX) {
      return false;
    }
  }

  return true;
}

bool MarvinMolBase::hasAny2dCoords() const {
  for (auto atom : atoms) {
    if (atom->x2 != DBL_MAX && atom->y2 != DBL_MAX) {
      return true;
    }
  }

  return false;
}

bool MarvinMolBase::hasAny3dCoords() const {
  for (auto atom : atoms) {
    if (atom->x3 != DBL_MAX && atom->y3 != DBL_MAX && atom->z3 != DBL_MAX) {
      return true;
    }
  }

  return false;
}

bool MarvinMolBase::hasCoords() const { return has2dCoords() || has3dCoords(); }

void MarvinMolBase::removeCoords() {
  for (auto atom : atoms) {
    atom->x2 = DBL_MAX;
    atom->y2 = DBL_MAX;
  }
}

void MarvinMolBase::setPrecision(unsigned int precision) {
  this->coordinatePrecision = precision;
}

int MarvinMolBase::getExplicitValence(const MarvinAtom &marvinAtom) const {
  unsigned int resTimes10 = 0;  // calculated as 10 * the actual value so we
                                // can use int match, and have 1.5 order bonds

  for (auto bondPtr : bonds) {
    if (bondPtr->atomRefs2[0] != marvinAtom.id &&
        bondPtr->atomRefs2[1] != marvinAtom.id) {
      continue;  // this bond is NOT to the atom
    }

    std::string marvinBondType = bondPtr->getBondType();

    if (marvinBondType == "SD" || marvinBondType == "SA" ||
        marvinBondType == "DA") {
      resTimes10 += 15;  // really 1.5 order bond
    } else if (marvinBondType == "ANY") {
      resTimes10 +=
          10;  // no good answer for Any bonds - treat as a single bond
    } else if (marvinBondType == "DATIVE") {
      //
      //  the following code has been removed because we really need both
      //  ends of the dative bond to be counted as zero
      //
      // if (bondPtr->atomRefs2[1] == marvinAtom.id) //second atom of dative
      // bond count as 1 (first atom is zero)
      //   resTimes10 += 10;  // really 1 order bond
    } else if (marvinBondType == "1") {
      resTimes10 += 10;  // really 1 order bond
    } else if (marvinBondType == "2") {
      resTimes10 += 20;  // really 2 order bond
    } else if (marvinBondType == "3") {
      resTimes10 += 30;  // really 3 order bond
    } else if (marvinBondType == "A") {
      resTimes10 += 15;  // really 1.5 order bond
    }
  }

  return resTimes10 / 10;
}

MarvinSruCoModSgroup::MarvinSruCoModSgroup(std::string roleNameInit,
                                           MarvinMolBase *parentInit) {
  PRECONDITION(parentInit != nullptr, "parentInit cannot be null");

  parent = parentInit;

  if (roleNameInit != "SruSgroup" && roleNameInit != "CopolymerSgroup" &&
      roleNameInit != "ModificationSgroup") {
    throw FileParseException(
        "A MarvinSruCoModSgroup type must be one of \"SruSgroup\". \"CopolymerSgroup\", and \"ModificationSgroup\"");
  }

  this->roleName = roleNameInit;
}

MarvinSruCoModSgroup::MarvinSruCoModSgroup(MarvinMolBase *parentInit,
                                           std::string roleNameInit,
                                           ptree &molTree) {
  PRECONDITION(parentInit != nullptr, "parentInit cannot be null");

  //      <molecule molID="m2" id="sg1" role="SruSgroup" atomRefs="a1 a3
  //      a4" title="n" connect="ht" correspondence="" bondList=""/>
  //      <molecule molID="m3" id="sg2" role="SruSgroup" atomRefs="a5 a6
  //      a7 a8" title="n" connect="hh" correspondence="" bondList=""/>
  //      <molecule molID="m4" id="sg3" role="SruSgroup" atomRefs="a10
  //      a11" title="n" connect="eu" correspondence=""
  //      bondList=""/></molecule>

  parent = parentInit;
  this->id = molTree.get<std::string>("<xmlattr>.id", "");
  if (this->id == "") {
    throw FileParseException("Expected a iD in MRV file");
  }
  this->molID = molTree.get<std::string>("<xmlattr>.molID", "");
  if (this->molID == "") {
    throw FileParseException("Expected a molID in MRV file");
  }

  this->roleName = roleNameInit;
  std::string atomRefsStr = molTree.get<std::string>("<xmlattr>.atomRefs", "");
  if (atomRefsStr == "") {
    throw FileParseException(
        "Expected  atomRefs for a SruSgroup definition in MRV file");
  }

  std::vector<std::string> atomList;
  boost::algorithm::split(atomList, atomRefsStr, boost::algorithm::is_space());
  for (auto &it : atomList) {
    auto atomPtr = this->parent->findAtomByRef(it);

    if (atomPtr == nullptr) {
      throw FileParseException(
          "AtomRef specification for an SRU, Copolymer, or Modification group definition was not found in any parent");
    }
    this->atoms.push_back(atomPtr);
  }

  this->title = molTree.get<std::string>("<xmlattr>.title", "");
  if (this->title == "") {
    throw FileParseException(
        "Expected title for a SruSgroup definition in MRV file");
  }

  // the title for an SRU group must be a lower case letter, or a range
  // of two positive ints (4-6)

  this->connect = molTree.get<std::string>("<xmlattr>.connect", "");
  if (this->connect == "") {
    this->connect = "ht";
  }
  if (std::find(sruSgroupConnectChoices.begin(), sruSgroupConnectChoices.end(),
                this->connect) == sruSgroupConnectChoices.end()) {
    std::ostringstream err;
    err << "Expected a connect  string of \""
        << boost::algorithm::join(sruSgroupConnectChoices, ", ")
        << "\" for a SruSgroup definition in MRV file";
    throw FileParseException(err.str());
  }

  this->correspondence =
      molTree.get<std::string>("<xmlattr>.correspondence", "");

  std::string bondListStr = molTree.get<std::string>("<xmlattr>.bondList", "");
  if (bondListStr != "") {
    std::vector<std::string> bondList;
    boost::algorithm::split(bondList, bondListStr,
                            boost::algorithm::is_space());

    for (auto &it : bondList) {
      auto bondPtr = this->parent->findBondByRef(it);

      if (bondPtr == nullptr) {
        throw FileParseException(
            "BondList specification for an SRU, Copolymer, or Modification group definition was not found in any parent");
      }
      this->bonds.push_back(bondPtr);
    }
  }
}

std::string MarvinSruCoModSgroup::toString() const {
  std::ostringstream out;

  out << "<molecule molID=\"" << molID << "\" id=\"" << id << "\" role=\""
      << roleName << "\" atomRefs=\""
      << boost::algorithm::join(getAtomList(), " ") << "\" title=\"" << title
      << "\" connect=\"" << connect << "\" correspondence=\"" << correspondence
      << "\" bondList=\"" << boost::algorithm::join(getBondList(), " ")
      << "\"/>";

  return out.str();
}

ptree MarvinSruCoModSgroup::toPtree() const {
  ptree out = MarvinMolBase::toPtree();

  out.put("<xmlattr>.atomRefs", boost::algorithm::join(getAtomList(), " "));
  out.put("<xmlattr>.title", title);
  out.put("<xmlattr>.connect", connect);
  out.put("<xmlattr>.correspondence", correspondence);
  out.put("<xmlattr>.bondList", boost::algorithm::join(getBondList(), " "));

  return out;
}

MarvinMolBase *getActualParent(const MarvinMolBase *child) {
  PRECONDITION(child, "child cannot be null");
  for (auto actualParent = child->parent;;
       actualParent = actualParent->parent) {
    TEST_ASSERT(actualParent);

    if (actualParent->role() != "MultipleSgroup") {
      return actualParent;
      ;
    }
  }

  TEST_ASSERT(false);  // should not be reachable
}

MarvinMolBase *MarvinSruCoModSgroup::copyMol(
    const std::string &idAppendage) const {
  auto outSgroup = new MarvinSruCoModSgroup(this->roleName, this->parent);
  this->parent->sgroups.emplace_back(outSgroup);

  outSgroup->molID = this->molID + idAppendage;
  outSgroup->title = this->title;
  outSgroup->connect = this->connect;
  outSgroup->correspondence = this->correspondence;

  auto actualParent = getActualParent(this);

  // the only time this is to be called is when a multiple group above it is
  // being expanded and the new atoms and bonds have already been made
  //  here we just need to find them and add refs to the new multiple sgroup

  for (auto atomToCopy : atoms) {
    auto atomIndex = actualParent->getAtomIndex(atomToCopy->id + idAppendage);
    if (atomIndex < 0) {
      throw FileParseException(
          "unexpected error - new atom not found in parent");
    }

    outSgroup->atoms.push_back(actualParent->atoms[atomIndex]);
  }

  for (auto bondToCopy : bonds) {
    auto bondIndex = actualParent->getBondIndex(bondToCopy->id + idAppendage);
    if (bondIndex < 0) {
      throw FileParseException(
          "unexpected error - new bond not found in parent");
    }

    outSgroup->bonds.push_back(actualParent->bonds[bondIndex]);
  }

  return outSgroup;
}

std::string MarvinSruCoModSgroup::role() const { return roleName; }

bool MarvinSruCoModSgroup::hasAtomBondBlocks() const { return false; }

MarvinDataSgroup::MarvinDataSgroup(MarvinMolBase *parentInit) {
  parent = parentInit;
}

MarvinDataSgroup::MarvinDataSgroup(MarvinMolBase *parentInit, ptree &molTree) {
  PRECONDITION(parentInit != nullptr, "parentInit cannot be null");
  parent = parentInit;

  this->id = molTree.get<std::string>("<xmlattr>.id", "");
  if (this->id == "") {
    throw FileParseException("Expected a iD in MRV file");
  }
  this->molID = molTree.get<std::string>("<xmlattr>.molID", "");
  if (this->molID == "") {
    throw FileParseException("Expected a molID in MRV file");
  }

  std::string atomRefsStr = molTree.get<std::string>("<xmlattr>.atomRefs", "");
  if (atomRefsStr == "") {
    throw FileParseException(
        "Expected  atomRefs for a DataSgroup definition in MRV file");
  }

  std::vector<std::string> atomList;
  boost::algorithm::split(atomList, atomRefsStr, boost::algorithm::is_space());
  for (auto &it : atomList) {
    auto atomPtr = this->parent->findAtomByRef(it);

    if (atomPtr == nullptr) {
      throw FileParseException(
          "AtomRef specification for a DataSgroup definition was not found in any parent");
    }

    this->atoms.push_back(atomPtr);
  }

  this->context = molTree.get<std::string>("<xmlattr>.context", "");

  this->fieldName = molTree.get<std::string>("<xmlattr>.fieldName", "");
  this->placement = molTree.get<std::string>("<xmlattr>.placement", "");

  this->unitsDisplayed = molTree.get<std::string>("<xmlattr>.unitsDisplayed",
                                                  "Unit not displayed");
  if (this->unitsDisplayed == "") {
    this->unitsDisplayed = "Unit not displayed";
  }
  std::string unitsDisplayed =
      boost::algorithm::to_lower_copy(this->unitsDisplayed);

  if (unitsDisplayed != "unit displayed" &&
      unitsDisplayed != "unit not displayed") {
    throw FileParseException(
        "Expected unitsDisplayed to be either \"Unit displayed\" or \"Unit not displayed\" for a DataSgroup definition in MRV file");
  }

  this->queryType = molTree.get<std::string>("<xmlattr>.queryType", "");
  this->queryOp = molTree.get<std::string>("<xmlattr>.queryOp", "");
  this->units = molTree.get<std::string>("<xmlattr>.units", "");

  this->fieldData = molTree.get<std::string>("<xmlattr>.fieldData", "");

  std::string x = molTree.get<std::string>("<xmlattr>.x", "0.0");
  std::string y = molTree.get<std::string>("<xmlattr>.y", "0.0");

  if (x == "") {
    throw FileParseException(
        "Expected x for a DataSgroup definition in MRV file");
  }
  if (!getCleanNumber(x, this->x)) {
    throw FileParseException(
        "The value for x must be a floating point value in MRV file");
  }
  if (y == "") {
    throw FileParseException(
        "Expected y for a DataSgroup definition in MRV file");
  }
  if (!getCleanNumber(y, this->y)) {
    throw FileParseException(
        "The value for y must be a floating point value in MRV file");
  }
}

MarvinMolBase *MarvinDataSgroup::copyMol(const std::string &idAppendage) const {
  auto outSgroup = new MarvinDataSgroup(this->parent);
  this->parent->sgroups.emplace_back(outSgroup);

  outSgroup->molID = this->molID + idAppendage;
  outSgroup->id = this->id + idAppendage;
  outSgroup->context = this->context;
  outSgroup->fieldName = this->fieldName;
  outSgroup->placement = this->placement;
  outSgroup->unitsDisplayed = this->unitsDisplayed;
  outSgroup->units = this->units;
  outSgroup->fieldData = this->fieldData;
  outSgroup->queryType = this->queryType;
  outSgroup->queryOp = this->queryOp;
  outSgroup->x = this->x;
  outSgroup->y = this->y;

  // the only time this is to be called is when a multiple group above it is
  // being expanded and the new atoms and bonds have already been made
  //  here we just need to find them and add refs to the new multiple sgroup

  for (auto atomToCopy : atoms) {
    auto atomIndex = this->parent->getAtomIndex(atomToCopy->id + idAppendage);
    if (atomIndex < 0) {
      throw FileParseException(
          "unexpected error - new atom not found in parent");
    }

    outSgroup->atoms.push_back(this->parent->atoms[atomIndex]);
  }

  return outSgroup;
}

std::string MarvinDataSgroup::toString() const {
  std::ostringstream out;

  out << "<molecule molID=\"" << molID << "\" id=\"" << id
      << "\" role=\"DataSgroup\" atomRefs=\""
      << boost::algorithm::join(getAtomList(), " ") << "\" context=\""
      << context << "\" fieldName=\"" << fieldName << "\" placement=\""
      << placement << "\" unitsDisplayed=\"" << unitsDisplayed
      << "\" fieldData=\"" << fieldData;

  if (units != "") {
    out << "\" units=\"" << units;
  }

  if (queryType != "" && queryOp != "") {
    out << "\" queryType=\"" << queryType << "\" queryOp=\""
        << boost::property_tree::xml_parser::encode_char_entities(queryOp);
  }

  out << "\" x=\"" << x << "\" y=\"" << y << "\"/>";

  return out.str();
}

ptree MarvinDataSgroup::toPtree() const {
  ptree out = MarvinMolBase::toPtree();

  out.put("<xmlattr>.atomRefs", boost::algorithm::join(getAtomList(), " "));
  out.put("<xmlattr>.context", context);
  out.put("<xmlattr>.fieldName", fieldName);
  out.put("<xmlattr>.placement", placement);
  out.put("<xmlattr>.unitsDisplayed", unitsDisplayed);
  out.put("<xmlattr>.fieldData", fieldData);

  if (units != "") {
    out.put("<xmlattr>.units", units);
  }

  if (queryType != "" && queryOp != "") {
    out.put("<xmlattr>.queryType", queryType);
    out.put("<xmlattr>.queryOp", queryOp);
  }
  std::ostringstream xstr, ystr;
  xstr << x;
  ystr << y;
  out.put("<xmlattr>.x", xstr.str());
  out.put("<xmlattr>.y", ystr.str());

  return out;
}

std::string MarvinDataSgroup::role() const { return "DataSgroup"; }

bool MarvinDataSgroup::hasAtomBondBlocks() const { return false; }

MarvinMultipleSgroup::MarvinMultipleSgroup(MarvinMolBase *parentInit) {
  parent = parentInit;
}

MarvinMultipleSgroup::MarvinMultipleSgroup(MarvinMolBase *parentInit,
                                           ptree &molTree) {
  PRECONDITION(parentInit != nullptr, "parentInit cannot be null");
  parent = parentInit;
  this->id = molTree.get<std::string>("<xmlattr>.id", "");
  if (this->id == "") {
    throw FileParseException("Expected a iD in MRV file");
  }
  this->molID = molTree.get<std::string>("<xmlattr>.molID", "");
  if (this->molID == "") {
    throw FileParseException("Expected a molID in MRV file");
  }

  // first make sure this can be made into a proper MultipleSgroup.
  // To be valid, the title must be a positive integer and there must be
  // exactly two bonds the connect to the repeating group

  std::string atomRefsStr = molTree.get<std::string>("<xmlattr>.atomRefs", "");
  if (atomRefsStr == "") {
    throw FileParseException(
        "Expected  atomRefs for a MultipleSgroup definition in MRV file");
  }

  std::vector<std::string> atomList;
  boost::algorithm::split(atomList, atomRefsStr, boost::algorithm::is_space());
  for (auto &it : atomList) {
    auto atomPtr = this->parent->findAtomByRef(it);

    if (atomPtr == nullptr) {
      throw FileParseException(
          "AtomRef specification for a MultipleSgroup definition was not found in any parent");
    }

    this->atoms.push_back(atomPtr);
    this->parentAtoms.push_back(atomPtr);
  }

  this->title = molTree.get<std::string>("<xmlattr>.title", "");
  int testInt;
  if (this->title == "" || !getCleanNumber(this->title, testInt) ||
      testInt <= 0) {
    throw FileParseException(
        "Expected a positive integer title for a MultipleSgroup definition in MRV file");
  }
}

std::string MarvinMultipleSgroup::role() const { return "MultipleSgroup"; }

bool MarvinMultipleSgroup::hasAtomBondBlocks() const { return false; }

MarvinMolBase *MarvinMultipleSgroup::copyMol(
    const std::string &idAppendage) const {
  auto outSgroup = new MarvinMultipleSgroup(this->parent);
  this->parent->sgroups.emplace_back(outSgroup);

  outSgroup->molID = this->molID + idAppendage;
  outSgroup->id = this->id + idAppendage;
  outSgroup->title = this->title;

  // the only time this is to be called is when a multiple group above it is
  // being expanded and the new atoms and bonds have already been made
  //  here we just need to find them and add refs to the new multiple sgroup

  for (auto atomToCopy : atoms) {
    auto atomIndex = this->parent->getAtomIndex(atomToCopy->id + idAppendage);
    if (atomIndex < 0) {
      throw FileParseException(
          "unexpected error - new atom not found in parent");
    }

    outSgroup->atoms.push_back(this->parent->atoms[atomIndex]);
  }

  for (auto atomToCopy : parentAtoms) {
    auto atomIndex = this->parent->getAtomIndex(atomToCopy->id + idAppendage);
    if (atomIndex < 0) {
      throw FileParseException(
          "unexpected error - new atom not found in parent");
    }

    outSgroup->parentAtoms.push_back(this->parent->atoms[atomIndex]);
  }

  for (auto bondToCopy : bonds) {
    auto bondIndex = this->parent->getBondIndex(bondToCopy->id + idAppendage);
    if (bondIndex < 0) {
      throw FileParseException(
          "unexpected error - new bond not found in parent");
    }

    outSgroup->bonds.push_back(this->parent->bonds[bondIndex]);
  }

  outSgroup->isExpanded = isExpanded;

  return outSgroup;
}

std::string MarvinMultipleSgroup::toString() const {
  std::ostringstream out;

  out << "<molecule molID=\"" << molID << "\" id=\"" << id
      << "\" role=\"MultipleSgroup\" atomRefs=\""
      << boost::algorithm::join(getAtomList(), " ") << "\" title=\"" << title
      << "\">";

  for (auto &sgroup : sgroups) {
    out << sgroup->toString();
  }

  out << "</molecule>";

  return out.str();
}

ptree MarvinMultipleSgroup::toPtree() const {
  ptree out = MarvinMolBase::toPtree();

  out.put("<xmlattr>.atomRefs", boost::algorithm::join(getAtomList(), " "));
  out.put("<xmlattr>.title", title);

  MarvinMolBase::addSgroupsToPtree(out);

  return out;
}

MarvinMulticenterSgroup::MarvinMulticenterSgroup(MarvinMolBase *parentInit) {
  PRECONDITION(parentInit != nullptr, "parentInit cannot be null");
  parent = parentInit;
}

MarvinMulticenterSgroup::MarvinMulticenterSgroup(MarvinMolBase *parentInit,
                                                 ptree &molTree) {
  PRECONDITION(parentInit != nullptr, "parentInit cannot be null");
  parent = parentInit;
  this->id = molTree.get<std::string>("<xmlattr>.id", "");
  if (this->id == "") {
    throw FileParseException("Expected a iD in MRV file");
  }
  this->molID = molTree.get<std::string>("<xmlattr>.molID", "");
  if (this->molID == "") {
    throw FileParseException("Expected a molID in MRV file");
  }

  std::string atomRefsStr = molTree.get<std::string>("<xmlattr>.atomRefs", "");
  if (atomRefsStr == "") {
    throw FileParseException(
        "Expected  atomRefs for a MulticenterSgroup definition in MRV file");
  }

  std::vector<std::string> atomList;
  boost::algorithm::split(atomList, atomRefsStr, boost::algorithm::is_space());
  for (auto &it : atomList) {
    auto atomPtr = this->parent->findAtomByRef(it);

    if (atomPtr == nullptr) {
      throw FileParseException(
          "AtomRef specification for a MulticenterSgroup definition was not found in any parent");
    }

    this->atoms.push_back(atomPtr);
  }

  std::string centerId = molTree.get<std::string>("<xmlattr>.center", "");

  auto atomPtr = this->parent->findAtomByRef(centerId);

  if (atomPtr == nullptr) {
    throw FileParseException(
        "Center specification for a MulticenterSgroup definition was not found in any parent");
  }

  this->center = atomPtr;
}

std::string MarvinMulticenterSgroup::role() const {
  return "MulticenterSgroup";
}

bool MarvinMulticenterSgroup::hasAtomBondBlocks() const { return false; }

MarvinMolBase *MarvinMulticenterSgroup::copyMol(
    const std::string &idAppendage) const {
  auto outSgroup = new MarvinMulticenterSgroup(this->parent);
  this->parent->sgroups.emplace_back(outSgroup);

  outSgroup->molID = this->molID + idAppendage;
  outSgroup->id = this->id;

  // the only time this is to be called is when a multiple group above it is
  // being expanded and the new atoms and bonds have already been made
  //  here we just need to find them and add refs to the new multiple sgroup

  for (auto atomToCopy : atoms) {
    auto atomIndex = this->parent->getAtomIndex(atomToCopy->id + idAppendage);
    if (atomIndex < 0) {
      throw FileParseException(
          "unexpected error - new atom not found in parent");
    }

    outSgroup->atoms.push_back(this->parent->atoms[atomIndex]);
  }

  auto centerIndex = this->parent->getAtomIndex(this->center->id + idAppendage);
  if (centerIndex < 0) {
    throw FileParseException("unexpected error - new atom not found in parent");
  }
  outSgroup->center = this->parent->atoms[centerIndex];

  return outSgroup;
}

std::string MarvinMulticenterSgroup::toString() const {
  // <molecule molID="m2" id="sg1" role="MulticenterSgroup" atomRefs="a2 a6
  // a5 a4 a3" center="a18"/>
  std::ostringstream out;

  out << "<molecule molID=\"" << molID << "\" id=\"" << id
      << "\" role=\"MulticenterSgroup\" atomRefs=\""
      << boost::algorithm::join(getAtomList(), " ") << "\" center=\""
      << center->id << "\"/>";

  return out.str();
}

ptree MarvinMulticenterSgroup::toPtree() const {
  ptree out = MarvinMolBase::toPtree();

  out.put("<xmlattr>.atomRefs", boost::algorithm::join(getAtomList(), " "));
  out.put("<xmlattr>.center", center->id);

  return out;
}

MarvinGenericSgroup::MarvinGenericSgroup(MarvinMolBase *parentInit) {
  PRECONDITION(parentInit != nullptr, "parentInit cannot be null");
  parent = parentInit;
}

MarvinGenericSgroup::MarvinGenericSgroup(MarvinMolBase *parentInit,
                                         ptree &molTree) {
  PRECONDITION(parentInit != nullptr, "parentInit cannot be null");
  parent = parentInit;
  this->id = molTree.get<std::string>("<xmlattr>.id", "");
  if (this->id == "") {
    throw FileParseException("Expected a iD in MRV file");
  }
  this->molID = molTree.get<std::string>("<xmlattr>.molID", "");
  if (this->molID == "") {
    throw FileParseException("Expected a molID in MRV file");
  }

  std::string atomRefsStr = molTree.get<std::string>("<xmlattr>.atomRefs", "");
  if (atomRefsStr == "") {
    throw FileParseException(
        "Expected  atomRefs for a GenericSgroup definition in MRV file");
  }

  std::vector<std::string> atomList;
  boost::algorithm::split(atomList, atomRefsStr, boost::algorithm::is_space());
  for (auto &it : atomList) {
    auto atomPtr = this->parent->findAtomByRef(it);

    if (atomPtr == nullptr) {
      throw FileParseException(
          "AtomRef specification for a GenericSgroup definition was not found in any parent");
    }

    this->atoms.push_back(atomPtr);
  }

  this->charge = molTree.get<std::string>("<xmlattr>.charge", "");
  if (this->charge != "onAtoms" && this->charge != "onBracket") {
    throw FileParseException(
        "Expected  omAtoms or onBracket for a charge attr of a GenericSgroup definition in MRV file");
  }
}

std::string MarvinGenericSgroup::role() const { return "GenericSgroup"; }

bool MarvinGenericSgroup::hasAtomBondBlocks() const { return false; }

MarvinMolBase *MarvinGenericSgroup::copyMol(
    const std::string &idAppendage) const {
  auto outSgroup = new MarvinGenericSgroup(this->parent);
  this->parent->sgroups.emplace_back(outSgroup);

  outSgroup->molID = this->molID + idAppendage;
  outSgroup->id = this->id + idAppendage;

  // the only time this is to be called is when a multiple group above it is
  // being expanded and the new atoms and bonds have already been made
  //  here we just need to find them and add refs to the new multiple sgroup

  for (auto atomToCopy : atoms) {
    auto atomIndex = this->parent->getAtomIndex(atomToCopy->id + idAppendage);
    if (atomIndex < 0) {
      throw FileParseException(
          "unexpected error - new atom not found in parent");
    }

    outSgroup->atoms.push_back(this->parent->atoms[atomIndex]);
  }

  return outSgroup;
}

std::string MarvinGenericSgroup::toString() const {
  // <molecule molID="m2" id="sg1" role="MulticenterSgroup" atomRefs="a2 a6
  // a5 a4 a3" center="a18"/>
  std::ostringstream out;

  out << "<molecule molID=\"" << molID << "\" id=\"" << id
      << "\" role=\"GenericSgroup\" atomRefs=\""
      << boost::algorithm::join(getAtomList(), " ") << "\"/>";

  return out.str();
}

ptree MarvinGenericSgroup::toPtree() const {
  ptree out = MarvinMolBase::toPtree();

  out.put("<xmlattr>.atomRefs", boost::algorithm::join(getAtomList(), " "));

  return out;
}

MarvinMonomerSgroup::MarvinMonomerSgroup(MarvinMolBase *parentInit) {
  PRECONDITION(parentInit != nullptr, "parentInit cannot be null");
  parent = parentInit;
}

MarvinMonomerSgroup::MarvinMonomerSgroup(MarvinMolBase *parentInit,
                                         ptree &molTree) {
  PRECONDITION(parentInit != nullptr, "parentInit cannot be null");
  parent = parentInit;
  this->id = molTree.get<std::string>("<xmlattr>.id", "");
  if (this->id == "") {
    throw FileParseException("Expected a iD in MRV file");
  }
  this->molID = molTree.get<std::string>("<xmlattr>.molID", "");
  if (this->molID == "") {
    throw FileParseException("Expected a molID in MRV file");
  }

  std::string atomRefsStr = molTree.get<std::string>("<xmlattr>.atomRefs", "");
  if (atomRefsStr == "") {
    throw FileParseException(
        "Expected  atomRefs for a MonomerSgroup definition in MRV file");
  }

  std::vector<std::string> atomList;
  boost::algorithm::split(atomList, atomRefsStr, boost::algorithm::is_space());
  for (auto &it : atomList) {
    auto atomPtr = this->parent->findAtomByRef(it);

    if (atomPtr == nullptr) {
      throw FileParseException(
          "AtomRef specification for a MonomerSgroup definition was not found in any parent");
    }

    this->atoms.push_back(atomPtr);
  }

  this->title = molTree.get<std::string>("<xmlattr>.title", "");
  if (this->title == "") {
    throw FileParseException(
        "Expected  title for a MonomerSgroup definition in MRV file");
  }
  this->charge = molTree.get<std::string>("<xmlattr>.charge", "");
  if (this->charge == "") {
    throw FileParseException(
        "Expected  omAtoms or onBracket for a charge attr of a MonomerSgroup definition in MRV file");
  }
}

std::string MarvinMonomerSgroup::role() const { return "MonomerSgroup"; }

bool MarvinMonomerSgroup::hasAtomBondBlocks() const { return false; }

MarvinMolBase *MarvinMonomerSgroup::copyMol(
    const std::string &idAppendage) const {
  auto outSgroup = new MarvinMonomerSgroup(this->parent);
  this->parent->sgroups.emplace_back(outSgroup);

  outSgroup->molID = this->molID + idAppendage;
  outSgroup->id = this->id + idAppendage;
  outSgroup->title = this->title;
  outSgroup->charge = this->charge;

  // the only time this is to be called is when a multiple group above it is
  // being expanded and the new atoms and bonds have already been made
  //  here we just need to find them and add refs to the new multiple sgroup

  for (auto atomToCopy : atoms) {
    auto atomIndex = this->parent->getAtomIndex(atomToCopy->id + idAppendage);
    if (atomIndex < 0) {
      throw FileParseException(
          "unexpected error - new atom not found in parent");
    }

    outSgroup->atoms.push_back(this->parent->atoms[atomIndex]);
  }

  return outSgroup;
}

std::string MarvinMonomerSgroup::toString() const {
  // <molecule id="sg1" role="MonomerSgroup" title="mon" charge="onAtoms"
  // molID="m2" atomRefs="a2 a1 a3 a4">
  // </molecule>

  std::ostringstream out;

  out << "<molecule molID=\"" << molID << "\" id=\"" << id
      << "\" role=\"MonomerSgroup\" atomRefs=\""
      << boost::algorithm::join(getAtomList(), " ") << "\" title=\"" << title
      << "\" charge=\"" << charge << "\">"
      << "</molecule>";

  return out.str();
}

ptree MarvinMonomerSgroup::toPtree() const {
  ptree out = MarvinMolBase::toPtree();

  out.put("<xmlattr>.atomRefs", boost::algorithm::join(getAtomList(), " "));
  out.put("<xmlattr>.title", title);
  out.put("<xmlattr>.charge", charge);

  return out;
}

MarvinSuperatomSgroupExpanded::MarvinSuperatomSgroupExpanded(
    MarvinMolBase *parentInit) {
  PRECONDITION(parentInit != nullptr, "parentInit cannot be null");
  parent = parentInit;
}

MarvinSuperatomSgroupExpanded::MarvinSuperatomSgroupExpanded(
    MarvinMolBase *parentInit, ptree &molTree) {
  PRECONDITION(parentInit != nullptr, "parentInit cannot be null");
  parent = parentInit;
  this->id = molTree.get<std::string>("<xmlattr>.id", "");
  if (this->id == "") {
    throw FileParseException("Expected a iD in MRV file");
  }
  this->molID = molTree.get<std::string>("<xmlattr>.molID", "");
  if (this->molID == "") {
    throw FileParseException("Expected a molID in MRV file");
  }

  std::string atomRefs = molTree.get<std::string>("<xmlattr>.atomRefs", "");
  if (atomRefs != "") {
    std::vector<std::string> atomList;
    boost::algorithm::split(atomList, atomRefs, boost::algorithm::is_space());
    for (auto &it : atomList) {
      auto atomPtr = this->parent->findAtomByRef(it);

      if (atomPtr == nullptr) {
        throw FileParseException(
            "AtomRef specification for an SuperatomSgroupExpanded group definition was not found in any parent");
      }
      this->atoms.push_back(atomPtr);
    }
  } else  // must have no atomRefs nor AtomArray - get the atoms from
          // the parent block - the ones that reference this
          // superSgroup
  {
    for (MarvinAtom *atom : parent->atoms) {
      if (atom->sgroupRef == this->id) {
        this->atoms.push_back(atom);
      }
    }
  }

  this->title = molTree.get<std::string>("<xmlattr>.title", "");
  if (this->title == "") {
    throw FileParseException(
        "Expected  title for a SuperatomSgroupExpanded definition in MRV file");
  }
}

MarvinSuperatomSgroupExpanded::~MarvinSuperatomSgroupExpanded() {}

MarvinMolBase *MarvinSuperatomSgroupExpanded::copyMol(
    const std::string &idAppendage) const {
  auto outSgroup = new MarvinSuperatomSgroupExpanded(this->parent);
  this->parent->sgroups.emplace_back(outSgroup);

  outSgroup->molID = this->molID + idAppendage;
  outSgroup->id = this->id + idAppendage;
  outSgroup->title = this->title;

  auto actualParent = getActualParent(this);

  // the only time this is to be called is when a multiple group above it is
  // being expanded and the new atoms and bonds have already been made
  //  here we just need to find them and add refs to the new multiple sgroup

  for (auto atomToCopy : atoms) {
    auto atomIndex = actualParent->getAtomIndex(atomToCopy->id + idAppendage);
    if (atomIndex < 0) {
      throw FileParseException(
          "unexpected error - new atom not found in parent");
    }

    outSgroup->atoms.push_back(actualParent->atoms[atomIndex]);
  }

  for (auto bondToCopy : bonds) {
    auto bondIndex = actualParent->getBondIndex(bondToCopy->id + idAppendage);
    if (bondIndex < 0) {
      throw FileParseException(
          "unexpected error - new bond not found in parent");
    }

    outSgroup->bonds.push_back(actualParent->bonds[bondIndex]);
  }

  return outSgroup;
}

std::string MarvinSuperatomSgroupExpanded::toString() const {
  std::ostringstream out;

  out << "<molecule molID=\"" << molID << "\" id=\"" << id
      << "\" role=\"SuperatomSgroup\" atomRefs=\""
      << boost::algorithm::join(getAtomList(), " ") << "\" title=\"" << title
      << "\"/>";

  return out.str();
}

ptree MarvinSuperatomSgroupExpanded::toPtree() const {
  ptree out = MarvinMolBase::toPtree();

  out.put("<xmlattr>.atomRefs", boost::algorithm::join(getAtomList(), " "));
  out.put("<xmlattr>.title", title);
  return out;
}

std::string MarvinSuperatomSgroupExpanded::role() const {
  return "SuperatomSgroupExpanded";
}

bool MarvinSuperatomSgroupExpanded::hasAtomBondBlocks() const { return false; }

MarvinSuperatomSgroup::MarvinSuperatomSgroup(MarvinMolBase *parentInit) {
  PRECONDITION(parentInit != nullptr, "parentInit cannot be null");
  parent = parentInit;
}

MarvinSuperatomSgroup::MarvinSuperatomSgroup(MarvinMolBase *parentInit,
                                             ptree &molTree) {
  PRECONDITION(parentInit != nullptr, "parentInit cannot be null");
  parent = parentInit;
  this->id = molTree.get<std::string>("<xmlattr>.id", "");
  if (this->id == "") {
    throw FileParseException("Expected a iD in MRV file");
  }
  this->molID = molTree.get<std::string>("<xmlattr>.molID", "");
  if (this->molID == "") {
    throw FileParseException("Expected a molID in MRV file");
  }

  this->title = molTree.get<std::string>("<xmlattr>.title", "");
  if (this->title == "") {
    throw FileParseException(
        "Expected  title for a SuperatomSgroup definition in MRV file");
  }

  this->parseAtomsAndBonds(molTree);

  bool found;

  try {
    boost::property_tree::ptree AttachmentPointArrayTree =
        molTree.get_child("AttachmentPointArray");
    found = true;
  } catch (const std::exception &e) {
    found = false;
  }

  if (found) {
    for (auto &v : molTree.get_child("AttachmentPointArray")) {
      std::string bondId = v.second.get<std::string>("<xmlattr>.bond", "");
      if (bondId == "") {  // this can happen if the attachment point is
                           // not actually used - as in Amino acids that
                           // have non-used crosslink atoms
        continue;
      }

      auto &marvinAttachmentPoint =
          this->attachmentPoints.emplace_back(new MarvinAttachmentPoint);

      marvinAttachmentPoint->atom =
          v.second.get<std::string>("<xmlattr>.atom", "");
      marvinAttachmentPoint->order =
          v.second.get<std::string>("<xmlattr>.order", "");
      marvinAttachmentPoint->bond = bondId;

      if (marvinAttachmentPoint->atom == "" ||
          marvinAttachmentPoint->order == "") {
        throw FileParseException(
            "Expected atom, order and bond, for an AttachmentPoint definition in MRV file");
      }
      if (std::find_if(atoms.begin(), atoms.end(),
                       [&marvinAttachmentPoint](auto a) {
                         return a->id == marvinAttachmentPoint->atom;
                       }) == atoms.end()) {
        throw FileParseException(
            "Atom specification for an AttachmentPoint definition must be in the parent's atom array in MRV file");
      }

      // bond must be found in the  bonds vector

      if (this->parent->findBondByRef(marvinAttachmentPoint->bond) == nullptr) {
        throw FileParseException(
            "Bond specification for an AttachmentPoint definition must be in the bond array in MRV file");
      }

      // the order must be an integer

      int orderInt;
      if (!getCleanNumber(marvinAttachmentPoint->order, orderInt)) {
        throw FileParseException(
            "Order for an AttachmentPoint definition must be an integer in MRV file");
      }
    }
  }
}

MarvinSuperatomSgroup::~MarvinSuperatomSgroup() {
  this->attachmentPoints.clear();
}

std::string MarvinSuperatomSgroup::role() const { return "SuperatomSgroup"; }

bool MarvinSuperatomSgroup::hasAtomBondBlocks() const { return true; }

MarvinMolBase *MarvinSuperatomSgroup::copyMol(const std::string &) const {
  PRECONDITION(0, "Internal error:  copying a SuperatomSgroup");
}

std::string MarvinSuperatomSgroup::toString() const {
  std::ostringstream out;

  out << "<molecule molID=\"" << molID << "\" id=\"" << id
      << "\" role=\"SuperatomSgroup\" title=\"" << title << "\">";

  out << "<atomArray>";
  for (auto atom : atoms) {
    out << atom->toString();
  }
  out << "</atomArray>";

  out << "<bondArray>";
  for (auto bond : bonds) {
    out << bond->toString();
  }
  out << "</bondArray>";

  if (attachmentPoints.size() > 0) {
    out << "<AttachmentPointArray>";
    for (auto &attachmentPoint : attachmentPoints) {
      out << attachmentPoint->toString();
    }
    out << "</AttachmentPointArray>";
  }

  for (auto &sgroup : sgroups) {
    out << sgroup->toString();
  }

  out << "</molecule>";

  return out.str();
}

ptree MarvinSuperatomSgroup::toPtree() const {
  ptree out = MarvinMolBase::toPtree();

  out.put("<xmlattr>.title", title);

  if (attachmentPoints.size() > 0) {
    ptree attachmentpointArray;
    for (auto &attachmentPoint : attachmentPoints) {
      attachmentpointArray.add_child("attachmentPoint",
                                     attachmentPoint->toPtree());
    }
    out.put_child("AttachmentPointArray", attachmentpointArray);
  }
  MarvinMolBase::addSgroupsToPtree(out);

  return out;
}

MarvinMol::MarvinMol() { parent = nullptr; }
MarvinMol::MarvinMol(ptree &molTree) {
  parent = nullptr;

  // get atoms if this mol is supposed to have them

  this->parseAtomsAndBonds(molTree);
}

MarvinMol::~MarvinMol() {}

std::string MarvinMol::role() const { return "MarvinMol"; }

bool MarvinMol::hasAtomBondBlocks() const { return true; }

void MarvinMol::pushOwnedAtom(MarvinAtom *atom) {
  PRECONDITION(atom, "bad atom");
  ownedAtoms.emplace_back(atom);
}

void MarvinMol::pushOwnedBond(MarvinBond *bond) {
  PRECONDITION(bond, "bad bond");
  ownedBonds.emplace_back(bond);
}

void MarvinMol::removeOwnedAtom(MarvinAtom *atom) {
  PRECONDITION(atom != nullptr, "atom cannot be null");
  eraseUniquePtr<MarvinAtom>(ownedAtoms, atom);
}

void MarvinMol::removeOwnedBond(MarvinBond *bond) {
  PRECONDITION(bond != nullptr, "bond cannot be null");
  eraseUniquePtr<MarvinBond>(ownedBonds, bond);
}

void MarvinMolBase::cleanUpSgNumbering(
    int &sgCount, std::map<std::string, std::string> &sgMap) {
  for (auto &sgroup : this->sgroups) {
    std::string newId = "sg" + std::to_string(++sgCount);
    sgMap[sgroup->id] = newId;
    sgroup->id = newId;

    sgroup->cleanUpSgNumbering(sgCount, sgMap);
  }
}

void MarvinSuperatomSgroup::cleanUpNumberingMolsAtomsBonds(
    int &molCount,   // this is the starting mol count, and receives the
                     // ending mol count - THis is used when
                     // MarvinMol->convertToSuperAtoms is called multiple
                     // times from a RXN
    int &atomCount,  // starting and ending atom count
    int &bondCount,  // starting and ending bond count
    std::map<std::string, std::string> &sgMap,
    std::map<std::string, std::string> &atomMap,
    std::map<std::string, std::string> &bondMap) {
  // the common part for all classes
  MarvinMolBase::cleanUpNumberingMolsAtomsBonds(molCount, atomCount, bondCount,
                                                sgMap, atomMap, bondMap);

  // the specific part for this class
  auto marvinSuperatomSgroup = (MarvinSuperatomSgroup *)this;
  for (auto &attachmentPoint : marvinSuperatomSgroup->attachmentPoints) {
    attachmentPoint->atom = atomMap[attachmentPoint->atom];
    attachmentPoint->bond =
        bondMap[attachmentPoint->bond];  // bond is actually in the parent
  }
}

void MarvinMolBase::cleanUpNumberingMolsAtomsBonds(
    int &molCount,   // this is the starting mol count, and receives the
                     // ending mol count - THis is used when
                     // MarvinMol->convertToSuperAtoms is called multiple
                     // times from a RXN
    int &atomCount,  // starting and ending atom count
    int &bondCount,  // starting and ending bond count)
    std::map<std::string, std::string> &sgMap,
    std::map<std::string, std::string> &atomMap,
    std::map<std::string, std::string> &bondMap) {
  // clean up the mol ids, the atomIds and bondIds.  make  map of the old to
  // new atom ids and bond ids

  this->molID = "m" + std::to_string(++molCount);

  if (this->hasAtomBondBlocks()) {
    for (auto atomPtr : this->atoms) {
      std::string newId = "a" + std::to_string(++atomCount);
      atomMap[atomPtr->id] = newId;
      atomPtr->id = newId;

      // fix the sgroupRef
      if (atomPtr->sgroupRef != "") {
        atomPtr->sgroupRef = sgMap[atomPtr->sgroupRef];
      }
    }

    for (auto bondPtr : this->bonds) {
      std::string newId = "b" + std::to_string(++bondCount);
      bondMap[bondPtr->id] = newId;
      bondPtr->id = newId;

      // fix the bond's references to atoms

      bondPtr->atomRefs2[0] = atomMap[bondPtr->atomRefs2[0]];
      bondPtr->atomRefs2[1] = atomMap[bondPtr->atomRefs2[1]];
    }
  }

  // Now the sgroups

  for (auto &sgroup : sgroups) {
    sgroup->cleanUpNumberingMolsAtomsBonds(molCount, atomCount, bondCount,
                                           sgMap, atomMap, bondMap);
  }
}

void MarvinMolBase::cleanUpNumbering(
    int &molCount  // this is the starting mol count, and receives the
                   // ending mol count - THis is used when
                   // MarvinMol->convertToSuperAtoms is called multiple
                   // times from a RXN
    ,
    int &atomCount  // starting and ending atom count
    ,
    int &bondCount  // starting and ending bond count
    ,
    int &sgCount  // starting and ending sg  count)
    ,
    std::map<std::string, std::string>
        &sgMap  // map from old sg number to new sg number
    ,
    std::map<std::string, std::string>
        &atomMap  // map from old atom number to new atom number
    ,
    std::map<std::string, std::string>
        &bondMap  // map from old bond number to new bond number
)

{
  this->cleanUpSgNumbering(sgCount, sgMap);
  this->cleanUpNumberingMolsAtomsBonds(molCount, atomCount, bondCount, sgMap,
                                       atomMap, bondMap);
}

bool MarvinMolBase::AnyOverLappingAtoms(const MarvinMolBase *otherMol) const {
  PRECONDITION(otherMol != nullptr, "otherMol cannot be null");
  std::vector<std::string> firstList = getAtomList();
  std::sort(firstList.begin(), firstList.end());
  std::vector<std::string> secondList = otherMol->getAtomList();
  std::sort(secondList.begin(), secondList.end());
  std::vector<std::string> intersection;
  std::set_intersection(firstList.begin(), firstList.end(), secondList.begin(),
                        secondList.end(), back_inserter(intersection));

  return intersection.size() > 0;
}

// the following routine determines if a sgroup role is passive when
// expanding in preparation for creating an RDKit mol.  sgroups are NOT
// passive if they create atoms or bonds in the parent when expanding

bool MarvinMolBase::isPassiveRoleForExpansion() const {
  // some derived classes override this and return false
  return true;
}

bool MarvinSuperatomSgroup::isPassiveRoleForExpansion() const { return false; }

bool MarvinMultipleSgroup::isPassiveRoleForExpansion() const { return false; }

// this routine determines if the sgroup is passive for contraction, whern
// coming from an RDKit mol to a Marvin Mol
//  It is NOT passive if atoms in the parent are removed by contracting it.

bool MarvinMolBase::isPassiveRoleForContraction() const {
  // some derived classes override this and return false

  return true;
}

bool MarvinMol::isPassiveRoleForContraction() const { return false; }

bool MarvinSuperatomSgroupExpanded::isPassiveRoleForContraction() const {
  return false;
}

bool MarvinMultipleSgroup::isPassiveRoleForContraction() const { return false; }

void MarvinMolBase::parseMoleculeSpecific(RDKit::RWMol *mol,
                                          std::unique_ptr<SubstanceGroup> &,
                                          int) {
  PRECONDITION(mol != nullptr, "mol cannot be null");
  // default is nothing - most derived classes override this
};

void MarvinSuperatomSgroupExpanded::parseMoleculeSpecific(
    RDKit::RWMol *mol, std::unique_ptr<SubstanceGroup> &sgroup,
    int sequenceId) {
  PRECONDITION(mol != nullptr, "mol cannot be null");

  std::string typ = "SUP";
  sgroup.reset(new SubstanceGroup(mol, typ));
  sgroup->setProp<unsigned int>("index", sequenceId);

  for (auto atomPtr : this->atoms) {
    sgroup->addAtomWithIdx(this->parent->getAtomIndex(atomPtr->id));
  }

  for (auto bondPtr : this->bonds) {
    sgroup->addBondWithIdx(this->parent->getBondIndex(bondPtr->id));
  }

  sgroup->setProp("LABEL", this->title);
}
void MarvinMultipleSgroup::parseMoleculeSpecific(
    RDKit::RWMol *mol, std::unique_ptr<SubstanceGroup> &sgroup,
    int sequenceId) {
  PRECONDITION(mol != nullptr, "mol cannot be null");

  // now the MultipleSgroups
  // note: sequence continues counting from the loop above

  std::string typ = "MUL";
  sgroup.reset(new SubstanceGroup(mol, typ));
  sgroup->setProp<unsigned int>("index", sequenceId);

  for (auto atomPtr : this->atoms) {
    sgroup->addAtomWithIdx(this->parent->getAtomIndex(atomPtr->id));
  }

  for (auto atomPtr : this->parentAtoms) {
    sgroup->addParentAtomWithIdx(this->parent->getAtomIndex(atomPtr->id));
  }

  // the connection bonds

  for (auto bondptr : this->bondsToAtomsNotInExpandedGroup) {
    sgroup->addBondWithIdx(this->parent->getBondIndex(bondptr->id));
  }

  sgroup->setProp("MULT", this->title);
}
void MarvinSruCoModSgroup::parseMoleculeSpecific(
    RDKit::RWMol *mol, std::unique_ptr<SubstanceGroup> &sgroup,
    int sequenceId) {
  PRECONDITION(mol != nullptr, "mol cannot be null");

  std::string typ;
  if (this->role() == "SruSgroup") {
    typ = "SRU";
  } else if (this->role() == "CopolymerSgroup") {
    typ = "COP";
  } else if (this->role() == "ModificationSgroup") {
    typ = "MOD";
  } else {
    throw FileParseException(
        "Internal error: unrecognized role in a MarvinSruCoPolSgroup");
  }

  sgroup.reset(new SubstanceGroup(mol, typ));
  sgroup->setProp<unsigned int>("index", sequenceId);

  sgroup->setProp("CONNECT", this->connect);

  for (auto atomPtr : this->atoms) {
    sgroup->addAtomWithIdx(this->parent->getAtomIndex(atomPtr->id));
  }

  for (auto bondPtr : this->bonds) {
    sgroup->addBondWithIdx(this->parent->getBondIndex(bondPtr->id));
  }

  sgroup->setProp("LABEL", this->title);
}

void MarvinDataSgroup::parseMoleculeSpecific(
    RDKit::RWMol *mol, std::unique_ptr<SubstanceGroup> &sgroup,
    int sequenceId) {
  PRECONDITION(mol != nullptr, "mol cannot be null");
  // Now the data groups

  std::string typ = "DAT";
  sgroup.reset(new SubstanceGroup(mol, typ));
  sgroup->setProp<unsigned int>("index", sequenceId);

  for (auto atomPtr : this->atoms) {
    sgroup->addAtomWithIdx(this->parent->getAtomIndex(atomPtr->id));
  }

  sgroup->setProp("FIELDNAME", this->fieldName);

  if (this->queryType != "") {
    sgroup->setProp("QUERYTYPE", this->queryType);
  }
  if (this->queryOp != "") {
    sgroup->setProp("QUERYOP", this->queryOp);
  }

  std::ostringstream out;
  out << std::fixed << std::setw(10) << std::setprecision(4) << this->x
      << std::fixed << std::setw(10) << std::setprecision(4) << this->y
      << "    DRU   ALL  0       0";

  sgroup->setProp("FIELDDISP", out.str());  // really not used by RDKIT

  std::vector<std::string> fieldDatas;
  fieldDatas.push_back(this->fieldData);
  sgroup->setProp("DATAFIELDS", fieldDatas);

  // The following props are not part of the RDKit structure for MOL
  // files, but we save them so that we can round-trip the MRV

  sgroup->setProp("UNITS", this->units);
  sgroup->setProp("UNITSDISPLAYED", this->unitsDisplayed);
  sgroup->setProp("CONTEXT", this->context);
  sgroup->setProp("PLACEMENT", this->placement);
  sgroup->setProp("X", this->x);
  sgroup->setProp("Y", this->y);
}

void MarvinMulticenterSgroup::parseMoleculeSpecific(
    RDKit::RWMol *, std::unique_ptr<SubstanceGroup> &, int) {
  // the MultiCenter Sgroups

  // There is really no place to put these in RDKit.  We should have
  // removed these already
  PRECONDITION(
      0, "Internal error:   a MarvinMulticenterSgroup has not been removed");
}

// the Generic groups

void MarvinGenericSgroup::parseMoleculeSpecific(
    RDKit::RWMol *mol, std::unique_ptr<SubstanceGroup> &sgroup,
    int sequenceId) {
  PRECONDITION(mol != nullptr, "mol cannot be null");

  std::string typ = "GEN";
  sgroup.reset(new SubstanceGroup(mol, typ));
  sgroup->setProp<unsigned int>("index", sequenceId);

  for (auto atomPtr : this->atoms) {
    sgroup->addAtomWithIdx(this->parent->getAtomIndex(atomPtr->id));
  }

  // note: there is no place to put the change="onAtoms" flag
}

// now the MonomerSgroups
// note: sequence continues counting from the loop above

void MarvinMonomerSgroup::parseMoleculeSpecific(
    RDKit::RWMol *mol, std::unique_ptr<SubstanceGroup> &sgroup,
    int sequenceId) {
  PRECONDITION(mol != nullptr, "mol cannot be null");

  std::string typ = "MON";
  sgroup.reset(new SubstanceGroup(mol, typ));
  sgroup->setProp<unsigned int>("index", sequenceId);

  for (auto atomPtr : this->parent->atoms) {
    int atomIndex = this->getAtomIndex(atomPtr->id);
    sgroup->addAtomWithIdx(atomIndex);
  }
  sgroup->setProp("LABEL", this->title);

  // Note: RDKit does not have a place for the Bracket information nor
  // the charge="onAtoms" attr
}

void moveSgroup(MarvinMolBase *sgroupToMove, MarvinMolBase *newParent,
                bool removeFromOldParent = true) {
  PRECONDITION(sgroupToMove, "bad sgroupToMove pointer");

  MarvinMolBase *parent = sgroupToMove->parent;
  PRECONDITION(parent, "bad sgroupToMove parent pointer");
  auto moveUniqIter =
      find_if(sgroupToMove->parent->sgroups.begin(),
              sgroupToMove->parent->sgroups.end(),
              [sgroupToMove](std::unique_ptr<MarvinMolBase> &sgptr) {
                return sgptr->id == sgroupToMove->id;
              });

  if (moveUniqIter == sgroupToMove->parent->sgroups.end()) {
    throw FileParseException(
        "Unexpected error - sgroup not found in its parent");
  }

  newParent->sgroups.push_back(std::move(*moveUniqIter));
  if (removeFromOldParent) {
    parent->sgroups.erase(moveUniqIter);
  }
  sgroupToMove->parent = newParent;
}

void promoteChild(MarvinMolBase *molToMove) {
  PRECONDITION(molToMove, "bad molToMove pointer");
  moveSgroup(molToMove, molToMove->parent->parent);
}

void MarvinMultipleSgroup::expandOneMultipleSgroup() {
  // Mulitplesgroups are handled differently in Marvin and RDKit/mol file
  // format
  //
  // In Marvin, the atoms of the group are indicated, and the "title"
  // contains the number of replicates In mol files, the atoms of the group
  // are actually replicated in the atomBlock, and the MUL constructs
  // indicates the list of ALL such atoms and the list of the original
  // parent atoms from which the others were replicated.  It also indicate
  // the two bonds from the group atoms to atoms NOT in the group (although
  // these could be derived
  //
  //  This routine takes a MarvinMol and  prepares it for generation of an
  //  RDKit mol.  Each MultipleSgroup is expanded by:
  //    1) expanding the atom block - the new replicate sets of atoms are
  //    places just after the last atom in the original (parent) set 2)
  //    records the two bonds to atoms NOT in the expanded group - one is
  //    from a "parent" atom and one from a replicated atom. 3) bonds the
  //    parent and replicated sets to each other in a head to tail fashion.

  // make sure it is not already expanded - this should not happen

  if (this->isExpanded) {
    return;
  }

  // find the two bonds (or zero bonds) to atoms NOT in the group

  std::vector<std::string>
      originalConnectorAtoms;     // the bonds in the parent that were to
                                  // outside atoms BEFORE replication
  std::string connectorAtoms[2];  // working atoms to connect the replicates
  std::string outsideConnectorAtom;
  std::vector<MarvinBond *> bondsInGroup;
  this->bondsToAtomsNotInExpandedGroup.clear();

  // find the actual parent - multiple groups can be nested, so the atoms
  // and bonds of the lower one are really in the grandparent or higher)

  auto actualParent = getActualParent(this);

  for (MarvinBond *bondPtr : actualParent->bonds) {
    bool atom1InSet =
        (std::find_if(atoms.begin(), atoms.end(), [&bondPtr](auto a) {
           return a->id == bondPtr->atomRefs2[0];
         }) != atoms.end());

    bool atom2InSet =
        (std::find_if(atoms.begin(), atoms.end(), [&bondPtr](auto a) {
           return a->id == bondPtr->atomRefs2[1];
         }) != atoms.end());

    if (atom1InSet && atom2InSet) {
      bondsInGroup.push_back(bondPtr);
    } else if (atom1InSet) {
      originalConnectorAtoms.push_back(bondPtr->atomRefs2[0]);
      this->bondsToAtomsNotInExpandedGroup.push_back(bondPtr);
      outsideConnectorAtom =
          bondPtr->atomRefs2[1];  // last one set wins - when done should be
                                  // the outside atom for the 2nd bond to
                                  // the outside
    } else if (atom2InSet) {
      originalConnectorAtoms.push_back(bondPtr->atomRefs2[1]);
      this->bondsToAtomsNotInExpandedGroup.push_back(bondPtr);
      outsideConnectorAtom =
          bondPtr->atomRefs2[0];  // last one set wins - when done should be
                                  // the outside atom for the 2nd bond to
                                  // the outside
    }
  }

  // should be two bonds to the outside (or zero)
  if (this->bondsToAtomsNotInExpandedGroup.size() != 2 &&
      this->bondsToAtomsNotInExpandedGroup.size() != 0) {
    throw FileParseException(
        "Error - there must be zero or two bonds from the group to atoms not in the group");
  }

  // find the hightest id of an atom in the Group - we will insert
  // replicated atoms after that one

  int highestIndex = 0;
  for (MarvinAtom *atomPtr : this->atoms) {
    int thisIndex = actualParent->getAtomIndex(atomPtr->id);
    if (thisIndex > highestIndex) {
      highestIndex = thisIndex;
    }
  }
  MarvinAtom *lastAtomInGroupPtr = actualParent->atoms[highestIndex];

  // ready to make copies of the group

  int copyCount = std::stoi(this->title);

  if (this->bondsToAtomsNotInExpandedGroup.size() == 2) {
    connectorAtoms[1] =
        originalConnectorAtoms[1];  // this one does NOT have an _# on it
  }

  for (int copyIndex = 2; copyIndex <= copyCount;
       ++copyIndex)  // start at 2, we already have the first copy
  {
    std::string idAppendage = "_" + this->id + ":" + std::to_string(copyIndex);
    for (auto parentAtomPtr : this->parentAtoms) {
      auto copyAtom =
          new MarvinAtom(*parentAtomPtr, parentAtomPtr->id + idAppendage);
      actualParent->pushOwnedAtom(copyAtom);
      if (parentAtomPtr->sgroupRef != "" && !copyAtom->sGroupRefIsSuperatom) {
        copyAtom->sgroupRef = parentAtomPtr->sgroupRef + idAppendage;
      }

      // copy atoms to all parents up to the actual parent (multipleSgroups
      // in multipleSgroups)

      for (auto thisParent = this->parent;; thisParent = thisParent->parent) {
        TEST_ASSERT(thisParent != nullptr);
        auto insertItr = find(thisParent->atoms.begin(),
                              thisParent->atoms.end(), lastAtomInGroupPtr);
        if (insertItr != thisParent->atoms.end()) {
          ++insertItr;  // insert after the last one
        }
        thisParent->atoms.insert(insertItr, copyAtom);

        // for multiple groups, also insert in the parentAtoms array - that
        // multiple sgroup has NOT been done yet

        if (thisParent->role() == "MultipleSgroup") {
          auto thisMultipleParent = (MarvinMultipleSgroup *)thisParent;
          insertItr =
              find(thisMultipleParent->parentAtoms.begin(),
                   thisMultipleParent->parentAtoms.end(), lastAtomInGroupPtr);
          if (insertItr != thisMultipleParent->parentAtoms.end()) {
            ++insertItr;  // insert after the last one
          }
          thisMultipleParent->parentAtoms.insert(insertItr, copyAtom);
        }

        if (thisParent == actualParent) {
          break;
        }
      }
      lastAtomInGroupPtr = copyAtom;
      this->atoms.push_back(copyAtom);
    }

    // add the bonds for this copy

    for (auto parentBondPtr : bondsInGroup) {
      auto copyBond =
          new MarvinBond(*parentBondPtr, parentBondPtr->id + idAppendage,
                         parentBondPtr->atomRefs2[0] + idAppendage,
                         parentBondPtr->atomRefs2[1] + idAppendage);
      actualParent->pushOwnedBond(copyBond);
      actualParent->bonds.push_back(copyBond);
    }

    for (int i = this->sgroups.size() - 1; i >= 0; --i) {
      auto copiedMol = this->sgroups[i]->copyMol(idAppendage);
      moveSgroup(copiedMol, this->parent);
    }

    // add the bond from the last group to the new one

    if (this->bondsToAtomsNotInExpandedGroup.size() == 2) {
      connectorAtoms[0] = originalConnectorAtoms[0] + idAppendage;
      auto connectorBond = new MarvinBond(
          *this->bondsToAtomsNotInExpandedGroup[0],
          this->bondsToAtomsNotInExpandedGroup[0]->id + idAppendage,
          connectorAtoms[0], connectorAtoms[1]);
      actualParent->pushOwnedBond(connectorBond);
      actualParent->bonds.push_back(connectorBond);

      // update connectorAtom[1] for the next pass (or the final bond to the
      // outside atom)

      connectorAtoms[1] = originalConnectorAtoms[1] + idAppendage;
    }
  }

  // fix the bond to the second outside atom to reflect that it comes from
  // the last replicate

  if (this->bondsToAtomsNotInExpandedGroup.size() == 2) {
    this->bondsToAtomsNotInExpandedGroup[1]->atomRefs2[0] =
        outsideConnectorAtom;
    this->bondsToAtomsNotInExpandedGroup[1]->atomRefs2[1] = connectorAtoms[1];
  }

  // move any sgroups below this one up to the parent - we have already made
  // copies of it

  for (int i = this->sgroups.size() - 1; i >= 0; --i) {
    promoteChild(sgroups[i].get());
  }

  this->isExpanded = true;
}

void MarvinSuperatomSgroup::convertFromOneSuperAtom() {
  // the mol-style super atoms are significanTly different than the Marvin
  // super atoms.  The mol style has all atoms and bonds in the main mol,
  // and parameter lines that indicate the name of the super atom and the
  // atom indices affected.
  //
  //  The SuperatomSgroup form can appear in contracted or expanded form in
  //  MRV blocks:
  //
  // In the contracted form, the MRV block can have one or more dummy atoms
  // with the super atom name in the main molecule, and a separate sub-mol
  // with the atoms and bonds of the superatom. It also can have one or more
  // separate records called attachmentPoints that specify which atom(s) in
  // the super atom sub-mol that replaces the dummy atom(s), and also a bond
  // pointer (in the parent mol).
  //
  // In the expanded form, all of the atoms are in the parent molecule, and
  // the sub-mol only refers to them.  The attachment points refer to the
  // atoms in the parent mol. The MultipleSgroup and SruGroup seem very much
  // alike.   In both, all atoms are in the parent mol, and the sub-mol
  // refers to a group of atoms in that parent. The SruGroup specifies the
  // name and also the connection information (head-to-tail, head-head, and
  // unspecified). The Multiple S-group specifies the report count for the
  // group
  //
  // This routine deals with only the contracted form of the
  // SuperatomSgroups, and copies the atoms and bonds from the sub=mol to
  // the parent mol, and deletes the dummy atom form the parent mol.
  //  It also saves the info creates a replacement
  //  MarvinSuperatomSgroupExpanded item.
  try {
    // save the name of the superatom

    auto superatomSgroupExpanded =
        new MarvinSuperatomSgroupExpanded(this->parent);
    this->parent->sgroups.push_back(
        std::unique_ptr<MarvinMolBase>(superatomSgroupExpanded));

    superatomSgroupExpanded->title = this->title;
    superatomSgroupExpanded->id =
        this->id;  // the expanded sgroup will replace the contracted one
    superatomSgroupExpanded->molID =
        this->molID;  // the expanded sgroup will replace the contracted one

    // find the actual parent - multiple groups can be nested, so the atoms
    // and bonds of the lower one are really in the grandparent or higher)

    auto actualParent = getActualParent(this);

    //  remove and delete the dummy atom from the parent.

    bool coordExist = this->has2dCoords();
    auto dummyAtomIter = find_if(
        actualParent->atoms.begin(), actualParent->atoms.end(),
        [this](const MarvinAtom *arg) { return arg->sgroupRef == this->id; });
    if (dummyAtomIter == actualParent->atoms.end()) {
      throw FileParseException(
          "No contracted atom found for a superatomSgroup");
    }
    auto dummyAtomPtr = *dummyAtomIter;

    // before we move or delete any atoms from the superatomSgroup,  Make
    // sure that the  sibling sgroups are handled if a sibling contains the
    // dummy R atom, then the atoms to be promoted from this sgroup should
    // be member of the sibling too

    for (auto &sibling : parent->sgroups) {
      if (sibling.get() == this) {
        continue;  // not a sibling
      }

      auto dummyInSibling =
          find_if(sibling->atoms.begin(), sibling->atoms.end(),
                  [dummyAtomPtr](const MarvinAtom *arg) {
                    return arg == dummyAtomPtr;
                  });

      if (dummyInSibling != sibling->atoms.end()) {
        sibling->atoms.erase(dummyInSibling);

        for (auto atom : this->atoms) {
          sibling->atoms.push_back(atom);
        }
      }
    }

    // get a list of the bonds that will need to be fixed after the copy of
    // atoms and bonds

    std::vector<MarvinAttachmentPoint *> orphanedBonds;
    RDGeom::Point3D centerOfAttachmentPoints;
    RDGeom::Point3D centerOfGroup;
    for (auto orphanedBond : actualParent->bonds) {
      std::string attachedAtomId = "";
      if (orphanedBond->atomRefs2[0] == dummyAtomPtr->id) {
        attachedAtomId = orphanedBond->atomRefs2[1];
      } else if (orphanedBond->atomRefs2[1] == dummyAtomPtr->id) {
        attachedAtomId = orphanedBond->atomRefs2[0];
      }

      if (attachedAtomId != "") {
        auto attachmentPoint = find_if(
            this->attachmentPoints.begin(), this->attachmentPoints.end(),
            [orphanedBond](const std::unique_ptr<MarvinAttachmentPoint> &arg) {
              return arg->bond == orphanedBond->id;
            });
        if (attachmentPoint == this->attachmentPoints.end()) {
          throw FileParseException(
              "No attachment point found for bond to the condensed atom in a superatomSgroup");
        }
        orphanedBonds.push_back(attachmentPoint->get());

        auto subMolAtomIndex = this->getAtomIndex((*attachmentPoint)->atom);
        if (subMolAtomIndex < 0) {
          throw FileParseException(
              "Attachment atom not found in the superatomsGroup");
        }
        MarvinAtom *attachedAtom = this->atoms[subMolAtomIndex];
        if (coordExist) {
          centerOfAttachmentPoints.x += attachedAtom->x2;
          centerOfAttachmentPoints.y += attachedAtom->y2;
        }
      }
    }

    if (coordExist) {
      RDGeom::Point3D offset;

      if (orphanedBonds.size() > 0) {
        centerOfAttachmentPoints.x /= orphanedBonds.size();
        centerOfAttachmentPoints.y /= orphanedBonds.size();
        offset.x = dummyAtomPtr->x2 - centerOfAttachmentPoints.x;
        offset.y = dummyAtomPtr->y2 - centerOfAttachmentPoints.y;
      } else  // use the center of all atoms in the group
      {
        RDGeom::Point3D centerOfGroup;

        for (auto atom : this->atoms) {
          centerOfGroup.x += atom->x2;
          centerOfGroup.y += atom->y2;
        }
        centerOfGroup.x /= this->atoms.size();
        centerOfGroup.y /= this->atoms.size();
        offset.x = dummyAtomPtr->x2 - centerOfGroup.x;
        offset.y = dummyAtomPtr->y2 - centerOfGroup.y;
      }

      for (auto atom : this->atoms) {
        atom->x2 += offset.x;
        atom->y2 += offset.y;
      }
    }

    for (auto thisParent = parent;; thisParent = thisParent->parent) {
      TEST_ASSERT(thisParent != nullptr);
      auto dummyInParent =
          find_if(thisParent->atoms.begin(), thisParent->atoms.end(),
                  [dummyAtomPtr](const MarvinAtom *arg) {
                    return arg == dummyAtomPtr;
                  });
      TEST_ASSERT(dummyInParent != thisParent->atoms.end());
      thisParent->atoms.erase(dummyInParent);  // get rid of the atoms pointer
                                               // to the old dummy atom

      // for multiple groups, also delete it from the parentAtoms array -
      // that multiple sgroup has NOT been done yet

      if (thisParent->role() == "MultipleSgroup") {
        auto thisMultipleParent = (MarvinMultipleSgroup *)thisParent;

        auto deleteIter =
            find(thisMultipleParent->parentAtoms.begin(),
                 thisMultipleParent->parentAtoms.end(), dummyAtomPtr);
        TEST_ASSERT(deleteIter != thisMultipleParent->parentAtoms.end());
        thisMultipleParent->parentAtoms.erase(deleteIter);
      }

      if (thisParent == actualParent) {
        break;
      }
    }

    removeOwnedAtom(dummyAtomPtr);

    // add the atoms and bonds from the super group to the parent

    for (auto subAtomPtr : this->atoms) {
      for (auto thisParent = parent;; thisParent = thisParent->parent) {
        TEST_ASSERT(thisParent != nullptr);
        thisParent->atoms.push_back(subAtomPtr);

        if (thisParent->role() == "MultipleSgroup") {
          auto thisMultipleParent = (MarvinMultipleSgroup *)thisParent;
          thisMultipleParent->parentAtoms.push_back(subAtomPtr);
        }

        if (thisParent == actualParent) {
          break;
        }
      }

      superatomSgroupExpanded->atoms.push_back(subAtomPtr);

      // remove the sgroupRef from the atom if it has one
      (subAtomPtr)->sgroupAttachmentPoint = "";
    }

    for (auto &bond : this->bonds) {
      actualParent->bonds.push_back(bond);
    }

    // process the attachment points - fix the bond that was made wrong by
    // deleting the dummy atom(s)

    for (auto &attachmentPoint : this->attachmentPoints) {
      // find the bond in the parent

      auto bondIter =
          find_if(actualParent->bonds.begin(), actualParent->bonds.end(),
                  [&attachmentPoint](const MarvinBond *arg) {
                    return arg->id == attachmentPoint->bond;
                  });
      if (bondIter == actualParent->bonds.end()) {
        throw FileParseException(
            "Bond specification for an AttachmentPoint definition was not found in the bond array in MRV file");
      }

      superatomSgroupExpanded->bonds.push_back(*bondIter);

      // one of the two atoms in the bond is NOT in the mol - we deleted the
      // dummy atom.

      int atomIndex;
      for (atomIndex = 0; atomIndex < 2; ++atomIndex) {
        if (std::find_if(actualParent->atoms.begin(), actualParent->atoms.end(),
                         [&, bondIter, atomIndex](auto a) {
                           return a->id == (*bondIter)->atomRefs2[atomIndex];
                         }) == actualParent->atoms.end()) {
          (*bondIter)->atomRefs2[atomIndex] =
              attachmentPoint->atom;  // the attach atom
          break;
        }
      }
      if (atomIndex == 2)  // not found?
      {
        std::ostringstream err;
        err << "Bond " << attachmentPoint->bond.c_str()
            << " from attachment point did not have a missing atom in MRV file";
        throw FileParseException(err.str());
      }
    }

    this->attachmentPoints.clear();
    this->atoms.clear();
    this->bonds.clear();

    // promote any children sgroups

    for (auto &childSgroup : this->sgroups) {
      moveSgroup(childSgroup.get(), actualParent, false);
    }
    this->sgroups.clear();
    auto sgroupItr =
        std::find_if(parent->sgroups.begin(), parent->sgroups.end(),
                     [this](std::unique_ptr<MarvinMolBase> &sgptr) {
                       return sgptr->id == this->id;
                     });
    TEST_ASSERT(sgroupItr != parent->sgroups.end());

    parent->sgroups.erase(sgroupItr);
  } catch (const std::exception &e) {
    throw;
  }
}

void MarvinMulticenterSgroup::processOneMulticenterSgroup() {
  auto actualParent = getActualParent(this);

  // delete the bonds to the dummy atom
  std::vector<MarvinBond *> orphanedBonds;  // list of bonds to delete
  for (auto orphanedBond : actualParent->bonds) {
    std::string attachedAtomId = "";
    if (orphanedBond->atomRefs2[0] == this->center->id ||
        orphanedBond->atomRefs2[1] == this->center->id) {
      orphanedBonds.push_back(orphanedBond);
    }
  }
  for (auto orphanedBond : orphanedBonds) {
    auto orphanedBondIter = std::find(actualParent->bonds.begin(),
                                      actualParent->bonds.end(), orphanedBond);
    TEST_ASSERT(orphanedBondIter != actualParent->bonds.end());
    actualParent->bonds.erase(orphanedBondIter);
    actualParent->removeOwnedBond(orphanedBond);
  }

  auto centerIter = std::find(actualParent->atoms.begin(),
                              actualParent->atoms.end(), this->center);
  if (centerIter !=
      actualParent->atoms.end())  // it might already have been deleted by
                                  // another multicenter group
  {
    auto centerPtr = *centerIter;
    for (auto thisParent = parent;; thisParent = thisParent->parent) {
      TEST_ASSERT(thisParent != nullptr);
      auto parentAtomIter = find(
          thisParent->atoms.begin(), thisParent->atoms.end(),
          centerPtr);  // get rid of the atoms pointer to the old dummy atom
      TEST_ASSERT(parentAtomIter != thisParent->atoms.end());
      thisParent->atoms.erase(parentAtomIter);  // get rid of the atoms pointer
                                                // to the old dummy atom

      if (thisParent->role() == "MultipleSgroup") {
        auto thisMultipleParent = (MarvinMultipleSgroup *)thisParent;
        auto deleteIter =
            find(thisMultipleParent->parentAtoms.begin(),
                 thisMultipleParent->parentAtoms.end(), centerPtr);
        TEST_ASSERT(deleteIter != thisMultipleParent->parentAtoms.end());
        thisMultipleParent->parentAtoms.erase(deleteIter);
      }

      if (thisParent == actualParent) {
        break;
      }
    }

    removeOwnedAtom(centerPtr);
  }

  // erase the multicenter group from its parent

  for (auto thisParent = parent;; thisParent = thisParent->parent) {
    TEST_ASSERT(thisParent != nullptr);
    auto sgrupIter =
        std::find_if(thisParent->sgroups.begin(), thisParent->sgroups.end(),
                     [this](std::unique_ptr<MarvinMolBase> &sgptr) {
                       return sgptr->id == this->id;
                     });
    TEST_ASSERT(sgrupIter != thisParent->sgroups.end());
    thisParent->sgroups.erase(sgrupIter);
    if (thisParent == actualParent) {
      break;
    }
  }
}

void MarvinMolBase::prepSgroupsForRDKit() {
  // this routine recursively fixes the hierarchy of sgroups - some may NOT
  // actually belong underneath their parent and can be promoted to the
  // grandparent

  // first fix all the children

  std::vector<std::string> sgroupsMolIdsDone;
  for (bool allDone = false;
       !allDone;)  // until all at this level are done - but fixing one
                   // child can add sgroups to this level
  {
    allDone = true;  // until it is not true in the loop below
    for (auto &childSgroup : this->sgroups) {
      if (std::find(sgroupsMolIdsDone.begin(), sgroupsMolIdsDone.end(),
                    childSgroup->molID) == sgroupsMolIdsDone.end()) {
        sgroupsMolIdsDone.push_back(childSgroup->molID);
        childSgroup->prepSgroupsForRDKit();
        allDone = false;
        break;  // have to start the loop over - we might have changed the
                // vector
      }
    }
  }
  // if this is top level, quit

  if (this->parent == nullptr) {
    return;
  }

  // check to see if we can move this sgroup up a level. We can if the
  // parent is not the root of the tree, and its parent is passive (it does
  // not change the atoms of the parent when it is processed or expanded, or
  // if all of its atoms do not belong to the the non-passive parent

  // if this is already a child of the root, it cannot be moved up
  if (this->parent->parent != nullptr) {
    // check this one

    if (this->parent->isPassiveRoleForExpansion()) {
      // move the child up

      promoteChild(this);
      return;
    }

    // check to see if all of its atomRefs of the child are in the parent.
    //  there are 3 possibilities:
    //  1) all atoms are in the parent - do NOT move the child - it belongs
    //  under the parent 2) NO atoms are in the parent - move the child up
    //  3) SOME atoms are in the parent - throw an error

    auto result = this->isSgroupInSetOfAtoms(this->parent->atoms);
    switch (result) {
      case SgroupNotInAtomSet:
        promoteChild(this);
        return;

      case SgroupInAtomSet:
        // do noting here
        break;

      case SgroupBothInAndNotInAtomSet:
        throw FileParseException(
            "Child sGroup has atoms both in the parent and NOT in the parent");
      default:
        throw FileParseException(
            "Unexpected error: unrecognized result from isSgroupInSetOfAtoms");
    }
  }

  // made to here, so the child belongs in the parent.
  //  do any sgroup specific processing

  processSpecialSgroups();
  return;
}

void MarvinMolBase::processSpecialSgroups() {
  // by default, nothing is done here.  Some subclasses will override this.
}

void MarvinSuperatomSgroup::processSpecialSgroups() {
  convertFromOneSuperAtom();
}

void MarvinMulticenterSgroup::processSpecialSgroups() {
  processOneMulticenterSgroup();
}
void MarvinMultipleSgroup::processSpecialSgroups() {
  expandOneMultipleSgroup();
}

MarvinMolBase *MarvinSuperatomSgroupExpanded::convertToOneSuperAtom() {
  // the mol-style super atoms are significantly different than the Marvin
  // super atoms.  The mol style has all atoms and bonds in the main mol,
  // and parameter lines that indicate the name of the super atom and the
  // atom indices affected.
  //
  // The Marvin has a dummy atom with the super atom name in the main
  // molecule, and a separate sub-mol with the atoms and bonds of the
  // superatom.  It also has a separate record called attachmentPoint that
  // atom in the super atom sub=mol that is replaces the dummy atom, and
  // also a bond pointer and bond order in case the bond order changes.
  //
  //  Takes information from a MarvinSuperatomSgroupExpanded and converts
  //  the MarvinSuperatomSgroup structure

  PRECONDITION(this->parent, "invalid parent");
  auto actualParent = getActualParent(this);

  // make a new sub mol

  auto marvinSuperatomSgroup = new MarvinSuperatomSgroup(this->parent);
  this->parent->sgroups.push_back(
      std::unique_ptr<MarvinMolBase>(marvinSuperatomSgroup));
  std::string newAtomName = "NA_" + this->molID;

  marvinSuperatomSgroup->molID = this->molID;
  marvinSuperatomSgroup->title = this->title;
  marvinSuperatomSgroup->id = this->id;

  bool coordsExist = has2dCoords();  // we have to check before we add the dummy
                                     // atom  - it will not have coords (yet)

  // add the dummy atom into the parent

  auto dummyParentAtom = new MarvinAtom();
  actualParent->pushOwnedAtom(dummyParentAtom);
  dummyParentAtom->elementType = "R";
  dummyParentAtom->id = newAtomName;
  dummyParentAtom->sgroupRef = marvinSuperatomSgroup->id;
  dummyParentAtom->sGroupRefIsSuperatom = true;

  for (auto thisParent = this->parent;;
       thisParent = thisParent->parent)  // do all parents and grandparents
                                         // ... to to the actual parent
  {
    thisParent->atoms.push_back(dummyParentAtom);

    if (thisParent->role() == "MultipleSgroup") {
      ((MarvinMultipleSgroup *)thisParent)
          ->parentAtoms.push_back(dummyParentAtom);
    }

    if (thisParent == actualParent) {
      break;
    }
  }

  RDGeom::Point3D centerOfGroup;

  for (auto atom : this->atoms) {
    atom->sgroupRef = "";
    marvinSuperatomSgroup->atoms.push_back(atom);

    for (auto thisParent = this->parent;;
         thisParent = thisParent->parent)  // do all parents and grandparents
                                           // ... to to the actual parent
    {
      auto deleteIter =
          find(thisParent->atoms.begin(), thisParent->atoms.end(), atom);
      TEST_ASSERT(deleteIter != thisParent->atoms.end());
      thisParent->atoms.erase(deleteIter);

      if (thisParent->role() == "MultipleSgroup") {
        auto marvinMultipleSgroup = (MarvinMultipleSgroup *)thisParent;
        auto sgroupIter = find(marvinMultipleSgroup->parentAtoms.begin(),
                               marvinMultipleSgroup->parentAtoms.end(), atom);
        TEST_ASSERT(sgroupIter != marvinMultipleSgroup->parentAtoms.end());
        marvinMultipleSgroup->parentAtoms.erase(sgroupIter);
      }

      if (thisParent == actualParent) {
        break;
      }
    }

    if (coordsExist)  // get the center of all atoms in the group - we might
                      // use this if there are no attachment points
    {
      centerOfGroup.x += atom->x2;
      centerOfGroup.y += atom->y2;
    }
  }

  // move the bonds of the group

  int attachmentPointsAdded = 0;
  MarvinAtom *atomPtr = nullptr;
  RDGeom::Point3D centerOfAttachmentPoints;

  for (auto bond : actualParent->bonds) {
    bool atom1InGroup =
        (std::find_if(marvinSuperatomSgroup->atoms.begin(),
                      marvinSuperatomSgroup->atoms.end(), [&bond](auto a) {
                        return a->id == (bond)->atomRefs2[0];
                      }) != marvinSuperatomSgroup->atoms.end());
    bool atom2InGroup =
        (std::find_if(marvinSuperatomSgroup->atoms.begin(),
                      marvinSuperatomSgroup->atoms.end(), [&bond](auto a) {
                        return a->id == (bond)->atomRefs2[1];
                      }) != marvinSuperatomSgroup->atoms.end());

    if (atom1InGroup && atom2InGroup) {  // both are in, so copy the bond
      marvinSuperatomSgroup->bonds.push_back(bond);

    } else if (atom1InGroup ||
               atom2InGroup)  // one is in so this is a connection point
    {
      // fix the bonds to the dummy atom and add an attachment point

      if (atom1InGroup) {
        atomPtr =
            marvinSuperatomSgroup->atoms[marvinSuperatomSgroup->getAtomIndex(
                (bond)->atomRefs2[0])];
        (bond)->atomRefs2[0] = newAtomName;

      } else {
        atomPtr =
            marvinSuperatomSgroup->atoms[marvinSuperatomSgroup->getAtomIndex(
                (bond)->atomRefs2[1])];
        (bond)->atomRefs2[1] = newAtomName;
      }

      atomPtr->sgroupAttachmentPoint = std::to_string(++attachmentPointsAdded);

      // add an attachmentPoint structure

      auto &marvinAttachmentPoint =
          marvinSuperatomSgroup->attachmentPoints.emplace_back(
              new MarvinAttachmentPoint);
      marvinAttachmentPoint->atom = atomPtr->id;
      marvinAttachmentPoint->bond = bond->id;

      marvinAttachmentPoint->order = std::to_string(attachmentPointsAdded);

      if (coordsExist) {
        centerOfAttachmentPoints.x += atomPtr->x2;
        centerOfAttachmentPoints.y += atomPtr->y2;
      }
    }
  }

  // now remove the bonds that were moved to the superGroup from the parent

  for (auto bond : marvinSuperatomSgroup->bonds) {
    int index = actualParent->getBondIndex(bond->id);
    TEST_ASSERT(index >= 0 &&
                static_cast<unsigned int>(index) < actualParent->bonds.size());
    actualParent->bonds.erase(actualParent->bonds.begin() + index);
  }

  if (coordsExist) {
    if (marvinSuperatomSgroup->attachmentPoints.size() >
        0)  // Any attachment points?  if so we use the center of the
            // attached atoms in the supergroup
    {
      // put the new dummy atom at the center of the removed group

      dummyParentAtom->x2 = centerOfAttachmentPoints.x /
                            marvinSuperatomSgroup->attachmentPoints.size();
      dummyParentAtom->y2 = centerOfAttachmentPoints.y /
                            marvinSuperatomSgroup->attachmentPoints.size();
    } else {
      // No attachments to the supergroup - (probably all atoms in the mol
      // are in the supergroup) -use the center of all atoms in the group
      dummyParentAtom->x2 =
          centerOfGroup.x / marvinSuperatomSgroup->atoms.size();
      dummyParentAtom->y2 =
          centerOfGroup.y / marvinSuperatomSgroup->atoms.size();
    }
  }

  // move any children from the old expanded group to the new
  // superatomSgroup

  for (auto &sgroupPtr : this->sgroups) {
    moveSgroup(sgroupPtr.get(), marvinSuperatomSgroup, false);
  }
  this->sgroups.clear();

  // remove the old expanded superatom sgroup
  auto sgroupIter = std::find_if(parent->sgroups.begin(), parent->sgroups.end(),
                                 [this](std::unique_ptr<MarvinMolBase> &sgptr) {
                                   return sgptr->id == this->id;
                                 });
  TEST_ASSERT(sgroupIter != parent->sgroups.end());
  parent->sgroups.erase(sgroupIter);

  // fix up any siblings that contain all the atoms of this group.

  for (auto &sibling : marvinSuperatomSgroup->parent->sgroups) {
    if (sibling.get() == marvinSuperatomSgroup) {
      continue;  // not a sibling
    }

    // see if the new superatom group has all of its atoms in the sibling.
    // If to add the dummy atom to the sibling and remove the atoms (there
    // must be at least one atom in the sibling that is not in the new
    // superatom, or it would be a child of the superatom already

    auto isSgroupInSetOfAtomsResult =
        marvinSuperatomSgroup->isSgroupInSetOfAtoms(sibling->atoms);

    switch (isSgroupInSetOfAtomsResult) {
      case SgroupInAtomSet:
        // remove the group atoms from the sibling and add the dummy atom

        sibling->atoms.push_back(dummyParentAtom);
        for (auto atomToRemove : marvinSuperatomSgroup->atoms) {
          int index = sibling->getAtomIndex(atomToRemove->id);
          TEST_ASSERT(index >= 0 &&
                      static_cast<unsigned int>(index) < sibling->atoms.size());
          sibling->atoms.erase(sibling->atoms.begin() + index);
        }

        break;

      case SgroupNotInAtomSet:
        // do nothing
        break;

      case SgroupBothInAndNotInAtomSet:
        throw FileParseException(
            "a subgroup contains some of the atoms of a superatomSgroup - this should not happen");
    }
  }

  return marvinSuperatomSgroup;
}

int MarvinMultipleSgroup::getMatchedOrphanBondIndex(
    std::string atomIdToCheck, std::vector<MarvinBond *> &bondsToTry,
    std::vector<MarvinBond *> &orphanedBonds) const {
  for (auto testBond = bondsToTry.begin(); testBond != bondsToTry.end();
       ++testBond) {
    if (*testBond == nullptr) {
      continue;
    }
    std::string otherAtomId;
    if ((*testBond)->atomRefs2[0] == atomIdToCheck) {
      otherAtomId = (*testBond)->atomRefs2[1];
    } else if ((*testBond)->atomRefs2[1] == atomIdToCheck) {
      otherAtomId = (*testBond)->atomRefs2[0];
    } else {
      continue;  // bond does not have the atomId
    }

    auto testBondIter =
        find(orphanedBonds.begin(), orphanedBonds.end(), *testBond);
    if (testBondIter != orphanedBonds.end()) {
      return testBondIter - orphanedBonds.begin();
    }

    *testBond = nullptr;

    // try the children

    int childId =
        getMatchedOrphanBondIndex(otherAtomId, bondsToTry, orphanedBonds);
    if (childId >= 0) {
      return childId;
    }
  }

  return -1;
}

void MarvinMultipleSgroup::contractOneMultipleSgroup() {
  // this routine takes the expanded MultipleSgroup (which comes from the
  // RDKit version, or is ready to produce the RDKit version), and contracts
  // it
  //  to the Marvin format version.
  //  the replicates are deleted (atoms and bonds), and the two orphaned
  //  bonds are  repaired

  // make sure it is not already contracted - this should not happen

  if (!this->isExpanded) {
    return;
  }

  // find the actual parent - multiple groups can be nested, so the atoms
  // and bonds of the lower one are really in the grandparent or higher)

  auto actualParent = getActualParent(this);

  // find the atoms to be deleted

  std::vector<MarvinAtom *> atomsToDelete;
  std::vector<MarvinBond *> bondsToDelete;
  std::vector<MarvinBond *> orphanedBonds;
  std::vector<MarvinMolBase *> sgroupsToDelete;

  for (MarvinAtom *atomPtr : this->atoms) {
    // Atoms in the group but NOT in the parent part are to be deleted
    if (std::find_if(parentAtoms.begin(), parentAtoms.end(),
                     [&, atomPtr](auto a) { return a->id == atomPtr->id; }) ==
        parentAtoms.end()) {
      atomsToDelete.push_back(atomPtr);
    }
  }

  for (MarvinBond *bondPtr : actualParent->bonds) {
    bool atom1ToBeDeleted =
        (std::find_if(atomsToDelete.begin(), atomsToDelete.end(),
                      [&bondPtr](auto a) {
                        return a->id == (bondPtr)->atomRefs2[0];
                      }) != atomsToDelete.end());

    bool atom2ToBeDeleted =
        (std::find_if(atomsToDelete.begin(), atomsToDelete.end(),
                      [&bondPtr](auto a) {
                        return a->id == (bondPtr)->atomRefs2[1];
                      }) != atomsToDelete.end());

    if (atom1ToBeDeleted && atom2ToBeDeleted) {
      bondsToDelete.push_back(bondPtr);
    } else if (atom1ToBeDeleted) {
      orphanedBonds.push_back(bondPtr);
      swap(bondPtr->atomRefs2[0],
           bondPtr->atomRefs2[1]);  // make sure the first ref atom is the
                                    // orphaned one (still in the mol), and
                                    // the second is the atom to be deleted
      bondsToDelete.push_back(
          bondPtr);  // one of each pair of orphaned bonds will be UNdeleted
    } else if (atom2ToBeDeleted) {
      orphanedBonds.push_back(bondPtr);
      bondsToDelete.push_back(
          bondPtr);  // one of each pair of orphaned bonds will be UNdeleted
    }
  }

  // there must be zero two or four orphaned bonds
  // zero happens when the whole group is replicated and not chained
  // two is most common - the replicates being deleted are connected to each
  // other 4 happens when the parent replicate (not deleted) is in between
  // two replicates that are deleted.
  //  there are two orphaned bonds on the parent replicate, and two on the
  //  rest of the molecule

  if (orphanedBonds.size() != 0 && orphanedBonds.size() != 2 &&
      orphanedBonds.size() != 4) {
    throw FileParseException(
        "Error: there should be zero, two or four orphaned bonds while contracting a MultipleSgroup");
  }

  // delete any of this group's children that were using the atoms to be
  // deleted

  for (auto &childSgroup : sgroups) {
    if (childSgroup->isSgroupInSetOfAtoms(atomsToDelete) !=
        SgroupNotInAtomSet) {
      sgroupsToDelete.push_back(childSgroup.get());
    }
  }

  // now fix the orphaned bonds - The first gets the atoms from the matched
  // second orphan bond  and was NOT removed. the matched second orphaned
  // bond is deleted

  while (orphanedBonds.size() > 0) {
    int matchedOrphanBondIndex = -1;
    auto orphanedBondToFix = orphanedBonds[0];
    orphanedBonds.erase(orphanedBonds.begin());

    if (orphanedBonds.size() == 3)  // was 4 but the first one was erased
    {
      std::vector<MarvinBond *> bondsToTry =
          bondsToDelete;  // copy of bonds to delete
      auto deleteIter =
          find(bondsToTry.begin(), bondsToTry.end(), orphanedBondToFix);
      TEST_ASSERT(deleteIter != bondsToTry.end());
      bondsToTry.erase(deleteIter);

      matchedOrphanBondIndex = this->getMatchedOrphanBondIndex(
          orphanedBondToFix->atomRefs2[1], bondsToTry, orphanedBonds);
      if (matchedOrphanBondIndex < 0) {
        throw FileParseException(
            "For a MultipleSgroup expansion, the matching orphaned bond was not found");
      }
    } else if (orphanedBonds.size() ==
               1) {                // was 2 but the first one was erased
      matchedOrphanBondIndex = 0;  // only one left - it must be the match
    } else {
      throw FileParseException(
          "For a MultipleSgroup contraction, the orphaned bonds must be 0,2 or 4");
    }

    orphanedBondToFix->atomRefs2[1] =
        orphanedBonds[matchedOrphanBondIndex]
            ->atomRefs2[0];  // [0] is the orphaned atom (still in the mol)

    // undelete the bond which has been fixed (really remove it from the
    // list of bonds to be delete)

    auto undeleteIter =
        find(bondsToDelete.begin(), bondsToDelete.end(), orphanedBondToFix);
    TEST_ASSERT(undeleteIter != bondsToDelete.end());
    bondsToDelete.erase(undeleteIter);

    // any siblings or children that reference the matched Orphaned bond
    // must be fixed to reference the retained (fixed) orphan bond

    for (auto &siblingSgroup :
         this->parent->sgroups)  // note: includes this sgroups, which is
                                 // technically NOT a sibling
    {
      for (auto &bond : siblingSgroup->bonds) {
        if (bond->id == orphanedBonds[matchedOrphanBondIndex]->id) {
          bond = orphanedBondToFix;
        }
      }
    }

    // it COULD happen that children referenced the matched orphan bond

    for (auto &childSgroup : this->sgroups) {
      for (auto childBond : childSgroup->bonds) {
        if (childBond->id == orphanedBonds[matchedOrphanBondIndex]->id) {
          childBond = orphanedBondToFix;
        }
      }
    }
    TEST_ASSERT(matchedOrphanBondIndex >= 0 &&
                static_cast<unsigned int>(matchedOrphanBondIndex) <
                    orphanedBonds.size());
    orphanedBonds.erase(orphanedBonds.begin() + matchedOrphanBondIndex);
  };

  // if we get here, all the changes to be made have been determined. so
  // make them

  for (auto childSgroup : sgroupsToDelete) {
    auto sgroupIter =
        std::find_if(sgroups.begin(), sgroups.end(),
                     [childSgroup](std::unique_ptr<MarvinMolBase> &sgptr) {
                       return sgptr->id == childSgroup->id;
                     });
    TEST_ASSERT(sgroupIter != sgroups.end());
    sgroups.erase(sgroupIter);
  }

  // remove the atoms

  for (auto atomPtr : atomsToDelete) {
    for (auto thisParent = this->parent;;
         thisParent = thisParent->parent) {  // do all parents and grandparents
                                             // ... to to the actual parent

      auto deleteIter = std::find(thisParent->atoms.begin(),
                                  thisParent->atoms.end(), atomPtr);
      TEST_ASSERT(deleteIter != thisParent->atoms.end());
      thisParent->atoms.erase(deleteIter);

      if (thisParent == actualParent) {
        break;
      }
    }

    // also delete the atoms from this multiple group AND any sibling
    // sgroups

    for (auto &siblingSgroup : this->parent->sgroups) {
      auto siblingAtomPtr = std::find(siblingSgroup->atoms.begin(),
                                      siblingSgroup->atoms.end(), atomPtr);
      if (siblingAtomPtr != siblingSgroup->atoms.end()) {
        siblingSgroup->atoms.erase(siblingAtomPtr);
      }
    }

    removeOwnedAtom(atomPtr);
  }

  atomsToDelete.clear();

  // remove the bonds

  for (MarvinBond *bondPtr : bondsToDelete) {
    auto deleteIter = std::find(actualParent->bonds.begin(),
                                actualParent->bonds.end(), bondPtr);
    TEST_ASSERT(deleteIter != actualParent->bonds.end());
    actualParent->bonds.erase(deleteIter);
    actualParent->removeOwnedBond(bondPtr);
  }
  bondsToDelete.clear();

  this->isExpanded = false;
}

IsSgroupInAtomSetResult MarvinMolBase::isSgroupInSetOfAtoms(
    const std::vector<MarvinAtom *> &setOfAtoms) const {
  // superatom sgroups are different - it has an override for this call
  // if not overridden,  types are in the group based on their atoms

  bool isInGroup = false;
  bool isNotInGroup = false;
  for (auto oneAtom : this->atoms) {
    if (std::find_if(setOfAtoms.begin(), setOfAtoms.end(),
                     [&, oneAtom](auto a) { return a->id == oneAtom->id; }) !=
        setOfAtoms.end()) {
      isInGroup = true;
    } else {
      isNotInGroup = true;
    }
  }

  if (isInGroup && isNotInGroup) {
    return SgroupBothInAndNotInAtomSet;
  }

  if (isInGroup) {
    return SgroupInAtomSet;
  }

  return SgroupNotInAtomSet;
}

IsSgroupInAtomSetResult MarvinSuperatomSgroup::isSgroupInSetOfAtoms(
    const std::vector<MarvinAtom *> &setOfAtoms) const {
  // superatom sgroups are different - they are in the set if one of the
  // condensed atom in the parent is in group

  auto dummyAtomIter = find_if(
      parent->atoms.begin(), parent->atoms.end(),
      [this](const MarvinAtom *arg) { return arg->sgroupRef == this->id; });
  if (dummyAtomIter == parent->atoms.end()) {
    throw FileParseException("No contracted atom found for a superatomSgroup");
  }

  if (std::find_if(setOfAtoms.begin(), setOfAtoms.end(),
                   [&, dummyAtomIter](auto a) {
                     return a->id == (*dummyAtomIter)->id;
                   }) != setOfAtoms.end()) {
    return SgroupInAtomSet;
  }
  return SgroupNotInAtomSet;
}

void MarvinMolBase::processSgroupsFromRDKit() {
  // this routine recursively fixes sgroups to be in the heirarchy expected
  // by Marvin format

  if (this->isPassiveRoleForContraction()) {
    return;  // passive mols are only leaves of the tree - nothing to do
  }

  // see if any siblings should be children of this one

  MarvinMolBase *molToProcess =
      this;  // the processing MIGHT change the mol from one kind to another
             // (e.g. MarvinSuperatomSgroupExpanded ->
             // MarvinSuperatomSgroup)

  if (this->parent != nullptr)  // NOT the top level mol
  {
    std::vector<std::string> sgroupsMolIdsDone;
    for (bool allDone = false; !allDone;) {
      // until all at this level are done - but fixing one
      // child can add sgroups to this level
      allDone = true;  // until it is not true in the loop below
      for (auto &sibling : this->parent->sgroups) {
        if (std::find(sgroupsMolIdsDone.begin(), sgroupsMolIdsDone.end(),
                      sibling->molID) != sgroupsMolIdsDone.end()) {
          continue;  // look at the next one to see if it is done
        }

        allDone = false;
        sgroupsMolIdsDone.push_back(sibling->molID);

        if (sibling.get() == this) {
          continue;  // cannot be a child of itself
        }

        //  there are 2 possibilities:
        //  1) all atoms are in this one - make the sibling into a child of
        //  this one 2) SOME atoms are NOT this one - it remains a sibling

        if (sibling->isSgroupInSetOfAtoms(this->atoms) != SgroupInAtomSet) {
          continue;
        }

        moveSgroup(sibling.get(), this);
        break;  // have to re=start the loop over sgroups - it has just
                // changed
      }
    }

    std::string thisSgroupRole = this->role();
    if (thisSgroupRole == "SuperatomSgroupExpanded") {
      molToProcess =
          ((MarvinSuperatomSgroupExpanded *)this)->convertToOneSuperAtom();
    } else if (thisSgroupRole == "MultipleSgroup" &&
               ((MarvinMultipleSgroup *)this)->isExpanded == true) {
      try {
        ((MarvinMultipleSgroup *)this)->contractOneMultipleSgroup();
      } catch (FileParseException &e) {
        BOOST_LOG(rdErrorLog)
            << e.what() << std::endl
            << "The multiple sgroup will be ignored" << std::endl;

        auto sgroupIter = std::find_if(
            this->parent->sgroups.begin(), this->parent->sgroups.end(),
            [this](std::unique_ptr<MarvinMolBase> &sgptr) {
              return sgptr->id == this->id;
            });
        TEST_ASSERT(sgroupIter != this->parent->sgroups.end());
        this->parent->sgroups.erase(sgroupIter);
        return;
      }
    }
  }

  // now fix all this groups children

  std::vector<std::string> childrenSgroupsMolIdsDone;
  for (bool allDone = false;
       !allDone;)  // until all at this level are done - but fixing one
                   // child can add sgroups to this level
  {
    allDone = true;  // until it is not true in the loop below
    for (auto &childSgroup : molToProcess->sgroups) {
      if (std::find(childrenSgroupsMolIdsDone.begin(),
                    childrenSgroupsMolIdsDone.end(),
                    childSgroup->molID) != childrenSgroupsMolIdsDone.end()) {
        continue;  // this one is done, look at the next one
      }

      childrenSgroupsMolIdsDone.push_back(childSgroup->molID);
      childSgroup->processSgroupsFromRDKit();
      allDone = false;
      break;  // have to start the loop over - we might have changed the
              // vector
    }
  }

  return;
}

MarvinMolBase *MarvinMol::copyMol(const std::string &) const {
  PRECONDITION(0, "Internal error:  copying a MarvinMol");
}

std::string MarvinMol::toString() const {
  std::ostringstream out;

  out << "<molecule molID=\"" << molID << "\">";

  out << "<atomArray>";
  for (auto atom : atoms) {
    out << atom->toString();
  }
  out << "</atomArray>";

  out << "<bondArray>";
  for (auto bond : bonds) {
    out << bond->toString();
  }
  out << "</bondArray>";

  for (auto &sgroup : sgroups) {
    out << sgroup->toString();
  }

  out << "</molecule>";

  return out.str();
}

ptree MarvinMol::toPtree() const {
  ptree out = MarvinMolBase::toPtree();

  MarvinMolBase::addSgroupsToPtree(out);

  return out;
}

std::string MarvinMol::generateMolString() {
  std::ostringstream out;

  out << "<cml xmlns=\"http://www.chemaxon.com\"  xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
         "xsi:schemaLocation=\"http://www.chemaxon.com http://www.chemaxon.com/marvin/schema/mrvSchema_20_20_0.xsd\">"
         "<MDocument><MChemicalStruct>";

  out << toString();

  out << "</MChemicalStruct></MDocument></cml>";

  return out.str();
}

ptree MarvinMol::toMolPtree() const {
  ptree out;

  out.put("cml.<xmlattr>.xmlns", "http://www.chemaxon.com");
  out.put("cml.<xmlattr>.xmlns:xsi",
          "http://www.w3.org/2001/XMLSchema-instance");
  out.put(
      "cml.<xmlattr>.xsi:schemaLocation",
      "http://www.chemaxon.com http://www.chemaxon.com/marvin/schema/mrvSchema_20_20_0.xsd");
  out.put_child("cml.MDocument.MChemicalStruct.molecule", toPtree());
  return out;
}

MarvinReaction::~MarvinReaction() {}

void MarvinReaction::prepSgroupsForRDKit() {
  // This routine converts all the mols in the rxn to be ready for
  // conversion to RDKIT mols
  int molCount = 0, atomCount = 0, bondCount = 0, sgCount = 0;

  std::map<std::string, std::string> sgMap;
  std::map<std::string, std::string> atomMap;
  std::map<std::string, std::string> bondMap;

  for (auto &reactant : reactants) {
    reactant->prepSgroupsForRDKit();

    reactant->cleanUpNumbering(molCount, atomCount, bondCount, sgCount, sgMap,
                               atomMap, bondMap);
  }
  for (auto &agent : agents) {
    agent->prepSgroupsForRDKit();
    agent->cleanUpNumbering(molCount, atomCount, bondCount, sgCount, sgMap,
                            atomMap, bondMap);
  }
  for (auto &product : products) {
    product->prepSgroupsForRDKit();
    product->cleanUpNumbering(molCount, atomCount, bondCount, sgCount, sgMap,
                              atomMap, bondMap);
  }
}

std::string MarvinReaction::toString() {
  std::ostringstream out;

  out << "<cml xmlns=\"http://www.chemaxon.com\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
         " xsi:schemaLocation=\"http://www.chemaxon.com http://www.chemaxon.com/marvin/schema/mrvSchema_20_20_0.xsd\">"
         "<MDocument><MChemicalStruct><reaction>";

  out << "<reactantList>";
  for (auto &reactant : reactants) {
    out << reactant->toString();
  }
  out << "</reactantList>";
  out << "<agentList>";
  for (auto &agent : agents) {
    out << agent->toString();
  }
  out << "</agentList>";
  out << "<productList>";
  for (auto &product : products) {
    out << product->toString();
  }
  out << "</productList>";

  out << arrow.toString();

  out << "</reaction></MChemicalStruct>";

  for (auto &pluse : pluses) {
    out << pluse->toString();
  }
  for (auto &condition : conditions) {
    out << condition->toString();
  }

  out << "</MDocument></cml>";
  return out.str();
}

ptree MarvinReaction::toPtree() const {
  ptree out;

  out.put("cml.<xmlattr>.xmlns", "http://www.chemaxon.com");
  out.put("cml.<xmlattr>.xmlns:xsi",
          "http://www.w3.org/2001/XMLSchema-instance");
  out.put(
      "cml.<xmlattr>.xsi:schemaLocation",
      "http://www.chemaxon.com http://www.chemaxon.com/marvin/schema/mrvSchema_20_20_0.xsd");

  for (auto &reactant : reactants) {
    out.add_child(
        "cml.MDocument.MChemicalStruct.reaction.reactantList.molecule",
        reactant->toPtree());
  }

  for (auto &agent : agents) {
    out.add_child("cml.MDocument.MChemicalStruct.reaction.agentList.molecule",
                  agent->toPtree());
  }

  for (auto &product : products) {
    out.add_child("cml.MDocument.MChemicalStruct.reaction.productList.molecule",
                  product->toPtree());
  }

  out.put_child("cml.MDocument.MChemicalStruct.reaction.arrow",
                arrow.toPtree());

  for (auto &plus : pluses) {
    out.add_child("cml.MDocument.MReactionSign", plus->toPtree());
  }

  for (auto &condition : conditions) {
    out.add_child("cml.MDocument.MTextBox", condition->toPtree());
  }

  return out;
}

MarvinRectangle::MarvinRectangle(double left, double right, double top,
                                 double bottom) {
  upperLeft.x = left;
  upperLeft.y = top;
  lowerRight.x = right;
  lowerRight.y = bottom;
  centerIsStale = true;
}

MarvinRectangle::MarvinRectangle(const RDGeom::Point3D &upperLeftInit,
                                 const RDGeom::Point3D &lowerRightInit) {
  upperLeft = upperLeftInit;
  lowerRight = lowerRightInit;
  centerIsStale = true;
}

MarvinRectangle::MarvinRectangle(const std::vector<MarvinAtom *> &atoms) {
  centerIsStale = true;

  if (atoms.size() == 0) {
    return;
  }
  upperLeft.x = DBL_MAX;
  upperLeft.y = -DBL_MAX;
  lowerRight.x = -DBL_MAX;
  lowerRight.y = DBL_MAX;

  for (auto atom : atoms) {
    upperLeft.x = std::min(upperLeft.x, atom->x2);
    lowerRight.x = std::max(lowerRight.x, atom->x2);
    upperLeft.y = std::max(upperLeft.y, atom->y2);
    lowerRight.y = std::min(lowerRight.y, atom->y2);
  }
}

MarvinRectangle::MarvinRectangle(const std::vector<MarvinRectangle> &rects) {
  centerIsStale = true;

  if (rects.size() == 0) {
    return;
  }
  upperLeft.x = DBL_MAX;
  upperLeft.y = -DBL_MAX;
  lowerRight.x = -DBL_MAX;
  lowerRight.y = DBL_MAX;

  for (auto rect : rects) {
    this->extend(rect);
  }
}

void MarvinRectangle::extend(const MarvinRectangle &otherRectangle) {
  if (otherRectangle.upperLeft.x < upperLeft.x) {
    upperLeft.x = otherRectangle.upperLeft.x;
  }
  if (otherRectangle.lowerRight.x > lowerRight.x) {
    lowerRight.x = otherRectangle.lowerRight.x;
  }

  if (otherRectangle.upperLeft.y > upperLeft.y) {
    upperLeft.y = otherRectangle.upperLeft.y;
  }
  if (otherRectangle.lowerRight.y < lowerRight.y) {
    lowerRight.y = otherRectangle.lowerRight.y;
  }

  centerIsStale = true;
}

RDGeom::Point3D &MarvinRectangle::getCenter() {
  if (centerIsStale) {
    center.x = (lowerRight.x + upperLeft.x) / 2.0;
    center.y = (lowerRight.y + upperLeft.y) / 2.0;
    centerIsStale = false;
  }
  return center;
}

bool MarvinRectangle::overlapsVertically(
    const MarvinRectangle &otherRectangle) const {
  if (otherRectangle.upperLeft.y < lowerRight.y ||
      otherRectangle.lowerRight.y > upperLeft.y) {
    return false;
  }
  return true;
}

bool MarvinRectangle::overlapsVHorizontally(
    const MarvinRectangle &otherRectangle) const {
  if (otherRectangle.upperLeft.x > lowerRight.x ||
      otherRectangle.lowerRight.x < upperLeft.x) {
    return false;
  }
  return true;
}

bool MarvinRectangle::compareRectanglesByX(MarvinRectangle &r1,
                                           MarvinRectangle &r2) {
  return (r1.getCenter().x < r2.getCenter().x);
}

bool MarvinRectangle::compareRectanglesByYReverse(MarvinRectangle &r1,
                                                  MarvinRectangle &r2) {
  return (r1.getCenter().y > r2.getCenter().y);
}

MarvinStereoGroup::MarvinStereoGroup(StereoGroupType grouptypeInit,
                                     int groupNumberInit) {
  groupType = grouptypeInit;
  groupNumber = groupNumberInit;
}
}  // namespace RDKit