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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
# cython: language_level=3
# cython: embedsignature=True
# cython: profile=True
###############################################################################
###############################################################################
## Cython wrapper for htslib VCF/BCF reader/writer
###############################################################################
#
# NOTICE: This code is incomplete and preliminary.  It offers a nearly
#         complete Pythonic interface to VCF/BCF metadata and data with
#         reading and writing capability.  Documentation and a unit test suite
#         are in the works.  The code is best tested under Python 2, but
#         should also work with Python 3.  Please report any remaining
#         str/bytes issues on the github site when using Python 3 and I'll
#         fix them promptly.
#
# Here is a minimal example of how to use the API:
#
#     $ cat bcfview.py
#     import sys
#     from pysam import VariantFile
#
#     bcf_in = VariantFile(sys.argv[1]) # auto-detect input format
#     bcf_out = VariantFile('-', 'w', header=bcf_in.header)
#
#     for rec in bcf_in:
#         bcf_out.write(rec)
#
# Performance is fairly close to that of bcftools view.  Here is an example
# using some 1k Genomes data:
#
#     $ time python bcfview.py ALL.chr22.phase3_shapeit2_mvncall_integrated_v5.20130502.genotypes.bcf |wc -l
#      1103799
#
#     real	0m56.114s
#     user	1m4.489s
#     sys	0m3.102s
#
#     $ time bcftools view ALL.chr22.phase3_shapeit2_mvncall_integrated_v5.20130502.genotypes.bcf |wc -l
#      1103800  # bcftools adds an extra header
#
#     real	0m55.126s
#     user	1m3.502s
#     sys	0m3.459s
#
###############################################################################
#
# TODO list:
#
#   * more genotype methods
#   * unit test suite (perhaps py.test based)
#   * documentation
#   * pickle support
#   * left/right locus normalization
#   * fix reopen to re-use fd
#
###############################################################################
#
# The MIT License
#
# Copyright (c) 2015,2016 Kevin Jacobs (jacobs@bioinformed.com)
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
###############################################################################

from __future__ import division, print_function

import os
import sys

from libc.errno  cimport errno, EPIPE
from libc.string cimport strcmp, strpbrk, strerror
from libc.stdint cimport INT8_MAX, INT16_MAX, INT32_MAX

cimport cython

from cpython.object  cimport PyObject
from cpython.ref     cimport Py_INCREF
from cpython.dict    cimport PyDict_GetItemString, PyDict_SetItemString
from cpython.tuple   cimport PyTuple_New, PyTuple_SET_ITEM
from cpython.bytes   cimport PyBytes_FromStringAndSize
from cpython.unicode cimport PyUnicode_DecodeUTF8

from pysam.libchtslib cimport HTSFile, hisremote

from pysam.utils import unquoted_str


__all__ = ['VariantFile',
           'VariantHeader',
           'VariantHeaderRecord',
           'VariantHeaderRecords',
           'VariantMetadata',
           'VariantHeaderMetadata',
           'VariantContig',
           'VariantHeaderContigs',
           'VariantHeaderSamples',
           'VariantRecordFilter',
           'VariantRecordFormat',
           'VariantRecordInfo',
           'VariantRecordSamples',
           'VariantRecord',
           'VariantRecordSample',
           'BaseIndex',
           'BCFIndex',
           'TabixIndex',
           'BaseIterator',
           'BCFIterator',
           'TabixIterator',
           'VariantRecord']

########################################################################
########################################################################
## Constants
########################################################################

cdef int MAX_POS = (1 << 31) - 1
cdef tuple VALUE_TYPES = ('Flag', 'Integer', 'Float', 'String')
cdef tuple METADATA_TYPES = ('FILTER', 'INFO', 'FORMAT', 'CONTIG', 'STRUCTURED', 'GENERIC')
cdef tuple METADATA_LENGTHS = ('FIXED', 'VARIABLE', 'A', 'G', 'R')


########################################################################
########################################################################
## Python 3 compatibility functions
########################################################################

from pysam.libcutils cimport force_bytes, force_str, charptr_to_str, charptr_to_str_w_len
from pysam.libcutils cimport encode_filename, from_string_and_size, decode_bytes


########################################################################
########################################################################
## Sentinel object
########################################################################

cdef object _nothing = object()

########################################################################
########################################################################
## VCF/BCF string intern system
########################################################################

cdef dict bcf_str_cache = {}

cdef inline bcf_str_cache_get_charptr(const char* s):
    if s == NULL:
        return None

    cdef PyObject *pystr = PyDict_GetItemString(bcf_str_cache, s)
    if pystr:
        return <object>pystr

    val = PyUnicode_DecodeUTF8(s, strlen(s), NULL)

    PyDict_SetItemString(bcf_str_cache, s, val)

    return val


########################################################################
########################################################################
## Genotype math
########################################################################

cdef int comb(int n, int k) except -1:
    """Return binomial coefficient: n choose k

    >>> comb(5, 1)
    5
    >>> comb(5, 2)
    10
    >>> comb(2, 2)
    1
    >>> comb(100, 2)
    4950
    """
    if k > n:
        return 0
    elif k == n:
        return 1
    elif k > n // 2:
        k = n - k

    cdef d, result

    d = result = n - k + 1
    for i in range(2, k + 1):
        d += 1
        result  *= d
        result //= i
    return result


cdef inline int bcf_geno_combinations(int ploidy, int alleles) except -1:
    """Return the count of genotypes expected for the given ploidy and number of alleles.

    >>> bcf_geno_combinations(1, 2)
    2
    >>> bcf_geno_combinations(2, 2)
    3
    >>> bcf_geno_combinations(2, 3)
    6
    >>> bcf_geno_combinations(3, 2)
    4
    """
    return comb(alleles + ploidy - 1, ploidy)


########################################################################
########################################################################
## Low level type conversion helpers
########################################################################


cdef inline bint check_header_id(bcf_hdr_t *hdr, int hl_type, int id):
    return id >= 0 and id < hdr.n[BCF_DT_ID] and bcf_hdr_idinfo_exists(hdr, hl_type, id)


cdef inline int is_gt_fmt(bcf_hdr_t *hdr, int fmt_id):
    return strcmp(bcf_hdr_int2id(hdr, BCF_DT_ID, fmt_id), 'GT') == 0


cdef inline int bcf_genotype_count(bcf_hdr_t *hdr, bcf1_t *rec, int sample) except -1:

    if sample < 0:
        raise ValueError('genotype is only valid as a format field')

    cdef int32_t *gt_arr = NULL
    cdef int ngt = 0
    ngt = bcf_get_genotypes(hdr, rec, &gt_arr, &ngt)

    if ngt <= 0 or not gt_arr:
        return 0

    assert ngt % rec.n_sample == 0
    cdef int max_ploidy = ngt // rec.n_sample
    cdef int32_t *gt = gt_arr + sample * max_ploidy
    cdef int ploidy = 0

    while ploidy < max_ploidy and gt[0] != bcf_int32_vector_end:
        gt += 1
        ploidy += 1

    free(<void*>gt_arr)

    return bcf_geno_combinations(ploidy, rec.n_allele)


cdef tuple char_array_to_tuple(const char **a, ssize_t n, int free_after=0):
    if not a:
        return None
    try:
         return tuple(charptr_to_str(a[i]) for i in range(n))
    finally:
        if free_after and a:
            free(a)


cdef bcf_array_to_object(void *data, int type, ssize_t n, ssize_t count, int scalar):
    cdef char    *datac
    cdef int8_t  *data8
    cdef int16_t *data16
    cdef int32_t *data32
    cdef float   *dataf
    cdef int      i
    cdef bytes    b

    if not data or n <= 0:
        return None

    if type == BCF_BT_CHAR:
        datac = <char *>data

        if not n:
            value = ()
        else:
            # Check if at least one null terminator is present
            if datac[n-1] == bcf_str_vector_end:
                # If so, create a string up to the first null terminator
                b = datac
            else:
                # Otherwise, copy the entire block
                b = datac[:n]
            value = tuple(decode_bytes(v, 'utf-8') if v and v != bcf_str_missing else None for v in b.split(b','))
    else:
        value = []
        if type == BCF_BT_INT8:
            data8 = <int8_t *>data
            for i in range(n):
                if data8[i] == bcf_int8_vector_end:
                    break
                value.append(data8[i] if data8[i] != bcf_int8_missing else None)
        elif type == BCF_BT_INT16:
            data16 = <int16_t *>data
            for i in range(n):
                if data16[i] == bcf_int16_vector_end:
                    break
                value.append(data16[i] if data16[i] != bcf_int16_missing else None)
        elif type == BCF_BT_INT32:
            data32 = <int32_t *>data
            for i in range(n):
                if data32[i] == bcf_int32_vector_end:
                    break
                value.append(data32[i] if data32[i] != bcf_int32_missing else None)
        elif type == BCF_BT_FLOAT:
            dataf = <float *>data
            for i in range(n):
                if bcf_float_is_vector_end(dataf[i]):
                    break
                value.append(dataf[i] if not bcf_float_is_missing(dataf[i]) else None)
        else:
            raise TypeError('unsupported info type code')

    # FIXME: Need to know length?  Report errors?  Pad with missing values?  Not clear what to do.
    if not value:
        if scalar:
            value = None
        elif count <= 0:
            value = ()
        else:
            value = (None,)*count
    elif scalar and len(value) == 1:
        value = value[0]
    else:
        value = tuple(value)

    return value


cdef bcf_object_to_array(values, void *data, int bt_type, ssize_t n, int vlen):
    cdef char    *datac
    cdef int8_t  *data8
    cdef int16_t *data16
    cdef int32_t *data32
    cdef float   *dataf
    cdef ssize_t  i, value_count = len(values)

    assert value_count <= n

    if bt_type == BCF_BT_CHAR:
        if not isinstance(values, (str, bytes)):
            values = b','.join(force_bytes(v) if v else bcf_str_missing for v in values)
            value_count = len(values)
        assert value_count <= n
        datac = <char *>data
        memcpy(datac, <char *>values, value_count)
        for i in range(value_count, n):
            datac[i] = 0
    elif bt_type == BCF_BT_INT8:
        datai8 = <int8_t *>data
        for i in range(value_count):
            val = values[i]
            datai8[i] = val if val is not None else bcf_int8_missing
        for i in range(value_count, n):
            datai8[i] = bcf_int8_vector_end
    elif bt_type == BCF_BT_INT16:
        datai16 = <int16_t *>data
        for i in range(value_count):
            val = values[i]
            datai16[i] = val if val is not None else bcf_int16_missing
        for i in range(value_count, n):
            datai16[i] = bcf_int16_vector_end
    elif bt_type == BCF_BT_INT32:
        datai32 = <int32_t *>data
        for i in range(value_count):
            val = values[i]
            datai32[i] = val if val is not None else bcf_int32_missing
        for i in range(value_count, n):
            datai32[i] = bcf_int32_vector_end
    elif bt_type == BCF_BT_FLOAT:
        dataf = <float *>data
        for i in range(value_count):
            val = values[i]
            if val is None:
                bcf_float_set(dataf + i, bcf_float_missing)
            else:
                dataf[i] = val
        for i in range(value_count, n):
            bcf_float_set(dataf + i, bcf_float_vector_end)
    else:
        raise TypeError('unsupported type')


cdef bcf_empty_array(int type, ssize_t n, int vlen):
    cdef char    *datac
    cdef int32_t *data32
    cdef float   *dataf
    cdef int      i

    if n <= 0:
        raise ValueError('Cannot create empty array')

    if type == BCF_HT_STR:
        value = PyBytes_FromStringAndSize(NULL, sizeof(char)*n)
        datac = <char *>value
        for i in range(n):
            datac[i] = bcf_str_missing if not vlen else bcf_str_vector_end
    elif type == BCF_HT_INT:
        value = PyBytes_FromStringAndSize(NULL, sizeof(int32_t)*n)
        data32 = <int32_t *><char *>value
        for i in range(n):
            data32[i] = bcf_int32_missing if not vlen else bcf_int32_vector_end
    elif type == BCF_HT_REAL:
        value = PyBytes_FromStringAndSize(NULL, sizeof(float)*n)
        dataf = <float *><char *>value
        for i in range(n):
            bcf_float_set(dataf + i, bcf_float_missing if not vlen else bcf_float_vector_end)
    else:
        raise TypeError('unsupported header type code')

    return value


cdef bcf_copy_expand_array(void *src_data, int src_type, size_t src_values,
                           void *dst_data, int dst_type, size_t dst_values,
                           int vlen):
    """copy data from src to dest where the size of the elements (src_type/dst_type) differ
    as well as the number of elements (src_values/dst_values).
    """

    cdef char    *src_datac
    cdef char    *dst_datac
    cdef int8_t  *src_datai8
    cdef int16_t *src_datai16
    cdef int32_t *src_datai32
    cdef int32_t *dst_datai
    cdef float   *src_dataf
    cdef float   *dst_dataf
    cdef ssize_t src_size, dst_size, i, j
    cdef int val

    if src_values > dst_values:
        raise ValueError('Cannot copy arrays with src_values={} > dst_values={}'.format(src_values, dst_values))

    if src_type == dst_type == BCF_BT_CHAR:
        src_datac = <char *>src_data
        dst_datac = <char *>dst_data
        memcpy(dst_datac, src_datac, src_values)
        for i in range(src_values, dst_values):
            dst_datac[i] = 0
    elif src_type == BCF_BT_INT8 and dst_type == BCF_BT_INT32:
        src_datai8 = <int8_t *>src_data
        dst_datai  = <int32_t *>dst_data
        for i in range(src_values):
            val = src_datai8[i]
            if val == bcf_int8_missing:
                val = bcf_int32_missing
            elif val == bcf_int8_vector_end:
                val = bcf_int32_vector_end
            dst_datai[i] = val
        for i in range(src_values, dst_values):
            dst_datai[i] = bcf_int32_missing if not vlen else bcf_int32_vector_end
    elif src_type == BCF_BT_INT16 and dst_type == BCF_BT_INT32:
        src_datai16 = <int16_t *>src_data
        dst_datai   = <int32_t *>dst_data
        for i in range(src_values):
            val = src_datai16[i]
            if val == bcf_int16_missing:
                val = bcf_int32_missing
            elif val == bcf_int16_vector_end:
                val = bcf_int32_vector_end
            dst_datai[i] = val
        for i in range(src_values, dst_values):
            dst_datai[i] = bcf_int32_missing if not vlen else bcf_int32_vector_end
    elif src_type == BCF_BT_INT32 and dst_type == BCF_BT_INT32:
        src_datai32 = <int32_t *>src_data
        dst_datai   = <int32_t *>dst_data
        for i in range(src_values):
            dst_datai[i] = src_datai32[i]
        for i in range(src_values, dst_values):
            dst_datai[i] = bcf_int32_missing if not vlen else bcf_int32_vector_end
    elif src_type == BCF_BT_FLOAT and dst_type == BCF_BT_FLOAT:
        src_dataf = <float *>src_data
        dst_dataf = <float *>dst_data
        for i in range(src_values):
            dst_dataf[i] = src_dataf[i]
        for i in range(src_values, dst_values):
            bcf_float_set(dst_dataf + i, bcf_float_missing if not vlen else bcf_float_vector_end)
    else:
        raise TypeError('unsupported types')


cdef bcf_get_value_count(VariantRecord record, int hl_type, int id, ssize_t *count, int *scalar, int sample):
    if record is None:
        raise ValueError('record must not be None')

    cdef bcf_hdr_t *hdr = record.header.ptr
    cdef bcf1_t *r = record.ptr

    if not check_header_id(hdr, hl_type, id):
        raise ValueError('Invalid header')

    cdef int length = bcf_hdr_id2length(hdr, hl_type, id)
    cdef int number = bcf_hdr_id2number(hdr, hl_type, id)

    scalar[0] = 0

    if hl_type == BCF_HL_FMT and is_gt_fmt(hdr, id):
        count[0] = number
    elif length == BCF_VL_FIXED:
        if number == 1:
            scalar[0] = 1
        count[0] = number
    elif length == BCF_VL_R:
        count[0] = r.n_allele
    elif length == BCF_VL_A:
        count[0] = r.n_allele - 1
    elif length == BCF_VL_G:
        count[0] = bcf_genotype_count(hdr, r, sample)
    elif length == BCF_VL_VAR:
        count[0] = -1
    else:
        raise ValueError('Unknown format length')


cdef object bcf_info_get_value(VariantRecord record, const bcf_info_t *z):
    if record is None:
        raise ValueError('record must not be None')

    cdef bcf_hdr_t *hdr = record.header.ptr

    cdef char *s
    cdef ssize_t count
    cdef int scalar

    bcf_get_value_count(record, BCF_HL_INFO, z.key, &count, &scalar, -1)

    if z.len == 0:
        if  bcf_hdr_id2type(hdr, BCF_HL_INFO, z.key) == BCF_HT_FLAG:
            value = True
        elif scalar:
            value = None
        else:
            value = ()
    elif z.len == 1:
        if z.type == BCF_BT_INT8:
            value = z.v1.i if z.v1.i != bcf_int8_missing else None
        elif z.type == BCF_BT_INT16:
            value = z.v1.i if z.v1.i != bcf_int16_missing else None
        elif z.type == BCF_BT_INT32:
            value = z.v1.i if z.v1.i != bcf_int32_missing else None
        elif z.type == BCF_BT_FLOAT:
            value = z.v1.f if not bcf_float_is_missing(z.v1.f) else None
        elif z.type == BCF_BT_CHAR:
            value = force_str(chr(z.v1.i))
        else:
            raise TypeError('unsupported info type code')

        if not scalar and value != ():
            value = (value,)
    else:
        value = bcf_array_to_object(z.vptr, z.type, z.len, count, scalar)

    return value


cdef object bcf_check_values(VariantRecord record, value, int sample,
                             int hl_type, int ht_type,
                             int id, int bt_type, ssize_t bt_len,
                             ssize_t *value_count, int *scalar, int *realloc):

    if record is None:
        raise ValueError('record must not be None')

    bcf_get_value_count(record, hl_type, id, value_count, scalar, sample)

    # Validate values now that we know the type and size
    values = (value,) if not isinstance(value, (list, tuple)) else value

    # Validate values now that we know the type and size
    if ht_type == BCF_HT_FLAG:
        value_count[0] = 1
    elif hl_type == BCF_HL_FMT and is_gt_fmt(record.header.ptr, id):
        # KBJ: htslib lies about the cardinality of GT fields-- they're really VLEN (-1)
        value_count[0] = -1

    cdef int given = len(values)
    if value_count[0] != -1 and value_count[0] != given:
        if scalar[0]:
            raise TypeError('value expected to be scalar, given len={}'.format(given))
        else:
            raise TypeError('values expected to be {}-tuple, given len={}'.format(value_count[0], given))

    if ht_type == BCF_HT_REAL:
        for v in values:
            if not(v is None or isinstance(v, (float, int))):
                raise TypeError('invalid value for Float format')
    elif ht_type == BCF_HT_INT:
        for v in values:
            if not(v is None or (isinstance(v, (float, int)) and int(v) == v)):
                raise TypeError('invalid value for Integer format')
        for v in values:
            if not(v is None or bcf_int32_missing < v <= INT32_MAX):
                raise ValueError('Integer value too small/large to store in VCF/BCF')
    elif ht_type == BCF_HT_STR:
        values = b','.join(force_bytes(v) if v is not None else b'' for v in values)
    elif ht_type == BCF_HT_FLAG:
        if values[0] not in (True, False, None, 1, 0):
            raise ValueError('Flag values must be: True, False, None, 1, 0')
    else:
        raise TypeError('unsupported type')

    realloc[0] = 0
    if len(values) <= 1 and hl_type == BCF_HL_INFO:
        realloc[0] = 0
    elif len(values) > bt_len:
        realloc[0] = 1
    elif bt_type == BCF_BT_INT8:
        for v in values:
            if v is not None and not(bcf_int8_missing < v <= INT8_MAX):
                realloc[0] = 1
                break
    elif bt_type == BCF_BT_INT16:
        for v in values:
            if v is not None and not(bcf_int16_missing < v <= INT16_MAX):
                realloc[0] = 1
                break

    return values


cdef bcf_encode_alleles(VariantRecord record, values):
    if record is None:
        raise ValueError('record must not be None')

    cdef bcf1_t *r = record.ptr
    cdef int32_t nalleles = r.n_allele
    cdef list gt_values = []
    cdef char *s
    cdef int i

    if values is None:
        return ()

    if not isinstance(values, (list, tuple)):
        values = (values,)

    for value in values:
        if value is None:
            gt_values.append(bcf_gt_missing)
        elif isinstance(value, (str, bytes)):
            bvalue = force_bytes(value)
            s = bvalue
            for i in range(r.n_allele):
                if strcmp(r.d.allele[i], s) != 0:
                    gt_values.append(bcf_gt_unphased(i))
                    break
            else:
                raise ValueError('Unknown allele')
        else:
            i = value
            if not (0 <= i < nalleles):
                raise ValueError('Invalid allele index')
            gt_values.append(bcf_gt_unphased(i))

    return gt_values


cdef bcf_info_set_value(VariantRecord record, key, value):
    if record is None:
        raise ValueError('record must not be None')

    cdef bcf_hdr_t *hdr = record.header.ptr
    cdef bcf1_t *r = record.ptr
    cdef int info_id, info_type, scalar, dst_type, realloc, vlen = 0
    cdef ssize_t i, value_count, alloc_len, alloc_size, dst_size

    if bcf_unpack(r, BCF_UN_INFO) < 0:
        raise ValueError('Error unpacking VariantRecord')

    cdef bytes bkey = force_bytes(key)
    cdef bcf_info_t *info = bcf_get_info(hdr, r, bkey)

    if info:
        info_id = info.key
    else:
        info_id = bcf_header_get_info_id(hdr, bkey)

    if info_id < 0:
        raise KeyError('unknown INFO: {}'.format(key))

    if not check_header_id(hdr, BCF_HL_INFO, info_id):
        raise ValueError('Invalid header')

    info_type = bcf_hdr_id2type(hdr, BCF_HL_INFO, info_id)
    values = bcf_check_values(record, value, -1,
                              BCF_HL_INFO, info_type, info_id,
                              info.type if info else -1,
                              info.len  if info else -1,
                              &value_count, &scalar, &realloc)

    if info_type == BCF_HT_FLAG:
        if bcf_update_info(hdr, r, bkey, NULL, bool(values[0]), info_type) < 0:
            raise ValueError('Unable to update INFO values')
        return

    vlen = value_count < 0
    value_count = len(values)

    # DISABLED DUE TO ISSUES WITH THE CRAZY POINTERS
    # If we can, write updated values to existing allocated storage
    if 0 and info and not realloc:
        r.d.shared_dirty |= BCF1_DIRTY_INF

        if value_count == 0:
            info.len = 0
            if not info.vptr:
                info.vptr = <uint8_t *>&info.v1.i

        elif value_count == 1:
            # FIXME: Check if need to free vptr if info.len > 0?
            if info.type == BCF_BT_INT8 or info.type == BCF_BT_INT16 or info.type == BCF_BT_INT32:
                bcf_object_to_array(values, &info.v1.i, BCF_BT_INT32, 1, vlen)
            elif info.type == BCF_BT_FLOAT:
                bcf_object_to_array(values, &info.v1.f, BCF_BT_FLOAT, 1, vlen)
            else:
                raise TypeError('unsupported info type code')

            info.len = 1
            if not info.vptr:
                info.vptr = <uint8_t *>&info.v1.i
        else:
            bcf_object_to_array(values, info.vptr, info.type, info.len, vlen)

        return

    alloc_len = max(1, value_count)
    if info and info.len > alloc_len:
        alloc_len = info.len

    new_values = bcf_empty_array(info_type, alloc_len, vlen)
    cdef char *valp = <char *>new_values

    if info_type == BCF_HT_INT:
        dst_type = BCF_BT_INT32
    elif info_type == BCF_HT_REAL:
        dst_type = BCF_BT_FLOAT
    elif info_type == BCF_HT_STR:
        dst_type = BCF_BT_CHAR
    else:
        raise ValueError('Unsupported INFO type')

    bcf_object_to_array(values, valp, dst_type, alloc_len, vlen)

    if bcf_update_info(hdr, r, bkey, valp, <int>alloc_len, info_type) < 0:
        raise ValueError('Unable to update INFO values')


cdef bcf_info_del_value(VariantRecord record, key):
    if record is None:
        raise ValueError('record must not be None')

    cdef bcf_hdr_t *hdr = record.header.ptr
    cdef bcf1_t *r = record.ptr
    cdef ssize_t value_count
    cdef int scalar

    if bcf_unpack(r, BCF_UN_INFO) < 0:
        raise ValueError('Error unpacking VariantRecord')

    cdef bytes bkey = force_bytes(key)
    cdef bcf_info_t *info = bcf_get_info(hdr, r, bkey)

    if not info:
        raise KeyError(key)

    bcf_get_value_count(record, BCF_HL_INFO, info.key, &value_count, &scalar, -1)

    if value_count <= 0:
        null_value = ()
    elif scalar:
        null_value = None
    else:
        null_value = (None,)*value_count

    bcf_info_set_value(record, bkey, null_value)


cdef bcf_format_get_value(VariantRecordSample sample, key):
    if sample is None:
        raise ValueError('sample must not be None')

    cdef bcf_hdr_t *hdr = sample.record.header.ptr
    cdef bcf1_t *r = sample.record.ptr
    cdef ssize_t count
    cdef int scalar

    if bcf_unpack(r, BCF_UN_ALL) < 0:
        raise ValueError('Error unpacking VariantRecord')

    cdef bytes bkey = force_bytes(key)
    cdef bcf_fmt_t *fmt = bcf_get_fmt(hdr, r, bkey)

    if not fmt or not fmt.p:
        raise KeyError('invalid FORMAT: {}'.format(key))

    if is_gt_fmt(hdr, fmt.id):
        return bcf_format_get_allele_indices(sample)

    bcf_get_value_count(sample.record, BCF_HL_FMT, fmt.id, &count, &scalar, sample.index)

    if fmt.p and fmt.n and fmt.size:
        return bcf_array_to_object(fmt.p + sample.index * fmt.size, fmt.type, fmt.n, count, scalar)
    elif scalar:
        return None
    elif count <= 0:
        return ()
    else:
        return (None,)*count


cdef bcf_format_set_value(VariantRecordSample sample, key, value):
    if sample is None:
        raise ValueError('sample must not be None')

    if key == 'phased':
        sample.phased = bool(value)
        return

    cdef bcf_hdr_t *hdr = sample.record.header.ptr
    cdef bcf1_t *r = sample.record.ptr
    cdef int fmt_id
    cdef vdict_t *d
    cdef khiter_t k
    cdef int fmt_type, scalar, realloc, dst_type, vlen = 0
    cdef ssize_t i, nsamples, value_count, alloc_size, alloc_len, dst_size

    if bcf_unpack(r, BCF_UN_ALL) < 0:
        raise ValueError('Error unpacking VariantRecord')

    cdef bytes bkey = force_bytes(key)
    cdef bcf_fmt_t *fmt = bcf_get_fmt(hdr, r, bkey)

    if fmt:
        fmt_id = fmt.id
    else:
        d = <vdict_t *>hdr.dict[BCF_DT_ID]
        k = kh_get_vdict(d, bkey)

        if k == kh_end(d) or kh_val_vdict(d, k).info[BCF_HL_FMT] & 0xF == 0xF:
            raise KeyError('unknown format: {}'.format(key))

        fmt_id = kh_val_vdict(d, k).id

    if not check_header_id(hdr, BCF_HL_FMT, fmt_id):
        raise ValueError('Invalid header')

    fmt_type = bcf_hdr_id2type(hdr, BCF_HL_FMT, fmt_id)

    if fmt_type == BCF_HT_FLAG:
        raise ValueError('Flag types are not allowed on FORMATs')

    if is_gt_fmt(hdr, fmt_id):
        value = bcf_encode_alleles(sample.record, value)
        # KBJ: GT field is considered to be a string by the VCF header but BCF represents it as INT.
        fmt_type = BCF_HT_INT

    values = bcf_check_values(sample.record, value, sample.index,
                              BCF_HL_FMT, fmt_type, fmt_id,
                              fmt.type if fmt else -1,
                              fmt.n    if fmt else -1,
                              &value_count, &scalar, &realloc)
    vlen = value_count < 0
    value_count = len(values)

    # If we can, write updated values to existing allocated storage.
    if fmt and not realloc:
        r.d.indiv_dirty = 1
        bcf_object_to_array(values, fmt.p + sample.index * fmt.size, fmt.type, fmt.n, vlen)
        return

    alloc_len = max(1, value_count)
    if fmt and fmt.n > alloc_len:
        alloc_len = fmt.n

    nsamples = r.n_sample
    new_values = bcf_empty_array(fmt_type, nsamples * alloc_len, vlen)
    cdef char *new_values_p = <char *>new_values

    if fmt_type == BCF_HT_INT:
        dst_type = BCF_BT_INT32
        dst_size = sizeof(int32_t) * alloc_len
    elif fmt_type == BCF_HT_REAL:
        dst_type = BCF_BT_FLOAT
        dst_size = sizeof(float) * alloc_len
    elif fmt_type == BCF_HT_STR:
        dst_type = BCF_BT_CHAR
        dst_size = sizeof(char) * alloc_len
    else:
        raise ValueError('Unsupported FORMAT type')

    if fmt and nsamples > 1:
        for i in range(nsamples):
            bcf_copy_expand_array(fmt.p + i * fmt.size, fmt.type, fmt.n,
                                  new_values_p  + i * dst_size, dst_type, alloc_len,
                                  vlen)

    bcf_object_to_array(values, new_values_p + sample.index * dst_size, dst_type, alloc_len, vlen)

    if bcf_update_format(hdr, r, bkey, new_values_p, <int>(nsamples * alloc_len), fmt_type) < 0:
        raise ValueError('Unable to update format values')


cdef bcf_format_del_value(VariantRecordSample sample, key):
    if sample is None:
        raise ValueError('sample must not be None')

    cdef bcf_hdr_t *hdr = sample.record.header.ptr
    cdef bcf1_t *r = sample.record.ptr
    cdef ssize_t value_count
    cdef int scalar

    if bcf_unpack(r, BCF_UN_ALL) < 0:
        raise ValueError('Error unpacking VariantRecord')

    cdef bytes bkey = force_bytes(key)
    cdef bcf_fmt_t *fmt = bcf_get_fmt(hdr, r, bkey)

    if not fmt or not fmt.p:
        raise KeyError(key)

    bcf_get_value_count(sample.record, BCF_HL_FMT, fmt.id, &value_count, &scalar, sample.index)

    if value_count <= 0:
        null_value = ()
    elif scalar:
        null_value = None
    else:
        null_value = (None,)*value_count

    bcf_format_set_value(sample, bkey, null_value)


cdef bcf_format_get_allele_indices(VariantRecordSample sample):
    if sample is None:
        raise ValueError('sample must not be None')

    cdef bcf_hdr_t *hdr = sample.record.header.ptr
    cdef bcf1_t *r = sample.record.ptr
    cdef int32_t n = r.n_sample

    if bcf_unpack(r, BCF_UN_ALL) < 0:
        raise ValueError('Error unpacking VariantRecord')

    if sample.index < 0 or sample.index >= n or not r.n_fmt:
        return ()

    cdef bcf_fmt_t *fmt0 = r.d.fmt
    cdef int gt0 = is_gt_fmt(hdr, fmt0.id)

    if not gt0 or not fmt0.n:
        return ()

    cdef int8_t  *data8
    cdef int16_t *data16
    cdef int32_t *data32
    cdef int32_t a, nalleles = r.n_allele
    cdef list alleles = []

    if fmt0.type == BCF_BT_INT8:
        data8 = <int8_t *>(fmt0.p + sample.index * fmt0.size)
        for i in range(fmt0.n):
            if data8[i] == bcf_int8_vector_end:
                break
            elif data8[i] == bcf_gt_missing:
                a = -1
            else:
                a = bcf_gt_allele(data8[i])
            alleles.append(a if 0 <= a < nalleles else None)
    elif fmt0.type == BCF_BT_INT16:
        data16 = <int16_t *>(fmt0.p + sample.index * fmt0.size)
        for i in range(fmt0.n):
            if data16[i] == bcf_int16_vector_end:
                break
            elif data16[i] == bcf_gt_missing:
                a = -1
            else:
                a = bcf_gt_allele(data16[i])
            alleles.append(a if 0 <= a < nalleles else None)
    elif fmt0.type == BCF_BT_INT32:
        data32 = <int32_t *>(fmt0.p + sample.index * fmt0.size)
        for i in range(fmt0.n):
            if data32[i] == bcf_int32_vector_end:
                break
            elif data32[i] == bcf_gt_missing:
                a = -1
            else:
                a = bcf_gt_allele(data32[i])
            alleles.append(a if 0 <= a < nalleles else None)

    return tuple(alleles)


cdef bcf_format_get_alleles(VariantRecordSample sample):
    if sample is None:
        raise ValueError('sample must not be None')

    cdef bcf_hdr_t *hdr = sample.record.header.ptr
    cdef bcf1_t *r = sample.record.ptr
    cdef int32_t nsamples = r.n_sample

    if bcf_unpack(r, BCF_UN_ALL) < 0:
        raise ValueError('Error unpacking VariantRecord')

    cdef int32_t nalleles = r.n_allele

    if sample.index < 0 or sample.index >= nsamples or not r.n_fmt:
        return ()

    cdef bcf_fmt_t *fmt0 = r.d.fmt
    cdef int gt0 = is_gt_fmt(hdr, fmt0.id)

    if not gt0 or not fmt0.n:
        return ()

    cdef int32_t  a
    cdef int8_t  *data8
    cdef int16_t *data16
    cdef int32_t *data32
    alleles = []
    if fmt0.type == BCF_BT_INT8:
        data8 = <int8_t *>(fmt0.p + sample.index * fmt0.size)
        for i in range(fmt0.n):
            if data8[i] == bcf_int8_vector_end:
                break
            a = bcf_gt_allele(data8[i])
            alleles.append(charptr_to_str(r.d.allele[a]) if 0 <= a < nalleles else None)
    elif fmt0.type == BCF_BT_INT16:
        data16 = <int16_t *>(fmt0.p + sample.index * fmt0.size)
        for i in range(fmt0.n):
            if data16[i] == bcf_int16_vector_end:
                break
            a = bcf_gt_allele(data16[i])
            alleles.append(charptr_to_str(r.d.allele[a]) if 0 <= a < nalleles else None)
    elif fmt0.type == BCF_BT_INT32:
        data32 = <int32_t *>(fmt0.p + sample.index * fmt0.size)
        for i in range(fmt0.n):
            if data32[i] == bcf_int32_vector_end:
                break
            a = bcf_gt_allele(data32[i])
            alleles.append(charptr_to_str(r.d.allele[a]) if 0 <= a < nalleles else None)
    return tuple(alleles)


cdef bint bcf_sample_get_phased(VariantRecordSample sample):
    if sample is None:
        raise ValueError('sample must not be None')

    cdef bcf_hdr_t *hdr = sample.record.header.ptr
    cdef bcf1_t *r = sample.record.ptr
    cdef int32_t n = r.n_sample

    if bcf_unpack(r, BCF_UN_ALL) < 0:
        raise ValueError('Error unpacking VariantRecord')

    if sample.index < 0 or sample.index >= n or not r.n_fmt:
        return False

    cdef bcf_fmt_t *fmt0 = r.d.fmt
    cdef int gt0 = is_gt_fmt(hdr, fmt0.id)

    if not gt0 or not fmt0.n:
        return False

    cdef int8_t  *data8
    cdef int16_t *data16
    cdef int32_t *data32

    cdef bint phased = False

    if fmt0.type == BCF_BT_INT8:
        data8 = <int8_t *>(fmt0.p + sample.index * fmt0.size)
        for i in range(fmt0.n):
            if data8[i] == bcf_int8_vector_end:
                break
            elif data8[i] == bcf_int8_missing:
                continue
            elif i and not bcf_gt_is_phased(data8[i]):
                return False
            else:
                phased = True
    elif fmt0.type == BCF_BT_INT16:
        data16 = <int16_t *>(fmt0.p + sample.index * fmt0.size)
        for i in range(fmt0.n):
            if data16[i] == bcf_int16_vector_end:
                break
            elif data16[i] == bcf_int16_missing:
                continue
            elif i and not bcf_gt_is_phased(data16[i]):
                return False
            else:
                phased = True
    elif fmt0.type == BCF_BT_INT32:
        data32 = <int32_t *>(fmt0.p + sample.index * fmt0.size)
        for i in range(fmt0.n):
            if data32[i] == bcf_int32_vector_end:
                break
            elif data32[i] == bcf_int32_missing:
                continue
            elif i and not bcf_gt_is_phased(data32[i]):
                return False
            else:
                phased = True

    return phased


cdef bcf_sample_set_phased(VariantRecordSample sample, bint phased):
    if sample is None:
        raise ValueError('sample must not be None')

    cdef bcf_hdr_t *hdr = sample.record.header.ptr
    cdef bcf1_t *r = sample.record.ptr
    cdef int32_t n = r.n_sample

    if bcf_unpack(r, BCF_UN_ALL) < 0:
        raise ValueError('Error unpacking VariantRecord')

    if sample.index < 0 or sample.index >= n or not r.n_fmt:
        return

    cdef bcf_fmt_t *fmt0 = r.d.fmt
    cdef int gt0 = is_gt_fmt(hdr, fmt0.id)

    if not gt0 or not fmt0.n:
        raise ValueError('Cannot set phased before genotype is set')

    cdef int8_t  *data8
    cdef int16_t *data16
    cdef int32_t *data32

    if fmt0.type == BCF_BT_INT8:
        data8 = <int8_t *>(fmt0.p + sample.index * fmt0.size)
        for i in range(fmt0.n):
            if data8[i] == bcf_int8_vector_end:
                break
            elif data8[i] == bcf_int8_missing:
                continue
            elif i:
                data8[i] = (data8[i] & 0xFE) | phased
    elif fmt0.type == BCF_BT_INT16:
        data16 = <int16_t *>(fmt0.p + sample.index * fmt0.size)
        for i in range(fmt0.n):
            if data16[i] == bcf_int16_vector_end:
                break
            elif data16[i] == bcf_int16_missing:
                continue
            elif i:
                data16[i] = (data16[i] & 0xFFFE) | phased
    elif fmt0.type == BCF_BT_INT32:
        data32 = <int32_t *>(fmt0.p + sample.index * fmt0.size)
        for i in range(fmt0.n):
            if data32[i] == bcf_int32_vector_end:
                break
            elif data32[i] == bcf_int32_missing:
                continue
            elif i:
                data32[i] = (data32[i] & 0xFFFFFFFE) | phased


cdef inline bcf_sync_end(VariantRecord record):
    cdef bcf_hdr_t *hdr = record.header.ptr
    cdef bcf_info_t *info
    cdef int end_id = bcf_header_get_info_id(record.header.ptr, b'END')
    cdef int ref_len

    # allow missing ref when instantiating a new record
    if record.ref is not None:
        ref_len = len(record.ref)
    else:
        ref_len = 0

    # Delete INFO/END if no alleles are present or if rlen is equal to len(ref)
    # Always keep END for symbolic alleles
    if not has_symbolic_allele(record) and (not record.ptr.n_allele or record.ptr.rlen == ref_len):
        # If INFO/END is not defined in the header, it doesn't exist in the record
        if end_id >= 0:
            info = bcf_get_info(hdr, record.ptr, b'END')
            if info and info.vptr:
                if bcf_update_info(hdr, record.ptr, b'END', NULL, 0, info.type) < 0:
                    raise ValueError('Unable to delete END')
    else:
        # Create END header, if not present
        if end_id < 0:
            record.header.info.add('END', number=1, type='Integer', description='Stop position of the interval')

        # Update to reflect stop position
        bcf_info_set_value(record, b'END', record.ptr.pos + record.ptr.rlen)


cdef inline int has_symbolic_allele(VariantRecord record):
    """Return index of first symbolic allele. 0 if no symbolic alleles."""

    for i in range(1, record.ptr.n_allele):
        alt = record.ptr.d.allele[i]
        if alt[0] == b'<' and alt[len(alt) - 1] == b'>':
            return i

    return 0


########################################################################
########################################################################
## Variant Header objects
########################################################################


cdef bcf_header_remove_hrec(VariantHeader header, int i):
    if header is None:
        raise ValueError('header must not be None')

    cdef bcf_hdr_t *hdr = header.ptr

    if i < 0 or i >= hdr.nhrec:
        raise ValueError('Invalid header record index')

    cdef bcf_hrec_t *hrec = hdr.hrec[i]
    hdr.nhrec -= 1

    if i < hdr.nhrec:
        memmove(&hdr.hrec[i], &hdr.hrec[i+1], (hdr.nhrec-i)*sizeof(bcf_hrec_t*))

    bcf_hrec_destroy(hrec)
    hdr.hrec[hdr.nhrec] = NULL
    hdr.dirty = 1


#FIXME: implement a full mapping interface
#FIXME: passing bcf_hrec_t* is not safe, since we cannot control the
#       object lifetime.
cdef class VariantHeaderRecord(object):
    """header record from a :class:`VariantHeader` object"""
    def __init__(self, *args, **kwargs):
        raise TypeError('this class cannot be instantiated from Python')

    @property
    def type(self):
        """header type: FILTER, INFO, FORMAT, CONTIG, STRUCTURED, or GENERIC"""
        cdef bcf_hrec_t *r = self.ptr
        if not r:
            return None
        return METADATA_TYPES[r.type]

    @property
    def key(self):
        """header key (the part before '=', in FILTER/INFO/FORMAT/contig/fileformat etc.)"""
        cdef bcf_hrec_t *r = self.ptr
        return bcf_str_cache_get_charptr(r.key) if r and r.key else None

    @property
    def value(self):
        """header value.  Set only for generic lines, None for FILTER/INFO, etc."""
        cdef bcf_hrec_t *r = self.ptr
        return charptr_to_str(r.value) if r and r.value else None

    @property
    def attrs(self):
        """sequence of additional header attributes"""
        cdef bcf_hrec_t *r = self.ptr
        if not r:
            return ()
        cdef int i
        return tuple((bcf_str_cache_get_charptr(r.keys[i]) if r.keys[i] else None,
                      charptr_to_str(r.vals[i]) if r.vals[i] else None)
                     for i in range(r.nkeys))

    def __len__(self):
        cdef bcf_hrec_t *r = self.ptr
        return r.nkeys if r else 0

    def __bool__(self):
        cdef bcf_hrec_t *r = self.ptr
        return r != NULL and r.nkeys != 0

    def __getitem__(self, key):
        """get attribute value"""
        cdef bcf_hrec_t *r = self.ptr
        cdef int i
        if r:
            bkey = force_bytes(key)
            for i in range(r.nkeys):
                if r.keys[i] and r.keys[i] == bkey:
                    return charptr_to_str(r.vals[i]) if r.vals[i] else None
        raise KeyError('cannot find metadata key')

    def __iter__(self):
        cdef bcf_hrec_t *r = self.ptr
        if not r:
            return
        cdef int i
        for i in range(r.nkeys):
            if r.keys[i]:
                yield bcf_str_cache_get_charptr(r.keys[i])

    def get(self, key, default=None):
        """D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None."""
        try:
            return self[key]
        except KeyError:
            return default

    def __contains__(self, key):
        try:
            self[key]
        except KeyError:
            return False
        else:
            return True

    def iterkeys(self):
        """D.iterkeys() -> an iterator over the keys of D"""
        return iter(self)

    def itervalues(self):
        """D.itervalues() -> an iterator over the values of D"""
        cdef bcf_hrec_t *r = self.ptr
        if not r:
            return
        cdef int i
        for i in range(r.nkeys):
            if r.keys[i]:
                yield charptr_to_str(r.vals[i]) if r.vals[i] else None

    def iteritems(self):
        """D.iteritems() -> an iterator over the (key, value) items of D"""
        cdef bcf_hrec_t *r = self.ptr
        if not r:
            return
        cdef int i
        for i in range(r.nkeys):
            if r.keys[i]:
                yield (bcf_str_cache_get_charptr(r.keys[i]), charptr_to_str(r.vals[i]) if r.vals[i] else None)

    def keys(self):
        """D.keys() -> list of D's keys"""
        return list(self)

    def items(self):
        """D.items() -> list of D's (key, value) pairs, as 2-tuples"""
        return list(self.iteritems())

    def values(self):
        """D.values() -> list of D's values"""
        return list(self.itervalues())

    def update(self, items=None, **kwargs):
        """D.update([E, ]**F) -> None.

        Update D from dict/iterable E and F.
        """
        for k, v in items.items():
            self[k] = v

        if kwargs:
            for k, v in kwargs.items():
                self[k] = v

    def pop(self, key, default=_nothing):
        try:
            value = self[key]
            del self[key]
            return value
        except KeyError:
            if default is not _nothing:
                return default
            raise

    # Mappings are not hashable by default, but subclasses can change this
    __hash__ = None

    #TODO: implement __richcmp__

    def __str__(self):
        cdef bcf_hrec_t *r = self.ptr

        if not r:
            raise ValueError('cannot convert deleted record to str')

        cdef kstring_t hrec_str
        hrec_str.l = hrec_str.m = 0
        hrec_str.s = NULL

        bcf_hrec_format(r, &hrec_str)

        ret = charptr_to_str_w_len(hrec_str.s, hrec_str.l)

        if hrec_str.m:
            free(hrec_str.s)

        return ret

    # FIXME: Not safe -- causes trivial segfaults at the moment
    def remove(self):
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef bcf_hrec_t *r = self.ptr
        if not r:
            return
        assert r.key
        cdef char *key = r.key if r.type == BCF_HL_GEN else r.value
        bcf_hdr_remove(hdr, r.type, key)
        self.ptr = NULL


cdef VariantHeaderRecord makeVariantHeaderRecord(VariantHeader header, bcf_hrec_t *hdr):
    if not header:
        raise ValueError('invalid VariantHeader')

    if not hdr:
        return None

    cdef VariantHeaderRecord record = VariantHeaderRecord.__new__(VariantHeaderRecord)
    record.header = header
    record.ptr = hdr

    return record


cdef class VariantHeaderRecords(object):
    """sequence of :class:`VariantHeaderRecord` object from a :class:`VariantHeader` object"""
    def __init__(self, *args, **kwargs):
        raise TypeError('this class cannot be instantiated from Python')

    def __len__(self):
        return self.header.ptr.nhrec

    def __bool__(self):
        return self.header.ptr.nhrec != 0

    def __getitem__(self, index):
        cdef int32_t i = index
        if i < 0 or i >= self.header.ptr.nhrec:
            raise IndexError('invalid header record index')
        return makeVariantHeaderRecord(self.header, self.header.ptr.hrec[i])

    def __iter__(self):
        cdef int32_t i
        for i in range(self.header.ptr.nhrec):
            yield makeVariantHeaderRecord(self.header, self.header.ptr.hrec[i])

    __hash__ = None


cdef VariantHeaderRecords makeVariantHeaderRecords(VariantHeader header):
    if not header:
        raise ValueError('invalid VariantHeader')

    cdef VariantHeaderRecords records = VariantHeaderRecords.__new__(VariantHeaderRecords)
    records.header = header
    return records


cdef class VariantMetadata(object):
    """filter, info or format metadata record from a :class:`VariantHeader` object"""
    def __init__(self, *args, **kwargs):
        raise TypeError('this class cannot be instantiated from Python')

    @property
    def name(self):
        """metadata name"""
        cdef bcf_hdr_t *hdr = self.header.ptr
        return bcf_str_cache_get_charptr(hdr.id[BCF_DT_ID][self.id].key)

    # Q: Should this be exposed?
    @property
    def id(self):
        """metadata internal header id number"""
        return self.id

    @property
    def number(self):
        """metadata number (i.e. cardinality)"""
        cdef bcf_hdr_t *hdr = self.header.ptr

        if not check_header_id(hdr, self.type, self.id):
            raise ValueError('Invalid header id')

        if self.type == BCF_HL_FLT:
            return None

        cdef int l = bcf_hdr_id2length(hdr, self.type, self.id)
        if l == BCF_VL_FIXED:
            return bcf_hdr_id2number(hdr, self.type, self.id)
        elif l == BCF_VL_VAR:
            return '.'
        else:
            return METADATA_LENGTHS[l]

    @property
    def type(self):
        """metadata value type"""
        cdef bcf_hdr_t *hdr = self.header.ptr
        if not check_header_id(hdr, self.type, self.id):
            raise ValueError('Invalid header id')

        if self.type == BCF_HL_FLT:
            return None
        return VALUE_TYPES[bcf_hdr_id2type(hdr, self.type, self.id)]

    @property
    def description(self):
        """metadata description (or None if not set)"""
        descr = self.record.get('Description')
        if descr:
            descr = descr.strip('"')
        return force_str(descr)

    @property
    def record(self):
        """:class:`VariantHeaderRecord` associated with this :class:`VariantMetadata` object"""
        cdef bcf_hdr_t *hdr = self.header.ptr
        if not check_header_id(hdr, self.type, self.id):
            raise ValueError('Invalid header id')
        cdef bcf_hrec_t *hrec = hdr.id[BCF_DT_ID][self.id].val.hrec[self.type]
        if not hrec:
            return None
        return makeVariantHeaderRecord(self.header, hrec)

    def remove_header(self):
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef const char *key = hdr.id[BCF_DT_ID][self.id].key
        bcf_hdr_remove(hdr, self.type, key)


cdef VariantMetadata makeVariantMetadata(VariantHeader header, int type, int id):
    if not header:
        raise ValueError('invalid VariantHeader')

    if type != BCF_HL_FLT and type != BCF_HL_INFO and type != BCF_HL_FMT:
        raise ValueError('invalid metadata type')

    if id < 0 or id >= header.ptr.n[BCF_DT_ID]:
        raise ValueError('invalid metadata id')

    cdef VariantMetadata meta = VariantMetadata.__new__(VariantMetadata)
    meta.header = header
    meta.type = type
    meta.id = id

    return meta


cdef class VariantHeaderMetadata(object):
    """mapping from filter, info or format name to :class:`VariantMetadata` object"""
    def __init__(self, *args, **kwargs):
        raise TypeError('this class cannot be instantiated from Python')

    def add(self, id, number, type, description, **kwargs):
        """Add a new filter, info or format record"""
        if id in self:
            raise ValueError('Header already exists for id={}'.format(id))

        if self.type == BCF_HL_FLT:
            if number is not None:
                raise ValueError('Number must be None when adding a filter')
            if type is not None:
                raise ValueError('Type must be None when adding a filter')

            items = [('ID', unquoted_str(id)), ('Description', description)]
        else:
            if type not in VALUE_TYPES:
                raise ValueError('unknown type specified: {}'.format(type))
            if number is None:
                number = '.'

            items = [('ID', unquoted_str(id)),
                     ('Number', unquoted_str(number)),
                     ('Type', unquoted_str(type)),
                     ('Description', description)]

        items += kwargs.items()
        self.header.add_meta(METADATA_TYPES[self.type], items=items)

    def __len__(self):
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef bcf_idpair_t *idpair
        cdef int32_t i, n = 0

        for i in range(hdr.n[BCF_DT_ID]):
            idpair = hdr.id[BCF_DT_ID] + i
            if idpair.key and idpair.val and idpair.val.info[self.type] & 0xF != 0xF:
                n += 1
        return n

    def __bool__(self):
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef bcf_idpair_t *idpair
        cdef int32_t i

        for i in range(hdr.n[BCF_DT_ID]):
            idpair = hdr.id[BCF_DT_ID] + i
            if idpair.key and idpair.val and idpair.val.info[self.type] & 0xF != 0xF:
                return True
        return False

    def __getitem__(self, key):
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef vdict_t *d = <vdict_t *>hdr.dict[BCF_DT_ID]

        cdef bytes bkey = force_bytes(key)
        cdef khiter_t k = kh_get_vdict(d, bkey)

        if k == kh_end(d) or kh_val_vdict(d, k).info[self.type] & 0xF == 0xF:
            raise KeyError('invalid key: {}'.format(key))

        return makeVariantMetadata(self.header, self.type, kh_val_vdict(d, k).id)

    def remove_header(self, key):
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef vdict_t *d = <vdict_t *>hdr.dict[BCF_DT_ID]

        cdef bytes bkey = force_bytes(key)
        cdef khiter_t k = kh_get_vdict(d, bkey)

        if k == kh_end(d) or kh_val_vdict(d, k).info[self.type] & 0xF == 0xF:
            raise KeyError('invalid key: {}'.format(key))

        bcf_hdr_remove(hdr, self.type, bkey)
        #bcf_hdr_sync(hdr)

    def clear_header(self):
        cdef bcf_hdr_t *hdr = self.header.ptr
        bcf_hdr_remove(hdr, self.type, NULL)
        #bcf_hdr_sync(hdr)

    def __iter__(self):
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef bcf_idpair_t *idpair
        cdef int32_t i

        for i in range(hdr.n[BCF_DT_ID]):
            idpair = hdr.id[BCF_DT_ID] + i
            if idpair.key and idpair.val and idpair.val.info[self.type] & 0xF != 0xF:
                yield bcf_str_cache_get_charptr(idpair.key)

    def get(self, key, default=None):
        """D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None."""
        try:
            return self[key]
        except KeyError:
            return default

    def __contains__(self, key):
        try:
            self[key]
        except KeyError:
            return False
        else:
            return True

    def iterkeys(self):
        """D.iterkeys() -> an iterator over the keys of D"""
        return iter(self)

    def itervalues(self):
        """D.itervalues() -> an iterator over the values of D"""
        for key in self:
            yield self[key]

    def iteritems(self):
        """D.iteritems() -> an iterator over the (key, value) items of D"""
        for key in self:
            yield (key, self[key])

    def keys(self):
        """D.keys() -> list of D's keys"""
        return list(self)

    def items(self):
        """D.items() -> list of D's (key, value) pairs, as 2-tuples"""
        return list(self.iteritems())

    def values(self):
        """D.values() -> list of D's values"""
        return list(self.itervalues())

    # Mappings are not hashable by default, but subclasses can change this
    __hash__ = None

    #TODO: implement __richcmp__


cdef VariantHeaderMetadata makeVariantHeaderMetadata(VariantHeader header, int32_t type):
    if not header:
        raise ValueError('invalid VariantHeader')

    cdef VariantHeaderMetadata meta = VariantHeaderMetadata.__new__(VariantHeaderMetadata)
    meta.header = header
    meta.type = type

    return meta


cdef class VariantContig(object):
    """contig metadata from a :class:`VariantHeader`"""
    def __init__(self, *args, **kwargs):
        raise TypeError('this class cannot be instantiated from Python')

    @property
    def name(self):
        """contig name"""
        cdef bcf_hdr_t *hdr = self.header.ptr
        return bcf_str_cache_get_charptr(hdr.id[BCF_DT_CTG][self.id].key)

    @property
    def id(self):
        """contig internal id number"""
        return self.id

    @property
    def length(self):
        """contig length or None if not available"""
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef uint32_t length = hdr.id[BCF_DT_CTG][self.id].val.info[0]
        return length if length else None

    @property
    def header_record(self):
        """:class:`VariantHeaderRecord` associated with this :class:`VariantContig` object"""
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef bcf_hrec_t *hrec = hdr.id[BCF_DT_CTG][self.id].val.hrec[0]
        return makeVariantHeaderRecord(self.header, hrec)

    def remove_header(self):
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef const char *key = hdr.id[BCF_DT_CTG][self.id].key
        bcf_hdr_remove(hdr, BCF_HL_CTG, key)


cdef VariantContig makeVariantContig(VariantHeader header, int id):
    if not header:
        raise ValueError('invalid VariantHeader')

    if id < 0 or id >= header.ptr.n[BCF_DT_CTG]:
        raise ValueError('invalid contig id')

    cdef VariantContig contig = VariantContig.__new__(VariantContig)
    contig.header = header
    contig.id = id

    return contig


cdef class VariantHeaderContigs(object):
    """mapping from contig name or index to :class:`VariantContig` object."""
    def __init__(self, *args, **kwargs):
        raise TypeError('this class cannot be instantiated from Python')

    def __len__(self):
        cdef bcf_hdr_t *hdr = self.header.ptr
        assert kh_size(<vdict_t *>hdr.dict[BCF_DT_CTG]) == hdr.n[BCF_DT_CTG]
        return hdr.n[BCF_DT_CTG]

    def __bool__(self):
        cdef bcf_hdr_t *hdr = self.header.ptr
        assert kh_size(<vdict_t *>hdr.dict[BCF_DT_CTG]) == hdr.n[BCF_DT_CTG]
        return hdr.n[BCF_DT_CTG] != 0

    def __getitem__(self, key):
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef int index

        if isinstance(key, int):
            index = key
            if index < 0 or index >= hdr.n[BCF_DT_CTG]:
                raise IndexError('invalid contig index')
            return makeVariantContig(self.header, index)

        cdef vdict_t *d = <vdict_t *>hdr.dict[BCF_DT_CTG]
        cdef bytes bkey = force_bytes(key)
        cdef khiter_t k = kh_get_vdict(d, bkey)

        if k == kh_end(d):
            raise KeyError('invalid contig: {}'.format(key))

        cdef int id = kh_val_vdict(d, k).id

        return makeVariantContig(self.header, id)

    def remove_header(self, key):
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef int index
        cdef const char *ckey
        cdef vdict_t *d
        cdef khiter_t k

        if isinstance(key, int):
            index = key
            if index < 0 or index >= hdr.n[BCF_DT_CTG]:
                raise IndexError('invalid contig index')
            ckey = hdr.id[BCF_DT_CTG][self.id].key
        else:
            d = <vdict_t *>hdr.dict[BCF_DT_CTG]
            key = force_bytes(key)
            if kh_get_vdict(d, key) == kh_end(d):
                raise KeyError('invalid contig: {}'.format(key))
            ckey = key

        bcf_hdr_remove(hdr, BCF_HL_CTG, ckey)

    def clear_header(self):
        cdef bcf_hdr_t *hdr = self.header.ptr
        bcf_hdr_remove(hdr, BCF_HL_CTG, NULL)
        #bcf_hdr_sync(hdr)

    def __iter__(self):
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef vdict_t *d = <vdict_t *>hdr.dict[BCF_DT_CTG]
        cdef uint32_t n = kh_size(d)

        assert n == hdr.n[BCF_DT_CTG]

        for i in range(n):
            yield bcf_str_cache_get_charptr(bcf_hdr_id2name(hdr, i))

    def get(self, key, default=None):
        """D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None."""
        try:
            return self[key]
        except KeyError:
            return default

    def __contains__(self, key):
        try:
            self[key]
        except KeyError:
            return False
        else:
            return True

    def iterkeys(self):
        """D.iterkeys() -> an iterator over the keys of D"""
        return iter(self)

    def itervalues(self):
        """D.itervalues() -> an iterator over the values of D"""
        for key in self:
            yield self[key]

    def iteritems(self):
        """D.iteritems() -> an iterator over the (key, value) items of D"""
        for key in self:
            yield (key, self[key])

    def keys(self):
        """D.keys() -> list of D's keys"""
        return list(self)

    def items(self):
        """D.items() -> list of D's (key, value) pairs, as 2-tuples"""
        return list(self.iteritems())

    def values(self):
        """D.values() -> list of D's values"""
        return list(self.itervalues())

    # Mappings are not hashable by default, but subclasses can change this
    __hash__ = None

    #TODO: implement __richcmp__

    def add(self, id, length=None, **kwargs):
        """Add a new contig record"""
        if id in self:
            raise ValueError('Header already exists for contig {}'.format(id))

        items = [('ID', unquoted_str(id))]
        if length is not None:
            items.append(("length", unquoted_str(length)))
        items += kwargs.items()
        self.header.add_meta('contig', items=items)


cdef VariantHeaderContigs makeVariantHeaderContigs(VariantHeader header):
    if not header:
        raise ValueError('invalid VariantHeader')

    cdef VariantHeaderContigs contigs = VariantHeaderContigs.__new__(VariantHeaderContigs)
    contigs.header = header

    return contigs


cdef class VariantHeaderSamples(object):
    """sequence of sample names from a :class:`VariantHeader` object"""
    def __init__(self, *args, **kwargs):
        raise TypeError('this class cannot be instantiated from Python')

    def __len__(self):
        return bcf_hdr_nsamples(self.header.ptr)

    def __bool__(self):
        return bcf_hdr_nsamples(self.header.ptr) != 0

    def __getitem__(self, index):
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef int32_t n = bcf_hdr_nsamples(hdr)
        cdef int32_t i = index

        if i < 0 or i >= n:
            raise IndexError('invalid sample index')

        return charptr_to_str(hdr.samples[i])

    def __iter__(self):
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef int32_t i, n = bcf_hdr_nsamples(hdr)

        for i in range(n):
            yield charptr_to_str(hdr.samples[i])

    def __contains__(self, key):
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef vdict_t *d = <vdict_t *>hdr.dict[BCF_DT_SAMPLE]
        cdef bytes bkey = force_bytes(key)
        cdef khiter_t k = kh_get_vdict(d, bkey)

        return k != kh_end(d)

    # Mappings are not hashable by default, but subclasses can change this
    __hash__ = None

    #TODO: implement __richcmp__

    def add(self, name):
        """Add a new sample"""
        self.header.add_sample(name)


cdef VariantHeaderSamples makeVariantHeaderSamples(VariantHeader header):
    if not header:
        raise ValueError('invalid VariantHeader')

    cdef VariantHeaderSamples samples = VariantHeaderSamples.__new__(VariantHeaderSamples)
    samples.header = header

    return samples


cdef class VariantHeader(object):
    """header information for a :class:`VariantFile` object"""
    #FIXME: Add structured proxy
    #FIXME: Add generic proxy
    #FIXME: Add mutable methods

    # See makeVariantHeader for C constructor
    def __cinit__(self):
        self.ptr = NULL

    # Python constructor
    def __init__(self):
        self.ptr = bcf_hdr_init(b'w')
        if not self.ptr:
            raise ValueError('cannot create VariantHeader')

    def __dealloc__(self):
        if self.ptr:
            bcf_hdr_destroy(self.ptr)
            self.ptr = NULL

    def __bool__(self):
        return self.ptr != NULL

    def copy(self):
        return makeVariantHeader(bcf_hdr_dup(self.ptr))

    def merge(self, VariantHeader header):
        if header is None:
            raise ValueError('header must not be None')
        bcf_hdr_merge(self.ptr, header.ptr)

    @property
    def version(self):
        """VCF version"""
        return force_str(bcf_hdr_get_version(self.ptr))

    @property
    def samples(self):
        """samples (:class:`VariantHeaderSamples`)"""
        return makeVariantHeaderSamples(self)

    @property
    def records(self):
        """header records (:class:`VariantHeaderRecords`)"""
        return makeVariantHeaderRecords(self)

    @property
    def contigs(self):
        """contig information (:class:`VariantHeaderContigs`)"""
        return makeVariantHeaderContigs(self)

    @property
    def filters(self):
        """filter metadata (:class:`VariantHeaderMetadata`)"""
        return makeVariantHeaderMetadata(self, BCF_HL_FLT)

    @property
    def info(self):
        """info metadata (:class:`VariantHeaderMetadata`)"""
        return makeVariantHeaderMetadata(self, BCF_HL_INFO)

    @property
    def formats(self):
        """format metadata (:class:`VariantHeaderMetadata`)"""
        return makeVariantHeaderMetadata(self, BCF_HL_FMT)

    @property
    def alts(self):
        """alt metadata (:class:`dict` ID->record).

        The data returned just a snapshot of alt records, is created
        every time the property is requested, and modifications will
        not be reflected in the header metadata and vice versa.

        i.e. it is just a dict that reflects the state of alt records
        at the time it is created.
        """
        return {record['ID']:record for record in self.records
                if record.key.upper() == 'ALT' }

    # only safe to do when opening an htsfile
    cdef _subset_samples(self, include_samples):
        keep_samples    = set(self.samples)
        include_samples = set(include_samples)
        missing_samples = include_samples - keep_samples
        keep_samples   &= include_samples

        if missing_samples:
            # FIXME: add specialized exception with payload
            raise ValueError(
                'missing {:d} requested samples'.format(
                    len(missing_samples)))

        keep_samples = force_bytes(','.join(keep_samples))
        cdef char *keep = <char *>keep_samples if keep_samples else NULL
        cdef ret = bcf_hdr_set_samples(self.ptr, keep, 0)

        if ret != 0:
            raise ValueError(
                'bcf_hdr_set_samples failed: ret = {}'.format(ret))

    def __str__(self):
        cdef int hlen
        cdef kstring_t line
        line.l = line.m = 0
        line.s = NULL

        if bcf_hdr_format(self.ptr, 0, &line) < 0:
            if line.m:
                free(line.s)
            raise ValueError('bcf_hdr_format failed')

        ret = charptr_to_str_w_len(line.s, line.l)

        if line.m:
            free(line.s)
        return ret

    def new_record(self, contig=None, start=0, stop=0, alleles=None,
                         id=None, qual=None, filter=None, info=None, samples=None,
                         **kwargs):
        """Create a new empty VariantRecord.

        Arguments are currently experimental.  Use with caution and expect
        changes in upcoming releases.

        """
        rec = makeVariantRecord(self, bcf_init())

        if not rec:
            raise MemoryError('unable to allocate BCF record')

        rec.ptr.n_sample = bcf_hdr_nsamples(self.ptr)

        if contig is not None:
            rec.contig  = contig

        rec.start = start
        rec.stop  = stop
        rec.id    = id
        rec.qual  = qual

        if alleles is not None:
            rec.alleles = alleles

        if filter is not None:
            if isinstance(filter, (list, tuple, VariantRecordFilter)):
                for f in filter:
                    rec.filter.add(f)
            else:
                rec.filter.add(filter)

        if info:
            rec.info.update(info)

        if kwargs:
            if 'GT' in kwargs:
                rec.samples[0]['GT'] = kwargs.pop('GT')
            rec.samples[0].update(kwargs)

        if samples:
            for i, sample in enumerate(samples):
                if 'GT' in sample:
                    rec.samples[i]['GT'] = sample.pop('GT')
                rec.samples[i].update(sample)

        return rec

    def add_record(self, VariantHeaderRecord record):
        """Add an existing :class:`VariantHeaderRecord` to this header"""
        if record is None:
            raise ValueError('record must not be None')

        cdef bcf_hrec_t *hrec = bcf_hrec_dup(record.ptr)

        bcf_hdr_add_hrec(self.ptr, hrec)

        self._hdr_sync()

    def add_line(self, line):
        """Add a metadata line to this header"""
        bline = force_bytes(line)
        if bcf_hdr_append(self.ptr, bline) < 0:
            raise ValueError('invalid header line')

        self._hdr_sync()


    def add_meta(self, key, value=None, items=None):
        """Add metadata to this header"""
        if not ((value is not None) ^ (items is not None)):
            raise ValueError('either value or items must be specified')

        cdef bcf_hrec_t *hrec = <bcf_hrec_t*>calloc(1, sizeof(bcf_hrec_t))
        cdef int quoted

        try:
            key = force_bytes(key)
            hrec.key = strdup(key)

            if value is not None:
                hrec.value = strdup(force_bytes(value))
            else:
                for key, value in items:
                    quoted = not isinstance(value, unquoted_str) and key not in ("ID", "Number", "Type")

                    key = force_bytes(key)
                    bcf_hrec_add_key(hrec, key, <int>len(key))

                    value = force_bytes(str(value))
                    bcf_hrec_set_val(hrec, hrec.nkeys-1, value, <int>len(value), quoted)
        except:
            bcf_hrec_destroy(hrec)
            raise

        bcf_hdr_add_hrec(self.ptr, hrec)

        self._hdr_sync()

    cdef _add_sample(self, name):
        bname = force_bytes(name)
        if bcf_hdr_add_sample(self.ptr, bname) < 0:
            raise ValueError('Duplicated sample name: {}'.format(name))

    cdef _hdr_sync(self):
        cdef bcf_hdr_t *hdr = self.ptr
        if hdr.dirty:
            if bcf_hdr_sync(hdr) < 0:
                raise MemoryError('unable to reallocate VariantHeader')

    def add_sample(self, name):
        """Add a new sample to this header"""
        self._add_sample(name)
        self._hdr_sync()

    def add_samples(self, *args):
        """Add several new samples to this header.
        This function takes multiple arguments, each of which may
        be either a sample name or an iterable returning sample names
        (e.g., a list of sample names).
        """
        for arg in args:
            if isinstance(arg, str):
                self._add_sample(arg)
            else:
                for name in arg:
                    self._add_sample(name)
        self._hdr_sync()


cdef VariantHeader makeVariantHeader(bcf_hdr_t *hdr):
    if not hdr:
        raise ValueError('cannot create VariantHeader')

    cdef VariantHeader header = VariantHeader.__new__(VariantHeader)
    header.ptr = hdr

    return header


cdef inline int bcf_header_get_info_id(bcf_hdr_t *hdr, key) except? -2:
    cdef vdict_t *d
    cdef khiter_t k
    cdef int info_id

    if isinstance(key, str):
        key = force_bytes(key)

    d = <vdict_t *>hdr.dict[BCF_DT_ID]
    k = kh_get_vdict(d, key)

    if k == kh_end(d) or kh_val_vdict(d, k).info[BCF_HL_INFO] & 0xF == 0xF:
        return -1

    return kh_val_vdict(d, k).id


########################################################################
########################################################################
## Variant Record objects
########################################################################

cdef class VariantRecordFilter(object):
    """Filters set on a :class:`VariantRecord` object, presented as a mapping from
       filter index or name to :class:`VariantMetadata` object"""
    def __init__(self, *args, **kwargs):
        raise TypeError('this class cannot be instantiated from Python')

    def __len__(self):
        return self.record.ptr.d.n_flt

    def __bool__(self):
        return self.record.ptr.d.n_flt != 0

    def __getitem__(self, key):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef int index, id
        cdef int n = r.d.n_flt

        if isinstance(key, int):
            index = key

            if index < 0 or index >= n:
                raise IndexError('invalid filter index')

            id = r.d.flt[index]
        else:
            if key == '.':
                key = 'PASS'

            bkey = force_bytes(key)
            id = bcf_hdr_id2int(hdr, BCF_DT_ID, bkey)

            if not check_header_id(hdr, BCF_HL_FLT, id) or not bcf_has_filter(hdr, r, bkey):
                raise KeyError('Invalid filter: {}'.format(key))

        return makeVariantMetadata(self.record.header, BCF_HL_FLT, id)

    def add(self, key):
        """Add a new filter"""
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef int id

        if key == '.':
            key = 'PASS'

        cdef bytes bkey = force_bytes(key)
        id = bcf_hdr_id2int(hdr, BCF_DT_ID, bkey)

        if not check_header_id(hdr, BCF_HL_FLT, id):
            raise KeyError('Invalid filter: {}'.format(key))

        bcf_add_filter(hdr, r, id)

    def __delitem__(self, key):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef int index, id
        cdef int n = r.d.n_flt

        if isinstance(key, int):
            index = key

            if index < 0 or index >= n:
                raise IndexError('invalid filter index')

            id = r.d.flt[index]
        else:
            if key == '.':
                key = 'PASS'

            bkey = force_bytes(key)
            id = bcf_hdr_id2int(hdr, BCF_DT_ID, bkey)

            if not check_header_id(hdr, BCF_HL_FLT, id) or not bcf_has_filter(hdr, r, bkey):
                raise KeyError('Invalid filter: {}'.format(key))

        bcf_remove_filter(hdr, r, id, 0)

    def clear(self):
        """Clear all filters"""
        cdef bcf1_t *r = self.record.ptr
        r.d.shared_dirty |= BCF1_DIRTY_FLT
        r.d.n_flt = 0

    def __iter__(self):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef int i

        for i in range(r.d.n_flt):
            yield bcf_str_cache_get_charptr(bcf_hdr_int2id(hdr, BCF_DT_ID, r.d.flt[i]))

    def get(self, key, default=None):
        """D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None."""
        try:
            return self[key]
        except KeyError:
            return default

    def __contains__(self, key):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef bytes bkey = force_bytes(key)
        return bcf_has_filter(hdr, r, bkey) == 1

    def iterkeys(self):
        """D.iterkeys() -> an iterator over the keys of D"""
        return iter(self)

    def itervalues(self):
        """D.itervalues() -> an iterator over the values of D"""
        for key in self:
            yield self[key]

    def iteritems(self):
        """D.iteritems() -> an iterator over the (key, value) items of D"""
        for key in self:
            yield (key, self[key])

    def keys(self):
        """D.keys() -> list of D's keys"""
        return list(self)

    def items(self):
        """D.items() -> list of D's (key, value) pairs, as 2-tuples"""
        return list(self.iteritems())

    def values(self):
        """D.values() -> list of D's values"""
        return list(self.itervalues())

    def __richcmp__(VariantRecordFilter self not None, VariantRecordFilter other not None, int op):
        if op != 2 and op != 3:
            return NotImplemented

        cdef bcf1_t *s = self.record.ptr
        cdef bcf1_t *o = other.record.ptr

        cdef bint cmp = (s.d.n_flt == o.d.n_flt and list(self) == list(other))

        if op == 3:
            cmp = not cmp

        return cmp

    # Mappings are not hashable by default, but subclasses can change this
    __hash__ = None

    #TODO: implement __richcmp__


cdef VariantRecordFilter makeVariantRecordFilter(VariantRecord record):
    if not record:
        raise ValueError('invalid VariantRecord')

    cdef VariantRecordFilter filter = VariantRecordFilter.__new__(VariantRecordFilter)
    filter.record = record

    return filter


cdef class VariantRecordFormat(object):
    """Format data present for each sample in a :class:`VariantRecord` object,
       presented as mapping from format name to :class:`VariantMetadata` object."""
    def __init__(self, *args, **kwargs):
        raise TypeError('this class cannot be instantiated from Python')

    def __len__(self):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef int i, n = 0

        for i in range(r.n_fmt):
            if r.d.fmt[i].p:
                n += 1
        return n

    def __bool__(self):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef int i

        for i in range(r.n_fmt):
            if r.d.fmt[i].p:
                return True
        return False

    def __getitem__(self, key):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr

        cdef bytes bkey = force_bytes(key)
        cdef bcf_fmt_t *fmt = bcf_get_fmt(hdr, r, bkey)

        if not fmt or not fmt.p:
            raise KeyError('unknown format: {}'.format(key))

        return makeVariantMetadata(self.record.header, BCF_HL_FMT, fmt.id)

    def __delitem__(self, key):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr

        cdef bytes bkey = force_bytes(key)
        cdef bcf_fmt_t *fmt = bcf_get_fmt(hdr, r, bkey)

        if not fmt or not fmt.p:
            raise KeyError('unknown format: {}'.format(key))

        if bcf_update_format(hdr, r, bkey, fmt.p, 0, fmt.type) < 0:
            raise ValueError('Unable to delete FORMAT')

    def clear(self):
        """Clear all formats for all samples within the associated
           :class:`VariantRecord` instance"""
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef bcf_fmt_t *fmt
        cdef const char *key
        cdef int i

        for i in reversed(range(r.n_fmt)):
            fmt = &r.d.fmt[i]
            if fmt.p:
                key = bcf_hdr_int2id(hdr, BCF_DT_ID, fmt.id)
                if bcf_update_format(hdr, r, key, fmt.p, 0, fmt.type) < 0:
                    raise ValueError('Unable to delete FORMAT')

    def __iter__(self):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef bcf_fmt_t *fmt
        cdef int i

        for i in range(r.n_fmt):
            fmt = &r.d.fmt[i]
            if fmt.p:
                yield bcf_str_cache_get_charptr(bcf_hdr_int2id(hdr, BCF_DT_ID, fmt.id))

    def get(self, key, default=None):
        """D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None."""
        try:
            return self[key]
        except KeyError:
            return default

    def __contains__(self, key):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef bytes bkey = force_bytes(key)
        cdef bcf_fmt_t *fmt = bcf_get_fmt(hdr, r, bkey)
        return fmt != NULL and fmt.p != NULL

    def iterkeys(self):
        """D.iterkeys() -> an iterator over the keys of D"""
        return iter(self)

    def itervalues(self):
        """D.itervalues() -> an iterator over the values of D"""
        for key in self:
            yield self[key]

    def iteritems(self):
        """D.iteritems() -> an iterator over the (key, value) items of D"""
        for key in self:
            yield (key, self[key])

    def keys(self):
        """D.keys() -> list of D's keys"""
        return list(self)

    def items(self):
        """D.items() -> list of D's (key, value) pairs, as 2-tuples"""
        return list(self.iteritems())

    def values(self):
        """D.values() -> list of D's values"""
        return list(self.itervalues())

    # Mappings are not hashable by default, but subclasses can change this
    __hash__ = None

    #TODO: implement __richcmp__


cdef VariantRecordFormat makeVariantRecordFormat(VariantRecord record):
    if not record:
        raise ValueError('invalid VariantRecord')

    cdef VariantRecordFormat format = VariantRecordFormat.__new__(VariantRecordFormat)
    format.record = record

    return format


#TODO: Add a getmeta method to return the corresponding VariantMetadata?
cdef class VariantRecordInfo(object):
    """Info data stored in a :class:`VariantRecord` object, presented as a
       mapping from info metadata name to value."""

    def __init__(self, *args, **kwargs):
        raise TypeError('this class cannot be instantiated from Python')

    def __len__(self):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef bcf_info_t *info
        cdef const char *key
        cdef int i, count = 0

        if bcf_unpack(r, BCF_UN_INFO) < 0:
            raise ValueError('Error unpacking VariantRecord')

        for i in range(r.n_info):
            info = &r.d.info[i]
            key = bcf_hdr_int2id(hdr, BCF_DT_ID, info.key)
            if info != NULL and info.vptr != NULL and strcmp(key, b'END') != 0:
                count += 1

        return count

    def __bool__(self):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef bcf_info_t *info
        cdef const char *key
        cdef int i

        if bcf_unpack(r, BCF_UN_INFO) < 0:
            raise ValueError('Error unpacking VariantRecord')

        for i in range(r.n_info):
            info = &r.d.info[i]
            key = bcf_hdr_int2id(hdr, BCF_DT_ID, info.key)
            if info != NULL and info.vptr != NULL and strcmp(key, b'END') != 0:
                return True

        return False

    def __getitem__(self, key):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr

        if bcf_unpack(r, BCF_UN_INFO) < 0:
            raise ValueError('Error unpacking VariantRecord')

        cdef bytes bkey = force_bytes(key)

        if strcmp(bkey, b'END') == 0:
            raise KeyError('END is a reserved attribute; access is via record.stop')

        cdef bcf_info_t *info = bcf_get_info(hdr, r, bkey)

        # Cannot stop here if info == NULL, since flags must return False
        cdef int info_id = bcf_header_get_info_id(hdr, bkey) if not info else info.key

        if info_id < 0:
            raise KeyError('Unknown INFO field: {}'.format(key))

        if not check_header_id(hdr, BCF_HL_INFO, info_id):
            raise ValueError('Invalid header')

        # Handle type=Flag values
        if bcf_hdr_id2type(hdr, BCF_HL_INFO, info_id) == BCF_HT_FLAG:
            return info != NULL and info.vptr != NULL

        if not info or not info.vptr:
            raise KeyError('Invalid INFO field: {}'.format(key))

        return bcf_info_get_value(self.record, info)

    def __setitem__(self, key, value):
        cdef bytes bkey = force_bytes(key)

        if strcmp(bkey, b'END') == 0:
            raise KeyError('END is a reserved attribute; access is via record.stop')

        if bcf_unpack(self.record.ptr, BCF_UN_INFO) < 0:
            raise ValueError('Error unpacking VariantRecord')

        bcf_info_set_value(self.record, key, value)

    def __delitem__(self, key):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr

        cdef bytes bkey = force_bytes(key)
        if strcmp(bkey, b'END') == 0:
            raise KeyError('END is a reserved attribute; access is via record.stop')

        if bcf_unpack(r, BCF_UN_INFO) < 0:
            raise ValueError('Error unpacking VariantRecord')

        cdef bcf_info_t *info = bcf_get_info(hdr, r, bkey)

        # Cannot stop here if info == NULL, since flags must return False
        cdef int info_id = bcf_header_get_info_id(hdr, bkey) if not info else info.key

        if info_id < 0:
            raise KeyError('Unknown INFO field: {}'.format(key))

        if not check_header_id(hdr, BCF_HL_INFO, info_id):
            raise ValueError('Invalid header')

        # Handle flags
        if bcf_hdr_id2type(hdr, BCF_HL_INFO, info_id) == BCF_HT_FLAG and (not info or not info.vptr):
            return

        if not info or not info.vptr:
            raise KeyError('Unknown INFO field: {}'.format(key))

        if bcf_update_info(hdr, r, bkey, NULL, 0, info.type) < 0:
            raise ValueError('Unable to delete INFO')

    def clear(self):
        """Clear all info data"""
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef bcf_info_t *info
        cdef const char *key
        cdef int i

        if bcf_unpack(r, BCF_UN_INFO) < 0:
            raise ValueError('Error unpacking VariantRecord')

        for i in range(r.n_info):
            info = &r.d.info[i]
            if info and info.vptr:
                key = bcf_hdr_int2id(hdr, BCF_DT_ID, info.key)
                if strcmp(key, b'END') == 0:
                    continue
                if bcf_update_info(hdr, r, key, NULL, 0, info.type) < 0:
                    raise ValueError('Unable to delete INFO')

    def __iter__(self):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef bcf_info_t *info
        cdef const char *key
        cdef int i

        if bcf_unpack(r, BCF_UN_INFO) < 0:
            raise ValueError('Error unpacking VariantRecord')

        for i in range(r.n_info):
            info = &r.d.info[i]
            if info and info.vptr:
                key = bcf_hdr_int2id(hdr, BCF_DT_ID, info.key)
                if strcmp(key, b'END') != 0:
                    yield bcf_str_cache_get_charptr(key)

    def get(self, key, default=None):
        """D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None."""
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr

        if bcf_unpack(r, BCF_UN_INFO) < 0:
            raise ValueError('Error unpacking VariantRecord')

        cdef bytes bkey = force_bytes(key)

        if strcmp(bkey, b'END') == 0:
            return default

        cdef bcf_info_t *info = bcf_get_info(hdr, r, bkey)

        # Cannot stop here if info == NULL, since flags must return False
        cdef int info_id = bcf_header_get_info_id(hdr, bkey) if not info else info.key

        if not check_header_id(hdr, BCF_HL_INFO, info_id):
            raise ValueError('Invalid header')

        # Handle flags
        if bcf_hdr_id2type(hdr, BCF_HL_INFO, info_id) == BCF_HT_FLAG:
            return info != NULL and info.vptr != NULL

        if not info or not info.vptr:
            return default

        return bcf_info_get_value(self.record, info)

    def __contains__(self, key):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr

        if bcf_unpack(r, BCF_UN_INFO) < 0:
            raise ValueError('Error unpacking VariantRecord')

        cdef bytes bkey = force_bytes(key)

        if strcmp(bkey, b'END') == 0:
            return False

        cdef bcf_info_t *info = bcf_get_info(hdr, r, bkey)

        return info != NULL and info.vptr != NULL

    def iterkeys(self):
        """D.iterkeys() -> an iterator over the keys of D"""
        return iter(self)

    def itervalues(self):
        """D.itervalues() -> an iterator over the values of D"""
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef bcf_info_t *info
        cdef const char *key
        cdef int i

        if bcf_unpack(r, BCF_UN_INFO) < 0:
            raise ValueError('Error unpacking VariantRecord')

        for i in range(r.n_info):
            info = &r.d.info[i]
            if info and info.vptr:
                key = bcf_hdr_int2id(hdr, BCF_DT_ID, info.key)
                if strcmp(key, b'END') != 0:
                    yield bcf_info_get_value(self.record, info)

    def iteritems(self):
        """D.iteritems() -> an iterator over the (key, value) items of D"""
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef bcf_info_t *info
        cdef const char *key
        cdef int i

        if bcf_unpack(r, BCF_UN_INFO) < 0:
            raise ValueError('Error unpacking VariantRecord')

        for i in range(r.n_info):
            info = &r.d.info[i]
            if info and info.vptr:
                key = bcf_hdr_int2id(hdr, BCF_DT_ID, info.key)
                if strcmp(key, b'END') != 0:
                    value = bcf_info_get_value(self.record, info)
                    yield bcf_str_cache_get_charptr(key), value

    def keys(self):
        """D.keys() -> list of D's keys"""
        return list(self)

    def items(self):
        """D.items() -> list of D's (key, value) pairs, as 2-tuples"""
        return list(self.iteritems())

    def values(self):
        """D.values() -> list of D's values"""
        return list(self.itervalues())

    def update(self, items=None, **kwargs):
        """D.update([E, ]**F) -> None.

        Update D from dict/iterable E and F.
        """
        for k, v in items.items():
            if k != 'END':
                self[k] = v

        if kwargs:
            kwargs.pop('END', None)
            for k, v in kwargs.items():
                self[k] = v

    def pop(self, key, default=_nothing):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr

        if bcf_unpack(r, BCF_UN_INFO) < 0:
            raise ValueError('Error unpacking VariantRecord')

        cdef bytes bkey = force_bytes(key)
        cdef bcf_info_t *info = bcf_get_info(hdr, r, bkey)

        # Cannot stop here if info == NULL, since flags must return False
        cdef int info_id = bcf_header_get_info_id(hdr, bkey) if not info else info.key

        if info_id < 0:
            if default is _nothing:
                raise KeyError('Unknown INFO field: {}'.format(key))
            return default

        if not check_header_id(hdr, BCF_HL_INFO, info_id):
            raise ValueError('Invalid header')

        # Handle flags
        if bcf_hdr_id2type(hdr, BCF_HL_INFO, info_id) == BCF_HT_FLAG and (not info or not info.vptr):
            return

        if not info or not info.vptr:
            if default is _nothing:
                raise KeyError('Unknown INFO field: {}'.format(key))
            return default

        value = bcf_info_get_value(self.record, info)

        if bcf_update_info(hdr, r, bkey, NULL, 0, info.type) < 0:
            raise ValueError('Unable to delete INFO')

        return value

    def __richcmp__(VariantRecordInfo self not None, VariantRecordInfo other not None, int op):
        if op != 2 and op != 3:
            return NotImplemented

        cdef bcf1_t *s = self.record.ptr
        cdef bcf1_t *o = other.record.ptr

        # Cannot use n_info as shortcut logic, since null values may remain
        cdef bint cmp = dict(self) == dict(other)

        if op == 3:
            cmp = not cmp

        return cmp

    # Mappings are not hashable by default, but subclasses can change this
    __hash__ = None


cdef VariantRecordInfo makeVariantRecordInfo(VariantRecord record):
    if not record:
        raise ValueError('invalid VariantRecord')

    cdef VariantRecordInfo info = VariantRecordInfo.__new__(VariantRecordInfo)
    info.record = record

    return info


cdef class VariantRecordSamples(object):
    """mapping from sample index or name to :class:`VariantRecordSample` object."""
    def __init__(self, *args, **kwargs):
        raise TypeError('this class cannot be instantiated from Python')

    def __len__(self):
        return self.record.ptr.n_sample  # bcf_hdr_nsamples(self.record.header.ptr)

    def __bool__(self):
        return self.record.ptr.n_sample != 0  # bcf_hdr_nsamples(self.record.header.ptr) != 0

    def __getitem__(self, key):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef int n = self.record.ptr.n_sample
        cdef int sample_index
        cdef vdict_t *d
        cdef khiter_t k

        if isinstance(key, int):
            sample_index = key
        else:
            bkey = force_bytes(key)
            sample_index = bcf_hdr_id2int(hdr, BCF_DT_SAMPLE, bkey)
            if sample_index < 0:
                raise KeyError('invalid sample name: {}'.format(key))

        if sample_index < 0 or sample_index >= n:
            raise IndexError('invalid sample index')

        return makeVariantRecordSample(self.record, sample_index)

    def __iter__(self):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef int32_t i, n = self.record.ptr.n_sample

        for i in range(n):
            yield charptr_to_str(hdr.samples[i])

    def get(self, key, default=None):
        """D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None."""
        try:
            return self[key]
        except KeyError:
            return default

    def __contains__(self, key):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef int n = self.record.ptr.n_sample
        cdef int sample_index
        cdef vdict_t *d
        cdef khiter_t k

        if isinstance(key, int):
            sample_index = key
        else:
            bkey = force_bytes(key)
            sample_index = bcf_hdr_id2int(hdr, BCF_DT_SAMPLE, bkey)
            if sample_index < 0:
                raise KeyError('invalid sample name: {}'.format(key))

        return 0 <= sample_index < n

    def iterkeys(self):
        """D.iterkeys() -> an iterator over the keys of D"""
        return iter(self)

    def itervalues(self):
        """D.itervalues() -> an iterator over the values of D"""
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef int32_t i, n = self.record.ptr.n_sample

        for i in range(n):
            yield makeVariantRecordSample(self.record, i)

    def iteritems(self):
        """D.iteritems() -> an iterator over the (key, value) items of D"""
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef int32_t i, n = self.record.ptr.n_sample

        for i in range(n):
            yield (charptr_to_str(hdr.samples[i]), makeVariantRecordSample(self.record, i))

    def keys(self):
        """D.keys() -> list of D's keys"""
        return list(self)

    def items(self):
        """D.items() -> list of D's (key, value) pairs, as 2-tuples"""
        return list(self.iteritems())

    def values(self):
        """D.values() -> list of D's values"""
        return list(self.itervalues())

    def update(self, items=None, **kwargs):
        """D.update([E, ]**F) -> None.

        Update D from dict/iterable E and F.
        """
        for k, v in items.items():
            self[k] = v

        if kwargs:
            for k, v in kwargs.items():
                self[k] = v

    def pop(self, key, default=_nothing):
        try:
            value = self[key]
            del self[key]
            return value
        except KeyError:
            if default is not _nothing:
                return default
            raise

    def __richcmp__(VariantRecordSamples self not None, VariantRecordSamples other not None, int op):
        if op != 2 and op != 3:
            return NotImplemented

        cdef bcf1_t *s = self.record.ptr
        cdef bcf1_t *o = other.record.ptr

        cdef bint cmp = (s.n_sample == o.n_sample and self.values() == other.values())

        if op == 3:
            cmp = not cmp

        return cmp

    # Mappings are not hashable by default, but subclasses can change this
    __hash__ = None


cdef VariantRecordSamples makeVariantRecordSamples(VariantRecord record):
    if not record:
        raise ValueError('invalid VariantRecord')

    cdef VariantRecordSamples samples = VariantRecordSamples.__new__(
        VariantRecordSamples)
    samples.record = record

    return samples


cdef class VariantRecord(object):
    """Variant record"""
    def __init__(self, *args, **kwargs):
        raise TypeError('this class cannot be instantiated from Python')

    def __dealloc__(self):
        if self.ptr:
            bcf_destroy1(self.ptr)
            self.ptr = NULL

    def copy(self):
        """return a copy of this VariantRecord object"""
        return makeVariantRecord(self.header, bcf_dup(self.ptr))

    def translate(self, VariantHeader dst_header):
        if dst_header is None:
            raise ValueError('dst_header must not be None')

        cdef bcf_hdr_t *src_hdr = self.header.ptr
        cdef bcf_hdr_t *dst_hdr = dst_header.ptr

        if src_hdr != dst_hdr:
            if self.ptr.n_sample != bcf_hdr_nsamples(dst_hdr):
                msg = 'Cannot translate record.  Number of samples does not match header ({} vs {})'
                raise ValueError(msg.format(self.ptr.n_sample, bcf_hdr_nsamples(dst_hdr)))

            bcf_translate(dst_hdr, src_hdr, self.ptr)
            self.header = dst_header

    @property
    def rid(self):
        """internal reference id number"""
        return self.ptr.rid

    @rid.setter
    def rid(self, value):
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef int r = value
        if r < 0 or r >= hdr.n[BCF_DT_CTG] or not hdr.id[BCF_DT_CTG][r].val:
            raise ValueError('invalid reference id')
        self.ptr.rid = r

    @property
    def chrom(self):
        """chromosome/contig name"""
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef int rid = self.ptr.rid
        if rid < 0 or rid >= hdr.n[BCF_DT_CTG]:
            raise ValueError('Invalid header')
        return bcf_str_cache_get_charptr(bcf_hdr_id2name(hdr, rid))

    @chrom.setter
    def chrom(self, value):
        cdef vdict_t *d = <vdict_t*>self.header.ptr.dict[BCF_DT_CTG]
        bchrom = force_bytes(value)
        cdef khint_t k = kh_get_vdict(d, bchrom)
        if k == kh_end(d):
            raise ValueError('Invalid chromosome/contig')
        self.ptr.rid = kh_val_vdict(d, k).id

    @property
    def contig(self):
        """chromosome/contig name"""
        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef int rid = self.ptr.rid
        if rid < 0 or rid >= hdr.n[BCF_DT_CTG]:
            raise ValueError('Invalid header')
        return bcf_str_cache_get_charptr(bcf_hdr_id2name(hdr, rid))

    @contig.setter
    def contig(self, value):
        cdef vdict_t *d = <vdict_t*>self.header.ptr.dict[BCF_DT_CTG]
        bchrom = force_bytes(value)
        cdef khint_t k = kh_get_vdict(d, bchrom)
        if k == kh_end(d):
            raise ValueError('Invalid chromosome/contig')
        self.ptr.rid = kh_val_vdict(d, k).id

    @property
    def pos(self):
        """record start position on chrom/contig (1-based inclusive)"""
        return self.ptr.pos + 1

    @pos.setter
    def pos(self, value):
        cdef int p = value
        if p < 1:
            raise ValueError('Position must be positive')
        self.ptr.pos = p - 1
        bcf_sync_end(self)

    @property
    def start(self):
        """record start position on chrom/contig (0-based inclusive)"""
        return self.ptr.pos

    @start.setter
    def start(self, value):
        cdef int s = value
        if s < 0:
            raise ValueError('Start coordinate must be non-negative')
        self.ptr.pos = s
        bcf_sync_end(self)

    @property
    def stop(self):
        """record stop position on chrom/contig (0-based exclusive)"""
        return self.ptr.pos + self.ptr.rlen

    @stop.setter
    def stop(self, value):
        cdef int s = value
        if s < 0:
            raise ValueError('Stop coordinate must be non-negative')
        self.ptr.rlen = s - self.ptr.pos
        bcf_sync_end(self)

    @property
    def rlen(self):
        """record length on chrom/contig (aka rec.stop - rec.start)"""
        return self.ptr.rlen

    @rlen.setter
    def rlen(self, value):
        cdef int r = value
        self.ptr.rlen = r
        bcf_sync_end(self)

    @property
    def qual(self):
        """phred scaled quality score or None if not available"""
        return self.ptr.qual if not bcf_float_is_missing(self.ptr.qual) else None

    @qual.setter
    def qual(self, value):
        if value is not None:
            self.ptr.qual = value
        else:
            bcf_float_set(&self.ptr.qual, bcf_float_missing)


#   @property
#   def n_allele(self):
#       return self.ptr.n_allele

#   @property
#   def n_sample(self):
#       return self.ptr.n_sample

    @property
    def id(self):
        """record identifier or None if not available"""
        cdef bcf1_t *r = self.ptr
        if bcf_unpack(r, BCF_UN_STR) < 0:
            raise ValueError('Error unpacking VariantRecord')
        # causes a memory leak https://github.com/pysam-developers/pysam/issues/773
        # return bcf_str_cache_get_charptr(r.d.id) if r.d.id != b'.' else None
        if (r.d.m_id == 0):
            raise ValueError('Error extracting ID')
        return charptr_to_str(r.d.id) if r.d.id != b'.' else None

    @id.setter
    def id(self, value):
        cdef bcf1_t *r = self.ptr
        if bcf_unpack(r, BCF_UN_STR) < 0:
            raise ValueError('Error unpacking VariantRecord')
        cdef char *idstr = NULL
        if value is not None:
            bid = force_bytes(value)
            idstr = bid
        if bcf_update_id(self.header.ptr, self.ptr, idstr) < 0:
            raise ValueError('Error updating id')

    @property
    def ref(self):
        """reference allele"""
        cdef bcf1_t *r = self.ptr
        if bcf_unpack(r, BCF_UN_STR) < 0:
            raise ValueError('Error unpacking VariantRecord')
        return charptr_to_str(r.d.allele[0]) if r.d.allele else None

    @ref.setter
    def ref(self, value):
        cdef bcf1_t *r = self.ptr
        if bcf_unpack(r, BCF_UN_STR) < 0:
            raise ValueError('Error unpacking VariantRecord')
        #FIXME: Set alleles directly -- this is stupid
        if not value:
            raise ValueError('ref allele must not be null')
        value = force_bytes(value)
        if r.d.allele and r.n_allele:
            alleles = [r.d.allele[i] for i in range(r.n_allele)]
            alleles[0] = value
        else:
            alleles = [value, '<NON_REF>']
        self.alleles = alleles
        bcf_sync_end(self)

    @property
    def alleles(self):
        """tuple of reference allele followed by alt alleles"""
        cdef bcf1_t *r = self.ptr
        if bcf_unpack(r, BCF_UN_STR) < 0:
            raise ValueError('Error unpacking VariantRecord')
        if not r.d.allele:
            return None
        cdef tuple res = PyTuple_New(r.n_allele)
        for i in range(r.n_allele):
            a = charptr_to_str(r.d.allele[i])
            PyTuple_SET_ITEM(res, i, a)
            Py_INCREF(a)
        return res

    @alleles.setter
    def alleles(self, values):
        cdef bcf1_t *r = self.ptr

        # Cache rlen of symbolic alleles before call to bcf_update_alleles_str
        cdef int rlen = r.rlen

        if bcf_unpack(r, BCF_UN_STR) < 0:
            raise ValueError('Error unpacking VariantRecord')

        values = [force_bytes(v) for v in values]

        if len(values) < 2:
            raise ValueError('must set at least 2 alleles')

        if b'' in values:
            raise ValueError('cannot set null allele')

        value = b','.join(values)

        if bcf_update_alleles_str(self.header.ptr, r, value) < 0:
            raise ValueError('Error updating alleles')

        # Reset rlen if alternate allele isn't symbolic, otherwise used cached
        if has_symbolic_allele(self):
            self.ptr.rlen = rlen
        else:
            self.ptr.rlen = len(values[0])
        r.d.var_type = -1
        bcf_sync_end(self)

    @property
    def alts(self):
        """tuple of alt alleles"""
        cdef bcf1_t *r = self.ptr
        if bcf_unpack(r, BCF_UN_STR) < 0:
            raise ValueError('Error unpacking VariantRecord')
        if r.n_allele < 2 or not r.d.allele:
            return None
        cdef tuple res = PyTuple_New(r.n_allele - 1)
        for i in range(1, r.n_allele):
            a = charptr_to_str(r.d.allele[i])
            PyTuple_SET_ITEM(res, i - 1, a)
            Py_INCREF(a)
        return res

    @alts.setter
    def alts(self, value):
        #FIXME: Set alleles directly -- this is stupid
        cdef bcf1_t *r = self.ptr
        if bcf_unpack(r, BCF_UN_STR) < 0:
            raise ValueError('Error unpacking VariantRecord')
        value = [force_bytes(v) for v in value]
        if b'' in value:
            raise ValueError('cannot set null alt allele')
        ref  = [r.d.allele[0] if r.d.allele and r.n_allele else b'.']
        self.alleles = ref + value
        r.d.var_type = -1

    @property
    def filter(self):
        """filter information (see :class:`VariantRecordFilter`)"""
        if bcf_unpack(self.ptr, BCF_UN_FLT) < 0:
            raise ValueError('Error unpacking VariantRecord')
        return makeVariantRecordFilter(self)

    @property
    def info(self):
        """info data (see :class:`VariantRecordInfo`)"""
        if bcf_unpack(self.ptr, BCF_UN_INFO) < 0:
            raise ValueError('Error unpacking VariantRecord')
        return makeVariantRecordInfo(self)

    @property
    def format(self):
        """sample format metadata (see :class:`VariantRecordFormat`)"""
        if bcf_unpack(self.ptr, BCF_UN_FMT) < 0:
            raise ValueError('Error unpacking VariantRecord')
        return makeVariantRecordFormat(self)

    @property
    def samples(self):
        """sample data (see :class:`VariantRecordSamples`)"""
        if bcf_unpack(self.ptr, BCF_UN_ALL) < 0:
            raise ValueError('Error unpacking VariantRecord')
        return makeVariantRecordSamples(self)

    property alleles_variant_types:
        def __get__(self):
            cdef bcf1_t *r = self.ptr
            cdef tuple result = PyTuple_New(r.n_allele)

            for i in range(r.n_allele):
                tp = bcf_get_variant_type(r, i)

                if tp == VCF_REF:
                    v_type = "REF"
                elif tp == VCF_SNP:
                    v_type = "SNP"
                elif tp == VCF_MNP:
                    v_type = "MNP"
                elif tp == VCF_INDEL:
                    v_type = "INDEL"
                elif tp == VCF_BND:
                    v_type = "BND"
                elif tp == VCF_OVERLAP:
                    v_type = "OVERLAP"
                else:
                    v_type = "OTHER"

                PyTuple_SET_ITEM(result, i, v_type)
                Py_INCREF(v_type)

            return result

    def __richcmp__(VariantRecord self not None, VariantRecord other not None, int op):
        if op != 2 and op != 3:
            return NotImplemented

        cdef bcf1_t *s = self.ptr
        cdef bcf1_t *o = other.ptr

        cdef bint cmp = self is other or (
                             s.pos        == o.pos
                        and  s.rlen       == o.rlen
                        and ((bcf_float_is_missing(s.qual) and bcf_float_is_missing(o.qual))
                          or s.qual       == o.qual)
                        and  s.n_sample   == o.n_sample
                        and  s.n_allele   == o.n_allele
                        and  self.contig  == other.contig
                        and  self.alleles == other.alleles
                        and  self.id      == other.id
                        and  self.info    == other.info
                        and  self.filter  == other.filter
                        and  self.samples == other.samples)

        if op == 3:
            cmp = not cmp

        return cmp

    def __str__(self):
        cdef kstring_t line
        cdef char c

        line.l = line.m = 0
        line.s = NULL

        if vcf_format(self.header.ptr, self.ptr, &line) < 0:
            if line.m:
                free(line.s)
            raise ValueError('vcf_format failed')

        # Strip CR/LF?
        #while line.l:
        #    c = line.s[line.l - 1]
        #    if c != b'\n' and c != b'\r':
        #        break
        #    line.l -= 1

        ret = charptr_to_str_w_len(line.s, line.l)

        if line.m:
            free(line.s)

        return ret


cdef VariantRecord makeVariantRecord(VariantHeader header, bcf1_t *r):
    if not header:
        raise ValueError('invalid VariantHeader')

    if not r:
        raise ValueError('cannot create VariantRecord')

    if r.errcode:
        msg = []
        #if r.errcode & BCF_ERR_CTG_UNDEF:
        #    msg.append('undefined contig')
        #if r.errcode & BCF_ERR_TAG_UNDEF:
        #    msg.append('undefined tag')
        if r.errcode & BCF_ERR_NCOLS:
            msg.append('invalid number of columns')
        if r.errcode & BCF_ERR_LIMITS:
            msg.append('limits violated')
        if r.errcode & BCF_ERR_CHAR:
            msg.append('invalid character found')
        if r.errcode & BCF_ERR_CTG_INVALID:
            msg.append('invalid contig')
        if r.errcode & BCF_ERR_TAG_INVALID:
            msg.append('invalid tag')

        if msg:
            msg = ', '.join(msg)
            raise ValueError('Error(s) reading record: {}'.format(msg))

    cdef VariantRecord record = VariantRecord.__new__(VariantRecord)
    record.header = header
    record.ptr = r

    return record


########################################################################
########################################################################
## Variant Sampletype object
########################################################################


cdef class VariantRecordSample(object):
    """Data for a single sample from a :class:`VariantRecord` object.
       Provides data accessors for genotypes and a mapping interface
       from format name to values.
    """
    def __init__(self, *args, **kwargs):
        raise TypeError('this class cannot be instantiated from Python')

    @property
    def name(self):
        """sample name"""
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef int32_t n = r.n_sample

        if self.index < 0 or self.index >= n:
            raise ValueError('invalid sample index')

        return charptr_to_str(hdr.samples[self.index])

    @property
    def allele_indices(self):
        """allele indices for called genotype, if present.  Otherwise None"""
        return bcf_format_get_allele_indices(self)

    @allele_indices.setter
    def allele_indices(self, value):
        self['GT'] = value

    @allele_indices.deleter
    def allele_indices(self):
        self['GT'] = ()

    @property
    def alleles(self):
        """alleles for called genotype, if present.  Otherwise None"""
        return bcf_format_get_alleles(self)

    @alleles.setter
    def alleles(self, value):
        # Sets the genotype, supply a tuple of alleles to set.
        # The supplied alleles need to be defined in the correspoding pysam.libcbcf.VariantRecord
        # The genotype is reset when an empty tuple, None or (None,) is supplied

        if value==(None,) or value==tuple() or value is None:
            self['GT'] = ()
            return

        if any((type(x) == int for x in value)):
            raise ValueError('Use .allele_indices to set integer allele indices')

        # determine and set allele indices:    
        try:
            self['GT'] = tuple( (self.record.alleles.index(allele) for allele in value) )
        except ValueError:
            raise ValueError("One or more of the supplied sample alleles are not defined as alleles of the corresponding pysam.libcbcf.VariantRecord."
                             "First set the .alleles of this record to define the alleles")

    @alleles.deleter
    def alleles(self):
        self['GT'] = ()

    @property
    def phased(self):
        """False if genotype is missing or any allele is unphased.  Otherwise True."""
        return bcf_sample_get_phased(self)

    @phased.setter
    def phased(self, value):
        bcf_sample_set_phased(self, value)

    def __len__(self):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef int i, n = 0

        if bcf_unpack(r, BCF_UN_FMT) < 0:
            raise ValueError('Error unpacking VariantRecord')

        for i in range(r.n_fmt):
            if r.d.fmt[i].p:
                n += 1
        return n

    def __bool__(self):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef int i

        if bcf_unpack(r, BCF_UN_FMT) < 0:
            raise ValueError('Error unpacking VariantRecord')

        for i in range(r.n_fmt):
            if r.d.fmt[i].p:
                return True
        return False

    def __getitem__(self, key):
        return bcf_format_get_value(self, key)

    def __setitem__(self, key, value):
        bcf_format_set_value(self, key, value)

    def __delitem__(self, key):
        bcf_format_del_value(self, key)

    def clear(self):
        """Clear all format data (including genotype) for this sample"""
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef bcf_fmt_t *fmt
        cdef int i

        for i in range(r.n_fmt):
            fmt = &r.d.fmt[i]
            if fmt.p:
                bcf_format_del_value(self, bcf_hdr_int2id(hdr, BCF_DT_ID, fmt.id))

    def __iter__(self):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef bcf_fmt_t *fmt
        cdef int i

        for i in range(r.n_fmt):
            fmt = &r.d.fmt[i]
            if r.d.fmt[i].p:
                yield bcf_str_cache_get_charptr(bcf_hdr_int2id(hdr, BCF_DT_ID, fmt.id))

    def get(self, key, default=None):
        """D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None."""
        try:
            return self[key]
        except KeyError:
            return default

    def __contains__(self, key):
        cdef bcf_hdr_t *hdr = self.record.header.ptr
        cdef bcf1_t *r = self.record.ptr
        cdef bytes bkey = force_bytes(key)
        cdef bcf_fmt_t *fmt = bcf_get_fmt(hdr, r, bkey)
        return fmt != NULL and fmt.p != NULL

    def iterkeys(self):
        """D.iterkeys() -> an iterator over the keys of D"""
        return iter(self)

    def itervalues(self):
        """D.itervalues() -> an iterator over the values of D"""
        for key in self:
            yield self[key]

    def iteritems(self):
        """D.iteritems() -> an iterator over the (key, value) items of D"""
        for key in self:
            yield (key, self[key])

    def keys(self):
        """D.keys() -> list of D's keys"""
        return list(self)

    def items(self):
        """D.items() -> list of D's (key, value) pairs, as 2-tuples"""
        return list(self.iteritems())

    def values(self):
        """D.values() -> list of D's values"""
        return list(self.itervalues())

    def update(self, items=None, **kwargs):
        """D.update([E, ]**F) -> None.

        Update D from dict/iterable E and F.
        """
        for k, v in items.items():
            self[k] = v

        if kwargs:
            for k, v in kwargs.items():
                self[k] = v

    def pop(self, key, default=_nothing):
        try:
            value = self[key]
            del self[key]
            return value
        except KeyError:
            if default is not _nothing:
                return default
            raise

    def __richcmp__(VariantRecordSample self not None, VariantRecordSample other not None, int op):
        if op != 2 and op != 3:
            return NotImplemented

        cdef bint cmp = dict(self) == dict(other)

        if op == 3:
            cmp = not cmp

        return cmp

    # Mappings are not hashable by default, but subclasses can change this
    __hash__ = None


cdef VariantRecordSample makeVariantRecordSample(VariantRecord record, int32_t sample_index):
    if not record or sample_index < 0:
        raise ValueError('cannot create VariantRecordSample')

    cdef VariantRecordSample sample = VariantRecordSample.__new__(VariantRecordSample)
    sample.record = record
    sample.index = sample_index

    return sample


########################################################################
########################################################################
## Index objects
########################################################################


cdef class BaseIndex(object):
    def __init__(self):
        self.refs = ()
        self.remap = {}

    def __len__(self):
        return len(self.refs)

    def __bool__(self):
        return len(self.refs) != 0

    def __getitem__(self, key):
        if isinstance(key, int):
            return self.refs[key]
        else:
            return self.refmap[key]

    def __iter__(self):
        return iter(self.refs)

    def get(self, key, default=None):
        """D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None."""
        try:
            return self[key]
        except KeyError:
            return default

    def __contains__(self, key):
        try:
            self[key]
        except KeyError:
            return False
        else:
            return True

    def iterkeys(self):
        """D.iterkeys() -> an iterator over the keys of D"""
        return iter(self)

    def itervalues(self):
        """D.itervalues() -> an iterator over the values of D"""
        for key in self:
            yield self[key]

    def iteritems(self):
        """D.iteritems() -> an iterator over the (key, value) items of D"""
        for key in self:
            yield (key, self[key])

    def keys(self):
        """D.keys() -> list of D's keys"""
        return list(self)

    def items(self):
        """D.items() -> list of D's (key, value) pairs, as 2-tuples"""
        return list(self.iteritems())

    def values(self):
        """D.values() -> list of D's values"""
        return list(self.itervalues())

    def update(self, items=None, **kwargs):
        """D.update([E, ]**F) -> None.

        Update D from dict/iterable E and F.
        """
        for k, v in items.items():
            self[k] = v

        if kwargs:
            for k, v in kwargs.items():
                self[k] = v

    def pop(self, key, default=_nothing):
        try:
            value = self[key]
            del self[key]
            return value
        except KeyError:
            if default is not _nothing:
                return default
            raise

    # Mappings are not hashable by default, but subclasses can change this
    __hash__ = None

    #TODO: implement __richcmp__


cdef class BCFIndex(object):
    """CSI index data structure for BCF files"""
    def __init__(self):
        self.refs = ()
        self.refmap = {}

        if not self.ptr:
            raise ValueError('Invalid index object')

        cdef int n
        cdef const char **refs = bcf_index_seqnames(self.ptr, self.header.ptr, &n)

        self.refs = char_array_to_tuple(refs, n, free_after=1) if refs else ()
        self.refmap = { r:i for i,r in enumerate(self.refs) }

    def __dealloc__(self):
        if self.ptr:
            hts_idx_destroy(self.ptr)
            self.ptr = NULL

    def fetch(self, bcf, contig, start, stop, reopen):
        return BCFIterator(bcf, contig, start, stop, reopen)


cdef BCFIndex makeBCFIndex(VariantHeader header, hts_idx_t *idx):
    if not idx:
        return None

    if not header:
        raise ValueError('invalid VariantHeader')

    cdef BCFIndex index = BCFIndex.__new__(BCFIndex)
    index.header = header
    index.ptr = idx
    index.__init__()

    return index


cdef class TabixIndex(BaseIndex):
    """Tabix index data structure for VCF files"""
    def __init__(self):
        self.refs = ()
        self.refmap = {}

        if not self.ptr:
            raise ValueError('Invalid index object')

        cdef int n
        cdef const char **refs = tbx_seqnames(self.ptr, &n)

        self.refs = char_array_to_tuple(refs, n, free_after=1) if refs else ()
        self.refmap = { r:i for i,r in enumerate(self.refs) }

    def __dealloc__(self):
        if self.ptr:
            tbx_destroy(self.ptr)
            self.ptr = NULL

    def fetch(self, bcf, contig, start, stop, reopen):
        return TabixIterator(bcf, contig, start, stop, reopen)


cdef TabixIndex makeTabixIndex(tbx_t *idx):
    if not idx:
        return None

    cdef TabixIndex index = TabixIndex.__new__(TabixIndex)
    index.ptr = idx
    index.__init__()

    return index


########################################################################
########################################################################
## Iterators
########################################################################


cdef class BaseIterator(object):
    pass


# Internal function to clean up after iteration stop or failure.
# This would be a nested function if it weren't a cdef function.
cdef void _stop_BCFIterator(BCFIterator self, bcf1_t *record):
    bcf_destroy1(record)

    # destroy iter so future calls to __next__ raise StopIteration
    bcf_itr_destroy(self.iter)
    self.iter = NULL


cdef class BCFIterator(BaseIterator):
    def __init__(self, VariantFile bcf, contig=None, start=None, stop=None, reopen=True):
        if bcf is None:
            raise ValueError('bcf must not be None')

        if contig is None:
            raise ValueError('contig must be specified')

        if not isinstance(bcf.index, BCFIndex):
            raise ValueError('bcf index required')

        cdef BCFIndex index = bcf.index

        self.bcf = bcf
        self.index = index

        cdef int rid, cstart, cstop

        try:
            rid = index.refmap[contig]
        except KeyError:
            # A query for a non-existent contig yields an empty iterator, does not raise an error
            self.iter = NULL
            return

        if reopen:
            self.bcf = self.bcf.copy()

        cstart = start if start is not None else 0
        cstop  = stop  if stop  is not None else MAX_POS

        with nogil:
            self.iter = bcf_itr_queryi(index.ptr, rid, cstart, cstop)

        if not self.iter:
            if errno:
                raise IOError(errno, strerror(errno))
            else:
                raise IOError('unable to fetch {}:{}-{}'.format(contig, start+1, stop))

    def __dealloc__(self):
        if self.iter:
            bcf_itr_destroy(self.iter)
            self.iter = NULL

    def __iter__(self):
        return self

    def __next__(self):
        if not self.iter:
            raise StopIteration

        cdef bcf1_t *record = bcf_init1()

        if not record:
            raise MemoryError('unable to allocate BCF record')

        record.pos = -1
        if self.bcf.drop_samples:
            record.max_unpack = BCF_UN_SHR

        cdef int ret

        with nogil:
            ret = bcf_itr_next(self.bcf.htsfile, self.iter, record)

        if ret < 0:
            _stop_BCFIterator(self, record)
            if ret == -1:
                raise StopIteration
            elif ret == -2:
                raise IOError('truncated file')
            elif errno:
                raise IOError(errno, strerror(errno))
            else:
                raise IOError('unable to fetch next record')

        ret = bcf_subset_format(self.bcf.header.ptr, record)

        if ret < 0:
            _stop_BCFIterator(self, record)
            raise ValueError('error in bcf_subset_format')

        return makeVariantRecord(self.bcf.header, record)


cdef class TabixIterator(BaseIterator):
    def __cinit__(self, *args, **kwargs):
        self.line_buffer.l = 0
        self.line_buffer.m = 0
        self.line_buffer.s = NULL

    def __init__(self, VariantFile bcf, contig=None, start=None, stop=None, reopen=True):
        if bcf is None:
            raise ValueError('bcf must not be None')

        if not isinstance(bcf.index, TabixIndex):
            raise ValueError('tabix index required')

        cdef TabixIndex index = bcf.index

        self.bcf = bcf
        self.index = index

        cdef int rid, cstart, cstop

        try:
            rid = index.refmap[contig]
        except KeyError:
            # A query for a non-existent contig yields an empty iterator, does not raise an error
            self.iter = NULL
            return

        if reopen:
            self.bcf = self.bcf.copy()

        cstart = start if start is not None else 0
        cstop  = stop  if stop  is not None else MAX_POS

        self.iter = tbx_itr_queryi(index.ptr, rid, start, stop)

        if not self.iter:
            if errno:
                raise IOError(errno, strerror(errno))
            else:
                raise IOError('unable to fetch {}:{}-{}'.format(contig, start+1, stop))

    def __dealloc__(self):
        if self.iter:
            tbx_itr_destroy(self.iter)
            self.iter = NULL

        if self.line_buffer.m:
            free(self.line_buffer.s)

        self.line_buffer.l = 0
        self.line_buffer.m = 0
        self.line_buffer.s = NULL

    def __iter__(self):
        return self

    def __next__(self):
        if not self.iter:
            raise StopIteration

        cdef int ret

        with nogil:
            ret = tbx_itr_next(self.bcf.htsfile, self.index.ptr, self.iter, &self.line_buffer)

        if ret < 0:
            tbx_itr_destroy(self.iter)
            self.iter = NULL
            if ret == -1:
                raise StopIteration
            elif ret == -2:
                raise IOError('truncated file')
            elif errno:
                raise IOError(errno, strerror(errno))
            else:
                raise IOError('unable to fetch next record')

        cdef bcf1_t *record = bcf_init1()

        if not record:
            raise MemoryError('unable to allocate BCF record')

        record.pos = -1
        if self.bcf.drop_samples:
            record.max_unpack = BCF_UN_SHR

        ret = vcf_parse1(&self.line_buffer, self.bcf.header.ptr, record)

        # FIXME: stop iteration on parse failure?
        if ret < 0:
            bcf_destroy1(record)
            raise ValueError('error in vcf_parse')

        return makeVariantRecord(self.bcf.header, record)


########################################################################
########################################################################
## Variant File
########################################################################


cdef class VariantFile(HTSFile):
    """*(filename, mode=None, index_filename=None, header=None, drop_samples=False,
    duplicate_filehandle=True, ignore_truncation=False, threads=1)*

    A :term:`VCF`/:term:`BCF` formatted file. The file is automatically
    opened.

    If an index for a variant file exists (.csi or .tbi), it will be
    opened automatically.  Without an index random access to records
    via :meth:`fetch` is disabled.

    For writing, a :class:`VariantHeader` object must be provided,
    typically obtained from another :term:`VCF` file/:term:`BCF`
    file.

    Parameters
    ----------
    mode : string
        *mode* should be ``r`` for reading or ``w`` for writing. The default is
        text mode (:term:`VCF`).  For binary (:term:`BCF`) I/O you should append
        ``b`` for compressed or ``u`` for uncompressed :term:`BCF` output.

        If ``b`` is present, it must immediately follow ``r`` or ``w``.  Valid
        modes are ``r``, ``w``, ``wh``, ``rb``, ``wb``, ``wbu`` and ``wb0``.
        For instance, to open a :term:`BCF` formatted file for reading, type::

            f = pysam.VariantFile('ex1.bcf','r')

        If mode is not specified, we will try to auto-detect the file type.  All
        of the following should work::

            f1 = pysam.VariantFile('ex1.bcf')
            f2 = pysam.VariantFile('ex1.vcf')
            f3 = pysam.VariantFile('ex1.vcf.gz')

    index_filename : string
        Explicit path to an index file.

    header : VariantHeader
        :class:`VariantHeader` object required for writing.

    drop_samples: bool
        Ignore sample information when reading.

    duplicate_filehandle: bool
        By default, file handles passed either directly or through
        File-like objects will be duplicated before passing them to
        htslib. The duplication prevents issues where the same stream
        will be closed by htslib and through destruction of the
        high-level python object. Set to False to turn off
        duplication.

    ignore_truncation: bool
        Issue a warning, instead of raising an error if the current file
        appears to be truncated due to a missing EOF marker.  Only applies
        to bgzipped formats. (Default=False)

    threads: integer
        Number of threads to use for compressing/decompressing VCF/BCF files.
        Setting threads to > 1 cannot be combined with `ignore_truncation`.
        (Default=1)

    """
    def __cinit__(self, *args, **kwargs):
        self.htsfile = NULL

    def __init__(self, *args, **kwargs):
        self.header         = None
        self.index          = None
        self.filename       = None
        self.mode           = None
        self.threads        = 1
        self.index_filename = None
        self.is_stream      = False
        self.is_remote      = False
        self.is_reading     = False
        self.drop_samples   = False
        self.header_written = False
        self.start_offset   = -1

        self.open(*args, **kwargs)

    def __dealloc__(self):
        if not self.htsfile or not self.header:
            return

        # Write header if no records were written
        if self.htsfile.is_write and not self.header_written:
            with nogil:
                bcf_hdr_write(self.htsfile, self.header.ptr)

        cdef int ret = hts_close(self.htsfile)
        self.htsfile = NULL
        self.header = self.index = None

        if ret < 0:
            global errno
            if errno == EPIPE:
                errno = 0
            else:
                raise IOError(errno, force_str(strerror(errno)))

    def close(self):
        """closes the :class:`pysam.VariantFile`."""
        if not self.htsfile:
            return

        # Write header if no records were written
        if self.htsfile.is_write and not self.header_written:
            with nogil:
                bcf_hdr_write(self.htsfile, self.header.ptr)

        cdef int ret = hts_close(self.htsfile)
        self.htsfile = NULL
        self.header = self.index = None

        if ret < 0:
            global errno
            if errno == EPIPE:
                errno = 0
            else:
                raise IOError(errno, force_str(strerror(errno)))

    def __iter__(self):
        if not self.is_open:
            raise ValueError('I/O operation on closed file')

        if self.htsfile.is_write:
            raise ValueError('cannot iterate over Variantfile opened for writing')

        self.is_reading = 1
        return self

    def __next__(self):
        cdef int ret
        cdef int errcode
        cdef bcf1_t *record = bcf_init1()

        if not record:
            raise MemoryError('unable to allocate BCF record')

        record.pos = -1
        if self.drop_samples:
            record.max_unpack = BCF_UN_SHR

        with nogil:
            ret = bcf_read1(self.htsfile, self.header.ptr, record)

        if ret < 0:
            errcode = record.errcode
            bcf_destroy1(record)
            if errcode:
                raise IOError('unable to parse next record')
            if ret == -1:
                raise StopIteration
            elif ret == -2:
                raise IOError('truncated file')
            elif errno:
                raise IOError(errno, strerror(errno))
            else:
                raise IOError('unable to fetch next record')

        return makeVariantRecord(self.header, record)

    def copy(self):
        if not self.is_open:
            raise ValueError

        cdef VariantFile vars = VariantFile.__new__(VariantFile)
        cdef bcf_hdr_t *hdr

        # FIXME: re-open using fd or else header and index could be invalid
        vars.htsfile = self._open_htsfile()

        if not vars.htsfile:
            raise ValueError('Cannot re-open htsfile')

        # minimize overhead by re-using header and index.  This approach is
        # currently risky, but see above for how this can be mitigated.
        vars.header         = self.header
        vars.index          = self.index

        vars.filename       = self.filename
        vars.mode           = self.mode
        vars.threads        = self.threads
        vars.index_filename = self.index_filename
        vars.drop_samples   = self.drop_samples
        vars.is_stream      = self.is_stream
        vars.is_remote      = self.is_remote
        vars.is_reading     = self.is_reading
        vars.start_offset   = self.start_offset
        vars.header_written = self.header_written

        if self.htsfile.is_bin:
            vars.seek(self.tell())
        else:
            with nogil:
                hdr = bcf_hdr_read(vars.htsfile)
            makeVariantHeader(hdr)

        return vars

    def open(self, filename, mode='r',
             index_filename=None,
             VariantHeader header=None,
             drop_samples=False,
             duplicate_filehandle=True,
             ignore_truncation=False,
             threads=1):
        """open a vcf/bcf file.

        If open is called on an existing VariantFile, the current file will be
        closed and a new file will be opened.
        """
        cdef bcf_hdr_t *hdr
        cdef BGZF *bgzfp
        cdef hts_idx_t *idx
        cdef tbx_t *tidx
        cdef char *cfilename
        cdef char *cindex_filename = NULL
        cdef char *cmode

        if threads > 1 and ignore_truncation:
            # This won't raise errors if reaching a truncated alignment,
            # because bgzf_mt_reader in htslib does not deal with
            # bgzf_mt_read_block returning non-zero values, contrary
            # to bgzf_read (https://github.com/samtools/htslib/blob/1.7/bgzf.c#L888)
            # Better to avoid this (for now) than to produce seemingly correct results.
            raise ValueError('Cannot add extra threads when "ignore_truncation" is True')
        self.threads = threads

        # close a previously opened file
        if self.is_open:
            self.close()

        if not mode or mode[0] not in 'rwa':
            raise ValueError('mode must begin with r, w or a')

        self.duplicate_filehandle = duplicate_filehandle

        format_modes = [m for m in mode[1:] if m in 'bcguz']
        if len(format_modes) > 1:
            raise ValueError('mode contains conflicting format specifiers: {}'.format(''.join(format_modes)))

        invalid_modes = [m for m in mode[1:] if m not in 'bcguz0123456789ex']
        if invalid_modes:
            raise ValueError('invalid mode options: {}'.format(''.join(invalid_modes)))

        # Autodetect mode from filename
        if mode == 'w' and isinstance(filename, str):
            if filename.endswith('.gz'):
                mode = 'wz'
            elif filename.endswith('.bcf'):
                mode = 'wb'

        # for htslib, wbu seems to not work
        if mode == 'wbu':
            mode = 'wb0'

        self.mode = mode = force_bytes(mode)
        try:
            filename = encode_filename(filename)
            self.is_remote = hisremote(filename)
            self.is_stream = filename == b'-'
        except TypeError:
            filename = filename
            self.is_remote = False
            self.is_stream = True

        self.filename = filename

        if index_filename is not None:
            self.index_filename = index_filename = encode_filename(index_filename)
        else:
            self.index_filename = None

        self.drop_samples = bool(drop_samples)
        self.header = None

        self.header_written = False

        if mode.startswith(b'w'):
            # open file for writing
            if index_filename is not None:
                raise ValueError('Cannot specify an index filename when writing a VCF/BCF file')

            # header structure (used for writing)
            if header:
                self.header = header.copy()
            else:
                self.header = VariantHeader()
                #raise ValueError('a VariantHeader must be specified')

            # Header is not written until the first write or on close
            self.htsfile = self._open_htsfile()

            if not self.htsfile:
                raise ValueError("could not open file `{}` (mode='{}')".format(filename, mode))

        elif mode.startswith(b'r'):
            # open file for reading
            self.htsfile = self._open_htsfile()

            if not self.htsfile:
                if errno:
                    raise IOError(errno, 'could not open variant file `{}`: {}'.format(filename, force_str(strerror(errno))))
                else:
                    raise ValueError('could not open variant file `{}`'.format(filename))

            if self.htsfile.format.format not in (bcf, vcf):
                raise ValueError('invalid file `{}` (mode=`{}`) - is it VCF/BCF format?'.format(filename, mode))

            self.check_truncation(ignore_truncation)

            with nogil:
                hdr = bcf_hdr_read(self.htsfile)

            try:
                self.header = makeVariantHeader(hdr)
            except ValueError:
                raise ValueError('file `{}` does not have valid header (mode=`{}`) - is it VCF/BCF format?'.format(filename, mode))

            if isinstance(self.filename, bytes):
                cfilename = self.filename
            else:
                cfilename = NULL

            # check for index and open if present
            if self.htsfile.format.format == bcf and cfilename:
                if index_filename is not None:
                    cindex_filename = index_filename
                with nogil:
                    idx = bcf_index_load2(cfilename, cindex_filename)
                self.index = makeBCFIndex(self.header, idx)

            elif self.htsfile.format.compression == bgzf and cfilename:
                if index_filename is not None:
                    cindex_filename = index_filename
                with nogil:
                    tidx = tbx_index_load2(cfilename, cindex_filename)
                self.index = makeTabixIndex(tidx)

            if not self.is_stream:
                self.start_offset = self.tell()
        else:
            raise ValueError('unknown mode {}'.format(mode))

    def reset(self):
        """reset file position to beginning of file just after the header."""
        return self.seek(self.start_offset)

    def is_valid_tid(self, tid):
        """
        return True if the numerical :term:`tid` is valid; False otherwise.

        returns -1 if reference is not known.
        """
        if not self.is_open:
            raise ValueError('I/O operation on closed file')

        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef int rid = tid
        return 0 <= rid < hdr.n[BCF_DT_CTG]

    def get_tid(self, reference):
        """
        return the numerical :term:`tid` corresponding to
        :term:`reference`

        returns -1 if reference is not known.
        """
        if not self.is_open:
            raise ValueError('I/O operation on closed file')

        cdef vdict_t *d = <vdict_t*>self.header.ptr.dict[BCF_DT_CTG]
        reference = force_bytes(reference)
        cdef khint_t k = kh_get_vdict(d, reference)
        return kh_val_vdict(d, k).id if k != kh_end(d) else -1

    def get_reference_name(self, tid):
        """
        return :term:`reference` name corresponding to numerical :term:`tid`
        """
        if not self.is_open:
            raise ValueError('I/O operation on closed file')

        cdef bcf_hdr_t *hdr = self.header.ptr
        cdef int rid = tid
        if rid < 0 or rid >= hdr.n[BCF_DT_CTG]:
            raise ValueError('Invalid tid')
        return bcf_str_cache_get_charptr(bcf_hdr_id2name(hdr, rid))

    def fetch(self, contig=None, start=None, stop=None, region=None, reopen=False, end=None, reference=None):
        """fetch records in a :term:`region`, specified either by
        :term:`contig`, *start*, and *end* (which are 0-based, half-open);
        or alternatively by a samtools :term:`region` string (which is
        1-based inclusive).

        Without *contig* or *region* all mapped records will be fetched.  The
        records will be returned ordered by contig, which will not necessarily
        be the order within the file.

        Set *reopen* to true if you will be using multiple iterators on the
        same file at the same time.  The iterator returned will receive its
        own copy of a filehandle to the file effectively re-opening the
        file.  Re-opening a file incurrs some overhead, so use with care.

        If only *contig* is set, all records on *contig* will be fetched.
        If both *region* and *contig* are given, an exception is raised.

        Note that a bgzipped :term:`VCF`.gz file without a tabix/CSI index
        (.tbi/.csi) or a :term:`BCF` file without a CSI index can only be
        read sequentially.
        """
        if not self.is_open:
            raise ValueError('I/O operation on closed file')

        if self.htsfile.is_write:
            raise ValueError('cannot fetch from Variantfile opened for writing')

        if contig is None and region is None:
            self.is_reading = 1
            bcf = self.copy() if reopen else self
            bcf.seek(self.start_offset)
            return iter(bcf)

        if self.index is None:
            raise ValueError('fetch requires an index')

        _, tid, start, stop = self.parse_region(contig, start, stop, region,
                                                None, end=end, reference=reference)

        if contig is None:
            contig = self.get_reference_name(tid)

        self.is_reading = 1
        return self.index.fetch(self, contig, start, stop, reopen)

    def new_record(self, *args, **kwargs):
        """Create a new empty :class:`VariantRecord`.

        See :meth:`VariantHeader.new_record`
        """
        return self.header.new_record(*args, **kwargs)

    cpdef int write(self, VariantRecord record) except -1:
        """
        write a single :class:`pysam.VariantRecord` to disk.

        returns the number of bytes written.
        """
        if record is None:
            raise ValueError('record must not be None')

        if not self.is_open:
            return ValueError('I/O operation on closed file')

        if not self.htsfile.is_write:
            raise ValueError('cannot write to a Variantfile opened for reading')

        if not self.header_written:
            self.header_written = True
            with nogil:
                bcf_hdr_write(self.htsfile, self.header.ptr)

        #if record.header is not self.header:
        #    record.translate(self.header)
        #    raise ValueError('Writing records from a different VariantFile is not yet supported')

        if record.ptr.n_sample != bcf_hdr_nsamples(self.header.ptr):
            msg = 'Invalid VariantRecord.  Number of samples does not match header ({} vs {})'
            raise ValueError(msg.format(record.ptr.n_sample, bcf_hdr_nsamples(self.header.ptr)))

        # Sync END annotation before writing
        bcf_sync_end(record)

        cdef int ret

        with nogil:
            ret = bcf_write1(self.htsfile, self.header.ptr, record.ptr)

        if ret < 0:
            raise IOError(errno, strerror(errno))

        return ret

    def subset_samples(self, include_samples):
        """
        Read only a subset of samples to reduce processing time and memory.
        Must be called prior to retrieving records.
        """
        if not self.is_open:
            raise ValueError('I/O operation on closed file')

        if self.htsfile.is_write:
            raise ValueError('cannot subset samples from Variantfile opened for writing')

        if self.is_reading:
            raise ValueError('cannot subset samples after fetching records')

        self.header._subset_samples(include_samples)

        # potentially unnecessary optimization that also sets max_unpack
        if not include_samples:
            self.drop_samples = True