package frenetic

  1. Overview
  2. Docs
The Frenetic Programming Language and Runtime System

Install

Dune Dependency

Authors

Maintainers

Sources

5.0.5.tar.gz
md5=baf754df13a759c32f2c86a1b6f328da
sha512=80140900e7009ccab14b25e244fe7edab87d858676f8a4b3799b4fea16825013cf68363fe5faec71dd54ba825bb4ea2f812c2c666390948ab217ffa75d9cbd29

doc/src/frenetic.kernel/OpenFlow0x04.ml.html

Source file OpenFlow0x04.ml

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
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
(* TODO(???): rename sizeof to size_of for consistency with 0x01 stuff. *)

(** OpenFlow 1.3 (protocol version 0x04) *)

open Core
open Printf
open Cstruct
open Cstruct.BE
open Packet


type uint128 = int64 * int64
type uint48 = uint64
type uint24 = int32
type uint12 = uint16

type 'a mask = { m_value : 'a; m_mask : 'a option } [@@deriving sexp]

type 'a asyncMask = { m_master : 'a ; m_slave : 'a } [@@deriving sexp]

type payload =
  | Buffered of int32 * Cstruct_sexp.t
  | NotBuffered of Cstruct_sexp.t
  [@@deriving sexp]

type xid = OpenFlow_Header.xid [@@deriving sexp]
type int12 = int16 [@@deriving sexp]
type int24 = int32 [@@deriving sexp]
type int128 = int64 * int64 [@@deriving sexp]

let val_to_mask v =
  { m_value = v; m_mask = None }

let ip_to_mask (p,m) =
  if Poly.(m = 32l) then { m_value = p; m_mask = None }
  else
    let m = Int32.shift_left 0xffffffffl (Int32.to_int_exn (Int32.(32l - m))) in
    { m_value = p; m_mask = Some m }

type switchId = int64 [@@deriving sexp]

type groupId = int32 [@@deriving sexp]

type portId = int32 [@@deriving sexp]

type tableId = int8 [@@deriving sexp]

type bufferId = int32 [@@deriving sexp]

type switchFlags = { frag_normal: bool; frag_drop: bool; frag_reasm: bool; } [@@deriving sexp]

type switchConfig = {flags : switchFlags; miss_send_len : int16 } [@@deriving sexp]

type helloFailed =
  | HelloIncompatible
  | HelloPermError
  [@@deriving sexp]

type badRequest =
  | ReqBadVersion
  | ReqBadType
  | ReqBadMultipart
  | ReqBadExp
  | ReqBadExpType
  | ReqPermError
  | ReqBadLen
  | ReqBufferEmpty
  | ReqBufferUnknown
  | ReqBadTableId
  | ReqIsSlave
  | ReqBadPort
  | ReqBadPacket
  | ReqMultipartBufOverflow
  [@@deriving sexp]

type badAction =
  | ActBadType
  | ActBadLen
  | ActBadExp
  | ActBadExpType
  | ActBadOutPort
  | ActBadArg
  | ActPermError
  | ActTooMany
  | ActBadQueue
  | ActBadOutGroup
  | ActMatchInconsistent
  | ActUnsupportedOrder
  | ActBadTag
  | ActBadSetTyp
  | ActBadSetLen
  | ActBadSetArg
  [@@deriving sexp]

type badInstruction =
  | InstUnknownInst
  | InstBadTableId
  | InstUnsupInst
  | InstUnsupMeta
  | InstUnsupMetaMask
  | InstBadExp
  | InstBadExpTyp
  | InstBadLen
  | InstPermError
  [@@deriving sexp]

type badMatch =
  | MatBadTyp
  | MatBadLen
  | MatBadTag
  | MatBadDlAddrMask
  | MatBadNwAddrMask
  | MatBadWildcards
  | MatBadField
  | MatBadValue
  | MatBadMask
  | MatBadPrereq
  | MatDupField
  | MatPermError
  [@@deriving sexp]

type flowModFailed =
  | FlUnknown
  | FlTableFull
  | FlBadTableId
  | FlOverlap
  | FlPermError
  | FlBadTimeout
  | FlBadCommand
  | FlBadFlags
  [@@deriving sexp]

type groupModFailed =
  | GrGroupExists
  | GrInvalidGroup
  | GrWeightUnsupported
  | GrOutOfGroups
  | GrOutOfBuckets
  | GrChainingUnsupported
  | GrWatchUnsupported
  | GrLoop
  | GrUnknownGroup
  | GrChainedGroup
  | GrBadTyp
  | GrBadCommand
  | GrBadBucket
  | GrBadWatch
  | GrPermError
  [@@deriving sexp]

type portModFailed =
  | PoBadPort
  | PoBadHwAddr
  | PoBadConfig
  | PoBadAdvertise
  | PoPermError
  [@@deriving sexp]

type tableModFailed =
  | TaBadTable
  | TaBadConfig
  | TaPermError
  [@@deriving sexp]

type queueOpFailed =
  | QuBadPort
  | QuBadQueue
  | QuPermError
  [@@deriving sexp]

type switchConfigFailed =
  | ScBadFlags
  | ScBadLen
  | ScPermError
  [@@deriving sexp]

type roleReqFailed =
  | RoStale
  | RoUnsup
  | RoBadRole
  [@@deriving sexp]

type meterModFailed =
  | MeUnknown
  | MeMeterExists
  | MeInvalidMeter
  | MeUnknownMeter
  | MeBadCommand
  | MeBadFlags
  | MeBadRate
  | MeBadBurst
  | MeBadBand
  | MeBadBandValue
  | MeOutOfMeters
  | MeOutOfBands
  [@@deriving sexp]

type tableFeatFailed =
  | TfBadTable
  | TfBadMeta
  | TfBadType
  | TfBadLen
  | TfBadArg
  | TfPermError
  [@@deriving sexp]

type experimenterFailed = { exp_typ : int16; exp_id : int32} [@@deriving sexp]

type errorTyp =
  | HelloFailed of helloFailed
  | BadRequest of badRequest
  | BadAction of badAction
  | BadInstruction of badInstruction
  | BadMatch of badMatch
  | FlowModFailed of flowModFailed
  | GroupModFailed of groupModFailed
  | PortModFailed of portModFailed
  | TableModFailed of tableModFailed
  | QueueOpFailed of queueOpFailed
  | SwitchConfigFailed of switchConfigFailed
  | RoleReqFailed of roleReqFailed
  | MeterModFailed of meterModFailed
  | TableFeatFailed of tableFeatFailed
  | ExperimenterFailed of experimenterFailed
  [@@deriving sexp]

type length = int16 [@@deriving sexp]

type oxmIPv6ExtHdr = { noext : bool; esp : bool; auth : bool;
                       dest : bool; frac : bool; router : bool;
                       hop : bool; unrep : bool; unseq : bool } [@@deriving sexp]

type oxm =
  | OxmInPort of portId
  | OxmInPhyPort of portId
  | OxmMetadata of int64 mask
  | OxmEthType of int16
  | OxmEthDst of int48 mask
  | OxmEthSrc of int48 mask
  | OxmVlanVId of int12 mask
  | OxmVlanPcp of int8
  | OxmIPProto of int8
  | OxmIPDscp of int8
  | OxmIPEcn of int8
  | OxmIP4Src of int32 mask
  | OxmIP4Dst of int32 mask
  | OxmTCPSrc of int16
  | OxmTCPDst of int16
  | OxmARPOp of int16
  | OxmARPSpa of int32 mask
  | OxmARPTpa of int32 mask
  | OxmARPSha of int48 mask
  | OxmARPTha of int48 mask
  | OxmICMPType of int8
  | OxmICMPCode of int8
  | OxmMPLSLabel of int32
  | OxmMPLSTc of int8
  | OxmTunnelId of int64 mask
  | OxmUDPSrc of int16
  | OxmUDPDst of int16
  | OxmSCTPSrc of int16
  | OxmSCTPDst of int16
  | OxmIPv6Src of int128 mask
  | OxmIPv6Dst of int128 mask
  | OxmIPv6FLabel of int32 mask
  | OxmICMPv6Type of int8
  | OxmICMPv6Code of int8
  | OxmIPv6NDTarget of int128 mask
  | OxmIPv6NDSll of int48
  | OxmIPv6NDTll of int48
  | OxmMPLSBos of bool
  | OxmPBBIsid of int24 mask
  | OxmIPv6ExtHdr of oxmIPv6ExtHdr mask
  [@@deriving sexp]

type oxmMatch = oxm list [@@deriving sexp]

type pseudoPort =
  | PhysicalPort of portId
  | InPort
  | Table
  | Normal
  | Flood
  | AllPorts
  | Controller of int16
  | Local
  | Any
  [@@deriving sexp]

type actionHdr =
  | OutputHdr
  | GroupHdr
  | PopVlanHdr
  | PushVlanHdr
  | PopMplsHdr
  | PushMplsHdr
  | SetFieldHdr
  | CopyTtlOutHdr
  | CopyTtlInHdr
  | SetNwTtlHdr
  | DecNwTtlHdr
  | PushPbbHdr
  | PopPbbHdr
  | SetMplsTtlHdr
  | DecMplsTtlHdr
  | SetQueueHdr
  | ExperimenterAHdr of int32
  [@@deriving sexp]

type action =
  | Output of pseudoPort
  | Group of groupId
  | PopVlan
  | PushVlan of int16
  | PopMpls of int16
  | PushMpls of int16
  | SetField of oxm
  | CopyTtlOut
  | CopyTtlIn
  | SetNwTtl of int8
  | DecNwTtl
  | PushPbb of int16
  | PopPbb
  | SetMplsTtl of int8
  | DecMplsTtl
  | SetQueue of int32
  | Experimenter of int32
  [@@deriving sexp]

type actionSequence = action list [@@deriving sexp]

type instructionHdr =
  | GotoTableHdr
  | ApplyActionsHdr
  | WriteActionsHdr
  | WriteMetadataHdr
  | ClearHdr
  | MeterHdr
  | ExperimenterHdr of int32
  [@@deriving sexp]

type instruction =
  | GotoTable of tableId
  | ApplyActions of actionSequence
  | WriteActions of actionSequence
  | WriteMetadata of int64 mask
  | Clear
  | Meter of int32
  | Experimenter of int32
  [@@deriving sexp]

type bucket = { bu_weight : int16; bu_watch_port : portId option;
                bu_watch_group : groupId option; bu_actions : actionSequence }
  [@@deriving sexp]

type groupType =
  | All
  | Select
  | Indirect
  | FF
[@@deriving sexp]

type groupMod =
  | AddGroup of groupType * groupId * bucket list
  | DeleteGroup of groupType * groupId
  | ModifyGroup of groupType * groupId * bucket list
  [@@deriving sexp]

type timeout =
  | Permanent
  | ExpiresAfter of int16
  [@@deriving sexp]

type flowModCommand =
  | AddFlow
  | ModFlow
  | ModStrictFlow
  | DeleteFlow
  | DeleteStrictFlow
  [@@deriving sexp]

type packetInReason =
  | NoMatch
  | ExplicitSend
  | InvalidTTL
  [@@deriving sexp]

type packetIn = { pi_total_len : int16; pi_reason : packetInReason;
                  pi_table_id : tableId; pi_cookie : int64;
                  pi_ofp_match : oxmMatch; pi_payload : payload } [@@deriving sexp]

type flowReason =
  | FlowIdleTimeout
  | FlowHardTiemout
  | FlowDelete
  | FlowGroupDelete
  [@@deriving sexp]

type flowRemoved = { cookie : int64; priority : int16; reason : flowReason;
                     table_id : tableId; duration_sec : int32; duration_nsec : int32;
                     idle_timeout : timeout; hard_timeout : timeout; packet_count : int64;
                     byte_count : int64; oxm : oxmMatch } [@@deriving sexp]

type capabilities = { flow_stats : bool; table_stats : bool;
                      port_stats : bool; group_stats : bool; ip_reasm :
                        bool; queue_stats : bool; port_blocked : bool } [@@deriving sexp]

type portState = { link_down : bool; blocked : bool; live : bool } [@@deriving sexp]

type portConfig = { port_down : bool; no_recv : bool; no_fwd : bool;
                    no_packet_in : bool } [@@deriving sexp]

type portFeatures = { rate_10mb_hd : bool; rate_10mb_fd : bool;
                      rate_100mb_hd : bool; rate_100mb_fd : bool;
                      rate_1gb_hd : bool; rate_1gb_fd : bool;
                      rate_10gb_fd : bool; rate_40gb_fd : bool;
                      rate_100gb_fd : bool; rate_1tb_fd : bool;
                      other : bool; copper : bool; fiber : bool;
                      autoneg : bool; pause : bool; pause_asym : bool } [@@deriving sexp]

type portDesc = { port_no : portId;
                  hw_addr : int48;
                  name : string;
                  config : portConfig;
                  state : portState;
                  curr : portFeatures;
                  advertised : portFeatures;
                  supported : portFeatures;
                  peer : portFeatures;
                  curr_speed : int32;
                  max_speed : int32} [@@deriving sexp]

type portMod = { mpPortNo : portId; mpHw_addr : int48; mpConfig : portConfig;
                 mpMask : int32; mpAdvertise : portFeatures } [@@deriving sexp]

type portReason =
  | PortAdd
  | PortDelete
  | PortModify
  [@@deriving sexp]

type portStatus = { reason : portReason; desc : portDesc } [@@deriving sexp]

type packetOut = {
  po_payload : payload;
  po_port_id : portId option;
  po_actions : actionSequence
} [@@deriving sexp]

type rate = int32 [@@deriving sexp]

type burst = int32 [@@deriving sexp]

type experimenterId = int32 [@@deriving sexp]

type meterBand =
  | Drop of (rate*burst)
  | DscpRemark of (rate*burst*int8)
  | ExpMeter of (rate*burst*experimenterId)
  [@@deriving sexp]

type meterCommand =
  | AddMeter
  | ModifyMeter
  | DeleteMeter
  [@@deriving sexp]

type meterFlags = { kbps : bool; pktps : bool; burst : bool; stats : bool} [@@deriving sexp]

type meterMod = { command : meterCommand; flags : meterFlags; meter_id : int32;
                  bands : meterBand list} [@@deriving sexp]

type flowRequest = {fr_table_id : tableId; fr_out_port : portId;
                    fr_out_group : portId; fr_cookie : int64 mask;
                    fr_match : oxmMatch} [@@deriving sexp]

type queueRequest = {port_number : portId; queue_id : int32} [@@deriving sexp]

type experimenter = {exp_id : int32; exp_type : int32} [@@deriving sexp]

type tableFeatureProp =
  | TfpInstruction of instructionHdr list
  | TfpInstructionMiss of instructionHdr list
  | TfpNextTable of tableId list
  | TfpNextTableMiss of tableId list
  | TfpWriteAction of actionHdr list
  | TfpWriteActionMiss of actionHdr list
  | TfpApplyAction of actionHdr list
  | TfpApplyActionMiss of actionHdr list
  | TfpMatch of oxm list
  | TfpWildcard of oxm list
  | TfpWriteSetField of oxm list
  | TfpWriteSetFieldMiss of oxm list
  | TfpApplySetField of oxm list
  | TfpApplySetFieldMiss of oxm list
  | TfpExperimenter of (experimenter*Cstruct_sexp.t)
  | TfpExperimenterMiss of (experimenter*Cstruct_sexp.t)
  [@@deriving sexp]

type tableConfig = Deprecated [@@deriving sexp]

type tableFeatures = {length : int16;table_id : tableId; name : string;
                      metadata_match : int64; metadata_write : int64;
                      config : tableConfig; max_entries: int32;
                      feature_prop : tableFeatureProp list} [@@deriving sexp]

type multipartType =
  | SwitchDescReq
  | PortsDescReq
  | FlowStatsReq of flowRequest
  | AggregFlowStatsReq of flowRequest
  | TableStatsReq
  | PortStatsReq of portId
  | QueueStatsReq of queueRequest
  | GroupStatsReq of int32
  | GroupDescReq
  | GroupFeatReq
  | MeterStatsReq of int32
  | MeterConfReq of int32
  | MeterFeatReq
  | TableFeatReq of (tableFeatures list) option
  | ExperimentReq of experimenter
  [@@deriving sexp]

type multipartRequest = { mpr_type : multipartType; mpr_flags : bool } [@@deriving sexp]

let portDescReq =
  { mpr_type = PortsDescReq
  ; mpr_flags = false }

type switchDesc = { mfr_desc :string ; hw_desc : string; sw_desc : string;
                    serial_num : string; dp_desc: string } [@@deriving sexp]

type flowModFlags = { fmf_send_flow_rem : bool; fmf_check_overlap : bool;
                      fmf_reset_counts : bool; fmf_no_pkt_counts : bool;
                      fmf_no_byt_counts : bool } [@@deriving sexp]

type flowStats = { table_id : tableId; duration_sec : int32; duration_nsec :
                     int32; priority : int16; idle_timeout : timeout;
                   hard_timeout : timeout; flags : flowModFlags; cookie : int64;
                   packet_count : int64; byte_count : int64; ofp_match : oxmMatch;
                   instructions : instruction list} [@@deriving sexp]

type aggregStats = { packet_count : int64; byte_count : int64; flow_count : int32} [@@deriving sexp]

type tableStats = { table_id : tableId; active_count : int32; lookup_count : int64;
                    matched_count : int64} [@@deriving sexp]

type portStats = { psPort_no : portId; rx_packets : int64; tx_packets : int64;
                   rx_bytes : int64; tx_bytes : int64; rx_dropped : int64;
                   tx_dropped : int64; rx_errors : int64; tx_errors : int64;
                   rx_frame_err : int64; rx_over_err : int64; rx_crc_err : int64;
                   collisions : int64; duration_sec : int32; duration_nsec : int32} [@@deriving sexp]


type queueStats = { qsPort_no : portId; queue_id : int32; tx_bytes : int64; tx_packets : int64;
                    tx_errors : int64; duration_sec : int32; duration_nsec : int32 } [@@deriving sexp]

type bucketStats = { packet_count : int64; byte_count : int64} [@@deriving sexp]

type groupStats = { length : int16; group_id : int32; ref_count : int32;
                    packet_count : int64; byte_count : int64; duration_sec : int32;
                    duration_nsec : int32; bucket_stats : bucketStats list} [@@deriving sexp]

type groupDesc = { length : int16; typ : groupType; group_id : int32; bucket : bucket list} [@@deriving sexp]

type groupCapabilities = { select_weight : bool; select_liveness : bool;
                           chaining : bool; chaining_checks : bool } [@@deriving sexp]

type groupTypeMap = { all : bool; select : bool; indirect : bool; ff : bool} [@@deriving sexp]

type actionTypeMap = { output : bool; copy_ttl_out : bool; copy_ttl_in : bool;
                       set_mpls_ttl : bool; dec_mpls_ttl : bool; push_vlan : bool;
                       pop_vlan : bool; push_mpls : bool; pop_mpls : bool; set_queue : bool;
                       group : bool; set_nw_ttl : bool; dec_nw_ttl : bool; set_field : bool;
                       push_pbb : bool; pop_pbb : bool } [@@deriving sexp]

type groupFeatures = { typ : groupTypeMap; capabilities : groupCapabilities;
                       max_groups_all : int32; max_groups_select : int32;
                       max_groups_indirect : int32; max_groups_ff :
                         int32; actions_all : actionTypeMap; actions_select : actionTypeMap;
                       actions_indirect : actionTypeMap; actions_ff : actionTypeMap }
                       [@@deriving sexp]

type meterBandStats = { packet_band_count : int64; byte_band_count : int64 }
  [@@deriving sexp]

type meterStats = { meter_id: int32; len : int16; flow_count : int32; packet_in_count :
                      int64; byte_in_count : int64; duration_sec : int32; duration_nsec :
                      int32; band : meterBandStats list} [@@deriving sexp]

type meterConfig = { length : length; flags : meterFlags; meter_id : int32; bands : meterBand list}
  [@@deriving sexp]

type meterBandMaps = { drop : bool; dscpRemark : bool} [@@deriving sexp]

type meterFeatures = { max_meter : int32; band_typ : meterBandMaps;
                       capabilities : meterFlags; max_band : int8;
                       max_color : int8 } [@@deriving sexp]

type multipartReplyTyp =
  | PortsDescReply of portDesc list
  | SwitchDescReply of switchDesc
  | FlowStatsReply of flowStats list
  | AggregateReply of aggregStats
  | TableReply of tableStats list
  | TableFeaturesReply of tableFeatures list
  | PortStatsReply of portStats list
  | QueueStatsReply of queueStats list
  | GroupStatsReply of groupStats list
  | GroupDescReply of groupDesc list
  | GroupFeaturesReply of groupFeatures
  | MeterReply of meterStats list
  | MeterConfig of meterConfig list
  | MeterFeaturesReply of meterFeatures
  [@@deriving sexp]

type multipartReply = {mpreply_typ : multipartReplyTyp; mpreply_flags : bool} [@@deriving sexp]

type tableMod = { table_id : tableId; config : tableConfig } [@@deriving sexp]

type rateQueue =
  | Rate of int
  | Disabled
  [@@deriving sexp]

type queueProp =
  | MinRateProp of rateQueue
  | MaxRateProp of rateQueue
  | ExperimenterProp of int32
  [@@deriving sexp]

type queueDesc = { queue_id : int32; port : portId; len : int16; properties : queueProp list }
  [@@deriving sexp]

type queueConfReq = { port : portId } [@@deriving sexp]

type queueConfReply = { port : portId; queues : queueDesc list } [@@deriving sexp]

type controllerRole =
  | NoChangeRole
  | EqualRole
  | MasterRole
  | SlaveRole
  [@@deriving sexp]

type roleRequest = { role : controllerRole; generation_id : int64 } [@@deriving sexp]

type supportedList = int list [@@deriving sexp]

type element =
  | VersionBitMap of supportedList
  [@@deriving sexp]

type helloElement = element list [@@deriving sexp]

type packetInReasonMap =  { table_miss : bool; apply_action : bool; invalid_ttl : bool } [@@deriving sexp]

type portReasonMap =  { add : bool; delete : bool; modify : bool } [@@deriving sexp]

type flowReasonMask = { idle_timeout : bool; hard_timeout : bool; delete : bool;
                        group_delete : bool} [@@deriving sexp]

type asyncConfig = { packet_in : packetInReasonMap asyncMask;
                     port_status : portReasonMap asyncMask;
                     flow_removed : flowReasonMask asyncMask } [@@deriving sexp]


type error = {
  err : errorTyp;
  data : Cstruct_sexp.t;
} [@@deriving sexp]


type flowMod = { mfCookie : int64 mask; mfTable_id : tableId;
                 mfCommand : flowModCommand; mfIdle_timeout : timeout;
                 mfHard_timeout : timeout; mfPriority : int16;
                 mfBuffer_id : bufferId option;
                 mfOut_port : pseudoPort option;
                 mfOut_group : groupId option; mfFlags : flowModFlags;
                 mfOfp_match : oxmMatch; mfInstructions : instruction list } [@@deriving sexp]

type switchFeatures = {
  datapath_id : int64;
  num_buffers : int32;
  num_tables : int8;
  aux_id : int8;
  supported_capabilities : capabilities
} [@@deriving sexp]

let match_all = []

let default_fm_flags =
  { fmf_send_flow_rem = false
  ; fmf_check_overlap = false
  ; fmf_reset_counts = false
  ; fmf_no_pkt_counts = false
  ; fmf_no_byt_counts = false }

let add_flow ~tbl ~prio ~pat ~insts =
  { mfCookie = val_to_mask 0L
  ; mfTable_id = tbl
  ; mfCommand = AddFlow
  ; mfIdle_timeout = Permanent
  ; mfHard_timeout = Permanent
  ; mfPriority = prio
  ; mfBuffer_id = None
  ; mfOut_port = None
  ; mfOut_group = None
  ; mfFlags = default_fm_flags
  ; mfOfp_match = pat
  ; mfInstructions = insts }

let delete_all_flows =
  { mfCookie = val_to_mask 0L
  ; mfTable_id = 0xff (* OFPTT_ALL *)
  ; mfCommand = DeleteFlow
  ; mfIdle_timeout = Permanent
  ; mfHard_timeout = Permanent
  ; mfPriority = 0
  ; mfBuffer_id = None
  ; mfOut_port = None
  ; mfOut_group = Some 0xffffffffl (* OFPG_ANY *)
  ; mfFlags = default_fm_flags
  ; mfOfp_match = match_all
  ; mfInstructions = [] }

let delete_all_groups =
  DeleteGroup (All, 0xfffffffcl)

let parse_payload = function
  | Buffered (_, b)
  | NotBuffered b ->
    Packet.parse b

let marshal_payload buffer pkt =
  let payload = Packet.marshal pkt in
  match buffer with
  | Some b -> Buffered (b, payload)
  | None -> NotBuffered payload


exception Unparsable of string
let sym_num = ref 0

let sum (lst : int list) = List.fold_left ~f:(fun x y -> x + y) ~init:0 lst

  (* OKAY *)
  [%%cenum
  type msg_code =
    | HELLO
    | ERROR
    | ECHO_REQ
    | ECHO_RESP
    | VENDOR
    | FEATURES_REQ
    | FEATURES_RESP
    | GET_CONFIG_REQ
    | GET_CONFIG_RESP
    | SET_CONFIG
    | PACKET_IN
    | FLOW_REMOVED
    | PORT_STATUS
    | PACKET_OUT
    | FLOW_MOD
    | GROUP_MOD
    | PORT_MOD
    | TABLE_MOD
    | MULTIPART_REQ
    | MULTIPART_RESP
    | BARRIER_REQ
    | BARRIER_RESP
    | QUEUE_GET_CONFIG_REQ
    | QUEUE_GET_CONFIG_RESP
    | ROLE_REQ
    | ROLE_RESP
    | GET_ASYNC_REQ
    | GET_ASYNC_REP
    | SET_ASYNC
    | METER_MOD
    [@@uint8_t]
  ]

  [%%cstruct
  type ofp_match = {
    typ: uint16_t;
    length: uint16_t;
  } [@@big_endian]]

let ofpp_in_port = 0xfffffff8l
let ofpp_flood = 0xfffffffbl
let ofpp_all = 0xfffffffcl
let ofpp_controller = 0xfffffffdl
let ofpp_any = 0xffffffffl

let ofp_no_buffer = 0xffffffffl

(* Not in the spec, comes from C headers. :rolleyes: *)
let ofpg_all = 0xfffffffcl
let ofpg_any = 0xffffffffl
let ofp_eth_alen = 6          (* Bytes in an Ethernet address. *)

    (* OKAY *)
  [%%cenum
  type ofp_oxm_class =
    | OFPXMC_NXM_0          [@id 0x0000]    (* Backward compatibility with NXM *)
    | OFPXMC_NXM_1          [@id 0x0001]    (* Backward compatibility with NXM *)
    | OFPXMC_OPENFLOW_BASIC [@id 0x8000]    (* Basic class for OpenFlow *)
    | OFPXMC_EXPERIMENTER   [@id 0xFFFF]    (* Experimenter class *)
    [@@uint16_t]
  ]

  (* OKAY *)
  [%%cenum
  type oxm_ofb_match_fields =
    | OFPXMT_OFB_IN_PORT        [@id 0]  (* Switch input port. *)
    | OFPXMT_OFB_IN_PHY_PORT    [@id 1]  (* Switch physical input port. *)
    | OFPXMT_OFB_METADATA       [@id 2]  (* Metadata passed between tables. *)
    | OFPXMT_OFB_ETH_DST        [@id 3]  (* Ethernet destination address. *)
    | OFPXMT_OFB_ETH_SRC        [@id 4]  (* Ethernet source address. *)
    | OFPXMT_OFB_ETH_TYPE       [@id 5]  (* Ethernet frame type. *)
    | OFPXMT_OFB_VLAN_VID       [@id 6]  (* VLAN id. *)
    | OFPXMT_OFB_VLAN_PCP       [@id 7]  (* VLAN priority. *)
    | OFPXMT_OFB_IP_DSCP        [@id 8]  (* IP DSCP (6 bits in ToS field). *)
    | OFPXMT_OFB_IP_ECN         [@id 9]  (* IP ECN (2 bits in ToS field). *)
    | OFPXMT_OFB_IP_PROTO       [@id 10] (* IP protocol. *)
    | OFPXMT_OFB_IPV4_SRC       [@id 11] (* IPv4 source address. *)
    | OFPXMT_OFB_IPV4_DST       [@id 12] (* IPv4 destination address. *)
    | OFPXMT_OFB_TCP_SRC        [@id 13] (* TCP source port. *)
    | OFPXMT_OFB_TCP_DST        [@id 14] (* TCP destination port. *)
    | OFPXMT_OFB_UDP_SRC        [@id 15] (* UDP source port. *)
    | OFPXMT_OFB_UDP_DST        [@id 16] (* UDP destination port. *)
    | OFPXMT_OFB_SCTP_SRC       [@id 17] (* SCTP source port. *)
    | OFPXMT_OFB_SCTP_DST       [@id 18] (* SCTP destination port. *)
    | OFPXMT_OFB_ICMPV4_TYPE    [@id 19] (* ICMP type. *)
    | OFPXMT_OFB_ICMPV4_CODE    [@id 20] (* ICMP code. *)
    | OFPXMT_OFB_ARP_OP         [@id 21] (* ARP opcode. *)
    | OFPXMT_OFB_ARP_SPA        [@id 22] (* ARP source IPv4 address. *)
    | OFPXMT_OFB_ARP_TPA        [@id 23] (* ARP target IPv4 address. *)
    | OFPXMT_OFB_ARP_SHA        [@id 24] (* ARP source hardware address. *)
    | OFPXMT_OFB_ARP_THA        [@id 25] (* ARP target hardware address. *)
    | OFPXMT_OFB_IPV6_SRC       [@id 26] (* IPv6 source address. *)
    | OFPXMT_OFB_IPV6_DST       [@id 27] (* IPv6 destination address. *)
    | OFPXMT_OFB_IPV6_FLABEL    [@id 28] (* IPv6 Flow Label *)
    | OFPXMT_OFB_ICMPV6_TYPE    [@id 29] (* ICMPv6 type. *)
    | OFPXMT_OFB_ICMPV6_CODE    [@id 30] (* ICMPv6 code. *)
    | OFPXMT_OFB_IPV6_ND_TARGET [@id 31] (* Target address for ND. *)
    | OFPXMT_OFB_IPV6_ND_SLL    [@id 32] (* Source link-layer for ND. *)
    | OFPXMT_OFB_IPV6_ND_TLL    [@id 33] (* Target link-layer for ND. *)
    | OFPXMT_OFB_MPLS_LABEL     [@id 34] (* MPLS label. *)
    | OFPXMT_OFB_MPLS_TC        [@id 35] (* MPLS TC. *)
    | OFPXMT_OFP_MPLS_BOS       [@id 36] (* MPLS BoS bit. *)
    | OFPXMT_OFB_PBB_ISID       [@id 37] (* PBB I-SID. *)
    | OFPXMT_OFB_TUNNEL_ID      [@id 38] (* Logical Port Metadata. *)
    | OFPXMT_OFB_IPV6_EXTHDR    [@id 39]  (* IPv6 Extension Header pseudo-field *)
    [@@uint8_t]
  ]

  [%%cenum
  type ofp_vlan_id =
    | OFPVID_PRESENT [@id 0x1000] (* Bit that indicate that a VLAN id is set *)
    | OFPVID_NONE    [@id 0x0000] (* No VLAN id was set. *)
    [@@uint16_t]
  ]

  [%%cstruct
  type ofp_switch_features = {
    datapath_id: uint64_t ;
    n_buffers: uint32_t ;
    n_tables: uint8_t ;
    auxiliary_id: uint8_t ;
    pad0: uint8_t ;
    pad1: uint8_t ;
    capabilities: uint32_t ;
    reserved: uint32_t ;
  } [@@big_endian]]

module PortConfig = struct

  type t = portConfig

  let config_to_int (config : t) : int32 =
    Int32.bit_or (if config.port_down then (Int32.shift_left 1l 0) else 0l)
      (Int32.bit_or (if config.no_recv then (Int32.shift_left 1l 2) else 0l)
         (Int32.bit_or (if config.no_fwd then (Int32.shift_left 1l 5) else 0l)
            (if config.no_packet_in then (Int32.shift_left 1l 6) else 0l)))

  let marshal (pc : t) : int32 = config_to_int pc


  let parse bits : t =
    { port_down     = Bits.test_bit 0 bits;
      no_recv       = Bits.test_bit 2 bits;
      no_fwd        = Bits.test_bit 5 bits;
      no_packet_in  = Bits.test_bit 6 bits
    }

  let to_string (config : t) =
    Format.sprintf "{ port_down = %b; no_recv = %b; no_fwd  = %b; no_packet_in = %b }"
      config.port_down
      config.no_recv
      config.no_fwd
      config.no_packet_in
end

module PortFeatures = struct

  type t = portFeatures

  let marshal (t : t) : int32 =
    Int32.bit_or (if t.rate_10mb_hd then (Int32.shift_left 1l 0) else 0l)
      (Int32.bit_or (if t.rate_10mb_fd then (Int32.shift_left 1l 1) else 0l)
         (Int32.bit_or (if t.rate_100mb_hd then (Int32.shift_left 1l 2) else 0l)
            (Int32.bit_or (if t.rate_100mb_fd then (Int32.shift_left 1l 3) else 0l)
               (Int32.bit_or (if t.rate_1gb_hd then (Int32.shift_left 1l 4) else 0l)
                  (Int32.bit_or (if t.rate_1gb_fd then (Int32.shift_left 1l 5) else 0l)
                     (Int32.bit_or (if t.rate_10gb_fd then (Int32.shift_left 1l 6) else 0l)
                        (Int32.bit_or (if t.rate_40gb_fd then (Int32.shift_left 1l 7) else 0l)
                           (Int32.bit_or (if t.rate_100gb_fd then (Int32.shift_left 1l 8) else 0l)
                              (Int32.bit_or (if t.rate_1tb_fd then (Int32.shift_left 1l 9) else 0l)
                                 (Int32.bit_or (if t.other then (Int32.shift_left 1l 10) else 0l)
                                    (Int32.bit_or (if t.copper then (Int32.shift_left 1l 11) else 0l)
                                       (Int32.bit_or (if t.fiber then (Int32.shift_left 1l 12) else 0l)
                                          (Int32.bit_or (if t.autoneg then (Int32.shift_left 1l 13) else 0l)
                                             (Int32.bit_or (if t.pause then (Int32.shift_left 1l 14) else 0l)
                                                (if t.pause_asym then (Int32.shift_left 1l 15) else 0l)))))))))))))))

  let parse (bits : int32) : t =
    { rate_10mb_hd  = Bits.test_bit 0 bits;
      rate_10mb_fd  = Bits.test_bit 1 bits;
      rate_100mb_hd = Bits.test_bit 2 bits;
      rate_100mb_fd = Bits.test_bit 3 bits;
      rate_1gb_hd   = Bits.test_bit 4 bits;
      rate_1gb_fd   = Bits.test_bit 5 bits;
      rate_10gb_fd  = Bits.test_bit 6 bits;
      rate_40gb_fd  = Bits.test_bit 7 bits;
      rate_100gb_fd = Bits.test_bit 8 bits;
      rate_1tb_fd   = Bits.test_bit 9 bits;
      other         = Bits.test_bit 10 bits;
      copper        = Bits.test_bit 11 bits;
      fiber         = Bits.test_bit 12 bits;
      autoneg       = Bits.test_bit 13 bits;
      pause         = Bits.test_bit 14 bits;
      pause_asym    = Bits.test_bit 15 bits
    }

  let to_string (feat : t) =
    Format.sprintf
      "{ 10mhd = %B; 10mfd  = %B; 100mhd  = %B; 100mfd  = %B; 1ghd = %B\
       1gfd  = %B; 10gfd  = %B; 40gfd  = %B; 100gfd  = %B; 1tfd  = %B; \
       other  = %B; copper  = %B; fiber  = %B; autoneg  = %B; pause  = %B; \
       pause_asym  = %B }"
      feat.rate_10mb_hd
      feat.rate_10mb_fd
      feat.rate_100mb_hd
      feat.rate_100mb_fd
      feat.rate_1gb_hd
      feat.rate_1gb_fd
      feat.rate_10gb_fd
      feat.rate_40gb_fd
      feat.rate_100gb_fd
      feat.rate_1tb_fd
      feat.other
      feat.copper
      feat.fiber
      feat.autoneg
      feat.pause
      feat.pause_asym
end

module PortState = struct

  type t = portState

  let state_to_int (state : t) : int32 =
    Int32.bit_or (if state.link_down then (Int32.shift_left 1l 0) else 0l)
      (Int32.bit_or (if state.blocked then (Int32.shift_left 1l 1) else 0l)
         (if state.live then (Int32.shift_left 1l 2) else 0l))

  let marshal (ps : t) : int32 = state_to_int ps

  let parse bits : t =
    { link_down = Bits.test_bit 0 bits;
      blocked = Bits.test_bit 1 bits;
      live = Bits.test_bit 2 bits
    }

  let to_string (state : t) =
    Format.sprintf "{ link_down = %B; blocked = %B; live = %B }"
      state.link_down
      state.blocked
      state.live
end

[%%cstruct
type ofp_port_stats_request = {
  port_no: uint32_t ;
  pad: uint8_t  [@len 4];
} [@@big_endian]]

[%%cstruct
type ofp_queue_stats_request = {
  port_no: uint32_t ;
  queue_id: uint32_t ;
} [@@big_endian]]

[%%cstruct
type ofp_group_stats_request = {
  group_id: uint32_t ;
  pad: uint8_t [@len 4];
} [@@big_endian]]

[%%cstruct
type ofp_meter_multipart_request = {
  meter_id: uint32_t ;
  pad: uint8_t [@len 4];
} [@@big_endian]]

[%%cstruct
type ofp_table_features = {
  length: uint16_t ;
  table_id: uint8_t ;
  pad: uint8_t [@len 5];
  name: uint8_t [@len 32];
  metadata_match: uint64_t ;
  metadata_write: uint64_t ;
  config: uint32_t ;
  max_entries: uint32_t ;
} [@@big_endian]]

(* Body of reply to OFPMP_PORT request. If a counter is unsupported, set
 * the field to all ones. *)
[%%cstruct
type ofp_port_stats = {
  port_no: uint32_t ;
  pad: uint8_t [@len 4]; (* Align to 64-bits. *)
  rx_packets: uint64_t ; (* Number of received packets. *)
  tx_packets: uint64_t ; (* Number of transmitted packets. *)
  rx_bytes: uint64_t ; (* Number of received bytes. *)
  tx_bytes: uint64_t ; (* Number of transmitted bytes. *)
  rx_dropped: uint64_t ; (* Number of packets dropped by RX. *)
  tx_dropped: uint64_t ; (* Number of packets dropped by TX. *)
  rx_errors: uint64_t ; (* Number of receive errors. This is a super-set
                         			 of more specific receive errors and should be
                         			 greater than or equal to the sum of all
                         			 rx_*_err values. *)
  tx_errors: uint64_t ; (* Number of transmit errors. This is a super-set
                         			 of more specific transmit errors and should be
                         			 greater than or equal to the sum of all
                         			 tx_*_err values (none currently defined.) *)
  rx_frame_err: uint64_t ; (* Number of frame alignment errors. *)
  rx_over_err: uint64_t ; (* Number of packets with RX overrun. *)
  rx_crc_err: uint64_t ; (* Number of CRC errors. *)
  collisions: uint64_t ; (* Number of collisions. *)
  duration_sec: uint32_t ; (* Time port has been alive in seconds. *)
  duration_nsec: uint32_t ; (* Time port has been alive in nanoseconds beyond
                            			     duration_sec. *)
} [@@big_endian]]

[%%cstruct
type ofp_port = {
  port_no: uint32_t ;
  pad: uint32_t ;
  hw_addr: uint8_t [@len 6];
  pad2: uint8_t ;
  pad3: uint8_t ;
  name: uint8_t [@len 16]; (* OFP_MAX_PORT_NAME_LEN, Null-terminated *)
  config: uint32_t ; (* Bitmap of OFPPC_* flags. *)
  state: uint32_t ; (* Bitmap of OFPPS_* flags. *)
  curr: uint32_t ; (* Current features. *)
  advertised: uint32_t ; (* Features being advertised by the port. *)
  supported: uint32_t ; (* Features supported by the port. *)
  peer: uint32_t ; (* Features advertised by peer. *)
  curr_speed: uint32_t ; (* Current port bitrate in kbps. *)
  max_speed: uint32_t ;  (* Max port bitrate in kbps *)
} [@@big_endian]]

[%%cenum
type ofp_port_reason =
  | OFPPR_ADD
  | OFPPR_DELETE
  | OFPPR_MODIFY
  [@@uint8_t]
]

[%%cstruct
type ofp_port_status = {
  reason: uint8_t;               (* One of OFPPR_* *)
  pad: uint8_t [@len 7];
} [@@big_endian]]

[%%cenum
type ofp_table_config =
  | OFPTC_DEPRECATED_MASK [@id 0x00000003l] (* currently deprecated *)
  [@@uint32_t]
]

[%%cenum
type ofp_table_feature_prop_type =
  | OFPTFPT_INSTRUCTIONS       [@id 0]
  | OFPTFPT_INSTRUCTIONS_MISS  [@id 1]
  | OFPTFPT_NEXT_TABLES        [@id 2]
  | OFPTFPT_NEXT_TABLES_MISS   [@id 3]
  | OFPTFPT_WRITE_ACTIONS      [@id 4]
  | OFPTFPT_WRITE_ACTIONS_MISS  [@id 5]
  | OFPTFPT_APPLY_ACTIONS       [@id 6]
  | OFPTFPT_APPLY_ACTIONS_MISS  [@id 7]
  | OFPTFPT_MATCH               [@id 8]
  | OFPTFPT_WILDCARDS           [@id 10]
  | OFPTFPT_WRITE_SETFIELD      [@id 12]
  | OFPTFPT_WRITE_SETFIELD_MISS [@id 13]
  | OFPTFPT_APPLY_SETFIELD      [@id 14]
  | OFPTFPT_APPLY_SETFIELD_MISS [@id 15]
  | OFPTFPT_EXPERIMENTER        [@id 0xFFFE]
  | OFPTFPT_EXPERIMENTER_MISS   [@id 0xFFFF]
  [@@uint16_t]
]

[%%cstruct
type ofp_table_feature_prop_header = {
  typ: uint16_t;
  length: uint16_t;
} [@@big_endian]]

[%%cenum
type ofp_flow_mod_command =
  | OFPFC_ADD            [@id 0] (* New flow. *)
  | OFPFC_MODIFY         [@id 1] (* Modify all matching flows. *)
  | OFPFC_MODIFY_STRICT  [@id 2] (* Modify entry strictly matching wildcards and
                               priority. *)
  | OFPFC_DELETE         [@id 3] (* Delete all matching flows. *)
  | OFPFC_DELETE_STRICT  [@id 4]  (* Delete entry strictly matching wildcards and
                               priority. *)
  [@@uint8_t]
]

[%%cstruct
type ofp_flow_mod = {
  cookie: uint64_t ;             (* Opaque controller-issued identifier. *)
  cookie_mask: uint64_t ;        (* Mask used to restrict the cookie bits
                                  that must match when the command is
                                  OFPFC_MODIFY* or OFPFC_DELETE*. A value
                                  of 0 indicates no restriction. *)

  (* Flow actions. *)
  table_id: uint8_t ;             (* ID of the table to put the flow in.
                                   For OFPFC_DELETE_* commands, OFPTT_ALL
                                   can also be used to delete matching
                                   flows from all tables. *)
  command: uint8_t ;              (* One of OFPFC_*. *)
  idle_timeout: uint16_t ;        (* Idle time before discarding (seconds). *)
  hard_timeout: uint16_t ;        (* Max time before discarding (seconds). *)
  priority: uint16_t ;            (* Priority level of flow entry. *)
  buffer_id: uint32_t ;           (* Buffered packet to apply to, or
                                   OFP_NO_BUFFER.
                                   Not meaningful for OFPFC_DELETE*. *)
  out_port: uint32_t ;            (* For OFPFC_DELETE* commands, require
                                   matching entries to include this as an
                                   output port.  A value of OFPP_ANY
                                   indicates no restriction. *)
  out_group: uint32_t ;           (* For OFPFC_DELETE* commands, require
                                   matching entries to include this as an
                                   output group.  A value of OFPG_ANY
                                   indicates no restriction. *)
  flags: uint16_t ;               (* One of OFPFF_*. *)
  pad0: uint8_t ;
  pad1: uint8_t ;
} [@@big_endian]]

(* OKAY *)
[%%cenum
type ofp_action_type =
  | OFPAT_OUTPUT       [@id 0]  (* Output to switch port. *)
  | OFPAT_COPY_TTL_OUT [@id 11] (* Copy TTL "outwards" -- from next-to-outermost
                              to outermost *)
  | OFPAT_COPY_TTL_IN  [@id 12] (* Copy TTL "inwards" -- from outermost to
                              next-to-outermost *)
  | OFPAT_SET_MPLS_TTL [@id 15] (* MPLS TTL *)
  | OFPAT_DEC_MPLS_TTL [@id 16] (* Decrement MPLS TTL *)

  | OFPAT_PUSH_VLAN    [@id 17] (* Push a new VLAN tag *)
  | OFPAT_POP_VLAN     [@id 18] (* Pop the outer VLAN tag *)
  | OFPAT_PUSH_MPLS    [@id 19] (* Push a new MPLS tag *)
  | OFPAT_POP_MPLS     [@id 20] (* Pop the outer MPLS tag *)
  | OFPAT_SET_QUEUE    [@id 21] (* Set queue id when outputting to a port *)
  | OFPAT_GROUP        [@id 22] (* Apply group. *)
  | OFPAT_SET_NW_TTL   [@id 23] (* IP TTL. *)
  | OFPAT_DEC_NW_TTL   [@id 24] (* Decrement IP TTL. *)
  | OFPAT_SET_FIELD    [@id 25] (* Set a header field using OXM TLV format. *)
  | OFPAT_PUSH_PBB     [@id 26] (* Push a new PBB service tag (I-TAG) *)
  | OFPAT_POP_PBB      [@id 27] (* Pop the outer PBB service tag (I-TAG) *)
  | OFPAT_EXPERIMENTER [@id 0xffff]
  [@@uint16_t]
]

(* Action structure for OFPAT_OUTPUT, which sends packets out 'port'.
 * When the 'port' is the OFPP_CONTROLLER, 'max_len' indicates the max
 * number of bytes to send.  A 'max_len' of zero means no bytes of the
 * packet should be sent. A 'max_len' of OFPCML_NO_BUFFER means that
 * the packet is not buffered and the complete packet is to be sent to
 * the controller. *)
[%%cstruct
type ofp_action_output = {
  typ: uint16_t ;                   (* OFPAT_OUTPUT. *)
  len: uint16_t ;                   (* Length is 16. *)
  port: uint32_t ;                  (* Output port. *)
  max_len: uint16_t ;               (* Max length to send to controller. *)
  pad0: uint8_t ;                   (* Pad to 64 bits. *)
  pad1: uint8_t ;                   (* Pad to 64 bits. *)
  pad2: uint8_t ;                   (* Pad to 64 bits. *)
  pad3: uint8_t ;                   (* Pad to 64 bits. *)
  pad4: uint8_t ;                   (* Pad to 64 bits. *)
  pad5: uint8_t ;                    (* Pad to 64 bits. *)
} [@@big_endian]]

(* Action structure for OFPAT_GROUP. *)
[%%cstruct
type ofp_action_group = {
  typ: uint16_t ;                   (* OFPAT_GROUP. *)
  len: uint16_t ;                   (* Length is 8. *)
  group_id: uint32_t                (* Group identifier. *)
} [@@big_endian]]

(* Generic action header. Used for POP_VLAN *)
[%%cstruct
type ofp_action_header = {
  typ: uint16_t ;                   (* POP_VLAN. *)
  len: uint16_t ;                   (* Length is 8. *)
  pad: uint8_t ;
  pad1: uint8_t ;
  pad2: uint8_t ;
  pad3: uint8_t
} [@@big_endian]]

(* Action structure for POP_MPLS *)
[%%cstruct
type ofp_action_pop_mpls = {
  typ: uint16_t ;                   (* POP_VLAN. *)
  len: uint16_t ;                   (* Length is 8. *)
  ethertype: uint16_t ;
  pad0: uint8_t ;                   (* Pad to 64 bits. *)
  pad1: uint8_t                     (* Pad to 64 bits. *)
} [@@big_endian]]

(* Action structure for SET_NW_TTL *)
[%%cstruct
type ofp_action_nw_ttl = {
  typ: uint16_t ;                   (* SET_NW_TTL. *)
  len: uint16_t ;                   (* Length is 8. *)
  nw_ttl: uint8_t ;
  pad: uint8_t ;
  pad1: uint8_t ;
  pad2: uint8_t
} [@@big_endian]]

(* Action structure for SET_MPLS_TTL *)
[%%cstruct
type ofp_action_mpls_ttl = {
  typ: uint16_t ;                   (* SET_MPLS_TTL. *)
  len: uint16_t ;                   (* Length is 8. *)
  mpls_ttl: uint8_t ;
  pad: uint8_t;
  pad1: uint8_t;
  pad2: uint8_t;
} [@@big_endian]]

(* Action structure for *_PUSH *)
[%%cstruct
type ofp_action_push = {
  typ: uint16_t ;                   (* OFPAT_PUSH_VLAN/MPLS/PBB *)
  len: uint16_t ;                   (* Length is 8. *)
  ethertype: uint16_t ;             (* Pad to 64 bits. *)
  pad0: uint8_t ;                   (* Pad to 64 bits. *)
  pad1: uint8_t ;                   (* Pad to 64 bits. *)
} [@@big_endian]]

(* Action structure for OFPAT_SET_FIELD. *)
[%%cstruct
type ofp_action_set_field = {
  typ: uint16_t ;                  (* OFPAT_SET_FIELD. *)
  len: uint16_t ;                   (* Length is padded to 64 bits. *)
  (* Followed by:
   *   - Exactly oxm_len bytes containing a single OXM TLV, then
   *   - Exactly ((oxm_len + 4) + 7)/8*8 - (oxm_len + 4) (between 0 and 7)
   *     bytes of all-zero bytes
  *)
} [@@big_endian]]

(* Action structure for SET_QUEUE *)
[%%cstruct
type ofp_action_set_queue = {
  typ: uint16_t ;                   (* OFPAT_SET_QUEUE*)
  len: uint16_t ;                   (* Length is 8. *)
  queue_id: uint32_t ;
} [@@big_endian]]

[%%cstruct
type ofp_action_experimenter = {
  typ: uint16_t ;
  len: uint16_t ;
  experimenter: uint32_t ;
} [@@big_endian]]

(* Instruction header that is common to all instructions.  The length includes
 * the header and any padding used to make the instruction 64-bit aligned.
 * NB: The length of an instruction *must* always be a multiple of eight. *)
[%%cstruct
type ofp_instruction = {
  typ: uint16_t ;                 (* Instruction type *)
  len: uint16_t ;                  (* Length of this struct in bytes. *)
} [@@big_endian]]

[%%cenum
type ofp_instruction_type =
  | OFPIT_GOTO_TABLE        [@id 1]
  | OFPIT_WRITE_METADATA    [@id 2]
  | OFPIT_WRITE_ACTIONS     [@id 3]
  | OFPIT_APPLY_ACTIONS     [@id 4]
  | OFPIT_CLEAR_ACTIONS     [@id 5]
  | OFPIT_METER             [@id 6]
  | OFPIT_EXPERIMENTER      [@id 0xFFFF]
  [@@uint16_t]
]

(* Instruction structure for OFPIT_GOTO_TABLE *)
[%%cstruct
type ofp_instruction_goto_table = {
  typ: uint16_t ;                 (* OFPIT_GOTO_TABLE *)
  len: uint16_t ;                 (* Length of this struct in bytes. *)
  table_id: uint8_t ;             (* Set next table in the lookup pipeline *)
  pad0: uint8_t ;                 (* Pad to 64 bits. *)
  pad1: uint8_t ;
  pad2: uint8_t
} [@@big_endian]]

(* Instruction structure for OFPIT_WRITE_METADATA *)
[%%cstruct
type ofp_instruction_write_metadata = {
  typ: uint16_t ;                 (* OFPIT_WRITE_METADATA *)
  len: uint16_t ;                 (* Length of this struct in bytes. *)
  pad0: uint8_t ;                 (* Align to 64-bits *)
  pad1: uint8_t ;
  pad2: uint8_t ;
  pad3: uint8_t ;
  metadata: uint64_t ;            (* Metadata value to write *)
  metadata_mask: uint64_t         (* Metadata write bitmask *)
} [@@big_endian]]

(* Instruction structure for OFPIT_WRITE/APPLY/CLEAR_ACTIONS *)
[%%cstruct
type ofp_instruction_actions = {
  typ: uint16_t ;               (* One of OFPIT_*_ACTIONS *)
  len: uint16_t ;               (* Length of this struct in bytes. *)
  pad0: uint8_t ;               (* Align to 64-bits *)
  pad1: uint8_t ;
  pad2: uint8_t ;
  pad3: uint8_t
} [@@big_endian]]

(* Instruction structure for OFPIT_METER *)
[%%cstruct
type ofp_instruction_meter = {
  typ: uint16_t ;                 (* OFPIT_METER *)
  len: uint16_t ;                 (* Length is 8. *)
  meter_id: uint32_t              (* Meter instance. *)
} [@@big_endian]]

(* Instruction structure for experimental instructions *)
[%%cstruct
type ofp_instruction_experimenter = {
  typ: uint16_t ;               (* OFPIT_EXPERIMENTER *)
  len: uint16_t ;               (* Length of this struct in bytes *)
  experimenter: uint32_t        (* Experimenter ID which takes the same form
                                 as in struct ofp_experimenter_header. *)
  (* Experimenter-defined arbitrary additional data. *)
} [@@big_endian]]


[%%cenum
type ofp_group_type =
  | OFPGT_ALL [@id 0] (* All (multicast/broadcast) group. *)
  | OFPGT_SELECT [@id 1] (* Select group. *)
  | OFPGT_INDIRECT [@id 2] (* Indirect group. *)
  | OFPGT_FF [@id 3] (* Fast failover group. *)
  [@@uint16_t]
]

(* Group setup and teardown (controller -> datapath). *)
[%%cstruct
type ofp_group_mod = {
  command: uint16_t ;             (* One of OFPGC_*. *)
  typ: uint8_t ;                 (* One of OFPGT_*. *)
  pad: uint8_t ;                  (* Pad to 64 bits. *)
  group_id: uint32_t             (* Group identifier. *)
} [@@big_endian]]

(* Bucket for use in groups. *)
[%%cstruct
type ofp_bucket = {
  len: uint16_t ;                   (* Length the bucket in bytes, including
                                     this header and any padding to make it
                                     64-bit aligned. *)
  weight: uint16_t ;                (* Relative weight of bucket.  Only
                                     defined for select groups. *)
  watch_port: uint32_t ;            (* Port whose state affects whether this
                                     bucket is live.  Only required for fast
                                     failover groups. *)
  watch_group: uint32_t ;           (* Group whose state affects whether this
                                     bucket is live.  Only required for fast
                                     failover groups. *)
  pad0: uint8_t ;
  pad1: uint8_t ;
  pad2: uint8_t ;
  pad3: uint8_t
} [@@big_endian]]

[%%cstruct
type ofp_oxm = {
  oxm_class: uint16_t ;
  oxm_field_and_hashmask: uint8_t ;
  oxm_length: uint8_t
} [@@big_endian]]


[%%cstruct
type ofp_meter_band_header = {
  typ: uint16_t ;
  len: uint16_t ;
  rate: uint32_t ;
  burst_size: uint32_t
} [@@big_endian]]

[%%cstruct
type ofp_meter_band_drop = {
  typ: uint16_t ;
  len: uint16_t ;
  rate: uint32_t ;
  burst_size: uint32_t ;
  pad: uint8_t [@len 4]
} [@@big_endian]]

[%%cstruct
type ofp_meter_band_dscp_remark = {
  typ: uint16_t ;
  len: uint16_t ;
  rate: uint32_t ;
  burst_size: uint32_t ;
  prec_level: uint8_t ;
  pad: uint8_t  [@len 3];
} [@@big_endian]]

[%%cstruct
type ofp_meter_band_experimenter = {
  typ: uint16_t ;
  len: uint16_t ;
  rate: uint32_t ;
  burst_size: uint32_t ;
  experimenter: uint32_t
} [@@big_endian]]

[%%cenum
type ofp_meter_flags =
  | OFPMF_KBPS [@id 1]
  | OFPMF_PKTPS [@id 2]
  | OFPMF_BURST [@id 4]
  | OFPMF_STATS [@id 8]
  [@@uint32_t]
]

[%%cstruct
type ofp_multipart_request = {
  typ: uint16_t ;   (* One of the OFPMP_* constants. *)
  flags: uint16_t ;  (* OFPMP_REQ_* flags (none yet defined). *)
  pad: uint8_t  [@len 4];
  body: uint8_t  [@len 1] (* Body of the request. *)
} [@@big_endian]]

[%%cenum
type ofp_multipart_request_flags =
  | OFPMPF_REQ_MORE [@id 1] (* More requests to follow. *)
  [@@uint16_t]
]

[%%cenum
type ofp_multipart_reply_flags =
  | OFPMPF_REPLY_MORE  [@id 1]  (* More replies to follow. *)
  [@@uint16_t]
]

[%%cstruct
type ofp_multipart_reply = {
  typ: uint16_t ;   (* One of the OFPMP_* constants. *)
  flags: uint16_t ;  (* OFPMP_REPLY_* flags. *)
  pad: uint8_t  [@len 4];
  body: uint8_t [@len 1]; (* Body of the reply. *)
} [@@big_endian]]

[%%cenum
type ofp_multipart_types =
  (* Description of this OpenFlow switch.
   * The request body is empty.
   * The reply body is struct ofp_desc. *)
  | OFPMP_DESC [@id 0]
  (* Individual flow statistics.
   * The request body is struct ofp_flow_multipart_request.
   * The reply body is an array of struct ofp_flow_stats. *)
  | OFPMP_FLOW [@id 1]
  (* Aggregate flow statistics.
   * The request body is struct ofp_aggregate_stats_request.
   * The reply body is struct ofp_aggregate_stats_reply. *)
  | OFPMP_AGGREGATE [@id 2]
  (* Flow table statistics.
   * The request body is empty.
   * The reply body is an array of struct ofp_table_stats. *)
  | OFPMP_TABLE [@id 3]
  (* Port statistics.
   * The request body is struct ofp_port_stats_request.
   * The reply body is an array of struct ofp_port_stats. *)
  | OFPMP_PORT_STATS [@id 4]
  (* Queue statistics for a port
   * The request body is struct ofp_queue_stats_request.
   * The reply body is an array of struct ofp_queue_stats *)
  | OFPMP_QUEUE [@id 5]
  (* Group counter statistics.
   * The request body is struct ofp_group_stats_request.
   * The reply is an array of struct ofp_group_stats. *)
  | OFPMP_GROUP [@id 6]
  (* Group description statistics.
   * The request body is empty.
   * The reply body is an array of struct ofp_group_desc_stats. *)
  | OFPMP_GROUP_DESC [@id 7]
  (* Group features.
   * The request body is empty.
   * The reply body is struct ofp_group_features_stats. *)
  | OFPMP_GROUP_FEATURES [@id 8]
  (* Meter statistics.
   * The request body is struct ofp_meter_multipart_requests.
   * The reply body is an array of struct ofp_meter_stats. *)
  | OFPMP_METER [@id 9]
  (* Meter configuration.
   * The request body is struct ofp_meter_multipart_requests.
   * The reply body is an array of struct ofp_meter_config. *)
  | OFPMP_METER_CONFIG [@id 10]
  (* Meter features.
   * The request body is empty.
   * The reply body is struct ofp_meter_features. *)
  | OFPMP_METER_FEATURES [@id 11]
  (* Table features.
   * The request body is either empty or contains an array of
   * struct ofp_table_features containing the controller’s
   * desired view of the switch. If the switch is unable to
   * set the specified view an error is returned.
   * The reply body is an array of struct ofp_table_features. *)
  | OFPMP_TABLE_FEATURES [@id 12]
  (* Port description.
   * The request body is empty.
   * The reply body is an array of struct ofp_port. *)
  | OFPMP_PORT_DESC [@id 13]
  (* Experimenter extension.
   * The request and reply bodies begin with
   * struct ofp_experimenter_stats_header.
   * The request and reply bodies are otherwise experimenter-defined. *)
  | OFPMP_EXPERIMENTER [@id 0xffff]
  [@@uint16_t]
]

[%%cstruct
type ofp_desc = {
  mfr_desc: uint8_t  [@len 256];
  hw_desc: uint8_t  [@len 256];
  sw_desc: uint8_t  [@len 256];
  serial_num: uint8_t  [@len 32];
  dp_desc: uint8_t [@len 256];
} [@@big_endian]]

[%%cstruct
type ofp_uint8 = {
  value: uint8_t ;
} [@@big_endian]]

[%%cstruct
type ofp_uint16 = {
  value: uint16_t ;
} [@@big_endian]]

[%%cstruct
type ofp_uint24 = {
  high: uint16_t ;
  low: uint8_t ;
} [@@big_endian]]

[%%cstruct
type ofp_uint32 = {
  value: uint32_t ;
} [@@big_endian]]

[%%cstruct
type ofp_uint48 = {
  high: uint32_t ;
  low: uint16_t ;
} [@@big_endian]]

[%%cstruct
type ofp_uint64 = {
  value: uint64_t ;
} [@@big_endian]]

[%%cstruct
type ofp_uint128 = {
  high: uint64_t ;
  low: uint64_t ;
} [@@big_endian]]

(* TODO(arjun): WTF *)
let max_uint32 = 4294967296L (* = 2^32*)

(* TODO(arjun): WTF *)
let compare_uint32 a b =
  (* val compare_uint32 : uint32 -> uint32 -> bool ; return a < b, for a, b uint32  *)
  let a' = if Poly.(a < 0l) then
      Int64.(max_uint32 - (of_int32_exn (Int32.abs a)))
    else Int64.of_int32 a in
  let b' = if Poly.(b < 0l) then
      Int64.(max_uint32 - (of_int32_exn (Int32.abs b)))
    else Int64.of_int32 b in
  Poly.(a' <= b')

let set_ofp_uint48_value (buf : Cstruct_sexp.t) (value : uint48) =
  let high = Int64.(to_int32_exn (shift_right_logical value 16)) in
  let low = Int64.to_int_exn value land 0xffff in
  set_ofp_uint48_high buf high;
  set_ofp_uint48_low buf low

let get_ofp_uint48_value (buf : Cstruct_sexp.t) : uint48 =
  let highBits = get_ofp_uint48_high buf in
  let high =
    if Poly.(highBits < 0l) then
      Int64.(max_uint32 - of_int32 (Int32.abs highBits))
    else
      Int64.(of_int32 highBits) in
  let high = Int64.shift_left high 16 in
  let low = Int64.of_int_exn (get_ofp_uint48_low buf) in
  Int64.bit_or low high

let get_ofp_uint24_value (buf : Cstruct_sexp.t) : uint24 =
  let high = Int32.(shift_left (of_int_exn (get_ofp_uint24_high buf)) 8) in
  let low = Int32.of_int_exn (get_ofp_uint24_low buf) in
  Int32.bit_or high low

let set_ofp_uint24_value (buf : Cstruct_sexp.t) (value : uint24) =
  let high = (Int32.to_int_exn value) lsr 8 in
  let low = (Int32.to_int_exn value) land 0xff in
  set_ofp_uint24_high buf high;
  set_ofp_uint24_low buf low

let set_ofp_uint128_value (buf : Cstruct_sexp.t) ((h,l) : uint128) =
  set_ofp_uint128_high buf h;
  set_ofp_uint128_low buf l

let get_ofp_uint128_value (buf : Cstruct_sexp.t) : uint128 =
  (get_ofp_uint128_high buf, get_ofp_uint128_low buf)

let rec marshal_fields (buf: Cstruct_sexp.t) (fields : 'a list) (marshal_func : Cstruct_sexp.t -> 'a -> int ): int =
  match fields with
  | [] -> 0
  | fields -> let size = marshal_func buf (List.hd_exn fields) in
    size + (marshal_fields (Cstruct.shift buf size) (List.tl_exn fields) marshal_func)

let parse_fields (bits : Cstruct_sexp.t) (parse_func : Cstruct_sexp.t -> 'a) (length_func : Cstruct_sexp.t -> int option) :'a list =
  let iter =
    Cstruct.iter
      length_func
      parse_func
      bits in
  List.rev (Cstruct.fold (fun acc bits -> bits :: acc) iter [])

let pad_to_64bits (n : int) : int =
  if n land 0x7 <> 0 then
    n + (8 - (n land 0x7))
  else
    n

let rec pad_with_zeros (buf : Cstruct_sexp.t) (pad : int) : int =
  if pad = 0 then 0
  else begin set_ofp_uint8_value buf 0;
    1 + pad_with_zeros (Cstruct.shift buf 1) (pad - 1) end

let test_bit16 (n:int) (x:int) : bool =
  (x lsr n) land 1 = 1

module Oxm = struct

  module IPv6ExtHdr = struct

    type t = oxmIPv6ExtHdr

    let marshal (hdr : t) : int16 =
      (if hdr.noext then 1 lsl 0 else 0) lor
      (if hdr.esp then 1 lsl 1 else 0) lor
      (if hdr.auth then 1 lsl 2 else 0) lor
      (if hdr.dest then 1 lsl 3 else 0) lor
      (if hdr.frac then 1 lsl 4 else 0) lor
      (if hdr.router then 1 lsl 5 else 0) lor
      (if hdr.hop then 1 lsl 6 else 0) lor
      (if hdr.unrep then 1 lsl 7 else 0) lor
      (if hdr.unseq then 1 lsl 8 else 0)

    let parse bits : t =
      { noext = test_bit16 0 bits
      ; esp = test_bit16 1 bits
      ; auth = test_bit16 2 bits
      ; dest = test_bit16 3 bits
      ; frac = test_bit16 4 bits
      ; router = test_bit16 5 bits
      ; hop = test_bit16 6 bits
      ; unrep = test_bit16 7 bits
      ; unseq = test_bit16 8 bits}

    let to_string (t : t) : string =
      Format.sprintf "{ noext = %B; esp = %B; auth = %B; dest = %B; frac = %B; router = %B; \
                      hop = %B; unrep = %B; unseq = %B }"
        t.noext
        t.esp
        t.auth
        t.dest
        t.frac
        t.router
        t.hop
        t.unrep
        t.unseq
  end

  type t = oxm

  let field_length (oxm : oxm) : int = match oxm with
    | OxmInPort _ -> 4
    | OxmInPhyPort _ -> 4
    | OxmEthType  _ -> 2
    | OxmEthDst ethaddr ->
      (match ethaddr.m_mask with
       | None -> 6
       | Some _ -> 12)
    | OxmEthSrc ethaddr ->
      (match ethaddr.m_mask with
       | None -> 6
       | Some _ -> 12)
    | OxmVlanVId vid ->
      (match vid.m_mask with
       | None -> 2
       | Some _ -> 4)
    | OxmVlanPcp _ -> 1
    | OxmIP4Src ipaddr ->
      (match ipaddr.m_mask with
       | None -> 4
       | Some _ -> 8)
    | OxmIP4Dst ipaddr ->
      (match ipaddr.m_mask with
       | None -> 4
       | Some _ -> 8)
    | OxmTCPSrc _ -> 2
    | OxmTCPDst _ -> 2
    | OxmARPOp _ -> 2
    | OxmARPSpa t->
      (match t.m_mask with
       | None -> 4
       | Some _ -> 8)
    | OxmARPTpa t->
      (match t.m_mask with
       | None -> 4
       | Some _ -> 8)
    | OxmARPSha t->
      (match t.m_mask with
       | None -> 6
       | Some _ -> 12)
    | OxmARPTha t->
      (match t.m_mask with
       | None -> 6
       | Some _ -> 12)
    | OxmMPLSLabel _ -> 4
    | OxmMPLSTc _ -> 1
    | OxmMetadata t ->
      (match t.m_mask with
       | None -> 8
       | Some _ -> 16)
    | OxmIPProto _ -> 1
    | OxmIPDscp _ -> 1
    | OxmIPEcn _ -> 1
    | OxmICMPType _ -> 1
    | OxmICMPCode _ -> 1
    | OxmTunnelId t ->
      (match t.m_mask with
       | None -> 8
       | Some _ -> 16)
    | OxmUDPSrc _ -> 2
    | OxmUDPDst _ -> 2
    | OxmSCTPSrc _ -> 2
    | OxmSCTPDst _ -> 2
    | OxmIPv6Src t ->
      (match t.m_mask with
       | None -> 16
       | Some _ -> 32)
    | OxmIPv6Dst t ->
      (match t.m_mask with
       | None -> 16
       | Some _ -> 32)
    | OxmIPv6FLabel t ->
      (match t.m_mask with
       | None -> 4
       | Some _ -> 8)
    | OxmICMPv6Type _ -> 1
    | OxmICMPv6Code _ -> 1
    | OxmIPv6NDTarget t ->
      (match t.m_mask with
       | None -> 16
       | Some _ -> 32)
    | OxmIPv6NDSll _ -> 6
    | OxmIPv6NDTll _ -> 6
    | OxmMPLSBos _ -> 1
    | OxmPBBIsid t ->
      (match t.m_mask with
       | None -> 3
       | Some _ -> 6)
    | OxmIPv6ExtHdr t ->
      (match t.m_mask with
       | None -> 2
       | Some _ -> 4)

  let field_name (oxm : oxm) : string = match oxm with
    | OxmInPort _ -> "InPort"
    | OxmInPhyPort _ -> "InPhyPort"
    | OxmEthType  _ -> "EthType"
    | OxmEthDst ethaddr ->
      (match ethaddr.m_mask with
       | None -> "EthDst"
       | Some _ -> "EthDst/mask")
    | OxmEthSrc ethaddr ->
      (match ethaddr.m_mask with
       | None -> "EthSrc"
       | Some _ -> "EthSrc/mask")
    | OxmVlanVId vid ->
      (match vid.m_mask with
       | None -> "VlanVId"
       | Some _ -> "VlanVId/mask")
    | OxmVlanPcp _ -> "VlanPcp"
    | OxmIP4Src ipaddr ->
      (match ipaddr.m_mask with
       | None -> "IPSrc"
       | Some _ -> "IPSrc/mask")
    | OxmIP4Dst ipaddr ->
      (match ipaddr.m_mask with
       | None -> "IPDst"
       | Some _ -> "IPDst/mask")
    | OxmTCPSrc _ -> "TCPSrc"
    | OxmTCPDst _ -> "TCPDst"
    | OxmARPOp _ -> "ARPOp"
    | OxmARPSpa t->
      (match t.m_mask with
       | None -> "ARPSpa"
       | Some _ -> "ARPSpa/mask")
    | OxmARPTpa t->
      (match t.m_mask with
       | None -> "ARPTpa"
       | Some _ -> "ARPTpa/mask")
    | OxmARPSha t->
      (match t.m_mask with
       | None -> "ARPSha"
       | Some _ -> "ARPSha/mask")
    | OxmARPTha t->
      (match t.m_mask with
       | None -> "ARPTha"
       | Some _ -> "ARPTha/mask")
    | OxmMPLSLabel _ -> "MPLSLabel"
    | OxmMPLSTc _ -> "MplsTc"
    | OxmMetadata t ->
      (match t.m_mask with
       | None -> "Metadata"
       | Some _ -> "Metadata/mask")
    | OxmIPProto _ -> "IPProto"
    | OxmIPDscp _ -> "IPDscp"
    | OxmIPEcn _ -> "IPEcn"
    | OxmICMPType _ -> "ICMP Type"
    | OxmICMPCode _ -> "ICMP Code"
    | OxmTunnelId t ->
      (match t.m_mask with
       | None -> "Tunnel ID"
       | Some _ -> "Tunnel ID/mask")
    | OxmUDPSrc _ -> "UDPSrc"
    | OxmUDPDst _ -> "UDPDst"
    | OxmSCTPSrc _ -> "SCTPSrc"
    | OxmSCTPDst _ -> "SCTPDst"
    | OxmIPv6Src t ->
      (match t.m_mask with
       | None -> "IPv6Src"
       | Some _ -> "IPv6Src/mask")
    | OxmIPv6Dst t ->
      (match t.m_mask with
       | None -> "IPv6Dst"
       | Some _ -> "IPv6Dst/mask")
    | OxmIPv6FLabel t ->
      (match t.m_mask with
       | None -> "IPv6FlowLabel"
       | Some _ -> "IPv6FlowLabel/mask")
    | OxmICMPv6Type _ -> "ICMPv6Type"
    | OxmICMPv6Code _ -> "IPCMPv6Code"
    | OxmIPv6NDTarget t ->
      (match t.m_mask with
       | None -> "IPv6NeighborDiscoveryTarget"
       | Some _ -> "IPv6NeighborDiscoveryTarget/mask")
    | OxmIPv6NDSll _ -> "IPv6NeighborDiscoverySourceLink"
    | OxmIPv6NDTll _ -> "IPv6NeighborDiscoveryTargetLink"
    | OxmMPLSBos _ -> "MPLSBoS"
    | OxmPBBIsid t ->
      (match t.m_mask with
       | None -> "PBBIsid"
       | Some _ -> "PBBIsid/mask")
    | OxmIPv6ExtHdr t ->
      (match t.m_mask with
       | None -> "IPv6ExtHdr"
       | Some _ -> "IPv6ExtHdr/mask")

  let sizeof (oxm : oxm) : int =
    sizeof_ofp_oxm + field_length oxm

  let sizeof_header (oxml : oxm) : int =
    sizeof_ofp_oxm

  let to_string (oxm : oxm) =
    sexp_of_oxm oxm
    |> Sexp.to_string

  let match_to_string (oxmMatch : oxmMatch) =
    sexp_of_oxmMatch oxmMatch
    |> Sexp.to_string

  let set_ofp_oxm (buf : Cstruct_sexp.t) (c : ofp_oxm_class) (f : oxm_ofb_match_fields) (hm : int) (l : int) =
    let value = (0x7f land (oxm_ofb_match_fields_to_int f)) lsl 1 in
    let value = value lor (0x1 land hm) in
    set_ofp_oxm_oxm_class buf (ofp_oxm_class_to_int c);
    set_ofp_oxm_oxm_field_and_hashmask buf value;
    set_ofp_oxm_oxm_length buf l

  let marshal (buf : Cstruct_sexp.t) (oxm : oxm) : int =
    let l = field_length oxm in
    let ofc = OFPXMC_OPENFLOW_BASIC in
    let buf2 = Cstruct.shift buf sizeof_ofp_oxm in
    match oxm with
    | OxmInPort pid ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IN_PORT 0 l;
      set_ofp_uint32_value buf2 pid;
      sizeof_ofp_oxm + l
    | OxmInPhyPort pid ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IN_PHY_PORT 0 l;
      set_ofp_uint32_value buf2 pid;
      sizeof_ofp_oxm + l
    | OxmEthType ethtype ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ETH_TYPE 0 l;
      set_ofp_uint16_value buf2 ethtype;
      sizeof_ofp_oxm + l
    | OxmEthDst ethaddr ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ETH_DST (match ethaddr.m_mask with None -> 0 | _ -> 1) l;
      set_ofp_uint48_value buf2 ethaddr.m_value;
      begin match ethaddr.m_mask with
        | None ->
          sizeof_ofp_oxm + l
        | Some mask ->
          let buf3 = Cstruct.shift buf2 (l/2) in
          set_ofp_uint48_value buf3 mask;
          sizeof_ofp_oxm + l
      end
    | OxmEthSrc ethaddr ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ETH_SRC (match ethaddr.m_mask with None -> 0 | _ -> 1) l;
      set_ofp_uint48_value buf2 ethaddr.m_value;
      begin match ethaddr.m_mask with
        | None ->
          sizeof_ofp_oxm + l
        | Some mask ->
          let buf3 = Cstruct.shift buf2 (l/2) in
          set_ofp_uint48_value buf3 mask;
          sizeof_ofp_oxm + l
      end
    | OxmIP4Src ipaddr ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IPV4_SRC (match ipaddr.m_mask with None -> 0 | _ -> 1) l;
      set_ofp_uint32_value buf2 ipaddr.m_value;
      begin match ipaddr.m_mask with
        | None ->
          sizeof_ofp_oxm + l
        | Some mask ->
          let buf3 = Cstruct.shift buf2 (l/2) in
          set_ofp_uint32_value buf3 mask;
          sizeof_ofp_oxm + l
      end
    | OxmIP4Dst ipaddr ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IPV4_DST (match ipaddr.m_mask with None -> 0 | _ -> 1) l;
      set_ofp_uint32_value buf2 ipaddr.m_value;
      begin match ipaddr.m_mask with
        | None ->
          sizeof_ofp_oxm + l
        | Some mask ->
          let buf3 = Cstruct.shift buf2 (l/2) in
          set_ofp_uint32_value buf3 mask;
          sizeof_ofp_oxm + l
      end
    | OxmVlanVId vid ->
      set_ofp_oxm buf ofc OFPXMT_OFB_VLAN_VID (match vid.m_mask with None -> 0 | _ -> 1) l;
      (* Set OFPVID_PRESENT bits of ofp_vlan_id field.
       * Without this flag set, openflow ignores the vid being matched against or set.
       *
       * NOTE: Are there cases where we would explicitly match against or set the vlan_id
       * field for which these bits should be set to OFPVID_NONE? *)
      set_ofp_uint16_value buf2 (vid.m_value lor 0x1000);
      begin match vid.m_mask with
        | None ->
          sizeof_ofp_oxm + l
        | Some mask ->
          let buf3 = Cstruct.shift buf2 (l/2) in
          set_ofp_uint16_value buf3 mask;
          sizeof_ofp_oxm + l
      end
    | OxmVlanPcp vid ->
      set_ofp_oxm buf ofc OFPXMT_OFB_VLAN_PCP 0 l;
      set_ofp_uint8_value buf2 vid;
      sizeof_ofp_oxm + l
    | OxmMPLSLabel vid ->
      set_ofp_oxm buf ofc OFPXMT_OFB_MPLS_LABEL 0 l;
      set_ofp_uint32_value buf2 vid;
      sizeof_ofp_oxm + l
    | OxmMPLSTc vid ->
      set_ofp_oxm buf ofc OFPXMT_OFB_MPLS_TC 0 l;
      set_ofp_uint8_value buf2 vid;
      sizeof_ofp_oxm + l
    | OxmMetadata meta ->
      set_ofp_oxm buf ofc OFPXMT_OFB_METADATA  (match meta.m_mask with None -> 0 | _ -> 1)  l;
      set_ofp_uint64_value buf2 meta.m_value;
      begin match meta.m_mask with
        | None ->
          sizeof_ofp_oxm + l
        | Some mask ->
          let buf3 = Cstruct.shift buf2 (l/2) in
          set_ofp_uint64_value buf3 mask;
          sizeof_ofp_oxm + l
      end
    | OxmIPProto ipproto ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IP_PROTO 0 l;
      set_ofp_uint8_value buf2 ipproto;
      sizeof_ofp_oxm + l
    | OxmIPDscp ipdscp ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IP_DSCP 0 l;
      set_ofp_uint8_value buf2 ipdscp;
      sizeof_ofp_oxm + l
    | OxmIPEcn ipecn ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IP_ECN 0 l;
      set_ofp_uint8_value buf2 ipecn;
      sizeof_ofp_oxm + l
    | OxmTCPSrc port ->
      set_ofp_oxm buf ofc OFPXMT_OFB_TCP_SRC 0 l;
      set_ofp_uint16_value buf2 port;
      sizeof_ofp_oxm + l
    | OxmTCPDst port ->
      set_ofp_oxm buf ofc OFPXMT_OFB_TCP_DST 0 l;
      set_ofp_uint16_value buf2 port;
      sizeof_ofp_oxm + l
    | OxmARPOp arp ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ARP_OP 0 l;
      set_ofp_uint16_value buf2 arp;
      sizeof_ofp_oxm + l
    | OxmARPSpa arp ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ARP_SPA  (match arp.m_mask with None -> 0 | _ -> 1)  l;
      set_ofp_uint32_value buf2 arp.m_value;
      begin match arp.m_mask with
        | None ->
          sizeof_ofp_oxm + l
        | Some mask ->
          let buf3 = Cstruct.shift buf2 (l/2) in
          set_ofp_uint32_value buf3 mask;
          sizeof_ofp_oxm + l
      end
    | OxmARPTpa arp ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ARP_TPA  (match arp.m_mask with None -> 0 | _ -> 1)  l;
      set_ofp_uint32_value buf2 arp.m_value;
      begin match arp.m_mask with
        | None ->
          sizeof_ofp_oxm + l
        | Some mask ->
          let buf3 = Cstruct.shift buf2 (l/2) in
          set_ofp_uint32_value buf3 mask;
          sizeof_ofp_oxm + l
      end
    | OxmARPSha arp ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ARP_SHA  (match arp.m_mask with None -> 0 | _ -> 1)  l;
      set_ofp_uint48_value buf2 arp.m_value;
      begin match arp.m_mask with
        | None ->
          sizeof_ofp_oxm + l
        | Some mask ->
          let buf3 = Cstruct.shift buf2 (l/2) in
          set_ofp_uint48_value buf3 mask;
          sizeof_ofp_oxm + l
      end
    | OxmARPTha arp ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ARP_THA  (match arp.m_mask with None -> 0 | _ -> 1)  l;
      set_ofp_uint48_value buf2 arp.m_value;
      begin match arp.m_mask with
        | None ->
          sizeof_ofp_oxm + l
        | Some mask ->
          let buf3 = Cstruct.shift buf2 (l/2) in
          set_ofp_uint48_value buf3 mask;
          sizeof_ofp_oxm + l
      end
    | OxmICMPType t ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ICMPV4_TYPE 0 l;
      set_ofp_uint8_value buf2 t;
      sizeof_ofp_oxm + l
    | OxmICMPCode c->
      set_ofp_oxm buf ofc OFPXMT_OFB_ICMPV4_CODE 0 l;
      set_ofp_uint8_value buf2 c;
      sizeof_ofp_oxm + l
    | OxmTunnelId tun ->
      set_ofp_oxm buf ofc OFPXMT_OFB_TUNNEL_ID  (match tun.m_mask with None -> 0 | _ -> 1)  l;
      set_ofp_uint64_value buf2 tun.m_value;
      begin match tun.m_mask with
        | None ->
          sizeof_ofp_oxm + l
        | Some mask ->
          let buf3 = Cstruct.shift buf2 (l/2) in
          set_ofp_uint64_value buf3 mask;
          sizeof_ofp_oxm + l
      end
    | OxmUDPSrc port ->
      set_ofp_oxm buf ofc OFPXMT_OFB_UDP_SRC 0 l;
      set_ofp_uint16_value buf2 port;
      sizeof_ofp_oxm + l
    | OxmUDPDst port ->
      set_ofp_oxm buf ofc OFPXMT_OFB_UDP_DST 0 l;
      set_ofp_uint16_value buf2 port;
      sizeof_ofp_oxm + l
    | OxmSCTPSrc port ->
      set_ofp_oxm buf ofc OFPXMT_OFB_SCTP_SRC 0 l;
      set_ofp_uint16_value buf2 port;
      sizeof_ofp_oxm + l
    | OxmSCTPDst port ->
      set_ofp_oxm buf ofc OFPXMT_OFB_SCTP_DST 0 l;
      set_ofp_uint16_value buf2 port;
      sizeof_ofp_oxm + l
    | OxmIPv6Src addr ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IPV6_SRC (match addr.m_mask with None -> 0 | _ -> 1)  l;
      set_ofp_uint128_value buf2 addr.m_value;
      begin match addr.m_mask with
        | None ->
          sizeof_ofp_oxm + l
        | Some mask ->
          let buf3 = Cstruct.shift buf2 (l/2) in
          set_ofp_uint128_value buf3 mask;
          sizeof_ofp_oxm + l
      end
    | OxmIPv6Dst addr ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IPV6_DST (match addr.m_mask with None -> 0 | _ -> 1)  l;
      set_ofp_uint128_value buf2 addr.m_value;
      begin match addr.m_mask with
        | None ->
          sizeof_ofp_oxm + l
        | Some mask ->
          let buf3 = Cstruct.shift buf2 (l/2) in
          set_ofp_uint128_value buf3 mask;
          sizeof_ofp_oxm + l
      end
    | OxmIPv6FLabel label ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IPV6_FLABEL (match label.m_mask with None -> 0 | _ -> 1)  l;
      set_ofp_uint32_value buf2 label.m_value;
      begin match label.m_mask with
        | None ->
          sizeof_ofp_oxm + l
        | Some mask ->
          let buf3 = Cstruct.shift buf2 (l/2) in
          set_ofp_uint32_value buf3 mask;
          sizeof_ofp_oxm + l
      end
    | OxmICMPv6Type typ ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ICMPV6_TYPE 0 l;
      set_ofp_uint8_value buf2 typ;
      sizeof_ofp_oxm + l
    | OxmICMPv6Code cod ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ICMPV6_CODE 0 l;
      set_ofp_uint8_value buf2 cod;
      sizeof_ofp_oxm + l
    | OxmIPv6NDTarget addr ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IPV6_ND_TARGET (match addr.m_mask with None -> 0 | _ -> 1)  l;
      set_ofp_uint128_value buf2 addr.m_value;
      begin match addr.m_mask with
        | None ->
          sizeof_ofp_oxm + l
        | Some mask ->
          let buf3 = Cstruct.shift buf2 (l/2) in
          set_ofp_uint128_value buf3 mask;
          sizeof_ofp_oxm + l
      end
    | OxmIPv6NDSll sll ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IPV6_ND_SLL 0 l;
      set_ofp_uint48_value buf2 sll;
      sizeof_ofp_oxm + l
    | OxmIPv6NDTll tll ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IPV6_ND_TLL 0 l;
      set_ofp_uint48_value buf2 tll;
      sizeof_ofp_oxm + l
    | OxmMPLSBos boS ->
      set_ofp_oxm buf ofc OFPXMT_OFP_MPLS_BOS 0 l;
      (match boS with
       | true -> set_ofp_uint8_value buf2 1
       | false -> set_ofp_uint8_value buf2 0);
      sizeof_ofp_oxm + l
    | OxmPBBIsid sid ->
      set_ofp_oxm buf ofc OFPXMT_OFB_PBB_ISID (match sid.m_mask with None -> 0 | _ -> 1)  l;
      set_ofp_uint24_value buf2 sid.m_value;
      begin match sid.m_mask with
        | None ->
          sizeof_ofp_oxm + l
        | Some mask ->
          let buf3 = Cstruct.shift buf2 (l/2) in
          set_ofp_uint24_value buf3 mask;
          sizeof_ofp_oxm + l
      end
    | OxmIPv6ExtHdr hdr ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IPV6_EXTHDR (match hdr.m_mask with None -> 0 | _ -> 1)  l;
      set_ofp_uint16_value buf2 (IPv6ExtHdr.marshal hdr.m_value);
      begin match hdr.m_mask with
        | None ->
          sizeof_ofp_oxm + l
        | Some mask ->
          let buf3 = Cstruct.shift buf2 (l/2) in
          set_ofp_uint16_value buf3 (IPv6ExtHdr.marshal mask);
          sizeof_ofp_oxm + l
      end

  let marshal_header (buf : Cstruct_sexp.t) (oxm : oxm) : int =
    (* Same as marshal, but without the payload *)
    let l = field_length oxm in
    let ofc = OFPXMC_OPENFLOW_BASIC in
    match oxm with
    | OxmInPort _ ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IN_PORT 0 l;
      sizeof_ofp_oxm
    | OxmInPhyPort _ ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IN_PHY_PORT 0 l;
      sizeof_ofp_oxm
    | OxmEthType _ ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ETH_TYPE 0 l;
      sizeof_ofp_oxm
    | OxmEthDst ethaddr ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ETH_DST (match ethaddr.m_mask with None -> 0 | _ -> 1) l;
      sizeof_ofp_oxm
    | OxmEthSrc ethaddr ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ETH_SRC (match ethaddr.m_mask with None -> 0 | _ -> 1) l;
      sizeof_ofp_oxm
    | OxmIP4Src ipaddr ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IPV4_SRC (match ipaddr.m_mask with None -> 0 | _ -> 1) l;
      sizeof_ofp_oxm
    | OxmIP4Dst ipaddr ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IPV4_DST (match ipaddr.m_mask with None -> 0 | _ -> 1) l;
      sizeof_ofp_oxm
    | OxmVlanVId vid ->
      set_ofp_oxm buf ofc OFPXMT_OFB_VLAN_VID (match vid.m_mask with None -> 0 | _ -> 1) l;
      sizeof_ofp_oxm
    | OxmVlanPcp vid ->
      set_ofp_oxm buf ofc OFPXMT_OFB_VLAN_PCP 0 l;
      sizeof_ofp_oxm
    | OxmMPLSLabel vid ->
      set_ofp_oxm buf ofc OFPXMT_OFB_MPLS_LABEL 0 l;
      sizeof_ofp_oxm
    | OxmMPLSTc vid ->
      set_ofp_oxm buf ofc OFPXMT_OFB_MPLS_TC 0 l;
      sizeof_ofp_oxm
    | OxmMetadata meta ->
      set_ofp_oxm buf ofc OFPXMT_OFB_METADATA  (match meta.m_mask with None -> 0 | _ -> 1)  l;
      sizeof_ofp_oxm
    | OxmIPProto ipproto ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IP_PROTO 0 l;
      sizeof_ofp_oxm
    | OxmIPDscp ipdscp ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IP_DSCP 0 l;
      sizeof_ofp_oxm
    | OxmIPEcn ipecn ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IP_ECN 0 l;
      sizeof_ofp_oxm
    | OxmTCPSrc port ->
      set_ofp_oxm buf ofc OFPXMT_OFB_TCP_SRC 0 l;
      sizeof_ofp_oxm
    | OxmTCPDst port ->
      set_ofp_oxm buf ofc OFPXMT_OFB_TCP_DST 0 l;
      sizeof_ofp_oxm
    | OxmARPOp arp ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ARP_OP 0 l;
      sizeof_ofp_oxm
    | OxmARPSpa arp ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ARP_SPA  (match arp.m_mask with None -> 0 | _ -> 1)  l;
      sizeof_ofp_oxm
    | OxmARPTpa arp ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ARP_TPA  (match arp.m_mask with None -> 0 | _ -> 1)  l;
      sizeof_ofp_oxm
    | OxmARPSha arp ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ARP_SHA  (match arp.m_mask with None -> 0 | _ -> 1)  l;
      sizeof_ofp_oxm
    | OxmARPTha arp ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ARP_THA  (match arp.m_mask with None -> 0 | _ -> 1)  l;
      sizeof_ofp_oxm
    | OxmICMPType t ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ICMPV4_TYPE 0 l;
      sizeof_ofp_oxm
    | OxmICMPCode c->
      set_ofp_oxm buf ofc OFPXMT_OFB_ICMPV4_CODE 0 l;
      sizeof_ofp_oxm
    | OxmTunnelId tun ->
      set_ofp_oxm buf ofc OFPXMT_OFB_TUNNEL_ID  (match tun.m_mask with None -> 0 | _ -> 1)  l;
      sizeof_ofp_oxm
    | OxmUDPSrc port ->
      set_ofp_oxm buf ofc OFPXMT_OFB_UDP_SRC 0 l;
      sizeof_ofp_oxm
    | OxmUDPDst port ->
      set_ofp_oxm buf ofc OFPXMT_OFB_UDP_DST 0 l;
      sizeof_ofp_oxm
    | OxmSCTPSrc port ->
      set_ofp_oxm buf ofc OFPXMT_OFB_SCTP_SRC 0 l;
      sizeof_ofp_oxm
    | OxmSCTPDst port ->
      set_ofp_oxm buf ofc OFPXMT_OFB_SCTP_DST 0 l;
      sizeof_ofp_oxm
    | OxmIPv6Src addr ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IPV6_SRC (match addr.m_mask with None -> 0 | _ -> 1)  l;
      sizeof_ofp_oxm
    | OxmIPv6Dst addr ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IPV6_DST (match addr.m_mask with None -> 0 | _ -> 1)  l;
      sizeof_ofp_oxm
    | OxmIPv6FLabel label ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IPV6_FLABEL (match label.m_mask with None -> 0 | _ -> 1)  l;
      sizeof_ofp_oxm
    | OxmICMPv6Type typ ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ICMPV6_TYPE 0 l;
      sizeof_ofp_oxm
    | OxmICMPv6Code cod ->
      set_ofp_oxm buf ofc OFPXMT_OFB_ICMPV6_CODE 0 l;
      sizeof_ofp_oxm
    | OxmIPv6NDTarget addr ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IPV6_ND_TARGET (match addr.m_mask with None -> 0 | _ -> 1)  l;
      sizeof_ofp_oxm
    | OxmIPv6NDSll sll ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IPV6_ND_SLL 0 l;
      sizeof_ofp_oxm
    | OxmIPv6NDTll tll ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IPV6_ND_TLL 0 l;
      sizeof_ofp_oxm
    | OxmMPLSBos boS ->
      set_ofp_oxm buf ofc OFPXMT_OFP_MPLS_BOS 0 l;
      sizeof_ofp_oxm
    | OxmPBBIsid sid ->
      set_ofp_oxm buf ofc OFPXMT_OFB_PBB_ISID (match sid.m_mask with None -> 0 | _ -> 1)  l;
      sizeof_ofp_oxm
    | OxmIPv6ExtHdr hdr ->
      set_ofp_oxm buf ofc OFPXMT_OFB_IPV6_EXTHDR (match hdr.m_mask with None -> 0 | _ -> 1)  l;
      sizeof_ofp_oxm



  let parse (bits : Cstruct_sexp.t) : oxm * Cstruct_sexp.t =
    (* printf "class= %d\n" (get_ofp_oxm_oxm_class bits); *)
    (* let c = match int_to_ofp_oxm_class (get_ofp_oxm_oxm_class bits) with *)
    (*   | Some n -> n *)
    (*   | None ->  *)
    (*     raise (Unparsable (sprintf "malformed class in oxm")) in *)
    (* TODO: assert c is OFPXMC_OPENFLOW_BASIC *)
    let value = get_ofp_oxm_oxm_field_and_hashmask bits in
    let f = match int_to_oxm_ofb_match_fields (value lsr 1) with
      | Some n -> n
      | None ->
        raise (Unparsable (sprintf "malformed field in oxm %d" (value lsr 1))) in
    let hm = value land 0x1 in
    let oxm_length = get_ofp_oxm_oxm_length bits in
    let bits = Cstruct.shift bits sizeof_ofp_oxm in
    let bits2 = Cstruct.shift bits oxm_length in
    match f with
    | OFPXMT_OFB_IN_PORT ->
      let pid = get_ofp_uint32_value bits in
      (OxmInPort pid, bits2)
    | OFPXMT_OFB_IN_PHY_PORT ->
      let pid = get_ofp_uint32_value bits in
      (OxmInPhyPort pid, bits2)
    | OFPXMT_OFB_METADATA ->
      let value = get_ofp_uint64_value bits in
      if hm = 1 then
        let bits = Cstruct.shift bits 8 in
        let mask = get_ofp_uint64_value bits in
        (OxmMetadata {m_value = value; m_mask = (Some mask)}, bits2)
      else
        (OxmMetadata {m_value = value; m_mask = None}, bits2)
    | OFPXMT_OFB_TUNNEL_ID ->
      let value = get_ofp_uint64_value bits in
      if hm = 1 then
        let bits = Cstruct.shift bits 8 in
        let mask = get_ofp_uint64_value bits in
        (OxmTunnelId {m_value = value; m_mask = (Some mask)}, bits2)
      else
        (OxmTunnelId {m_value = value; m_mask = None}, bits2)
    (* Ethernet destination address. *)
    | OFPXMT_OFB_ETH_DST ->
      let value = get_ofp_uint48_value bits in
      if hm = 1 then
        let bits = Cstruct.shift bits 6 in
        let mask = get_ofp_uint48_value bits in
        (OxmEthDst {m_value = value; m_mask = (Some mask)}, bits2)
      else
        (OxmEthDst {m_value = value; m_mask = None}, bits2)
    (* Ethernet source address. *)
    | OFPXMT_OFB_ETH_SRC ->
      let value = get_ofp_uint48_value bits in
      if hm = 1 then
        let bits = Cstruct.shift bits 6 in
        let mask = get_ofp_uint48_value bits in
        (OxmEthSrc {m_value = value; m_mask = (Some mask)}, bits2)
      else
        (OxmEthSrc {m_value = value; m_mask = None}, bits2)
    (* Ethernet frame type. *)
    | OFPXMT_OFB_ETH_TYPE ->
      let value = get_ofp_uint16_value bits in
      (OxmEthType value, bits2)
    (* IP protocol. *)
    | OFPXMT_OFB_IP_PROTO ->
      let value = get_ofp_uint8_value bits in
      (OxmIPProto value, bits2)
    (* IP DSCP (6 bits in ToS field). *)
    | OFPXMT_OFB_IP_DSCP ->
      let value = get_ofp_uint8_value bits in
      (OxmIPDscp (value land 63), bits2)
    (* IP ECN (2 bits in ToS field). *)
    |  OFPXMT_OFB_IP_ECN ->
      let value = get_ofp_uint8_value bits in
      (OxmIPEcn (value land 3), bits2)
    (* IPv4 source address. *)
    | OFPXMT_OFB_IPV4_SRC ->
      let value = get_ofp_uint32_value bits in
      if hm = 1 then
        let bits = Cstruct.shift bits 4 in
        let mask = get_ofp_uint32_value bits in
        (OxmIP4Src {m_value = value; m_mask = (Some mask)}, bits2)
      else
        (OxmIP4Src {m_value = value; m_mask = None}, bits2)
    (* IPv4 destination address. *)
    | OFPXMT_OFB_IPV4_DST ->
      let value = get_ofp_uint32_value bits in
      if hm = 1 then
        let bits = Cstruct.shift bits 4 in
        let mask = get_ofp_uint32_value bits in
        (OxmIP4Dst {m_value = value; m_mask = (Some mask)}, bits2)
      else
        (OxmIP4Dst {m_value = value; m_mask = None}, bits2)
    (* ARP opcode. *)
    | OFPXMT_OFB_ARP_OP ->
      let value = get_ofp_uint16_value bits in
      (OxmARPOp value, bits2)
    (* ARP source IPv4 address. *)
    | OFPXMT_OFB_ARP_SPA ->
      let value = get_ofp_uint32_value bits in
      if hm = 1 then
        let bits = Cstruct.shift bits 4 in
        let mask = get_ofp_uint32_value bits in
        (OxmARPSpa {m_value = value; m_mask = (Some mask)}, bits2)
      else
        (OxmARPSpa {m_value = value; m_mask = None}, bits2)
    (* ARP target IPv4 address. *)
    | OFPXMT_OFB_ARP_TPA ->
      let value = get_ofp_uint32_value bits in
      if hm = 1 then
        let bits = Cstruct.shift bits 4 in
        let mask = get_ofp_uint32_value bits in
        (OxmARPTpa {m_value = value; m_mask = (Some mask)}, bits2)
      else
        (OxmARPTpa {m_value = value; m_mask = None}, bits2)
    (* ARP source hardware address. *)
    | OFPXMT_OFB_ARP_SHA ->
      let value = get_ofp_uint48_value bits in
      if hm = 1 then
        let bits = Cstruct.shift bits 6 in
        let mask = get_ofp_uint48_value bits in
        (OxmARPSha {m_value = value; m_mask = (Some mask)}, bits2)
      else
        (OxmARPSha {m_value = value; m_mask = None}, bits2)
    (* ARP target hardware address. *)
    | OFPXMT_OFB_ARP_THA ->
      let value = get_ofp_uint48_value bits in
      if hm = 1 then
        let bits = Cstruct.shift bits 6 in
        let mask = get_ofp_uint48_value bits in
        (OxmARPTha {m_value = value; m_mask = (Some mask)}, bits2)
      else
        (OxmARPTha {m_value = value; m_mask = None}, bits2)
    (* ICMP Type *)
    | OFPXMT_OFB_ICMPV4_TYPE ->
      let value = get_ofp_uint8_value bits in
      (OxmICMPType value, bits2)
    (* ICMP code. *)
    |   OFPXMT_OFB_ICMPV4_CODE ->
      let value = get_ofp_uint8_value bits in
      (OxmICMPCode value, bits2)
    | OFPXMT_OFB_TCP_DST ->
      let value = get_ofp_uint16_value bits in
      (OxmTCPDst value, bits2)
    | OFPXMT_OFB_TCP_SRC ->
      let value = get_ofp_uint16_value bits in
      (OxmTCPSrc value, bits2)
    | OFPXMT_OFB_MPLS_LABEL ->
      let value = get_ofp_uint32_value bits in
      (OxmMPLSLabel value, bits2)
    | OFPXMT_OFB_VLAN_PCP ->
      let value = get_ofp_uint8_value bits in
      (OxmVlanPcp value, bits2)
    | OFPXMT_OFB_VLAN_VID ->
      let value = get_ofp_uint16_value bits in
      if hm = 1 then
        let bits = Cstruct.shift bits 2 in
        let mask = get_ofp_uint16_value bits in
        (OxmVlanVId {m_value = value; m_mask = (Some mask)}, bits2)
      else
        (OxmVlanVId {m_value = value; m_mask = None}, bits2)
    | OFPXMT_OFB_MPLS_TC ->
      let value = get_ofp_uint8_value bits in
      (OxmMPLSTc value, bits2)
    | OFPXMT_OFB_UDP_SRC ->
      let value = get_ofp_uint16_value bits in
      (OxmUDPSrc value, bits2)
    | OFPXMT_OFB_UDP_DST ->
      let value = get_ofp_uint16_value bits in
      (OxmUDPDst value, bits2)
    | OFPXMT_OFB_SCTP_SRC ->
      let value = get_ofp_uint16_value bits in
      (OxmSCTPSrc value, bits2)
    | OFPXMT_OFB_SCTP_DST ->
      let value = get_ofp_uint16_value bits in
      (OxmSCTPDst value, bits2)
    | OFPXMT_OFB_IPV6_SRC ->
      let value = get_ofp_uint128_value bits in
      if hm = 1 then
        let bits = Cstruct.shift bits 16 in
        let mask = get_ofp_uint128_value bits in
        (OxmIPv6Src {m_value = value; m_mask = (Some mask)}, bits2)
      else
        (OxmIPv6Src {m_value = value; m_mask = None}, bits2)
    | OFPXMT_OFB_IPV6_DST ->
      let value = get_ofp_uint128_value bits in
      if hm = 1 then
        let bits = Cstruct.shift bits 16 in
        let mask = get_ofp_uint128_value bits in
        (OxmIPv6Dst {m_value = value; m_mask = (Some mask)}, bits2)
      else
        (OxmIPv6Dst {m_value = value; m_mask = None}, bits2)
    | OFPXMT_OFB_IPV6_FLABEL ->
      let value = get_ofp_uint32_value bits in
      if hm = 1 then
        let bits = Cstruct.shift bits 4 in
        let mask = get_ofp_uint32_value bits in
        (OxmIPv6FLabel {m_value = value; m_mask = (Some mask)}, bits2)
      else
        (OxmIPv6FLabel {m_value = value; m_mask = None}, bits2)
    | OFPXMT_OFB_ICMPV6_TYPE ->
      let value = get_ofp_uint8_value bits in
      (OxmICMPv6Type value, bits2)
    | OFPXMT_OFB_ICMPV6_CODE ->
      let value = get_ofp_uint8_value bits in
      (OxmICMPv6Code value, bits2)
    | OFPXMT_OFB_IPV6_ND_TARGET ->
      let value = get_ofp_uint128_value bits in
      if hm = 1 then
        let bits = Cstruct.shift bits 16 in
        let mask = get_ofp_uint128_value bits in
        (OxmIPv6NDTarget {m_value = value; m_mask = (Some mask)}, bits2)
      else
        (OxmIPv6NDTarget {m_value = value; m_mask = None}, bits2)
    | OFPXMT_OFB_IPV6_ND_SLL ->
      let value = get_ofp_uint48_value bits in
      (OxmIPv6NDSll value, bits2)
    | OFPXMT_OFB_IPV6_ND_TLL ->
      let value = get_ofp_uint48_value bits in
      (OxmIPv6NDTll value, bits2)
    | OFPXMT_OFP_MPLS_BOS ->
      let value = get_ofp_uint8_value bits in
      (OxmMPLSBos ((value land 1) = 1), bits2)
    | OFPXMT_OFB_PBB_ISID ->
      let value = get_ofp_uint24_value bits in
      if hm = 1 then
        let bits = Cstruct.shift bits 3 in
        let mask = get_ofp_uint24_value bits in
        (OxmPBBIsid {m_value = value; m_mask = (Some mask)}, bits2)
      else
        (OxmPBBIsid {m_value = value; m_mask = None}, bits2)
    | OFPXMT_OFB_IPV6_EXTHDR ->
      let value = IPv6ExtHdr.parse (get_ofp_uint16_value bits) in
      if hm = 1 then
        let bits = Cstruct.shift bits 2 in
        let mask = IPv6ExtHdr.parse (get_ofp_uint16_value bits) in
        (OxmIPv6ExtHdr {m_value = value; m_mask = (Some mask)}, bits2)
      else
        (OxmIPv6ExtHdr {m_value = value; m_mask = None}, bits2)

  let parse_header (bits : Cstruct_sexp.t) : oxm * Cstruct_sexp.t =
    (* parse Oxm header function for TableFeatureProp. Similar to parse, but without
       parsing the payload *)
    let value = get_ofp_oxm_oxm_field_and_hashmask bits in
    let f = match int_to_oxm_ofb_match_fields (value lsr 1) with
      | Some n -> n
      | None -> raise (Unparsable (sprintf "malformed field in oxm %d" (value lsr 1))) in
    let hm = value land 0x1 in
    let bits2 = Cstruct.shift bits sizeof_ofp_oxm in
    match f with
    | OFPXMT_OFB_IN_PORT ->
      (OxmInPort 0l, bits2)
    | OFPXMT_OFB_IN_PHY_PORT ->
      (OxmInPhyPort 0l, bits2)
    | OFPXMT_OFB_METADATA ->
      if hm = 1 then
        (OxmMetadata {m_value = 0L; m_mask = (Some 0L)}, bits2)
      else
        (OxmMetadata {m_value = 0L; m_mask = None}, bits2)
    | OFPXMT_OFB_TUNNEL_ID ->
      if hm = 1 then
        (OxmTunnelId {m_value = 0L; m_mask = (Some 0L)}, bits2)
      else
        (OxmTunnelId {m_value = 0L; m_mask = None}, bits2)
    (* Ethernet destination address. *)
    | OFPXMT_OFB_ETH_DST ->
      if hm = 1 then
        (OxmEthDst {m_value = 0L; m_mask = (Some 0L)}, bits2)
      else
        (OxmEthDst {m_value = 0L; m_mask = None}, bits2)
    (* Ethernet source address. *)
    | OFPXMT_OFB_ETH_SRC ->
      if hm = 1 then
        (OxmEthSrc {m_value = 0L; m_mask = (Some 0L)}, bits2)
      else
        (OxmEthSrc {m_value = 0L; m_mask = None}, bits2)
    (* Ethernet frame type. *)
    | OFPXMT_OFB_ETH_TYPE ->
      (OxmEthType 0, bits2)
    (* IP protocol. *)
    | OFPXMT_OFB_IP_PROTO ->
      (OxmIPProto 0, bits2)
    (* IP DSCP (6 bits in ToS field). *)
    | OFPXMT_OFB_IP_DSCP ->
      (OxmIPDscp (0 land 63), bits2)
    (* IP ECN (2 bits in ToS field). *)
    |  OFPXMT_OFB_IP_ECN ->
      (OxmIPEcn (0 land 3), bits2)
    (* IPv4 source address. *)
    | OFPXMT_OFB_IPV4_SRC ->
      if hm = 1 then
        (OxmIP4Src {m_value = 0l; m_mask = (Some 0l)}, bits2)
      else
        (OxmIP4Src {m_value = 0l; m_mask = None}, bits2)
    (* IPv4 destination address. *)
    | OFPXMT_OFB_IPV4_DST ->
      if hm = 1 then
        (OxmIP4Dst {m_value = 0l; m_mask = (Some 0l)}, bits2)
      else
        (OxmIP4Dst {m_value = 0l; m_mask = None}, bits2)
    (* ARP opcode. *)
    | OFPXMT_OFB_ARP_OP ->
      (OxmARPOp 0, bits2)
    (* ARP source IPv4 address. *)
    | OFPXMT_OFB_ARP_SPA ->
      if hm = 1 then
        (OxmARPSpa {m_value = 0l; m_mask = (Some 0l)}, bits2)
      else
        (OxmARPSpa {m_value = 0l; m_mask = None}, bits2)
    (* ARP target IPv4 address. *)
    | OFPXMT_OFB_ARP_TPA ->
      if hm = 1 then
        (OxmARPTpa {m_value = 0l; m_mask = (Some 0l)}, bits2)
      else
        (OxmARPTpa {m_value = 0l; m_mask = None}, bits2)
    (* ARP source hardware address. *)
    | OFPXMT_OFB_ARP_SHA ->
      if hm = 1 then
        (OxmARPSha {m_value = 0L; m_mask = (Some 0L)}, bits2)
      else
        (OxmARPSha {m_value = 0L; m_mask = None}, bits2)
    (* ARP target hardware address. *)
    | OFPXMT_OFB_ARP_THA ->
      if hm = 1 then
        (OxmARPTha {m_value = 0L; m_mask = (Some 0L)}, bits2)
      else
        (OxmARPTha {m_value = 0L; m_mask = None}, bits2)
    (* ICMP Type *)
    | OFPXMT_OFB_ICMPV4_TYPE ->
      (OxmICMPType 0, bits2)
    (* ICMP code. *)
    |   OFPXMT_OFB_ICMPV4_CODE ->
      (OxmICMPCode 0, bits2)
    | OFPXMT_OFB_TCP_DST ->
      (OxmTCPDst 0, bits2)
    | OFPXMT_OFB_TCP_SRC ->
      (OxmTCPSrc 0, bits2)
    | OFPXMT_OFB_MPLS_LABEL ->
      (OxmMPLSLabel 0l, bits2)
    | OFPXMT_OFB_VLAN_PCP ->
      (OxmVlanPcp 0, bits2)
    | OFPXMT_OFB_VLAN_VID ->
      if hm = 1 then
        (OxmVlanVId {m_value = 0; m_mask = (Some 0)}, bits2)
      else
        (OxmVlanVId {m_value = 0; m_mask = None}, bits2)
    | OFPXMT_OFB_MPLS_TC ->
      (OxmMPLSTc 0, bits2)
    | OFPXMT_OFB_UDP_SRC ->
      (OxmUDPSrc 0, bits2)
    | OFPXMT_OFB_UDP_DST ->
      (OxmUDPDst 0, bits2)
    | OFPXMT_OFB_SCTP_SRC ->
      (OxmSCTPSrc 0, bits2)
    | OFPXMT_OFB_SCTP_DST ->
      (OxmSCTPDst 0, bits2)
    | OFPXMT_OFB_IPV6_SRC ->
      if hm = 1 then
        (OxmIPv6Src {m_value = (0L,0L); m_mask = (Some (0L,0L))}, bits2)
      else
        (OxmIPv6Src {m_value = (0L,0L); m_mask = None}, bits2)
    | OFPXMT_OFB_IPV6_DST ->
      if hm = 1 then
        (OxmIPv6Dst {m_value = (0L,0L); m_mask = (Some (0L,0L))}, bits2)
      else
        (OxmIPv6Dst {m_value = (0L,0L); m_mask = None}, bits2)
    | OFPXMT_OFB_IPV6_FLABEL ->
      if hm = 1 then
        (OxmIPv6FLabel {m_value = 0l; m_mask = (Some 0l)}, bits2)
      else
        (OxmIPv6FLabel {m_value = 0l; m_mask = None}, bits2)
    | OFPXMT_OFB_ICMPV6_TYPE ->
      (OxmICMPv6Type 0, bits2)
    | OFPXMT_OFB_ICMPV6_CODE ->
      (OxmICMPv6Code 0, bits2)
    | OFPXMT_OFB_IPV6_ND_TARGET ->
      if hm = 1 then
        (OxmIPv6NDTarget {m_value = (0L,0L); m_mask = (Some (0L,0L))}, bits2)
      else
        (OxmIPv6NDTarget {m_value = (0L,0L); m_mask = None}, bits2)
    | OFPXMT_OFB_IPV6_ND_SLL ->
      (OxmIPv6NDSll 0L, bits2)
    | OFPXMT_OFB_IPV6_ND_TLL ->
      (OxmIPv6NDTll 0L, bits2)
    | OFPXMT_OFP_MPLS_BOS ->
      (OxmMPLSBos false, bits2)
    | OFPXMT_OFB_PBB_ISID ->
      if hm = 1 then
        (OxmPBBIsid {m_value = 0l; m_mask = (Some 0l)}, bits2)
      else
        (OxmPBBIsid {m_value = 0l; m_mask = None}, bits2)
    | OFPXMT_OFB_IPV6_EXTHDR ->
      let nul = {noext = false; esp = false; auth = false; dest = false; frac = false; router = false; hop = false; unrep = false; unseq = false } in
      if hm = 1 then
        (OxmIPv6ExtHdr {m_value = nul; m_mask = (Some nul)}, bits2)
      else
        (OxmIPv6ExtHdr {m_value = nul; m_mask = None}, bits2)

  let rec parse_headers (bits : Cstruct_sexp.t) : oxmMatch*Cstruct_sexp.t =
    if Cstruct.length bits < sizeof_ofp_oxm then ([], bits)
    else let field, bits2 = parse_header bits in
      let fields, bits3 = parse_headers bits2 in
      (List.append [field] fields, bits3)

  (* Take a generic pattern and produce an openflow 1.3 pattern *)
  let from_of_pattern (pat : OpenFlow.Pattern.t) : oxm list =
    (if Poly.(pat.dlSrc = None) then []
    else [OxmEthSrc (val_to_mask (Option.value_exn pat.dlSrc))])
    |> (fun accum -> if Poly.(pat.dlDst = None) then accum
       else (OxmEthDst (val_to_mask (Option.value_exn pat.dlDst))) :: accum)
    |> (fun accum -> if Poly.(pat.dlTyp = None) then accum
       else (OxmEthType (Option.value_exn pat.dlTyp)) :: accum)
    |> (fun accum -> if Poly.(pat.dlVlan = None) then accum
       else (OxmVlanVId (val_to_mask (Option.value_exn pat.dlVlan))) :: accum)
    |> (fun accum -> if Poly.(pat.dlVlanPcp = None) then accum
       else (OxmVlanPcp (Option.value_exn pat.dlVlanPcp)) :: accum)
    |> (fun accum -> if Poly.(pat.nwSrc = None) then accum
       (* TODO(mulias): nwSrc is an int32*int32, the second int is proably the mask *)
       else let (src,_) = Option.value_exn pat.nwSrc in
         (OxmIP4Src (val_to_mask src)) :: accum)
    |> (fun accum -> if Poly.(pat.nwDst = None) then accum
       else let (dst,_) = Option.value_exn pat.nwDst in
         (OxmIP4Dst (val_to_mask dst)) :: accum)
    |> (fun accum -> if Poly.(pat.nwProto = None) then accum
       else (OxmIPProto (Option.value_exn pat.nwProto)) :: accum)
    |> (fun accum -> if Poly.(pat.tpSrc = None) then accum
       else (OxmTCPSrc (Option.value_exn pat.tpSrc)) :: accum)
    |> (fun accum -> if Poly.(pat.tpDst = None) then accum
       else (OxmTCPDst (Option.value_exn pat.tpDst)) :: accum)
    |> (fun accum -> if Poly.(pat.inPort = None) then accum
       else (OxmInPort (Option.value_exn pat.inPort)) :: accum)

end

module PseudoPort = struct
  type t = pseudoPort

  [%%cenum
  type ofp_port_no =
    (* Maximum number of physical and logical switch ports. *)
    | OFPP_MAX        [@id 0xffffff00l]

    (* Reserved OpenFlow Port (fake output "ports"). *)
    | OFPP_IN_PORT    [@id 0xfffffff8l] (* Send the packet out the input port. This
                                      reserved port must be explicitly used
                                      in order to send back out of the input
                                      port.*)
    | OFPP_TABLE      [@id 0xfffffff9l] (* Submit the packet to the first flow table
                                      NB: This destination port can only be
                                      used in packet-out messages. *)
    | OFPP_NORMAL     [@id 0xfffffffal] (* Process with normal L2/L3 switching. *)
    | OFPP_FLOOD      [@id 0xfffffffbl] (* All physical ports in VLAN, except input
                                      port and those blocked or link down. *)
    | OFPP_ALL        [@id 0xfffffffcl] (* All physical ports except input port. *)
    | OFPP_CONTROLLER [@id 0xfffffffdl] (* Send to controller. *)
    | OFPP_LOCAL      [@id 0xfffffffel] (* Local openflow "port". *)
    | OFPP_ANY        [@id 0xffffffffl]  (* Wildcard port used only for flow mod
                                      (delete) and flow stats requests. Selects
                                      all flows regardless of output port
                                      (including flows with no output port). *)
    [@@uint32_t]
  ]

  let size_of _ = 4

  let to_string (t : t) =
    match t with
    | PhysicalPort p -> sprintf "PhysicalPort = %lu" p
    | InPort -> "InPort"
    | Table -> "Table"
    | Normal -> "Normal"
    | Flood -> "Flood"
    | AllPorts -> "AllPorts"
    | Controller n -> sprintf "Controller<%d bytes>" n
    | Local -> "Local"
    | Any -> "Any"

  let marshal (t : t) : int32 = match t with
    | PhysicalPort(p) -> p
    | InPort -> ofp_port_no_to_int OFPP_IN_PORT
    | Table -> ofp_port_no_to_int OFPP_TABLE
    | Normal -> ofp_port_no_to_int OFPP_NORMAL
    | Flood -> ofp_port_no_to_int  OFPP_FLOOD
    | AllPorts -> ofp_port_no_to_int OFPP_ALL
    | Controller(_) -> ofp_port_no_to_int  OFPP_CONTROLLER
    | Local -> ofp_port_no_to_int  OFPP_LOCAL
    | Any -> ofp_port_no_to_int  OFPP_ANY

  let make ofp_port_no_code len =
    match int_to_ofp_port_no ofp_port_no_code with
    | Some OFPP_IN_PORT -> InPort
    | Some OFPP_TABLE -> Table
    | Some OFPP_NORMAL -> Normal
    | Some OFPP_FLOOD -> Flood
    | Some OFPP_ALL -> AllPorts
    | Some OFPP_CONTROLLER -> Controller len
    | Some OFPP_LOCAL -> Local
    | Some OFPP_ANY -> Any
    | _ ->
      if compare_uint32 ofp_port_no_code (ofp_port_no_to_int OFPP_MAX) then
        PhysicalPort ofp_port_no_code
      else
        raise
          (Unparsable (sprintf "unsupported port number (%lu)" ofp_port_no_code))

end

module QueueDesc = struct

  [%%cstruct
  type ofp_packet_queue = {
    queue_id: uint32_t ;
    port: uint32_t ;
    len: uint16_t ;
    pad: uint8_t  [@len 6];
  } [@@big_endian]]

  module QueueProp = struct

    [%%cstruct
    type ofp_queue_prop_header = {
      property: uint16_t ;
      len: uint16_t ;
      pad: uint8_t  [@len 4];
    } [@@big_endian]]

    [%%cenum
    type ofp_queue_properties =
      | OFPQT_MIN_RATE [@id 1]
      | OFPQT_MAX_RATE [@id 2]
      | OFPQT_EXPERIMENTER [@id 0xffff]
      [@@uint16_t]
    ]

    [%%cstruct
    type ofp_queue_prop_min_rate = {
      property: uint16_t ;
      len: uint16_t ;
      pad: uint8_t  [@len 4];
      rate: uint16_t ;
      pad2: uint8_t  [@len 6];
    } [@@big_endian]]

    [%%cstruct
    type ofp_queue_prop_max_rate = {
      property: uint16_t ;
      len: uint16_t ;
      pad: uint8_t [@len 4];
      rate: uint16_t ;
      pad2: uint8_t  [@len 6];
    } [@@big_endian]]

    [%%cstruct
    type ofp_queue_prop_experimenter = {
      property: uint16_t ;
      len: uint16_t ;
      pad: uint8_t  [@len 4];
      experimenter: uint32_t ;
      pad2: uint8_t  [@len 4];
    } [@@big_endian]]

    type t = queueProp

    let sizeof (qp : t) : int =
      match qp with
      | MinRateProp _ -> sizeof_ofp_queue_prop_min_rate
      | MaxRateProp _-> sizeof_ofp_queue_prop_max_rate
      | ExperimenterProp _ -> sizeof_ofp_queue_prop_experimenter

    let to_string (qp : t) : string =
      match qp with
      | MinRateProp rate ->
        Format.sprintf "MinRate = %s"
          (match rate with
           | Rate n -> string_of_int n
           | Disabled -> "Disabled")
      | MaxRateProp rate ->
        Format.sprintf "MaxRate = %s"
          (match rate with
           | Rate n -> string_of_int n
           | Disabled -> "Disabled")
      | ExperimenterProp id ->
        Format.sprintf "Experimenter<ID=%lu>"
          id

    let length_func (buf : Cstruct_sexp.t) : int option =
      if Cstruct.length buf < sizeof_ofp_queue_prop_header then None
      else Some (get_ofp_queue_prop_header_len buf)

    let marshal (buf : Cstruct_sexp.t) (qp : t) : int =
      match qp with
      | MinRateProp rate ->
        set_ofp_queue_prop_min_rate_property buf (ofp_queue_properties_to_int OFPQT_MIN_RATE);
        set_ofp_queue_prop_min_rate_len buf 16; (* fixed by specification *)
        set_ofp_queue_prop_min_rate_pad (String.make 4 '\000') 0 buf;
        set_ofp_queue_prop_min_rate_rate buf (
          match rate with
          | Rate n -> n
          | Disabled -> 0xffff);
        set_ofp_queue_prop_min_rate_pad2 (String.make 6 '\000') 0 buf;
        sizeof_ofp_queue_prop_min_rate
      | MaxRateProp rate ->
        set_ofp_queue_prop_max_rate_property buf (ofp_queue_properties_to_int OFPQT_MAX_RATE);
        set_ofp_queue_prop_max_rate_len buf 16; (* fixed by specification *)
        set_ofp_queue_prop_max_rate_pad (String.make 4 '\000') 0 buf;
        set_ofp_queue_prop_max_rate_rate buf (
          match rate with
          | Rate n -> n
          | Disabled -> 0xffff);
        set_ofp_queue_prop_max_rate_pad2 (String.make 6 '\000') 0 buf;
        sizeof_ofp_queue_prop_max_rate
      | ExperimenterProp id ->
        set_ofp_queue_prop_experimenter_property buf (ofp_queue_properties_to_int OFPQT_EXPERIMENTER);
        set_ofp_queue_prop_experimenter_len buf 16; (* fixed by specification *)
        set_ofp_queue_prop_experimenter_pad (String.make 4 '\000') 0 buf;
        set_ofp_queue_prop_experimenter_experimenter buf id;
        set_ofp_queue_prop_experimenter_pad2 (String.make 4 '\000') 0 buf;
        sizeof_ofp_queue_prop_experimenter

    let parse (bits : Cstruct_sexp.t) : t =
      let typ = int_to_ofp_queue_properties (get_ofp_queue_prop_header_property bits) in
      match typ with
      | Some OFPQT_MIN_RATE ->
        let rate = get_ofp_queue_prop_min_rate_rate bits in
        if rate > 1000 then MinRateProp Disabled
        else MinRateProp (Rate rate)
      | Some OFPQT_MAX_RATE ->
        let rate = get_ofp_queue_prop_max_rate_rate bits in
        if rate > 1000 then MaxRateProp Disabled
        else MaxRateProp (Rate rate)
      | Some OFPQT_EXPERIMENTER ->
        let exp_id = get_ofp_queue_prop_experimenter_experimenter bits
        in ExperimenterProp exp_id
      | None -> raise (Unparsable (sprintf "malformed property"))
  end

  type t = queueDesc

  let sizeof (qd : t) : int =
    sizeof_ofp_packet_queue + sum (List.map ~f:QueueProp.sizeof qd.properties)

  let to_string (qd : t) : string =
    Format.sprintf "{ queue_id = %lu; port = %lu; len = %u; properties = %s }"
      qd.queue_id
      qd.port
      qd.len
      ("[ " ^ (String.concat ~sep:"; " (List.map ~f:QueueProp.to_string qd.properties)) ^ " ]")

  let length_func (buf : Cstruct_sexp.t) : int option =
    if Cstruct.length buf < sizeof_ofp_packet_queue then None
    else Some (get_ofp_packet_queue_len buf)

  let marshal (buf : Cstruct_sexp.t) (qd : t) : int =
    set_ofp_packet_queue_queue_id buf qd.queue_id;
    set_ofp_packet_queue_port buf qd.port;
    set_ofp_packet_queue_len buf qd.len;
    set_ofp_packet_queue_pad (String.make 6 '\000') 0 buf;
    let propBuf = Cstruct.sub buf sizeof_ofp_packet_queue (qd.len - sizeof_ofp_packet_queue) in
    sizeof_ofp_packet_queue + (marshal_fields propBuf qd.properties QueueProp.marshal)

  let parse (bits : Cstruct_sexp.t) : t =
    let queue_id = get_ofp_packet_queue_queue_id bits in
    let port = get_ofp_packet_queue_port bits in
    let len = get_ofp_packet_queue_len bits in
    let propBits = Cstruct.sub bits sizeof_ofp_packet_queue (len - sizeof_ofp_packet_queue) in
    let properties = parse_fields propBits QueueProp.parse QueueProp.length_func in
    { queue_id; port; len; properties}

end

module SwitchConfig = struct

  [%%cstruct
  type ofp_switch_config = {
    flags: uint16_t;
    miss_send_len: uint16_t;
  } [@@big_endian]]

  module Flags = struct

    let to_string (flags : switchFlags) : string =
      Format.sprintf "{ frag_normal = %B; frag_drop = %B; frag_reasm = %B; }"
        flags.frag_normal
        flags.frag_drop
        flags.frag_reasm

    let marshal (flags : switchFlags) =
     (* This is unusual, but it's in the spec.  One would think drop and reasm were mutually
        exclusive, but they're not. *)
     if flags.frag_normal then 0
     else
      (if flags.frag_drop then 1 lsl 0 else 0) lor
      (if flags.frag_reasm then 1 lsl 1 else 0)

    let parse bits : switchFlags =
      { frag_normal = (bits = 0)
      ; frag_drop = test_bit16 0 bits
      ; frag_reasm = test_bit16 1 bits
      }

  end

  type t = switchConfig

  let sizeof (sc : switchConfig) : int =
    sizeof_ofp_switch_config

  let to_string (sc : switchConfig) : string =
    Format.sprintf "{ flags = %s; miss_send_length = %u }"
      (Flags.to_string sc.flags)
      sc.miss_send_len

  let marshal (buf : Cstruct_sexp.t) (sc : switchConfig) : int =
    set_ofp_switch_config_flags buf (Flags.marshal sc.flags);
    set_ofp_switch_config_miss_send_len buf sc.miss_send_len;
    sizeof_ofp_switch_config

  let parse (bits : Cstruct_sexp.t) : switchConfig =
    let flags = Flags.parse (get_ofp_switch_config_flags bits) in
    let miss_send_len = get_ofp_switch_config_miss_send_len bits in
    { flags; miss_send_len }

end

module OfpMatch = struct

  type t = oxmMatch

  let sizeof (om : t) : int =
    let n = sizeof_ofp_match + sum (List.map ~f:Oxm.sizeof om) in
    pad_to_64bits n

  let to_string om =
    "[ " ^ (String.concat ~sep:"; " (List.map ~f:Oxm.to_string om)) ^ " ]"

  let marshal (buf : Cstruct_sexp.t) (om : t) : int =
    let size = sizeof om in
    set_ofp_match_typ buf 1; (* OXPMT_OXM *)
    set_ofp_match_length buf (sizeof_ofp_match + sum (List.map ~f:Oxm.sizeof om)); (* Length of ofp_match (excluding padding) *)
    let buf = Cstruct.shift buf sizeof_ofp_match in
    let oxm_size = marshal_fields buf om Oxm.marshal in
    let pad = size - (sizeof_ofp_match + oxm_size) in
    if pad > 0 then
      let buf = Cstruct.shift buf oxm_size in
      let _ = pad_with_zeros buf pad in
      size
    else size

  let rec parse_fields (bits : Cstruct_sexp.t) : t * Cstruct_sexp.t =
    if Cstruct.length bits <= sizeof_ofp_oxm then ([], bits)
    else let field, bits2 = Oxm.parse bits in
      let fields, bits3 = parse_fields bits2 in
      (List.append [field] fields, bits3)

  let parse (bits : Cstruct_sexp.t) : t * Cstruct_sexp.t =
    let length = get_ofp_match_length bits in
    let oxm_bits = Cstruct.sub bits sizeof_ofp_match (length - sizeof_ofp_match) in
    let fields, _ = parse_fields oxm_bits in
    let bits = Cstruct.shift bits (pad_to_64bits length) in
    (fields, bits)

end

module Action = struct

  type t = action
  type sequence = actionSequence

  let sizeof (act : t) : int = match act with
    | Output _ -> sizeof_ofp_action_output
    | Group _ -> sizeof_ofp_action_group
    | PopVlan -> sizeof_ofp_action_header
    | PushVlan _ -> sizeof_ofp_action_push
    | PopMpls _ -> sizeof_ofp_action_pop_mpls
    | PushMpls _ -> sizeof_ofp_action_push
    | SetField oxm -> pad_to_64bits (sizeof_ofp_action_set_field + Oxm.sizeof oxm)
    | CopyTtlOut -> sizeof_ofp_action_header
    | CopyTtlIn -> sizeof_ofp_action_header
    | SetNwTtl _ -> sizeof_ofp_action_nw_ttl
    | DecNwTtl -> sizeof_ofp_action_header
    | PushPbb _ -> sizeof_ofp_action_push
    | PopPbb -> sizeof_ofp_action_header
    | SetMplsTtl _ -> sizeof_ofp_action_mpls_ttl
    | DecMplsTtl -> sizeof_ofp_action_header
    | SetQueue _ -> sizeof_ofp_action_set_queue
    | Experimenter _ -> sizeof_ofp_action_experimenter

  let marshal (buf : Cstruct_sexp.t) (act : t) : int =
    let size = sizeof act in
    match act with
    | Output port ->
      set_ofp_action_output_typ buf 0; (* OFPAT_OUTPUT *)
      set_ofp_action_output_len buf size;
      set_ofp_action_output_port buf (PseudoPort.marshal port);
      set_ofp_action_output_max_len buf
        (match port with
         | Controller max_len -> max_len
         | _ -> 0);
      set_ofp_action_output_pad0 buf 0;
      set_ofp_action_output_pad1 buf 0;
      set_ofp_action_output_pad2 buf 0;
      set_ofp_action_output_pad3 buf 0;
      set_ofp_action_output_pad4 buf 0;
      set_ofp_action_output_pad5 buf 0;
      size
    | PushVlan ethertype ->
      set_ofp_action_push_typ buf 17; (* PUSH_VLAN *)
      set_ofp_action_push_len buf size;
      set_ofp_action_push_ethertype buf ethertype;
      set_ofp_action_push_pad0 buf 0;
      set_ofp_action_push_pad1 buf 0;
      size
    | PopVlan ->
      set_ofp_action_header_typ buf 18; (* POP_VLAN *)
      set_ofp_action_header_len buf size;
      set_ofp_action_header_pad buf 0;
      set_ofp_action_header_pad1 buf 0;
      set_ofp_action_header_pad2 buf 0;
      set_ofp_action_header_pad3 buf 0;
      size
    | PushMpls ethertype ->
      set_ofp_action_push_typ buf 19; (* PUSH_MPLS *)
      set_ofp_action_push_len buf size;
      set_ofp_action_push_ethertype buf ethertype;
      set_ofp_action_push_pad0 buf 0;
      set_ofp_action_push_pad1 buf 0;
      size
    | PopMpls ethertype ->
      set_ofp_action_pop_mpls_typ buf 20; (* POP_MPLS *)
      set_ofp_action_pop_mpls_len buf size;
      set_ofp_action_pop_mpls_ethertype buf ethertype;
      set_ofp_action_pop_mpls_pad0 buf 0;
      set_ofp_action_pop_mpls_pad1 buf 0;
      size
    | Group gid ->
      set_ofp_action_group_typ buf 22; (* OFPAT_GROUP *)
      set_ofp_action_group_len buf size;
      set_ofp_action_group_group_id buf gid;
      size
    | SetField oxm ->
      set_ofp_action_set_field_typ buf 25; (* OFPAT_SET_FIELD *)
      set_ofp_action_set_field_len buf size;
      let buf = Cstruct.shift buf sizeof_ofp_action_set_field in
      let oxm_size = Oxm.marshal buf oxm in
      let pad = size - (sizeof_ofp_action_set_field + oxm_size) in
      (* printf "pad = %d\n" pad; *)
      if pad > 0 then
        let buf = Cstruct.shift buf oxm_size in
        let _ = pad_with_zeros buf pad in
        size
      else size
    | CopyTtlOut ->
      set_ofp_action_header_typ buf 11; (* OFPAT_COPY_TTL_OUT *)
      set_ofp_action_header_len buf size;
      set_ofp_action_header_pad buf 0;
      set_ofp_action_header_pad1 buf 0;
      set_ofp_action_header_pad2 buf 0;
      set_ofp_action_header_pad3 buf 0;
      size
    | CopyTtlIn ->
      set_ofp_action_header_typ buf 12; (* OFPAT_COPY_TTL_IN *)
      set_ofp_action_header_len buf size;
      set_ofp_action_header_pad buf 0;
      set_ofp_action_header_pad1 buf 0;
      set_ofp_action_header_pad2 buf 0;
      set_ofp_action_header_pad3 buf 0;
      size
    | SetNwTtl newTtl ->
      set_ofp_action_nw_ttl_typ buf 23; (* OFPAT_SET_NW_TTL *)
      set_ofp_action_nw_ttl_len buf size;
      set_ofp_action_nw_ttl_nw_ttl buf newTtl;
      set_ofp_action_nw_ttl_pad buf 0;
      set_ofp_action_nw_ttl_pad1 buf 0;
      set_ofp_action_nw_ttl_pad2 buf 0;
      size
    | DecNwTtl ->
      set_ofp_action_header_typ buf 24; (* OFPAT_DEC_NW_TTL *)
      set_ofp_action_header_len buf size;
      set_ofp_action_header_pad buf 0;
      set_ofp_action_header_pad1 buf 0;
      set_ofp_action_header_pad2 buf 0;
      set_ofp_action_header_pad3 buf 0;
      size
    | PushPbb ethertype ->
      set_ofp_action_push_typ buf 26; (* OFPAT_PUSH_PBB *)
      set_ofp_action_push_len buf size;
      set_ofp_action_push_ethertype buf ethertype;
      size
    | PopPbb ->
      set_ofp_action_header_typ buf 27; (* OFPAT_POP_PBB *)
      set_ofp_action_header_len buf size;
      set_ofp_action_header_pad buf 0;
      set_ofp_action_header_pad1 buf 0;
      set_ofp_action_header_pad2 buf 0;
      set_ofp_action_header_pad3 buf 0;
      size
    | SetMplsTtl newTtl ->
      set_ofp_action_mpls_ttl_typ buf 15; (* OFPAT_SET_MPLS_TTL *)
      set_ofp_action_mpls_ttl_len buf size;
      set_ofp_action_mpls_ttl_mpls_ttl buf newTtl;
      set_ofp_action_mpls_ttl_pad buf 0;
      set_ofp_action_mpls_ttl_pad1 buf 0;
      set_ofp_action_mpls_ttl_pad2 buf 0;
      size
    | DecMplsTtl ->
      set_ofp_action_header_typ buf 16; (* OFPAT_DEC_MPLS_TTL *)
      set_ofp_action_header_len buf size;
      set_ofp_action_header_pad buf 0;
      set_ofp_action_header_pad1 buf 0;
      set_ofp_action_header_pad2 buf 0;
      set_ofp_action_header_pad3 buf 0;
      size
    | SetQueue queueId ->
      set_ofp_action_set_queue_typ buf 21; (* OFPAT_SET_QUEUE *)
      set_ofp_action_set_queue_len buf size;
      set_ofp_action_set_queue_queue_id buf queueId;
      size
    | Experimenter exp ->
      set_ofp_action_experimenter_typ buf 0xffff; (* OFPAT_EXPERIMENTER *)
      set_ofp_action_experimenter_len buf size;
      set_ofp_action_experimenter_experimenter buf exp;
      size

  let parse (bits : Cstruct_sexp.t) : t =
    match int_to_ofp_action_type (get_ofp_action_header_typ bits) with
    | Some OFPAT_OUTPUT -> Output (PseudoPort.make (get_ofp_action_output_port bits)  (get_ofp_action_output_max_len bits))
    | Some OFPAT_COPY_TTL_OUT -> CopyTtlOut
    | Some OFPAT_COPY_TTL_IN -> CopyTtlIn
    | Some OFPAT_SET_MPLS_TTL -> SetMplsTtl (get_ofp_action_mpls_ttl_mpls_ttl bits)
    | Some OFPAT_DEC_MPLS_TTL -> DecMplsTtl
    | Some OFPAT_PUSH_VLAN -> PushVlan (get_ofp_action_push_ethertype bits)
    | Some OFPAT_POP_VLAN -> PopVlan
    | Some OFPAT_PUSH_MPLS -> PushMpls  (get_ofp_action_push_ethertype bits)
    | Some OFPAT_POP_MPLS -> PopMpls  (get_ofp_action_pop_mpls_ethertype bits)
    | Some OFPAT_SET_QUEUE -> SetQueue (get_ofp_action_set_queue_queue_id bits)
    | Some OFPAT_GROUP -> Group (get_ofp_action_group_group_id bits)
    | Some OFPAT_SET_NW_TTL -> SetNwTtl (get_ofp_action_nw_ttl_nw_ttl bits)
    | Some OFPAT_DEC_NW_TTL -> DecNwTtl
    | Some OFPAT_SET_FIELD -> let field,_ = Oxm.parse (
        Cstruct.shift bits 4) in
      SetField (field)
    | Some OFPAT_PUSH_PBB -> PushPbb (get_ofp_action_push_ethertype bits)
    | Some OFPAT_POP_PBB -> PopPbb
    | Some OFPAT_EXPERIMENTER -> Experimenter (get_ofp_action_experimenter_experimenter bits)
    | None -> failwith "None type"

  let rec parse_fields (bits : Cstruct_sexp.t) : sequence * Cstruct_sexp.t =
    if Cstruct.length bits < sizeof_ofp_action_header then ([], bits)
    else let field = parse bits in
      let bits2 = Cstruct.shift bits (sizeof field) in
      let fields, bits3 = parse_fields bits2 in
      (List.append [field] fields, bits3)

  let parse_sequence (bits : Cstruct_sexp.t) : sequence =
    let fields, _ = parse_fields bits in
    fields

  let to_string seq =
    match seq with
    | Output o -> Format.sprintf "PseudoPort: %s" (PseudoPort.to_string o)
    | Group g -> Format.sprintf "Group ID: %lu" g
    | PopVlan -> "Pop Vlan"
    | PushVlan _ -> "Push Vlan"
    | PopMpls _ -> "Pop Mpls"
    | PushMpls _ -> "Push Mpls"
    | SetField oxm -> Format.sprintf "oxm: %s" "" (*Oxm.to_string oxm*)
    | CopyTtlOut -> "Copy TTL out"
    | CopyTtlIn -> "Copy TTL In"
    | SetNwTtl t -> Format.sprintf "Set NW TTL %u" t
    | DecNwTtl -> "Dec NW TTL"
    | PushPbb _ -> "Push PBB"
    | PopPbb -> "Pop PBB"
    | SetMplsTtl t -> Format.sprintf "Set MPLS TTL: %u" t
    | DecMplsTtl -> "Dec MPLS TTL"
    | SetQueue q -> Format.sprintf "Set Queue: %lu" q
    | Experimenter e -> Format.sprintf "Experimenter: %lu" e

  (* Map generic single action to openflow 1.3 actions *)
  let from_of_action (action : OpenFlow.action) : t =
    let open OpenFlow in
    match action with
    | OpenFlow.Output pseudoport  ->
     (let port = match pseudoport with
      | Physical port_id -> PhysicalPort port_id
      | InPort           -> InPort
      | Table            -> Table
      | Normal           -> Normal
      | Flood            -> Flood
      | All              -> AllPorts
      | Controller c     -> Controller c
      | Local            -> Local
      in Output port)
    | OpenFlow.Modify fieldmod ->
     (let oxm = match fieldmod with
      | SetEthSrc dlAddr     -> OxmEthSrc (val_to_mask dlAddr)
      | SetEthDst dlAddr     -> OxmEthDst (val_to_mask dlAddr)
      | SetVlan dlVlan       -> OxmVlanVId (val_to_mask (Option.value_exn dlVlan))
      | SetVlanPcp dlVlanPcp -> OxmVlanPcp dlVlanPcp
      | SetEthTyp dlTyp      -> OxmEthType dlTyp
      | SetIPProto nwProto   -> OxmIPProto nwProto
      | SetIP4Src nwAddr     -> OxmIP4Src (val_to_mask nwAddr)
      | SetIP4Dst nwAddr     -> OxmIP4Dst (val_to_mask nwAddr)
      | SetTCPSrcPort tpPort -> OxmTCPSrc tpPort
      | SetTCPDstPort tpPort -> OxmTCPDst tpPort
      in SetField oxm)
    | OpenFlow.FastFail gid -> Group gid
    | Enqueue _ -> failwith "Not Yet Implemented"
  (* Map generic action sequence to openflow 1.3 instruction *)
  let from_of_seq (seq : OpenFlow.seq) : sequence =
    List.map seq ~f:from_of_action

end

module Bucket = struct

  type t = bucket

  let sizeof (bucket : bucket) : int =
    let n = sizeof_ofp_bucket + sum (List.map ~f:Action.sizeof bucket.bu_actions) in
    pad_to_64bits n

  let to_string (bucket : bucket) : string =
    Format.sprintf "{ length = %u; weight = %u; watch_port = %s; watch_group = %s; actions = %s }"
      (sizeof bucket)
      bucket.bu_weight
      (match bucket.bu_watch_port with
       | Some n -> Int32.to_string n
       | None -> "None")
      (match bucket.bu_watch_group with
       | Some n -> Int32.to_string n
       | None -> "None")
      ("[ " ^ (String.concat ~sep:"; " (List.map ~f:Action.to_string bucket.bu_actions)) ^ " ]")

  let length_func (buf : Cstruct_sexp.t) : int option =
    if Cstruct.length buf < sizeof_ofp_bucket then None
    else Some (pad_to_64bits (get_ofp_bucket_len buf))

  let marshal (buf : Cstruct_sexp.t) (bucket : bucket) : int =
    let size = sizeof bucket in
    set_ofp_bucket_len buf size;
    set_ofp_bucket_weight buf bucket.bu_weight;
    set_ofp_bucket_watch_port buf
      (match bucket.bu_watch_port with
       | None -> ofpg_any
       | Some port -> port);
    set_ofp_bucket_watch_group buf
      (match bucket.bu_watch_group with
       | None -> ofpg_any
       | Some group_id -> group_id);
    set_ofp_bucket_pad0 buf 0;
    set_ofp_bucket_pad1 buf 0;
    set_ofp_bucket_pad2 buf 0;
    set_ofp_bucket_pad3 buf 0;
    let action_marshal buf act =
      match act with
      | Output Table ->
        failwith "OFPP_TABLE not allowed in installed flow"
      | _ -> Action.marshal buf act in
    let buf = Cstruct.shift buf sizeof_ofp_bucket in
    (sizeof_ofp_bucket + (marshal_fields buf bucket.bu_actions action_marshal))

  let parse (bits : Cstruct_sexp.t) : bucket =
    let len = get_ofp_bucket_len bits in
    let bu_weight = get_ofp_bucket_weight bits in
    let bu_watch_port = match get_ofp_bucket_watch_port bits with
      | 0xffffffffl -> None (* ofpp_any *)
      | n -> Some n in
    let bu_watch_group = match get_ofp_bucket_watch_group bits with
      | 0xffffffffl -> None (* ofpg_any *)
      | n -> Some n in
    let bu_actions = Action.parse_sequence (Cstruct.sub bits sizeof_ofp_bucket (len - sizeof_ofp_bucket)) in
    {bu_weight; bu_watch_port; bu_watch_group; bu_actions}
end

module FlowModCommand = struct

  type t = flowModCommand

  let n = ref 0L

  let sizeof _ = 1

  let marshal (t : t) : int = match t with
    | AddFlow -> n := Int64.succ !n; ofp_flow_mod_command_to_int OFPFC_ADD
    | ModFlow -> ofp_flow_mod_command_to_int OFPFC_MODIFY
    | ModStrictFlow -> ofp_flow_mod_command_to_int OFPFC_MODIFY_STRICT
    | DeleteFlow -> ofp_flow_mod_command_to_int OFPFC_DELETE
    | DeleteStrictFlow -> ofp_flow_mod_command_to_int OFPFC_DELETE_STRICT

  let parse bits : flowModCommand =
    match (int_to_ofp_flow_mod_command bits) with
    | Some OFPFC_ADD -> AddFlow
    | Some OFPFC_MODIFY -> ModFlow
    | Some OFPFC_MODIFY_STRICT -> ModStrictFlow
    | Some OFPFC_DELETE -> DeleteFlow
    | Some OFPFC_DELETE_STRICT -> DeleteStrictFlow
    | None -> raise (Unparsable (sprintf "malformed command"))

  let to_string t =
    match t with
    | AddFlow -> "Add"
    | ModFlow -> "Modify"
    | ModStrictFlow -> "ModifyStrict"
    | DeleteFlow -> "Delete"
    | DeleteStrictFlow -> "DeleteStrict"
end

module GroupType = struct

  type t = groupType

  let n = ref 0L

  let to_string (t : t) : string = match t with
    | All -> "All"
    | Select -> "Select"
    | Indirect -> "Indirect"
    | FF -> "FF"

  let marshal (t : t) : int = match t with
    | All -> ofp_group_type_to_int OFPGT_ALL
    | Select -> ofp_group_type_to_int OFPGT_SELECT
    | Indirect -> ofp_group_type_to_int OFPGT_INDIRECT
    | FF -> ofp_group_type_to_int OFPGT_FF

  let parse (bits : int) : t =
    match int_to_ofp_group_type bits with
    | Some OFPGT_ALL -> All
    | Some OFPGT_SELECT  -> Select
    | Some OFPGT_INDIRECT -> Indirect
    | Some OFPGT_FF  -> FF
    | None -> raise (Unparsable (sprintf "malformed ofp_group_type"))

end

module GroupMod = struct

  [%%cenum
  type ofp_group_mod_command =
    | OFPGC_ADD [@id 0]
    | OFPGC_MODIFY [@id 1]
    | OFPGC_DELETE [@id 2]
    [@@uint16_t]
  ]

  type t = groupMod

  let sizeof (gm: groupMod) : int =
    match gm with
    | AddGroup (typ, gid, buckets) ->
      sizeof_ofp_group_mod + sum (List.map ~f:Bucket.sizeof buckets)
    | DeleteGroup (typ, gid) ->
      sizeof_ofp_group_mod
    | ModifyGroup (typ, _, buckets) ->
      sizeof_ofp_group_mod + sum (List.map ~f:Bucket.sizeof buckets)

  let to_string (gm : groupMod) : string =
    match gm with
    | AddGroup (typ, gid, buckets) -> Format.sprintf "AddGroup { typ = %s; gid = %lu ; bucket = %s }"
                                        (GroupType.to_string typ)
                                        gid
                                        ("[ " ^ (String.concat ~sep:"; " (List.map ~f:Bucket.to_string buckets)) ^ " ]")
    | DeleteGroup (typ, gid) -> Format.sprintf "DeleteGroup {type = %s; gid = %lu }"
                                  (GroupType.to_string typ)
                                  gid
    | ModifyGroup (typ, gid , buckets) -> Format.sprintf "ModifyGroup { typ = %s; gid = %lu ; bucket = %s }"
                                            (GroupType.to_string typ)
                                            gid
                                            ("[ " ^ (String.concat ~sep:"; " (List.map ~f:Bucket.to_string buckets)) ^ " ]")


  let marshal (buf : Cstruct_sexp.t) (gm : groupMod) : int =
    match gm with
    | AddGroup (typ, gid, buckets) ->
      set_ofp_group_mod_command buf 0; (* OFPGC_ADD *)
      set_ofp_group_mod_typ buf (GroupType.marshal typ);
      set_ofp_group_mod_pad buf 0;
      set_ofp_group_mod_group_id buf gid;
      sizeof_ofp_group_mod + (marshal_fields (Cstruct.shift buf sizeof_ofp_group_mod) buckets Bucket.marshal)
    | DeleteGroup (typ, gid) ->
      set_ofp_group_mod_command buf 2; (* OFPGC_DEL *)
      set_ofp_group_mod_typ buf (GroupType.marshal typ);
      set_ofp_group_mod_pad buf 0;
      set_ofp_group_mod_group_id buf gid;
      sizeof_ofp_group_mod
    | ModifyGroup (typ, gid, buckets) ->
      set_ofp_group_mod_command buf 1; (* OFPGC_MODIFY *)
      set_ofp_group_mod_typ buf (GroupType.marshal typ);
      set_ofp_group_mod_pad buf 0;
      set_ofp_group_mod_group_id buf gid;
      sizeof_ofp_group_mod + (marshal_fields (Cstruct.shift buf sizeof_ofp_group_mod) buckets Bucket.marshal)

  let parse (bits : Cstruct_sexp.t) : groupMod =
    let typ = GroupType.parse (get_ofp_group_mod_typ bits) in
    let gid = get_ofp_group_mod_group_id bits in
    let command = get_ofp_group_mod_command bits in
    match int_to_ofp_group_mod_command command with
    | Some OFPGC_ADD ->
      let bucket = parse_fields (Cstruct.shift bits sizeof_ofp_group_mod) Bucket.parse (Bucket.length_func) in
      AddGroup (typ,gid,bucket)
    | Some OFPGC_MODIFY -> DeleteGroup (typ,gid)
    | Some OFPGC_DELETE ->
      let bucket = parse_fields (Cstruct.shift bits sizeof_ofp_group_mod) Bucket.parse (Bucket.length_func) in
      ModifyGroup (typ,gid,bucket)
    | None -> raise (Unparsable (sprintf "malformed group command"))
end

module PortMod = struct

  [%%cstruct
  type ofp_port_mod = {
    port_no: uint32_t ;
    pad: uint8_t  [@len 4];
    hw_addr: uint8_t  [@len 6];
    pad2: uint8_t  [@len 2];
    config: uint32_t ;
    mask: uint32_t ;
    advertise: uint32_t ;
    pad3: uint8_t  [@len 4]
  } [@@big_endian]]

  type t = portMod

  let sizeof pm : int =
    sizeof_ofp_port_mod

  let to_string (pm : t) : string =
    Format.sprintf "{ port_no = %lu; hw_addr = %s; config = %s; mask = %lu; advertise = %s }"
      pm.mpPortNo
      (string_of_mac pm.mpHw_addr)
      (PortConfig.to_string pm.mpConfig)
      pm.mpMask
      (PortFeatures.to_string pm.mpAdvertise)

  let marshal (buf : Cstruct_sexp.t) (pm : t) : int =
    set_ofp_port_mod_port_no buf pm.mpPortNo;
    set_ofp_port_mod_pad (String.make 4 '\000') 0 buf;
    set_ofp_port_mod_hw_addr (bytes_of_mac pm.mpHw_addr) 0 buf;
    set_ofp_port_mod_pad2 (String.make 2 '\000') 0 buf;
    set_ofp_port_mod_config buf (PortConfig.marshal pm.mpConfig);
    set_ofp_port_mod_mask buf pm.mpMask;
    set_ofp_port_mod_advertise buf (PortFeatures.marshal pm.mpAdvertise);
    set_ofp_port_mod_pad3 (String.make 4 '\000') 0 buf;
    sizeof_ofp_port_mod

  let parse (bits : Cstruct_sexp.t) : t =
    let mpPortNo = get_ofp_port_mod_port_no bits in
    let mpHw_addr = mac_of_bytes (copy_ofp_port_mod_hw_addr bits) in
    let mpConfig = PortConfig.parse (get_ofp_port_mod_config bits) in
    let mpMask = get_ofp_port_mod_mask bits in
    let mpAdvertise = PortFeatures.parse (get_ofp_port_mod_advertise bits) in
    { mpPortNo; mpHw_addr; mpConfig; mpMask; mpAdvertise}

end

module MeterBand = struct

  [%%cenum
  type ofp_meter_band_type =
    | OFPMBT_DROP [@id 1]
    | OFPMBT_DSCP_REMARK [@id 2]
    | OFPMBT_EXPERIMENTER [@id 0xffff]
    [@@uint16_t]
  ]

  type t = meterBand

  let sizeof (mb : meterBand) : int =
    match mb with
    | Drop _ -> sizeof_ofp_meter_band_drop
    | DscpRemark _ -> sizeof_ofp_meter_band_dscp_remark
    | ExpMeter _ ->  sizeof_ofp_meter_band_experimenter

  let length_fun (buf : Cstruct_sexp.t) : int option =
    if Cstruct.length buf < sizeof_ofp_meter_band_header then None
    else Some (get_ofp_meter_band_header_len buf)

  let to_string (mb : meterBand) : string =
    match mb with
    | Drop (r,b) ->
      Format.sprintf "Drop { rate = %lu; burst_size = %lu }" r b
    | DscpRemark (r,b,p) ->
      Format.sprintf "Dscp Remark { rate = %lu; burst_size = %lu; prec level = %u }" r b p
    | ExpMeter (r,b,e) ->
      Format.sprintf "Experimetner { rate = %lu; burst_size = %lu; experimenter_id = %lu }" r b e

  let marshal (buf : Cstruct_sexp.t) (mb : meterBand) : int =
    match mb with
    | Drop (r,b) ->
      set_ofp_meter_band_drop_typ buf 1; (* OFPMBT_DROP *)
      set_ofp_meter_band_drop_len buf sizeof_ofp_meter_band_drop;
      set_ofp_meter_band_drop_rate buf r;
      set_ofp_meter_band_drop_burst_size buf b;
      set_ofp_meter_band_drop_pad (String.make 4 '\000') 0 buf;
      sizeof_ofp_meter_band_drop
    | DscpRemark (r,b,p) ->
      set_ofp_meter_band_dscp_remark_typ buf 2; (* OFPMBT_DSCP_REMARK *)
      set_ofp_meter_band_dscp_remark_len buf sizeof_ofp_meter_band_dscp_remark;
      set_ofp_meter_band_dscp_remark_rate buf r;
      set_ofp_meter_band_dscp_remark_burst_size buf b;
      set_ofp_meter_band_dscp_remark_prec_level buf p;
      set_ofp_meter_band_dscp_remark_pad (String.make 3 '\000') 0 buf;
      sizeof_ofp_meter_band_dscp_remark
    | ExpMeter (r,b,e) ->
      set_ofp_meter_band_experimenter_typ buf 0xffff; (* OFPMBT_EXPERIMENTER *)
      set_ofp_meter_band_experimenter_len buf sizeof_ofp_meter_band_experimenter;
      set_ofp_meter_band_experimenter_rate buf r;
      set_ofp_meter_band_experimenter_burst_size buf b;
      set_ofp_meter_band_experimenter_experimenter buf e;
      sizeof_ofp_meter_band_experimenter

  let parse (bits : Cstruct_sexp.t) : meterBand =
    let rate = get_ofp_meter_band_header_rate bits in
    let burst = get_ofp_meter_band_header_burst_size bits in
    let typ = get_ofp_meter_band_header_typ bits in
    match int_to_ofp_meter_band_type typ with
    | Some OFPMBT_DROP ->
      Drop (rate,burst)
    | Some OFPMBT_DSCP_REMARK ->
      let p = get_ofp_meter_band_dscp_remark_prec_level bits in
      DscpRemark (rate,burst,p)
    | Some OFPMBT_EXPERIMENTER ->
      let e = get_ofp_meter_band_experimenter_experimenter bits in
      ExpMeter (rate,burst,e)
    | None -> raise (Unparsable (sprintf "malformed typ"))

end

module MeterFlags = struct

  let marshal (mfm : meterFlags) : int =
    (if mfm.kbps then 1 lsl 0 else 0) lor
    (if mfm.pktps then 1 lsl 1 else 0) lor
    (if mfm.burst then 1 lsl 2 else 0) lor
    (if mfm.stats then 1 lsl 3 else 0)

  let parse bits : meterFlags =
    { kbps = test_bit16 0 bits
    ; pktps = test_bit16 1 bits
    ; burst = test_bit16 2 bits
    ; stats = test_bit16 3 bits }

  let to_string (mfm : meterFlags) : string =
    Format.sprintf "{ kpbs = %B; pktps = %B; burst = %B; stats = %B }"
      mfm.kbps
      mfm.pktps
      mfm.burst
      mfm.stats

end

module MeterMod = struct

  [%%cstruct
  type ofp_meter_mod = {
    commands: uint16_t ;
    flags: uint16_t ;
    meter_id: uint32_t ;
  } [@@big_endian]]

  module Command = struct

    [%%cenum
    type ofp_meter_mod_command =
      | OFPMC_ADD
      | OFPMC_MODIFY
      | OFPMC_DELETE
      [@@uint16_t]
    ]

    let to_string (t :  meterCommand) =
      match t with
      | AddMeter -> "AddMeter"
      | ModifyMeter -> "ModifyMeter"
      | DeleteMeter -> "DeleteMmeter"

    let marshal (t : meterCommand) : int =
      match t with
      | AddMeter -> ofp_meter_mod_command_to_int OFPMC_ADD
      | ModifyMeter -> ofp_meter_mod_command_to_int OFPMC_MODIFY
      | DeleteMeter -> ofp_meter_mod_command_to_int OFPMC_DELETE

    let parse t : meterCommand =
      match int_to_ofp_meter_mod_command t with
      | Some OFPMC_ADD -> AddMeter
      | Some OFPMC_MODIFY -> ModifyMeter
      | Some OFPMC_DELETE -> DeleteMeter
      | None -> raise (Unparsable (sprintf "malformed command"))
  end

  type t = meterMod

  let sizeof (mm : t) : int =
    sizeof_ofp_meter_mod + (sum (List.map ~f:MeterBand.sizeof mm.bands))

  let to_string (mm : t) : string =
    Format.sprintf "{ command = %s; flags = %s = meter_id = %lu; bands = %s }"
      (Command.to_string mm.command)
      (MeterFlags.to_string mm.flags)
      mm.meter_id
      ("[ " ^ (String.concat ~sep:"; " (List.map ~f:MeterBand.to_string mm.bands)) ^ " ]")

  let marshal (buf : Cstruct_sexp.t) (mm : t) : int =
    set_ofp_meter_mod_commands buf (Command.marshal mm.command);
    set_ofp_meter_mod_flags buf (MeterFlags.marshal mm.flags);
    set_ofp_meter_mod_meter_id buf mm.meter_id;
    sizeof_ofp_meter_mod + (marshal_fields (Cstruct.shift buf sizeof_ofp_meter_mod) mm.bands MeterBand.marshal)

  let parse (bits : Cstruct_sexp.t) : t =
    let command = Command.parse (get_ofp_meter_mod_commands bits) in
    let flags = MeterFlags.parse (get_ofp_meter_mod_flags bits) in
    let meter_id = get_ofp_meter_mod_meter_id bits in
    let bandsBits = Cstruct.shift bits sizeof_ofp_meter_mod in
    let bands = parse_fields bandsBits MeterBand.parse MeterBand.length_fun in
    { command; flags; meter_id; bands }

end

module Instruction = struct

  type t = instruction

  let to_string (ins : t) =
    match ins with
    | GotoTable t -> Format.sprintf "Go to Table = %u" t
    | ApplyActions actions -> Format.sprintf "Apply Actions = [ %s ]"
                                (String.concat ~sep:"; " (List.map ~f:Action.to_string actions))
    | WriteActions actions -> Format.sprintf "Write Actions = [ %s ]"
                                (String.concat ~sep:"; " (List.map ~f:Action.to_string actions))
    | WriteMetadata meta ->
      (match meta.m_mask with
       | None -> Format.sprintf "WriteMeta = %LX" meta.m_value
       | Some m -> Format.sprintf "WriteMeta = %LX/%LX" meta.m_value m)
    | Clear -> "Clear"
    | Meter m -> Format.sprintf "Meter = %lu" m
    | Experimenter e -> Format.sprintf "Experimenter = %lu" e

  let sizeof (ins : t) : int =
    match ins with
    | GotoTable _ ->
      sizeof_ofp_instruction_goto_table
    | ApplyActions actions ->
      sizeof_ofp_instruction_actions + sum (List.map ~f:Action.sizeof actions)
    | WriteActions actions ->
      sizeof_ofp_instruction_actions + sum (List.map ~f:Action.sizeof actions)
    | WriteMetadata _ -> sizeof_ofp_instruction_write_metadata
    | Clear -> sizeof_ofp_instruction_actions
    | Meter _ -> sizeof_ofp_instruction_meter
    | Experimenter _ -> sizeof_ofp_instruction_experimenter

  let marshal (buf : Cstruct_sexp.t) (ins : t) : int =
    let size = sizeof ins in
    match ins with
    | GotoTable table_id ->
      set_ofp_instruction_goto_table_typ buf 1; (* OFPIT_GOTO_TABLE *)
      set_ofp_instruction_goto_table_len buf size;
      set_ofp_instruction_goto_table_table_id buf table_id;
      set_ofp_instruction_goto_table_pad0 buf 0;
      set_ofp_instruction_goto_table_pad1 buf 0;
      set_ofp_instruction_goto_table_pad2 buf 0;
      size
    | WriteActions actions ->
      set_ofp_instruction_actions_typ buf 3; (* OFPIT_WRITE_ACTIONS *)
      set_ofp_instruction_actions_len buf size;
      set_ofp_instruction_actions_pad0 buf 0;
      set_ofp_instruction_actions_pad1 buf 0;
      set_ofp_instruction_actions_pad2 buf 0;
      set_ofp_instruction_actions_pad3 buf 0;
      sizeof_ofp_instruction_actions + (
        marshal_fields
          (Cstruct.shift buf sizeof_ofp_instruction_actions)
          actions
          Action.marshal)
    | ApplyActions actions ->
      set_ofp_instruction_actions_typ buf 4; (* OFPIT_APPLY_ACTIONS *)
      set_ofp_instruction_actions_len buf size;
      set_ofp_instruction_actions_pad0 buf 0;
      set_ofp_instruction_actions_pad1 buf 0;
      set_ofp_instruction_actions_pad2 buf 0;
      set_ofp_instruction_actions_pad3 buf 0;
      sizeof_ofp_instruction_actions + (marshal_fields (Cstruct.shift buf sizeof_ofp_instruction_actions) actions Action.marshal)
    | WriteMetadata metadata ->
      set_ofp_instruction_write_metadata_typ buf 2; (* OFPIT_WRITE_METADATA *)
      set_ofp_instruction_write_metadata_len buf size;
      set_ofp_instruction_write_metadata_pad0 buf 0;
      set_ofp_instruction_write_metadata_pad1 buf 0;
      set_ofp_instruction_write_metadata_pad2 buf 0;
      set_ofp_instruction_write_metadata_pad3 buf 0;
      set_ofp_instruction_write_metadata_metadata buf metadata.m_value;
      set_ofp_instruction_write_metadata_metadata_mask buf (
        match metadata.m_mask with
        | None -> 0L
        | Some mask -> mask);
      size
    | Clear ->
      set_ofp_instruction_actions_typ buf 5; (* OFPIT_CLEAR_ACTIONS *)
      set_ofp_instruction_actions_len buf size;
      set_ofp_instruction_actions_pad0 buf 0;
      set_ofp_instruction_actions_pad1 buf 0;
      set_ofp_instruction_actions_pad2 buf 0;
      set_ofp_instruction_actions_pad3 buf 0;
      size
    | Meter meterId->
      set_ofp_instruction_meter_typ buf 6; (* OFPIT_METER *)
      set_ofp_instruction_meter_len buf size;
      set_ofp_instruction_meter_meter_id buf meterId;
      size
    | Experimenter experimenterId->
      set_ofp_instruction_experimenter_typ buf 0xffff; (* OFPIT_EXPERIMENTER *)
      set_ofp_instruction_experimenter_len buf size;
      set_ofp_instruction_experimenter_experimenter buf experimenterId;
      size


  let parse (bits : Cstruct_sexp.t) : t =
    let typ = get_ofp_instruction_typ bits in
    let len = get_ofp_instruction_len bits in
    match (int_to_ofp_instruction_type typ) with
    | Some OFPIT_GOTO_TABLE -> GotoTable (
        get_ofp_instruction_goto_table_table_id bits)
    | Some OFPIT_WRITE_METADATA ->
      let value = get_ofp_instruction_write_metadata_metadata bits in
      let mask = get_ofp_instruction_write_metadata_metadata_mask bits in
      if Poly.(mask <> 0L) then
        WriteMetadata ({m_value = value; m_mask = Some mask})
      else
        WriteMetadata ({m_value = value; m_mask = None})
    | Some OFPIT_WRITE_ACTIONS -> WriteActions (
        Action.parse_sequence (Cstruct.sub bits sizeof_ofp_instruction_actions (len-sizeof_ofp_instruction_actions)))
    | Some OFPIT_APPLY_ACTIONS -> ApplyActions (
        Action.parse_sequence (Cstruct.sub bits sizeof_ofp_instruction_actions (len-sizeof_ofp_instruction_actions)))
    | Some OFPIT_CLEAR_ACTIONS -> Clear
    | Some OFPIT_METER -> Meter (get_ofp_instruction_meter_meter_id bits)
    | Some OFPIT_EXPERIMENTER -> Experimenter (
        get_ofp_instruction_experimenter_experimenter bits)
    | _ -> raise (Unparsable (sprintf "Unkown instruction message"))

end

module Instructions = struct

  type t = instruction list [@@deriving sexp]

  let sizeof (inss : t) : int =
    sum (List.map ~f:Instruction.sizeof inss)

  let marshal (buf : Cstruct_sexp.t) (inss : t) : int =
    if sizeof inss <> 0 then
      marshal_fields buf inss Instruction.marshal
    else 0

  let rec parse_field (bits : Cstruct_sexp.t) : t * Cstruct_sexp.t =
    if Cstruct.length bits < sizeof_ofp_instruction then [],bits
    else let field = Instruction.parse bits in
      let bits2 = Cstruct.shift bits (Instruction.sizeof field) in
      let fields, bits3 = parse_field bits2 in
      (List.append [field] fields, bits3)

  let to_string insts =
    sexp_of_t insts
    |> Sexp.to_string

  let parse (bits : Cstruct_sexp.t) : t =
    let field,_ = parse_field bits in
    field

  (* Take a generic action group and produce an openflow 1.3 instruction list *)
  let from_of_group (group : OpenFlow.group) : t =
    (* group is a singleton list containing a list of lists of actions *)
    match group with
    | []        -> []
    | par :: [] -> [ApplyActions (List.concat (List.map par ~f:Action.from_of_seq))]
    (* TODO(mulias): this is a bug. When running mininet with ovs 2.0.2, a non
     * singleton action group would not be propperly processed by the switch. *)
    | _         -> failwith "Action group can not contain more than one sequence"

end

module FlowMod = struct

  type t = flowMod

  let sizeof (fm : t) =
    sizeof_ofp_flow_mod + (OfpMatch.sizeof fm.mfOfp_match) + (Instructions.sizeof fm.mfInstructions)

  module Flags = struct

    let marshal (f : flowModFlags) =
      (if f.fmf_send_flow_rem then 1 lsl 0 else 0) lor
      (if f.fmf_check_overlap then 1 lsl 1 else 0) lor
      (if f.fmf_reset_counts then 1 lsl 2 else 0) lor
      (if f.fmf_no_pkt_counts then 1 lsl 3 else 0) lor
      (if f.fmf_no_byt_counts then 1 lsl 4 else 0)

    let parse bits : flowModFlags =
      { fmf_send_flow_rem = test_bit16  0 bits
      ; fmf_check_overlap = test_bit16  1 bits
      ; fmf_reset_counts = test_bit16  2 bits
      ; fmf_no_pkt_counts = test_bit16  3 bits
      ; fmf_no_byt_counts = test_bit16  4 bits
      }

    let to_string f =
      Format.sprintf "{ send_flow_rem = %B; check_overlap = %B; reset_counts = %B; \
                      no_pkt_counts = %B; no_byt_counts = %B }"
        f.fmf_send_flow_rem
        f.fmf_check_overlap
        f.fmf_reset_counts
        f.fmf_no_pkt_counts
        f.fmf_no_byt_counts

  end

  let marshal (buf : Cstruct_sexp.t) (fm : t) : int =
    set_ofp_flow_mod_cookie buf fm.mfCookie.m_value;
    set_ofp_flow_mod_cookie_mask buf (
      match fm.mfCookie.m_mask with
      | None -> 0L
      | Some mask -> mask);
    set_ofp_flow_mod_table_id buf fm.mfTable_id;
    set_ofp_flow_mod_command buf (FlowModCommand.marshal fm.mfCommand);
    set_ofp_flow_mod_idle_timeout buf
      (match fm.mfIdle_timeout with
       | Permanent -> 0
       | ExpiresAfter value -> value);
    set_ofp_flow_mod_hard_timeout buf
      (match fm.mfHard_timeout with
       | Permanent -> 0
       | ExpiresAfter value -> value);
    set_ofp_flow_mod_priority buf fm.mfPriority;
    set_ofp_flow_mod_buffer_id buf
      (match fm.mfBuffer_id with
       | None -> ofp_no_buffer
       | Some bid -> bid);
    set_ofp_flow_mod_out_port buf
      (match fm.mfOut_port with
       | None -> PseudoPort.marshal Any
       | Some port -> PseudoPort.marshal port);
    set_ofp_flow_mod_out_group buf
      (match fm.mfOut_group with
       | None -> 0l
       | Some gid -> gid);
    set_ofp_flow_mod_flags buf (Flags.marshal fm.mfFlags);
    set_ofp_flow_mod_pad0 buf 0;
    set_ofp_flow_mod_pad1 buf 0;

    let size = sizeof_ofp_flow_mod +
               OfpMatch.marshal
                 (Cstruct.sub buf sizeof_ofp_flow_mod (OfpMatch.sizeof fm.mfOfp_match))
                 fm.mfOfp_match in
    size + Instructions.marshal (Cstruct.shift buf size) fm.mfInstructions

  let parse (bits : Cstruct_sexp.t) : t =
    let mfMask = get_ofp_flow_mod_cookie_mask bits in
    let mfCookie =
      if Poly.(mfMask <> 0L) then
        {m_value = get_ofp_flow_mod_cookie bits;
         m_mask = (Some (get_ofp_flow_mod_cookie_mask bits))}
      else {m_value = get_ofp_flow_mod_cookie bits;
            m_mask = None}
    in
    let mfTable_id = get_ofp_flow_mod_table_id bits in
    let mfCommand = FlowModCommand.parse (get_ofp_flow_mod_command bits) in
    let mfIdle_timeout = match (get_ofp_flow_mod_idle_timeout bits) with
      | 0 -> Permanent
      | n -> ExpiresAfter n in
    let mfHard_timeout = match (get_ofp_flow_mod_hard_timeout bits) with
      | 0 -> Permanent
      | n -> ExpiresAfter n in
    let mfPriority = get_ofp_flow_mod_priority bits in
    let mfBuffer_id = match (get_ofp_flow_mod_buffer_id bits) with
      | 0xffffffffl -> None
      | n -> Some n in
    let mfOut_port = match (get_ofp_flow_mod_out_port bits) with
      | 0l -> None
      | _ -> Some (PseudoPort.make (get_ofp_flow_mod_out_port bits) 0) in
    let mfOut_group = match (get_ofp_flow_mod_out_group bits) with
      | 0l -> None
      | n -> Some n in
    let mfFlags = Flags.parse (get_ofp_flow_mod_flags bits) in
    let mfOfp_match,instructionsBits = OfpMatch.parse (Cstruct.shift bits sizeof_ofp_flow_mod) in
    let mfInstructions = Instructions.parse instructionsBits in
    { mfCookie; mfTable_id;
      mfCommand; mfIdle_timeout;
      mfHard_timeout; mfPriority;
      mfBuffer_id;
      mfOut_port;
      mfOut_group; mfFlags;
      mfOfp_match; mfInstructions}

  let to_string (flow : t) =
    Format.sprintf "{ cookie = %s; table = %u; command = %s; idle_timeout = %s; \
                    hard_timeout = %s; priority = %u; bufferId = %s; out_port = %s; \
                    out_group = %s; flags = %s; match = %s; instructions = %s }"
      (match flow.mfCookie.m_mask with
       | None -> Int64.to_string flow.mfCookie.m_value
       | Some m -> Format.sprintf "%LX/%LX" flow.mfCookie.m_value m)
      flow.mfTable_id
      (FlowModCommand.to_string flow.mfCommand)
      (match flow.mfIdle_timeout with
       | Permanent -> "Permanent"
       | ExpiresAfter t-> string_of_int t)
      (match flow.mfHard_timeout with
       | Permanent -> "Permanent"
       | ExpiresAfter t-> string_of_int t)
      flow.mfPriority
      (match flow.mfBuffer_id with
       | None -> "None"
       | Some t -> Int32.to_string t)
      (match flow.mfOut_port with
       | None -> "None"
       | Some t -> PseudoPort.to_string t)
      (match flow.mfOut_group with
       | None -> "None"
       | Some t -> Int32.to_string t)
      (Flags.to_string flow.mfFlags)
      (OfpMatch.to_string flow.mfOfp_match)
      (Instructions.to_string flow.mfInstructions)
end

module Capabilities = struct

  type t = capabilities

  let to_int32 (capa : t) : int32 =
    Int32.bit_or (if capa.flow_stats then (Int32.shift_left 1l 0) else 0l)
      (Int32.bit_or (if capa.table_stats then (Int32.shift_left 1l 1) else 0l)
         (Int32.bit_or (if capa.port_stats then (Int32.shift_left 1l 2) else 0l)
            (Int32.bit_or (if capa.group_stats then (Int32.shift_left 1l 3) else 0l)
               (Int32.bit_or (if capa.ip_reasm then (Int32.shift_left 1l 5) else 0l)
                  (Int32.bit_or (if capa.queue_stats then (Int32.shift_left 1l 6) else 0l)
                     (if capa.port_blocked then (Int32.shift_left 1l 8) else 0l))))))

  let to_string (cap : t) : string =
    Format.sprintf "{ port_blocked = %B; queue_stats = %B; ip_reasm = %B; group_stats = %B; \
                    port_stats = %B; table_stats = %B; flow_stats = %B }"
      cap.port_blocked
      cap.queue_stats
      cap.ip_reasm
      cap.group_stats
      cap.port_stats
      cap.table_stats
      cap.flow_stats

  let parse (bits : int32) : t =
    { port_blocked = Bits.test_bit 8 bits;
      queue_stats = Bits.test_bit 6 bits;
      ip_reasm = Bits.test_bit 5 bits;
      group_stats = Bits.test_bit 3 bits;
      port_stats = Bits.test_bit 2 bits;
      table_stats = Bits.test_bit 1 bits;
      flow_stats = Bits.test_bit 0 bits;
    }

end

module SwitchFeatures = struct

  type t = switchFeatures

  let sizeof (sw : t) : int =
    sizeof_ofp_switch_features

  let to_string (sw : t) : string =
    Format.sprintf "{ datapath_id = %Lu; num_buffers = %lu; num_Tables = %u; aux_id = %u; capabilities = %s }"
      sw.datapath_id
      sw.num_buffers
      sw.num_tables
      sw.aux_id
      (Capabilities.to_string sw.supported_capabilities)

  let marshal (buf : Cstruct_sexp.t) (features : t) : int =
    set_ofp_switch_features_datapath_id buf features.datapath_id;
    set_ofp_switch_features_n_buffers buf features.num_buffers;
    set_ofp_switch_features_n_tables buf features.num_tables;
    set_ofp_switch_features_auxiliary_id buf features.aux_id;
    set_ofp_switch_features_pad0 buf 0;
    set_ofp_switch_features_pad1 buf 0;
    set_ofp_switch_features_capabilities buf (Capabilities.to_int32 features.supported_capabilities);
    sizeof_ofp_switch_features

  let parse (bits : Cstruct_sexp.t) : t =
    let datapath_id = get_ofp_switch_features_datapath_id bits in
    let num_buffers = get_ofp_switch_features_n_buffers bits in
    let num_tables = get_ofp_switch_features_n_tables bits in
    let aux_id = get_ofp_switch_features_auxiliary_id bits in
    let supported_capabilities = Capabilities.parse
        (get_ofp_switch_features_capabilities bits) in
    { datapath_id;
      num_buffers;
      num_tables;
      aux_id;
      supported_capabilities }

end

module PortDesc = struct

  type t = portDesc

  let sizeof (_ : t) =
    sizeof_ofp_port

  let marshal (buf : Cstruct_sexp.t) (desc : t) : int =
    let size = sizeof_ofp_port in
    set_ofp_port_port_no buf desc.port_no;
    set_ofp_port_pad buf 0l;
    set_ofp_port_hw_addr (bytes_of_mac desc.hw_addr) 0 buf;
    set_ofp_port_pad2 buf 0;
    set_ofp_port_pad3 buf 0;
    set_ofp_port_name desc.name 0 buf;
    set_ofp_port_config buf (PortConfig.marshal desc.config);
    set_ofp_port_state buf (PortState.marshal desc.state);
    set_ofp_port_curr buf (PortFeatures.marshal desc.curr);
    set_ofp_port_advertised buf (PortFeatures.marshal desc.advertised);
    set_ofp_port_supported buf (PortFeatures.marshal desc.supported);
    set_ofp_port_peer buf (PortFeatures.marshal desc.peer);
    set_ofp_port_curr_speed buf desc.curr_speed;
    set_ofp_port_max_speed buf desc.max_speed;
    size

  let parse (bits : Cstruct_sexp.t) : t =
    let port_no = get_ofp_port_port_no bits in
    let hw_addr = mac_of_bytes (copy_ofp_port_hw_addr bits) in
    let name = copy_ofp_port_name bits in
    let state = PortState.parse (get_ofp_port_state bits) in
    let config = PortConfig.parse (get_ofp_port_config bits) in
    let curr = PortFeatures.parse (get_ofp_port_curr bits) in
    let advertised = PortFeatures.parse (get_ofp_port_advertised bits) in
    let supported = PortFeatures.parse (get_ofp_port_supported bits) in
    let peer = PortFeatures.parse (get_ofp_port_peer bits) in
    let curr_speed = get_ofp_port_curr_speed bits in
    let max_speed = get_ofp_port_max_speed bits in
    { port_no;
      hw_addr;
      name;
      config;
      state;
      curr;
      advertised;
      supported;
      peer;
      curr_speed;
      max_speed }

  let to_string (port : t) =
    Format.sprintf " { port_no = %lu; hw_addr = %s; name = %s; config = %s; \
                    state = %s; curr = %s; advertised = %s; \
                    supported = %s; peer = %s; curr_speed = %lu; max_speed = %lu }"
      port.port_no
      (string_of_mac port.hw_addr)
      port.name
      (PortConfig.to_string port.config)
      (PortState.to_string port.state)
      (PortFeatures.to_string port.curr)
      (PortFeatures.to_string port.advertised)
      (PortFeatures.to_string port.supported)
      (PortFeatures.to_string port.peer)
      port.curr_speed
      port.max_speed

  let length_func = (fun buf -> Some sizeof_ofp_port)
end

module PortStatus = struct

  type t = portStatus

  let sizeof (_ : t) : int =
    sizeof_ofp_port_status + sizeof_ofp_port

  module Reason = struct

    let marshal (pr : portReason) : int =
      match pr with
      | PortAdd -> ofp_port_reason_to_int OFPPR_ADD
      | PortDelete -> ofp_port_reason_to_int OFPPR_DELETE
      | PortModify -> ofp_port_reason_to_int OFPPR_MODIFY

    let to_string (pr : portReason) =
      match pr with
      | PortAdd -> "PortAdd"
      | PortDelete -> "PortDelete"
      | PortModify -> "PortModify"

    let parse t : portReason =
      match int_to_ofp_port_reason t with
      | Some OFPPR_ADD -> PortAdd
      | Some OFPPR_DELETE -> PortDelete
      | Some OFPPR_MODIFY -> PortModify
      | None -> raise (Unparsable (sprintf "unexpected port reason"))
  end

  let marshal (buf : Cstruct_sexp.t) (status : t) : int =
    set_ofp_port_status_reason buf (Reason.marshal status.reason);
    let size = sizeof_ofp_port_status +
               PortDesc.marshal (Cstruct.shift buf sizeof_ofp_port_status) status.desc in
    size

  let parse (bits : Cstruct_sexp.t) : t =
    let reason = Reason.parse (get_ofp_port_status_reason bits)in
    let bits = Cstruct.shift bits sizeof_ofp_port_status in
    let desc = PortDesc.parse bits in
    { reason;
      desc }

  let to_string (t : t) =
    Format.sprintf
      "{ reason = %s; desc = %s }"
      (Reason.to_string t.reason)
      (PortDesc.to_string t.desc)
end

module PacketIn = struct

  type t = packetIn

  module Reason = struct

    [%%cenum
    type ofp_packet_in_reason =
      | NO_MATCH [@id 0]
      | ACTION [@id 1]
      | INVALID_TTL [@id 2]
      [@@uint8_t]
    ]

    type t = packetInReason

    let to_string t : string =
      match t with
      | NoMatch -> "NO_MATCH"
      | ExplicitSend -> "ACTION"
      | InvalidTTL -> "INVALID_TTL"

    let marshal t : int =
      match t with
      | NoMatch -> ofp_packet_in_reason_to_int NO_MATCH
      | ExplicitSend -> ofp_packet_in_reason_to_int ACTION
      | InvalidTTL -> ofp_packet_in_reason_to_int INVALID_TTL

    let parse t : packetInReason =
      match int_to_ofp_packet_in_reason t with
      | Some NO_MATCH -> NoMatch
      | Some ACTION -> ExplicitSend
      | Some INVALID_TTL -> InvalidTTL
      | None -> raise (Unparsable (sprintf "bad reason in packet_in (%d)" t))
  end

  [%%cstruct
  type ofp_packet_in = {
    buffer_id: uint32_t ;
    total_len: uint16_t ;
    reason: uint8_t ;
    table_id: uint8_t ;
    cookie: uint64_t ;
  } [@@big_endian]]

  let sizeof (pi : t) : int =
    pi.pi_total_len + (OfpMatch.sizeof pi.pi_ofp_match) + sizeof_ofp_packet_in + 2 (*2 bytes of pad*)

  let to_string (pi: t) : string =
    Format.sprintf "{ total_len = %u; reason = %s; table_id = %u; cookie = %Lu; match = %s; payload = %s }"
      pi.pi_total_len
      (Reason.to_string pi.pi_reason)
      pi.pi_table_id
      pi.pi_cookie
      (OfpMatch.to_string pi.pi_ofp_match)
      (match pi.pi_payload with
       | Buffered (n,bytes) -> Format.sprintf "Buffered<id=%lu>= %s; len = %u" n (Packet.to_string (Packet.parse bytes)) (Cstruct.length bytes)
       | NotBuffered bytes -> Format.sprintf "NotBuffered = %s; len = %u"  (Packet.to_string (Packet.parse bytes)) (Cstruct.length bytes))

  let marshal (buf : Cstruct_sexp.t) (pi : t) : int =
    let bufMatch = Cstruct.shift buf sizeof_ofp_packet_in in
    let size = pi.pi_total_len + (OfpMatch.marshal bufMatch pi.pi_ofp_match) +
               sizeof_ofp_packet_in in
    let buffer_id,bytes = match pi.pi_payload with
      | Buffered (n,bytes) -> n, bytes
      | NotBuffered bytes -> -1l, bytes in
    set_ofp_uint8_value (Cstruct.shift bufMatch (OfpMatch.sizeof pi.pi_ofp_match)) 0; (*pad*)
    set_ofp_uint8_value (Cstruct.shift bufMatch (OfpMatch.sizeof pi.pi_ofp_match + 1)) 0; (*pad*)
    Cstruct.blit bytes 0 bufMatch (2 + OfpMatch.sizeof pi.pi_ofp_match) pi.pi_total_len;
    set_ofp_packet_in_buffer_id buf buffer_id;
    set_ofp_packet_in_total_len buf pi.pi_total_len;
    set_ofp_packet_in_reason buf (Reason.marshal pi.pi_reason);
    set_ofp_packet_in_table_id buf pi.pi_table_id;
    set_ofp_packet_in_cookie buf pi.pi_cookie;
    size

  let parse (bits : Cstruct_sexp.t) : t =
    (* let oc = open_out "test-msg-1.3-msg3-bits" in *)
    (* let str = Cstruct.to_string bits in *)
    (* fprintf oc "%s" str; *)
    (* close_out oc; *)
    let bufId = match get_ofp_packet_in_buffer_id bits with
      | -1l -> None
      | n -> Some n in
    let total_len = get_ofp_packet_in_total_len bits in
    let reason_code = get_ofp_packet_in_reason bits in
    let reason = Reason.parse (reason_code) in
    let table_id = get_ofp_packet_in_table_id bits in
    let cookie = get_ofp_packet_in_cookie bits in
    let ofp_match_bits = Cstruct.shift bits sizeof_ofp_packet_in in
    let ofp_match, pkt_bits = OfpMatch.parse ofp_match_bits in
    let pkt_bits = Cstruct.sub pkt_bits 2 total_len in (* pad bytes *)
    let final_bits = Cstruct.create total_len in
    (* create a new [cstruct type to set the offset to 0 *)
    Cstruct.blit pkt_bits 0 final_bits 0 total_len;
    (* printf "len = %d\n" (Cstruct.length pkt_bits); *)
    let pkt = match bufId with
      | None -> NotBuffered final_bits
      | Some n -> Buffered (n,final_bits)
    in
    { pi_total_len = total_len;
      pi_reason = reason;
      pi_table_id = table_id;
      pi_cookie = cookie;
      pi_ofp_match = ofp_match;
      pi_payload = pkt
    }

end

module PacketOut = struct

  [%%cstruct
  type ofp_packet_out = {
    buffer_id: uint32_t ;           (* ID assigned by datapath (OFP_NO_BUFFER if none). *)
    in_port: uint32_t ;             (* Packet's input port or OFPP_CONTROLLER. *)
    actions_len: uint16_t ;         (* Size of action array in bytes. *)
    pad0: uint8_t ;
    pad1: uint8_t ;
    pad2: uint8_t ;
    pad3: uint8_t ;
    pad4: uint8_t ;
    pad5: uint8_t ;
    (* struct ofp_action_header actions[0]; *) (* Action list. *)
    (* uint8_t data[0]; *)        (* Packet data.  The length is inferred
                                     from the length field in the header.
                                     (Only meaningful if buffer_id == -1.) *)
  } [@@big_endian]]

  type t = packetOut

  let sizeof (po : t) =
    sizeof_ofp_packet_out + sum (List.map ~f:Action.sizeof po.po_actions) +
    (match po.po_payload with
     | Buffered _ -> 0
     | NotBuffered bytes -> Cstruct.length bytes)

  let to_string (po : t) =
    Format.sprintf "{ payload = %s; port_id = %s; actions = %s }"
      (match po.po_payload with
       | Buffered (n,_) -> Format.sprintf "Buffered<id=%lu>" n
       | NotBuffered bytes -> Format.sprintf "NotBuffered = %s; len = %u" (Packet.to_string (Packet.parse bytes)) (Cstruct.length bytes))
      (match po.po_port_id with
       | Some n -> Int32.to_string n
       | None -> "No Port")
      ("[ " ^ (String.concat ~sep:"; " (List.map ~f:Action.to_string po.po_actions)) ^ " ]")

  let marshal (buf : Cstruct_sexp.t) (po : t) : int =
    let size = sizeof po in
    set_ofp_packet_out_buffer_id buf (
      match po.po_payload with
      | NotBuffered _ -> 0xffffffffl
      | Buffered (buffer_id, _) -> buffer_id);
    set_ofp_packet_out_in_port buf
      (match po.po_port_id with
       | None -> 0l
       | Some(port_id) -> port_id);
    set_ofp_packet_out_actions_len buf (sum (List.map ~f:Action.sizeof po.po_actions));
    set_ofp_packet_out_pad0 buf 0;
    set_ofp_packet_out_pad1 buf 0;
    set_ofp_packet_out_pad2 buf 0;
    set_ofp_packet_out_pad3 buf 0;
    set_ofp_packet_out_pad4 buf 0;
    set_ofp_packet_out_pad5 buf 0;
    let buf = Cstruct.shift buf sizeof_ofp_packet_out in
    let act_size = marshal_fields buf po.po_actions Action.marshal in
    match po.po_payload with
    | Buffered _ -> size
    | NotBuffered pkt_buf ->
      Cstruct.blit pkt_buf 0 buf act_size (Cstruct.length pkt_buf);
      size

  let parse (bits : Cstruct_sexp.t) : t =
    let bufId = match get_ofp_packet_out_buffer_id bits with
      | -1l -> None
      | n -> Some n in
    let po_port_id = match get_ofp_packet_out_in_port bits with
      | 0l -> None
      | n -> Some n in
    let actions_size = get_ofp_packet_out_actions_len bits in
    let bits = Cstruct.shift bits sizeof_ofp_packet_out in
    let po_actions = Action.parse_sequence (Cstruct.sub bits 0 actions_size) in
    let po_payload = match bufId with
      | None ->
        let data_bits = Cstruct.shift bits actions_size in
        let final_bits = Cstruct.create (Cstruct.length data_bits) in
        Cstruct.blit data_bits 0 final_bits 0 (Cstruct.length data_bits);
        NotBuffered final_bits
      | Some n ->
        let final_bits = Cstruct.create 0 in
        Buffered (n,final_bits) in
    { po_payload; po_port_id; po_actions }

end

module FlowRemoved = struct

  module RemovedReason = struct

    [%%cenum
    type ofp_flow_removed_reason =
      | OFPRR_IDLE_TIMEOUT [@id 0]
      | OFPRR_HARD_TIMEOUT [@id 1]
      | OFPRR_DELETE [@id 2]
      | OFPRR_GROUP_DELETE [@id 3]
      [@@uint8_t]
    ]

    type t = flowReason

    let to_string (t : flowReason) : string =
      match t with
      | FlowIdleTimeout -> "IDLE_TIMEOUT"
      | FlowHardTiemout -> "HARD_TIMEOUT"
      | FlowDelete -> "DELETE"
      | FlowGroupDelete -> "GROUP_DELETE"

    let marshal (t : flowReason) : int8 =
      match t with
      | FlowIdleTimeout -> ofp_flow_removed_reason_to_int OFPRR_IDLE_TIMEOUT
      | FlowHardTiemout -> ofp_flow_removed_reason_to_int OFPRR_HARD_TIMEOUT
      | FlowDelete -> ofp_flow_removed_reason_to_int OFPRR_DELETE
      | FlowGroupDelete -> ofp_flow_removed_reason_to_int OFPRR_GROUP_DELETE

    let parse bits : flowReason =
      match (int_to_ofp_flow_removed_reason bits) with
      | Some OFPRR_IDLE_TIMEOUT -> FlowIdleTimeout
      | Some OFPRR_HARD_TIMEOUT -> FlowHardTiemout
      | Some OFPRR_DELETE -> FlowDelete
      | Some OFPRR_GROUP_DELETE -> FlowGroupDelete
      | None -> raise (Unparsable (sprintf "malformed reason"))

  end

  [%%cstruct
  type ofp_flow_removed = {
    cookie: uint64_t ;
    priority: uint16_t ;
    reason: uint8_t ;
    table_id: uint8_t ;
    duration_sec: uint32_t ;
    duration_nsec: uint32_t ;
    idle_timeout: uint16_t ;
    hard_timeout: uint16_t ;
    packet_count: uint64_t ;
    byte_count: uint64_t
  } [@@big_endian]]

  type t = flowRemoved

  let sizeof (f : flowRemoved) : int =
    sizeof_ofp_flow_removed + (OfpMatch.sizeof f.oxm)

  let to_string (f : flowRemoved) : string =
    Format.sprintf "{ cookie = %Lu; priotity = %u; reason = %s; table_id = %u;\
                    duration s/ns = %lu/%lu; idle_timeout = %s; hard_timeout = %s; packet_count = %Lu;\
                    byte_count = %Lu; match = %s }"
      f.cookie
      f.priority
      (RemovedReason.to_string f.reason)
      f.table_id
      f.duration_sec
      f.duration_nsec
      (match f.idle_timeout with
       | Permanent -> "Permanent"
       | ExpiresAfter t-> string_of_int t)
      (match f.hard_timeout with
       | Permanent -> "Permanent"
       | ExpiresAfter t-> string_of_int t)
      f.packet_count
      f.byte_count
      (OfpMatch.to_string f.oxm)

  let marshal (buf : Cstruct_sexp.t) (f : flowRemoved) : int =
    set_ofp_flow_removed_cookie buf f.cookie;
    set_ofp_flow_removed_priority buf f.priority;
    set_ofp_flow_removed_reason buf (RemovedReason.marshal f.reason);
    set_ofp_flow_removed_table_id buf f.table_id;
    set_ofp_flow_removed_duration_sec buf f.duration_sec;
    set_ofp_flow_removed_duration_nsec buf f.duration_nsec;
    set_ofp_flow_removed_idle_timeout buf (match f.idle_timeout with
        | Permanent -> 0
        | ExpiresAfter v -> v);
    set_ofp_flow_removed_hard_timeout buf (match f.hard_timeout with
        | Permanent -> 0
        | ExpiresAfter v -> v);
    set_ofp_flow_removed_packet_count buf f.packet_count;
    set_ofp_flow_removed_byte_count buf f.byte_count;
    let oxm_buf = Cstruct.shift buf sizeof_ofp_flow_removed in
    sizeof_ofp_flow_removed + (OfpMatch.marshal oxm_buf f.oxm)

  let parse (bits : Cstruct_sexp.t) : flowRemoved =
    let cookie = get_ofp_flow_removed_cookie bits in
    let priority = get_ofp_flow_removed_priority bits in
    let reason = RemovedReason.parse (get_ofp_flow_removed_reason bits) in
    let table_id = get_ofp_flow_removed_table_id bits in
    let duration_sec = get_ofp_flow_removed_duration_sec bits in
    let duration_nsec = get_ofp_flow_removed_duration_nsec bits in
    let idle_timeout = match (get_ofp_flow_removed_idle_timeout bits) with
      | 0 -> Permanent
      | n -> ExpiresAfter n in
    let hard_timeout = match (get_ofp_flow_removed_hard_timeout bits) with
      | 0 -> Permanent
      | n -> ExpiresAfter n in
    let packet_count = get_ofp_flow_removed_packet_count bits in
    let byte_count = get_ofp_flow_removed_byte_count bits in
    let oxm,_ = OfpMatch.parse (Cstruct.shift bits sizeof_ofp_flow_removed) in
    { cookie; priority; reason; table_id; duration_sec; duration_nsec; idle_timeout;
      hard_timeout; packet_count; byte_count; oxm }


end

module FlowRequest = struct

  [%%cstruct
  type ofp_flow_stats_request = {
    table_id: uint8_t ;
    pad: uint8_t [@len 3];
    out_port: uint32_t ;
    out_group: uint32_t ;
    pad2: uint8_t [@len 4];
    cookie: uint64_t ;
    cookie_mask: uint64_t ;
  } [@@big_endian]]

  type t = flowRequest

  let sizeof (fr : flowRequest) : int =
    sizeof_ofp_flow_stats_request + (OfpMatch.sizeof fr.fr_match)

  let to_string (fr : flowRequest) : string =
    Format.sprintf "{ table_id = %u; out_port = %lu; out_group = %lu; cookie = %s; match = %s }"
      fr.fr_table_id
      fr.fr_out_port
      fr.fr_out_group
      (match fr.fr_cookie.m_mask with
       | None -> Int64.to_string fr.fr_cookie.m_value
       | Some m -> Format.sprintf "%Lu/%Lu" fr.fr_cookie.m_value m)
      (OfpMatch.to_string fr.fr_match)

  let marshal (buf : Cstruct_sexp.t) (fr : flowRequest) : int =
    set_ofp_flow_stats_request_table_id buf fr.fr_table_id;
    set_ofp_flow_stats_request_out_port buf fr.fr_out_port;
    set_ofp_flow_stats_request_out_group buf fr.fr_out_group;
    set_ofp_flow_stats_request_cookie buf fr.fr_cookie.m_value;
    set_ofp_flow_stats_request_cookie_mask buf (
      match fr.fr_cookie.m_mask with
      | None -> 0L
      | Some mask -> mask);
    sizeof_ofp_flow_stats_request + (OfpMatch.marshal
                                       (Cstruct.shift buf sizeof_ofp_flow_stats_request) fr.fr_match)


  let parse (bits : Cstruct_sexp.t) : flowRequest =
    let tableId = get_ofp_flow_stats_request_table_id bits in
    let out_port = get_ofp_flow_stats_request_out_port bits in
    let out_group = get_ofp_flow_stats_request_out_group bits in
    let cookie = get_ofp_flow_stats_request_cookie bits in
    let mask = get_ofp_flow_stats_request_cookie_mask bits in
    let fr_cookie = match mask with
      | 0L -> {m_value = cookie; m_mask = None}
      | n -> {m_value = cookie; m_mask = Some n} in
    let oxmMatch,_ = OfpMatch.parse (Cstruct.shift bits sizeof_ofp_flow_stats_request) in
    { fr_table_id = tableId
    ; fr_out_port = out_port
    ; fr_out_group = out_group
    ; fr_cookie = fr_cookie
    ; fr_match = oxmMatch}

end

module QueueRequest = struct

  type t = queueRequest

  let marshal (buf : Cstruct_sexp.t) (qr : t) : int =
    set_ofp_queue_stats_request_port_no buf qr.port_number;
    set_ofp_queue_stats_request_queue_id buf qr.queue_id;
    sizeof_ofp_queue_stats_request

  let parse (bits : Cstruct_sexp.t) : t =
    let portNumber = get_ofp_queue_stats_request_port_no bits in
    let queueId = get_ofp_queue_stats_request_queue_id bits in
    { port_number = portNumber
    ; queue_id = queueId}

  let sizeof _ =
    sizeof_ofp_queue_stats_request

  let to_string qr =
    Format.sprintf "{ port_no = %lu; queue_id = %lu }" qr.port_number qr.queue_id

end

module InstructionHdr = struct
  (* Same as Instruction, but only on ofp_instruction, without additional payload *)
  type t = instructionHdr

  let sizeof (ins : t) =
    match ins with
    | GotoTableHdr
    | ApplyActionsHdr
    | WriteActionsHdr
    | WriteMetadataHdr
    | ClearHdr
    | MeterHdr -> 4
    | ExperimenterHdr _ ->  8

  let to_string (ins : t) =
    match ins with
    | GotoTableHdr -> "Go to Table"
    | ApplyActionsHdr -> "Apply Actions"
    | WriteActionsHdr -> "Write Actions"
    | WriteMetadataHdr -> "WriteMeta"
    | ClearHdr -> "Clear"
    | MeterHdr -> "Meter"
    | ExperimenterHdr e -> Format.sprintf "Experimenter = %lu" e

  let marshal (buf : Cstruct_sexp.t) (ins : t) : int =
    match ins with
    | GotoTableHdr ->
      set_ofp_instruction_typ buf (ofp_instruction_type_to_int OFPIT_GOTO_TABLE);
      set_ofp_instruction_len buf 4;
      sizeof_ofp_instruction
    | ApplyActionsHdr ->
      set_ofp_instruction_typ buf (ofp_instruction_type_to_int OFPIT_APPLY_ACTIONS);
      set_ofp_instruction_len buf 4;
      sizeof_ofp_instruction
    | WriteActionsHdr ->
      set_ofp_instruction_typ buf (ofp_instruction_type_to_int OFPIT_WRITE_ACTIONS);
      set_ofp_instruction_len buf 4;
      sizeof_ofp_instruction
    | WriteMetadataHdr ->
      set_ofp_instruction_typ buf (ofp_instruction_type_to_int OFPIT_WRITE_METADATA);
      set_ofp_instruction_len buf 4;
      sizeof_ofp_instruction
    | ClearHdr ->
      set_ofp_instruction_typ buf (ofp_instruction_type_to_int OFPIT_CLEAR_ACTIONS);
      set_ofp_instruction_len buf 4;
      sizeof_ofp_instruction
    | MeterHdr ->
      set_ofp_instruction_typ buf (ofp_instruction_type_to_int OFPIT_METER);
      set_ofp_instruction_len buf 4;
      sizeof_ofp_instruction
    | ExperimenterHdr e ->
      set_ofp_instruction_typ buf (ofp_instruction_type_to_int OFPIT_EXPERIMENTER);
      set_ofp_instruction_len buf 8;
      set_ofp_instruction_experimenter_experimenter buf e;
      sizeof_ofp_instruction_experimenter

  let parse (bits : Cstruct_sexp.t) : t =
    let typ = int_to_ofp_instruction_type (get_ofp_instruction_typ bits) in
    match typ with
    | Some OFPIT_GOTO_TABLE -> GotoTableHdr
    | Some OFPIT_APPLY_ACTIONS -> ApplyActionsHdr
    | Some OFPIT_WRITE_ACTIONS -> WriteActionsHdr
    | Some OFPIT_WRITE_METADATA -> WriteMetadataHdr
    | Some OFPIT_CLEAR_ACTIONS -> ClearHdr
    | Some OFPIT_METER -> MeterHdr
    | Some OFPIT_EXPERIMENTER -> ExperimenterHdr (get_ofp_instruction_experimenter_experimenter bits)
    | None -> raise (Unparsable (sprintf "malfomed typ"))

  let length_func (buf : Cstruct_sexp.t) : int option =
    if Cstruct.length buf < sizeof_ofp_instruction then None
    else Some (get_ofp_instruction_len buf)

end

module ActionHdr = struct
  (* Same as Action, but only on ofp_action_header, without additional payload  *)
  type t = actionHdr

  let sizeof (act : t) =
    match act with
    | OutputHdr
    | GroupHdr
    | PopVlanHdr
    | PushVlanHdr
    | PopMplsHdr
    | PushMplsHdr
    | SetFieldHdr
    | CopyTtlOutHdr
    | CopyTtlInHdr
    | SetNwTtlHdr
    | DecNwTtlHdr
    | PushPbbHdr
    | PopPbbHdr
    | SetMplsTtlHdr
    | DecMplsTtlHdr
    | SetQueueHdr -> 4
    | ExperimenterAHdr _ -> 8

  let to_string (act : t) =
    match act with
    | OutputHdr -> "Output"
    | GroupHdr -> "Group"
    | PopVlanHdr -> "PopVlan"
    | PushVlanHdr -> "PushVlan"
    | PopMplsHdr -> "PopMpls"
    | PushMplsHdr -> "PushMpls"
    | SetFieldHdr -> "SetField"
    | CopyTtlOutHdr -> "CopyTTLOut"
    | CopyTtlInHdr -> "CopyTTLIn"
    | SetNwTtlHdr -> "SetNwTtl"
    | DecNwTtlHdr -> "DecMplsTtl"
    | PushPbbHdr -> "PushPBB"
    | PopPbbHdr -> "PopPBB"
    | SetMplsTtlHdr -> "SetMplsTtl"
    | DecMplsTtlHdr -> "DecMplsTtl"
    | SetQueueHdr -> "SetQueue"
    | ExperimenterAHdr e -> Format.sprintf "Experimenter = %lu" e

  let marshal (buf : Cstruct_sexp.t) (act : t) : int =
    set_ofp_action_header_pad buf 0;
    set_ofp_action_header_pad1 buf 0;
    set_ofp_action_header_pad2 buf 0;
    set_ofp_action_header_pad3 buf 0;
    match act with
    | OutputHdr ->
      set_ofp_action_header_typ buf (ofp_action_type_to_int OFPAT_OUTPUT);
      set_ofp_action_header_len buf 4;
      4 (* ofp_action_header without the padding *)
    | CopyTtlOutHdr ->
      set_ofp_action_header_typ buf (ofp_action_type_to_int OFPAT_COPY_TTL_OUT);
      set_ofp_action_header_len buf 4;
      4
    | CopyTtlInHdr ->
      set_ofp_action_header_typ buf (ofp_action_type_to_int OFPAT_COPY_TTL_IN);
      set_ofp_action_header_len buf 4;
      4
    | SetMplsTtlHdr ->
      set_ofp_action_header_typ buf (ofp_action_type_to_int OFPAT_SET_MPLS_TTL);
      set_ofp_action_header_len buf 4;
      4
    | DecMplsTtlHdr ->
      set_ofp_action_header_typ buf (ofp_action_type_to_int OFPAT_DEC_MPLS_TTL);
      set_ofp_action_header_len buf 4;
      4
    | PushVlanHdr ->
      set_ofp_action_header_typ buf (ofp_action_type_to_int OFPAT_PUSH_VLAN);
      set_ofp_action_header_len buf 4;
      4
    | PopVlanHdr ->
      set_ofp_action_header_typ buf (ofp_action_type_to_int OFPAT_POP_VLAN);
      set_ofp_action_header_len buf 4;
      4
    | PushMplsHdr ->
      set_ofp_action_header_typ buf (ofp_action_type_to_int OFPAT_PUSH_MPLS);
      set_ofp_action_header_len buf 4;
      4
    | PopMplsHdr ->
      set_ofp_action_header_typ buf (ofp_action_type_to_int OFPAT_POP_MPLS);
      set_ofp_action_header_len buf 4;
      4
    | SetQueueHdr ->
      set_ofp_action_header_typ buf (ofp_action_type_to_int OFPAT_SET_QUEUE);
      set_ofp_action_header_len buf 4;
      4
    | GroupHdr ->
      set_ofp_action_header_typ buf (ofp_action_type_to_int OFPAT_GROUP);
      set_ofp_action_header_len buf 4;
      4
    | SetNwTtlHdr ->
      set_ofp_action_header_typ buf (ofp_action_type_to_int OFPAT_SET_NW_TTL);
      set_ofp_action_header_len buf 4;
      4
    | DecNwTtlHdr ->
      set_ofp_action_header_typ buf (ofp_action_type_to_int OFPAT_DEC_NW_TTL);
      set_ofp_action_header_len buf 4;
      4
    | SetFieldHdr ->
      set_ofp_action_header_typ buf (ofp_action_type_to_int OFPAT_SET_FIELD);
      set_ofp_action_header_len buf 4;
      4
    | PushPbbHdr ->
      set_ofp_action_header_typ buf (ofp_action_type_to_int OFPAT_PUSH_PBB);
      set_ofp_action_header_len buf 4;
      4
    | PopPbbHdr ->
      set_ofp_action_header_typ buf (ofp_action_type_to_int OFPAT_POP_PBB);
      set_ofp_action_header_len buf 4;
      4
    | ExperimenterAHdr e ->
      set_ofp_action_header_typ buf (ofp_action_type_to_int OFPAT_EXPERIMENTER);
      set_ofp_action_header_len buf 8;
      set_ofp_action_experimenter_experimenter buf e;
      sizeof_ofp_action_experimenter

  let parse (bits : Cstruct_sexp.t) : t =
    match (int_to_ofp_action_type (get_ofp_action_header_typ bits)) with
    | Some OFPAT_OUTPUT -> OutputHdr
    | Some OFPAT_COPY_TTL_OUT -> CopyTtlOutHdr
    | Some OFPAT_COPY_TTL_IN -> CopyTtlInHdr
    | Some OFPAT_SET_MPLS_TTL -> SetMplsTtlHdr
    | Some OFPAT_DEC_MPLS_TTL -> DecMplsTtlHdr
    | Some OFPAT_PUSH_VLAN -> PushVlanHdr
    | Some OFPAT_POP_VLAN -> PopVlanHdr
    | Some OFPAT_PUSH_MPLS -> PushMplsHdr
    | Some OFPAT_POP_MPLS -> PopMplsHdr
    | Some OFPAT_SET_QUEUE -> SetQueueHdr
    | Some OFPAT_GROUP -> GroupHdr
    | Some OFPAT_SET_NW_TTL -> SetNwTtlHdr
    | Some OFPAT_DEC_NW_TTL -> DecNwTtlHdr
    | Some OFPAT_SET_FIELD -> SetFieldHdr
    | Some OFPAT_PUSH_PBB -> PushPbbHdr
    | Some OFPAT_POP_PBB -> PopPbbHdr
    | Some OFPAT_EXPERIMENTER -> ExperimenterAHdr (get_ofp_action_experimenter_experimenter bits)
    | None -> failwith "None type"

  let length_func (buf : Cstruct_sexp.t) : int option =
    if Cstruct.length buf < 4 (* ofp_action_header without padding *) then None
    else Some (get_ofp_action_header_len buf)

end

module TableFeatureProp = struct

  [%%cstruct
  type ofp_table_feature_prop_experimenter = {
    typ: uint16_t ;
    length: uint16_t ;
    experimenter: uint32_t ;
    exp_typ: uint32_t
  } [@@big_endian]]

  type t = tableFeatureProp

  let length_func (buf : Cstruct_sexp.t) : int option =
    if Cstruct.length buf < sizeof_ofp_table_feature_prop_header then None
    else Some (pad_to_64bits (get_ofp_table_feature_prop_header_length buf))

  let sizeof tfp : int =
    let size = sizeof_ofp_table_feature_prop_header + (match tfp with
        | TfpInstruction ins ->
          sum (List.map ~f:InstructionHdr.sizeof ins)
        | TfpInstructionMiss ins ->
          sum (List.map ~f:InstructionHdr.sizeof ins)
        | TfpNextTable t ->
          List.length t
        | TfpNextTableMiss t ->
          List.length t
        | TfpWriteAction act ->
          sum (List.map ~f:ActionHdr.sizeof act)
        | TfpWriteActionMiss act ->
          sum (List.map ~f:ActionHdr.sizeof act)
        | TfpApplyAction act ->
          sum (List.map ~f:ActionHdr.sizeof act)
        | TfpApplyActionMiss act ->
          sum (List.map ~f:ActionHdr.sizeof act)
        | TfpMatch ox ->
          sum (List.map ~f:Oxm.sizeof_header ox)
        | TfpWildcard ox ->
          sum (List.map ~f:Oxm.sizeof_header ox)
        | TfpWriteSetField ox->
          sum (List.map ~f:Oxm.sizeof_header ox)
        | TfpWriteSetFieldMiss ox ->
          sum (List.map ~f:Oxm.sizeof_header ox)
        | TfpApplySetField ox ->
          sum (List.map ~f:Oxm.sizeof_header ox)
        | TfpApplySetFieldMiss ox ->
          sum (List.map ~f:Oxm.sizeof_header ox)
        | TfpExperimenter (_,by) ->
          Cstruct.length by
        | TfpExperimenterMiss (_,by) ->
          Cstruct.length by
      ) in
    pad_to_64bits size

  let marshal (buf : Cstruct_sexp.t) (tfp : tableFeatureProp) =
    let buf_payload = Cstruct.shift buf sizeof_ofp_table_feature_prop_header in
    let size = sizeof_ofp_table_feature_prop_header +
               (match tfp with
                | TfpInstruction ins ->
                  set_ofp_table_feature_prop_header_typ buf (ofp_table_feature_prop_type_to_int OFPTFPT_INSTRUCTIONS);
                  marshal_fields buf_payload ins InstructionHdr.marshal
                | TfpInstructionMiss ins ->
                  set_ofp_table_feature_prop_header_typ buf (ofp_table_feature_prop_type_to_int OFPTFPT_INSTRUCTIONS_MISS);
                  marshal_fields buf_payload ins InstructionHdr.marshal
                | TfpNextTable t ->
                  set_ofp_table_feature_prop_header_typ buf (ofp_table_feature_prop_type_to_int OFPTFPT_NEXT_TABLES);
                  let marsh (buf : Cstruct_sexp.t) (id : uint8) : int =
                    set_uint8 buf 0 id;
                    1 in
                  marshal_fields buf_payload t marsh
                | TfpNextTableMiss t ->
                  set_ofp_table_feature_prop_header_typ buf (ofp_table_feature_prop_type_to_int OFPTFPT_NEXT_TABLES_MISS);
                  let marsh (buf : Cstruct_sexp.t) (id : uint8) : int =
                    set_uint8 buf 0 id;
                    1 in
                  marshal_fields buf_payload t marsh
                | TfpWriteAction act ->
                  set_ofp_table_feature_prop_header_typ buf (ofp_table_feature_prop_type_to_int OFPTFPT_WRITE_ACTIONS);
                  marshal_fields buf_payload act ActionHdr.marshal
                | TfpWriteActionMiss act ->
                  set_ofp_table_feature_prop_header_typ buf (ofp_table_feature_prop_type_to_int OFPTFPT_WRITE_ACTIONS_MISS);
                  marshal_fields buf_payload act ActionHdr.marshal
                | TfpApplyAction act ->
                  set_ofp_table_feature_prop_header_typ buf (ofp_table_feature_prop_type_to_int OFPTFPT_APPLY_ACTIONS);
                  marshal_fields buf_payload act ActionHdr.marshal
                | TfpApplyActionMiss act ->
                  set_ofp_table_feature_prop_header_typ buf (ofp_table_feature_prop_type_to_int OFPTFPT_APPLY_ACTIONS_MISS);
                  marshal_fields buf_payload act ActionHdr.marshal
                | TfpMatch ox ->
                  set_ofp_table_feature_prop_header_typ buf (ofp_table_feature_prop_type_to_int OFPTFPT_MATCH);
                  marshal_fields buf_payload ox Oxm.marshal_header
                | TfpWildcard ox ->
                  set_ofp_table_feature_prop_header_typ buf (ofp_table_feature_prop_type_to_int OFPTFPT_WILDCARDS);
                  marshal_fields buf_payload ox Oxm.marshal_header
                | TfpWriteSetField ox->
                  set_ofp_table_feature_prop_header_typ buf (ofp_table_feature_prop_type_to_int OFPTFPT_WRITE_SETFIELD);
                  marshal_fields buf_payload ox Oxm.marshal_header
                | TfpWriteSetFieldMiss ox ->
                  set_ofp_table_feature_prop_header_typ buf (ofp_table_feature_prop_type_to_int OFPTFPT_WRITE_SETFIELD_MISS);
                  marshal_fields buf_payload ox Oxm.marshal_header
                | TfpApplySetField ox ->
                  set_ofp_table_feature_prop_header_typ buf (ofp_table_feature_prop_type_to_int OFPTFPT_APPLY_SETFIELD);
                  marshal_fields buf_payload ox Oxm.marshal_header
                | TfpApplySetFieldMiss ox ->
                  set_ofp_table_feature_prop_header_typ buf (ofp_table_feature_prop_type_to_int OFPTFPT_APPLY_SETFIELD_MISS);
                  marshal_fields buf_payload ox Oxm.marshal_header
                | TfpExperimenter (ex,by) ->
                  set_ofp_table_feature_prop_header_typ buf (ofp_table_feature_prop_type_to_int OFPTFPT_EXPERIMENTER);
                  Cstruct.blit by 0 buf_payload 0 (Cstruct.length by);
                  Cstruct.length by
                | TfpExperimenterMiss (ex,by) ->
                  set_ofp_table_feature_prop_header_typ buf (ofp_table_feature_prop_type_to_int OFPTFPT_EXPERIMENTER_MISS);
                  Cstruct.blit by 0 buf_payload 0 (Cstruct.length by);
                  Cstruct.length by) in
    set_ofp_table_feature_prop_header_length buf size;
    pad_to_64bits size

  let rec parse_tables (bits : Cstruct_sexp.t) len =
    if Cstruct.length bits < 1 then ([], bits)
    else let field, bits2 = get_uint8 bits 0, Cstruct.shift bits 1 in
      let fields, bits3 = parse_tables bits2 (len -1) in
      (List.append [field] fields, bits3)

  let parse (bits : Cstruct_sexp.t) : tableFeatureProp =
    let tfpType = get_ofp_table_feature_prop_header_typ bits in
    let tfpLength = get_ofp_table_feature_prop_header_length bits in
    let tfpPayBits = Cstruct.sub bits sizeof_ofp_table_feature_prop_header (tfpLength - sizeof_ofp_table_feature_prop_header) in
    match int_to_ofp_table_feature_prop_type tfpType with
    | Some OFPTFPT_INSTRUCTIONS ->
      TfpInstruction (parse_fields tfpPayBits InstructionHdr.parse InstructionHdr.length_func)
    | Some OFPTFPT_INSTRUCTIONS_MISS ->
      TfpInstructionMiss (parse_fields tfpPayBits InstructionHdr.parse InstructionHdr.length_func)
    | Some OFPTFPT_NEXT_TABLES ->
      let ids,_ = parse_tables tfpPayBits (tfpLength - sizeof_ofp_table_feature_prop_header) in
      TfpNextTable ids
    | Some OFPTFPT_NEXT_TABLES_MISS ->
      let ids,_ = parse_tables tfpPayBits (tfpLength - sizeof_ofp_table_feature_prop_header) in
      TfpNextTableMiss ids
    | Some OFPTFPT_WRITE_ACTIONS ->
      TfpWriteAction (parse_fields tfpPayBits ActionHdr.parse ActionHdr.length_func)
    | Some OFPTFPT_WRITE_ACTIONS_MISS ->
      TfpWriteActionMiss (parse_fields tfpPayBits ActionHdr.parse ActionHdr.length_func)
    | Some OFPTFPT_APPLY_ACTIONS ->
      TfpApplyAction (parse_fields tfpPayBits ActionHdr.parse ActionHdr.length_func)
    | Some OFPTFPT_APPLY_ACTIONS_MISS ->
      TfpApplyActionMiss (parse_fields tfpPayBits ActionHdr.parse ActionHdr.length_func)
    | Some OFPTFPT_MATCH ->
      let fields,_ = Oxm.parse_headers tfpPayBits in
      TfpMatch fields
    | Some OFPTFPT_WILDCARDS ->
      let fields,_ = Oxm.parse_headers tfpPayBits in
      TfpWildcard fields
    | Some OFPTFPT_WRITE_SETFIELD ->
      let fields,_ = Oxm.parse_headers tfpPayBits in
      TfpWriteSetField fields
    | Some OFPTFPT_WRITE_SETFIELD_MISS ->
      let fields,_ = Oxm.parse_headers tfpPayBits in
      TfpWriteSetFieldMiss fields
    | Some OFPTFPT_APPLY_SETFIELD ->
      let fields,_ = Oxm.parse_headers tfpPayBits in
      TfpApplySetField fields
    | Some OFPTFPT_APPLY_SETFIELD_MISS ->
      let fields,_ = Oxm.parse_headers tfpPayBits in
      TfpApplySetFieldMiss fields
    | Some OFPTFPT_EXPERIMENTER ->
      let exp_id = get_ofp_table_feature_prop_experimenter_experimenter bits in
      let exp_type = get_ofp_table_feature_prop_experimenter_exp_typ bits in
      TfpExperimenter ({exp_id;exp_type},tfpPayBits)
    | Some OFPTFPT_EXPERIMENTER_MISS ->
      let exp_id = get_ofp_table_feature_prop_experimenter_experimenter bits in
      let exp_type = get_ofp_table_feature_prop_experimenter_exp_typ bits in
      TfpExperimenterMiss ({exp_id;exp_type},tfpPayBits)
    | _ -> raise (Unparsable (sprintf "malformed type"))

  let to_string tfp =
    Format.sprintf "{ type = %s; len:%u }"
      (match tfp with
       | TfpInstruction i->
         (Format.sprintf "Instructions [ %s ]" (String.concat ~sep:"; " (List.map ~f:InstructionHdr.to_string i)))
       | TfpInstructionMiss i->
         (Format.sprintf "InstructionMiss [ %s ]" (String.concat ~sep:"; " (List.map ~f:InstructionHdr.to_string i)))
       | TfpNextTable n->
         (Format.sprintf "NextTable [ %s ]"
            (String.concat ~sep:"; " (List.map ~f:string_of_int n)))
       | TfpNextTableMiss n ->
         (Format.sprintf "NextTableMiss [ %s ]"
            (String.concat ~sep:"; " (List.map ~f:string_of_int n)))
       | TfpWriteAction a ->
         (Format.sprintf "WriteAction [ %s ]"
            (String.concat ~sep:"; " (List.map ~f:ActionHdr.to_string a)))
       | TfpWriteActionMiss a ->
         (Format.sprintf "WriteActionMiss [ %s ]"
            (String.concat ~sep:"; " (List.map ~f:ActionHdr.to_string a)))
       | TfpApplyAction a ->
         (Format.sprintf "ApplyActions [ %s ]"
            (String.concat ~sep:"; " (List.map ~f:ActionHdr.to_string a)))
       | TfpApplyActionMiss a ->
         (Format.sprintf "ApplyActionsMiss [ %s ]"
            (String.concat ~sep:"; " (List.map ~f:ActionHdr.to_string a)))
       | TfpMatch s ->
         (Format.sprintf "Match [ %s ]"
            (String.concat ~sep:"; " (List.map ~f:Oxm.field_name s)))
       | TfpWildcard s ->
         (Format.sprintf "MatchMiss [ %s ]"
            (String.concat ~sep:"; " (List.map ~f:Oxm.field_name s)))
       | TfpWriteSetField s ->
         (Format.sprintf "WriteSetField [ %s ]"
            (String.concat ~sep:"; " (List.map ~f:Oxm.field_name s)))
       | TfpWriteSetFieldMiss s ->
         (Format.sprintf "WriteSetFieldMiss [ %s ]"
            (String.concat ~sep:"; " (List.map ~f:Oxm.field_name s)))
       | TfpApplySetField s ->
         (Format.sprintf "ApplySetField [ %s ]"
            (String.concat ~sep:"; " (List.map ~f:Oxm.field_name s)))
       | TfpApplySetFieldMiss s ->
         (Format.sprintf "ApplySetFieldMiss [ %s ]"
            (String.concat ~sep:"; " (List.map ~f:Oxm.field_name s)))
       | TfpExperimenter (e,_)->
         (Format.sprintf "Experimenter<id=%lu>; typ = %lu" e.exp_id e.exp_type)
       | TfpExperimenterMiss (e,_)->
         (Format.sprintf "ExperimenterMiss<id=%lu>; typ = %lu" e.exp_id e.exp_type)
      )
      (sizeof tfp)

end

module TableConfig = struct

  [%%cenum
  type ofp_table_config =
    | OFPTC_DEPRECATED_MASK [@id 3]
    [@@uint32_t]
  ]

  type t = tableConfig
  let marshal (tc : tableConfig) : int32 =
    match tc with
    | Deprecated -> ofp_table_config_to_int OFPTC_DEPRECATED_MASK

  let parse t : tableConfig =
    match int_to_ofp_table_config t with
    | Some OFPTC_DEPRECATED_MASK -> Deprecated
    | _ -> raise (Unparsable (sprintf "unsupported config "))

  let to_string tc =
    match tc with
    | Deprecated -> "Deprecated"

end

module TableFeature = struct

  type t = tableFeatures

  let sizeof (tf : t) =
    (* should be equal to tf.length *)
    pad_to_64bits (sizeof_ofp_table_features + sum (List.map ~f:TableFeatureProp.sizeof tf.feature_prop))

  let marshal (buf : Cstruct_sexp.t) (tf : t) : int =
    set_ofp_table_features_length buf tf.length;
    set_ofp_table_features_table_id buf tf.table_id;
    set_ofp_table_features_pad (String.make 5 '\000') 0 buf;
    set_ofp_table_features_name tf.name 0 buf;
    set_ofp_table_features_metadata_match buf tf.metadata_match;
    set_ofp_table_features_metadata_write buf tf.metadata_write;
    set_ofp_table_features_config buf (TableConfig.marshal tf.config);
    set_ofp_table_features_max_entries buf tf.max_entries;
    sizeof_ofp_table_features + (
      marshal_fields (Cstruct.shift buf sizeof_ofp_table_features) tf.feature_prop TableFeatureProp.marshal)

  let parse (bits : Cstruct_sexp.t) : t =
    let length = get_ofp_table_features_length bits in
    let tableId = get_ofp_table_features_table_id bits in
    let name = Cstruct.to_string (get_ofp_table_features_name bits) in
    let metadataMatch = get_ofp_table_features_metadata_match bits in
    let metadataWrite = get_ofp_table_features_metadata_write bits in
    let config = TableConfig.parse (get_ofp_table_features_config bits) in
    let maxEntries = get_ofp_table_features_max_entries bits in
    let featureProp = parse_fields (Cstruct.sub bits sizeof_ofp_table_features (length-sizeof_ofp_table_features)) TableFeatureProp.parse TableFeatureProp.length_func in
    { length = length;
      table_id = tableId;
      name = name;
      metadata_match = metadataMatch;
      metadata_write = metadataWrite;
      config = config;
      max_entries = maxEntries;
      feature_prop = featureProp}

  let to_string (tf : t) =
    Format.sprintf "{ table_id = %u; name = %s; metadata_match = %Lu; \
                    metadata_write = %Lu; config = %s; max_entries = %lu;
                      feature_prop = %s }"
      tf.table_id
      tf.name
      tf.metadata_match
      tf.metadata_write
      (TableConfig.to_string tf.config)
      tf.max_entries
      ("[ " ^ (String.concat ~sep:"; " (List.map ~f:TableFeatureProp.to_string tf.feature_prop)) ^ " ]")

  let length_func (buf : Cstruct_sexp.t) : int option =
    if Cstruct.length buf < sizeof_ofp_table_features then None
    else Some (get_ofp_table_features_length buf)
end

module MultipartReq = struct

  [%%cstruct
  type ofp_multipart_request = {
    typ: uint16_t ; (* One of the OFPMP_* constants. *)
    flags: uint16_t ; (* OFPMPF_REQ_* flags. *)
    pad0: uint8_t ;
    pad1: uint8_t ;
    pad2: uint8_t ;
    pad3: uint8_t
  } [@@big_endian]]

  [%%cstruct
  type ofp_experimenter_multipart_header = {
    experimenter: uint32_t ;
    exp_type: uint32_t
  } [@@big_endian]]

  type t = multipartRequest

  let msg_code_of_request mpr = match mpr with
    | SwitchDescReq -> OFPMP_DESC
    | PortsDescReq -> OFPMP_PORT_DESC
    | FlowStatsReq _ -> OFPMP_FLOW
    | AggregFlowStatsReq _ -> OFPMP_AGGREGATE
    | TableStatsReq -> OFPMP_TABLE
    | PortStatsReq _ -> OFPMP_PORT_STATS
    | QueueStatsReq _ -> OFPMP_QUEUE
    | GroupStatsReq _ -> OFPMP_GROUP
    | GroupDescReq -> OFPMP_GROUP_DESC
    | GroupFeatReq -> OFPMP_GROUP_FEATURES
    | MeterStatsReq _ -> OFPMP_METER
    | MeterConfReq _ -> OFPMP_METER_CONFIG
    | MeterFeatReq -> OFPMP_METER_FEATURES
    | TableFeatReq _ -> OFPMP_TABLE_FEATURES
    | ExperimentReq _ -> OFPMP_EXPERIMENTER

  let sizeof (mpr : multipartRequest) =
    sizeof_ofp_multipart_request +
    (match mpr.mpr_type with
     | SwitchDescReq | PortsDescReq | TableStatsReq | MeterFeatReq | GroupDescReq
     | GroupFeatReq -> 0
     | FlowStatsReq fr -> FlowRequest.sizeof fr
     | AggregFlowStatsReq fr -> FlowRequest.sizeof fr
     | PortStatsReq _ -> sizeof_ofp_port_stats_request
     | QueueStatsReq _ -> sizeof_ofp_queue_stats_request
     | GroupStatsReq _ -> sizeof_ofp_group_stats_request
     | MeterStatsReq _  | MeterConfReq _ -> sizeof_ofp_meter_multipart_request
     | TableFeatReq tfr -> (match tfr with
         | None -> 0
         | Some t -> sum (List.map ~f:TableFeature.sizeof t))
     | ExperimentReq _ -> sizeof_ofp_experimenter_multipart_header)

  let to_string (mpr : multipartRequest) : string =
    Format.sprintf "{ more = %B; typ = %s }"
      mpr.mpr_flags
      (match mpr.mpr_type with
       | SwitchDescReq -> "SwitchDesc Req"
       | PortsDescReq -> "PortDesc Req"
       | FlowStatsReq f ->
         Format.sprintf "FlowStats Req %s" (FlowRequest.to_string f)
       | AggregFlowStatsReq f ->
         Format.sprintf "AggregFlowStats %s Req" (FlowRequest.to_string f)
       | TableStatsReq -> "TableStats Req"
       | PortStatsReq p ->
         Format.sprintf "PortStats Req %lu" p
       | QueueStatsReq q ->
         Format.sprintf "QueueStats Req %s" (QueueRequest.to_string q)
       | GroupStatsReq g -> Format.sprintf "GroupStats Req %lu" g
       | GroupDescReq -> "GroupDesc Req"
       | GroupFeatReq -> "GroupFeat Req"
       | MeterStatsReq m -> Format.sprintf "MeterStats Req %lu " m
       | MeterConfReq m -> Format.sprintf "MeterConf Req %lu" m
       | MeterFeatReq -> "MeterFeat Req"
       | TableFeatReq t-> Format.sprintf "TableFeat Req %s" (match t with
           | Some v -> "[ " ^ (String.concat ~sep:"; " (List.map ~f:TableFeature.to_string v)) ^ " ]"
           | None -> "None" )
       | ExperimentReq e-> Format.sprintf "Experimenter Req: id: %lu; type: %lu" e.exp_id e.exp_type)

  let marshal (buf : Cstruct_sexp.t) (mpr : multipartRequest) : int =
    let size = sizeof_ofp_multipart_request in
    set_ofp_multipart_request_typ buf (ofp_multipart_types_to_int (msg_code_of_request mpr.mpr_type));
    set_ofp_multipart_request_flags buf (
      match mpr.mpr_flags with
      | true -> ofp_multipart_request_flags_to_int OFPMPF_REQ_MORE
      | false -> 0);
    set_ofp_multipart_request_pad0 buf 0;
    set_ofp_multipart_request_pad1 buf 0;
    set_ofp_multipart_request_pad2 buf 0;
    set_ofp_multipart_request_pad3 buf 0;
    let pay_buf = Cstruct.shift buf sizeof_ofp_multipart_request in
    match mpr.mpr_type with
    | SwitchDescReq
    | PortsDescReq -> size
    | FlowStatsReq f -> size + (FlowRequest.marshal pay_buf f)
    | AggregFlowStatsReq f -> size + (FlowRequest.marshal pay_buf f)
    | TableStatsReq -> size
    | PortStatsReq p ->
      set_ofp_port_stats_request_port_no pay_buf p;
      set_ofp_port_stats_request_pad (String.make 4 '\000') 0 pay_buf;
      size + sizeof_ofp_port_stats_request
    | QueueStatsReq q -> size + (QueueRequest.marshal pay_buf q)
    | GroupStatsReq g ->
      set_ofp_group_stats_request_group_id pay_buf g;
      set_ofp_group_stats_request_pad (String.make 4 '\000') 0 pay_buf;
      size + sizeof_ofp_port_stats_request
    | GroupDescReq
    | GroupFeatReq -> size
    | MeterStatsReq m ->
      set_ofp_meter_multipart_request_meter_id pay_buf m;
      set_ofp_meter_multipart_request_pad (String.make 4 '\000') 0 pay_buf;
      size + sizeof_ofp_meter_multipart_request
    | MeterConfReq m ->
      set_ofp_meter_multipart_request_meter_id pay_buf m;
      set_ofp_meter_multipart_request_pad (String.make 4 '\000') 0 pay_buf;
      size + sizeof_ofp_meter_multipart_request
    | MeterFeatReq -> size
    | TableFeatReq t ->
      (match t with
       | None -> 0
       | Some v -> size + marshal_fields pay_buf v TableFeature.marshal)
    | ExperimentReq _ -> size

  let parse (bits : Cstruct_sexp.t) : multipartRequest =
    let mprType = int_to_ofp_multipart_types (get_ofp_multipart_request_typ bits) in
    let mpr_flags = (
      match int_to_ofp_multipart_request_flags (get_ofp_multipart_request_flags bits) with
      | Some OFPMPF_REQ_MORE -> true
      | _ -> false) in
    let mpr_type = match mprType with
      | Some OFPMP_DESC -> SwitchDescReq
      | Some OFPMP_PORT_DESC -> PortsDescReq
      | Some OFPMP_FLOW -> FlowStatsReq (
          FlowRequest.parse (Cstruct.shift bits sizeof_ofp_multipart_request))
      | Some OFPMP_AGGREGATE -> AggregFlowStatsReq (
          FlowRequest.parse (Cstruct.shift bits sizeof_ofp_multipart_request))
      | Some OFPMP_TABLE -> TableStatsReq
      | Some OFPMP_PORT_STATS -> PortStatsReq (
          get_ofp_port_stats_request_port_no (Cstruct.shift bits sizeof_ofp_multipart_request))
      | Some OFPMP_QUEUE -> QueueStatsReq (
          QueueRequest.parse (Cstruct.shift bits sizeof_ofp_multipart_request))
      | Some OFPMP_GROUP -> GroupStatsReq (
          get_ofp_group_stats_request_group_id (Cstruct.shift bits sizeof_ofp_multipart_request))
      | Some OFPMP_GROUP_DESC -> GroupDescReq
      | Some OFPMP_GROUP_FEATURES -> GroupFeatReq
      | Some OFPMP_METER -> MeterStatsReq (
          get_ofp_meter_multipart_request_meter_id (Cstruct.shift bits sizeof_ofp_multipart_request))
      | Some OFPMP_METER_CONFIG -> MeterConfReq (
          get_ofp_meter_multipart_request_meter_id (Cstruct.shift bits sizeof_ofp_multipart_request))
      | Some OFPMP_METER_FEATURES -> MeterFeatReq
      | Some OFPMP_TABLE_FEATURES -> TableFeatReq (
          if Cstruct.length bits <= sizeof_ofp_multipart_request then None
          else Some (
              parse_fields (Cstruct.shift bits sizeof_ofp_multipart_request) TableFeature.parse TableFeature.length_func
            ))
      | Some OFPMP_EXPERIMENTER -> ExperimentReq (
          let exp_bits = Cstruct.shift bits sizeof_ofp_multipart_request in
          let exp_id = get_ofp_experimenter_multipart_header_experimenter exp_bits in
          let exp_type = get_ofp_experimenter_multipart_header_exp_type exp_bits in
          {exp_id; exp_type})
      | _ -> raise (Unparsable (sprintf "bad ofp_multipart_types number"))
    in {mpr_type; mpr_flags}


end

module SwitchDescriptionReply = struct

  type t = switchDesc

  let sizeof (sdr : switchDesc) : int =
    sizeof_ofp_desc

  let to_string (sdr : switchDesc) : string =
    Format.sprintf "{ mfr_desc = %s; hw_desc = %s; sw_desc = %s; serial_num = %s; dp_desc = %s  }"
      sdr.mfr_desc
      sdr.hw_desc
      sdr.sw_desc
      sdr.serial_num
      sdr.dp_desc

  let marshal (buf : Cstruct_sexp.t) (sdr : switchDesc) : int =
    set_ofp_desc_mfr_desc sdr.mfr_desc 0 buf;
    set_ofp_desc_hw_desc sdr.hw_desc 0 buf;
    set_ofp_desc_sw_desc sdr.sw_desc 0 buf;
    set_ofp_desc_serial_num sdr.serial_num 0 buf;
    set_ofp_desc_dp_desc sdr.dp_desc 0 buf;
    sizeof_ofp_desc

  let parse (bits : Cstruct_sexp.t) : switchDesc =
    let mfr_desc = copy_ofp_desc_mfr_desc bits in
    let hw_desc = copy_ofp_desc_hw_desc bits in
    let sw_desc = copy_ofp_desc_sw_desc bits in
    let serial_num = copy_ofp_desc_serial_num bits in
    let dp_desc = copy_ofp_desc_dp_desc bits in
     { mfr_desc;
       hw_desc;
       sw_desc;
       serial_num;
       dp_desc}

end

module FlowStats = struct

  [%%cstruct
  type ofp_flow_stats = {
    length: uint16_t ;
    table_id: uint8_t ;
    pad0: uint8_t ;
    duration_sec: uint32_t ;
    duration_nsec: uint32_t ;
    priority: uint16_t ;
    idle_timeout: uint16_t ;
    hard_timeout: uint16_t ;
    flags: uint16_t ;
    pad1: uint8_t [@len 4];
    cookie: uint64_t ;
    packet_count: uint64_t ;
    byte_count: uint64_t ;
  } [@@big_endian]]

  type t = flowStats

  let sizeof (fs : flowStats) =
    sizeof_ofp_flow_stats +
    (OfpMatch.sizeof fs.ofp_match)+
    (Instructions.sizeof fs.instructions)

  let to_string f =
    Format.sprintf "{ length = %u; tableId = %u; duration = %lus/%luns; priority = %u; \
                    idle_timeout = %s; hard_timeout = %s; flags = %s; cookie = %Lu; pkt_count = %Lu; \
                    byte_count = %Lu; match = %s; instructions = %s }"
      (sizeof f)
      f.table_id
      f.duration_sec
      f.duration_nsec
      f.priority
      (match f.idle_timeout with
       | Permanent -> "Permanent"
       | ExpiresAfter v -> string_of_int v)
      (match f.hard_timeout with
       | Permanent -> "Permanent"
       | ExpiresAfter v -> string_of_int v)
      (FlowMod.Flags.to_string f.flags)
      f.cookie
      f.packet_count
      f.byte_count
      (OfpMatch.to_string f.ofp_match)
      (Instructions.to_string f.instructions)

  let marshal (buf : Cstruct_sexp.t) (fs : flowStats) : int =
    set_ofp_flow_stats_length buf (sizeof fs);
    set_ofp_flow_stats_table_id buf fs.table_id;
    set_ofp_flow_stats_pad0 buf 0;
    set_ofp_flow_stats_duration_sec buf fs.duration_sec;
    set_ofp_flow_stats_duration_nsec buf fs.duration_nsec;
    set_ofp_flow_stats_priority buf fs.priority;
    set_ofp_flow_stats_idle_timeout buf
      (match fs.idle_timeout with
       | Permanent -> 0
       | ExpiresAfter  v -> v);
    set_ofp_flow_stats_hard_timeout buf
      (match fs.hard_timeout with
       | Permanent -> 0
       | ExpiresAfter  v -> v);
    set_ofp_flow_stats_flags buf (FlowMod.Flags.marshal fs.flags);
    set_ofp_flow_stats_pad1 (String.make 4 '\000') 0 buf;
    set_ofp_flow_stats_cookie buf fs.cookie;
    set_ofp_flow_stats_packet_count buf fs.packet_count;
    set_ofp_flow_stats_byte_count buf fs.byte_count;
    let size = sizeof_ofp_flow_stats +
               OfpMatch.marshal (Cstruct.shift buf sizeof_ofp_flow_stats) fs.ofp_match in
    size + Instructions.marshal (Cstruct.shift buf size) fs.instructions

  let parse (bits : Cstruct_sexp.t) : flowStats =
    let table_id = get_ofp_flow_stats_table_id bits in
    let duration_sec = get_ofp_flow_stats_duration_sec bits in
    let duration_nsec = get_ofp_flow_stats_duration_nsec bits in
    let priority = get_ofp_flow_stats_priority bits in
    let idle_timeout = match (get_ofp_flow_stats_idle_timeout bits) with
      | 0 -> Permanent
      | n -> ExpiresAfter n in
    let hard_timeout = match (get_ofp_flow_stats_hard_timeout bits) with
      | 0 -> Permanent
      | n -> ExpiresAfter n in
    let flagsBits = get_ofp_flow_stats_flags bits in
    let flags = FlowMod.Flags.parse flagsBits in
    let cookie = get_ofp_flow_stats_cookie bits in
    let packet_count = get_ofp_flow_stats_packet_count bits in
    let byte_count = get_ofp_flow_stats_byte_count bits in
    let ofp_match_bits = Cstruct.shift bits sizeof_ofp_flow_stats in
    let ofp_match, instruction_bits = OfpMatch.parse ofp_match_bits in
    let instructions = Instructions.parse instruction_bits in
    { table_id
    ; duration_sec
    ; duration_nsec
    ; priority
    ; idle_timeout
    ; hard_timeout
    ; flags
    ; cookie
    ; packet_count
    ; byte_count
    ; ofp_match
    ; instructions}

  let length_func (buf :  Cstruct_sexp.t) : int option =
    if Cstruct.length buf < sizeof_ofp_flow_stats then None
    else Some (get_ofp_flow_stats_length buf)

end

module AggregateStats = struct

  [%%cstruct
  type ofp_aggregate_stats_reply = {
    packet_count: uint64_t ;
    byte_count: uint64_t ;
    flow_count: uint32_t ;
    pad: uint8_t  [@len 4];
  } [@@big_endian]]

  type t = aggregStats

  let sizeof ag =
    sizeof_ofp_aggregate_stats_reply

  let to_string (ag : aggregStats) =
    Format.sprintf "{ packet_count = %Lu; byte = %Lu; flow_count = %lu }"
      ag.packet_count
      ag.byte_count
      ag.flow_count

  let marshal (buf : Cstruct_sexp.t) (ag : aggregStats) : int =
    set_ofp_aggregate_stats_reply_packet_count buf ag.packet_count;
    set_ofp_aggregate_stats_reply_byte_count buf ag.byte_count;
    set_ofp_aggregate_stats_reply_flow_count buf ag.flow_count;
    set_ofp_aggregate_stats_reply_pad (String.make 3 '\000') 0 buf;
    sizeof_ofp_aggregate_stats_reply

  let parse (bits : Cstruct_sexp.t) : aggregStats =
    { packet_count = (get_ofp_aggregate_stats_reply_packet_count bits)
    ; byte_count = (get_ofp_aggregate_stats_reply_byte_count bits)
    ; flow_count = (get_ofp_aggregate_stats_reply_flow_count bits)}

end

module TableStats = struct
  [%%cstruct
  type ofp_table_stats = {
    table_id: uint8_t ;
    pad: uint8_t  [@len 3];
    active_count: uint32_t ;
    lookup_count: uint64_t ;
    matched_count: uint64_t ;
  } [@@big_endian]]

  type t = tableStats

  let sizeof (ts : tableStats) =
    sizeof_ofp_table_stats


  let to_string (ts : tableStats) =
    Format.sprintf "{ table_id = %u; active_count = %lu; lookup_count = %Lu; matched_count = %Lu }"
      ts.table_id
      ts.active_count
      ts.lookup_count
      ts.matched_count

  let marshal (buf : Cstruct_sexp.t) (ts : tableStats) : int =
    set_ofp_table_stats_table_id buf ts.table_id;
    set_ofp_table_stats_pad (String.make 3 '\000') 0 buf;
    set_ofp_table_stats_active_count buf ts.active_count;
    set_ofp_table_stats_lookup_count buf ts.lookup_count;
    set_ofp_table_stats_matched_count buf ts.matched_count;
    sizeof_ofp_table_stats

  let parse (bits : Cstruct_sexp.t) : tableStats =
    { table_id = get_ofp_table_stats_table_id bits
    ; active_count = get_ofp_table_stats_active_count bits
    ; lookup_count = get_ofp_table_stats_lookup_count bits
    ; matched_count = get_ofp_table_stats_matched_count bits}

  let length_func = (fun buf -> Some sizeof_ofp_table_stats)

end

module PortStats = struct

  type t = portStats

  let sizeof (ps : portStats) =
    sizeof_ofp_port_stats

  let to_string ps =
    Format.sprintf "{ port_no = %lu; rx/tx pkt = %Lu/%Lu; rx/tx byt = %Lu/%Lu; \
                    rx/tx dropped = %Lu/%Lu; rx/tx error = %Lu/%Lu; rx frame \
                    erro = %Lu; rx_over_err = %Lu; rx_crc_err = %Lu; \
                    collisisions = %Lu; duration (s/ns) = %lu/%lu }"
      ps.psPort_no
      ps.rx_packets
      ps.tx_packets
      ps.rx_bytes
      ps.tx_bytes
      ps.rx_dropped
      ps.tx_dropped
      ps.rx_errors
      ps.tx_errors
      ps.rx_frame_err
      ps.rx_over_err
      ps.rx_crc_err
      ps.collisions
      ps.duration_sec
      ps.duration_nsec

  let marshal (buf : Cstruct_sexp.t) (ps : portStats) : int =
    set_ofp_port_stats_port_no buf ps.psPort_no;
    set_ofp_port_stats_pad (String.make 4 '\000') 0 buf;
    set_ofp_port_stats_rx_packets buf ps.rx_packets;
    set_ofp_port_stats_tx_packets buf ps.tx_packets;
    set_ofp_port_stats_rx_bytes buf ps.rx_bytes;
    set_ofp_port_stats_tx_bytes buf ps.tx_bytes;
    set_ofp_port_stats_rx_dropped buf ps.rx_dropped;
    set_ofp_port_stats_tx_dropped buf ps.tx_dropped;
    set_ofp_port_stats_rx_errors buf ps.rx_errors;
    set_ofp_port_stats_tx_errors buf ps.tx_errors;
    set_ofp_port_stats_rx_frame_err buf ps.rx_frame_err;
    set_ofp_port_stats_rx_over_err buf ps.rx_over_err;
    set_ofp_port_stats_rx_crc_err buf ps.rx_crc_err;
    set_ofp_port_stats_collisions buf ps.collisions;
    set_ofp_port_stats_duration_sec buf ps.duration_sec;
    set_ofp_port_stats_duration_nsec buf ps.duration_nsec;
    sizeof_ofp_port_stats

  let parse (bits : Cstruct_sexp.t) : portStats =
    { psPort_no     = get_ofp_port_stats_port_no bits;
      rx_packets    = get_ofp_port_stats_rx_packets bits;
      tx_packets    = get_ofp_port_stats_tx_packets bits;
      rx_bytes      = get_ofp_port_stats_rx_bytes bits;
      tx_bytes      = get_ofp_port_stats_tx_bytes bits;
      rx_dropped    = get_ofp_port_stats_rx_dropped bits;
      tx_dropped    = get_ofp_port_stats_tx_dropped bits;
      rx_errors     = get_ofp_port_stats_rx_errors bits;
      tx_errors     = get_ofp_port_stats_tx_errors bits;
      rx_frame_err  = get_ofp_port_stats_rx_frame_err bits;
      rx_over_err   = get_ofp_port_stats_rx_over_err bits;
      rx_crc_err    = get_ofp_port_stats_rx_crc_err bits;
      collisions    = get_ofp_port_stats_collisions bits;
      duration_sec  = get_ofp_port_stats_duration_sec bits;
      duration_nsec = get_ofp_port_stats_duration_nsec bits
    }

  let length_func = (fun buf -> Some sizeof_ofp_port_stats)

end

module QueueStats = struct

  [%%cstruct
  type ofp_queue_stats = {
    port_no: uint32_t ;
    queue_id: uint32_t ;
    tx_bytes: uint64_t ;
    tx_packets: uint64_t ;
    tx_errors: uint64_t ;
    duration_sec: uint32_t ;
    duration_nsec: uint32_t
  } [@@big_endian]]

  type t = queueStats

  let sizeof (qs : queueStats) : int =
    sizeof_ofp_queue_stats

  let to_string (qs : queueStats) : string =
    Format.sprintf "{ port no = %lu; queue_id = %lu; tx bytes = %Lu; tx pkt = %Lu; tx errors = %Lu; duration (s/ns) = %lu/%lu }"
      qs.qsPort_no
      qs.queue_id
      qs.tx_bytes
      qs.tx_packets
      qs.tx_errors
      qs.duration_sec
      qs.duration_nsec

  let marshal (buf : Cstruct_sexp.t) (qs : queueStats) : int =
    set_ofp_queue_stats_port_no buf qs.qsPort_no;
    set_ofp_queue_stats_queue_id buf qs.queue_id;
    set_ofp_queue_stats_tx_bytes buf qs.tx_bytes;
    set_ofp_queue_stats_tx_packets buf qs.tx_packets;
    set_ofp_queue_stats_tx_errors buf qs.tx_errors;
    set_ofp_queue_stats_duration_sec buf qs.duration_sec;
    set_ofp_queue_stats_duration_nsec buf qs.duration_nsec;
    sizeof_ofp_queue_stats

  let parse (bits : Cstruct_sexp.t) : queueStats =
    { qsPort_no = get_ofp_queue_stats_port_no bits
    ; queue_id = get_ofp_queue_stats_queue_id bits
    ; tx_bytes = get_ofp_queue_stats_tx_bytes bits
    ; tx_packets = get_ofp_queue_stats_tx_packets bits
    ; tx_errors = get_ofp_queue_stats_tx_errors bits
    ; duration_sec = get_ofp_queue_stats_duration_sec bits
    ; duration_nsec = get_ofp_queue_stats_duration_nsec bits
    }

  let length_func = (fun buf -> Some sizeof_ofp_queue_stats)

end

module GroupStats = struct

  [%%cstruct
  type ofp_group_stats = {
    length: uint16_t ;
    pad: uint8_t [@len 2];
    group_id: uint32_t ;
    ref_count: uint32_t ;
    pad2: uint8_t [@len 4];
    packet_count: uint64_t ;
    byte_count: uint64_t ;
    duration_sec: uint32_t ;
    duration_nsec: uint32_t
  } [@@big_endian]]

  module BucketStats = struct

    [%%cstruct
    type ofp_bucket_counter = {
      packet_count: uint64_t ;
      byte_count: uint64_t
    } [@@big_endian]]

    type t = bucketStats

    let sizeof (gs : bucketStats) : int =
      sizeof_ofp_bucket_counter

    let to_string (bs : bucketStats) : string =
      Format.sprintf "{ packet_count = %Lu; byte_count = %Lu }"
        bs.packet_count
        bs.byte_count

    let marshal (buf : Cstruct_sexp.t) (bs : bucketStats) : int =
      set_ofp_bucket_counter_packet_count buf bs.packet_count;
      set_ofp_bucket_counter_byte_count buf bs.byte_count;
      sizeof_ofp_bucket_counter

    let parse (bits : Cstruct_sexp.t) : bucketStats =
      { packet_count = get_ofp_bucket_counter_packet_count bits
      ; byte_count = get_ofp_bucket_counter_byte_count bits }

    let length_func = (fun buf -> Some sizeof_ofp_bucket_counter)

  end

  type t = groupStats

  let sizeof (gs : groupStats) : int =
    gs.length

  let to_string (gs : groupStats) : string =
    Format.sprintf "{ length =  %u; group_id = %lu; ref_count: = %lu; packet_count = %Lu; \
                    byte_count = %Lu; duration (s/ns) = %lu/%lu; bucket stats = %s }"
      gs.length
      gs.group_id
      gs.ref_count
      gs.packet_count
      gs.byte_count
      gs.duration_sec
      gs.duration_nsec
      ("[ " ^ (String.concat ~sep:";" (List.map ~f:BucketStats.to_string gs.bucket_stats)) ^ " ]")

  let marshal (buf : Cstruct_sexp.t) (gs : groupStats) : int =
    set_ofp_group_stats_length buf gs.length;
    set_ofp_group_stats_pad (String.make 2 '\000') 0 buf;
    set_ofp_group_stats_group_id buf gs.group_id;
    set_ofp_group_stats_ref_count buf gs.ref_count;
    set_ofp_group_stats_pad2 (String.make 4 '\000') 0 buf;
    set_ofp_group_stats_packet_count buf gs.packet_count;
    set_ofp_group_stats_byte_count buf gs.byte_count;
    set_ofp_group_stats_duration_sec buf gs.duration_sec;
    set_ofp_group_stats_duration_nsec buf gs.duration_nsec;
    sizeof_ofp_group_stats + (marshal_fields (Cstruct.shift buf sizeof_ofp_group_stats) gs.bucket_stats BucketStats.marshal)

  let parse (bits : Cstruct_sexp.t) : groupStats =
    { length = get_ofp_group_stats_length bits
    ; group_id = get_ofp_group_stats_group_id bits
    ; ref_count = get_ofp_group_stats_ref_count bits
    ; packet_count = get_ofp_group_stats_packet_count bits
    ; byte_count = get_ofp_group_stats_byte_count bits
    ; duration_sec = get_ofp_group_stats_duration_sec bits
    ; duration_nsec = get_ofp_group_stats_duration_nsec bits
    ; bucket_stats = parse_fields (Cstruct.shift bits sizeof_ofp_group_stats) BucketStats.parse BucketStats.length_func
    }

  let length_func (buf :  Cstruct_sexp.t) : int option =
    if Cstruct.length buf < sizeof_ofp_group_stats then None
    else Some (get_ofp_group_stats_length buf)

end

module GroupDesc = struct

  [%%cstruct
  type ofp_group_desc = {
    length: uint16_t ;
    typ: uint8_t ;
    pad: uint8_t ;
    group_id: uint32_t ;
  } [@@big_endian]]

  type t = groupDesc

  let sizeof (gd : groupDesc) : int =
    sizeof_ofp_group_desc + sum (List.map ~f:Bucket.sizeof gd.bucket)

  let to_string (gd : groupDesc) : string =
    Format.sprintf "{ length = %u; group_type = %s; group_id = %lu; bucket = %s }"
      gd.length
      (GroupType.to_string gd.typ)
      gd.group_id
      ( "[ " ^(String.concat ~sep:"; " (List.map ~f:Bucket.to_string gd.bucket)) ^ " ]")

  let marshal (buf : Cstruct_sexp.t) (gd : groupDesc) : int =
    set_ofp_group_desc_length buf gd.length;
    set_ofp_group_desc_typ buf (GroupType.marshal gd.typ);
    set_ofp_group_desc_group_id buf gd.group_id;
    let size_bucket =
      (marshal_fields (Cstruct.shift buf sizeof_ofp_group_desc) gd.bucket Bucket.marshal) in
    sizeof_ofp_group_desc + size_bucket

  let parse (bits : Cstruct_sexp.t) : groupDesc =
    let len = get_ofp_group_desc_length bits in
    let typ = GroupType.parse (get_ofp_group_desc_typ bits) in
    let group_id = get_ofp_group_desc_group_id bits in
    let bucket_bits = Cstruct.sub bits sizeof_ofp_group_desc (len - sizeof_ofp_group_desc) in
    let bucket = parse_fields bucket_bits Bucket.parse Bucket.length_func in
    { length = len
    ; typ = typ
    ; group_id = group_id
    ; bucket = bucket}

  let length_func buf =
    if Cstruct.length buf < sizeof_ofp_group_desc  then None
    else Some (get_ofp_group_desc_length buf)

end

module GroupFeatures = struct

  [%%cstruct
  type ofp_group_features = {
    typ: uint32_t ;
    capabilities: uint32_t ;
    max_groups_all: uint32_t ;
    max_groups_select: uint32_t ;
    max_groups_indirect: uint32_t ;
    max_groups_fastfailover: uint32_t ;
    actions_all: uint32_t ;
    actions_select: uint32_t ;
    actions_indirect: uint32_t ;
    actions_fastfailover: uint32_t
  } [@@big_endian]]

  module GroupType = struct

    type t = groupTypeMap

    let marshal (gtm : groupTypeMap) : int32 =
      Int32.bit_or (if gtm.all then (Int32.shift_left 1l 0) else 0l)
        (Int32.bit_or (if gtm.select then (Int32.shift_left 1l 1) else 0l)
           (Int32.bit_or (if gtm.indirect then (Int32.shift_left 1l 2) else 0l)
              (if gtm.ff then (Int32.shift_left 1l 3) else 0l)))

    let parse bits : groupTypeMap =
      { all = Bits.test_bit 0 bits
      ; select = Bits.test_bit 1 bits
      ; indirect = Bits.test_bit 2 bits
      ; ff = Bits.test_bit 3 bits }

    let to_string (gtm : groupTypeMap) : string =
      Format.sprintf "{ all = %B; select = %B; indirect = %B; ff = %B }"
        gtm.all
        gtm.select
        gtm.indirect
        gtm.ff

  end

  module Capabilities = struct

    type t = groupCapabilities

    let marshal (gc : groupCapabilities) : int32 =
      Int32.bit_or (if gc.select_weight then (Int32.shift_left 1l 0) else 0l)
        (Int32.bit_or (if gc.select_liveness then (Int32.shift_left 1l 1) else 0l)
           (Int32.bit_or (if gc.chaining then (Int32.shift_left 1l 2) else 0l)
              (if gc.chaining_checks then (Int32.shift_left 1l 3) else 0l)))

    let parse bits : groupCapabilities =
      { select_weight = Bits.test_bit 0 bits
      ; select_liveness = Bits.test_bit 1 bits
      ; chaining = Bits.test_bit 2 bits
      ; chaining_checks = Bits.test_bit 3 bits }

    let to_string (gc : groupCapabilities) : string =
      Format.sprintf "{ select_weight = %B; select_liveness = %B; chaining = %B; chaining_checks = %B }"
        gc.select_weight
        gc.select_liveness
        gc.chaining
        gc.chaining_checks

  end

  module ActionTypeMap = struct

    type t = actionTypeMap

    let marshal (atm : actionTypeMap) : int32 =
      Int32.bit_or (if atm.output then (Int32.shift_left 1l 0) else 0l)
        (Int32.bit_or (if atm.copy_ttl_out then (Int32.shift_left 1l 11) else 0l)
           (Int32.bit_or (if atm.copy_ttl_in then (Int32.shift_left 1l 12) else 0l)
              (Int32.bit_or (if atm.set_mpls_ttl then (Int32.shift_left 1l 15) else 0l)
                 (Int32.bit_or (if atm.dec_mpls_ttl then (Int32.shift_left 1l 16) else 0l)
                    (Int32.bit_or (if atm.push_vlan then (Int32.shift_left 1l 17) else 0l)
                       (Int32.bit_or (if atm.pop_vlan then (Int32.shift_left 1l 18) else 0l)
                          (Int32.bit_or (if atm.push_mpls then (Int32.shift_left 1l 19) else 0l)
                             (Int32.bit_or (if atm.pop_mpls then (Int32.shift_left 1l 20) else 0l)
                                (Int32.bit_or (if atm.set_queue then (Int32.shift_left 1l 21) else 0l)
                                   (Int32.bit_or (if atm.group then (Int32.shift_left 1l 22) else 0l)
                                      (Int32.bit_or (if atm.set_nw_ttl then (Int32.shift_left 1l 23) else 0l)
                                         (Int32.bit_or (if atm.dec_nw_ttl then (Int32.shift_left 1l 24) else 0l)
                                            (Int32.bit_or (if atm.set_field then (Int32.shift_left 1l 25) else 0l)
                                               (Int32.bit_or (if atm.push_pbb then (Int32.shift_left 1l 26) else 0l)
                                                  (if atm.pop_pbb then (Int32.shift_left 1l 27) else 0l)))))))))))))))

    let parse bits : actionTypeMap =
      { output = Bits.test_bit 0 bits
      ; copy_ttl_out = Bits.test_bit 11 bits
      ; copy_ttl_in = Bits.test_bit 12 bits
      ; set_mpls_ttl = Bits.test_bit 15 bits
      ; dec_mpls_ttl = Bits.test_bit 16 bits
      ; push_vlan = Bits.test_bit 17 bits
      ; pop_vlan = Bits.test_bit 18 bits
      ; push_mpls = Bits.test_bit 19 bits
      ; pop_mpls = Bits.test_bit 20 bits
      ; set_queue = Bits.test_bit 21 bits
      ; group = Bits.test_bit 22 bits
      ; set_nw_ttl = Bits.test_bit 23 bits
      ; dec_nw_ttl = Bits.test_bit 24 bits
      ; set_field = Bits.test_bit 25 bits
      ; push_pbb = Bits.test_bit 26 bits
      ; pop_pbb = Bits.test_bit 27 bits }

    let to_string (atm : actionTypeMap) : string =
      Format.sprintf "{ output = %B; copy_ttl_out = %B; copy_ttl_in = %B; set_mpls ttl = %B; \
                      dec_mpls_ttl = %B; push_vlan = %B; pop_vlan = %B; push_mpls = %B; pop_mpls = %B; \
                      set_queue = %B; group = %B; set_nw_ttl = %B; dec_nw_ttl = %B; set_field = %B; \
                      push_pbb = %B; pop_pbb = %B }"
        atm.output
        atm.copy_ttl_out
        atm.copy_ttl_in
        atm.set_mpls_ttl
        atm.dec_mpls_ttl
        atm.push_vlan
        atm.pop_vlan
        atm.push_mpls
        atm.pop_mpls
        atm.set_queue
        atm.group
        atm.set_nw_ttl
        atm.dec_nw_ttl
        atm.set_field
        atm.push_pbb
        atm.pop_pbb

  end

  type t = groupFeatures

  let sizeof (gf : groupFeatures) : int =
    sizeof_ofp_group_features

  let to_string (gf : groupFeatures) : string =
    Format.sprintf "{ type =  %s; capbailities =  %s; max group = {\
                    all =  %lu; select =  %lu; indirect =  %lu; fastfailover =  %lu }; actions = {
    all =  %s; select =  %s; indirect =  %s; fastfailover =  %s } }"
      (GroupType.to_string gf.typ)
      (Capabilities.to_string gf.capabilities)
      gf.max_groups_all
      gf.max_groups_select
      gf.max_groups_indirect
      gf.max_groups_ff
      (ActionTypeMap.to_string gf.actions_all)
      (ActionTypeMap.to_string gf.actions_select)
      (ActionTypeMap.to_string gf.actions_indirect)
      (ActionTypeMap.to_string gf.actions_ff)

  let marshal (buf : Cstruct_sexp.t) (gf : groupFeatures) : int =
    set_ofp_group_features_typ buf (GroupType.marshal gf.typ);
    set_ofp_group_features_capabilities buf (Capabilities.marshal gf.capabilities);
    set_ofp_group_features_max_groups_all buf gf.max_groups_all;
    set_ofp_group_features_max_groups_select buf gf.max_groups_select;
    set_ofp_group_features_max_groups_indirect buf gf.max_groups_indirect;
    set_ofp_group_features_max_groups_fastfailover buf gf.max_groups_ff;
    set_ofp_group_features_actions_all buf (ActionTypeMap.marshal gf.actions_all);
    set_ofp_group_features_actions_select buf (ActionTypeMap.marshal gf.actions_select);
    set_ofp_group_features_actions_indirect buf (ActionTypeMap.marshal gf.actions_indirect);
    set_ofp_group_features_actions_fastfailover buf (ActionTypeMap.marshal gf.actions_ff);
    sizeof_ofp_group_features

  let parse (bits : Cstruct_sexp.t) : groupFeatures =
    { typ = GroupType.parse (get_ofp_group_features_typ bits)
    ; capabilities = Capabilities.parse (get_ofp_group_features_capabilities bits)
    ; max_groups_all = get_ofp_group_features_max_groups_all bits
    ; max_groups_select = get_ofp_group_features_max_groups_select bits
    ; max_groups_indirect = get_ofp_group_features_max_groups_indirect bits
    ; max_groups_ff = get_ofp_group_features_max_groups_fastfailover bits
    ; actions_all = ActionTypeMap.parse (get_ofp_group_features_actions_all bits)
    ; actions_select = ActionTypeMap.parse (get_ofp_group_features_actions_select bits)
    ; actions_indirect = ActionTypeMap.parse (get_ofp_group_features_actions_indirect bits)
    ; actions_ff = ActionTypeMap.parse (get_ofp_group_features_actions_fastfailover bits)
    }

end

module MeterStats = struct

  [%%cstruct
  type ofp_meter_stats = {
    meter_id: uint32_t ;
    len: uint16_t ;
    pad: uint8_t [@len 6];
    flow_count: uint32_t ;
    packet_in_count: uint64_t ;
    byte_in_count: uint64_t ;
    duration_sec: uint32_t ;
    duration_nsec: uint32_t
  } [@@big_endian]]

  module Band = struct

    [%%cstruct
    type ofp_meter_band_stats = {
      packet_band_count: uint64_t ;
      byte_band_count: uint64_t
    } [@@big_endian]]

    type t = meterBandStats

    let length_func = fun buf -> Some sizeof_ofp_meter_band_stats

    let marshal (buf : Cstruct_sexp.t) (mbs : meterBandStats) : int =
      set_ofp_meter_band_stats_packet_band_count buf mbs.packet_band_count;
      set_ofp_meter_band_stats_byte_band_count buf mbs.byte_band_count;
      sizeof_ofp_meter_band_stats

    let parse (bits : Cstruct_sexp.t) : meterBandStats =
      { packet_band_count = get_ofp_meter_band_stats_packet_band_count bits
      ; byte_band_count = get_ofp_meter_band_stats_byte_band_count bits}

    let to_string (mbs : meterBandStats) : string =
      Format.sprintf "{ packet_count:%Lu; byte_count = %Lu }"
        mbs.packet_band_count
        mbs.byte_band_count

  end

  type t = meterStats

  let sizeof (ms : meterStats) : int =
    ms.len

  let to_string (ms : meterStats) : string =
    Format.sprintf "{ meter_id = %lu; len = %u; flow_count = %lu; packet_in_count = %Lu\
                    byte_in_count = %Lu; duration (s/ns) = %lu/%lu; band = %s }"
      ms.meter_id
      ms.len
      ms.flow_count
      ms.packet_in_count
      ms.byte_in_count
      ms.duration_sec
      ms.duration_nsec
      ("[ " ^ (String.concat ~sep:";" (List.map ~f:Band.to_string ms.band)) ^ " ]")

  let marshal (buf : Cstruct_sexp.t) (ms : meterStats) =
    set_ofp_meter_stats_meter_id buf ms.meter_id;
    set_ofp_meter_stats_len buf ms.len;
    set_ofp_meter_stats_pad (String.make 6 '\000') 0 buf;
    set_ofp_meter_stats_flow_count buf ms.flow_count;
    set_ofp_meter_stats_packet_in_count buf ms.packet_in_count;
    set_ofp_meter_stats_byte_in_count buf ms.byte_in_count;
    set_ofp_meter_stats_duration_sec buf ms.duration_sec;
    set_ofp_meter_stats_duration_nsec buf ms.duration_nsec;
    let band_buf = Cstruct.sub buf sizeof_ofp_meter_stats (ms.len - sizeof_ofp_meter_stats) in
    sizeof_ofp_meter_stats + (marshal_fields band_buf ms.band Band.marshal)

  let parse (bits : Cstruct_sexp.t) : meterStats =
    let meter_id = get_ofp_meter_stats_meter_id bits in
    let len = get_ofp_meter_stats_len bits in
    let flow_count = get_ofp_meter_stats_flow_count bits in
    let packet_in_count = get_ofp_meter_stats_packet_in_count bits in
    let byte_in_count = get_ofp_meter_stats_byte_in_count bits in
    let duration_sec = get_ofp_meter_stats_duration_sec bits in
    let duration_nsec = get_ofp_meter_stats_duration_nsec bits in
    let band_bits = Cstruct.sub bits sizeof_ofp_meter_stats (len - sizeof_ofp_meter_stats) in
    let band = parse_fields band_bits Band.parse Band.length_func in
    { meter_id; len; flow_count; packet_in_count; byte_in_count; duration_sec; duration_nsec; band }

  let length_func buf =
    if Cstruct.length buf < sizeof_ofp_meter_stats  then None
    else Some (get_ofp_meter_stats_len buf)

end

module MeterConfig = struct

  [%%cstruct
  type ofp_meter_config = {
    length: uint16_t ;
    flags: uint16_t ;
    meter_id: uint32_t
  } [@@big_endian]]

  type t = meterConfig

  let sizeof (mc : meterConfig) : int =
    sizeof_ofp_meter_config + sum (List.map ~f:MeterBand.sizeof mc.bands)

  let to_string (mc : meterConfig) : string =
    Format.sprintf "{ len = %u; flags = %s; meter_id = %lu; bands = %s }"
      mc.length
      (MeterFlags.to_string mc.flags)
      mc.meter_id
      ( "[ " ^ (String.concat ~sep:"; " (List.map ~f:MeterBand.to_string mc.bands)) ^ " ]")

  let marshal (buf : Cstruct_sexp.t) (mc : meterConfig) : int =
    set_ofp_meter_config_length buf mc.length;
    set_ofp_meter_config_flags buf (MeterFlags.marshal mc.flags);
    set_ofp_meter_config_meter_id buf mc.meter_id;
    sizeof_ofp_meter_config + (marshal_fields (Cstruct.shift buf sizeof_ofp_meter_config) mc.bands MeterBand.marshal)

  let parse (bits : Cstruct_sexp.t) : meterConfig =
    let length = get_ofp_meter_config_length bits in
    let flags = MeterFlags.parse (get_ofp_meter_config_flags bits) in
    let meter_id = get_ofp_meter_config_meter_id bits in
    let bands_bits = Cstruct.sub bits sizeof_ofp_meter_config (length-sizeof_ofp_meter_config) in
    let bands = parse_fields bands_bits MeterBand.parse MeterBand.length_fun in
    { length
    ; flags
    ; meter_id
    ; bands
    }

  let length_func (buf : Cstruct_sexp.t) : int option =
    if Cstruct.length buf < sizeof_ofp_meter_config then None
    else Some (get_ofp_meter_config_length buf)

end

module MeterFeatures = struct

  [%%cstruct
  type ofp_meter_features = {
    max_meter: uint32_t ;
    band_types: uint32_t ;
    capabilities: uint32_t ;
    max_bands: uint8_t ;
    max_color: uint8_t ;
    pad: uint8_t [@len 2]
  } [@@big_endian]]

  module Bands = struct
    type t = meterBandMaps

    let marshal (mbm : meterBandMaps) : int32 =
      Int32.bit_or (if mbm.drop then (Int32.shift_left 1l 1) else 0l)
        (if mbm.dscpRemark then (Int32.shift_left 1l 2) else 0l)

    let parse bits : meterBandMaps =
      { drop = Bits.test_bit 1 bits
      ; dscpRemark = Bits.test_bit 2 bits }

    let to_string (mbm : meterBandMaps) : string =
      Format.sprintf "{ drop = %B; dscp_remark =  %B }"
        mbm.drop
        mbm.dscpRemark

  end

  type t = meterFeatures

  let sizeof (mfs : t) : int =
    sizeof_ofp_meter_features

  let to_string (mfs : t) : string =
    Format.sprintf "{ max_meter = %lu; band_typ = %s; capabilities = %s; max_band = %u; max_color = %u }"
      mfs.max_meter
      (Bands.to_string mfs.band_typ)
      (MeterFlags.to_string mfs.capabilities)
      mfs.max_band
      mfs.max_color

  let marshal (buf : Cstruct_sexp.t) (mfs : t) : int =
    set_ofp_meter_features_max_meter buf mfs.max_meter;
    set_ofp_meter_features_band_types buf (Bands.marshal mfs.band_typ);
    (* int -> int32 fix, before release of OF1.3.5 *)
    set_ofp_meter_features_capabilities buf (Int32.of_int_exn (MeterFlags.marshal mfs.capabilities));
    set_ofp_meter_features_max_bands buf mfs.max_band;
    set_ofp_meter_features_max_color buf mfs.max_color;
    set_ofp_meter_features_pad (String.make 2 '\000') 0 buf;
    sizeof_ofp_meter_features

  let parse (bits : Cstruct_sexp.t) : t =
    { max_meter = get_ofp_meter_features_max_meter bits
    ; band_typ = Bands.parse (get_ofp_meter_features_band_types bits)
    (* int32 -> int fix, before release of OF1.3.5 *)
    ; capabilities = MeterFlags.parse (Int32.to_int_exn (get_ofp_meter_features_capabilities bits))
    ; max_band = get_ofp_meter_features_max_bands bits
    ; max_color = get_ofp_meter_features_max_color bits
    }
end

module MultipartReply = struct

  type t = multipartReply

  let sizeof (mpr : multipartReply) =
    sizeof_ofp_multipart_reply +
    match mpr.mpreply_typ with
    | PortsDescReply pdr -> sum (List.map ~f:PortDesc.sizeof pdr)
    | SwitchDescReply _ -> sizeof_ofp_desc
    | FlowStatsReply fsr -> sum (List.map ~f:FlowStats.sizeof fsr)
    | AggregateReply ag -> AggregateStats.sizeof ag
    | TableReply tr -> sum (List.map ~f:TableStats.sizeof tr)
    | TableFeaturesReply tf -> sum (List.map ~f:TableFeature.sizeof tf)
    | PortStatsReply psr -> sum (List.map ~f:PortStats.sizeof psr)
    | QueueStatsReply qsr -> sum (List.map ~f:QueueStats.sizeof qsr)
    | GroupStatsReply gs -> sum (List.map ~f:GroupStats.sizeof gs)
    | GroupDescReply gd -> sum (List.map ~f:GroupDesc.sizeof gd)
    | GroupFeaturesReply gf -> GroupFeatures.sizeof gf
    | MeterReply mr -> sum (List.map ~f:MeterStats.sizeof mr)
    | MeterConfig mc -> sum (List.map ~f:MeterConfig.sizeof mc)
    | MeterFeaturesReply mf -> MeterFeatures.sizeof mf

  let to_string (mpr : multipartReply) =
    match mpr.mpreply_typ with
    | PortsDescReply pdr -> Format.sprintf "PortsDescReply { %s }" (String.concat ~sep:"; " (List.map ~f:PortDesc.to_string pdr))
    | SwitchDescReply sdc -> Format.sprintf "SwitchDescReply %s" (SwitchDescriptionReply.to_string sdc)
    | FlowStatsReply fsr -> Format.sprintf "Flow { %s }" (String.concat ~sep:"; " (List.map ~f:FlowStats.to_string fsr))
    | AggregateReply ag -> Format.sprintf "Aggregate Flow %s" (AggregateStats.to_string ag)
    | TableReply tr -> Format.sprintf "TableReply { %s }" (String.concat ~sep:"; " (List.map ~f:TableStats.to_string tr))
    | TableFeaturesReply tf -> Format.sprintf "TableFeaturesReply { %s }" (String.concat ~sep:"; " (List.map ~f:TableFeature.to_string tf))
    | PortStatsReply psr -> Format.sprintf "PortStatsReply { %s }" (String.concat ~sep:"; " (List.map ~f:PortStats.to_string psr))
    | QueueStatsReply qsr -> Format.sprintf "QueueStats { %s }" (String.concat ~sep:"; " (List.map ~f:QueueStats.to_string qsr))
    | GroupStatsReply gs -> Format.sprintf "GroupStats { %s }" (String.concat ~sep:"; " (List.map ~f:GroupStats.to_string gs))
    | GroupDescReply gd -> Format.sprintf "GroupSDesc { %s }" (String.concat ~sep:"; " (List.map ~f:GroupDesc.to_string gd))
    | GroupFeaturesReply gf -> Format.sprintf "GroupFeatures %s" (GroupFeatures.to_string gf)
    | MeterReply mr -> Format.sprintf "MeterStats { %s }" (String.concat ~sep:"; " (List.map ~f:MeterStats.to_string mr))
    | MeterConfig mc -> Format.sprintf "MeterConfig { %s }" (String.concat ~sep:"; " (List.map ~f:MeterConfig.to_string mc))
    | MeterFeaturesReply mf -> Format.sprintf "MeterFeaturesStats %s" (MeterFeatures.to_string mf)

  let marshal (buf : Cstruct_sexp.t) (mpr : multipartReply) : int =
    let ofp_body_bits = Cstruct.shift buf sizeof_ofp_multipart_reply in
    set_ofp_multipart_reply_flags buf (
      match mpr.mpreply_flags with
      | true -> ofp_multipart_request_flags_to_int OFPMPF_REQ_MORE
      | false -> 0);
    set_ofp_multipart_reply_pad (String.make 4 '\000') 0 buf;
    sizeof_ofp_multipart_reply + (match mpr.mpreply_typ with
        | PortsDescReply pdr ->
          set_ofp_multipart_reply_typ buf (ofp_multipart_types_to_int OFPMP_PORT_DESC);
          marshal_fields ofp_body_bits pdr PortDesc.marshal
        | SwitchDescReply sdr ->
          set_ofp_multipart_reply_typ buf (ofp_multipart_types_to_int OFPMP_DESC);
          SwitchDescriptionReply.marshal ofp_body_bits sdr
        | FlowStatsReply fsr ->
          set_ofp_multipart_reply_typ buf (ofp_multipart_types_to_int OFPMP_FLOW);
          marshal_fields ofp_body_bits fsr FlowStats.marshal
        | AggregateReply ar ->
          set_ofp_multipart_reply_typ buf (ofp_multipart_types_to_int OFPMP_AGGREGATE);
          AggregateStats.marshal ofp_body_bits ar
        | TableReply tr ->
          set_ofp_multipart_reply_typ buf (ofp_multipart_types_to_int OFPMP_TABLE);
          marshal_fields ofp_body_bits tr TableStats.marshal
        | TableFeaturesReply tf ->
          set_ofp_multipart_reply_typ buf (ofp_multipart_types_to_int OFPMP_TABLE_FEATURES);
          marshal_fields ofp_body_bits tf TableFeature.marshal
        | PortStatsReply psr ->
          set_ofp_multipart_reply_typ buf (ofp_multipart_types_to_int OFPMP_PORT_STATS);
          marshal_fields ofp_body_bits psr PortStats.marshal
        | QueueStatsReply qsr ->
          set_ofp_multipart_reply_typ buf (ofp_multipart_types_to_int OFPMP_QUEUE);
          marshal_fields ofp_body_bits qsr QueueStats.marshal
        | GroupStatsReply gs ->
          set_ofp_multipart_reply_typ buf (ofp_multipart_types_to_int OFPMP_GROUP);
          marshal_fields ofp_body_bits gs GroupStats.marshal
        | GroupDescReply gd ->
          set_ofp_multipart_reply_typ buf (ofp_multipart_types_to_int OFPMP_GROUP_DESC);
          marshal_fields ofp_body_bits gd GroupDesc.marshal
        | GroupFeaturesReply gf ->
          set_ofp_multipart_reply_typ buf (ofp_multipart_types_to_int OFPMP_GROUP_FEATURES);
          GroupFeatures.marshal ofp_body_bits gf
        | MeterReply mr ->
          set_ofp_multipart_reply_typ buf (ofp_multipart_types_to_int OFPMP_METER);
          marshal_fields ofp_body_bits mr MeterStats.marshal
        | MeterConfig mc ->
          set_ofp_multipart_reply_typ buf (ofp_multipart_types_to_int OFPMP_METER_CONFIG);
          marshal_fields ofp_body_bits mc MeterConfig.marshal
        | MeterFeaturesReply mfr ->
          set_ofp_multipart_reply_typ buf (ofp_multipart_types_to_int OFPMP_METER_FEATURES);
          MeterFeatures.marshal ofp_body_bits mfr
      )

  let parse (bits : Cstruct_sexp.t) : multipartReply =
    let ofp_body_bits = Cstruct.shift bits sizeof_ofp_multipart_reply in
    let typ = (match int_to_ofp_multipart_types (get_ofp_multipart_reply_typ bits) with
        | Some OFPMP_PORT_DESC ->
          PortsDescReply (parse_fields ofp_body_bits PortDesc.parse PortDesc.length_func)
        | Some OFPMP_DESC ->
          SwitchDescReply (SwitchDescriptionReply.parse ofp_body_bits)
        | Some OFPMP_FLOW ->
          FlowStatsReply (parse_fields ofp_body_bits FlowStats.parse FlowStats.length_func)
        | Some OFPMP_AGGREGATE ->
          AggregateReply (AggregateStats.parse ofp_body_bits)
        | Some OFPMP_TABLE ->
          TableReply (parse_fields ofp_body_bits TableStats.parse TableStats.length_func)
        | Some OFPMP_TABLE_FEATURES ->
          TableFeaturesReply (parse_fields ofp_body_bits TableFeature.parse TableFeature.length_func)
        | Some OFPMP_PORT_STATS ->
          PortStatsReply (parse_fields ofp_body_bits PortStats.parse PortStats.length_func)
        | Some OFPMP_QUEUE ->
          QueueStatsReply (parse_fields ofp_body_bits QueueStats.parse QueueStats.length_func)
        | Some OFPMP_GROUP ->
          GroupStatsReply (parse_fields ofp_body_bits GroupStats.parse GroupStats.length_func)
        | Some OFPMP_GROUP_DESC ->
          GroupDescReply (parse_fields ofp_body_bits GroupDesc.parse GroupDesc.length_func)
        | Some OFPMP_GROUP_FEATURES ->
          GroupFeaturesReply (GroupFeatures.parse ofp_body_bits)
        | Some OFPMP_METER ->
          MeterReply (parse_fields ofp_body_bits MeterStats.parse MeterStats.length_func)
        | Some OFPMP_METER_CONFIG ->
          MeterConfig (parse_fields ofp_body_bits MeterConfig.parse MeterConfig.length_func)
        | Some OFPMP_METER_FEATURES ->
          MeterFeaturesReply (MeterFeatures.parse ofp_body_bits)
        | _ -> raise (Unparsable (sprintf "NYI: can't parse this multipart reply"))) in
    let flags = (
      match int_to_ofp_multipart_request_flags (get_ofp_multipart_request_flags bits) with
      | Some OFPMPF_REQ_MORE -> true
      | _ -> false) in
    {mpreply_typ = typ; mpreply_flags = flags}

end

module TableMod = struct

  [%%cstruct
  type ofp_table_mod = {
    table_id: uint8_t ;
    pad: uint8_t [@len 3];
    config: uint32_t
  } [@@big_endian]]

  type t = tableMod

  let sizeof (tab : tableMod) : int =
    sizeof_ofp_table_mod

  let to_string (tab : tableMod) : string =
    Format.sprintf "{ tabled_id = %u; config = %s }"
      tab.table_id
      (TableConfig.to_string tab.config)

  let marshal (buf : Cstruct_sexp.t) (tab : tableMod) : int =
    set_ofp_table_mod_table_id buf tab.table_id;
    set_ofp_table_mod_config buf (TableConfig.marshal tab.config);
    set_ofp_table_mod_pad (String.make 3 '\000') 0 buf;
    sizeof_ofp_table_mod

  let parse (bits : Cstruct_sexp.t) : tableMod =
    let table_id = get_ofp_table_mod_table_id bits in
    let config = TableConfig.parse (get_ofp_table_mod_config bits) in
    { table_id; config }

end

module QueueConfReq = struct

  [%%cstruct
  type ofp_queue_get_config_request = {
    port: uint32_t ;
    pad: uint8_t [@len 4]
  } [@@big_endian]]

  type t = queueConfReq

  let sizeof (qr : t) : int =
    sizeof_ofp_queue_get_config_request

  let to_string (qr : t) : string =
    Format.sprintf "{ port = %lu }" qr.port

  let marshal (buf : Cstruct_sexp.t) (qr : t) : int =
    set_ofp_queue_get_config_request_port buf qr.port;
    set_ofp_queue_get_config_request_pad (String.make 4 '\000') 0 buf;
    sizeof_ofp_queue_get_config_request

  let parse (bits : Cstruct_sexp.t) : t =
    let port = get_ofp_queue_get_config_request_port bits in
    { port }
end

module QueueConfReply = struct

  [%%cstruct
  type ofp_queue_get_config_reply = {
    port: uint32_t ;
    pad: uint8_t [@len 4];
  } [@@big_endian]]

  type t = queueConfReply

  let sizeof (qr : t) : int =
    sizeof_ofp_queue_get_config_reply + sum (List.map ~f:QueueDesc.sizeof qr.queues)

  let to_string (qr : t) : string =
    Format.sprintf "{ port = %lu; queue = %s }"
      qr.port
      ("[ " ^ (String.concat ~sep:"; " (List.map ~f:QueueDesc.to_string qr.queues)) ^ " ]")

  let marshal (buf : Cstruct_sexp.t) (qr : t) : int =
    set_ofp_queue_get_config_reply_port buf qr.port;
    set_ofp_queue_get_config_reply_pad (String.make 4 '\000') 0 buf;
    let queueBuf = Cstruct.shift buf sizeof_ofp_queue_get_config_reply in
    sizeof_ofp_queue_get_config_reply + (marshal_fields queueBuf qr.queues QueueDesc.marshal)

  let parse (bits : Cstruct_sexp.t) : t =
    let port = get_ofp_queue_get_config_reply_port bits in
    let queuesBits = Cstruct.shift bits sizeof_ofp_queue_get_config_reply in
    let queues = parse_fields queuesBits QueueDesc.parse QueueDesc.length_func in
    { port; queues}

end

module RoleRequest = struct

  [%%cstruct
  type ofp_role_request = {
    role: uint32_t ;
    pad: uint8_t [@len 4];
    generation_id: uint64_t
  } [@@big_endian]]

  module Role = struct
    [%%cenum
    type ofp_controller_role =
      | OFPCR_ROLE_NOCHANGE [@id 0]
      | OFPCR_ROLE_EQUAL [@id 1]
      | OFPCR_ROLE_MASTER [@id 2]
      | OFPCR_ROLE_SLAVE [@id 3]
      [@@uint32_t]
    ]

    let to_string (role : controllerRole) : string =
      match role with
      | NoChangeRole -> "NOCHANGE"
      | EqualRole -> "EQUAL"
      | MasterRole -> "MASTER"
      | SlaveRole -> "SLAVE"

    let marshal (role : controllerRole) : int32 =
      match role with
      | NoChangeRole -> ofp_controller_role_to_int OFPCR_ROLE_NOCHANGE
      | EqualRole -> ofp_controller_role_to_int OFPCR_ROLE_EQUAL
      | MasterRole -> ofp_controller_role_to_int OFPCR_ROLE_MASTER
      | SlaveRole -> ofp_controller_role_to_int OFPCR_ROLE_SLAVE

    let parse t : controllerRole =
      match int_to_ofp_controller_role t with
      | Some OFPCR_ROLE_NOCHANGE -> NoChangeRole
      | Some OFPCR_ROLE_EQUAL -> EqualRole
      | Some OFPCR_ROLE_MASTER -> MasterRole
      | Some OFPCR_ROLE_SLAVE -> SlaveRole
      | None -> raise (Unparsable (sprintf "malformed role"))

  end

  type t = roleRequest

  let sizeof (role : roleRequest) : int =
    sizeof_ofp_role_request

  let to_string (role : roleRequest) : string =
    Format.sprintf "{ role = %s; generation_id = %Lu }"
      (Role.to_string role.role)
      role.generation_id

  let marshal (buf : Cstruct_sexp.t) (role : roleRequest) : int =
    set_ofp_role_request_role buf (Role.marshal role.role);
    set_ofp_role_request_pad (String.make 4 '\000') 0 buf;
    set_ofp_role_request_generation_id buf role.generation_id;
    sizeof_ofp_role_request

  let parse (bits : Cstruct_sexp.t) : roleRequest =
    { role = Role.parse (get_ofp_role_request_role bits)
    ; generation_id = get_ofp_role_request_generation_id bits }
end

module Error = struct

  type t = error

    [%%cstruct
    type ofp_error_msg = {
      typ: uint16_t ;
      code: uint16_t
    } [@@big_endian]]

    [%%cenum
    type ofp_error_type =
      | OFPET_HELLO_FAILED [@id 0]
      | OFPET_BAD_REQUEST [@id 1]
      | OFPET_BAD_ACTION [@id 2]
      | OFPET_BAD_INSTRUCTION [@id 3]
      | OFPET_BAD_MATCH [@id 4]
      | OFPET_FLOW_MOD_FAILED [@id 5]
      | OFPET_GROUP_MOD_FAILED [@id 6]
      | OFPET_PORT_MOD_FAILED [@id 7]
      | OFPET_TABLE_MOD_FAILED [@id 8]
      | OFPET_QUEUE_OP_FAILED [@id 9]
      | OFPET_SWITCH_CONFIG_FAILED [@id 10]
      | OFPET_ROLE_REQUEST_FAILED [@id 11]
      | OFPET_METER_MOD_FAILED [@id 12]
      | OFPET_TABLE_FEATURES_FAILED [@id 13]
      | OFPET_EXPERIMENTER [@id 0xffff]
      [@@uint16_t]
    ]

  module HelloFailed = struct

    [%%cenum
    type ofp_hello_failed_code =
      | OFPHFC_INCOMPATIBLE [@id 0]
      | OFPHFC_EPERM [@id 1]
      [@@uint16_t]
    ]

    type t = helloFailed

    let to_string (cod : helloFailed) =
      match cod with
      | HelloIncompatible -> "INCOMPATIBLE"
      | HelloPermError -> "Permission_Error"

    let marshal (cod : helloFailed) : int =
      match cod with
      | HelloIncompatible -> ofp_hello_failed_code_to_int OFPHFC_INCOMPATIBLE
      | HelloPermError -> ofp_hello_failed_code_to_int OFPHFC_EPERM

    let parse t : helloFailed =
      match int_to_ofp_hello_failed_code t with
      | Some OFPHFC_INCOMPATIBLE -> HelloIncompatible
      | Some OFPHFC_EPERM -> HelloPermError
      | None -> raise (Unparsable (sprintf "malfomed hello_failed code"))

  end

  module BadRequest = struct

    [%%cenum
    type ofp_bad_request_code =
      | OFPBRC_BAD_VERSION [@id 0]
      | OFPBRC_BAD_TYPE [@id 1]
      | OFPBRC_BAD_MULTIPART [@id 2]
      | OFPBRC_BAD_EXPERIMENTER [@id 3]
      | OFPBRC_BAD_EXP_TYPE [@id 4]
      | OFPBRC_EPERM [@id 5]
      | OFPBRC_BAD_LEN [@id 6]
      | OFPBRC_BUFFER_EMPTY [@id 7]
      | OFPBRC_BUFFER_UNKNOWN [@id 8]
      | OFPBRC_BAD_TABLE_ID [@id 9]
      | OFPBRC_IS_SLAVE [@id 10]
      | OFPBRC_BAD_PORT [@id 11]
      | OFPBRC_BAD_PACKET [@id 12]
      | OFPBRC_MULTIPART_BUFFER_OVERFLOW [@id 13]
      [@@uint16_t]
    ]

    type t = badRequest

    let to_string (cod : badRequest) : string =
      match cod with
      | ReqBadVersion -> "BadVersion"
      | ReqBadType -> "BadTyp"
      | ReqBadMultipart -> "BadMultipart"
      | ReqBadExp -> "BadExp"
      | ReqBadExpType -> "BadExpType"
      | ReqPermError -> "Permission_Error"
      | ReqBadLen -> "BadLen"
      | ReqBufferEmpty -> "BufferEmpty"
      | ReqBufferUnknown -> "BufferUnknown"
      | ReqBadTableId -> "BadTableId"
      | ReqIsSlave -> "IsSlave"
      | ReqBadPort -> "BadPort"
      | ReqBadPacket -> "BadPacket"
      | ReqMultipartBufOverflow -> "MultipartBufOverflow"

    let marshal (cod : badRequest) : int =
      match cod with
      | ReqBadVersion -> ofp_bad_request_code_to_int OFPBRC_BAD_VERSION
      | ReqBadType -> ofp_bad_request_code_to_int OFPBRC_BAD_TYPE
      | ReqBadMultipart -> ofp_bad_request_code_to_int OFPBRC_BAD_MULTIPART
      | ReqBadExp -> ofp_bad_request_code_to_int OFPBRC_BAD_EXPERIMENTER
      | ReqBadExpType -> ofp_bad_request_code_to_int OFPBRC_BAD_EXP_TYPE
      | ReqPermError -> ofp_bad_request_code_to_int OFPBRC_EPERM
      | ReqBadLen -> ofp_bad_request_code_to_int OFPBRC_BAD_LEN
      | ReqBufferEmpty -> ofp_bad_request_code_to_int OFPBRC_BUFFER_EMPTY
      | ReqBufferUnknown -> ofp_bad_request_code_to_int OFPBRC_BUFFER_UNKNOWN
      | ReqBadTableId -> ofp_bad_request_code_to_int OFPBRC_BAD_TABLE_ID
      | ReqIsSlave -> ofp_bad_request_code_to_int OFPBRC_IS_SLAVE
      | ReqBadPort -> ofp_bad_request_code_to_int OFPBRC_BAD_PORT
      | ReqBadPacket -> ofp_bad_request_code_to_int OFPBRC_BAD_PACKET
      | ReqMultipartBufOverflow -> ofp_bad_request_code_to_int OFPBRC_MULTIPART_BUFFER_OVERFLOW

    let parse t : badRequest =
      match int_to_ofp_bad_request_code t with
      | Some OFPBRC_BAD_VERSION -> ReqBadVersion
      | Some OFPBRC_BAD_TYPE -> ReqBadType
      | Some OFPBRC_BAD_MULTIPART -> ReqBadMultipart
      | Some OFPBRC_BAD_EXPERIMENTER -> ReqBadExp
      | Some OFPBRC_BAD_EXP_TYPE -> ReqBadExpType
      | Some OFPBRC_EPERM -> ReqPermError
      | Some OFPBRC_BAD_LEN -> ReqBadLen
      | Some OFPBRC_BUFFER_EMPTY -> ReqBufferEmpty
      | Some OFPBRC_BUFFER_UNKNOWN -> ReqBufferUnknown
      | Some OFPBRC_BAD_TABLE_ID -> ReqBadTableId
      | Some OFPBRC_IS_SLAVE -> ReqIsSlave
      | Some OFPBRC_BAD_PORT -> ReqBadPort
      | Some OFPBRC_BAD_PACKET -> ReqBadPacket
      | Some OFPBRC_MULTIPART_BUFFER_OVERFLOW -> ReqMultipartBufOverflow
      | None -> raise (Unparsable (sprintf "malfomed bad_request code"))

  end

  module BadAction = struct

    [%%cenum
    type ofp_bad_action_code =
      | OFPBAC_BAD_TYPE [@id 0]
      | OFPBAC_BAD_LEN [@id 1]
      | OFPBAC_BAD_EXPERIMENTER [@id 2]
      | OFPBAC_BAD_EXP_TYPE [@id 3]
      | OFPBAC_BAD_OUT_PORT [@id 4]
      | OFPBAC_BAD_ARGUMENT [@id 5]
      | OFPBAC_EPERM [@id 6]
      | OFPBAC_TOO_MANY [@id 7]
      | OFPBAC_BAD_QUEUE [@id 8]
      | OFPBAC_BAD_OUT_GROUP [@id 9]
      | OFPBAC_MATCH_INCONSISTENT [@id 10]
      | OFPBAC_UNSUPPORTED_ORDER [@id 11]
      | OFPBAC_BAD_TAG [@id 12]
      | OFPBAC_BAD_SET_TYPE [@id 13]
      | OFPBAC_BAD_SET_LEN [@id 14]
      | OFPBAC_BAD_SET_ARGUMENT [@id 15]
      [@@uint16_t]
    ]

    type t = badAction

    let to_string (cod : badAction) : string =
      match cod with
      | ActBadType -> "BadType"
      | ActBadLen -> "BadLen"
      | ActBadExp -> "Unknown experimenter id specified"
      | ActBadExpType -> "BadExp"
      | ActBadOutPort -> "BadOutPort"
      | ActBadArg -> "BadArg"
      | ActPermError -> "Permission_Error"
      | ActTooMany -> "TooMany"
      | ActBadQueue ->  "BadQueue"
      | ActBadOutGroup ->  "BadOutGroup"
      | ActMatchInconsistent -> "MatchInconsistent"
      | ActUnsupportedOrder -> "UnsupportedOrder"
      | ActBadTag -> "BadTag"
      | ActBadSetTyp -> "BadSetTyp"
      | ActBadSetLen -> "BadSetLen"
      | ActBadSetArg -> "BadSetArg"

    let marshal (cod : badAction) : int =
      match cod with
      | ActBadType -> ofp_bad_action_code_to_int OFPBAC_BAD_TYPE
      | ActBadLen -> ofp_bad_action_code_to_int OFPBAC_BAD_LEN
      | ActBadExp -> ofp_bad_action_code_to_int OFPBAC_BAD_EXPERIMENTER
      | ActBadExpType -> ofp_bad_action_code_to_int OFPBAC_BAD_EXP_TYPE
      | ActBadOutPort -> ofp_bad_action_code_to_int OFPBAC_BAD_OUT_PORT
      | ActBadArg -> ofp_bad_action_code_to_int OFPBAC_BAD_ARGUMENT
      | ActPermError -> ofp_bad_action_code_to_int OFPBAC_EPERM
      | ActTooMany -> ofp_bad_action_code_to_int OFPBAC_TOO_MANY
      | ActBadQueue -> ofp_bad_action_code_to_int OFPBAC_BAD_QUEUE
      | ActBadOutGroup -> ofp_bad_action_code_to_int OFPBAC_BAD_OUT_GROUP
      | ActMatchInconsistent -> ofp_bad_action_code_to_int OFPBAC_MATCH_INCONSISTENT
      | ActUnsupportedOrder -> ofp_bad_action_code_to_int OFPBAC_UNSUPPORTED_ORDER
      | ActBadTag -> ofp_bad_action_code_to_int OFPBAC_BAD_TAG
      | ActBadSetTyp -> ofp_bad_action_code_to_int OFPBAC_BAD_SET_TYPE
      | ActBadSetLen -> ofp_bad_action_code_to_int OFPBAC_BAD_SET_LEN
      | ActBadSetArg -> ofp_bad_action_code_to_int OFPBAC_BAD_SET_ARGUMENT

    let parse t : badAction =
      match int_to_ofp_bad_action_code t with
      | Some OFPBAC_BAD_TYPE -> ActBadType
      | Some OFPBAC_BAD_LEN -> ActBadLen
      | Some OFPBAC_BAD_EXPERIMENTER -> ActBadExp
      | Some OFPBAC_BAD_EXP_TYPE -> ActBadExpType
      | Some OFPBAC_BAD_OUT_PORT -> ActBadOutPort
      | Some OFPBAC_BAD_ARGUMENT -> ActBadArg
      | Some OFPBAC_EPERM -> ActPermError
      | Some OFPBAC_TOO_MANY -> ActTooMany
      | Some OFPBAC_BAD_QUEUE -> ActBadQueue
      | Some OFPBAC_BAD_OUT_GROUP -> ActBadOutGroup
      | Some OFPBAC_MATCH_INCONSISTENT -> ActMatchInconsistent
      | Some OFPBAC_UNSUPPORTED_ORDER -> ActUnsupportedOrder
      | Some OFPBAC_BAD_TAG -> ActBadTag
      | Some OFPBAC_BAD_SET_TYPE -> ActBadSetTyp
      | Some OFPBAC_BAD_SET_LEN -> ActBadSetLen
      | Some OFPBAC_BAD_SET_ARGUMENT -> ActBadSetArg
      | None -> raise (Unparsable (sprintf "malfomed bad_action code"))

  end

  module BadInstruction = struct

    [%%cenum
    type ofp_bad_instruction_code =
      | OFPBIC_UNKNOWN_INST [@id 0]
      | OFPBIC_UNSUP_INST [@id 1]
      | OFPBIC_BAD_TABLE_ID [@id 2]
      | OFPBIC_UNSUP_METADATA [@id 3]
      | OFPBIC_UNSUP_METADATA_MASK [@id 4]
      | OFPBIC_BAD_EXPERIMENTER [@id 5]
      | OFPBIC_BAD_EXP_TYPE [@id 6]
      | OFPBIC_BAD_LEN [@id 7]
      | OFPBIC_EPERM [@id 8]
      [@@uint16_t]
    ]

    type t = badInstruction

    let to_string (cod : badInstruction) : string =
      match cod with
      | InstUnknownInst -> "UnknownInst"
      | InstUnsupInst -> "UnsupInst"
      | InstBadTableId -> "BadTableId"
      | InstUnsupMeta -> "UnsupMeta"
      | InstUnsupMetaMask -> "UnsupMetaMask"
      | InstBadExp -> "BadExp"
      | InstBadExpTyp -> "BadExpTyp"
      | InstBadLen -> "BadLen"
      | InstPermError -> "Permission_Error"

    let marshal (cod : badInstruction) : int =
      match cod with
      | InstUnknownInst -> ofp_bad_instruction_code_to_int OFPBIC_UNKNOWN_INST
      | InstBadTableId -> ofp_bad_instruction_code_to_int OFPBIC_BAD_TABLE_ID
      | InstUnsupInst -> ofp_bad_instruction_code_to_int OFPBIC_UNSUP_INST
      | InstUnsupMeta -> ofp_bad_instruction_code_to_int OFPBIC_UNSUP_METADATA
      | InstUnsupMetaMask -> ofp_bad_instruction_code_to_int OFPBIC_UNSUP_METADATA_MASK
      | InstBadExp -> ofp_bad_instruction_code_to_int OFPBIC_BAD_EXPERIMENTER
      | InstBadExpTyp -> ofp_bad_instruction_code_to_int OFPBIC_BAD_EXP_TYPE
      | InstBadLen -> ofp_bad_instruction_code_to_int OFPBIC_BAD_LEN
      | InstPermError -> ofp_bad_instruction_code_to_int OFPBIC_EPERM

    let parse t : badInstruction =
      match int_to_ofp_bad_instruction_code t with
      | Some OFPBIC_UNKNOWN_INST -> InstUnknownInst
      | Some OFPBIC_BAD_TABLE_ID -> InstBadTableId
      | Some OFPBIC_UNSUP_INST -> InstUnsupInst
      | Some OFPBIC_UNSUP_METADATA -> InstUnsupMeta
      | Some OFPBIC_UNSUP_METADATA_MASK -> InstUnsupMetaMask
      | Some OFPBIC_BAD_EXPERIMENTER -> InstBadExp
      | Some OFPBIC_BAD_EXP_TYPE -> InstBadExpTyp
      | Some OFPBIC_BAD_LEN -> InstBadLen
      | Some OFPBIC_EPERM -> InstPermError
      | None -> raise (Unparsable (sprintf "malfomed bad_instruction code"))

  end

  module BadMatch = struct

    [%%cenum
    type ofp_bad_match_code =
      | OFPBMC_BAD_TYPE [@id 0]
      | OFPBMC_BAD_LEN [@id 1]
      | OFPBMC_BAD_TAG [@id 2]
      | OFPBMC_BAD_DL_ADDR_MASK [@id 3]
      | OFPBMC_BAD_NW_ADDR_MASK [@id 4]
      | OFPBMC_BAD_WILDCARDS [@id 5]
      | OFPBMC_BAD_FIELD [@id 6]
      | OFPBMC_BAD_VALUE [@id 7]
      | OFPBMC_BAD_MASK [@id 8]
      | OFPBMC_BAD_PREREQ [@id 9]
      | OFPBMC_DUP_FIELD [@id 10]
      | OFPBMC_EPERM [@id 11]
      [@@uint16_t]
    ]

    type t = badMatch

    let to_string (cod : badMatch) : string =
      match cod with
      | MatBadTyp -> "BadTyp"
      | MatBadLen -> "BadLen"
      | MatBadTag -> "BadTag"
      | MatBadDlAddrMask -> "BadDlAddrMask"
      | MatBadNwAddrMask -> "BadNwAddrMask"
      | MatBadWildcards -> "BadWildcards"
      | MatBadField -> "BadField"
      | MatBadValue -> "BadValue"
      | MatBadMask -> "BadMask"
      | MatBadPrereq -> "BadPrereq"
      | MatDupField -> "DupField"
      | MatPermError -> "Permission_Error"

    let marshal (cod : badMatch) : int =
      match cod with
      | MatBadTyp -> ofp_bad_match_code_to_int OFPBMC_BAD_TYPE
      | MatBadLen -> ofp_bad_match_code_to_int OFPBMC_BAD_LEN
      | MatBadTag -> ofp_bad_match_code_to_int OFPBMC_BAD_TAG
      | MatBadDlAddrMask -> ofp_bad_match_code_to_int OFPBMC_BAD_DL_ADDR_MASK
      | MatBadNwAddrMask -> ofp_bad_match_code_to_int OFPBMC_BAD_NW_ADDR_MASK
      | MatBadWildcards -> ofp_bad_match_code_to_int OFPBMC_BAD_WILDCARDS
      | MatBadField -> ofp_bad_match_code_to_int OFPBMC_BAD_FIELD
      | MatBadValue -> ofp_bad_match_code_to_int OFPBMC_BAD_VALUE
      | MatBadMask -> ofp_bad_match_code_to_int OFPBMC_BAD_MASK
      | MatBadPrereq -> ofp_bad_match_code_to_int OFPBMC_BAD_PREREQ
      | MatDupField -> ofp_bad_match_code_to_int OFPBMC_DUP_FIELD
      | MatPermError -> ofp_bad_match_code_to_int OFPBMC_EPERM

    let parse t : badMatch =
      match int_to_ofp_bad_match_code t with
      | Some OFPBMC_BAD_TYPE -> MatBadTyp
      | Some OFPBMC_BAD_LEN -> MatBadLen
      | Some OFPBMC_BAD_TAG -> MatBadTag
      | Some OFPBMC_BAD_DL_ADDR_MASK -> MatBadDlAddrMask
      | Some OFPBMC_BAD_NW_ADDR_MASK -> MatBadNwAddrMask
      | Some OFPBMC_BAD_WILDCARDS -> MatBadWildcards
      | Some OFPBMC_BAD_FIELD -> MatBadField
      | Some OFPBMC_BAD_VALUE -> MatBadValue
      | Some OFPBMC_BAD_MASK -> MatBadMask
      | Some OFPBMC_BAD_PREREQ -> MatBadPrereq
      | Some OFPBMC_DUP_FIELD -> MatDupField
      | Some OFPBMC_EPERM -> MatPermError
      | None -> raise (Unparsable (sprintf "malfomed bad_match code"))

  end

  module FlowModFailed = struct

    [%%cenum
    type ofp_flow_mod_failed_code =
      | OFPFMFC_UNKNOWN [@id 0]
      | OFPFMFC_TABLE_FULL [@id 1]
      | OFPFMFC_BAD_TABLE_ID [@id 2]
      | OFPFMFC_OVERLAP [@id 3]
      | OFPFMFC_EPERM [@id 4]
      | OFPFMFC_BAD_TIMEOUT [@id 5]
      | OFPFMFC_BAD_COMMAND [@id 6]
      | OFPFMFC_BAD_FLAGS [@id 7]
      [@@uint16_t]
    ]

    type t = flowModFailed

    let to_string (cod : flowModFailed) : string =
      match cod with
      | FlUnknown -> "Unknown"
      | FlTableFull -> "TableFull"
      | FlBadTableId -> "BadTableId"
      | FlOverlap -> "Overlap"
      | FlPermError -> "Permission_Error"
      | FlBadTimeout -> "BadTimeout"
      | FlBadCommand -> "BadCommand"
      | FlBadFlags  -> "BadFlags"

    let marshal (cod : flowModFailed) : int =
      match cod with
      | FlUnknown -> ofp_flow_mod_failed_code_to_int OFPFMFC_UNKNOWN
      | FlTableFull -> ofp_flow_mod_failed_code_to_int OFPFMFC_TABLE_FULL
      | FlBadTableId -> ofp_flow_mod_failed_code_to_int OFPFMFC_BAD_TABLE_ID
      | FlOverlap -> ofp_flow_mod_failed_code_to_int OFPFMFC_OVERLAP
      | FlPermError -> ofp_flow_mod_failed_code_to_int OFPFMFC_EPERM
      | FlBadTimeout -> ofp_flow_mod_failed_code_to_int OFPFMFC_BAD_TIMEOUT
      | FlBadCommand -> ofp_flow_mod_failed_code_to_int OFPFMFC_BAD_COMMAND
      | FlBadFlags  -> ofp_flow_mod_failed_code_to_int OFPFMFC_BAD_FLAGS

    let parse t : flowModFailed =
      match int_to_ofp_flow_mod_failed_code t with
      | Some OFPFMFC_UNKNOWN -> FlUnknown
      | Some OFPFMFC_TABLE_FULL -> FlTableFull
      | Some OFPFMFC_BAD_TABLE_ID -> FlBadTableId
      | Some OFPFMFC_OVERLAP -> FlOverlap
      | Some OFPFMFC_EPERM -> FlPermError
      | Some OFPFMFC_BAD_TIMEOUT -> FlBadTimeout
      | Some OFPFMFC_BAD_COMMAND -> FlBadCommand
      | Some OFPFMFC_BAD_FLAGS -> FlBadFlags
      | None -> raise (Unparsable (sprintf "malfomed flow mod failed code"))

  end

  module GroupModFailed = struct

    [%%cenum
    type ofp_group_mod_failed_code =
      | OFPGMFC_GROUP_EXISTS [@id 0]
      | OFPGMFC_INVALID_GROUP [@id 1]
      | OFPGMFC_WEIGHT_UNSUPPORTED [@id 2]
      | OFPGMFC_OUT_OF_GROUPS [@id 3]
      | OFPGMFC_OUT_OF_BUCKETS [@id 4]
      | OFPGMFC_CHAINING_UNSUPPORTED [@id 5]
      | OFPGMFC_WATCH_UNSUPPORTED [@id 6]
      | OFPGMFC_LOOP [@id 7]
      | OFPGMFC_UNKNOWN_GROUP [@id 8]
      | OFPGMFC_CHAINED_GROUP [@id 9]
      | OFPGMFC_BAD_TYPE [@id 10]
      | OFPGMFC_BAD_COMMAND [@id 11]
      | OFPGMFC_BAD_BUCKET [@id 12]
      | OFPGMFC_BAD_WATCH [@id 13]
      | OFPGMFC_EPERM [@id 14]
      [@@uint16_t]
    ]

    type t = groupModFailed

    let to_string (cod : groupModFailed) : string =
      match cod with
      | GrGroupExists -> "GroupExists"
      | GrInvalidGroup -> "InvalidGroup"
      | GrWeightUnsupported -> "WeightUnsupported"
      | GrOutOfGroups -> "OutOfGroups"
      | GrOutOfBuckets -> "OutOfBuckets"
      | GrChainingUnsupported -> "ChainingUnsupported"
      | GrWatchUnsupported -> "WatchUnsupported"
      | GrLoop -> "Loop"
      | GrUnknownGroup -> "UnknownGroup"
      | GrChainedGroup -> "ChainedGroup"
      | GrBadTyp -> "BadTyp"
      | GrBadCommand -> "BadCommand"
      | GrBadBucket -> "BadBucket"
      | GrBadWatch -> "BadWatch"
      | GrPermError -> "Permission_Error"

    let marshal (cod : groupModFailed) : int =
      match cod with
      | GrGroupExists -> ofp_group_mod_failed_code_to_int OFPGMFC_GROUP_EXISTS
      | GrInvalidGroup -> ofp_group_mod_failed_code_to_int OFPGMFC_INVALID_GROUP
      | GrWeightUnsupported -> ofp_group_mod_failed_code_to_int OFPGMFC_WEIGHT_UNSUPPORTED
      | GrOutOfGroups -> ofp_group_mod_failed_code_to_int OFPGMFC_OUT_OF_GROUPS
      | GrOutOfBuckets -> ofp_group_mod_failed_code_to_int OFPGMFC_OUT_OF_BUCKETS
      | GrChainingUnsupported -> ofp_group_mod_failed_code_to_int OFPGMFC_CHAINING_UNSUPPORTED
      | GrWatchUnsupported -> ofp_group_mod_failed_code_to_int OFPGMFC_WATCH_UNSUPPORTED
      | GrLoop -> ofp_group_mod_failed_code_to_int OFPGMFC_LOOP
      | GrUnknownGroup -> ofp_group_mod_failed_code_to_int OFPGMFC_UNKNOWN_GROUP
      | GrChainedGroup -> ofp_group_mod_failed_code_to_int OFPGMFC_CHAINED_GROUP
      | GrBadTyp -> ofp_group_mod_failed_code_to_int OFPGMFC_BAD_TYPE
      | GrBadCommand -> ofp_group_mod_failed_code_to_int OFPGMFC_BAD_COMMAND
      | GrBadBucket -> ofp_group_mod_failed_code_to_int OFPGMFC_BAD_BUCKET
      | GrBadWatch -> ofp_group_mod_failed_code_to_int OFPGMFC_BAD_WATCH
      | GrPermError -> ofp_group_mod_failed_code_to_int OFPGMFC_EPERM

    let parse t : groupModFailed =
      match int_to_ofp_group_mod_failed_code t with
      | Some OFPGMFC_GROUP_EXISTS -> GrGroupExists
      | Some OFPGMFC_INVALID_GROUP -> GrInvalidGroup
      | Some OFPGMFC_WEIGHT_UNSUPPORTED -> GrWeightUnsupported
      | Some OFPGMFC_OUT_OF_GROUPS -> GrOutOfGroups
      | Some OFPGMFC_OUT_OF_BUCKETS -> GrOutOfBuckets
      | Some OFPGMFC_CHAINING_UNSUPPORTED -> GrChainingUnsupported
      | Some OFPGMFC_WATCH_UNSUPPORTED -> GrWatchUnsupported
      | Some OFPGMFC_LOOP -> GrLoop
      | Some OFPGMFC_UNKNOWN_GROUP -> GrUnknownGroup
      | Some OFPGMFC_CHAINED_GROUP -> GrChainedGroup
      | Some OFPGMFC_BAD_TYPE -> GrBadTyp
      | Some OFPGMFC_BAD_COMMAND -> GrBadCommand
      | Some OFPGMFC_BAD_BUCKET -> GrBadBucket
      | Some OFPGMFC_BAD_WATCH -> GrBadWatch
      | Some OFPGMFC_EPERM -> GrPermError
      | None -> raise (Unparsable (sprintf "malfomed group mod failed code"))

  end

  module PortModFailed = struct

    [%%cenum
    type ofp_port_mod_failed_code =
      | OFPPMFC_BAD_PORT [@id 0]
      | OFPPMFC_BAD_HW_ADDR [@id 1]
      | OFPPMFC_BAD_CONFIG [@id 2]
      | OFPPMFC_BAD_ADVERTISE [@id 3]
      | OFPPMFC_EPERM [@id 4]
      [@@uint16_t]
    ]

    type t = portModFailed

    let to_string (cod : portModFailed) : string =
      match cod with
      | PoBadPort -> "BadPort"
      | PoBadHwAddr -> "BadHwAddr"
      | PoBadConfig -> "BadConfig"
      | PoBadAdvertise -> "BadAdvertise"
      | PoPermError -> "Permission_Error"

    let marshal (cod : portModFailed) : int =
      match cod with
      | PoBadPort -> ofp_port_mod_failed_code_to_int OFPPMFC_BAD_PORT
      | PoBadHwAddr -> ofp_port_mod_failed_code_to_int OFPPMFC_BAD_HW_ADDR
      | PoBadConfig -> ofp_port_mod_failed_code_to_int OFPPMFC_BAD_CONFIG
      | PoBadAdvertise -> ofp_port_mod_failed_code_to_int OFPPMFC_BAD_ADVERTISE
      | PoPermError -> ofp_port_mod_failed_code_to_int OFPPMFC_EPERM

    let parse t : portModFailed =
      match int_to_ofp_port_mod_failed_code t with
      | Some OFPPMFC_BAD_PORT -> PoBadPort
      | Some OFPPMFC_BAD_HW_ADDR -> PoBadHwAddr
      | Some OFPPMFC_BAD_CONFIG -> PoBadConfig
      | Some OFPPMFC_BAD_ADVERTISE -> PoBadAdvertise
      | Some OFPPMFC_EPERM -> PoPermError
      | None -> raise (Unparsable (sprintf "malfomed port mod failed code"))

  end

  module TableModFailed = struct

    [%%cenum
    type ofp_table_mod_failed_code =
      | OFPTMFC_BAD_TABLE [@id 0]
      | OFPTMFC_BAD_CONFIG [@id 1]
      | OFPTMFC_EPERM [@id 2]
      [@@uint16_t]
    ]

    type t = tableModFailed

    let to_string (cod : tableModFailed) : string =
      match cod with
      | TaBadTable -> "BadTable"
      | TaBadConfig -> "BadConfig"
      | TaPermError -> "Permission_Error"

    let marshal (cod : tableModFailed) : int =
      match cod with
      | TaBadTable -> ofp_table_mod_failed_code_to_int OFPTMFC_BAD_TABLE
      | TaBadConfig -> ofp_table_mod_failed_code_to_int OFPTMFC_BAD_CONFIG
      | TaPermError -> ofp_table_mod_failed_code_to_int OFPTMFC_EPERM

    let parse t : tableModFailed =
      match int_to_ofp_table_mod_failed_code t with
      | Some OFPTMFC_BAD_TABLE -> TaBadTable
      | Some OFPTMFC_BAD_CONFIG -> TaBadConfig
      | Some OFPTMFC_EPERM -> TaPermError
      | None -> raise (Unparsable (sprintf "malfomed table mod failed code"))

  end

  module QueueOpFailed = struct

    [%%cenum
    type ofp_queue_op_failed_code =
      | OFPQOFC_BAD_PORT [@id 0]
      | OFPQOFC_BAD_QUEUE [@id 1]
      | OFPQOFC_EPERM [@id 2]
      [@@uint16_t]
    ]

    type t = queueOpFailed

    let to_string (cod : queueOpFailed) : string =
      match cod with
      | QuBadPort -> "BadPort"
      | QuBadQueue -> "BadQueue"
      | QuPermError -> "Permission_Error"

    let marshal (cod : queueOpFailed) : int =
      match cod with
      | QuBadPort -> ofp_queue_op_failed_code_to_int OFPQOFC_BAD_PORT
      | QuBadQueue -> ofp_queue_op_failed_code_to_int OFPQOFC_BAD_QUEUE
      | QuPermError -> ofp_queue_op_failed_code_to_int OFPQOFC_EPERM

    let parse t : queueOpFailed =
      match int_to_ofp_queue_op_failed_code t with
      | Some OFPQOFC_BAD_PORT -> QuBadPort
      | Some OFPQOFC_BAD_QUEUE -> QuBadQueue
      | Some OFPQOFC_EPERM -> QuPermError
      | None -> raise (Unparsable (sprintf "malfomed queue op failed code"))

  end

  module SwitchConfigFailed = struct

    [%%cenum
    type ofp_switch_config_failed_code =
      | OFPSCFC_BAD_FLAGS [@id 0]
      | OFPSCFC_BAD_LEN [@id 1]
      | OFPSCFC_EPERM [@id 2]
      [@@uint16_t]
    ]

    type t = switchConfigFailed

    let to_string (cod : switchConfigFailed) : string =
      match cod with
      | ScBadFlags ->  "BadFlags"
      | ScBadLen -> "BadLen"
      | ScPermError -> "Permission_Error"

    let marshal (cod : switchConfigFailed) : int =
      match cod with
      | ScBadFlags ->  ofp_switch_config_failed_code_to_int OFPSCFC_BAD_FLAGS
      | ScBadLen -> ofp_switch_config_failed_code_to_int OFPSCFC_BAD_LEN
      | ScPermError -> ofp_switch_config_failed_code_to_int OFPSCFC_EPERM

    let parse t : switchConfigFailed =
      match int_to_ofp_switch_config_failed_code t with
      | Some OFPSCFC_BAD_FLAGS -> ScBadFlags
      | Some OFPSCFC_BAD_LEN -> ScBadLen
      | Some OFPSCFC_EPERM -> ScPermError
      | None -> raise (Unparsable (sprintf "malfomed switch config failed code"))

  end

  module RoleReqFailed = struct

    [%%cenum
    type ofp_role_request_failed_code =
      | OFPRRFC_STALE [@id 0]
      | OFPRRFC_UNSUP [@id 1]
      | OFPRRFC_BAD_ROLE [@id 2]
      [@@uint16_t]
    ]

    type t = roleReqFailed

    let to_string (cod : roleReqFailed) : string =
      match cod with
      | RoStale -> "Stale"
      | RoUnsup -> "Unsup"
      | RoBadRole -> "BadRole"

    let marshal (cod : roleReqFailed) : int =
      match cod with
      | RoStale -> ofp_role_request_failed_code_to_int OFPRRFC_STALE
      | RoUnsup -> ofp_role_request_failed_code_to_int OFPRRFC_UNSUP
      | RoBadRole -> ofp_role_request_failed_code_to_int OFPRRFC_BAD_ROLE

    let parse t : roleReqFailed =
      match int_to_ofp_role_request_failed_code t with
      | Some OFPRRFC_STALE -> RoStale
      | Some OFPRRFC_UNSUP -> RoUnsup
      | Some OFPRRFC_BAD_ROLE -> RoBadRole
      | None -> raise (Unparsable (sprintf "malfomed role request failed code"))

  end

  module MeterModFailed = struct

    [%%cenum
    type ofp_meter_mod_failed_code =
      | OFPMMFC_UNKNOWN [@id 0]
      | OFPMMFC_METER_EXISTS [@id 1]
      | OFPMMFC_INVALID_METER [@id 2]
      | OFPMMFC_UNKNOWN_METER [@id 3]
      | OFPMMFC_BAD_COMMAND [@id 4]
      | OFPMMFC_BAD_FLAGS [@id 5]
      | OFPMMFC_BAD_RATE [@id 6]
      | OFPMMFC_BAD_BURST [@id 7]
      | OFPMMFC_BAD_BAND [@id 8]
      | OFPMMFC_BAD_BAND_VALUE [@id 9]
      | OFPMMFC_OUT_OF_METERS [@id 10]
      | OFPMMFC_OUT_OF_BANDS [@id 11]
      [@@uint16_t]
    ]

    type t = meterModFailed

    let to_string (cod : meterModFailed) : string =
      match cod with
      | MeUnknown -> "Unknown"
      | MeMeterExists -> "MeterExists"
      | MeInvalidMeter -> "InvalidMeter"
      | MeUnknownMeter -> "UnknownMeter"
      | MeBadCommand -> "BadCommand"
      | MeBadFlags -> "BadFlags"
      | MeBadRate -> "BadRate"
      | MeBadBurst -> "BadBurst"
      | MeBadBand -> "BadBand"
      | MeBadBandValue -> "BadBandValue"
      | MeOutOfMeters -> "OutOfMeters"
      | MeOutOfBands -> "OutOfBands"

    let marshal (cod : meterModFailed) : int =
      match cod with
      | MeUnknown -> ofp_meter_mod_failed_code_to_int OFPMMFC_UNKNOWN
      | MeMeterExists -> ofp_meter_mod_failed_code_to_int OFPMMFC_METER_EXISTS
      | MeInvalidMeter -> ofp_meter_mod_failed_code_to_int OFPMMFC_INVALID_METER
      | MeUnknownMeter -> ofp_meter_mod_failed_code_to_int OFPMMFC_UNKNOWN_METER
      | MeBadCommand -> ofp_meter_mod_failed_code_to_int OFPMMFC_BAD_COMMAND
      | MeBadFlags -> ofp_meter_mod_failed_code_to_int OFPMMFC_BAD_FLAGS
      | MeBadRate -> ofp_meter_mod_failed_code_to_int OFPMMFC_BAD_RATE
      | MeBadBurst -> ofp_meter_mod_failed_code_to_int OFPMMFC_BAD_BURST
      | MeBadBand -> ofp_meter_mod_failed_code_to_int OFPMMFC_BAD_BAND
      | MeBadBandValue -> ofp_meter_mod_failed_code_to_int OFPMMFC_BAD_BAND_VALUE
      | MeOutOfMeters -> ofp_meter_mod_failed_code_to_int OFPMMFC_OUT_OF_METERS
      | MeOutOfBands -> ofp_meter_mod_failed_code_to_int OFPMMFC_OUT_OF_BANDS

    let parse t : meterModFailed =
      match int_to_ofp_meter_mod_failed_code t with
      | Some OFPMMFC_UNKNOWN -> MeUnknown
      | Some OFPMMFC_METER_EXISTS -> MeMeterExists
      | Some OFPMMFC_INVALID_METER -> MeInvalidMeter
      | Some OFPMMFC_UNKNOWN_METER -> MeUnknownMeter
      | Some OFPMMFC_BAD_COMMAND -> MeBadCommand
      | Some OFPMMFC_BAD_FLAGS -> MeBadFlags
      | Some OFPMMFC_BAD_RATE -> MeBadRate
      | Some OFPMMFC_BAD_BURST -> MeBadBurst
      | Some OFPMMFC_BAD_BAND -> MeBadBand
      | Some OFPMMFC_BAD_BAND_VALUE -> MeBadBandValue
      | Some OFPMMFC_OUT_OF_METERS -> MeOutOfMeters
      | Some OFPMMFC_OUT_OF_BANDS -> MeOutOfBands
      | None -> raise (Unparsable (sprintf "malfomed meter mod failed code"))

  end

  module TableFeatFailed = struct

    [%%cenum
    type ofp_table_features_failed_code =
      | OFPTFFC_BAD_TABLE [@id 0]
      | OFPTFFC_BAD_METADATA [@id 1]
      | OFPTFFC_BAD_TYPE [@id 2]
      | OFPTFFC_BAD_LEN [@id 3]
      | OFPTFFC_BAD_ARGUMENT [@id 4]
      | OFPTFFC_EPERM [@id 5]
      [@@uint16_t]
    ]

    type t = tableFeatFailed

    let to_string (cod : tableFeatFailed) : string =
      match cod with
      | TfBadTable -> "BadTable"
      | TfBadMeta -> "BadMeta"
      | TfBadType -> "BadType"
      | TfBadLen -> "BadLen"
      | TfBadArg -> "BadArg"
      | TfPermError -> "Permission_Error"

    let marshal (cod : tableFeatFailed) : int =
      match cod with
      | TfBadTable -> ofp_table_features_failed_code_to_int OFPTFFC_BAD_TABLE
      | TfBadMeta -> ofp_table_features_failed_code_to_int OFPTFFC_BAD_METADATA
      | TfBadType -> ofp_table_features_failed_code_to_int OFPTFFC_BAD_TYPE
      | TfBadLen -> ofp_table_features_failed_code_to_int OFPTFFC_BAD_LEN
      | TfBadArg -> ofp_table_features_failed_code_to_int OFPTFFC_BAD_ARGUMENT
      | TfPermError -> ofp_table_features_failed_code_to_int OFPTFFC_EPERM

    let parse t : tableFeatFailed =
      match int_to_ofp_table_features_failed_code t with
      | Some OFPTFFC_BAD_TABLE -> TfBadTable
      | Some OFPTFFC_BAD_METADATA -> TfBadMeta
      | Some OFPTFFC_BAD_TYPE -> TfBadType
      | Some OFPTFFC_BAD_LEN -> TfBadLen
      | Some OFPTFFC_BAD_ARGUMENT -> TfBadArg
      | Some OFPTFFC_EPERM -> TfPermError
      | None -> raise (Unparsable (sprintf "malfomed table features failed code"))

  end

  [%%cstruct
  type ofp_error_experimenter_msg = {
    typ: uint16_t ;
    exp_type: uint16_t ;
    experimenter: uint32_t
  } [@@big_endian]]

  let experimenterFailed_to_string (exp : experimenterFailed) : string =
    Format.sprintf "Exp type : %u; exp ID: %lu"
      exp.exp_typ
      exp.exp_id

  let to_string (t : t) : string =
    match t.err with
    | HelloFailed h -> Format.sprintf "Hello Failed error, code: %s" (HelloFailed.to_string h)
    | BadRequest br -> Format.sprintf "Bad Request error, code: %s" (BadRequest.to_string br)
    | BadAction ba -> Format.sprintf "Bad Action error, code: %s" (BadAction.to_string ba)
    | BadInstruction bi -> Format.sprintf "Bad Instruction error, code: %s" (BadInstruction.to_string bi)
    | BadMatch bm -> Format.sprintf "Bad Match error, code: %s" (BadMatch.to_string bm)
    | FlowModFailed fm -> Format.sprintf "Flow Mod Failed error, code: %s" (FlowModFailed.to_string fm)
    | GroupModFailed gm -> Format.sprintf "Group Mod Failed error, code: %s" (GroupModFailed.to_string gm)
    | PortModFailed pm -> Format.sprintf "Port Mod Failed error, code: %s" (PortModFailed.to_string pm)
    | TableModFailed tm -> Format.sprintf "Table Mod Failed error, code: %s" (TableModFailed.to_string tm)
    | QueueOpFailed qo -> Format.sprintf "Queue Op Failed error, code: %s" (QueueOpFailed.to_string qo)
    | SwitchConfigFailed sc -> Format.sprintf "Switch Config Failed error, code: %s" (SwitchConfigFailed.to_string sc)
    | RoleReqFailed rr -> Format.sprintf "Role Request Failed error, code: %s" (RoleReqFailed.to_string rr)
    | MeterModFailed mm -> Format.sprintf "Meter Mod Failed error, code: %s" (MeterModFailed.to_string mm)
    | TableFeatFailed tf -> Format.sprintf "Table Features Failed error, code: %s" (TableFeatFailed.to_string tf)
    | ExperimenterFailed e -> Format.sprintf "Experimenter Failed error, code: %s" (experimenterFailed_to_string e)

  let sizeof (t : t) : int =
    match t.err with
    | ExperimenterFailed _ -> sizeof_ofp_error_experimenter_msg + (Cstruct.length t.data)
    | _ -> sizeof_ofp_error_msg + (Cstruct.length t.data)

  let marshal (buf : Cstruct_sexp.t) (t : t) : int =
    match t.err with
    | HelloFailed h ->
      set_ofp_error_msg_typ buf (ofp_error_type_to_int OFPET_HELLO_FAILED);
      set_ofp_error_msg_code buf (HelloFailed.marshal h);
      let dataBuf = Cstruct.shift buf sizeof_ofp_error_msg in
      Cstruct.blit t.data 0 dataBuf 0 (Cstruct.length t.data);
      sizeof_ofp_error_msg + (Cstruct.length t.data)
    | BadRequest br ->
      set_ofp_error_msg_typ buf (ofp_error_type_to_int OFPET_BAD_REQUEST);
      set_ofp_error_msg_code buf (BadRequest.marshal br);
      let dataBuf = Cstruct.shift buf sizeof_ofp_error_msg in
      Cstruct.blit t.data 0 dataBuf 0 (Cstruct.length t.data);
      sizeof_ofp_error_msg + (Cstruct.length t.data)
    | BadAction ba ->
      set_ofp_error_msg_typ buf (ofp_error_type_to_int OFPET_BAD_ACTION);
      set_ofp_error_msg_code buf (BadAction.marshal ba);
      let dataBuf = Cstruct.shift buf sizeof_ofp_error_msg in
      Cstruct.blit t.data 0 dataBuf 0 (Cstruct.length t.data);
      sizeof_ofp_error_msg + (Cstruct.length t.data)
    | BadInstruction bi ->
      set_ofp_error_msg_typ buf (ofp_error_type_to_int OFPET_BAD_INSTRUCTION);
      set_ofp_error_msg_code buf (BadInstruction.marshal bi);
      let dataBuf = Cstruct.shift buf sizeof_ofp_error_msg in
      Cstruct.blit t.data 0 dataBuf 0 (Cstruct.length t.data);
      sizeof_ofp_error_msg + (Cstruct.length t.data)
    | BadMatch bm ->
      set_ofp_error_msg_typ buf (ofp_error_type_to_int OFPET_BAD_MATCH);
      set_ofp_error_msg_code buf (BadMatch.marshal bm);
      let dataBuf = Cstruct.shift buf sizeof_ofp_error_msg in
      Cstruct.blit t.data 0 dataBuf 0 (Cstruct.length t.data);
      sizeof_ofp_error_msg + (Cstruct.length t.data)
    | FlowModFailed fm ->
      set_ofp_error_msg_typ buf (ofp_error_type_to_int OFPET_FLOW_MOD_FAILED);
      set_ofp_error_msg_code buf (FlowModFailed.marshal fm);
      let dataBuf = Cstruct.shift buf sizeof_ofp_error_msg in
      Cstruct.blit t.data 0 dataBuf 0 (Cstruct.length t.data);
      sizeof_ofp_error_msg + (Cstruct.length t.data)
    | GroupModFailed gm ->
      set_ofp_error_msg_typ buf (ofp_error_type_to_int OFPET_GROUP_MOD_FAILED);
      set_ofp_error_msg_code buf (GroupModFailed.marshal gm);
      let dataBuf = Cstruct.shift buf sizeof_ofp_error_msg in
      Cstruct.blit t.data 0 dataBuf 0 (Cstruct.length t.data);
      sizeof_ofp_error_msg + (Cstruct.length t.data)
    | PortModFailed pm ->
      set_ofp_error_msg_typ buf (ofp_error_type_to_int OFPET_PORT_MOD_FAILED);
      set_ofp_error_msg_code buf (PortModFailed.marshal pm);
      let dataBuf = Cstruct.shift buf sizeof_ofp_error_msg in
      Cstruct.blit t.data 0 dataBuf 0 (Cstruct.length t.data);
      sizeof_ofp_error_msg + (Cstruct.length t.data)
    | TableModFailed tm ->
      set_ofp_error_msg_typ buf (ofp_error_type_to_int OFPET_TABLE_MOD_FAILED);
      set_ofp_error_msg_code buf (TableModFailed.marshal tm);
      let dataBuf = Cstruct.shift buf sizeof_ofp_error_msg in
      Cstruct.blit t.data 0 dataBuf 0 (Cstruct.length t.data);
      sizeof_ofp_error_msg + (Cstruct.length t.data)
    | QueueOpFailed qo ->
      set_ofp_error_msg_typ buf (ofp_error_type_to_int OFPET_QUEUE_OP_FAILED);
      set_ofp_error_msg_code buf (QueueOpFailed.marshal qo);
      let dataBuf = Cstruct.shift buf sizeof_ofp_error_msg in
      Cstruct.blit t.data 0 dataBuf 0 (Cstruct.length t.data);
      sizeof_ofp_error_msg + (Cstruct.length t.data)
    | SwitchConfigFailed sc ->
      set_ofp_error_msg_typ buf (ofp_error_type_to_int OFPET_SWITCH_CONFIG_FAILED);
      set_ofp_error_msg_code buf (SwitchConfigFailed.marshal sc);
      let dataBuf = Cstruct.shift buf sizeof_ofp_error_msg in
      Cstruct.blit t.data 0 dataBuf 0 (Cstruct.length t.data);
      sizeof_ofp_error_msg + (Cstruct.length t.data)
    | RoleReqFailed rr ->
      set_ofp_error_msg_typ buf (ofp_error_type_to_int OFPET_ROLE_REQUEST_FAILED);
      set_ofp_error_msg_code buf (RoleReqFailed.marshal rr);
      let dataBuf = Cstruct.shift buf sizeof_ofp_error_msg in
      Cstruct.blit t.data 0 dataBuf 0 (Cstruct.length t.data);
      sizeof_ofp_error_msg + (Cstruct.length t.data)
    | MeterModFailed mm ->
      set_ofp_error_msg_typ buf (ofp_error_type_to_int OFPET_METER_MOD_FAILED);
      set_ofp_error_msg_code buf (MeterModFailed.marshal mm);
      let dataBuf = Cstruct.shift buf sizeof_ofp_error_msg in
      Cstruct.blit t.data 0 dataBuf 0 (Cstruct.length t.data);
      sizeof_ofp_error_msg + (Cstruct.length t.data)
    | TableFeatFailed tf ->
      set_ofp_error_msg_typ buf (ofp_error_type_to_int OFPET_TABLE_FEATURES_FAILED);
      set_ofp_error_msg_code buf (TableFeatFailed.marshal tf);
      let dataBuf = Cstruct.shift buf sizeof_ofp_error_msg in
      Cstruct.blit t.data 0 dataBuf 0 (Cstruct.length t.data);
      sizeof_ofp_error_msg + (Cstruct.length t.data)
    | ExperimenterFailed e ->
      set_ofp_error_experimenter_msg_typ buf (ofp_error_type_to_int OFPET_EXPERIMENTER);
      set_ofp_error_experimenter_msg_exp_type buf e.exp_typ;
      set_ofp_error_experimenter_msg_experimenter buf e.exp_id;
      let dataBuf = Cstruct.shift buf sizeof_ofp_error_experimenter_msg in
      Cstruct.blit t.data 0 dataBuf 0 (Cstruct.length t.data);
      sizeof_ofp_error_experimenter_msg + (Cstruct.length t.data)

  let parse (bits : Cstruct_sexp.t) : t =
    let typ = get_ofp_error_msg_typ bits in
    let code = get_ofp_error_msg_code bits in
    let err =  match int_to_ofp_error_type typ with
      | Some OFPET_HELLO_FAILED -> HelloFailed (HelloFailed.parse code)
      | Some OFPET_BAD_REQUEST -> BadRequest (BadRequest.parse code)
      | Some OFPET_BAD_ACTION -> BadAction (BadAction.parse code)
      | Some OFPET_BAD_INSTRUCTION -> BadInstruction (BadInstruction.parse code)
      | Some OFPET_BAD_MATCH -> BadMatch (BadMatch.parse code)
      | Some OFPET_FLOW_MOD_FAILED -> FlowModFailed (FlowModFailed.parse code)
      | Some OFPET_GROUP_MOD_FAILED -> GroupModFailed (GroupModFailed.parse code)
      | Some OFPET_PORT_MOD_FAILED -> PortModFailed (PortModFailed.parse code)
      | Some OFPET_TABLE_MOD_FAILED -> TableModFailed (TableModFailed.parse code)
      | Some OFPET_QUEUE_OP_FAILED -> QueueOpFailed (QueueOpFailed.parse code)
      | Some OFPET_SWITCH_CONFIG_FAILED -> SwitchConfigFailed (SwitchConfigFailed.parse code)
      | Some OFPET_ROLE_REQUEST_FAILED -> RoleReqFailed (RoleReqFailed.parse code)
      | Some OFPET_METER_MOD_FAILED -> MeterModFailed (MeterModFailed.parse code)
      | Some OFPET_TABLE_FEATURES_FAILED -> TableFeatFailed (TableFeatFailed.parse code)
      | Some OFPET_EXPERIMENTER -> (
          let exp_typ = get_ofp_error_experimenter_msg_exp_type bits in
          let exp_id = get_ofp_error_experimenter_msg_experimenter bits in
          ExperimenterFailed ({exp_typ; exp_id}) )
      | None -> raise (Unparsable (sprintf "malfomed type error")) in
    let err_bits = match err with
      | ExperimenterFailed _ -> Cstruct.shift bits sizeof_ofp_error_experimenter_msg
      | _ -> Cstruct.shift bits sizeof_ofp_error_msg in
    let data = Cstruct.create (Cstruct.length err_bits) in
    (* create a new cstruct type to set the offset to 0 *)
    Cstruct.blit err_bits 0 data 0 (Cstruct.length err_bits);
    { err; data }

end

module Hello = struct

  module Element = struct

    [%%cstruct
    type ofp_hello_elem_header = {
      typ: uint16_t ;
      len: uint16_t ;
    } [@@big_endian]]

    [%%cenum
    type ofp_hello_elem_type =
      | OFPHET_VERSIONBITMAP [@id 1]
      [@@uint16_t]
    ]

    module VersionBitMap = struct

      type t = supportedList

      let sizeof (l : supportedList) : int =
        match l with
        | [] -> 0
        | t::q -> ((t / 32 ) + 1 ) * 4

      let to_string (l : supportedList) : string =
        let rec printVersion ls =
          match ls with
          | [] -> ""
          | t::q -> Format.sprintf "0x%x;%s" t (printVersion q) in
        printVersion l

      let marshal (buf : Cstruct_sexp.t) (t : supportedList) : int =
        let rec marshal_bitmap (ls : supportedList) acc curr =
          match ls,curr with
          | [],0 ->
            set_ofp_uint32_value buf acc;
          | [],n->
            set_ofp_uint32_value (Cstruct.shift buf (4*n)) acc;
            marshal_bitmap [] 0l (n-1)
          | t::q,n ->
            if t / 32 <> n then (
              set_ofp_uint32_value (Cstruct.shift buf (4*n)) acc;
              marshal_bitmap ls 0l (n-1))
            else (
              let acc = Int32.bit_or (Int32.shift_left 1l (t mod 32)) acc in
              marshal_bitmap q acc n
            ) in
        marshal_bitmap t 0l (List.hd_exn t / 32);
        ((List.hd_exn t / 32) + 1) * 4

      let parse (bits : Cstruct_sexp.t) : supportedList =
        let rec parse_uint32 (bits : Cstruct_sexp.t) index curr (acc : supportedList) : supportedList =
          if Cstruct.length bits < sizeof_ofp_uint32 then acc
          else (
            let acc = if Bits.test_bit index (get_ofp_uint32_value bits) then
                (index+(curr*32))::acc
              else acc in
            if index = 31 then
              parse_uint32 (Cstruct.shift bits 4) 0 (curr+1) acc
            else
              parse_uint32 bits (index+1) (curr) acc) in
        parse_uint32 bits 0 0 []

    end
    type t = element

    let sizeof (t : element) : int =
      let size = sizeof_ofp_hello_elem_header + (
          match t with
          | VersionBitMap v ->
            VersionBitMap.sizeof v) in
      pad_to_64bits size

    let to_string (t : element) : string =
      match t with
      | VersionBitMap v ->
        Format.sprintf "version bitmap: %s" (VersionBitMap.to_string v)

    let length_func (buf : Cstruct_sexp.t) : int option =
      if Cstruct.length buf < sizeof_ofp_hello_elem_header then None
      else Some (pad_to_64bits (get_ofp_hello_elem_header_len buf))

    let marshal (buf : Cstruct_sexp.t) (t : element) : int =
      match t with
      | VersionBitMap v ->
        set_ofp_hello_elem_header_typ buf (ofp_hello_elem_type_to_int OFPHET_VERSIONBITMAP);
        set_ofp_hello_elem_header_len buf (sizeof_ofp_hello_elem_header +
                                           VersionBitMap.marshal (Cstruct.shift buf sizeof_ofp_hello_elem_header) v);
        sizeof t

    let parse (bits : Cstruct_sexp.t) : element =
      let typ = get_ofp_hello_elem_header_typ bits in
      let len = get_ofp_hello_elem_header_len bits in
      let payBits = Cstruct.sub bits sizeof_ofp_hello_elem_header (len - sizeof_ofp_hello_elem_header) in
      match int_to_ofp_hello_elem_type typ with
      | Some OFPHET_VERSIONBITMAP -> VersionBitMap (VersionBitMap.parse payBits)
      | None -> raise (Unparsable (sprintf "malformed type"))

  end

  type t = helloElement

  let sizeof (t : helloElement) : int =
    sum (List.map ~f:Element.sizeof t)

  let to_string (t : helloElement) : string =
    String.concat ~sep:"\n" (List.map ~f:Element.to_string t)

  let marshal (buf : Cstruct_sexp.t) (t : helloElement) : int =
    marshal_fields buf t Element.marshal

  let parse (bits : Cstruct_sexp.t) : helloElement =
    parse_fields bits Element.parse Element.length_func

end

module AsyncConfig = struct

  module PacketIn = struct
    type t = packetInReasonMap

    let to_string (t : t) =
      Format.sprintf "{ table_miss = %B; apply_action = %B; invalid_ttl = %B }"
        t.table_miss
        t.apply_action
        t.invalid_ttl

    let marshal (t : t) : int8 =
      (if t.table_miss then 1 lsl 0 else 0) lor
      (if t.apply_action then 1 lsl 1 else 0) lor
      (if t.invalid_ttl then 1 lsl 2 else 0)

    let parse bits : t =
      { table_miss = test_bit16 0 bits
      ; apply_action = test_bit16 1 bits
      ; invalid_ttl = test_bit16 2 bits}

  end

  module PortStatus = struct

    type t = portReasonMap

    let to_string (t : t) =
      Format.sprintf "{ add  = %B; delete = %B; modify = %B }"
        t.add
        t.delete
        t.modify

    let marshal (t : t) : int8 =
      (if t.add then 1 lsl 0 else 0) lor
      (if t.delete then 1 lsl 1 else 0) lor
      (if t.modify then 1 lsl 2 else 0)

    let parse bits : t =
      { add = test_bit16 0 bits
      ; delete = test_bit16 1 bits
      ; modify = test_bit16 2 bits }

  end

  module FlowRemoved = struct

    type t = flowReasonMask

    let to_string (t : t) =
      Format.sprintf "{ idle_timeout = %B; hard_timeout = %B; delete = %B; \
                      group_delete = %B }"
        t.idle_timeout
        t.hard_timeout
        t.delete
        t.group_delete

    let marshal (t : t) : int8 =
      (if t.idle_timeout then 1 lsl 0 else 0) lor
      (if t.hard_timeout then 1 lsl 1 else 0) lor
      (if t.delete then 1 lsl 2 else 0) lor
      (if t.group_delete then 1 lsl 3 else 0)

    let parse bits : t =
      { idle_timeout = test_bit16 0 bits
      ; hard_timeout = test_bit16 1 bits
      ; delete = test_bit16 2 bits
      ; group_delete = test_bit16 3 bits }

  end

  [%%cstruct
  type ofp_async_config = {
    packet_in_mask0: uint32_t ;
    packet_in_mask1: uint32_t ;
    port_status_mask0: uint32_t ;
    port_status_mask1: uint32_t ;
    flow_removed_mask0: uint32_t ;
    flow_removed_mask1: uint32_t ;
  } [@@big_endian]]

  type t = asyncConfig

  let sizeof (async : asyncConfig) : int =
    sizeof_ofp_async_config

  let to_string (async : asyncConfig) : string =
    Format.sprintf "{ packet_in reason (master/slave) = %s/%s; \
                    port_status reason (master/slave) = %s/%s; \
                    flow_removed reason (master/slave) = %s/%s }"
      (PacketIn.to_string async.packet_in.m_master)
      (PacketIn.to_string async.packet_in.m_slave)
      (PortStatus.to_string async.port_status.m_master)
      (PortStatus.to_string async.port_status.m_slave)
      (FlowRemoved.to_string async.flow_removed.m_master)
      (FlowRemoved.to_string async.flow_removed.m_slave)

  let marshal (buf : Cstruct_sexp.t) (async : asyncConfig) : int =
    set_ofp_async_config_packet_in_mask0 buf (Int32.of_int_exn (PacketIn.marshal async.packet_in.m_master));
    set_ofp_async_config_packet_in_mask1 buf (Int32.of_int_exn (PacketIn.marshal async.packet_in.m_slave));
    set_ofp_async_config_port_status_mask0 buf (Int32.of_int_exn (PortStatus.marshal async.port_status.m_master));
    set_ofp_async_config_port_status_mask1 buf (Int32.of_int_exn (PortStatus.marshal async.port_status.m_slave));
    set_ofp_async_config_flow_removed_mask0 buf (Int32.of_int_exn (FlowRemoved.marshal async.flow_removed.m_master));
    set_ofp_async_config_flow_removed_mask1 buf (Int32.of_int_exn (FlowRemoved.marshal async.flow_removed.m_slave));
    sizeof_ofp_async_config

  let parse (bits : Cstruct_sexp.t) : asyncConfig =
    let packet_in = { m_master = PacketIn.parse (Int32.to_int_exn (get_ofp_async_config_packet_in_mask0 bits));
                      m_slave = PacketIn.parse (Int32.to_int_exn (get_ofp_async_config_packet_in_mask1 bits))} in
    let port_status = { m_master = PortStatus.parse (Int32.to_int_exn (get_ofp_async_config_port_status_mask0 bits));
                        m_slave = PortStatus.parse (Int32.to_int_exn (get_ofp_async_config_port_status_mask1 bits))} in
    let flow_removed = { m_master = FlowRemoved.parse (Int32.to_int_exn (get_ofp_async_config_flow_removed_mask0 bits));
                         m_slave = FlowRemoved.parse (Int32.to_int_exn (get_ofp_async_config_flow_removed_mask1 bits))} in
    { packet_in; port_status; flow_removed }

end

module Message = struct

  type t =
    | Hello of element list
    | EchoRequest of Cstruct_sexp.t
    | EchoReply of Cstruct_sexp.t
    | FeaturesRequest
    | FeaturesReply of switchFeatures
    | FlowModMsg of flowMod
    | GroupModMsg of groupMod
    | PortModMsg of portMod
    | MeterModMsg of meterMod
    | PacketInMsg of packetIn
    | FlowRemoved of flowRemoved
    | PacketOutMsg of packetOut
    | PortStatusMsg of portStatus
    | MultipartReq of multipartRequest
    | MultipartReply of multipartReply
    | BarrierRequest
    | BarrierReply
    | RoleRequest of roleRequest
    | RoleReply of roleRequest
    | QueueGetConfigReq of queueConfReq
    | QueueGetConfigReply of queueConfReply
    | GetConfigRequestMsg
    | GetConfigReplyMsg of switchConfig
    | SetConfigMsg of switchConfig
    | TableModMsg of tableMod
    | GetAsyncRequest
    | GetAsyncReply of asyncConfig
    | SetAsync of asyncConfig
    | Error of error
    [@@deriving sexp]


  let string_of_msg_code (msg : msg_code) : string = match msg with
    | HELLO -> "HELLO"
    | ECHO_REQ -> "ECHO_REQ"
    | ECHO_RESP -> "ECHO_RESP"
    | FEATURES_REQ -> "FEATURES_REQ"
    | FEATURES_RESP -> "FEATURES_RESP"
    | FLOW_MOD -> "FLOW_MOD"
    | GROUP_MOD -> "GROUP_MOD"
    | PACKET_IN -> "PACKET_IN"
    | PACKET_OUT -> "PACKET_OUT"
    | PORT_STATUS -> "PORT_STATUS"
    | MULTIPART_REQ -> "MULTIPART_REQ"
    | MULTIPART_RESP -> "MULTIPART_RESP"
    | BARRIER_REQ -> "BARRIER_REQ"
    | BARRIER_RESP -> "BARRIER_RESP"
    | ERROR -> "ERROR"
    | VENDOR -> "VENDOR"
    | GET_CONFIG_REQ -> "GET_CONFIG_REQ"
    | GET_CONFIG_RESP -> "GET_CONFIG_RESP"
    | SET_CONFIG -> "SET_CONFIG"
    | FLOW_REMOVED -> "FLOW_REMOVED"
    | PORT_MOD -> "PORT_MOD"
    | TABLE_MOD -> "TABLE_MOD"
    | QUEUE_GET_CONFIG_REQ -> "QUEUE_GET_CONFIG_REQ"
    | QUEUE_GET_CONFIG_RESP -> "QUEUE_GET_CONFIG_RESP"
    | ROLE_REQ -> "ROLE_REQ"
    | ROLE_RESP -> "ROLE_RESP"
    | GET_ASYNC_REQ -> "GET_ASYNC_REQ"
    | GET_ASYNC_REP -> "GET_ASYNC_REP"
    | SET_ASYNC -> "SET_ASYNC"
    | METER_MOD -> "METER_MOD"

  module Header = OpenFlow_Header

  let msg_code_of_message (msg : t) : msg_code = match msg with
    | Hello _ -> HELLO
    | EchoRequest _ -> ECHO_REQ
    | EchoReply _ -> ECHO_RESP
    | FeaturesRequest -> FEATURES_REQ
    | FeaturesReply _ -> FEATURES_RESP
    | FlowModMsg _ -> FLOW_MOD
    | GroupModMsg _ -> GROUP_MOD
    | PortModMsg _ -> PORT_MOD
    | MeterModMsg _ -> METER_MOD
    | PacketInMsg _ -> PACKET_IN
    | FlowRemoved _ -> FLOW_REMOVED
    | PacketOutMsg _ -> PACKET_OUT
    | PortStatusMsg _ ->   PORT_STATUS
    | MultipartReq _ -> MULTIPART_REQ
    | MultipartReply _ -> MULTIPART_RESP
    | BarrierRequest ->   BARRIER_REQ
    | BarrierReply ->   BARRIER_RESP
    | QueueGetConfigReq _ -> QUEUE_GET_CONFIG_REQ
    | QueueGetConfigReply _ -> QUEUE_GET_CONFIG_RESP
    | GetConfigRequestMsg -> GET_CONFIG_REQ
    | GetConfigReplyMsg _ -> GET_CONFIG_RESP
    | SetConfigMsg _ -> SET_CONFIG
    | TableModMsg _ -> TABLE_MOD
    | GetAsyncRequest -> GET_ASYNC_REQ
    | GetAsyncReply _ -> GET_ASYNC_REP
    | SetAsync _ -> SET_ASYNC
    | Error _ -> ERROR
    | RoleRequest _ -> ROLE_REQ
    | RoleReply _ -> ROLE_RESP

  let sizeof (msg : t) : int = match msg with
    | Hello e -> Header.size + Hello.sizeof e
    | EchoRequest b -> Header.size + (String.length (Cstruct.to_string b))
    | EchoReply b -> Header.size + (String.length (Cstruct.to_string b))
    | FeaturesRequest -> Header.size
    | FeaturesReply f -> Header.size + SwitchFeatures.sizeof f
    | FlowModMsg fm -> Header.size + FlowMod.sizeof fm
    | GroupModMsg gm -> Header.size + GroupMod.sizeof gm
    | PortModMsg pm -> Header.size + PortMod.sizeof pm
    | MeterModMsg mm -> Header.size + MeterMod.sizeof mm
    | PacketInMsg pi -> Header.size + PacketIn.sizeof pi
    | FlowRemoved fr -> Header.size + FlowRemoved.sizeof fr
    | PacketOutMsg po -> Header.size + PacketOut.sizeof po
    | PortStatusMsg p -> Header.size + PortStatus.sizeof p
    | MultipartReq req -> Header.size + MultipartReq.sizeof req
    | MultipartReply rep -> Header.size + MultipartReply.sizeof rep
    | QueueGetConfigReq qc -> Header.size + QueueConfReq.sizeof qc
    | QueueGetConfigReply qc -> Header.size + QueueConfReply.sizeof qc
    | GetConfigRequestMsg -> Header.size
    | GetConfigReplyMsg conf -> Header.size + SwitchConfig.sizeof conf
    | SetConfigMsg conf -> Header.size + SwitchConfig.sizeof conf
    | TableModMsg tm -> Header.size + TableMod.sizeof tm
    | BarrierRequest -> Header.size
    | BarrierReply -> Header.size
    | GetAsyncRequest -> Header.size
    | GetAsyncReply async -> Header.size + AsyncConfig.sizeof async
    | SetAsync async -> Header.size + AsyncConfig.sizeof async
    | Error err -> Header.size + Error.sizeof err
    | RoleRequest rr -> Header.size + RoleRequest.sizeof rr
    | RoleReply rr -> Header.size + RoleRequest.sizeof rr

  let to_string (msg : t) : string = match msg with
    | Hello hello -> Format.sprintf "Hello = %s" (Hello.to_string hello)
    | Error error -> Format.sprintf "Error = %s" (Error.to_string error)
    | EchoRequest _ -> "EchoRequest"
    | EchoReply _ -> "EchoReply"
    | FeaturesRequest -> "FeaturesRequest"
    | FeaturesReply features -> Format.sprintf "FeaturesReply = %s" (SwitchFeatures.to_string features)
    | FlowModMsg flow -> Format.sprintf "FlowMod = %s" (FlowMod.to_string flow)
    | GroupModMsg group -> Format.sprintf "GroupMod = %s" (GroupMod.to_string group)
    | PortModMsg port -> Format.sprintf "PortMod = %s" (PortMod.to_string port)
    | MeterModMsg meter -> Format.sprintf "MeterMod = %s" (MeterMod.to_string meter)
    | PacketInMsg packet -> Format.sprintf "PacketIn = %s" (PacketIn.to_string packet)
    | FlowRemoved flow -> Format.sprintf "FlowRemoved = %s" (FlowRemoved.to_string flow)
    | PacketOutMsg packet -> Format.sprintf "PacketOut = %s" (PacketOut.to_string packet)
    | PortStatusMsg port -> Format.sprintf "PortStatus = %s" (PortStatus.to_string port)
    | MultipartReq mult -> Format.sprintf "MultipartRequest = %s" (MultipartReq.to_string mult)
    | MultipartReply mult -> Format.sprintf "MultipartReply = %s" (MultipartReply.to_string mult)
    | BarrierRequest -> "BarrierRequest"
    | BarrierReply -> "BarrierReply"
    | RoleRequest role -> Format.sprintf "RoleRequest = %s" (RoleRequest.to_string role)
    | RoleReply role -> Format.sprintf "RoleReply = %s" (RoleRequest.to_string role)
    | QueueGetConfigReq queue -> Format.sprintf "QueueGetConfigReq = %s" (QueueConfReq.to_string queue)
    | QueueGetConfigReply queue -> Format.sprintf "QueueGetConfigReply = %s" (QueueConfReply.to_string queue)
    | GetConfigRequestMsg -> "GetConfigRequest"
    | GetConfigReplyMsg conf -> Format.sprintf "GetConfigReply = %s" (SwitchConfig.to_string conf)
    | SetConfigMsg conf -> Format.sprintf "SetConfig = %s" (SwitchConfig.to_string conf)
    | TableModMsg table -> Format.sprintf "TableMod = %s" (TableMod.to_string table)
    | GetAsyncRequest -> "GetAsyncRequest"
    | GetAsyncReply async -> Format.sprintf "GetAsyncReply = %s" (AsyncConfig.to_string async)
    | SetAsync async -> Format.sprintf "SetAsync = %s" (AsyncConfig.to_string async)

  (* let marshal (buf : Cstruct_sexp.t) (msg : message) : int = *)
  (*   let buf2 = (Cstruct.shift buf Header.size) in *)
  (*   set_ofp_header_version buf 0x04; *)
  (*   set_ofp_header_typ buf (msg_code_to_int (msg_code_of_message msg)); *)
  (*   set_ofp_header_length buf (sizeof msg); *)

  let blit_message (msg : t) (out : Cstruct_sexp.t) =
    match msg with
    | Hello e ->
      Header.size + Hello.marshal out e
    | EchoRequest b
    | EchoReply b ->
      Cstruct.blit_from_string (Cstruct.to_string b) 0 out 0 (String.length (Cstruct.to_string b));
      Header.size + String.length (Cstruct.to_string b)
    | FeaturesRequest ->
      Header.size
    | FeaturesReply fr ->
      Header.size + SwitchFeatures.marshal out fr
    | FlowModMsg fm ->
      Header.size + FlowMod.marshal out fm
    | GroupModMsg gm ->
      Header.size + GroupMod.marshal out gm
    | PortModMsg pm ->
      Header.size + PortMod.marshal out pm
    | MeterModMsg mm ->
      Header.size + MeterMod.marshal out mm
    | PacketOutMsg po ->
      Header.size + PacketOut.marshal out po
    | MultipartReq mpr ->
      Header.size + MultipartReq.marshal out mpr
    | BarrierRequest ->
      Header.size
    | BarrierReply ->
      Header.size
    | MultipartReply mpr ->
      Header.size + MultipartReply.marshal out mpr
    | QueueGetConfigReq qr ->
      Header.size + QueueConfReq.marshal out qr
    | QueueGetConfigReply qr ->
      Header.size + QueueConfReply.marshal out qr
    | PacketInMsg pi ->
      Header.size + PacketIn.marshal out pi
    | PortStatusMsg ps ->
      Header.size + PortStatus.marshal out ps
    | RoleRequest rr ->
      Header.size + RoleRequest.marshal out rr
    | RoleReply rr ->
      Header.size + RoleRequest.marshal out rr
    | GetConfigRequestMsg ->
      Header.size
    | GetConfigReplyMsg conf ->
      Header.size + SwitchConfig.marshal out conf
    | SetConfigMsg conf ->
      Header.size + SwitchConfig.marshal out conf
    | TableModMsg tm ->
      Header.size + TableMod.marshal out tm
    | FlowRemoved fr ->
      Header.size + FlowRemoved.marshal out fr
    | GetAsyncRequest ->
      Header.size
    | GetAsyncReply async ->
      Header.size + AsyncConfig.marshal out async
    | SetAsync async ->
      Header.size + AsyncConfig.marshal out async
    | Error err ->
      Header.size + Error.marshal out err


  let header_of xid msg =
    let open Header in
    { version = 0x04; type_code = msg_code_to_int (msg_code_of_message msg);
      length = sizeof msg; xid = xid }

  let marshal_body (msg : t) (buf : Cstruct_sexp.t) =
    let _ = blit_message msg buf in
    ()

  let marshal (xid : xid) (msg : t) : string =
    let sizeof_buf = sizeof msg in
    let hdr = header_of xid msg in
    let buf = Cstruct.create sizeof_buf in
    Header.marshal buf hdr;
    let _ = blit_message msg (Cstruct.shift buf Header.size) in
    Cstruct.to_string buf

  let parse (hdr : Header.t) (body_buf : string) : (xid * t) =
    let body_bits = Cstruct.of_string body_buf in
    let typ = match int_to_msg_code hdr.Header.type_code with
      | Some code -> code
      | None -> raise (Unparsable "unknown message code") in
    let msg = match typ with
      | HELLO -> Hello (Hello.parse body_bits)
      | ECHO_RESP -> EchoReply body_bits
      | FEATURES_RESP -> FeaturesReply (SwitchFeatures.parse body_bits)
      | FLOW_MOD -> FlowModMsg (FlowMod.parse body_bits)
      | GROUP_MOD -> GroupModMsg (GroupMod.parse body_bits)
      | PORT_MOD -> PortModMsg (PortMod.parse body_bits)
      | METER_MOD -> MeterModMsg (MeterMod.parse body_bits)
      | PACKET_IN -> PacketInMsg (PacketIn.parse body_bits)
      | PACKET_OUT -> PacketOutMsg (PacketOut.parse body_bits)
      | ECHO_REQ -> EchoRequest body_bits
      | PORT_STATUS -> PortStatusMsg (PortStatus.parse body_bits)
      | MULTIPART_REQ -> MultipartReq (MultipartReq.parse body_bits)
      | MULTIPART_RESP -> MultipartReply (MultipartReply.parse body_bits)
      | QUEUE_GET_CONFIG_REQ -> QueueGetConfigReq (QueueConfReq.parse body_bits)
      | QUEUE_GET_CONFIG_RESP -> QueueGetConfigReply (QueueConfReply.parse body_bits)
      | BARRIER_REQ -> BarrierRequest
      | BARRIER_RESP -> BarrierReply
      | ERROR -> Error (Error.parse body_bits)
      | ROLE_REQ -> RoleRequest (RoleRequest.parse body_bits)
      | ROLE_RESP -> RoleReply (RoleRequest.parse body_bits)
      | GET_CONFIG_RESP -> GetConfigReplyMsg (SwitchConfig.parse body_bits)
      | SET_CONFIG -> SetConfigMsg (SwitchConfig.parse body_bits)
      | TABLE_MOD -> TableModMsg (TableMod.parse body_bits)
      | FLOW_REMOVED -> FlowRemoved (FlowRemoved.parse body_bits)
      | GET_ASYNC_REQ -> GetAsyncRequest
      | GET_ASYNC_REP -> GetAsyncReply (AsyncConfig.parse body_bits)
      | SET_ASYNC -> SetAsync (AsyncConfig.parse body_bits)
      | code -> raise (Unparsable (Printf.sprintf "unexpected message type %s" (string_of_msg_code typ))) in
    (hdr.Header.xid, msg)
end

let portsDescRequest = Message.MultipartReq portDescReq
OCaml

Innovation. Community. Security.