This file is indexed.

/usr/include/InsightToolkit/Utilities/NrrdIO/NrrdIO.h is in libinsighttoolkit3-dev 3.20.1-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
/*
  NrrdIO: stand-alone code for basic nrrd functionality
  Copyright (C) 2008, 2007, 2006, 2005  Gordon Kindlmann
  Copyright (C) 2004, 2003, 2002, 2001, 2000, 1999, 1998  University of Utah
 
  This software is provided 'as-is', without any express or implied
  warranty.  In no event will the authors be held liable for any
  damages arising from the use of this software.
 
  Permission is granted to anyone to use this software for any
  purpose, including commercial applications, and to alter it and
  redistribute it freely, subject to the following restrictions:
 
  1. The origin of this software must not be misrepresented; you must
     not claim that you wrote the original software. If you use this
     software in a product, an acknowledgment in the product
     documentation would be appreciated but is not required.
 
  2. Altered source versions must be plainly marked as such, and must
     not be misrepresented as being the original software.
 
  3. This notice may not be removed or altered from any source distribution.
*/

#include "NrrdConfigure.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <float.h>

/*
******** TEEM_VERSION 
**
** TEEM_VERSION is a single (decimal) number that will always increase
** monotically, and the _MAJOR, _MINOR, _PATCH are also numbers that
** can be used to implement pre-processor logic about specifc
** versions.  The TEEM_VERSION_STRING is used in the (existing) char
** *airTeemVersion (added in version 1.9.0).  Yes, keeping these in
** sync is currently a manual operation.
**
** NOTE: Significant API changes (aside from API additions) should NOT
** occur with changes in patch level, only with major or minor version
** changes.
**
** NOTE: ../../CMakeLists.txt's Teem_VERSION variables must be in sync
*/
#define TEEM_VERSION_MAJOR       1   /* must be 1 digit */
#define TEEM_VERSION_MINOR      11   /* 1 or 2 digits */
#define TEEM_VERSION_PATCH      00   /* 1 or 2 digits */
#define TEEM_VERSION         11100   /* can be easily compared numerically */
#define TEEM_VERSION_STRING "1.11.0" /* cannot be so easily compared */

/* THE FOLLOWING INCLUDE IS ONLY FOR THE ITK DISTRIBUTION.
   This header mangles the symbols in the NrrdIO library, preventing
   conflicts in applications linked against two versions of NrrdIO. */
#include "itk_NrrdIO_mangle.h"

#ifdef __cplusplus
extern "C" {
#endif

#define TEEM_BUILD 1
#if defined(_WIN32) && !defined(__CYGWIN__) && !defined(TEEM_STATIC)
#  if defined(TEEM_BUILD) || defined(air_EXPORTS) || defined(teem_EXPORTS)
#    define NRRDIO_EXPORT extern __declspec(dllexport)
#  else
#    define NRRDIO_EXPORT extern __declspec(dllimport)
#  endif
#else /* TEEM_STATIC || UNIX */
#  define NRRDIO_EXPORT extern
#endif

#if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__)
typedef signed __int64 airLLong;
typedef unsigned __int64 airULLong;
#define AIR_LLONG_FMT "%I64d"
#define AIR_ULLONG_FMT "%I64u"
#define AIR_LLONG(x) x##i64
#define AIR_ULLONG(x) x##ui64
#else
typedef signed long long airLLong;
typedef unsigned long long airULLong;
#define AIR_LLONG_FMT "%lld"
#define AIR_ULLONG_FMT "%llu"
#define AIR_LLONG(x) x##ll
#define AIR_ULLONG(x) x##ull
#endif

/* This is annoying, thanks to windows */
#define AIR_PI 3.14159265358979323846
#define AIR_E  2.71828182845904523536

#define AIR_STRLEN_SMALL (128+1)
#define AIR_STRLEN_MED   (256+1)
#define AIR_STRLEN_LARGE (512+1)
#define AIR_STRLEN_HUGE  (1024+1)

/* enum.c: enum value <--> string conversion utility */  
typedef struct {
  const char *name;
               /* what are these things? */
  unsigned int M;
               /* If "val" is NULL, the the valid enum values are from 1 
                  to M (represented by strings str[1] through str[M]), and
                  the unknown/invalid value is 0.  If "val" is non-NULL, the
                  valid enum values are from val[1] to val[M] (but again, 
                  represented by strings str[1] through str[M]), and the
                  unknown/invalid value is val[0].  In both cases, str[0]
                  is the string to represent an unknown/invalid value */
  const char **str; 
               /* "canonical" textual representation of the enum values */
  const int *val;
               /* non-NULL iff valid values in the enum are not [1..M], and/or
                  if value for unknown/invalid is not zero */
  const char **desc;
               /* desc[i] is a short description of the enum values represented
                  by str[i] (thereby starting with the unknown value), to be
                  used to by things like hest */
  const char **strEqv;  
               /* All the variations in strings recognized in mapping from
                  string to value (the values in valEqv).  This **MUST** be
                  terminated by a zero-length string ("") so as to signify
                  the end of the list.  This should not contain the string
                  for unknown/invalid.  If "strEqv" is NULL, then mapping
                  from string to value is done by traversing "str", and 
                  "valEqv" is ignored. */
  const int *valEqv;
               /* The values corresponding to the strings in strEqv; there
                  should be one integer for each non-zero-length string in
                  strEqv: strEqv[i] is a valid string representation for
                  value valEqv[i]. This should not contain the value for
                  unknown/invalid.  This "valEqv" is ignored if "strEqv" is
                  NULL. */
  int sense;   /* require case matching on strings */
} airEnum;
NRRDIO_EXPORT int airEnumUnknown(const airEnum *enm);
NRRDIO_EXPORT int airEnumLast(const airEnum *enm);
NRRDIO_EXPORT int airEnumValCheck(const airEnum *enm, int val);
NRRDIO_EXPORT const char *airEnumStr(const airEnum *enm, int val);
NRRDIO_EXPORT const char *airEnumDesc(const airEnum *enm, int val);
NRRDIO_EXPORT int airEnumVal(const airEnum *enm, const char *str);
NRRDIO_EXPORT char *airEnumFmtDesc(const airEnum *enm, int val, int canon,
                                const char *fmt);
NRRDIO_EXPORT void airEnumPrint(FILE *file, const airEnum *enm);


/*
******** airEndian enum
**
** for identifying how a file was written to disk, for those encodings
** where the raw data on disk is dependent on the endianness of the
** architecture.
*/
enum {
  airEndianUnknown,         /* 0: nobody knows */
  airEndianLittle = 1234,   /* 1234: Intel and friends */
  airEndianBig = 4321,      /* 4321: the rest */
  airEndianLast
};
/* endianAir.c */
NRRDIO_EXPORT const airEnum *const airEndian;
NRRDIO_EXPORT const int airMyEndian;

/* array.c: poor-man's dynamically resizable arrays */
typedef struct {
  void *data,         /* where the data is */
    **dataP;          /* (possibly NULL) address of user's data variable,
                         kept in sync with internal "data" variable */
  unsigned int len,   /* length of array: # units for which there is
                         considered to be data (which is <= total # units
                         allocated).  The # bytes which contain data is
                         len*unit.  Always updated (unlike "*lenP") */
    *lenP,            /* (possibly NULL) address of user's length variable,
                         kept in sync with internal "len" variable */
    incr,             /* the granularity of the changes in amount of space
                         allocated: when the length reaches a multiple of
                         "incr", then the array is resized */
    size;             /* array is allocated to have "size" increments, or,
                         size*incr elements, or, 
                         size*incr*unit bytes */
  size_t unit;        /* the size in bytes of one element in the array */
  int noReallocWhenSmaller;  /* as it says */

  /* the following are all callbacks useful for maintaining either an array
     of pointers (allocCB and freeCB) or array of structs (initCB and
     doneCB).  allocCB or initCB is called when the array length increases,
     and freeCB or doneCB when it decreases.  Any of them can be NULL if no
     such activity is desired.  allocCB sets values in the array (as in
     storing the return from malloc(); freeCB is called on values in the
     array (as in calling free()), and the values are cast to void*.  allocCB
     and freeCB don't care about the value of "unit" (though perhaps they
     should).  initCB and doneCB are called on the _addresses_ of elements in
     the array.  allocCB and initCB are called for the elements in ascending
     order in the array, and freeCB and doneCB are called in descending
     order.  allocCB and initCB are mutually exclusive- they can't both be
     non-NULL. Same goes for freeCB and doneCB */
  void *(*allocCB)(void);  /* values of new elements set to return of this */
  void *(*freeCB)(void *); /* called on the values of invalidated elements */
  void (*initCB)(void *);  /* called on addresses of new elements */
  void (*doneCB)(void *);  /* called on addresses of invalidated elements */

} airArray;
NRRDIO_EXPORT airArray *airArrayNew(void **dataP, unsigned int *lenP, size_t unit,
                                 unsigned int incr);
NRRDIO_EXPORT void airArrayStructCB(airArray *a, void (*initCB)(void *),
                                 void (*doneCB)(void *));
NRRDIO_EXPORT void airArrayPointerCB(airArray *a, void *(*allocCB)(void),
                                  void *(*freeCB)(void *));
NRRDIO_EXPORT void airArrayLenSet(airArray *a, unsigned int newlen);
NRRDIO_EXPORT void airArrayLenPreSet(airArray *a, unsigned int newlen);
NRRDIO_EXPORT unsigned int airArrayLenIncr(airArray *a, int delta);
NRRDIO_EXPORT airArray *airArrayNix(airArray *a);
NRRDIO_EXPORT airArray *airArrayNuke(airArray *a);


/*
******** airFP enum
**
** the different kinds of floating point number afforded by IEEE 754,
** and the values returned by airFPClass_f().
**
** The values probably won't agree with those in #include's like
** ieee.h, ieeefp.h, fp_class.h.  This is because IEEE 754 hasn't
** defined standard values for these, so everyone does it differently.
** 
** This enum uses underscores (against Teem convention) to help
** legibility while also conforming to the spirit of the somewhat
** standard naming conventions
*/
enum {
  airFP_Unknown,               /*  0: nobody knows */
  airFP_SNAN,                  /*  1: signalling NaN */
  airFP_QNAN,                  /*  2: quiet NaN */
  airFP_POS_INF,               /*  3: positive infinity */
  airFP_NEG_INF,               /*  4: negative infinity */
  airFP_POS_NORM,              /*  5: positive normalized non-zero */
  airFP_NEG_NORM,              /*  6: negative normalized non-zero */
  airFP_POS_DENORM,            /*  7: positive denormalized non-zero */
  airFP_NEG_DENORM,            /*  8: negative denormalized non-zero */
  airFP_POS_ZERO,              /*  9: +0.0, positive zero */
  airFP_NEG_ZERO,              /* 10: -0.0, negative zero */
  airFP_Last                   /* after the last valid one */
};
/* 754.c: IEEE-754 related stuff values */
typedef union {
  unsigned int i;
  float f;
} airFloat;
typedef union {
  airULLong i;
  double d;
} airDouble;
NRRDIO_EXPORT const int airMyQNaNHiBit;
NRRDIO_EXPORT float airFPPartsToVal_f(unsigned int sign, 
                                   unsigned int expo, 
                                   unsigned int mant);
NRRDIO_EXPORT void airFPValToParts_f(unsigned int *signP, 
                                  unsigned int *expoP, 
                                  unsigned int *mantP, float v);
NRRDIO_EXPORT double airFPPartsToVal_d(unsigned int sign, 
                                    unsigned int expo,
                                    unsigned int mant0,
                                    unsigned int mant1);
NRRDIO_EXPORT void airFPValToParts_d(unsigned int *signP, 
                                  unsigned int *expoP,
                                  unsigned int *mant0P,
                                  unsigned int *mant1P,
                                  double v);
NRRDIO_EXPORT float airFPGen_f(int cls);
NRRDIO_EXPORT double airFPGen_d(int cls);
NRRDIO_EXPORT int airFPClass_f(float val);
NRRDIO_EXPORT int airFPClass_d(double val);
NRRDIO_EXPORT void airFPFprintf_f(FILE *file, float val);
NRRDIO_EXPORT void airFPFprintf_d(FILE *file, double val);
NRRDIO_EXPORT const airFloat airFloatQNaN;
NRRDIO_EXPORT const airFloat airFloatSNaN;
NRRDIO_EXPORT const airFloat airFloatPosInf;
NRRDIO_EXPORT const airFloat airFloatNegInf;
NRRDIO_EXPORT float airNaN(void);
NRRDIO_EXPORT int airIsNaN(double d);
NRRDIO_EXPORT int airIsInf_f(float f);
NRRDIO_EXPORT int airIsInf_d(double d);
NRRDIO_EXPORT int airExists(double d);


/*
******** airType
**
** Different types which air cares about.
** Currently only used in the command-line parsing, but perhaps will
** be used elsewhere in air later
*/
enum {
  airTypeUnknown,   /*  0 */
  airTypeBool,      /*  1 */
  airTypeInt,       /*  2 */
  airTypeUInt,      /*  3 */
  airTypeLongInt,   /*  4 */
  airTypeSize_t,    /*  5 */
  airTypeFloat,     /*  6 */
  airTypeDouble,    /*  7 */
  airTypeChar,      /*  8 */
  airTypeString,    /*  9 */
  airTypeEnum,      /* 10 */
  airTypeOther,     /* 11 */
  airTypeLast
};
#define AIR_TYPE_MAX   11
/* parseAir.c */
NRRDIO_EXPORT double airAtod(const char *str);
NRRDIO_EXPORT int airSingleSscanf(const char *str, const char *fmt, void *ptr);
NRRDIO_EXPORT const airEnum *const airBool;
NRRDIO_EXPORT unsigned int airParseStrB(int *out, const char *s,
                                     const char *ct, unsigned int n, 
                                     ... /* (nothing used) */);
NRRDIO_EXPORT unsigned int airParseStrI(int *out, const char *s,
                                     const char *ct, unsigned int n,
                                     ... /* (nothing used) */);
NRRDIO_EXPORT unsigned int airParseStrUI(unsigned int *out, const char *s,
                                      const char *ct, unsigned int n,
                                      ... /* (nothing used) */);
NRRDIO_EXPORT unsigned int airParseStrZ(size_t *out, const char *s,
                                     const char *ct, unsigned int n,
                                     ... /* (nothing used) */);
NRRDIO_EXPORT unsigned int airParseStrF(float *out, const char *s,
                                     const char *ct, unsigned int n,
                                     ... /* (nothing used) */);
NRRDIO_EXPORT unsigned int airParseStrD(double *out, const char *s,
                                     const char *ct, unsigned int n,
                                     ... /* (nothing used) */);
NRRDIO_EXPORT unsigned int airParseStrC(char *out, const char *s,
                                     const char *ct, unsigned int n,
                                     ... /* (nothing used) */);
NRRDIO_EXPORT unsigned int airParseStrS(char **out, const char *s,
                                     const char *ct, unsigned int n,
                                     ... /* REQ'D even if n>1: int greedy */);
NRRDIO_EXPORT unsigned int airParseStrE(int *out, const char *s,
                                     const char *ct, unsigned int n, 
                                     ... /* REQUIRED: airEnum *e */);
NRRDIO_EXPORT unsigned int (*airParseStr[AIR_TYPE_MAX+1])(void *, const char *,
                                                       const char *,
                                                       unsigned int, ...);

/* string.c */
NRRDIO_EXPORT char *airStrdup(const char *s);
NRRDIO_EXPORT size_t airStrlen(const char *s);
NRRDIO_EXPORT int airStrtokQuoting;
NRRDIO_EXPORT char *airStrtok(char *s, const char *ct, char **last);
NRRDIO_EXPORT unsigned int airStrntok(const char *s, const char *ct);
NRRDIO_EXPORT char *airStrtrans(char *s, char from, char to);
NRRDIO_EXPORT int airEndsWith(const char *s, const char *suff);
NRRDIO_EXPORT char *airUnescape(char *s);
NRRDIO_EXPORT char *airOneLinify(char *s);
NRRDIO_EXPORT char *airToLower(char *str);
NRRDIO_EXPORT char *airToUpper(char *str);
NRRDIO_EXPORT unsigned int airOneLine(FILE *file, char *line, int size);

/* sane.c */
/*
******** airInsane enum
** 
** reasons for why airSanity() failed (specifically, the possible
** return values for airSanity()
*/
enum {
  airInsane_not,           /*  0: actually, all sanity checks passed */
  airInsane_endian,        /*  1: airMyEndian is wrong */
  airInsane_pInfExists,    /*  2: AIR_EXISTS(positive infinity) was true */
  airInsane_nInfExists,    /*  3: AIR_EXISTS(negative infinity) was true */
  airInsane_NaNExists,     /*  4: AIR_EXISTS(NaN) was true */
  airInsane_FltDblFPClass, /*  5: double -> float assignment messed up the
                               airFPClass_f() of the value */
  airInsane_QNaNHiBit,     /*  6: airMyQNaNHiBit is wrong */
  airInsane_AIR_NAN,       /*  7: airFPClass_f(AIR_QNAN,AIR_SNAN) wrong */
  airInsane_dio,           /*  8: airMyDio set to something invalid */
  airInsane_32Bit,         /*  9: airMy32Bit is wrong */
  airInsane_UCSize,        /* 10: unsigned char isn't 8 bits */
  airInsane_FISize,        /* 11: sizeof(float), sizeof(int) not 4 */
  airInsane_DLSize         /* 12: sizeof(double), sizeof(airLLong) not 8 */
};
#define AIR_INSANE_MAX        12
NRRDIO_EXPORT const char *airInsaneErr(int insane);
NRRDIO_EXPORT int airSanity(void);

/* miscAir.c */
NRRDIO_EXPORT const char *airTeemVersion;
NRRDIO_EXPORT const char *airTeemReleaseDate;
NRRDIO_EXPORT void *airNull(void);
NRRDIO_EXPORT void *airSetNull(void **ptrP);
NRRDIO_EXPORT void *airFree(void *ptr);
NRRDIO_EXPORT FILE *airFopen(const char *name, FILE *std, const char *mode);
NRRDIO_EXPORT FILE *airFclose(FILE *file);
NRRDIO_EXPORT int airSinglePrintf(FILE *file, char *str, const char *fmt, ...);
NRRDIO_EXPORT const int airMy32Bit;

/* dio.c */
/*
******** airNoDio enum
**
** reasons for why direct I/O won't be used with a particular 
** file/pointer combination
*/
enum {
  airNoDio_okay,    /*  0: actually, you CAN do direct I/O */
  airNoDio_arch,    /*  1: Teem thinks this architecture can't do it */
  airNoDio_format,  /*  2: Teem thinks given data file format can't use it */
  airNoDio_std,     /*  3: DIO isn't possible for std{in|out|err} */
  airNoDio_fd,      /*  4: couldn't get underlying file descriptor */
  airNoDio_dioinfo, /*  5: calling fcntl() to get direct I/O info failed */
  airNoDio_small,   /*  6: requested size is too small */
  airNoDio_size,    /*  7: requested size not a multiple of d_miniosz */
  airNoDio_ptr,     /*  8: pointer not multiple of d_mem */
  airNoDio_fpos,    /*  9: current file position not multiple of d_miniosz */
  airNoDio_setfl,   /* 10: fcntl(fd, SETFL, FDIRECT) failed */
  airNoDio_test,    /* 11: couldn't memalign() even a small bit of memory */
  airNoDio_disable  /* 12: someone disabled it with airDisableDio */
};
#define AIR_NODIO_MAX  12
NRRDIO_EXPORT const char *airNoDioErr(int noDio);
NRRDIO_EXPORT const int airMyDio;
NRRDIO_EXPORT int airDisableDio;
NRRDIO_EXPORT void airDioInfo(int *align, int *min, int *max, int fd);
NRRDIO_EXPORT int airDioTest(int fd, const void *ptr, size_t size);
NRRDIO_EXPORT void *airDioMalloc(size_t size, int fd);
NRRDIO_EXPORT size_t airDioRead(int fd, void *ptr, size_t size);
NRRDIO_EXPORT size_t airDioWrite(int fd, const void *ptr, size_t size);

/* mop.c: clean-up utilities */
enum {
  airMopNever,
  airMopOnError,
  airMopOnOkay,
  airMopAlways
};
typedef void *(*airMopper)(void *);
typedef struct {
  void *ptr;         /* the thing to be processed */
  airMopper mop;     /* the function to which does the processing */
  int when;          /* from the airMopWhen enum */
} airMop;
NRRDIO_EXPORT airArray *airMopNew(void);
NRRDIO_EXPORT int airMopAdd(airArray *arr, void *ptr, airMopper mop, int when);
NRRDIO_EXPORT void airMopSub(airArray *arr, void *ptr, airMopper mop);
NRRDIO_EXPORT void airMopMem(airArray *arr, void *_ptrP, int when);
NRRDIO_EXPORT void airMopUnMem(airArray *arr, void *_ptrP);
NRRDIO_EXPORT void airMopPrint(airArray *arr, const void *_str, int when);
NRRDIO_EXPORT void airMopDone(airArray *arr, int error);
NRRDIO_EXPORT void airMopError(airArray *arr);
NRRDIO_EXPORT void airMopOkay(airArray *arr);
NRRDIO_EXPORT void airMopDebug(airArray *arr);

/*******     the interminable sea of defines and macros     *******/

#define AIR_TRUE 1
#define AIR_FALSE 0
#define AIR_WHITESPACE " \t\n\r\v\f"       /* K+R pg. 157 */

/*
******** AIR_UNUSED
**
** one way of reconciling "warning: unused parameter" with
** C's "error: parameter name omitted"
*/
#define AIR_UNUSED(x) (void)(x)

/*
******** AIR_CAST
**
** just a cast, but with the added ability to grep for it more easily,
** since casts should probably always be revisited and reconsidered.
*/
#define AIR_CAST(t, v) ((t)(v))

/*
******** AIR_CALLOC
**
** slightly simpler wrapper around cast and calloc
**
** HEY note that "T" is not guarded by parentheses in its first usage,
** as arguments in Teem macros normally are
*/
#define AIR_CALLOC(N, T) (T*)(calloc((N), sizeof(T)))

/*
******** AIR_ENDIAN, AIR_QNANHIBIT, AIR_DIO
**
** These reflect particulars of hardware which we're running on.
** The reason to have these in addition to TEEM_ENDIAN, TEEM_DIO, etc.,
** is that those are not by default defined for every source-file
** compilation: the Teem library has to define NEED_ENDIAN, NEED_DIO, etc,
** and these in turn generate appropriate compile command-line flags
** by Common.mk. By having these defined here, they become available
** to anyone who simply links against the air library (and includes air.h),
** with no command-line flags required, and no usage of Common.mk required.
*/
#define AIR_ENDIAN (airMyEndian)
#define AIR_QNANHIBIT (airMyQNaNHiBit)
#define AIR_DIO (airMyDio)
#define AIR_32BIT (airMy32Bit)

/*
******** AIR_NAN, AIR_QNAN, AIR_SNAN, AIR_POS_INF, AIR_NEG_INF
**
** its nice to have these values available without the cost of a 
** function call.
**
** NOTE: AIR_POS_INF and AIR_NEG_INF correspond to the _unique_
** bit-patterns which signify positive and negative infinity.  With
** the NaNs, however, they are only one of many possible
** representations.
*/
#define AIR_NAN  (airFloatQNaN.f)
#define AIR_QNAN (airFloatQNaN.f)
#define AIR_SNAN (airFloatSNaN.f)
#define AIR_POS_INF (airFloatPosInf.f)
#define AIR_NEG_INF (airFloatNegInf.f)

/* 
******** AIR_EXISTS
**
** is non-zero (true) only for values which are not NaN or +/-infinity
** 
** You'd think that (x == x) might work, but no no no, some optimizing
** compilers (e.g. SGI's cc) say "well of course they're equal, for all
** possible values".  Bastards!
**
** One of the benefits of IEEE 754 floating point numbers is that
** gradual underflow means that x = y <==> x - y = 0 for any (positive
** or negative) normalized or denormalized float.  Otherwise this
** macro could not be valid; some floating point conventions say that
** a zero-valued exponent means zero, regardless of the mantissa.
**
** However, there MAY be problems on machines which use extended
** (80-bit) floating point registers, such as Intel chips- where the
** same initial value 1) directly read from the register, versus 2)
** saved to memory and loaded back, may end up being different.  I
** have yet to produce this behavior, or convince myself it can't happen.
**
** The reason to #define AIR_EXISTS as airExists_d is that on some
** optimizing compilers, the !((x) - (x)) doesn't work.  This has been
** the case on Windows and 64-bit irix6 (64 bit) with -Ofast.  If
** airSanity fails because a special value "exists", then use the
** first version of AIR_EXISTS.
**
** There are two performance consequences of using airExists_d(x):
** 1) Its a function call (but WIN32 can __inline it)
** 2) (via AIR_EXISTS_D) It requires bit-wise operations on 64-bit
** ints, which might be terribly slow.
**
** The reason for using airExists_d and not airExists_f is for
** doubles > FLT_MAX: airExists_f would say these are infinity.
*/
#if 1
#define AIR_EXISTS(x) (airExists(x))
#else
#define AIR_EXISTS(x) (!((x) - (x)))
#endif


/*
******** AIR_MAX(a,b), AIR_MIN(a,b), AIR_ABS(a)
**
** the usual
*/
#define AIR_MAX(a,b) ((a) > (b) ? (a) : (b))
#define AIR_MIN(a,b) ((a) < (b) ? (a) : (b))
#define AIR_ABS(a) ((a) > 0.0f ? (a) : -(a))

/*
******** AIR_COMPARE(a,b)
**
** the sort of compare that qsort() wants for ascending sort
*/
#define AIR_COMPARE(a,b) ((a) < (b)     \
                          ? -1          \
                          : ((a) > (b) \
                             ? 1        \
                             : 0))

/*
******** AIR_IN_OP(a,b,c), AIR_IN_CL(a,b,c)
**
** is true if the middle argument is in the open/closed interval
** defined by the first and third arguments
** 
** AIR_IN_OP is new name for old AIR_BETWEEN
** AIR_IN_CL is new name for old AIR_INSIDE
*/
#define AIR_IN_OP(a,b,c) ((a) < (b) && (b) < (c))     /* closed interval */
#define AIR_IN_CL(a,b,c) ((a) <= (b) && (b) <= (c))   /* open interval */

/*
******** AIR_CLAMP(a,b,c)
**
** returns the middle argument, after being clamped to the closed
** interval defined by the first and third arguments
*/
#define AIR_CLAMP(a,b,c) ((b) < (a)        \
                           ? (a)           \
                           : ((b) > (c)    \
                              ? (c)        \
                              : (b)))

/*
******** AIR_MOD(i, N)
**
** returns that integer in [0, N-1] which is i plus a multiple of N. It
** may be unfortunate that the expression (i)%(N) appears three times;
** this should be inlined.  Or perhaps the compiler's optimizations
** (common sub-expression elimination) will save us.
**
** Note: integer divisions are not very fast on some modern chips;
** don't go silly using this one.
*/
#define AIR_MOD(i, N) ((i)%(N) >= 0 ? (i)%(N) : N + (i)%(N))

/*
******** AIR_LERP(w, a, b)
**
** returns a when w=0, and b when w=1, and linearly varies in between
*/
#define AIR_LERP(w, a, b) ((w)*((b) - (a)) + (a))

/*
******** AIR_AFFINE(i,x,I,o,O)
**
** given intervals [i,I], [o,O] and a value x which may or may not be
** inside [i,I], return the value y such that y stands in the same
** relationship to [o,O] that x does with [i,I].  Or:
**
**    y - o         x - i     
**   -------   =   -------
**    O - o         I - i
**
** It is the callers responsibility to make sure I-i and O-o are 
** both non-zero.  Strictly speaking, real problems arise only when
** when I-i is zero: division by zero generates either NaN or infinity
**
** NOTE that "x" is evaluated only once (which makes this more useful),
** as is "I" and "O" (usually not so important); "i" and "o" are each
** evaluated twice
*/
#define AIR_AFFINE(i,x,I,o,O) ( \
((double)(O)-(o))*((double)(x)-(i)) / ((double)(I)-(i)) + (o))

/*
******** AIR_DELTA(i,x,I,o,O)
**
** given intervals [i,I] and [o,O], calculates the number y such that
** a change of x within [i,I] is proportional to a change of y within
** [o,O].  Or:
**
**      y             x     
**   -------   =   -------
**    O - o         I - i
**
** It is the callers responsibility to make sure I-i and O-o are 
** both non-zero
**
** NOTE that all arguments are evaluated only once
*/
#define AIR_DELTA(i,x,I,o,O) ( \
((double)(O)-(o))*((double)(x)) / ((double)(I)-(i)) )

/*
******** AIR_ROUNDUP, AIR_ROUNDDOWN
**
** rounds integers up or down; just wrappers around floor and ceil
*/
#define AIR_ROUNDUP(x)   ((int)(floor((x)+0.5)))
#define AIR_ROUNDDOWN(x) ((int)(ceil((x)-0.5)))
#define AIR_ROUNDUP_UI(x)   ((unsigned int)(floor((x)+0.5)))
#define AIR_ROUNDDOWN_UI(x) ((unsigned int)(ceil((x)-0.5)))

/*
******** _AIR_SIZE_T_CNV, _AIR_PTRDIFF_T_CNV, 
**
** Format specifiers to use when printf/fprintf/sprintf-ing a value of
** type size_t or ptrdiff_t.  In C99, this is done with "%z" and "%t",
** respectively.
**
** This is not a useful macro for the world at large- only for Teem
** source files.  Why: we need to leave this as a bare string, so that
** we can exploit C's implicit string concatenation in forming a
** format string.  Therefore, unlike the definition of AIR_ENDIAN,
** AIR_DIO, etc, _AIR_SIZE_T_CNV can NOT just refer to a const variable
** (like airMyEndian).  Therefore, TEEM_32BIT has to be defined for
** ALL source files which want to use _AIR_SIZE_T_CNV, and to be safe,
** that's all Teem files.  The converse is, since there is no
** expectation that other projects which use Teem will be defining
** TEEM_32BIT, this is not useful outside Teem, thus the leading _.
**
** http://www.viva64.com/art-1-2-710804781.html for size conventions.
**
** It appears that 32 bit APPLE uses ld for size_t and int for ptrdiff.
*/
#if TEEM_32BIT == 0
#  ifdef _WIN64
#    define _AIR_SIZE_T_CNV "%I64u"
#    define _AIR_PTRDIFF_T_CNV "%I64d"
#  else
#    define _AIR_SIZE_T_CNV "%lu"
#    define _AIR_PTRDIFF_T_CNV "%ld"
#  endif
#elif TEEM_32BIT == 1
#  ifdef __APPLE__
#    define _AIR_SIZE_T_CNV "%lu"
#    define _AIR_PTRDIFF_T_CNV "%d"
#  else
#    define _AIR_SIZE_T_CNV "%u"
#    define _AIR_PTRDIFF_T_CNV "%d"
#  endif
#else
#  define _AIR_SIZE_T_CNV "(no _AIR_SIZE_T_CNV w/out TEEM_32BIT %*d)"
#  define _AIR_PTRDIFF_T_CNV "(no _AIR_PTRDIFF_T_CNV w/out TEEM_32BIT %*d)"
#endif

#ifdef __cplusplus
}
#endif





#ifdef __cplusplus
extern "C" {
#endif

/*
** biffMsg struct
**
** externally usable thing for holding error messages
*/
typedef struct {
  char *key;                   /* string for identifying the general source
                                  of the error message; set once, at time 
                                  of biffMsg creation */
  char **err;                  /* array of error strings; the err array itself
                                  is NOT null-terminated */
  unsigned int errNum;         /* length of "err" == # strings stored */
  airArray *errArr;            /* air array for err and num */
} biffMsg;

/* biffmsg.c */
NRRDIO_EXPORT biffMsg *biffMsgNew(const char *key);
NRRDIO_EXPORT biffMsg *biffMsgNix(biffMsg *msg);
NRRDIO_EXPORT void biffMsgAdd(biffMsg *msg, const char *err);
NRRDIO_EXPORT void biffMsgAddVL(biffMsg *msg, const char *errfmt, va_list args);
NRRDIO_EXPORT void biffMsgAddf(biffMsg *msg, const char *errfmt, ...)
#ifdef __GNUC__
__attribute__ ((format(printf,2,3)))
#endif
;
NRRDIO_EXPORT void biffMsgClear(biffMsg *msg);
NRRDIO_EXPORT unsigned int biffMsgLineLenMax(const biffMsg *msg);
NRRDIO_EXPORT void biffMsgMove(biffMsg *dest, biffMsg *src,
                             const char *err);
NRRDIO_EXPORT void biffMsgMoveVL(biffMsg *dest, biffMsg *src,
                               const char *errfmt, va_list args);
NRRDIO_EXPORT void biffMsgMovef(biffMsg *dest, biffMsg *src,
                                const char *errfmt, ...)
#ifdef __GNUC__
__attribute__ ((format(printf,3,4)))
#endif
;
NRRDIO_EXPORT unsigned int biffMsgStrlen(const biffMsg *msg);
NRRDIO_EXPORT char *biffMsgStrAlloc(const biffMsg *msg);
NRRDIO_EXPORT void biffMsgStrSet(char *ret, const biffMsg *msg);
NRRDIO_EXPORT char *biffMsgStrGet(const biffMsg *msg);
NRRDIO_EXPORT biffMsg *biffMsgNoop;

/* biffbiff.c */
NRRDIO_EXPORT void biffAdd(const char *key, const char *err);
NRRDIO_EXPORT void biffAddVL(const char *key, const char *errfmt, va_list args);
NRRDIO_EXPORT void biffAddf(const char *key, const char *errfmt, ...)
#ifdef __GNUC__
  __attribute__ ((format(printf,2,3)))
#endif
;
NRRDIO_EXPORT void biffMaybeAdd(const char *key, const char *err, int useBiff);
NRRDIO_EXPORT void biffMaybeAddf(int useBiff, const char *key,
                               const char *errfmt, ... )
#ifdef __GNUC__
__attribute__ ((format(printf,3,4)))
#endif
;
NRRDIO_EXPORT char *biffGet(const char *key);
NRRDIO_EXPORT int biffGetStrlen(const char *key);
NRRDIO_EXPORT void biffSetStr(char *str, const char *key);
NRRDIO_EXPORT int biffCheck(const char *key);
NRRDIO_EXPORT void biffDone(const char *key);
NRRDIO_EXPORT void biffMove(const char *destKey, const char *err,
                          const char *srcKey);
NRRDIO_EXPORT void biffMoveVL(const char *destKey, const char *srcKey,
                            const char *errfmt, va_list args);
NRRDIO_EXPORT void biffMovef(const char *destKey, const char *srcKey,
                            const char *errfmt, ...)
#ifdef __GNUC__
__attribute__ ((format(printf,3,4)))
#endif
;
NRRDIO_EXPORT char *biffGetDone(const char *key);
NRRDIO_EXPORT void biffSetStrDone(char *str, const char *key);

#ifdef __cplusplus
}
#endif



#include <limits.h>

#ifdef __cplusplus
extern "C" {
#endif

/* feel free to set these to higher values and recompile */
#define NRRD_DIM_MAX 16            /* Max array dimension (nrrd->dim) */
#define NRRD_SPACE_DIM_MAX 8       /* Max dimension of "space" around array 
                                      (nrrd->spaceDim) */

#define NRRD_EXT_NRRD   ".nrrd"
#define NRRD_EXT_NHDR   ".nhdr"
#define NRRD_EXT_PGM    ".pgm"
#define NRRD_EXT_PPM    ".ppm"
#define NRRD_EXT_PNG    ".png"
#define NRRD_EXT_VTK    ".vtk"
#define NRRD_EXT_TEXT   ".txt"
#define NRRD_EXT_EPS    ".eps"

#define NRRD_KERNEL_PARMS_NUM 8    /* max # arguments to a kernel-
                                      this is weird: it isn't the max
                                      of any of the NrrdKernels
                                      defined by the nrrd library
                                      (that is more like 3), but is
                                      the max number of parms of any
                                      NrrdKernel used by anyone using
                                      Teem, such as in gage.
                                      Enforcing one global max
                                      simplifies implementation. */

/* 
** For the 64-bit integer types (not standard except in C99), we try
** to use the names for the _MIN and _MAX values which are used in C99
** (as well as gcc) such as LLONG_MAX.
** 
** If these aren't defined, we try the ones used on SGI such as
** LONGLONG_MAX.
**
** If these aren't defined either, we go wild and define something
** ourselves (which just happen to be the values defined in C99), with
** total disregard to what the architecture and compiler actually
** support.  These values are tested, however, by nrrdSanity().
*/

#ifdef LLONG_MAX
#  define NRRD_LLONG_MAX LLONG_MAX
#else
#  ifdef LONGLONG_MAX
#    define NRRD_LLONG_MAX LONGLONG_MAX
#  else
#    define NRRD_LLONG_MAX AIR_LLONG(9223372036854775807)
#  endif
#endif

#ifdef LLONG_MIN
#  define NRRD_LLONG_MIN LLONG_MIN
#else
#  ifdef LONGLONG_MIN
#    define NRRD_LLONG_MIN LONGLONG_MIN
#  else
#    define NRRD_LLONG_MIN (-NRRD_LLONG_MAX-AIR_LLONG(1))
#  endif
#endif

#ifdef ULLONG_MAX
#  define NRRD_ULLONG_MAX ULLONG_MAX
#else
#  ifdef ULONGLONG_MAX
#    define NRRD_ULLONG_MAX ULONGLONG_MAX
#  else
#    define NRRD_ULLONG_MAX AIR_ULLONG(18446744073709551615)
#  endif
#endif

/*
** Chances are, you shouldn't mess with these
*/

#define NRRD_COMMENT_CHAR '#'
#define NRRD_FILENAME_INCR 32
#define NRRD_COMMENT_INCR 16
#define NRRD_KEYVALUE_INCR 32
#define NRRD_LIST_FLAG "LIST"
#define NRRD_PNM_COMMENT "# NRRD>"    /* this is designed to be robust against
                                         the mungling that xv does, but no
                                         promises for any other image
                                         programs */

#define NRRD_PNG_FIELD_KEY "NRRD"     /* this is the key used for getting nrrd
                                         fields into/out of png comments */
#define NRRD_PNG_COMMENT_KEY "NRRD#"  /* this is the key used for getting nrrd
                                         comments into/out of png comments */

#define NRRD_UNKNOWN  "???"           /* how to represent something unknown in
                                         a field of the nrrd header, when it
                                         being unknown is not an error */
#define NRRD_NONE "none"              /* like NRRD_UNKNOWN, but with an air
                                         of certainty */

#ifdef __cplusplus
}
#endif



#ifdef __cplusplus
extern "C" {
#endif

/*******
******** NONE of these enums should have values set explicitly in their
******** definition.  The values should simply start at 0 (for Unknown)
******** and increase one integer per value.  The _nrrdCheckEnums()
******** sanity check assumes this, and there is no reason to use 
******** explicit values for any of the enums.
*******/

/*
******** nrrdIoState* enum
** 
** the various things it makes sense to get and set in nrrdIoState struct
** via nrrdIoStateGet and nrrdIoStateSet
*/
enum {
  nrrdIoStateUnknown,
  nrrdIoStateDetachedHeader,
  nrrdIoStateBareText,
  nrrdIoStateCharsPerLine,
  nrrdIoStateValsPerLine,
  nrrdIoStateSkipData,
  nrrdIoStateKeepNrrdDataFileOpen,
  nrrdIoStateZlibLevel,
  nrrdIoStateZlibStrategy,
  nrrdIoStateBzip2BlockSize,
  nrrdIoStateLast
};

/*
******** nrrdFormatType* enum
**
** the different file formats which nrrd supports
*/
enum {
  nrrdFormatTypeUnknown,
  nrrdFormatTypeNRRD,   /* 1: basic nrrd format (associated with any of
                           the magics starting with "NRRD") */
  nrrdFormatTypePNM,    /* 2: PNM image */
  nrrdFormatTypePNG,    /* 3: PNG image */
  nrrdFormatTypeVTK,    /* 4: VTK Structured Points datasets (v1.0 and 2.0) */
  nrrdFormatTypeText,   /* 5: bare ASCII text for 2D arrays */
  nrrdFormatTypeEPS,    /* 6: Encapsulated PostScript (write-only) */
  nrrdFormatTypeLast
};
#define NRRD_FORMAT_TYPE_MAX    6

/*
******** nrrdBoundary* enum
**
** when resampling, how to deal with the ends of a scanline
*/
enum {
  nrrdBoundaryUnknown,
  nrrdBoundaryPad,      /* 1: fill with some user-specified value */
  nrrdBoundaryBleed,    /* 2: copy the last/first value out as needed */
  nrrdBoundaryWrap,     /* 3: wrap-around */
  nrrdBoundaryWeight,   /* 4: normalize the weighting on the existing samples;
                           ONLY sensible for a strictly positive kernel
                           which integrates to unity (as in blurring) */
  nrrdBoundaryMirror,   /* 5: mirror folding */
  nrrdBoundaryLast
};
#define NRRD_BOUNDARY_MAX  5

/*
******** nrrdType* enum
**
** all the different types, identified by integer
**
** 18 July 03: After some consternation, I decided to set
** nrrdTypeUnknown and nrrdTypeDefault to the same thing, with the
** reasoning that the only times that nrrdTypeDefault is used is when
** controlling an *output* type (the type of "nout"), or rather,
** choosing not to control an output type.  As output types must be
** known, there is no confusion between being unset/unknown (invalid)
** and being simply default.
*/
enum {
  nrrdTypeUnknown=0,     /*  0: signifies "type is unset/unknown" */
  nrrdTypeDefault=0,     /*  0: signifies "determine output type for me" */
  nrrdTypeChar,          /*  1:   signed 1-byte integer */
  nrrdTypeUChar,         /*  2: unsigned 1-byte integer */
  nrrdTypeShort,         /*  3:   signed 2-byte integer */
  nrrdTypeUShort,        /*  4: unsigned 2-byte integer */
  nrrdTypeInt,           /*  5:   signed 4-byte integer */
  nrrdTypeUInt,          /*  6: unsigned 4-byte integer */
  nrrdTypeLLong,         /*  7:   signed 8-byte integer */
  nrrdTypeULLong,        /*  8: unsigned 8-byte integer */
  nrrdTypeFloat,         /*  9:          4-byte floating point */
  nrrdTypeDouble,        /* 10:          8-byte floating point */
  nrrdTypeBlock,         /* 11: size user defined at run time; MUST BE LAST */
  nrrdTypeLast
};
#define NRRD_TYPE_MAX       11
#define NRRD_TYPE_SIZE_MAX   8    /* max(sizeof()) over all scalar types */
#define NRRD_TYPE_BIGGEST double  /* this should be a basic C type which
                                     requires for storage the maximum size
                                     of all the basic C types */

/*
******** nrrdEncodingType enum
**
** how data might be encoded into a bytestream
*/
enum {
  nrrdEncodingTypeUnknown,
  nrrdEncodingTypeRaw,      /* 1: same as memory layout (modulo endianness) */
  nrrdEncodingTypeAscii,    /* 2: decimal values are spelled out in ascii */
  nrrdEncodingTypeHex,      /* 3: hexidecimal (two chars per byte) */
  nrrdEncodingTypeGzip,     /* 4: gzip'ed raw data */
  nrrdEncodingTypeBzip2,    /* 5: bzip2'ed raw data */
  nrrdEncodingTypeLast
};
#define NRRD_ENCODING_TYPE_MAX 5

/*
******** nrrdZlibStrategy enum
**
** how gzipped data is compressed
*/
enum {
  nrrdZlibStrategyUnknown,
  nrrdZlibStrategyDefault,   /* 1: default (Huffman + string match) */
  nrrdZlibStrategyHuffman,   /* 2: Huffman only */
  nrrdZlibStrategyFiltered,  /* 3: specialized for filtered data */
  nrrdZlibStrategyLast
};
#define NRRD_ZLIB_STRATEGY_MAX  3

/*
******** nrrdCenter enum
**
** node-centered vs. cell-centered
*/
enum {
  nrrdCenterUnknown,         /* 0: no centering known for this axis */
  nrrdCenterNode,            /* 1: samples at corners of things
                                (how "voxels" are usually imagined)
                                |\______/|\______/|\______/|
                                X        X        X        X   */
  nrrdCenterCell,            /* 2: samples at middles of things
                                (characteristic of histogram bins)
                                 \___|___/\___|___/\___|___/
                                     X        X        X       */
  nrrdCenterLast
};
#define NRRD_CENTER_MAX         2

/*
******** nrrdKind enum
**
** For describing the information along one axis of an array.  This is
** most important for clarifying the representation of non-scalar
** data, in order to distinguish between axes that are genuine image
** domain axes, and axes that exist just to store the multiple
** attributes per sample.  One could argue that this information
** should be per-array and not per-axis, but you still have to
** indicate which one of the axes is the attribute axis.  And, if you
** have, say, the gradient of RGB colors, you want the per-pixel 3x3
** array to have those two attribute axes tagged accordingly.
**
** More of these may be added in the future, such as when nrrd
** supports bricking.  Since nrrd is never going to be in the business
** of manipulating the kind information or supporting kind-specific
** semantics, there can be proliferation of nrrdKinds, provided
** pointless redundancy is avoided.  
**
**  There is a relationship between some of these (nrrdKindSpace is a
** specific nrrdKindDomain), but currently there is no effort to
** record this meta-kind information.
**
** Keep in sync:
**   enumsNrrd.c: nrrdKind airEnum
**        axis.c: nrrdKindSize()
**        axis.c: _nrrdKindAltered()
**
** NOTE: The nrrdKindSize() function returns the valid size for these.
** 
*/
enum {
  nrrdKindUnknown,
  nrrdKindDomain,            /*  1: any image domain */
  nrrdKindSpace,             /*  2: a spatial domain */
  nrrdKindTime,              /*  3: a temporal domain */
  /* -------------------------- end domain kinds */
  /* -------------------------- begin range kinds */
  nrrdKindList,              /*  4: any list of values, non-resample-able */
  nrrdKindPoint,             /*  5: coords of a point */
  nrrdKindVector,            /*  6: coeffs of (contravariant) vector */
  nrrdKindCovariantVector,   /*  7: coeffs of covariant vector (eg gradient) */
  nrrdKindNormal,            /*  8: coeffs of unit-length covariant vector */
  /* -------------------------- end arbitrary size kinds */
  /* -------------------------- begin size-specific kinds */
  nrrdKindStub,              /*  9: axis with one sample (a placeholder) */
  nrrdKindScalar,            /* 10: effectively, same as a stub */
  nrrdKindComplex,           /* 11: real and imaginary components */
  nrrdKind2Vector,           /* 12: 2 component vector */
  nrrdKind3Color,            /* 13: ANY 3-component color value */
  nrrdKindRGBColor,          /* 14: RGB, no colorimetry */
  nrrdKindHSVColor,          /* 15: HSV, no colorimetry */
  nrrdKindXYZColor,          /* 16: perceptual primary colors */
  nrrdKind4Color,            /* 17: ANY 4-component color value */
  nrrdKindRGBAColor,         /* 18: RGBA, no colorimetry */
  nrrdKind3Vector,           /* 19: 3-component vector */
  nrrdKind3Gradient,         /* 20: 3-component covariant vector */
  nrrdKind3Normal,           /* 21: 3-component covector, assumed normalized */
  nrrdKind4Vector,           /* 22: 4-component vector */
  nrrdKindQuaternion,        /* 23: (w,x,y,z), not necessarily normalized */
  nrrdKind2DSymMatrix,       /* 24: Mxx Mxy Myy */
  nrrdKind2DMaskedSymMatrix, /* 25: mask Mxx Mxy Myy */
  nrrdKind2DMatrix,          /* 26: Mxx Mxy Myx Myy */
  nrrdKind2DMaskedMatrix,    /* 27: mask Mxx Mxy Myx Myy */
  nrrdKind3DSymMatrix,       /* 28: Mxx Mxy Mxz Myy Myz Mzz */
  nrrdKind3DMaskedSymMatrix, /* 29: mask Mxx Mxy Mxz Myy Myz Mzz */
  nrrdKind3DMatrix,          /* 30: Mxx Mxy Mxz Myx Myy Myz Mzx Mzy Mzz */
  nrrdKind3DMaskedMatrix,    /* 31: mask Mxx Mxy Mxz Myx Myy Myz Mzx Mzy Mzz */
  nrrdKindLast
};
#define NRRD_KIND_MAX           31

/*
******** nrrdAxisInfo enum
**
** the different pieces of per-axis information recorded in a nrrd
*/
enum {
  nrrdAxisInfoUnknown,
  nrrdAxisInfoSize,                   /*  1: number of samples along axis */
#define NRRD_AXIS_INFO_SIZE_BIT      (1<< 1)
  nrrdAxisInfoSpacing,                /*  2: spacing between samples */
#define NRRD_AXIS_INFO_SPACING_BIT   (1<< 2)
  nrrdAxisInfoThickness,              /*  3: thickness of sample region */
#define NRRD_AXIS_INFO_THICKNESS_BIT (1<< 3)
  nrrdAxisInfoMin,                    /*  4: min pos. assoc. w/ 1st sample */
#define NRRD_AXIS_INFO_MIN_BIT       (1<< 4) 
  nrrdAxisInfoMax,                    /*  5: max pos. assoc. w/ last sample */
#define NRRD_AXIS_INFO_MAX_BIT       (1<< 5)
  nrrdAxisInfoSpaceDirection,         /*  6: inter-sample vector in "space" */
#define NRRD_AXIS_INFO_SPACEDIRECTION_BIT (1<< 6)
  nrrdAxisInfoCenter,                 /*  7: cell vs. node */
#define NRRD_AXIS_INFO_CENTER_BIT    (1<< 7)
  nrrdAxisInfoKind,                   /*  8: from the nrrdKind* enum */
#define NRRD_AXIS_INFO_KIND_BIT      (1<< 8)
  nrrdAxisInfoLabel,                  /*  9: string describing the axis */
#define NRRD_AXIS_INFO_LABEL_BIT     (1<< 9)
  nrrdAxisInfoUnits,                  /* 10: from the nrrdUnit* enum */
#define NRRD_AXIS_INFO_UNITS_BIT     (1<<10)
  nrrdAxisInfoLast
};
#define NRRD_AXIS_INFO_MAX               10
#define NRRD_AXIS_INFO_ALL  \
    ((1<<1)|(1<<2)|(1<<3)|(1<<4)|(1<<5)|(1<<6)|(1<<7)|(1<<8)|(1<<9)|(1<<10))
#define NRRD_AXIS_INFO_NONE 0

/*
******** nrrdBasicInfo enum
**
** the non-per-axis (or per-array) pieces of information that could
** meaningfully be copied between nrrds (hence the void *data is not
** included).
**
** "Basic" is named after the "basic field specifications" described
** in the NRRD file format definition
*/
enum {
  nrrdBasicInfoUnknown,
  nrrdBasicInfoData,                          /*  1 */
#define NRRD_BASIC_INFO_DATA_BIT             (1<< 1)
  nrrdBasicInfoType,                          /*  2 */
#define NRRD_BASIC_INFO_TYPE_BIT             (1<< 2)
  nrrdBasicInfoBlocksize,                     /*  3 */
#define NRRD_BASIC_INFO_BLOCKSIZE_BIT        (1<< 3)
  nrrdBasicInfoDimension,                     /*  4 */
#define NRRD_BASIC_INFO_DIMENSION_BIT        (1<< 4)
  nrrdBasicInfoContent,                       /*  5 */
#define NRRD_BASIC_INFO_CONTENT_BIT          (1<< 5)
  nrrdBasicInfoSampleUnits,                   /*  6 */
#define NRRD_BASIC_INFO_SAMPLEUNITS_BIT      (1<< 6)
  nrrdBasicInfoSpace,                         /*  7 */
#define NRRD_BASIC_INFO_SPACE_BIT            (1<< 7)
  nrrdBasicInfoSpaceDimension,                /*  8 */
#define NRRD_BASIC_INFO_SPACEDIMENSION_BIT   (1<< 8)
  nrrdBasicInfoSpaceUnits,                    /*  9 */
#define NRRD_BASIC_INFO_SPACEUNITS_BIT       (1<< 9)
  nrrdBasicInfoSpaceOrigin,                   /* 10 */
#define NRRD_BASIC_INFO_SPACEORIGIN_BIT      (1<<10)
  nrrdBasicInfoMeasurementFrame,              /* 11 */
#define NRRD_BASIC_INFO_MEASUREMENTFRAME_BIT (1<<11)
  nrrdBasicInfoOldMin,                        /* 12 */
#define NRRD_BASIC_INFO_OLDMIN_BIT           (1<<12)
  nrrdBasicInfoOldMax,                        /* 13 */ 
#define NRRD_BASIC_INFO_OLDMAX_BIT           (1<<13)
  nrrdBasicInfoComments,                      /* 14 */
#define NRRD_BASIC_INFO_COMMENTS_BIT         (1<<14)
  nrrdBasicInfoKeyValuePairs,                 /* 15 */
#define NRRD_BASIC_INFO_KEYVALUEPAIRS_BIT    (1<<15)
  nrrdBasicInfoLast
};
#define NRRD_BASIC_INFO_MAX                      15
#define NRRD_BASIC_INFO_ALL  \
    ((1<<1)|(1<<2)|(1<<3)|(1<<4)|(1<<5)|(1<<6)|(1<<7)|(1<<8)|(1<<9)|(1<<10)\
     |(1<<11)|(1<<12)|(1<<13)|(1<<14)|(1<<15))
#define NRRD_BASIC_INFO_SPACE (NRRD_BASIC_INFO_SPACE_BIT \
                               | NRRD_BASIC_INFO_SPACEDIMENSION_BIT \
                               | NRRD_BASIC_INFO_SPACEUNITS_BIT \
                               | NRRD_BASIC_INFO_SPACEORIGIN_BIT \
                               | NRRD_BASIC_INFO_MEASUREMENTFRAME_BIT)
#define NRRD_BASIC_INFO_NONE 0

/*
** the "endian" enum is actually in the air library, but it is very
** convenient to have it incorporated into the nrrd enum framework for
** the purposes of string<-->int conversion.  Unfortunately, the
** little and big values are 1234 and 4321 respectively, so
** NRRD_ENDIAN_MAX is not actually the highest valid value, but only
** an indicator of how many valid values there are.
*/
#define NRRD_ENDIAN_MAX 2

/*
******** nrrdField enum
**
** the various fields we can parse in a NRRD header
**
** other things which must be kept in sync:
** arraysNrrd.c: 
**    _nrrdFieldValidInImage[]
**    _nrrdFieldOnePerAxis[]
**    _nrrdFieldValidInText[]
**    _nrrdFieldRequired[]
** parseNrrd.c:
**    _nrrdReadNrrdParseInfo[]
** enumsNrrd.c:
**    nrrdField definition
** simple.c:
**    _nrrdFieldCheck[]
** write.c:
**    _nrrdFieldInteresting()
**    _nrrdSprintFieldInfo()
** to some extent, in this file:
**    nrrdAxisInfo and nrrdBasicInfo enums
** axis.c (for per-axis info):
**    _nrrdAxisInfoCopy()
** methodsNrrd.c:
**    lots of functions, but you knew that ...
*/
enum {
  nrrdField_unknown,
  nrrdField_comment,           /*  1 */
  nrrdField_content,           /*  2 */
  nrrdField_number,            /*  3 */
  nrrdField_type,              /*  4 */
  nrrdField_block_size,        /*  5 */
  nrrdField_dimension,         /*  6 */
  nrrdField_space,             /*  7 */
  nrrdField_space_dimension,   /*  8 */
  nrrdField_sizes,             /*  9 ----- begin per-axis ----- */
  nrrdField_spacings,          /* 10 */
  nrrdField_thicknesses,       /* 11 */
  nrrdField_axis_mins,         /* 12 */
  nrrdField_axis_maxs,         /* 13 */
  nrrdField_space_directions,  /* 14 */
  nrrdField_centers,           /* 15 */
  nrrdField_kinds,             /* 16 */
  nrrdField_labels,            /* 17 */
  nrrdField_units,             /* 18 ------ end per-axis ------ */
  nrrdField_min,               /* 19 */
  nrrdField_max,               /* 20 */
  nrrdField_old_min,           /* 21 */
  nrrdField_old_max,           /* 22 */
  nrrdField_endian,            /* 23 */
  nrrdField_encoding,          /* 24 */
  nrrdField_line_skip,         /* 25 */
  nrrdField_byte_skip,         /* 26 */
  nrrdField_keyvalue,          /* 27 */
  nrrdField_sample_units,      /* 28 */
  nrrdField_space_units,       /* 29 */
  nrrdField_space_origin,      /* 30 */
  nrrdField_measurement_frame, /* 31 */
  nrrdField_data_file,         /* 32 */
  nrrdField_last
};
#define NRRD_FIELD_MAX            32

/* 
******** nrrdHasNonExist* enum
**
** oh look, I'm violating my rules outline above for how the enum values
** should be ordered.  The reason for this is that its just too bizarro to
** have the logical value of both nrrdHasNonExistFalse and nrrdHasNonExistTrue
** to be (in C) true.  For instance, nrrdHasNonExist() should be able to 
** return a value from this enum which also functions in a C expressions as
** the expected boolean value.  If for some reason (outide the action of
** nrrdHasNonExist(), nrrdHasNonExistUnknown is interpreted as true, that's
** probably harmlessly conservative.  Time will tell.
*/
enum {
  nrrdHasNonExistFalse,     /* 0: no non-existent values were seen */
  nrrdHasNonExistTrue,      /* 1: some non-existent values were seen */
  nrrdHasNonExistOnly,      /* 2: NOTHING BUT non-existant values were seen */
  nrrdHasNonExistUnknown,   /* 3 */
  nrrdHasNonExistLast
};
#define NRRD_HAS_NON_EXIST_MAX 3

/*
******** nrrdSpace* enum
**
** Identifies the space in which which the origin and direction
** vectors have their coordinates measured.  When a direction is named
** here (like "Left" or "Anterior"), that implies a basis vector that
** points in that direction, along which that coordinate becomes *larger*
** (this is the opposite of MetaIO, for example).
**
** All of these spaces have a well-defined expected dimension, as
** determined by nrrdSpaceDimension(), and setting a nrrd to be in
** such a space, by nrrdSpaceSet(), will automatically set nrrd->spaceDim.
**
** The first six spaces here are PATIENT-ORIENTED spaces, which are
** properly speaking aligned with the patient, and not the scanner
** itself.  But nrrdSpaceScannerXYZ and nrrdSpaceScannerXYZTime are
** DEVICE-ORIENTED spaces, irrespective of the patient, used in a
** previous version of the DICOM standard.  When the two spaces are
** lined up with normal patient orientation in the scanner,
** nrrdSpaceScannerXYZ is the same as nrrdSpaceLeftPosteriorSuperior.
** To quote Part 3 (Information Object Definitions) of the DICOM spec
** (page 275): "If a patient lies parallel to the ground, face-up on
** the table, with his feet-to-head direction same as the
** front-to-back direction of the imaging equipment, the direction of
** the axes of this patient based coordinate system and the equipment
** based coordinate system in previous versions of this Standard will
** coincide."
**
** Keep in sync:
**   enumsNrrd.c: nrrdSpace airEnum
**      simple.c: int nrrdSpaceDimension(int space)
*/
enum {
  nrrdSpaceUnknown,
  nrrdSpaceRightAnteriorSuperior,     /*  1: NIFTI-1 (right-handed) */
  nrrdSpaceLeftAnteriorSuperior,      /*  2: standard Analyze (left-handed) */
  nrrdSpaceLeftPosteriorSuperior,     /*  3: DICOM 3.0 (right-handed) */
  nrrdSpaceRightAnteriorSuperiorTime, /*  4: */
  nrrdSpaceLeftAnteriorSuperiorTime,  /*  5: */
  nrrdSpaceLeftPosteriorSuperiorTime, /*  6: */
  nrrdSpaceScannerXYZ,                /*  7: ACR/NEMA 2.0 (pre-DICOM 3.0) */
  nrrdSpaceScannerXYZTime,            /*  8: */
  nrrdSpace3DRightHanded,             /*  9: */
  nrrdSpace3DLeftHanded,              /* 10: */
  nrrdSpace3DRightHandedTime,         /* 11: */
  nrrdSpace3DLeftHandedTime,          /* 12: */
  nrrdSpaceLast
};
#define NRRD_SPACE_MAX                   12

/*
******** nrrdSpacingStatus* enum
**
** a way of describing how spacing information is known or not known for a 
** given axis, as determined by nrrdSpacingCalculate
*/
enum {
  nrrdSpacingStatusUnknown,           /* 0: nobody knows,
                                         or invalid axis choice */
  nrrdSpacingStatusNone,              /* 1: neither axis->spacing nor
                                         axis->spaceDirection is set */
  nrrdSpacingStatusScalarNoSpace,     /* 2: axis->spacing set,
                                         w/out space info */
  nrrdSpacingStatusScalarWithSpace,   /* 3: axis->spacing set, but there *is*
                                         space info, which means the spacing
                                         does *not* live in the surrounding
                                         space */
  nrrdSpacingStatusDirection,         /* 4: axis->spaceDirection set, and 
                                         measured according to surrounding
                                         space */
  nrrdSpacingStatusLast
};
#define NRRD_SPACING_STATUS_MAX          4

/*
******** nrrdOriginStatus* enum
**
** how origin information was or was not computed by nrrdOriginCalculate
*/
enum {
  nrrdOriginStatusUnknown,        /* 0: nobody knows, or invalid parms */
  nrrdOriginStatusDirection,      /* 1: chosen axes have spaceDirections */
  nrrdOriginStatusNoMin,          /* 2: axis->min doesn't exist */
  nrrdOriginStatusNoMaxOrSpacing, /* 3: axis->max or ->spacing doesn't exist */
  nrrdOriginStatusOkay,           /* 4: all is well */
  nrrdOriginStatusLast
};


#ifdef __cplusplus
}
#endif



#ifdef __cplusplus
extern "C" {
#endif

/*
******** NRRD_CELL_POS, NRRD_NODE_POS, NRRD_POS
******** NRRD_CELL_IDX, NRRD_NODE_IDX, NRRD_IDX
**
** the guts of nrrdAxisPos() and nrrdAxisIdx(), for converting
** between "index space" location and "position" or "world space" location,
** given the centering, min and max "position", and number of samples.
**
** Unlike nrrdAxisPos() and nrrdAxisIdx(), this assumes that center
** is either nrrdCenterCell or nrrdCenterNode, but not nrrdCenterUnknown.
*/
/* index to position, cell centering */
#define NRRD_CELL_POS(min, max, size, idx)       \
  AIR_AFFINE(0, (idx) + 0.5, (size), (min), (max))

/* index to position, node centering */
#define NRRD_NODE_POS(min, max, size, idx)       \
  AIR_AFFINE(0, (idx), (size)-1, (min), (max))

/* index to position, either centering */
#define NRRD_POS(center, min, max, size, idx)    \
  (nrrdCenterCell == (center)                         \
   ? NRRD_CELL_POS((min), (max), (size), (idx))  \
   : NRRD_NODE_POS((min), (max), (size), (idx)))

/* position to index, cell centering */
#define NRRD_CELL_IDX(min, max, size, pos)       \
  (AIR_AFFINE((min), (pos), (max), 0, (size)) - 0.5)

/* position to index, node centering */
#define NRRD_NODE_IDX(min, max, size, pos)       \
  AIR_AFFINE((min), (pos), (max), 0, (size)-1)

/* position to index, either centering */
#define NRRD_IDX(center, min, max, size, pos)    \
  (nrrdCenterCell == (center)                         \
   ? NRRD_CELL_IDX((min), (max), (size), (pos))  \
   : NRRD_NODE_IDX((min), (max), (size), (pos)))

/*
******** NRRD_SPACING
**
** the guts of nrrdAxisSpacing(), determines the inter-sample
** spacing, given centering, min and max "position", and number of samples
**
** Unlike nrrdAxisSpacing, this assumes that center is either
** nrrdCenterCell or nrrdCenterNode, but not nrrdCenterUnknown.
*/
#define NRRD_SPACING(center, min, max, size)  \
  (nrrdCenterCell == center                        \
   ? ((max) - (min))/(size)                        \
   : ((max) - (min))/((size) - 1))                 \

/*
******** NRRD_COORD_UPDATE
**
** This is for doing the "carrying" associated with gradually
** incrementing an array of coordinates.  Assuming that the given
** coordinate array "coord" has been incrementing by adding 1 to THE
** FIRST, THE ZERO-ETH, ELEMENT (this is a strong assumption), then,
** this macro is good for propagating the change up to higher axes
** (which really only happens when the position has stepped over the
** limit on a lower axis.)  Relies on the array of axes sizes "size",
** as as the length "dim" of "coord" and "size".
**
** This may be turned into something more general purpose soon. 
*/
#define NRRD_COORD_UPDATE(coord, size, dim)    \
do {                                           \
  unsigned int d;                              \
  for (d=0;                                    \
       d < (dim)-1 && (coord)[d] == (size)[d]; \
       d++) {                                  \
    (coord)[d] = 0;                            \
    (coord)[d+1]++;                            \
  }                                            \
} while (0)

/*
******** NRRD_COORD_INCR
**
** same as NRRD_COORD_UPDATE, but starts by incrementing coord[idx]
*/
#define NRRD_COORD_INCR(coord, size, dim, idx) \
do {                                           \
  unsigned int d;                              \
  for (d=idx, (coord)[d]++;                    \
       d < (dim)-1 && (coord)[d] == (size)[d]; \
       d++) {                                  \
    (coord)[d] = 0;                            \
    (coord)[d+1]++;                            \
  }                                            \
} while (0)

/*
******** NRRD_INDEX_GEN
**
** Given a coordinate array "coord", as well as the array sizes "size"
** and dimension "dim", calculates the linear index, and stores it in
** "I".
*/
#define NRRD_INDEX_GEN(I, coord, size, dim)     \
{                                               \
  int d;                                        \
  d = (dim) - 1;                                \
  if ( (d) >= 0 )                               \
  {                                             \
    (I) = (coord)[d];                           \
    d--;                                        \
    while( d >= 0 )                             \
    {                                           \
    (I) = (coord)[d] + (size)[d] * (I);         \
    d--;                                        \
    }                                           \
  }                                             \
}
/*
******** NRRD_COORD_GEN
**
** opposite of NRRD_INDEX_GEN: going from linear index "I" to
** coordinate array "coord".
**
** HUGE NOTE: the I argument will end up as ZERO when this is done!
** If passing a loop control variable, pass a copy instead!
** Hello, side-effects!  This is awful!
*/
#define NRRD_COORD_GEN(coord, size, dim, I)   \
do {                                          \
  unsigned int d;                             \
  for (d=0; d<=(dim)-1; d++) {                \
    (coord)[d] = I % (size)[d];               \
    I /= (size)[d];                           \
  }                                           \
} while (0)

#ifdef __cplusplus
}
#endif



#include <errno.h>
#include <stddef.h>      /* for ptrdiff_t */



#ifdef __cplusplus
extern "C" {
#endif

#define NRRD nrrdBiffKey

/*
******** NrrdAxisInfo struct
**
** all the information which can sensibly be associated with
** one axis of a nrrd.  The only member which MUST be explicitly
** set to something meaningful is "size".
**
** If an axis lies conceptually along some direction in an enclosing
** space of dimension nrrd->spaceDim, then the first nrrd->spaceDim
** entries of spaceDirection[] must be non-NaN, and min, max, spacing,
** and units must NOT be set;  thickness, center, and label can still
** be used.  The mutual exclusion between axis-aligned and general
** direction information is enforced per-axis, not per-array.
**
** The min and max values give the range of positions "represented"
** by the samples along this axis.  In node-centering, "min" IS the
** position at the lowest index.  In cell-centering, the position at
** the lowest index is between min and max (a touch bigger than min,
** assuming min < max).
**
** There needs to be a one-to-one correspondence between these variables
** and the nrrdAxisInfo* enum (nrrdEnums.h), the per-axis header fields
** (see nrrdField* enum in nrrdEnums.h), and the various methods in axis.c
*/
typedef struct {
  size_t size;              /* number of elements along each axis */
  double spacing;           /* if non-NaN, distance between samples */
  double thickness;         /* if non-NaN, nominal thickness of region
                               represented by one sample along the axis. No
                               semantics relative to spacing are assumed or
                               imposed, and unlike spacing, there is no
                               sensible way to alter thickness- it is either
                               copied (as with cropping and slicing) or set to
                               NaN (when resampled). */
  double min, max;          /* if non-NaN, range of positions spanned by the
                               samples on this axis.  Obviously, one can set
                               "spacing" to something incompatible with min
                               and max: the idea is that only one (min and
                               max, or spacing) should be taken to be
                               significant at any time. */
  double spaceDirection[NRRD_SPACE_DIM_MAX]; 
                            /* the vector, in "space" (as described by
                               nrrd->space and/or nrrd->spaceDim), from one
                               sample to the next sample along this axis.  It
                               is the column vector of the transform from
                               index space to "space" space */
  int center;               /* cell vs. node centering (value should be one of
                               nrrdCenter{Unknown,Node,Cell} */
  int kind;                 /* what kind of information is along this axis
                               (from the nrrdKind* enum) */
  char *label,              /* short info string for each axis */
    *units;                 /* string identifying the unit */
} NrrdAxisInfo;

/*
******** Nrrd struct
**
** The struct used to wrap around the raw data array
*/
typedef struct {
  /* 
  ** NECESSARY information describing the main array.  This is
  ** generally set at the same time that either the nrrd is created,
  ** or at the time that the nrrd is wrapped around an existing array 
  */

  void *data;                       /* the data in memory */
  int type;                         /* a value from the nrrdType enum */
  unsigned int dim;                 /* the dimension (rank) of the array */

  /* 
  ** All per-axis specific information
  */
  NrrdAxisInfo axis[NRRD_DIM_MAX];  /* axis[0] is the fastest axis in the scan-
                                       line ordering, the one who's coordinates
                                       change the fastest as the elements are
                                       accessed in the order in which they
                                       appear in memory */

  /* 
  ** Optional information descriptive of whole array, some of which is
  ** meaningfuly for only some uses of a nrrd
  */
  char *content;                    /* brief account of what this data is */
  char *sampleUnits;                /* units of measurement of the values 
                                       stored in the array itself (not the 
                                       array axes and not space coordinates).
                                       The logical name might be "dataUnits",
                                       but that's perhaps ambiguous.  Note that
                                       these units may apply to non-scalar
                                       kinds (e.g. coefficients of a vector
                                       have the same units) */
  int space;                        /* from nrrdSpace* enum, and often 
                                       implies the value of spaceDim */
  unsigned int spaceDim;            /* if non-zero, the dimension of the space
                                       in which the regular sampling grid
                                       conceptually lies.  This is a separate
                                       variable because this dimension can be
                                       different than the array dimension. 
                                       The non-zero-ness of this value is in 
                                       fact the primary indicator that space
                                       and orientation information is set.
                                       This identifies the number of entries in
                                       "origin" and the per-axis "direction"
                                       vectors that are taken as meaningful */
  char *spaceUnits[NRRD_SPACE_DIM_MAX];
                                    /* units for coordinates of space */
  double spaceOrigin[NRRD_SPACE_DIM_MAX];
                                    /* the location of the center the first
                                       (lowest memory address) array sample,
                                       regardless of node-vs-cell centering */
  double measurementFrame[NRRD_SPACE_DIM_MAX][NRRD_SPACE_DIM_MAX];
                                    /* if spaceDim is non-zero, this may store 
                                       a spaceDim-by-spaceDim matrix which 
                                       transforms vector/matrix coefficients
                                       in the "measurement frame" to those in
                                       the world space described by spaceDim
                                       (and hopefully space).  Coeff [i][j] is
                                       *column* i & *row* j, which is probably
                                       the *transpose* of what you expect.
                                       There are no semantics linking this to
                                       the "kind" of any axis, for a variety
                                       of reasons */
  size_t blockSize;                 /* for nrrdTypeBlock, block byte size */
  double oldMin, oldMax;            /* if non-NaN, and if nrrd is of integral
                                       type, extremal values for the array
                                       BEFORE it was quantized */
  void *ptr;                        /* never read or set by nrrd; use/abuse
                                       as you see fit */

  /* 
  ** Comments.  Read from, and written to, header.
  ** The comment array "cmt" is NOT NULL-terminated.
  ** The number of comments is cmtArr->len.
  */
  char **cmt;
  airArray *cmtArr;

  /*
  ** Key-value pairs.
  */
  char **kvp;
  airArray *kvpArr;
} Nrrd;

struct NrrdIoState_t;
struct NrrdEncoding_t;

/*
******** NrrdFormat
**
** All information and behavior relevent to one datafile format
*/
typedef struct {
  char name[AIR_STRLEN_SMALL];    /* short identifying string */
  int isImage,    /* this format is intended solely for "2D" images, which
                     controls the invocation of _nrrdReshapeUpGrayscale()
                     if nrrdStateGrayscaleImage3D */
    readable,     /* we can read as well as write this format */
    usesDIO;      /* this format can use Direct IO */

  /* tests if this format is currently available in this build */
  int (*available)(void);

  /* (for writing) returns non-zero if a given filename could likely be
     represented by this format */
  int (*nameLooksLike)(const char *filename);

  /* (for writing) returns non-zero if a given nrrd/encoding pair will fit
     in this format */
  int (*fitsInto)(const Nrrd *nrrd, const struct NrrdEncoding_t *encoding, 
                   int useBiff);

  /* (for reading) returns non-zero if what has been read in so far 
     is recognized as the beginning of this format */
  int (*contentStartsLike)(struct NrrdIoState_t *nio);

  /* reader and writer */
  int (*read)(FILE *file, Nrrd *nrrd, struct NrrdIoState_t *nio);
  int (*write)(FILE *file, const Nrrd *nrrd, struct NrrdIoState_t *nio);
} NrrdFormat;

/*
******** NrrdEncoding
**
** All information and behavior relevent to one way of encoding data
**
** The data readers are responsible for memory allocation.
** This is necessitated by the memory restrictions of direct I/O
*/
typedef struct NrrdEncoding_t {
  char name[AIR_STRLEN_SMALL],    /* short identifying string */
    suffix[AIR_STRLEN_SMALL];     /* costumary filename suffix */
  int endianMatters,
    isCompression;
  int (*available)(void);
  /* The "data" and "elementNum" values have to be passed explicitly
     to read/wrote because they will be different from nrrd->data and
     nrrdElementNumber(nrrd) in the case of multiple data files.  You
     might think that the only other thing required to be passed is
     nrrdElementSize(nrrd), but no, it is in fact best to pass the
     whole Nrrd, instead of just certain attributes.  The stupid details:
             nrrd->dim: needed to know whether to put one value per line
                        in case of 1-D nrrdEncodingAscii
    nrrd->axis[0].size: need for proper formatting of nrrdEncodingAscii
            nrrd->type: needed for nrrdEncodingAscii, since its action is
                        entirely parameterized by type
       nrrd->blockSize: needed for nrrdElementSize in case of nrrdTypeBlock */
  int (*read)(FILE *file, void *data, size_t elementNum,
              Nrrd *nrrd, struct NrrdIoState_t *nio);
  int (*write)(FILE *file, const void *data, size_t elementNum,
               const Nrrd *nrrd, struct NrrdIoState_t *nio);
} NrrdEncoding;

/*
******** NrrdIoState struct
**
** Everything relating to how the nrrd is read and written.
** Multiple parameters for writing are set here (like format, encoding, 
** zlib parameters).  Also, this is the place where those few parameters
** of reading are stored (like skipData and keepNrrdDataFileOpen).  Also,
** after the nrrd has been read, it is a potentially useful record of what
** it took to read it in.
*/
typedef struct NrrdIoState_t {
  char *path,               /* allows us to remember the directory
                               from whence this nrrd was "load"ed, or
                               to whence this nrrd is "save"ed, MINUS the
                               trailing "/", so as to facilitate games with
                               header-relative data files */
    *base,                  /* when "save"ing a nrrd into seperate
                               header and data, the name of the header
                               file (e.g. "output.nhdr") MINUS the ".nhdr".
                               This is massaged to produce a header-
                               relative data filename.  */
    *line,                  /* buffer for saving one line from file */
    *dataFNFormat,          /* if non-NULL, the format string (containing 
                               something like "%d" as a substring) to be 
                               used to identify multiple detached datafiles.
                               NB: This is "format" in the sense of a printf-
                               style format string, not in the sense of a 
                               file format.  This may need header-relative
                               path processing. */
    **dataFN,               /* ON READ + WRITE: array of data filenames. These
                               are not passed directly to fopen, they may need
                               header-relative path processing. Like the
                               cmtArr in the Nrrd, this array is not NULL-
                               terminated */
    *headerStringWrite;     /* ON WRITE: string from to which the header can
                               be written.  On write, it is assumed allocated
                               for as long as it needs to be (probably via a
                               first pass with learningHeaderStrlen). NOTE:
                               It is the non-NULL-ity of this which signifies
                               the intent to do string-based writing */
  const char
    *headerStringRead;      /* ON READ: like headerStringWrite, but for
                               reading the header from.  NOTE: It is the
                               non-NULL-ity of this which signifies the
                               intent to do string-based reading */
  airArray *dataFNArr;      /* for managing the above */

  FILE *headerFile,         /* if non-NULL, the file from which the NRRD
                               header is being read */
    *dataFile;              /* this used to be a central part of how the 
                               I/O code worked, but now it is simply the 
                               place to store the dataFile in the case of
                               keepNrrdDataFileOpen */
  unsigned int dataFileDim, /* The dimension of the data in each data file.
                               Together with dataFNArr->len, this determines
                               how many bytes should be in each data file */
    lineLen,                /* allocated size of line, including the
                               last character for \0 */
    charsPerLine,           /* when writing ASCII data in which we
                               intend only to write a huge long list
                               of numbers whose text formatting
                               implies nothing, then how many
                               characters do we limit ourselves to per
                               line */
    valsPerLine,            /* when writing ASCII data in which we DO
                               intend to sigify (or at least hint at)
                               something with the formatting, then
                               what is the max number of values to
                               write on a line */
    lineSkip,               /* if dataFile non-NULL, the number of
                               lines in dataFile that should be
                               skipped over (so as to bypass another
                               form of ASCII header preceeding raw
                               data) */
    headerStrlen,           /* ON WRITE, for NRRDs, if learningHeaderStrlen,
                               the learned strlen of the header so far */
    headerStrpos;           /* ON READ, for NRRDs, if headerStringRead is
                               non-NULL, the current location of reading
                               in the header */
  long int byteSkip;        /* exactly like lineSkip, but bytes
                               instead of lines.  First the lines are
                               skipped, then the bytes */
  int dataFNMin,            /* used with dataFNFormat to identify .. */
    dataFNMax,              /* .. all the multiple detached datafiles */
    dataFNStep,             /* how to step from max to min */
    dataFNIndex,            /* which of the data files are being read */
    pos,                    /* line[pos] is beginning of stuff which
                               still has yet to be parsed */
    endian,                 /* endian-ness of the data in file, for
                               those encoding/type combinations for
                               which it matters (from nrrdEndian) */
    seen[NRRD_FIELD_MAX+1], /* for error checking in header parsing */
    detachedHeader,         /* ON WRITE: request for file (NRRD format only)
                               to be split into distinct header and data. 
                               This only has an effect if detaching the header
                               is not already necessary, as it is with multiple
                               data files */
    bareText,               /* when writing a plain text file, is there any
                               effort made to record the nrrd struct
                               info in the text file */
    skipData,               /* if non-zero (all formats):
                               ON READ: don't allocate memory for, and don't
                               read in, the data portion of the file (but we
                               do verify that for nrrds, detached datafiles
                               can be opened).  Note: Does NOT imply 
                               keepNrrdDataFileOpen.  Warning: resulting
                               nrrd struct will have "data" pointer NULL.
                               ON WRITE: don't write data portion of file
                               (for nrrds, don't even try to open detached
                               datafiles).  Warning: can result in broken
                               noncomformant files.
                               (be careful with this) */
    keepNrrdDataFileOpen,   /* ON READ: when there is only a single dataFile,
                               don't close nio->dataFile when
                               you otherwise would, when reading the
                               nrrd format. Probably used in conjunction with
                               skipData.  (currently for "unu data")
                               ON WRITE: no semantics */
    zlibLevel,              /* zlib compression level (0-9, -1 for
                               default[6], 0 for no compression). */
    zlibStrategy,           /* zlib compression strategy, can be one
                               of the nrrdZlibStrategy enums, default is
                               nrrdZlibStrategyDefault. */
    bzip2BlockSize,         /* block size used for compression, 
                               roughly equivalent to better but slower
                               (1-9, -1 for default[9]). */
    learningHeaderStrlen;   /* ON WRITE, for nrrds, learn and save the total
                               length of header into headerStrlen. This is
                               used to allocate a buffer for header */
  void *oldData;            /* ON READ: if non-NULL, pointer to space that 
                               has already been allocated for oldDataSize */
  size_t oldDataSize;       /* ON READ: size of mem pointed to by oldData */

  /* The format and encoding.  These are initialized to nrrdFormatUnknown
     and nrrdEncodingUnknown, respectively. USE THESE VALUES for 
     any kind of initialization or flagging; DO NOT USE NULL */
  const NrrdFormat *format;
  const NrrdEncoding *encoding;
} NrrdIoState;


/******** defaults (nrrdDefault..) and state (nrrdState..) */
/* defaultsNrrd.c */
NRRDIO_EXPORT int nrrdDefaultWriteEncodingType;
NRRDIO_EXPORT int nrrdDefaultWriteBareText;
NRRDIO_EXPORT unsigned int nrrdDefaultWriteCharsPerLine;
NRRDIO_EXPORT unsigned int nrrdDefaultWriteValsPerLine;
NRRDIO_EXPORT int nrrdDefaultCenter;
NRRDIO_EXPORT double nrrdDefaultSpacing;
NRRDIO_EXPORT int nrrdStateVerboseIO;
NRRDIO_EXPORT int nrrdStateKeyValuePairsPropagate;
NRRDIO_EXPORT int nrrdStateAlwaysSetContent;
NRRDIO_EXPORT int nrrdStateDisableContent;
NRRDIO_EXPORT const char *nrrdStateUnknownContent;
NRRDIO_EXPORT int nrrdStateGrayscaleImage3D;
NRRDIO_EXPORT int nrrdStateKeyValueReturnInternalPointers;
NRRDIO_EXPORT int nrrdStateKindNoop;

/******** all the airEnums used through-out nrrd */
/* 
** the actual C enums are in nrrdEnums.h; experience has shown that it
** is not particularly useful to name those enums, since the shortest
** name is best used for the airEnums here
*/
/* enumsNrrd.c */
NRRDIO_EXPORT const airEnum *const nrrdFormatType;
NRRDIO_EXPORT const airEnum *const nrrdType;
NRRDIO_EXPORT const airEnum *const nrrdEncodingType;
NRRDIO_EXPORT const airEnum *const nrrdCenter;
NRRDIO_EXPORT const airEnum *const nrrdKind;
NRRDIO_EXPORT const airEnum *const nrrdField;
NRRDIO_EXPORT const airEnum *const nrrdSpace;
NRRDIO_EXPORT const airEnum *const nrrdSpacingStatus;

/******** arrays of things (poor-man's functions/predicates) */
/* arraysNrrd.c */
NRRDIO_EXPORT const char nrrdTypePrintfStr[][AIR_STRLEN_SMALL];
NRRDIO_EXPORT const size_t nrrdTypeSize[];
NRRDIO_EXPORT const double nrrdTypeMin[];
NRRDIO_EXPORT const double nrrdTypeMax[];
NRRDIO_EXPORT const int nrrdTypeIsIntegral[];
NRRDIO_EXPORT const int nrrdTypeIsUnsigned[];
NRRDIO_EXPORT const double nrrdTypeNumberOfValues[];

/******** pseudo-constructors, pseudo-destructors, and such */
/* methodsNrrd.c */
NRRDIO_EXPORT NrrdIoState *nrrdIoStateNew(void);
NRRDIO_EXPORT void nrrdIoStateInit(NrrdIoState *nio);
NRRDIO_EXPORT NrrdIoState *nrrdIoStateNix(NrrdIoState *nio);
NRRDIO_EXPORT void nrrdInit(Nrrd *nrrd);
NRRDIO_EXPORT Nrrd *nrrdNew(void);
NRRDIO_EXPORT Nrrd *nrrdNix(Nrrd *nrrd);
NRRDIO_EXPORT Nrrd *nrrdEmpty(Nrrd *nrrd);
NRRDIO_EXPORT Nrrd *nrrdNuke(Nrrd *nrrd);
NRRDIO_EXPORT int nrrdWrap_nva(Nrrd *nrrd, void *data, int type,
                             unsigned int dim, const size_t *size);
NRRDIO_EXPORT int nrrdWrap_va(Nrrd *nrrd, void *data, int type, unsigned int dim,
                            ... /* size_t sx, sy, .., axis(dim-1) size */);
NRRDIO_EXPORT void nrrdBasicInfoInit(Nrrd *nrrd, int excludeBitflag);
NRRDIO_EXPORT int nrrdBasicInfoCopy(Nrrd *nout, const Nrrd *nin,
                                  int excludeBitflag);
NRRDIO_EXPORT int nrrdCopy(Nrrd *nout, const Nrrd *nin);
NRRDIO_EXPORT int nrrdAlloc_nva(Nrrd *nrrd, int type, unsigned int dim,
                              const size_t *size);
NRRDIO_EXPORT int nrrdAlloc_va(Nrrd *nrrd, int type, unsigned int dim,
                             ... /* size_t sx, sy, .., axis(dim-1) size */);
NRRDIO_EXPORT int nrrdMaybeAlloc_nva(Nrrd *nrrd, int type, unsigned int dim,
                                   const size_t *size);
NRRDIO_EXPORT int nrrdMaybeAlloc_va(Nrrd *nrrd, int type, unsigned int dim,
                                  ... /* size_t sx, sy, .., ax(dim-1) size */);
NRRDIO_EXPORT int nrrdPPM(Nrrd *, size_t sx, size_t sy);
NRRDIO_EXPORT int nrrdPGM(Nrrd *, size_t sx, size_t sy);

/******** axis info related */
/* axis.c */
NRRDIO_EXPORT int nrrdKindIsDomain(int kind);
NRRDIO_EXPORT unsigned int nrrdKindSize(int kind);
NRRDIO_EXPORT int nrrdAxisInfoCopy(Nrrd *nout, const Nrrd *nin,
                                 const int *axmap, int excludeBitflag);
NRRDIO_EXPORT void nrrdAxisInfoSet_nva(Nrrd *nin, int axInfo, const void *info);
NRRDIO_EXPORT void nrrdAxisInfoSet_va(Nrrd *nin, int axInfo,
                                    ... /* const void* */);
NRRDIO_EXPORT void nrrdAxisInfoGet_nva(const Nrrd *nrrd, int axInfo, void *info);
NRRDIO_EXPORT void nrrdAxisInfoGet_va(const Nrrd *nrrd, int axInfo,
                                    ... /* ??? */);
NRRDIO_EXPORT double nrrdAxisInfoPos(const Nrrd *nrrd, unsigned int ax,
                                   double idx);
NRRDIO_EXPORT double nrrdAxisInfoIdx(const Nrrd *nrrd, unsigned int ax,
                                   double pos);
NRRDIO_EXPORT void nrrdAxisInfoPosRange(double *loP, double *hiP,
                                      const Nrrd *nrrd, unsigned int ax,
                                      double loIdx, double hiIdx);
NRRDIO_EXPORT void nrrdAxisInfoIdxRange(double *loP, double *hiP,
                                      const Nrrd *nrrd, unsigned int ax,
                                      double loPos, double hiPos);
NRRDIO_EXPORT void nrrdAxisInfoSpacingSet(Nrrd *nrrd, unsigned int ax);
NRRDIO_EXPORT void nrrdAxisInfoMinMaxSet(Nrrd *nrrd, unsigned int ax,
                                       int defCenter);
NRRDIO_EXPORT unsigned int nrrdDomainAxesGet(const Nrrd *nrrd,
                                           unsigned int axisIdx[NRRD_DIM_MAX]);
NRRDIO_EXPORT unsigned int nrrdRangeAxesGet(const Nrrd *nrrd,
                                          unsigned int axisIdx[NRRD_DIM_MAX]);
NRRDIO_EXPORT unsigned int nrrdSpatialAxesGet(const Nrrd *nrrd,
                                            unsigned int
                                            axisIdx[NRRD_DIM_MAX]);
NRRDIO_EXPORT unsigned int nrrdNonSpatialAxesGet(const Nrrd *nrrd,
                                               unsigned int
                                               axisIdx[NRRD_DIM_MAX]);
NRRDIO_EXPORT int nrrdSpacingCalculate(const Nrrd *nrrd, unsigned int ax,
                                     double *spacing,
                                     double vector[NRRD_SPACE_DIM_MAX]);
NRRDIO_EXPORT int nrrdOrientationReduce(Nrrd *nout, const Nrrd *nin,
                                      int setMinsFromOrigin);

/******** simple things */
/* simple.c */
NRRDIO_EXPORT const char *nrrdBiffKey;
NRRDIO_EXPORT unsigned int nrrdSpaceDimension(int space);
NRRDIO_EXPORT int nrrdSpaceSet(Nrrd *nrrd, int space);
NRRDIO_EXPORT int nrrdSpaceDimensionSet(Nrrd *nrrd, unsigned int spaceDim);
NRRDIO_EXPORT unsigned int nrrdSpaceOriginGet(const Nrrd *nrrd,
                                            double vector[NRRD_SPACE_DIM_MAX]);
NRRDIO_EXPORT int nrrdSpaceOriginSet(Nrrd *nrrd,
                                   double vector[NRRD_SPACE_DIM_MAX]);
NRRDIO_EXPORT int nrrdOriginCalculate(const Nrrd *nrrd,
                                    unsigned int *axisIdx,
                                    unsigned int axisIdxNum,
                                    int defaultCenter, double *origin);
NRRDIO_EXPORT int nrrdContentSet_va(Nrrd *nout, const char *func,
                                  const Nrrd *nin, const char *format,
                                  ... /* printf-style arg list */ );
NRRDIO_EXPORT void nrrdDescribe(FILE *file, const Nrrd *nrrd);
NRRDIO_EXPORT int nrrdCheck(const Nrrd *nrrd);
NRRDIO_EXPORT int _nrrdCheck(const Nrrd *nrrd, int checkData, int useBiff);
NRRDIO_EXPORT size_t nrrdElementSize(const Nrrd *nrrd);
NRRDIO_EXPORT size_t nrrdElementNumber(const Nrrd *nrrd);
NRRDIO_EXPORT int nrrdSanity(void);
NRRDIO_EXPORT int nrrdSameSize(const Nrrd *n1, const Nrrd *n2, int useBiff);
NRRDIO_EXPORT void nrrdSpaceVecCopy(double dst[NRRD_SPACE_DIM_MAX], 
                                  const double src[NRRD_SPACE_DIM_MAX]);
NRRDIO_EXPORT void nrrdSpaceVecScaleAdd2(double sum[NRRD_SPACE_DIM_MAX], 
                                       double sclA, 
                                       const double vecA[NRRD_SPACE_DIM_MAX],
                                       double sclB, 
                                       const double vecB[NRRD_SPACE_DIM_MAX]);
NRRDIO_EXPORT void nrrdSpaceVecScale(double out[NRRD_SPACE_DIM_MAX], 
                                   double scl, 
                                   const double vec[NRRD_SPACE_DIM_MAX]);
NRRDIO_EXPORT double nrrdSpaceVecNorm(int sdim,
                                    const double vec[NRRD_SPACE_DIM_MAX]);
NRRDIO_EXPORT void nrrdSpaceVecSetNaN(double vec[NRRD_SPACE_DIM_MAX]);

/******** comments related */
/* comment.c */
NRRDIO_EXPORT int nrrdCommentAdd(Nrrd *nrrd, const char *str);
NRRDIO_EXPORT void nrrdCommentClear(Nrrd *nrrd);
NRRDIO_EXPORT int nrrdCommentCopy(Nrrd *nout, const Nrrd *nin);

/******** key/value pairs */
/* keyvalue.c */
NRRDIO_EXPORT unsigned int nrrdKeyValueSize(const Nrrd *nrrd);
NRRDIO_EXPORT int nrrdKeyValueAdd(Nrrd *nrrd,
                                const char *key, const char *value);
NRRDIO_EXPORT char *nrrdKeyValueGet(const Nrrd *nrrd, const char *key);
NRRDIO_EXPORT void nrrdKeyValueIndex(const Nrrd *nrrd, 
                                   char **keyP, char **valueP,
                                   unsigned int ki);
NRRDIO_EXPORT int nrrdKeyValueErase(Nrrd *nrrd, const char *key);
NRRDIO_EXPORT void nrrdKeyValueClear(Nrrd *nrrd);
NRRDIO_EXPORT int nrrdKeyValueCopy(Nrrd *nout, const Nrrd *nin);

/******** endian related */
/* endianNrrd.c */
NRRDIO_EXPORT void nrrdSwapEndian(Nrrd *nrrd);

/******** getting information to and from files */
/* formatXXX.c */
NRRDIO_EXPORT const NrrdFormat *const nrrdFormatNRRD;
NRRDIO_EXPORT const NrrdFormat *const nrrdFormatPNM;
NRRDIO_EXPORT const NrrdFormat *const nrrdFormatPNG;
NRRDIO_EXPORT const NrrdFormat *const nrrdFormatVTK;
NRRDIO_EXPORT const NrrdFormat *const nrrdFormatText;
NRRDIO_EXPORT const NrrdFormat *const nrrdFormatEPS;
/* format.c */
NRRDIO_EXPORT const NrrdFormat *const nrrdFormatUnknown;
NRRDIO_EXPORT const NrrdFormat *
  const nrrdFormatArray[NRRD_FORMAT_TYPE_MAX+1];

/* encodingXXX.c */
NRRDIO_EXPORT const NrrdEncoding *const nrrdEncodingRaw;
NRRDIO_EXPORT const NrrdEncoding *const nrrdEncodingAscii;
NRRDIO_EXPORT const NrrdEncoding *const nrrdEncodingHex;
NRRDIO_EXPORT const NrrdEncoding *const nrrdEncodingGzip;
NRRDIO_EXPORT const NrrdEncoding *const nrrdEncodingBzip2;
/* encoding.c */
NRRDIO_EXPORT const NrrdEncoding *const nrrdEncodingUnknown;
NRRDIO_EXPORT const NrrdEncoding *
  const nrrdEncodingArray[NRRD_ENCODING_TYPE_MAX+1];

/* parseNrrd.c */
/* this needs the "FILE *file" first arg for the sole reason that
   parsing a "data file: " field which identifies a LIST must then
   read in all the data filenames from the same file */
NRRDIO_EXPORT int (*nrrdFieldInfoParse[NRRD_FIELD_MAX+1])(FILE *file, Nrrd *nrrd,
                                                        NrrdIoState *nio,
                                                        int useBiff);
NRRDIO_EXPORT unsigned int _nrrdDataFNNumber(NrrdIoState *nio);
NRRDIO_EXPORT int _nrrdContainsPercentThisAndMore(const char *str, char thss);
NRRDIO_EXPORT int _nrrdDataFNCheck(NrrdIoState *nio, Nrrd *nrrd, int useBiff);

/* read.c */
NRRDIO_EXPORT int _nrrdOneLine(unsigned int *lenP, NrrdIoState *nio, FILE *file);
NRRDIO_EXPORT int nrrdLineSkip(FILE *dataFile, NrrdIoState *nio);
NRRDIO_EXPORT int nrrdByteSkip(FILE *dataFile, Nrrd *nrrd, NrrdIoState *nio);
NRRDIO_EXPORT int nrrdLoad(Nrrd *nrrd, const char *filename, NrrdIoState *nio);
NRRDIO_EXPORT int nrrdLoadMulti(Nrrd *const *nin, unsigned int ninLen,
                              const char *fnameFormat,
                              unsigned int numStart, NrrdIoState *nio);
NRRDIO_EXPORT int nrrdRead(Nrrd *nrrd, FILE *file, NrrdIoState *nio);
NRRDIO_EXPORT int nrrdStringRead(Nrrd *nrrd, const char *string,
                               NrrdIoState *nio);

/* write.c */
NRRDIO_EXPORT int nrrdIoStateSet(NrrdIoState *nio, int parm, int value);
NRRDIO_EXPORT int nrrdIoStateEncodingSet(NrrdIoState *nio,
                                       const NrrdEncoding *encoding);
NRRDIO_EXPORT int nrrdIoStateFormatSet(NrrdIoState *nio, 
                                     const NrrdFormat *format);
NRRDIO_EXPORT int nrrdIoStateGet(NrrdIoState *nio, int parm);
NRRDIO_EXPORT const NrrdEncoding *nrrdIoStateEncodingGet(NrrdIoState *nio);
NRRDIO_EXPORT const NrrdFormat *nrrdIoStateFormatGet(NrrdIoState *nio);
NRRDIO_EXPORT int nrrdSave(const char *filename, const Nrrd *nrrd, 
                         NrrdIoState *nio);
NRRDIO_EXPORT int nrrdSaveMulti(const char *fnameFormat,
                              const Nrrd *const *nin, unsigned int ninLen,
                              unsigned int numStart, NrrdIoState *nio);
NRRDIO_EXPORT int nrrdWrite(FILE *file, const Nrrd *nrrd, 
                          NrrdIoState *nio);
NRRDIO_EXPORT int nrrdStringWrite(char **stringP, const Nrrd *nrrd,
                                NrrdIoState *nio);

/******** getting value into and out of an array of general type, and
   all other simplistic functionality pseudo-parameterized by type */
/* accessors.c */
NRRDIO_EXPORT double (*nrrdDLoad[NRRD_TYPE_MAX+1])(const void *v);
NRRDIO_EXPORT float  (*nrrdFLoad[NRRD_TYPE_MAX+1])(const void *v);
NRRDIO_EXPORT int    (*nrrdILoad[NRRD_TYPE_MAX+1])(const void *v);
NRRDIO_EXPORT unsigned int (*nrrdUILoad[NRRD_TYPE_MAX+1])(const void *v);
NRRDIO_EXPORT double (*nrrdDStore[NRRD_TYPE_MAX+1])(void *v, double d);
NRRDIO_EXPORT float  (*nrrdFStore[NRRD_TYPE_MAX+1])(void *v, float f);
NRRDIO_EXPORT int    (*nrrdIStore[NRRD_TYPE_MAX+1])(void *v, int j);
NRRDIO_EXPORT unsigned int (*nrrdUIStore[NRRD_TYPE_MAX+1])(void *v,
                                                         unsigned int j);
NRRDIO_EXPORT double (*nrrdDLookup[NRRD_TYPE_MAX+1])(const void *v, size_t I);
NRRDIO_EXPORT float  (*nrrdFLookup[NRRD_TYPE_MAX+1])(const void *v, size_t I);
NRRDIO_EXPORT int    (*nrrdILookup[NRRD_TYPE_MAX+1])(const void *v, size_t I);
NRRDIO_EXPORT unsigned int (*nrrdUILookup[NRRD_TYPE_MAX+1])(const void *v,
                                                          size_t I);
NRRDIO_EXPORT double (*nrrdDInsert[NRRD_TYPE_MAX+1])(void *v, size_t I,
                                                   double d);
NRRDIO_EXPORT float  (*nrrdFInsert[NRRD_TYPE_MAX+1])(void *v, size_t I,
                                                   float f);
NRRDIO_EXPORT int    (*nrrdIInsert[NRRD_TYPE_MAX+1])(void *v, size_t I,
                                                   int j);
NRRDIO_EXPORT unsigned int (*nrrdUIInsert[NRRD_TYPE_MAX+1])(void *v, size_t I,
                                                          unsigned int j);
NRRDIO_EXPORT int    (*nrrdSprint[NRRD_TYPE_MAX+1])(char *, const void *);


/******** permuting, shuffling, and all flavors of reshaping */
/* reorder.c */
NRRDIO_EXPORT int nrrdAxesInsert(Nrrd *nout, const Nrrd *nin, unsigned int ax);
NRRDIO_EXPORT int nrrdInvertPerm(unsigned int *invp, const unsigned int *perm,
                               unsigned int n);
NRRDIO_EXPORT int nrrdAxesPermute(Nrrd *nout, const Nrrd *nin,
                                const unsigned int *axes);
NRRDIO_EXPORT int nrrdShuffle(Nrrd *nout, const Nrrd *nin, unsigned int axis,
                            const size_t *perm);

/******** sampling, slicing, cropping */
/* subset.c */
NRRDIO_EXPORT int nrrdSlice(Nrrd *nout, const Nrrd *nin,
                          unsigned int axis, size_t pos);
NRRDIO_EXPORT int nrrdCrop(Nrrd *nout, const Nrrd *nin,
                         size_t *min, size_t *max);

#ifdef __cplusplus
}
#endif