summary refs log tree commit diff stats
path: root/generator/generator.cpp
blob: ad665a24296ace9006e6a2b6f484bf4e5a35c45b (plain) (blame)
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
#include "generator.h"
#include <stdexcept>
#include <iostream>
#include <regex>
#include <dirent.h>
#include <fstream>
#include <hkutil/string.h>
#include <hkutil/progress.h>
#include "role.h"
#include "part.h"
#include "../lib/enums.h"
#include "../lib/version.h"

namespace verbly {
  namespace generator {

    generator::generator(
      std::string verbNetPath,
      std::string agidPath,
      std::string wordNetPath,
      std::string cmudictPath,
      std::string imageNetPath,
      std::string outputPath) :
        verbNetPath_(verbNetPath),
        agidPath_(agidPath),
        wordNetPath_(wordNetPath),
        cmudictPath_(cmudictPath),
        imageNetPath_(imageNetPath),
        db_(outputPath, hatkirby::dbmode::create)
    {
      // Ensure VerbNet directory exists
      DIR* dir;
      if ((dir = opendir(verbNetPath_.c_str())) == nullptr)
      {
        throw std::invalid_argument("Invalid VerbNet data directory");
      }

      closedir(dir);

      // Ensure AGID infl.txt exists
      if (!std::ifstream(agidPath_))
      {
        throw std::invalid_argument("AGID infl.txt file not found");
      }

      // Add directory separator to WordNet path
      if ((wordNetPath_.back() != '/') && (wordNetPath_.back() != '\\'))
      {
        wordNetPath_ += '/';
      }

      // Ensure WordNet tables exist
      for (std::string table : {
        "s", "sk", "ant", "at", "cls", "hyp", "ins", "mm", "mp", "ms", "per",
        "sa", "sim", "syntax"
      })
      {
        if (!std::ifstream(wordNetPath_ + "wn_" + table + ".pl"))
        {
          throw std::invalid_argument("WordNet " + table + " table not found");
        }
      }

      // Ensure CMUDICT file exists
      if (!std::ifstream(cmudictPath_))
      {
        throw std::invalid_argument("CMUDICT file not found");
      }

      // Ensure ImageNet urls.txt exists
      if (!std::ifstream(imageNetPath_))
      {
        throw std::invalid_argument("ImageNet urls.txt file not found");
      }
    }

    void generator::run()
    {
      // Create notions, words, lemmas, and forms from WordNet synsets
      readWordNetSynsets();

      // Reads adjective positioning WordNet data
      readAdjectivePositioning();

      // Counts the number of URLs ImageNet has per notion
      readImageNetUrls();

      // Creates a word by WordNet sense key lookup table
      readWordNetSenseKeys();

      // Creates groups and frames from VerbNet data
      readVerbNet();

      // Creates forms and inflections from AGID. To reduce the amount of forms
      // created, we do this after most lemmas that need inflecting have been
      // created through other means, and then only generate forms for
      // inflections of already-existing lemmas. The exception to this regards
      // verb lemmas. If a verb lemma in AGID either does not exist yet, or does
      // exist but is not related to any words that are related to verb notions,
      // then a notion and a word is generated and the form generation proceeds
      // as usual.
      readAgidInflections();

      // Reads in prepositions and the is_a relationship
      readPrepositions();

      // Creates pronunciations from CMUDICT. To reduce the amount of
      // pronunciations created, we do this after all forms have been created,
      // and then only generate pronunciations for already-exisiting forms.
      readCmudictPronunciations();

      // Writes the database schema
      writeSchema();

      // Writes the database version
      writeVersion();

      // Dumps data to the database
      dumpObjects();

      // Populates the antonymy relationship from WordNet
      readWordNetAntonymy();

      // Populates the variation relationship from WordNet
      readWordNetVariation();

      // Populates the usage, topicality, and regionality relationships from
      // WordNet
      readWordNetClasses();

      // Populates the causality relationship from WordNet
      readWordNetCausality();

      // Populates the entailment relationship from WordNet
      readWordNetEntailment();

      // Populates the hypernymy relationship from WordNet
      readWordNetHypernymy();

      // Populates the instantiation relationship from WordNet
      readWordNetInstantiation();

      // Populates the member meronymy relationship from WordNet
      readWordNetMemberMeronymy();

      // Populates the part meronymy relationship from WordNet
      readWordNetPartMeronymy();

      // Populates the substance meronymy relationship from WordNet
      readWordNetSubstanceMeronymy();

      // Populates the pertainymy and mannernymy relationships from WordNet
      readWordNetPertainymy();

      // Populates the specification relationship from WordNet
      readWordNetSpecification();

      // Populates the adjective similarity relationship from WordNet
      readWordNetSimilarity();

      // Generates analysis data to assist in query planning.
      analyzeDatabase();
    }

    void generator::readWordNetSynsets()
    {
      std::list<std::string> lines(readFile(wordNetPath_ + "wn_s.pl"));
      hatkirby::progress ppgs("Reading synsets from WordNet...", lines.size());

      for (std::string line : lines)
      {
        ppgs.update();

        std::regex relation(
          "^s\\(([1234]\\d{8}),(\\d+),'(.+)',\\w,\\d+,(\\d+)\\)\\.$");

        std::smatch relation_data;
        if (!std::regex_search(line, relation_data, relation))
        {
          continue;
        }

        int synset_id = std::stoi(relation_data[1]);
        int wnum = std::stoi(relation_data[2]);
        std::string text = relation_data[3];
        int tag_count = std::stoi(relation_data[4]);
        size_t word_it;
        while ((word_it = text.find("''")) != std::string::npos)
        {
          text.erase(word_it, 1);
        }

        // The WordNet data does contain duplicates, so we need to check that we
        // haven't already created this word.
        std::pair<int, int> lookup(synset_id, wnum);
        if (!wordByWnidAndWnum_.count(lookup))
        {
          notion& synset = lookupOrCreateNotion(synset_id);
          lemma& lex = lookupOrCreateLemma(text);
          word& entry = createWord(synset, lex, tag_count);

          wordByWnidAndWnum_[lookup] = &entry;
        }
      }
    }

    void generator::readAdjectivePositioning()
    {
      std::list<std::string> lines(readFile(wordNetPath_ + "wn_syntax.pl"));

      hatkirby::progress ppgs(
        "Reading adjective positionings from WordNet...",
        lines.size());

      for (std::string line : lines)
      {
        ppgs.update();

        std::regex relation("^syntax\\((3\\d{8}),(\\d+),([ipa])p?\\)\\.");
        std::smatch relation_data;
        if (!std::regex_search(line, relation_data, relation))
        {
          continue;
        }

        int synset_id = stoi(relation_data[1]);
        int wnum = stoi(relation_data[2]);
        std::string adjpos_str = relation_data[3];

        std::pair<int, int> lookup(synset_id, wnum);
        if (wordByWnidAndWnum_.count(lookup))
        {
          word& adj = *wordByWnidAndWnum_.at(lookup);

          if (adjpos_str == "p")
          {
            adj.setAdjectivePosition(positioning::predicate);
          } else if (adjpos_str == "a")
          {
            adj.setAdjectivePosition(positioning::attributive);
          } else if (adjpos_str == "i")
          {
            adj.setAdjectivePosition(positioning::postnominal);
          } else {
            throw std::logic_error("adjpos_str invalid");
          }
        }
      }
    }

    void generator::readImageNetUrls()
    {
      // The ImageNet datafile is so large that it is unreasonable and
      // unnecessary to read it into memory; instead, we will parse each line as
      // we read it. This has the caveat that we cannot display a progress bar.
      std::cout << "Reading image counts from ImageNet..." << std::endl;

      std::ifstream file(imageNetPath_);
      if (!file)
      {
        throw std::invalid_argument("Could not find file " + imageNetPath_);
      }

      std::string line;
      while (std::getline(file, line))
      {
        if (line.back() == '\r')
        {
          line.pop_back();
        }

        std::string wnid_s = line.substr(1, 8);
        int wnid = stoi(wnid_s) + 100000000;
        if (notionByWnid_.count(wnid))
        {
          // We know that this notion has a wnid and is a noun.
          notionByWnid_.at(wnid)->incrementNumOfImages();
        }
      }
    }

    void generator::readWordNetSenseKeys()
    {
      std::list<std::string> lines(readFile(wordNetPath_ + "wn_sk.pl"));

      hatkirby::progress ppgs(
        "Reading sense keys from WordNet...",
        lines.size());

      for (std::string line : lines)
      {
        ppgs.update();

        // We only actually need to lookup verbs by sense key so we'll just
        // ignore everything that isn't a verb.
        std::regex relation("^sk\\((2\\d{8}),(\\d+),'(.+)'\\)\\.$");
        std::smatch relation_data;
        if (!std::regex_search(line, relation_data, relation))
        {
          continue;
        }

        int synset_id = stoi(relation_data[1]);
        int wnum = stoi(relation_data[2]);
        std::string sense_key = relation_data[3];

        // We are treating this mapping as injective, which is not entirely
        // accurate. First, the WordNet table contains duplicate rows, so those
        // need to be ignored. More importantly, a small number of sense keys
        // (one for each letter of the Latin alphabet, plus 9 other words) each
        // map to two different words in the same synset which differ only by
        // capitalization. Luckily, none of these exceptions are verbs, so we
        // can pretend that the mapping is injective.
        if (!wnSenseKeys_.count(sense_key))
        {
          std::pair<int, int> lookup(synset_id, wnum);
          if (wordByWnidAndWnum_.count(lookup))
          {
            wnSenseKeys_[sense_key] = wordByWnidAndWnum_.at(lookup);
          }
        }
      }
    }

    void generator::readVerbNet()
    {
      std::cout << "Reading frames from VerbNet..." << std::endl;

      DIR* dir;
      if ((dir = opendir(verbNetPath_.c_str())) == nullptr)
      {
        throw std::invalid_argument("Invalid VerbNet data directory");
      }

      struct dirent* ent;
      while ((ent = readdir(dir)) != nullptr)
      {
        std::string filename(verbNetPath_);

        if (filename.back() != '/')
        {
          filename += '/';
        }

        filename += ent->d_name;

        if (filename.rfind(".xml") != filename.size() - 4)
        {
          continue;
        }

        xmlDocPtr doc = xmlParseFile(filename.c_str());
        if (doc == nullptr)
        {
          throw std::logic_error("Error opening " + filename);
        }

        xmlNodePtr top = xmlDocGetRootElement(doc);
        if ((top == nullptr) ||
            (xmlStrcmp(top->name, reinterpret_cast<const xmlChar*>("VNCLASS"))))
        {
          throw std::logic_error("Bad VerbNet file format: " + filename);
        }

        try
        {
          createGroup(top);
        } catch (const std::exception& e)
        {
          std::throw_with_nested(
            std::logic_error("Error parsing VerbNet file: " + filename));
        }
      }

      closedir(dir);
    }

    void generator::readAgidInflections()
    {
      std::list<std::string> lines(readFile(agidPath_));
      hatkirby::progress ppgs("Reading inflections from AGID...", lines.size());

      for (std::string line : lines)
      {
        ppgs.update();

        int divider = line.find_first_of(" ");
        std::string infinitive = line.substr(0, divider);
        line = line.substr(divider+1);
        char type = line[0];

        if (line[1] == '?')
        {
          line.erase(0, 4);
        } else {
          line.erase(0, 3);
        }

        if (!lemmaByBaseForm_.count(infinitive) && (type != 'V'))
        {
          continue;
        }

        lemma& curLemma = lookupOrCreateLemma(infinitive);

        auto inflWordList =
          hatkirby::split<std::list<std::string>>(line, " | ");

        std::vector<std::list<std::string>> agidForms;
        for (std::string inflForms : inflWordList)
        {
          auto inflFormList =
            hatkirby::split<std::list<std::string>>(std::move(inflForms), ", ");

          std::list<std::string> forms;
          for (std::string inflForm : inflFormList)
          {
            int sympos = inflForm.find_first_of("~<!? ");
            if (sympos != std::string::npos)
            {
              inflForm = inflForm.substr(0, sympos);
            }

            forms.push_back(std::move(inflForm));
          }

          agidForms.push_back(std::move(forms));
        }

        std::map<inflection, std::list<std::string>> mappedForms;
        switch (type)
        {
          case 'V':
          {
            if (agidForms.size() == 4)
            {
              mappedForms[inflection::past_tense] = agidForms[0];
              mappedForms[inflection::past_participle] = agidForms[1];
              mappedForms[inflection::ing_form] = agidForms[2];
              mappedForms[inflection::s_form] = agidForms[3];
            } else if (agidForms.size() == 3)
            {
              mappedForms[inflection::past_tense] = agidForms[0];
              mappedForms[inflection::past_participle] = agidForms[0];
              mappedForms[inflection::ing_form] = agidForms[1];
              mappedForms[inflection::s_form] = agidForms[2];
            } else if (agidForms.size() == 8)
            {
              // As of AGID 2014.08.11, this is only "to be"
              mappedForms[inflection::past_tense] = agidForms[0];
              mappedForms[inflection::past_participle] = agidForms[2];
              mappedForms[inflection::ing_form] = agidForms[3];
              mappedForms[inflection::s_form] = agidForms[4];
            } else {
              // Words that don't fit the cases above as of AGID 2014.08.11:
              // - may and shall do not conjugate the way we want them to
              // - methinks only has a past tense and is an outlier
              // - wit has five forms, and is archaic/obscure enough that we can ignore it for now
              std::cout << " Ignoring verb \"" << infinitive
                << "\" due to non-standard number of forms." << std::endl;
            }

            // For verbs in particular, we sometimes create a notion and a word
            // from inflection data. Specifically, if there are not yet any
            // verbs existing that have the same infinitive form. "Yet" means
            // that this verb appears in the AGID data but not in either WordNet
            // or VerbNet.
            if (!wordsByBaseForm_.count(infinitive)
              || !std::any_of(
                std::begin(wordsByBaseForm_.at(infinitive)),
                std::end(wordsByBaseForm_.at(infinitive)),
                [] (word* w) {
                  return (w->getNotion().getPartOfSpeech() ==
                    part_of_speech::verb);
                }))
            {
              notion& n = createNotion(part_of_speech::verb);
              createWord(n, curLemma);
            }

            break;
          }

          case 'A':
          {
            if (agidForms.size() == 2)
            {
              mappedForms[inflection::comparative] = agidForms[0];
              mappedForms[inflection::superlative] = agidForms[1];
            } else {
              // As of AGID 2014.08.11, this is only "only", which has only the form "onliest"
              std::cout << " Ignoring adjective/adverb \"" << infinitive
                << "\" due to non-standard number of forms." << std::endl;
            }

            break;
          }

          case 'N':
          {
            if (agidForms.size() == 1)
            {
              mappedForms[inflection::plural] = agidForms[0];
            } else {
              // As of AGID 2014.08.11, this is non-existent.
              std::cout << " Ignoring noun \"" << infinitive
                << "\" due to non-standard number of forms." << std::endl;
            }

            break;
          }
        }

        // Compile the forms we have mapped.
        for (auto mapping : std::move(mappedForms))
        {
          for (std::string infl : std::move(mapping.second))
          {
            curLemma.addInflection(
              mapping.first,
              lookupOrCreateForm(std::move(infl)));
          }
        }
      }
    }

    void generator::readPrepositions()
    {
      std::list<std::string> lines(readFile("prepositions.txt"));
      hatkirby::progress ppgs("Reading prepositions...", lines.size());

      for (std::string line : lines)
      {
        ppgs.update();

        std::regex relation("^([^:]+): (.+)");
        std::smatch relation_data;
        std::regex_search(line, relation_data, relation);
        std::string prep = relation_data[1];

        auto groups =
          hatkirby::split<std::list<std::string>>(relation_data[2], ", ");

        notion& n = createNotion(part_of_speech::preposition);
        lemma& l = lookupOrCreateLemma(prep);
        word& w = createWord(n, l);

        n.setPrepositionGroups(groups);
      }
    }

    void generator::readCmudictPronunciations()
    {
      std::list<std::string> lines(readFile(cmudictPath_));

      hatkirby::progress ppgs(
        "Reading pronunciations from CMUDICT...",
        lines.size());

      for (std::string line : lines)
      {
        ppgs.update();

        std::regex phoneme("([A-Z][^ \\(]*)(?:\\(\\d+\\))?  ([A-Z 0-9]+)");
        std::smatch phoneme_data;
        if (std::regex_search(line, phoneme_data, phoneme))
        {
          std::string canonical = hatkirby::lowercase(phoneme_data[1]);

          if (!formByText_.count(canonical))
          {
            continue;
          }

          std::string phonemes = phoneme_data[2];
          if (pronunciationByPhonemes_.count(phonemes)) {
            pronunciation& p = *pronunciationByPhonemes_[phonemes];
            formByText_.at(canonical)->addPronunciation(p);
          } else {
            pronunciations_.emplace_back(phonemes);
            pronunciation& p = pronunciations_.back();
            pronunciationByPhonemes_[phonemes] = &p;
            formByText_.at(canonical)->addPronunciation(p);
          }
        }
      }
    }

    void generator::writeSchema()
    {
      std::ifstream file("schema.sql");
      if (!file)
      {
        throw std::invalid_argument("Could not find database schema");
      }

      std::ostringstream schemaBuilder;
      std::string line;
      while (std::getline(file, line))
      {
        if (line.back() == '\r')
        {
          line.pop_back();
        }

        schemaBuilder << line;
      }

      std::string schema = schemaBuilder.str();
      auto queries = hatkirby::split<std::list<std::string>>(schema, ";");

      hatkirby::progress ppgs("Writing database schema...", queries.size());
      for (std::string query : queries)
      {
        if (!queries.empty())
        {
          db_.execute(query);
        }

        ppgs.update();
      }
    }

    void generator::writeVersion()
    {
      db_.insertIntoTable(
        "version",
        {
          { "major", DATABASE_MAJOR_VERSION },
          { "minor", DATABASE_MINOR_VERSION }
        });
    }

    void generator::dumpObjects()
    {
      {
        hatkirby::progress ppgs("Writing notions...", notions_.size());

        for (notion& n : notions_)
        {
          db_ << n;

          ppgs.update();
        }
      }

      {
        hatkirby::progress ppgs("Writing words...", words_.size());

        for (word& w : words_)
        {
          db_ << w;

          ppgs.update();
        }
      }

      {
        hatkirby::progress ppgs("Writing lemmas...", lemmas_.size());

        for (lemma& l : lemmas_)
        {
          db_ << l;

          ppgs.update();
        }
      }

      {
        hatkirby::progress ppgs("Writing forms...", forms_.size());

        for (form& f : forms_)
        {
          db_ << f;

          ppgs.update();
        }
      }

      {
        hatkirby::progress ppgs("Writing pronunciations...", pronunciations_.size());

        for (pronunciation& p : pronunciations_)
        {
          db_ << p;

          ppgs.update();
        }
      }

      {
        hatkirby::progress ppgs("Writing verb frames...", groups_.size());

        for (group& g : groups_)
        {
          db_ << g;

          ppgs.update();
        }
      }
    }

    void generator::readWordNetAntonymy()
    {
      std::list<std::string> lines(readFile(wordNetPath_ + "wn_ant.pl", true));

      hatkirby::progress ppgs("Writing antonyms...", lines.size());
      for (auto line : lines)
      {
        ppgs.update();

        std::regex relation(
          "^ant\\(([134]\\d{8}),(\\d+),([134]\\d{8}),(\\d+)\\)\\.");

        std::smatch relation_data;
        if (!std::regex_search(line, relation_data, relation))
        {
          continue;
        }

        std::pair<int, int> lookup1(
          std::stoi(relation_data[1]),
          std::stoi(relation_data[2]));

        std::pair<int, int> lookup2(
          std::stoi(relation_data[3]),
          std::stoi(relation_data[4]));

        if (wordByWnidAndWnum_.count(lookup1) &&
            wordByWnidAndWnum_.count(lookup2))
        {
          word& word1 = *wordByWnidAndWnum_.at(lookup1);
          word& word2 = *wordByWnidAndWnum_.at(lookup2);

          db_.insertIntoTable(
            "antonymy",
            {
              { "antonym_1_id", word1.getId() },
              { "antonym_2_id", word2.getId() }
            });
        }
      }
    }

    void generator::readWordNetVariation()
    {
      std::list<std::string> lines(readFile(wordNetPath_ + "wn_at.pl"));
      hatkirby::progress ppgs("Writing variation...", lines.size());
      for (auto line : lines)
      {
        ppgs.update();

        std::regex relation("^at\\((1\\d{8}),(3\\d{8})\\)\\.");
        std::smatch relation_data;
        if (!std::regex_search(line, relation_data, relation))
        {
          continue;
        }

        int lookup1 = std::stoi(relation_data[1]);
        int lookup2 = std::stoi(relation_data[2]);

        if (notionByWnid_.count(lookup1) && notionByWnid_.count(lookup2))
        {
          notion& notion1 = *notionByWnid_.at(lookup1);
          notion& notion2 = *notionByWnid_.at(lookup2);

          db_.insertIntoTable(
            "variation",
            {
              { "noun_id", notion1.getId() },
              { "adjective_id", notion2.getId() }
            });
        }
      }
    }

    void generator::readWordNetClasses()
    {
      std::list<std::string> lines(readFile(wordNetPath_ + "wn_cls.pl", true));

      hatkirby::progress ppgs(
        "Writing usage, topicality, and regionality...",
        lines.size());

      for (auto line : lines)
      {
        ppgs.update();

        std::regex relation(
          "^cls\\(([134]\\d{8}),(\\d+),(1\\d{8}),(\\d+),([tur])\\)\\.");

        std::smatch relation_data;
        if (!std::regex_search(line, relation_data, relation))
        {
          continue;
        }

        std::pair<int, int> lookup1(
          std::stoi(relation_data[1]),
          std::stoi(relation_data[2]));

        std::pair<int, int> lookup2(
          std::stoi(relation_data[3]),
          std::stoi(relation_data[4]));

        std::string class_type = relation_data[5];

        std::string table_name;
        if (class_type == "t")
        {
          table_name += "topicality";
        } else if (class_type == "u")
        {
          table_name += "usage";
        } else if (class_type == "r")
        {
          table_name += "regionality";
        }

        std::list<int> leftJoin;
        std::list<int> rightJoin;

        if ((lookup1.second == 0) && (wordsByWnid_.count(lookup1.first)))
        {
          auto& wordSet = wordsByWnid_.at(lookup1.first);

          std::transform(
            std::begin(wordSet),
            std::end(wordSet),
            std::back_inserter(leftJoin),
            [] (word* w) {
              return w->getId();
            });
        } else if (wordByWnidAndWnum_.count(lookup1)) {
          leftJoin.push_back(wordByWnidAndWnum_.at(lookup1)->getId());
        }

        if ((lookup2.second == 0) && (wordsByWnid_.count(lookup2.first)))
        {
          auto& wordSet = wordsByWnid_.at(lookup2.first);

          std::transform(
            std::begin(wordSet),
            std::end(wordSet),
            std::back_inserter(rightJoin),
            [] (word* w) {
              return w->getId();
            });
        } else if (wordByWnidAndWnum_.count(lookup2)) {
          rightJoin.push_back(wordByWnidAndWnum_.at(lookup2)->getId());
        }

        for (int word1 : leftJoin)
        {
          for (int word2 : rightJoin)
          {
            db_.insertIntoTable(
              table_name,
              {
                { "term_id", word1 },
                { "domain_id", word2 }
              });
          }
        }
      }
    }

    void generator::readWordNetCausality()
    {
      std::list<std::string> lines(readFile(wordNetPath_ + "wn_cs.pl"));
      hatkirby::progress ppgs("Writing causality...", lines.size());
      for (auto line : lines)
      {
        ppgs.update();

        std::regex relation("^cs\\((2\\d{8}),(2\\d{8})\\)\\.");
        std::smatch relation_data;
        if (!std::regex_search(line, relation_data, relation))
        {
          continue;
        }

        int lookup1 = std::stoi(relation_data[1]);
        int lookup2 = std::stoi(relation_data[2]);

        if (notionByWnid_.count(lookup1) && notionByWnid_.count(lookup2))
        {
          notion& notion1 = *notionByWnid_.at(lookup1);
          notion& notion2 = *notionByWnid_.at(lookup2);

          db_.insertIntoTable(
            "causality",
            {
              { "effect_id", notion1.getId() },
              { "cause_id", notion2.getId() }
            });
        }
      }
    }

    void generator::readWordNetEntailment()
    {
      std::list<std::string> lines(readFile(wordNetPath_ + "wn_ent.pl"));
      hatkirby::progress ppgs("Writing entailment...", lines.size());
      for (auto line : lines)
      {
        ppgs.update();

        std::regex relation("^ent\\((2\\d{8}),(2\\d{8})\\)\\.");
        std::smatch relation_data;
        if (!std::regex_search(line, relation_data, relation))
        {
          continue;
        }

        int lookup1 = std::stoi(relation_data[1]);
        int lookup2 = std::stoi(relation_data[2]);

        if (notionByWnid_.count(lookup1) && notionByWnid_.count(lookup2))
        {
          notion& notion1 = *notionByWnid_.at(lookup1);
          notion& notion2 = *notionByWnid_.at(lookup2);

          db_.insertIntoTable(
            "entailment",
            {
              { "given_id", notion1.getId() },
              { "entailment_id", notion2.getId() }
            });
        }
      }
    }

    void generator::readWordNetHypernymy()
    {
      std::list<std::string> lines(readFile(wordNetPath_ + "wn_hyp.pl"));
      hatkirby::progress ppgs("Writing hypernymy...", lines.size());
      for (auto line : lines)
      {
        ppgs.update();

        std::regex relation("^hyp\\(([12]\\d{8}),([12]\\d{8})\\)\\.");
        std::smatch relation_data;
        if (!std::regex_search(line, relation_data, relation))
        {
          continue;
        }

        int lookup1 = std::stoi(relation_data[1]);
        int lookup2 = std::stoi(relation_data[2]);

        if (notionByWnid_.count(lookup1) && notionByWnid_.count(lookup2))
        {
          notion& notion1 = *notionByWnid_.at(lookup1);
          notion& notion2 = *notionByWnid_.at(lookup2);

          db_.insertIntoTable(
            "hypernymy",
            {
              { "hyponym_id", notion1.getId() },
              { "hypernym_id", notion2.getId() }
            });
        }
      }
    }

    void generator::readWordNetInstantiation()
    {
      std::list<std::string> lines(readFile(wordNetPath_ + "wn_ins.pl"));
      hatkirby::progress ppgs("Writing instantiation...", lines.size());
      for (auto line : lines)
      {
        ppgs.update();

        std::regex relation("^ins\\((1\\d{8}),(1\\d{8})\\)\\.");
        std::smatch relation_data;
        if (!std::regex_search(line, relation_data, relation))
        {
          continue;
        }

        int lookup1 = std::stoi(relation_data[1]);
        int lookup2 = std::stoi(relation_data[2]);

        if (notionByWnid_.count(lookup1) && notionByWnid_.count(lookup2))
        {
          notion& notion1 = *notionByWnid_.at(lookup1);
          notion& notion2 = *notionByWnid_.at(lookup2);

          db_.insertIntoTable(
            "instantiation",
            {
              { "instance_id", notion1.getId() },
              { "class_id", notion2.getId() }
            });
        }
      }
    }

    void generator::readWordNetMemberMeronymy()
    {
      std::list<std::string> lines(readFile(wordNetPath_ + "wn_mm.pl"));
      hatkirby::progress ppgs("Writing member meronymy...", lines.size());
      for (auto line : lines)
      {
        ppgs.update();

        std::regex relation("^mm\\((1\\d{8}),(1\\d{8})\\)\\.");
        std::smatch relation_data;
        if (!std::regex_search(line, relation_data, relation))
        {
          continue;
        }

        int lookup1 = std::stoi(relation_data[1]);
        int lookup2 = std::stoi(relation_data[2]);

        if (notionByWnid_.count(lookup1) && notionByWnid_.count(lookup2))
        {
          notion& notion1 = *notionByWnid_.at(lookup1);
          notion& notion2 = *notionByWnid_.at(lookup2);

          db_.insertIntoTable(
            "member_meronymy",
            {
              { "holonym_id", notion1.getId() },
              { "meronym_id", notion2.getId() }
            });
        }
      }
    }

    void generator::readWordNetPartMeronymy()
    {
      std::list<std::string> lines(readFile(wordNetPath_ + "wn_mp.pl"));
      hatkirby::progress ppgs("Writing part meronymy...", lines.size());
      for (auto line : lines)
      {
        ppgs.update();

        std::regex relation("^mp\\((1\\d{8}),(1\\d{8})\\)\\.");
        std::smatch relation_data;
        if (!std::regex_search(line, relation_data, relation))
        {
          continue;
        }

        int lookup1 = std::stoi(relation_data[1]);
        int lookup2 = std::stoi(relation_data[2]);

        if (notionByWnid_.count(lookup1) && notionByWnid_.count(lookup2))
        {
          notion& notion1 = *notionByWnid_.at(lookup1);
          notion& notion2 = *notionByWnid_.at(lookup2);

          db_.insertIntoTable(
            "part_meronymy",
            {
              { "holonym_id", notion1.getId() },
              { "meronym_id", notion2.getId() }
            });
        }
      }
    }

    void generator::readWordNetSubstanceMeronymy()
    {
      std::list<std::string> lines(readFile(wordNetPath_ + "wn_ms.pl"));
      hatkirby::progress ppgs("Writing substance meronymy...", lines.size());
      for (auto line : lines)
      {
        ppgs.update();

        std::regex relation("^ms\\((1\\d{8}),(1\\d{8})\\)\\.");
        std::smatch relation_data;
        if (!std::regex_search(line, relation_data, relation))
        {
          continue;
        }

        int lookup1 = std::stoi(relation_data[1]);
        int lookup2 = std::stoi(relation_data[2]);

        if (notionByWnid_.count(lookup1) && notionByWnid_.count(lookup2))
        {
          notion& notion1 = *notionByWnid_.at(lookup1);
          notion& notion2 = *notionByWnid_.at(lookup2);

          db_.insertIntoTable(
            "substance_meronymy",
            {
              { "holonym_id", notion1.getId() },
              { "meronym_id", notion2.getId() }
            });
        }
      }
    }

    void generator::readWordNetPertainymy()
    {
      std::list<std::string> lines(readFile(wordNetPath_ + "wn_per.pl", true));

      hatkirby::progress ppgs(
        "Writing pertainymy and mannernymy...",
        lines.size());

      for (auto line : lines)
      {
        ppgs.update();

        std::regex relation(
          "^per\\(([34]\\d{8}),(\\d+),([13]\\d{8}),(\\d+)\\)\\.");

        std::smatch relation_data;
        if (!std::regex_search(line, relation_data, relation))
        {
          continue;
        }

        std::pair<int, int> lookup1(
          std::stoi(relation_data[1]),
          std::stoi(relation_data[2]));

        std::pair<int, int> lookup2(
          std::stoi(relation_data[3]),
          std::stoi(relation_data[4]));

        if (wordByWnidAndWnum_.count(lookup1) &&
            wordByWnidAndWnum_.count(lookup2))
        {
          word& word1 = *wordByWnidAndWnum_.at(lookup1);
          word& word2 = *wordByWnidAndWnum_.at(lookup2);

          if (word1.getNotion().getPartOfSpeech() ==
              part_of_speech::adjective)
          {
            db_.insertIntoTable(
              "pertainymy",
              {
                { "pertainym_id", word1.getId() },
                { "noun_id", word2.getId() }
              });
          } else if (word1.getNotion().getPartOfSpeech() ==
                      part_of_speech::adverb)
          {
            db_.insertIntoTable(
              "mannernymy",
              {
                { "mannernym_id", word1.getId() },
                { "adjective_id", word2.getId() }
              });
          }
        }
      }
    }

    void generator::readWordNetSpecification()
    {
      std::list<std::string> lines(readFile(wordNetPath_ + "wn_sa.pl"));
      hatkirby::progress ppgs("Writing specifications...", lines.size());
      for (auto line : lines)
      {
        ppgs.update();

        std::regex relation("^sa\\((23\\d{8}),(\\d+),(23\\d{8}),(\\d+)\\)\\.");
        std::smatch relation_data;
        if (!std::regex_search(line, relation_data, relation))
        {
          continue;
        }

        std::pair<int, int> lookup1(
          std::stoi(relation_data[1]),
          std::stoi(relation_data[2]));

        std::pair<int, int> lookup2(
          std::stoi(relation_data[3]),
          std::stoi(relation_data[4]));


        if (wordByWnidAndWnum_.count(lookup1) &&
            wordByWnidAndWnum_.count(lookup2))
        {
          word& word1 = *wordByWnidAndWnum_.at(lookup1);
          word& word2 = *wordByWnidAndWnum_.at(lookup2);

          db_.insertIntoTable(
            "specification",
            {
              { "general_id", word1.getId() },
              { "specific_id", word2.getId() }
            });
        }
      }
    }

    void generator::readWordNetSimilarity()
    {
      std::list<std::string> lines(readFile(wordNetPath_ + "wn_sim.pl"));
      hatkirby::progress ppgs("Writing adjective similarity...", lines.size());
      for (auto line : lines)
      {
        ppgs.update();

        std::regex relation("^sim\\((3\\d{8}),(3\\d{8})\\)\\.");
        std::smatch relation_data;
        if (!std::regex_search(line, relation_data, relation))
        {
          continue;
        }

        int lookup1 = std::stoi(relation_data[1]);
        int lookup2 = std::stoi(relation_data[2]);

        if (notionByWnid_.count(lookup1) && notionByWnid_.count(lookup2))
        {
          notion& notion1 = *notionByWnid_.at(lookup1);
          notion& notion2 = *notionByWnid_.at(lookup2);

          db_.insertIntoTable(
            "similarity",
            {
              { "adjective_1_id", notion1.getId() },
              { "adjective_2_id", notion2.getId() }
            });
        }
      }
    }

    void generator::analyzeDatabase()
    {
      std::cout << "Analyzing data..." << std::endl;

      db_.execute("ANALYZE");
    }

    std::list<std::string> generator::readFile(std::string path, bool uniq)
    {
      std::ifstream file(path);
      if (!file)
      {
        throw std::invalid_argument("Could not find file " + path);
      }

      std::list<std::string> lines;
      std::string line;
      while (std::getline(file, line))
      {
        if (line.back() == '\r')
        {
          line.pop_back();
        }

        lines.push_back(line);
      }

      if (uniq)
      {
        std::vector<std::string> uniq(std::begin(lines), std::end(lines));
        lines.clear();

        std::sort(std::begin(uniq), std::end(uniq));
        std::unique_copy(
          std::begin(uniq),
          std::end(uniq),
          std::back_inserter(lines));
      }

      return lines;
    }

    part_of_speech generator::partOfSpeechByWnid(int wnid)
    {
      switch (wnid / 100000000)
      {
        case 1: return part_of_speech::noun;
        case 2: return part_of_speech::verb;
        case 3: return part_of_speech::adjective;
        case 4: return part_of_speech::adverb;
        default: throw std::domain_error(
          "Invalid WordNet synset ID: " + std::to_string(wnid));
      }
    }

    notion& generator::createNotion(part_of_speech partOfSpeech)
    {
      notions_.emplace_back(partOfSpeech);

      return notions_.back();
    }

    notion& generator::lookupOrCreateNotion(int wnid)
    {
      if (!notionByWnid_.count(wnid))
      {
        notions_.emplace_back(partOfSpeechByWnid(wnid), wnid);
        notionByWnid_[wnid] = &notions_.back();
      }

      return *notionByWnid_.at(wnid);
    }

    lemma& generator::lookupOrCreateLemma(std::string base_form)
    {
      if (!lemmaByBaseForm_.count(base_form))
      {
        lemmas_.emplace_back(lookupOrCreateForm(base_form));
        lemmaByBaseForm_[base_form] = &lemmas_.back();
      }

      return *lemmaByBaseForm_.at(base_form);
    }

    form& generator::lookupOrCreateForm(std::string text)
    {
      if (!formByText_.count(text))
      {
        forms_.emplace_back(text);
        formByText_[text] = &forms_.back();
      }

      return *formByText_[text];
    }

    template <typename... Args> word& generator::createWord(Args&&... args)
    {
      words_.emplace_back(std::forward<Args>(args)...);
      word& w = words_.back();

      wordsByBaseForm_[w.getLemma().getBaseForm().getText()].insert(&w);

      if (w.getNotion().hasWnid())
      {
        wordsByWnid_[w.getNotion().getWnid()].insert(&w);
      }

      return w;
    }

    void generator::createGroup(xmlNodePtr top, const group* parent)
    {
      if (parent != nullptr)
      {
        groups_.emplace_back(*parent);
      } else {
        groups_.emplace_back();
      }

      group& grp = groups_.back();

      xmlChar* key;

      for (xmlNodePtr node = top->xmlChildrenNode; node != nullptr; node = node->next)
      {
        if (!xmlStrcmp(node->name, reinterpret_cast<const xmlChar*>("SUBCLASSES")))
        {
          for (xmlNodePtr subclass = node->xmlChildrenNode; subclass != nullptr; subclass = subclass->next)
          {
            if (!xmlStrcmp(subclass->name, reinterpret_cast<const xmlChar*>("VNSUBCLASS")))
            {
              try
              {
                // Parsing a subgroup starts by making a copy of everything in
                // the parent. This is okay to do at this point because in the
                // VerbNet data, subgroups are always defined after everything
                // else.
                createGroup(subclass, &grp);
              } catch (const std::exception& e)
              {
                key = xmlGetProp(subclass, reinterpret_cast<const xmlChar*>("ID"));

                if (key == nullptr)
                {
                  std::throw_with_nested(std::logic_error("Error parsing IDless subgroup"));
                } else {
                  std::string subgroupId(reinterpret_cast<const char*>(key));
                  xmlFree(key);

                  std::throw_with_nested(std::logic_error("Error parsing subgroup " + subgroupId));
                }
              }
            }
          }
        } else if (!xmlStrcmp(node->name, reinterpret_cast<const xmlChar*>("MEMBERS")))
        {
          for (xmlNodePtr member = node->xmlChildrenNode; member != nullptr; member = member->next)
          {
            if (!xmlStrcmp(member->name, reinterpret_cast<const xmlChar*>("MEMBER")))
            {
              key = xmlGetProp(member, reinterpret_cast<const xmlChar*>("wn"));
              std::string wnSenses(reinterpret_cast<const char*>(key));
              xmlFree(key);

              auto wnSenseKeys =
                hatkirby::split<std::list<std::string>>(wnSenses, " ");

              if (!wnSenseKeys.empty())
              {
                std::list<std::string> tempKeys;

                std::transform(
                  std::begin(wnSenseKeys),
                  std::end(wnSenseKeys),
                  std::back_inserter(tempKeys),
                  [] (std::string sense) {
                    return sense + "::";
                  });

                std::list<std::string> filteredKeys;

                std::remove_copy_if(
                  std::begin(tempKeys),
                  std::end(tempKeys),
                  std::back_inserter(filteredKeys),
                  [&] (std::string sense) {
                    return !wnSenseKeys_.count(sense);
                  });

                wnSenseKeys = std::move(filteredKeys);
              }

              if (!wnSenseKeys.empty())
              {
                for (std::string sense : wnSenseKeys)
                {
                  word& wordSense = *wnSenseKeys_[sense];
                  wordSense.setVerbGroup(grp);
                }
              } else {
                key = xmlGetProp(member, reinterpret_cast<const xmlChar*>("name"));
                std::string memberName(reinterpret_cast<const char*>(key));
                xmlFree(key);

                notion& n = createNotion(part_of_speech::verb);
                lemma& l = lookupOrCreateLemma(memberName);
                word& w = createWord(n, l);

                w.setVerbGroup(grp);
              }
            }
          }
        } else if (!xmlStrcmp(node->name, reinterpret_cast<const xmlChar*>("THEMROLES")))
        {
          for (xmlNodePtr roletopnode = node->xmlChildrenNode; roletopnode != nullptr; roletopnode = roletopnode->next)
          {
            if (!xmlStrcmp(roletopnode->name, reinterpret_cast<const xmlChar*>("THEMROLE")))
            {
              key = xmlGetProp(roletopnode, reinterpret_cast<const xmlChar*>("type"));
              std::string roleName = reinterpret_cast<const char*>(key);
              xmlFree(key);

              std::set<std::string> roleSelrestrs;
              for (xmlNodePtr rolenode = roletopnode->xmlChildrenNode; rolenode != nullptr; rolenode = rolenode->next)
              {
                if (!xmlStrcmp(rolenode->name, reinterpret_cast<const xmlChar*>("SELRESTRS")))
                {
                  for (xmlNodePtr selrestrnode = rolenode->xmlChildrenNode; selrestrnode != nullptr; selrestrnode = selrestrnode->next)
                  {
                    if (!xmlStrcmp(selrestrnode->name, reinterpret_cast<const xmlChar*>("SELRESTR")))
                    {
                      key = xmlGetProp(selrestrnode, reinterpret_cast<const xmlChar*>("type"));
                      roleSelrestrs.insert(std::string(reinterpret_cast<const char*>(key)));
                      xmlFree(key);
                    }
                  }
                }
              }

              grp.addRole({roleName, std::move(roleSelrestrs)});
            }
          }
        } else if (!xmlStrcmp(node->name, reinterpret_cast<const xmlChar*>("FRAMES")))
        {
          for (xmlNodePtr frametopnode = node->xmlChildrenNode; frametopnode != nullptr; frametopnode = frametopnode->next)
          {
            if (!xmlStrcmp(frametopnode->name, reinterpret_cast<const xmlChar*>("FRAME")))
            {
              frame fr;

              for (xmlNodePtr framenode = frametopnode->xmlChildrenNode; framenode != nullptr; framenode = framenode->next)
              {
                if (!xmlStrcmp(framenode->name, reinterpret_cast<const xmlChar*>("SYNTAX")))
                {
                  for (xmlNodePtr syntaxnode = framenode->xmlChildrenNode; syntaxnode != nullptr; syntaxnode = syntaxnode->next)
                  {
                    if (!xmlStrcmp(syntaxnode->name, reinterpret_cast<const xmlChar*>("NP")))
                    {
                      key = xmlGetProp(syntaxnode, reinterpret_cast<const xmlChar*>("value"));
                      std::string partRole = reinterpret_cast<const char*>(key);
                      xmlFree(key);

                      std::set<std::string> partSelrestrs;
                      std::set<std::string> partSynrestrs;

                      for (xmlNodePtr npnode = syntaxnode->xmlChildrenNode; npnode != nullptr; npnode = npnode->next)
                      {
                        if (!xmlStrcmp(npnode->name, reinterpret_cast<const xmlChar*>("SYNRESTRS")))
                        {
                          for (xmlNodePtr synrestr = npnode->xmlChildrenNode; synrestr != nullptr; synrestr = synrestr->next)
                          {
                            if (!xmlStrcmp(synrestr->name, reinterpret_cast<const xmlChar*>("SYNRESTR")))
                            {
                              key = xmlGetProp(synrestr, reinterpret_cast<const xmlChar*>("type"));
                              partSynrestrs.insert(reinterpret_cast<const char*>(key));
                              xmlFree(key);
                            }
                          }
                        } else if (!xmlStrcmp(npnode->name, reinterpret_cast<const xmlChar*>("SELRESTRS")))
                        {
                          for (xmlNodePtr selrestrnode = npnode->xmlChildrenNode; selrestrnode != nullptr; selrestrnode = selrestrnode->next)
                          {
                            if (!xmlStrcmp(selrestrnode->name, reinterpret_cast<const xmlChar*>("SELRESTR")))
                            {
                              key = xmlGetProp(selrestrnode, reinterpret_cast<const xmlChar*>("type"));
                              partSelrestrs.insert(std::string(reinterpret_cast<const char*>(key)));
                              xmlFree(key);
                            }
                          }
                        }
                      }

                      fr.push_back(part::createNounPhrase(std::move(partRole), std::move(partSelrestrs), std::move(partSynrestrs)));
                    } else if (!xmlStrcmp(syntaxnode->name, reinterpret_cast<const xmlChar*>("VERB")))
                    {
                      fr.push_back(part::createVerb());
                    } else if (!xmlStrcmp(syntaxnode->name, reinterpret_cast<const xmlChar*>("PREP")))
                    {
                      std::set<std::string> partChoices;
                      bool partLiteral;

                      if (xmlHasProp(syntaxnode, reinterpret_cast<const xmlChar*>("value")))
                      {
                        partLiteral = true;

                        key = xmlGetProp(syntaxnode, reinterpret_cast<const xmlChar*>("value"));
                        std::string choicesStr = reinterpret_cast<const char*>(key);
                        xmlFree(key);

                        auto choices =
                          hatkirby::split<std::list<std::string>>(
                            choicesStr, " ");

                        for (std::string choice : choices)
                        {
                          int chloc;
                          while ((chloc = choice.find_first_of("_"))
                                  != std::string::npos)
                          {
                            choice.replace(chloc, 1, " ");
                          }

                          partChoices.insert(std::move(choice));
                        }
                      } else {
                        partLiteral = false;

                        for (xmlNodePtr npnode = syntaxnode->xmlChildrenNode;
                              npnode != nullptr;
                              npnode = npnode->next)
                        {
                          if (!xmlStrcmp(npnode->name, reinterpret_cast<const xmlChar*>("SELRESTRS")))
                          {
                            for (xmlNodePtr synrestr = npnode->xmlChildrenNode; synrestr != nullptr; synrestr = synrestr->next)
                            {
                              if (!xmlStrcmp(synrestr->name, reinterpret_cast<const xmlChar*>("SELRESTR")))
                              {
                                key = xmlGetProp(synrestr, reinterpret_cast<const xmlChar*>("type"));
                                partChoices.insert(reinterpret_cast<const char*>(key));
                                xmlFree(key);
                              }
                            }
                          }
                        }
                      }

                      fr.push_back(part::createPreposition(std::move(partChoices), partLiteral));
                    } else if (!xmlStrcmp(syntaxnode->name, reinterpret_cast<const xmlChar*>("ADJ")))
                    {
                      fr.push_back(part::createAdjective());
                    } else if (!xmlStrcmp(syntaxnode->name, reinterpret_cast<const xmlChar*>("ADV")))
                    {
                      fr.push_back(part::createAdverb());
                    } else if (!xmlStrcmp(syntaxnode->name, reinterpret_cast<const xmlChar*>("LEX")))
                    {
                      key = xmlGetProp(syntaxnode, reinterpret_cast<const xmlChar*>("value"));
                      std::string literalValue = reinterpret_cast<const char*>(key);
                      xmlFree(key);

                      fr.push_back(part::createLiteral(literalValue));
                    } else {
                      continue;
                    }
                  }

                  grp.addFrame(std::move(fr));
                }
              }
            }
          }
        }
      }
    }

  };
};