File: netcdf_convenience.c

package info (click to toggle)
minc 2.1.10-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 8,160 kB
  • sloc: ansic: 82,507; sh: 10,666; yacc: 1,187; perl: 612; makefile: 586; lex: 319
file content (1944 lines) | stat: -rw-r--r-- 66,106 bytes parent folder | download
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
/* ----------------------------- MNI Header -----------------------------------
@NAME       : netcdf_convenience.c
@DESCRIPTION: File of convenience functions for netcdf routines. There
              is nothing MINC specific about these routines, they just
              provide convenient ways of getting netcdf data. The
              routines MI_convert_type, mivarget and mivarget1 break this
              rule by making use of the MINC variable attribute MIsigntype
              to determine the sign of an integer variable.
@METHOD     : Routines included in this file :
              public :
                 miexpand_file
                 miopen
                 micreate
                 miclose
                 miattget
                 miattget1
                 miattgetstr
                 miattputint
                 miattputdbl
                 miattputstr
                 mivarget
                 mivarget1
                 mivarput
                 mivarput1
                 miset_coords
                 mitranslate_coords
                 micopy_all_atts
                 micopy_var_def
                 micopy_var_values
                 micopy_all_var_defs
                 micopy_all_var_values
                 micreate_tempfile
                 miget_cfg_bool
                 miget_cfg_int
                 miget_cfg_str
              private :
                 execute_decompress_command
                 MI_vcopy_action
@CREATED    : July 27, 1992. (Peter Neelin, Montreal Neurological Institute)
@MODIFIED   : 
 * $Log: netcdf_convenience.c,v $
 * Revision 6.21  2008-01-17 02:33:02  rotor
 *  * removed all rcsids
 *  * removed a bunch of ^L's that somehow crept in
 *  * removed old (and outdated) BUGS file
 *
 * Revision 6.20  2008/01/12 19:08:14  stever
 * Add __attribute__ ((unused)) to all rcsid variables.
 *
 * Revision 6.19  2005/08/26 21:04:58  bert
 * Use #if rather than #ifdef with MINC2 symbol
 *
 * Revision 6.18  2005/05/20 16:49:51  bert
 * Avoid direct usage of H5Fis_hdf5(), replace with hdf_access() function
 *
 * Revision 6.17  2005/05/20 15:39:45  bert
 * Remove and/or conditionalize test code for memory-mapped files (see HDF5_MMAP_TEST)
 *
 * Revision 6.16  2004/12/14 23:53:46  bert
 * Get rid of compilation warnings
 *
 * Revision 6.15  2004/12/03 21:52:35  bert
 * Minor changes for Windows build
 *
 * Revision 6.14  2004/10/15 13:48:33  bert
 * Minor changes for Windows compatibility
 *
 * Revision 6.13  2004/06/04 18:16:25  bert
 * Create and add an 'ident' attribute when a file is created
 *
 * Revision 6.12  2004/04/30 18:57:39  bert
 * Explicitly cast return values of NULL to char * where appropriate to make IRIX MIPSpro compiler happy
 *
 * Revision 6.11  2004/04/27 15:50:41  bert
 * The full 2.0 treatment
 *
 * Revision 6.10  2004/03/23 21:16:05  bert
 * Conditionally include fcntl.h
 *
 * Revision 6.9  2003/12/01 22:45:58  stever
 * Check for fork(); use for file decompression if available
 *
 * Revision 6.8  2003/03/17 16:15:33  bert
 * Added micreate_tempfile() to resolve issues with tempfile naming and creation, especially to suppress those annoying GNU linker messages about tempnam() and tmpnam().
 *
 * Revision 6.7  2001/08/20 13:19:15  neelin
 * Added function miattget_with_sign to allow the caller to specify the sign
 * of the input attribute since this information is ambiguous. This is
 * necessary for the valid_range attribute which should have the same sign
 * as the image data. Modified miget_valid_range to make use of this function.
 *
 * Revision 6.6  2001/04/24 14:49:39  neelin
 * In execute_decompress_command, close all file handles in child after
 * fork to avoid problems with buffer flushing.
 *
 * Revision 6.5  2001/04/17 18:40:14  neelin
 * Modifications to work with NetCDF 3.x
 * In particular, changed NC_LONG to NC_INT (and corresponding longs to ints).
 * Changed NC_UNSPECIFIED to NC_NAT.
 * A few fixes to the configure script.
 *
 * Revision 6.4  2000/09/13 14:02:00  neelin
 * Added support for bzip files. (Modified patch from Steve Robbins)
 *
 * Revision 6.3  2000/02/02 18:43:29  neelin
 * Fixed bug in miexpand_file that would call fclose with a NULL file handle.
 * For newer versions of glibc, this would cause a seg fault.
 *
 * Revision 6.2  1999/10/19 14:45:11  neelin
 * Fixed Log subsitutions for CVS
 *
 * Revision 6.1  1997/10/06 12:54:08  neelin
 * Changed call to tmpnam to tempnam so that TMPDIR variable is checked when
 * creating temporary files.
 *
 * Revision 6.0  1997/09/12  13:24:54  neelin
 * Release of minc version 0.6
 *
 * Revision 5.0  1997/08/21  13:25:53  neelin
 * Release of minc version 0.5
 *
 * Revision 4.0  1997/05/07  20:07:52  neelin
 * Release of minc version 0.4
 *
 * Revision 3.3  1997/04/10  19:22:18  neelin
 * Removed redefinition of NULL and added pointer casts in appropriate places.
 *
 * Revision 3.2  1995/09/29  14:34:09  neelin
 * Modified micopy_all_atts to handle MI_ERROR being passed in as a varid.
 *
 * Revision 3.1  1995/06/12  20:43:52  neelin
 * Modified miexpand_file and miopen to try adding compression exetensions
 * to filenames if the first open fails.
 *
 * Revision 3.0  1995/05/15  19:33:12  neelin
 * Release of minc version 0.3
 *
 * Revision 2.6  1995/03/14  14:36:35  neelin
 * Got rid of broken pipe messages from miexpand_file by using exec
 * in system call.
 *
 * Revision 2.5  1995/02/08  19:14:44  neelin
 * More changes for irix 5 lint.
 *
 * Revision 2.4  1995/02/08  19:01:06  neelin
 * Moved private function declarations from minc_routines.h to appropriate file.
 *
 * Revision 2.3  1995/01/24  08:34:11  neelin
 * Added optional tempfile argument to miexpand_file.
 *
 * Revision 2.2  95/01/23  08:28:19  neelin
 * Changed name of midecompress_file to miexpand_file.
 * 
 * Revision 2.1  95/01/20  15:20:33  neelin
 * Added midecompress_file with ability to decompress only the header of a file.
 * 
 * Revision 2.0  94/09/28  10:38:13  neelin
 * Release of minc version 0.2
 * 
 * Revision 1.11  94/09/28  10:37:19  neelin
 * Pre-release
 * 
 * Revision 1.10  93/11/03  12:28:04  neelin
 * Added miopen, micreate, miclose routines.
 * miopen will uncompress files before opening them, if needed.
 * 
 * Revision 1.9  93/08/11  12:06:28  neelin
 * Added RCS logging in source.
 * 
@COPYRIGHT  :
              Copyright 1993 Peter Neelin, McConnell Brain Imaging Centre, 
              Montreal Neurological Institute, McGill University.
              Permission to use, copy, modify, and distribute this
              software and its documentation for any purpose and without
              fee is hereby granted, provided that the above copyright
              notice appear in all copies.  The author and McGill University
              make no representations about the suitability of this
              software for any purpose.  It is provided "as is" without
              express or implied warranty.
---------------------------------------------------------------------------- */

#include "minc_private.h"

#if HAVE_UNISTD_H
#include <unistd.h>
#endif

#if HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif

#if HAVE_SYS_STAT_H
#include <sys/stat.h>           /* For S_IREAD, S_IWRITE */
#endif

#include <ctype.h>

#if MINC2
#undef ncopen
#undef ncclose
#undef nccreate
#include "hdf_convenience.h"
#endif /* MINC2 defined */

#if HAVE_FCNTL_H
#include <fcntl.h>
#endif

/* Private functions */
PRIVATE int execute_decompress_command(char *command, char *infile, 
                                       char *outfile, int header_only);
PRIVATE int MI_vcopy_action(int ndims, long start[], long count[], 
                            long nvalues, void *var_buffer, void *caller_data);


#if MINC2
/* These flags are used to count miopen() calls which open either an HDF5
 * file or a NetCDF file.  The exact count is not important; the library
 * will automatically choose to create a HDF5 output file if only HDF5
 * files have been opened.
 */
static int mi_nc_files = 0;
static int mi_h5_files = 0;

#endif /* MINC2 defined */

/* ----------------------------- MNI Header -----------------------------------
@NAME       : execute_decompress_command
@INPUT      : command - command to execute
              infile - input file
              outfile - output file
              header_only - ignored
@OUTPUT     : (none)
@RETURNS    : status of decompress command (zero = success)
@DESCRIPTION: Routine to execute a decompression command on a minc file.
              The command must take a file name argument and must send 
              to standard output.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF routines, external decompression programs
@CREATED    : January 20, 1995 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
PRIVATE int execute_decompress_command(char *command, char *infile, 
                                       char *outfile, int header_only)
{
   char whole_command[1024];
   int status;


#if !(HAVE_WORKING_FORK && HAVE_SYSTEM && HAVE_POPEN)

   return 1;

#else      /* Unix */

   /* we now ignore header_only and always uncompress the whole
    * file as the previous "header only" hack that used to work
    * on MINC1 files doesn't work reliably with MINC2 */
   (void) sprintf(whole_command, "exec %s %s > %s 2> /dev/null", 
                  command, infile, outfile);
   status = system(whole_command);

   /* Return the status */
   return status;

#endif         /* ifndef unix else */
}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : miexpand_file
@INPUT      : path  - name of file to open.
              tempfile - user supplied name for temporary file. If 
                 NULL, then the routine generates its own name.
              header_only - TRUE if only the header needs to be expanded.
@OUTPUT     : created_tempfile - TRUE if a temporary file was created, FALSE
                 if no file was created (either because the original file
                 was not compressed or because of an error).
@RETURNS    : name of uncompressed file (either original or a temporary file)
              or NULL if an error occurred during decompression. The caller 
              must free the string. If a system error occurs on file open or 
              the decompression type is unknown, then the original file name
              is returned.
@DESCRIPTION: Routine to expand a compressed minc file. If the original file 
              is not compressed then its name is returned. If the name of a 
              temporary file is returned, then *created_tempfile is set to
              TRUE. If header_only is TRUE, then only the header part of the 
              file will be expanded - the data part may or may not be present.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF routines, external decompression programs
@CREATED    : January 20, 1995 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI char *miexpand_file(char *path, char *tempfile, int header_only,
                           int *created_tempfile)
{
   typedef enum 
      {BZIPPED, GZIPPED, COMPRESSED, PACKED, ZIPPED, UNKNOWN} Compress_type;
   int status, oldncopts, first_ncerr, iext;
   char *newfile, *extension, *compfile;
   FILE *fp;
   Compress_type compress_type;
   static struct {
      char *extension;
      Compress_type type;
   } compression_code_list[] = {
      {".bz", BZIPPED},
      {".bz2", BZIPPED},
      {".gz", GZIPPED},
      {".Z", COMPRESSED},
      {".z", PACKED},
      {".zip", ZIPPED}
   };
   static int complist_length = 
      sizeof(compression_code_list) / sizeof(compression_code_list[0]);
   static int max_compression_code_length = 5;

   MI_SAVE_ROUTINE_NAME("miexpand_file");

   /* We have not created a temporary file yet */
   *created_tempfile = FALSE;

#if MINC2
   if (hdf_access(path)) {
      newfile = strdup(path);
      MI_RETURN(newfile);
   }
#endif /* MINC2 defined */

   /* Try to open the file (close it again immediately) */
   oldncopts = ncopts; ncopts = 0;
   status = ncopen(path, NC_NOWRITE);
   if (status != MI_ERROR) {
      (void) ncclose(status);
   }
   ncopts = oldncopts;

   /* If there is no error then return the original file name */
   if (status != MI_ERROR) {
      newfile = strdup(path);
      MI_RETURN(newfile);
   }

   /* Save the error code */
   first_ncerr = ncerr;

   /* Check for the system error that doesn't show */
   if (first_ncerr == NC_NOERR) {
      fp = fopen(path, "r");
      if (fp == NULL) {
         first_ncerr = NC_SYSERR;
      }
      else {
         (void) fclose(fp);
      }
   }

   /* Get the file extension */
   extension = strrchr(path, '.');
   if (extension == NULL) {
      extension = &path[strlen(path)];
   }

   /* Determine the type */
   compress_type = UNKNOWN;
   for (iext = 0; iext < complist_length; iext++) {
      if (STRINGS_EQUAL(extension, compression_code_list[iext].extension)) {
         compress_type = compression_code_list[iext].type;
         break;
      }
   }

   /* If there was a system error and it's not already a compressed file, 
      then maybe there exists a compressed version (with appropriate 
      extension). Loop through the list of extensions. */
   compfile = NULL;
   if ((first_ncerr == NC_SYSERR) && (compress_type == UNKNOWN)) {
      compfile = MALLOC(strlen(path) + max_compression_code_length + 2, char);
      for (iext=0; iext < complist_length; iext++) {
         (void) strcat(strcpy(compfile, path), 
                       compression_code_list[iext].extension);
         fp = fopen(compfile, "r");
         if (fp != NULL) {
            (void) fclose(fp);
            break;
         }
      }
      if (iext >= complist_length) {
         FREE(compfile);
         newfile = strdup(path);
         MI_RETURN(newfile);
      }
      compress_type = compression_code_list[iext].type;
      path = compfile;
   }

   /* If there was a system error or we don't know what to do 
      with the file, then return the original file name */
   else if ((first_ncerr == NC_SYSERR) || (compress_type == UNKNOWN)) {
      newfile = strdup(path);
      MI_RETURN(newfile);
   }

   /* Create a temporary file name */
   if (tempfile == NULL) {
      newfile = micreate_tempfile();
   }
   else {
      newfile = strdup(tempfile);
   }
   *created_tempfile = TRUE;

   /* Try to use gunzip */
   if ((compress_type == GZIPPED) || 
       (compress_type == COMPRESSED) ||
       (compress_type == PACKED) ||
       (compress_type == ZIPPED)) {
      status = execute_decompress_command("gunzip -c", path, newfile, 
                                          header_only);
   }
   else if (compress_type == BZIPPED) {
      status = execute_decompress_command("bunzip2 -c", path, newfile, 
                                          header_only);
   }

   /* If that doesn't work, try something else */
   if (status != 0) {
      if (compress_type == COMPRESSED) {
         status = execute_decompress_command("zcat", path, newfile, 
                                             header_only);
      }
      else if (compress_type == PACKED) {
         status = execute_decompress_command("pcat", path, newfile, 
                                             header_only);
      }
   }

   /* Free the compressed file name, if necessary */
   if (compfile != NULL) {
      FREE(compfile);
      path = NULL;
   }

   /* Check for failure to uncompress the file */
   if (status != 0) {
      (void) remove(newfile);
      *created_tempfile = FALSE;
      FREE(newfile);
      milog_message(MI_MSG_UNCMPFAIL);
      MI_RETURN((char *)NULL);  /* Explicit cast needed for MIPSpro cc */
   }

   /* Return the new file name */
   MI_RETURN(newfile);

}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : miopen
@INPUT      : path  - name of file to open
              mode  - NC_WRITE or NC_NOWRITE to indicate whether file should
                 be opened for write or read-only.
@OUTPUT     : (nothing)
@RETURNS    : file id or MI_ERROR (=-1) when an error occurs
@DESCRIPTION: Similar to routine ncopen, but will de-compress (temporarily)
              read-only files as needed.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF routines
@CREATED    : November 2, 1993 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI int miopen(char *path, int mode)
{
   int status, oldncopts, created_tempfile;
   char *tempfile;
#if MINC2
   int hmode;
#endif /* MINC2 defined */

   MI_SAVE_ROUTINE_NAME("miopen");

   /* Try to open the file */
   oldncopts = ncopts; ncopts = 0;
   status = ncopen(path, mode);
   ncopts = oldncopts;

#if MINC2
   if (status != MI_ERROR) {
     mi_nc_files++;             /* Count open netcdf files */
     MI_RETURN(status);
   }

   if (mode & NC_WRITE) {
     hmode = H5F_ACC_RDWR;
   } 
   else {
     hmode = H5F_ACC_RDONLY;
   }

#if HDF5_MMAP_TEST
   hmode = (mode & 0x8000);     /* !!!! Pass along magic memory-mapping bit */
#endif /* HDF5_MMAP_TEST */

   status = hdf_open(path, hmode);

   /* If there is no error then return */
   if (status >= 0) {
      mi_h5_files++;           /* Count open HDF5 files */
      MI_RETURN(status);
   }
#endif /* MINC2 defined */

   /* If the user wants to modify the file then return an error, since
    * we don't allow write access to compressed files.
    */
   if (mode & NC_WRITE) {
       milog_message(MI_MSG_NOWRITECMP);
       MI_RETURN(MI_ERROR);
   }

   /* Try to expand the file */
   tempfile = miexpand_file(path, NULL, FALSE, &created_tempfile);

   /* Check for error */
   if (tempfile == NULL) {
      MI_RETURN(MI_ERROR);
   }

   /* Open the temporary file and unlink it so that it will disappear when
      the file is closed */
   oldncopts = ncopts;
   ncopts = 0;
   status = ncopen(tempfile, mode);
   ncopts = oldncopts;

#if MINC2
   if (status == MI_ERROR) {
     status = hdf_open(tempfile, hmode);
     if (status >= 0) {
         mi_h5_files++;
     }
   }
   else {
       mi_nc_files++;
   }
#endif /* MINC2 defined */

   if (created_tempfile) {
      (void) remove(tempfile);
   }
   if (status < 0) {
       milog_message(MI_MSG_OPENFILE, tempfile);
   }
   MI_RETURN(status);

}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : micreate
@INPUT      : path  - name of file to create
              cmode - NC_CLOBBER or NC_NOCLOBBER
@OUTPUT     : (nothing)
@RETURNS    : file id or MI_ERROR (=-1) when an error occurs
@DESCRIPTION: A wrapper for routine nccreate, allowing future enhancements.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF routines
@CREATED    : November 2, 1993 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
#if MINC2
MNCAPI int micreatex(char *path, int cmode, struct mi2opts *opts_ptr)
{
    int fd;

    MI_SAVE_ROUTINE_NAME("micreate");

    if ((cmode & MI2_CREATE_V1) != 0) {
        fd = nccreate(path, cmode);
    }
    else if (miget_cfg_bool(MICFG_FORCE_V2) || (cmode & MI2_CREATE_V2) != 0) {
	fd = hdf_create(path, cmode, opts_ptr);
    }
    else {
        if (mi_nc_files == 0 && mi_h5_files != 0) {
            /* Create an HDF5 file. */
            fd = hdf_create(path, cmode, opts_ptr);
        }
        else {
            /* Create a NetCDF file. */
            fd = nccreate(path, cmode);
        }
    }
    if (fd < 0) {
	milog_message(MI_MSG_CREATEFILE, path);
    }
    else {
        char ident[128];

        micreate_ident(ident, sizeof(ident));
        miattputstr(fd, NC_GLOBAL, "ident", ident);
        miattputstr(fd, NC_GLOBAL, "minc_version", VERSION);
    }
    MI_RETURN(fd);
}

MNCAPI int micreate(char *path, int cmode)
{
    MI_SAVE_ROUTINE_NAME("micreate");

    MI_RETURN(micreatex(path, cmode, NULL));
}

#else

MNCAPI int micreate(char *path, int cmode)
{
    int fd;

    MI_SAVE_ROUTINE_NAME("micreate");

    /* Create a NetCDF file. */
    fd = nccreate(path, cmode);
    if (fd < 0) {
	milog_message(MI_MSG_CREATEFILE, path);
    }
    MI_RETURN(fd);
}
#endif /* MINC2 not defined */

/* ----------------------------- MNI Header -----------------------------------
@NAME       : miclose
@INPUT      : cdfid - id of file to close
@OUTPUT     : (nothing)
@RETURNS    : MI_ERROR (=-1) when an error occurs
@DESCRIPTION: A wrapper for routine ncclose, allowing future enhancements.
              read-only files as needed.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF routines
@CREATED    : November 2, 1993 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI int miclose(int cdfid)
{
   int status;

   MI_SAVE_ROUTINE_NAME("miclose");

#if MINC2
   if (MI2_ISH5OBJ(cdfid)) {
       status = hdf_close(cdfid);
   }
   else {
       status = ncclose(cdfid);
   }
#else
   status = ncclose(cdfid);
#endif /* MINC2 not defined */

   if (status < 0) {
       milog_message(MI_MSG_CLOSEFILE);
   }
   MI_RETURN(status);
}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : miattget
@INPUT      : cdfid      - cdf file id
              varid      - variable id
              name       - name of attribute
              datatype   - type that calling routine wants (one of the valid
                 netcdf data types, excluding NC_CHAR)
              max_length - maximum length to return (number of elements)
@OUTPUT     : value      - value of attribute
              att_length - actual length of attribute (number of elements)
                 If NULL, then no value is returned.
@RETURNS    : MI_ERROR (=-1) when an error occurs
@DESCRIPTION: Similar to routine ncattget, but the calling routine specifies
              the form in which data should be returned (datatype), as well
              as the maximum number of elements to get. The datatype can
              only be a numeric type. If the attribute in the file is of type 
              NC_CHAR, then an error is returned. The actual length of the
              vector is returned in att_length.
@METHOD     : 
@GLOBALS    : 
@CALLS      : miattget_with_sign
@CREATED    : July 27, 1992 (Peter Neelin)
@MODIFIED   : August 20, 2001 (P.N.)
                 - changed to call miattget_with_sign
---------------------------------------------------------------------------- */
MNCAPI int miattget(int cdfid, int varid, char *name, nc_type datatype,
                    int max_length, void *value, int *att_length)
{
    int status;

    MI_SAVE_ROUTINE_NAME("miattget");

    status = miattget_with_sign(cdfid, varid, name, 
				NULL, datatype, NULL, 
				max_length, value, att_length);

    MI_RETURN(status);
}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : miattget_with_sign
@INPUT      : cdfid      - cdf file id
              varid      - variable id
              name       - name of attribute
              insign     - sign of input attribute. If NULL, then use default.
              datatype   - type that calling routine wants (one of the valid
                 netcdf data types, excluding NC_CHAR)
              outsign    - sign of type for calling routine. If NULL, then use
                 default
              max_length - maximum length to return (number of elements)
@OUTPUT     : value      - value of attribute
              att_length - actual length of attribute (number of elements)
                 If NULL, then no value is returned.
@RETURNS    : MI_ERROR (=-1) when an error occurs
@DESCRIPTION: Similar to routine miattget, but the calling routine specifies
              the sign of the attribute in the file (which may be ambiguous)
              as well as the sign of the return type. Sign strings can be
              MI_SIGNED, MI_UNSIGNED, an empty string or NULL - the latter
              two mean use the default for the type.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF routines and MI_convert_type
@CREATED    : August 20, 2001 (Peter Neelin)
                 - slightly modified version of old miattget
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI int miattget_with_sign(int cdfid, int varid, char *name, 
                              char *insign, nc_type datatype, char *outsign,
                              int max_length, void *value, int *att_length)
{
   nc_type att_type;          /* Type of attribute */
   int actual_length;         /* Actual length of attribute */
   void *att_value;           /* Pointer to attribute value */
   int status;                /* Status of nc routine */
   int att_sign, data_sign;   /* Integer sign values */

   MI_SAVE_ROUTINE_NAME("miattget_with_sign");

   /* Inquire about the attribute */
   status = ncattinq(cdfid, varid, name, &att_type, &actual_length);
   if (status < 0) {
       milog_message(MI_MSG_FINDATTR, name);
       MI_RETURN(MI_ERROR);
   }

   /* Save the actual length of the attribute */
   if (att_length != NULL)
      *att_length = actual_length;

   /* Check that the attribute type is numeric */
   if ((datatype==NC_CHAR) || (att_type==NC_CHAR)) {
      milog_message(MI_MSG_ATTRNOTNUM, name);
      MI_RETURN(MI_ERROR);
   }

   /* Check to see if the type requested is the same as the attribute type
      and that the length is less than or equal to max_length. If it is, just 
      get the value. */
   if ((datatype == att_type) && (actual_length <= max_length)) {
       status = ncattget(cdfid, varid, name, value);
       if (status < 0) {
           milog_message(MI_MSG_READATTR, name);
       }
       MI_RETURN(status);
   }

   /* Otherwise, get space for the attribute */
   if ((att_value = MALLOC(actual_length * nctypelen(att_type), char))
                      == NULL) {
       milog_message(MI_MSG_NOMEMATTR, name);
       MI_RETURN(MI_ERROR);
   }

   /* Get the attribute */
   if (ncattget(cdfid, varid, name, att_value)==MI_ERROR) {
      FREE(att_value);
      milog_message(MI_MSG_READATTR, name);
      MI_RETURN(MI_ERROR);
   }

   /* Get the signs */
   att_sign = MI_get_sign_from_string(att_type, insign);
   data_sign = MI_get_sign_from_string(datatype, outsign);

   /* Get the values.
      Call MI_convert_type with :
         MI_convert_type(number_of_values,
                         intype,  insign,  invalues,
                         outtype, outsign, outvalues,
                         icvp) */
   status=MI_convert_type(MIN(max_length, actual_length), 
                          att_type, att_sign, att_value,
                          datatype, data_sign, value,
                          NULL);
   FREE(att_value);
   if (status < 0) {
       milog_message(MI_MSG_CONVATTR, name);
   }
   MI_RETURN(status);
}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : miattget1
@INPUT      : cdfid      - cdf file id
              varid      - variable id
              name       - name of attribute
              datatype   - type that calling routine wants (one of the valid
                 netcdf data types, excluding NC_CHAR)
@OUTPUT     : value      - value of attribute
@RETURNS    : MI_ERROR (=-1) when an error occurs
@DESCRIPTION: Similar to routine miattget, but the its gets only one value
              of an attribute. If the attribute is longer, then an error
              occurs.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF routines and miattget
@CREATED    : July 27, 1992 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI int miattget1(int cdfid, int varid, char *name, nc_type datatype,
                    void *value)
{
   int att_length;      /* Actual length of the attribute */
   int status;

   MI_SAVE_ROUTINE_NAME("miattget1");

   /* Get the attribute value and its actual length */
   status = miattget(cdfid, varid, name, datatype, 1, value, &att_length);
   if (status < 0) {
       milog_message(MI_MSG_FINDATTR, name);
       MI_RETURN(MI_ERROR);
   }

   /* Check that the length is 1 */
   if (att_length != 1) {
      milog_message(MI_MSG_ATTRNOTSCALAR, name);
      MI_RETURN(MI_ERROR);
   }

   MI_RETURN(MI_NOERROR);

}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : miattgetstr
@INPUT      : cdfid    - cdf file id
              varid    - variable id
              name     - name of attribute
              maxlen   - maximum length of string to be copied
@OUTPUT     : value    - string returned
@RETURNS    : pointer to string value or NULL if an error occurred.
@DESCRIPTION: Gets a character attribute, copying up to maxlen characters
              into value and adding a terminating '\0' if necessary. A
              pointer to the string is returned to facilitate use.
              If the attribute is non-character, a NULL pointer is returned.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF routines.
@CREATED    : July 28, 1992 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI char *miattgetstr(int cdfid, int varid, char *name, 
                         int maxlen, char *value)
{
   nc_type att_type;          /* Type of attribute */
   int att_length;            /* Length of attribute */
   char *att_value;           /* Pointer to attribute value */

   MI_SAVE_ROUTINE_NAME("miattgetstr");

   /* Inquire about the attribute */
   if (ncattinq(cdfid, varid, name, &att_type, &att_length)==MI_ERROR) {
       milog_message(MI_MSG_FINDATTR, name);
       MI_RETURN((char *)NULL); /* Explicit cast for MIPSpro cc */
   }

   /* Check that the attribute type is character */
   if (att_type!=NC_CHAR) {
       milog_message(MI_MSG_ATTRNOTSTR, name);
       MI_RETURN((char *)NULL); /* Explicit cast for MIPSpro cc */
   }

   /* Check to see if the attribute length is less than maxlen. 
      If it is, just get the value. */
   if (att_length <= maxlen) {
      if (ncattget(cdfid, varid, name, value) == MI_ERROR) {
	  milog_message(MI_MSG_READATTR, name);
	  MI_RETURN((char *)NULL); /* Explicit cast for MIPSpro cc */
      }
      /* Check the last character for a '\0' */
      if (value[att_length-1] != '\0') {
         if (att_length==maxlen)
            value[att_length-1] = '\0';
         else
            value[att_length]   = '\0';
      }
      MI_RETURN(value);
   }

   /* Otherwise, get space for the attribute */
   if ((att_value = MALLOC(att_length * nctypelen(att_type), char)) ==NULL) {
       milog_message(MI_MSG_NOMEMATTR, name);
       MI_RETURN((char *)NULL); /* Explicit cast for MIPSpro cc */
   }

   /* Get the attribute */
   if (ncattget(cdfid, varid, name, att_value)==MI_ERROR) {
      FREE(att_value);
      milog_message(MI_MSG_READATTR, name);
      MI_RETURN((char *)NULL);
   }

   /* Copy the attribute */
   (void) strncpy(value, att_value, (size_t) maxlen-1);
   value[maxlen-1] = '\0';

   /* Free the string */
   FREE(att_value);

   /* Return a pointer to the string */
   MI_RETURN(value);

}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : miattputint
@INPUT      : cdfid    - cdf file id
              varid    - variable id
              name     - name of attribute
              value    - integer value for attribute
@OUTPUT     : (none)
@RETURNS    : MI_ERROR (=-1) if an error occurs
@DESCRIPTION: Convenience routine for calling ncattput with integers.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF routines.
@CREATED    : November 25, 1992 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI int miattputint(int cdfid, int varid, char *name, int value)
{
    int lvalue;
    int status;

    MI_SAVE_ROUTINE_NAME("miattputint");

    lvalue = value;
    status = ncattput(cdfid, varid, name, NC_INT, 1, (void *) &lvalue);
    if (status < 0) {
	milog_message(MI_MSG_WRITEATTR, name);
    }
    MI_RETURN(status);
}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : miattputdbl
@INPUT      : cdfid    - cdf file id
              varid    - variable id
              name     - name of attribute
              value    - double value for attribute
@OUTPUT     : (none)
@RETURNS    : MI_ERROR (=-1) if an error occurs
@DESCRIPTION: Convenience routine for calling ncattput with doubles.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF routines.
@CREATED    : August 5, 1992 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI int miattputdbl(int cdfid, int varid, char *name, double value)
{
    int status;
    MI_SAVE_ROUTINE_NAME("miattputdbl");
    status = ncattput(cdfid, varid, name, NC_DOUBLE, 1, (void *) &value);
    if (status < 0) {
	milog_message(MI_MSG_WRITEATTR, name);
    }
    MI_RETURN(status);
}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : miattputstr
@INPUT      : cdfid    - cdf file id
              varid    - variable id
              name     - name of attribute
              value    - string value for attribute
@OUTPUT     : (none)
@RETURNS    : MI_ERROR (=-1) if an error occurs
@DESCRIPTION: Convenience routine for calling ncattput with character strings.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF routines.
@CREATED    : July 28, 1992 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI int miattputstr(int cdfid, int varid, char *name, char *value)
{
    int status;
    MI_SAVE_ROUTINE_NAME("miattputstr");

    status = ncattput(cdfid, varid, name, NC_CHAR, 
                       strlen(value) + 1, (void *) value);
    if (status < 0) {
	milog_message(MI_MSG_WRITEATTR, name);
    }
    MI_RETURN(status);
}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : mivarget
@INPUT      : cdfid    - cdf file id
              varid    - variable id
              start    - vector of coordinates of corner of hyperslab
              count    - vector of edge lengths of hyperslab
              datatype - type that calling routine wants (one of the valid
                 netcdf data types, excluding NC_CHAR)
              sign     - sign that calling routine wants (one of
                 EMPTY_STRING (or NULL) = use default sign
                 MI_SIGNED              = signed values
                 MI_UNSIGNED            = unsigned values
@OUTPUT     : values   - value of variable
@RETURNS    : MI_ERROR (=-1) when an error occurs
@DESCRIPTION: Similar to routine ncvarget, but the calling routine specifies
              the form in which data should be returned (datatype), as well
              as the sign. The datatype can only be a numeric type. If the 
              variable in the file is of type NC_CHAR, then an error is 
              returned.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF and MINC routines
@CREATED    : July 29, 1992 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI int mivarget(int cdfid, int varid, long start[], long count[],
                    nc_type datatype, char *sign, void *values)
{
    int status;
    MI_SAVE_ROUTINE_NAME("mivarget");

    status = MI_varaccess(MI_PRIV_GET, cdfid, varid, start, count,
			  datatype, MI_get_sign_from_string(datatype, sign),
			  values, NULL, NULL);
    if (status < 0) {
	milog_message(MI_MSG_READVAR, varid);
    }
    MI_RETURN(status);
}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : mivarget1
@INPUT      : cdfid    - cdf file id
              varid    - variable id
              mindex   - vector of coordinates of value to get
              datatype - type that calling routine wants (one of the valid
                 netcdf data types, excluding NC_CHAR)
              sign     - sign that calling routine wants (one of
                 EMPTY_STRING (or NULL) = use default sign
                 MI_SIGNED              = signed values
                 MI_UNSIGNED            = unsigned values
@OUTPUT     : value    - value of variable
@RETURNS    : MI_ERROR (=-1) when an error occurs
@DESCRIPTION: Similar to routine ncvarget1, but the calling routine specifies
              the form in which data should be returned (datatype), as well
              as the sign. The datatype can only be a numeric type. If the 
              variable in the file is of type NC_CHAR, then an error is 
              returned.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF and MINC routines
@CREATED    : July 29, 1992 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI int mivarget1(int cdfid, int varid, long mindex[],
                     nc_type datatype, char *sign, void *value)
{
    int status;
    long count[MAX_VAR_DIMS];

    MI_SAVE_ROUTINE_NAME("mivarget1");
    
    status = MI_varaccess(MI_PRIV_GET, cdfid, varid, mindex, 
			  miset_coords(MAX_VAR_DIMS, 1L, count),
			  datatype, MI_get_sign_from_string(datatype, sign),
			  value, NULL, NULL);
    if (status < 0) {
	milog_message(MI_MSG_READVAR, varid);
    }
    MI_RETURN(status);
}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : mivarput
@INPUT      : cdfid    - cdf file id
              varid    - variable id
              start    - vector of coordinates of corner of hyperslab
              count    - vector of edge lengths of hyperslab
              datatype - type that calling routine is passing (one of the valid
                 netcdf data types, excluding NC_CHAR)
              sign     - sign that calling routine is passing (one of
                 EMPTY_STRING (or NULL) = use default sign
                 MI_SIGNED              = signed values
                 MI_UNSIGNED            = unsigned values
              values   - value of variable
@OUTPUT     : (none)
@RETURNS    : MI_ERROR (=-1) when an error occurs
@DESCRIPTION: Similar to routine ncvarput, but the calling routine specifies
              the form in which data is passes (datatype), as well
              as the sign. The datatype can only be a numeric type. If the 
              variable in the file is of type NC_CHAR, then an error is 
              returned.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF and MINC routines
@CREATED    : July 29, 1992 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI int mivarput(int cdfid, int varid, long start[], long count[],
                    nc_type datatype, char *sign, void *values)
{
    int status;
    MI_SAVE_ROUTINE_NAME("mivarput");

    status = MI_varaccess(MI_PRIV_PUT, cdfid, varid, start, count,
			  datatype, MI_get_sign_from_string(datatype, sign),
			  values, NULL, NULL);
    if (status < 0) {
	milog_message(MI_MSG_WRITEVAR, varid);
    }
    MI_RETURN(status);
}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : mivarput1
@INPUT      : cdfid    - cdf file id
              varid    - variable id
              mindex   - vector of coordinates of value to put
              datatype - type that calling routine is passing (one of the valid
                 netcdf data types, excluding NC_CHAR)
              sign     - sign that calling routine is passing (one of
                 EMPTY_STRING (or NULL) = use default sign
                 MI_SIGNED              = signed values
                 MI_UNSIGNED            = unsigned values
@OUTPUT     : value    - value of variable
@RETURNS    : MI_ERROR (=-1) when an error occurs
@DESCRIPTION: Similar to routine ncvarput1, but the calling routine specifies
              the form in which data is passed (datatype), as well
              as the sign. The datatype can only be a numeric type. If the 
              variable in the file is of type NC_CHAR, then an error is 
              returned.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF and MINC routines
@CREATED    : July 29, 1992 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI int mivarput1(int cdfid, int varid, long mindex[],
                     nc_type datatype, char *sign, void *value)
{
    int status;
    long count[MAX_VAR_DIMS];

    MI_SAVE_ROUTINE_NAME("mivarput1");

    status = MI_varaccess(MI_PRIV_PUT, cdfid, varid, mindex, 
			  miset_coords(MAX_VAR_DIMS, 1L, count),
			  datatype, MI_get_sign_from_string(datatype, sign),
			  value, NULL, NULL);
    if (status < 0) {
	milog_message(MI_MSG_WRITEVAR, varid);
    }
    MI_RETURN(status);
}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : miset_coords
@INPUT      : nvals  - number of values in coordinate vector to set
              value  - value to which coordinates should be set
@OUTPUT     : coords - coordinate vector
@RETURNS    : pointer to coords.
@DESCRIPTION: Sets nvals entries of the vector coords to value.
@METHOD     : 
@GLOBALS    : 
@CALLS      : 
@CREATED    : July 29, 1992 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI long *miset_coords(int nvals, long value, long coords[])
{
   int i;

   MI_SAVE_ROUTINE_NAME("miset_coords");

   for (i=0; i<nvals; i++) {
      coords[i] = value;
   }
   MI_RETURN(coords);
}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : mitranslate_coords
@INPUT      : cdfid     - cdf file id
              invar     - variable subscripted by incoords
              incoords  - coordinates to be copied
              outvar    - variable subscripted by outcoords
@OUTPUT     : outcoords - new coordinates
@RETURNS    : pointer to outcoords or NULL if an error occurred.
@DESCRIPTION: Translates the coordinate vector used for subscripting one
              variable (invar) to a coordinate vector that can be used to
              subscript another (outvar). This is useful when two variables
              have similar dimensions, but not necessarily the same order of
              dimensions. If invar has a dimension that is not in outvar, then
              the corresponding coordinate is ignored. If outvar has a
              dimension that is not in invar, then the corresponding coordinate
              is not modified.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF routines.
@CREATED    : July 29, 1992 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI long *mitranslate_coords(int cdfid, 
                                int invar,  long incoords[],
                                int outvar, long outcoords[])
{
   int in_ndims, in_dim[MAX_VAR_DIMS], out_ndims, out_dim[MAX_VAR_DIMS];
   int i,j;

   MI_SAVE_ROUTINE_NAME("mitranslate_coords");

   /* Inquire about the dimensions of the two variables */
   if ( (ncvarinq(cdfid, invar,  NULL, NULL, &in_ndims,  in_dim,  NULL)
                    == MI_ERROR) ||
        (ncvarinq(cdfid, outvar, NULL, NULL, &out_ndims, out_dim, NULL)
                    == MI_ERROR)) {
      milog_message(MI_MSG_FINDVAR, invar);
      MI_RETURN((long *) NULL);
   }

   /* Loop through out_dim, looking for dimensions in in_dim */
   for (i=0; i<out_ndims; i++) {
      for (j=0; j<in_ndims; j++) {
         if (out_dim[i]==in_dim[j]) break;
      }
      /* If we found the dimension, then copy it */
      if (j<in_ndims) {
         outcoords[i] = incoords[j];
      }
   }

   MI_RETURN(outcoords);
}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : micopy_all_atts
@INPUT      : incdfid  - input cdf file id
              invarid  - input variable id
              outcdfid - output cdf file id
              outvarid - output variable id
@OUTPUT     : (none)
@RETURNS    : MI_ERROR (=-1) if an error occurs
@DESCRIPTION: Copies all of the attributes of one variable to another.
              Attributes that already exist in outvarid are not copied.
              outcdfid must be in define mode. This routine will only copy
              global attributes to global attributes or variable attributes
              to variable attributes, but not variable to global or global
              to variable. This means that one can safely use
                 micopy_all_atts(inmincid, ncvarid(inmincid, varname),...)
              if outvarid is known to exist (the problem arises because
              MI_ERROR == NC_GLOBAL). No error is flagged if the a bad
              combination is given.

@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF routines
@CREATED    : 
@MODIFIED   : 
---------------------------------------------------------------------------- */

MNCAPI int micopy_all_atts(int incdfid, int invarid, 
                           int outcdfid, int outvarid)
{
   int num_atts;             /* Number of attributes */
   char name[MAX_NC_NAME];   /* Name of attribute */
   int oldncopts;            /* Old value of ncopts */
   int status;               /* Status returned by function call */
   int i;

   MI_SAVE_ROUTINE_NAME("micopy_all_atts");


   /* Only allow copying of global attributes to global attributes or
      variable attributes to variable attributes - this makes
      micopy_all_atts(inmincid, ncvarid(inmincid, varname),...) safer, since
      MI_ERROR == NC_GLOBAL */
   if (((invarid == NC_GLOBAL) || (outvarid == NC_GLOBAL)) &&
       (invarid != outvarid)) {
      MI_RETURN(MI_NOERROR);
   }

   /* Inquire about the number of input variable attributes */
   if (invarid != NC_GLOBAL) {
       status = ncvarinq(incdfid, invarid, 
			 NULL, NULL, NULL, NULL, &num_atts);
   }
   else {
       status = ncinquire(incdfid, NULL, NULL, &num_atts, NULL);
   }
   if (status < 0) {
       milog_message(MI_MSG_ATTRCOUNT);
       MI_RETURN(MI_ERROR);
   }

   /* Loop through input attributes */
   for (i=0; i<num_atts; i++){
      
      /* Get the attribute name */
       status = ncattname(incdfid, invarid, i, name);
       if (status < 0) {
	   milog_message(MI_MSG_ATTRNAME);
	   MI_RETURN(MI_ERROR);
       }

      /* Check to see if it is in the output file. We must set and reset
         ncopts to avoid surprises to the calling program. (This is no
	 longer needed with new MI_SAVE_ROUTINE_NAME macro). */
      oldncopts=ncopts; ncopts=0;
      status=ncattinq(outcdfid, outvarid, name, NULL, NULL);
      ncopts=oldncopts;

      /* If the attribute does not exist, copy it.
       * Must always copy signtype, if present!
       */
      if (status == MI_ERROR || !strcmp(name,  MIsigntype)) {
	  status = ncattcopy(incdfid, invarid, name, outcdfid, outvarid);
	  if (status < 0) {
	      milog_message(MI_MSG_COPYATTR, name);
	      MI_RETURN(MI_ERROR);
	  }
      }
   }

   MI_RETURN(MI_NOERROR);
}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : micopy_var_def
@INPUT      : incdfid  - input cdf file id
              invarid  - input variable id
              outcdfid - output cdf file id
@OUTPUT     : (none)
@RETURNS    : Variable id of variable created in outcdfid or MI_ERROR (=-1)
              if an error occurs.
@DESCRIPTION: Copies a variable definition (including attributes) from one 
              cdf file to another. outcdfid must be in define mode.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF routines.
@CREATED    : 
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI int micopy_var_def(int incdfid, int invarid, int outcdfid)
{
   char varname[MAX_NC_NAME]; /* Name of variable */
   char dimname[MAX_NC_NAME]; /* Name of dimension */
   nc_type datatype;          /* Type of variable */
   int ndims;                 /* Number of dimensions of variable */
   int indim[MAX_VAR_DIMS];   /* Dimensions of input variable */
   int outdim[MAX_VAR_DIMS];  /* Dimensions of output variable */
   long insize, outsize;      /* Size of each dimension */
   int recdim;                /* Dimension that is unlimited for input file */
   int outvarid;              /* Id of newly created variable */
   int oldncopts;             /* Store ncopts */
   int i;
   int status;

   MI_SAVE_ROUTINE_NAME("micopy_var_def");

   /* Get name and dimensions of variable */
   status = ncvarinq(incdfid, invarid, varname, &datatype, &ndims, 
                     indim, NULL);
   if (status < 0) {
       milog_message(MI_MSG_VARINQ);
       MI_RETURN(MI_ERROR);
   }

   /* Get unlimited dimension for input file */
   status = ncinquire(incdfid, NULL, NULL, NULL, &recdim);
   if (status < 0) {
       milog_message(MI_MSG_UNLIMDIM);
       MI_RETURN(MI_ERROR);
   }

   /* Create any new dimensions that need creating */
   for (i=0; i<ndims; i++) {

      /* Get the dimension info */
       status = ncdiminq(incdfid, indim[i], dimname, &insize);
       if (status < 0) {
	   milog_message(MI_MSG_DIMINQ);
	   MI_RETURN(MI_ERROR);
       }

      /* If it exists in the output file, check the size. */
      oldncopts=ncopts; ncopts = 0;
      outdim[i] = ncdimid(outcdfid, dimname);
      ncopts=oldncopts;
      if (outdim[i] != MI_ERROR) {
	if ((ncdiminq(outcdfid, outdim[i], NULL, &outsize) == MI_ERROR) ||
             ((insize!=0) && (outsize!=0) && (insize != outsize)) ) {
            if ((insize!=0) && (outsize!=0) && (insize != outsize))
		milog_message(MI_MSG_VARCONFLICT);
            MI_RETURN(MI_ERROR);
         }
      }
      /* Otherwise create it */
      else {
         /* If the dimension is unlimited then try to create it unlimited
            in the output file */
         if (indim[i]==recdim) {
            oldncopts=ncopts; ncopts=0;
            outdim[i]=ncdimdef(outcdfid, dimname, NC_UNLIMITED);
            ncopts=oldncopts;
         }
         /* If it's not meant to be unlimited, or if we cannot create it
            unlimited, then create it with the current size */
         if ((indim[i]!=recdim) || (outdim[i]==MI_ERROR)) {
	     outdim[i] = ncdimdef(outcdfid, dimname, MAX(1,insize));
	     if (outdim[i] < 0) {
		 milog_message(MI_MSG_DIMDEF, dimname);
		 MI_RETURN(MI_ERROR);
	     }
         }
      }
   }

   /* Create a new variable */
   outvarid = ncvardef(outcdfid, varname, datatype, ndims, outdim);

   if (outvarid < 0) {
       milog_message(MI_MSG_VARDEF, varname);
       MI_RETURN(MI_ERROR);
   }
   else {
       /* Copy all the attributes */
       status = micopy_all_atts(incdfid, invarid, outcdfid, outvarid);
       if (status < 0) {
	   MI_RETURN(MI_ERROR);
       }
   }

   MI_RETURN(MI_NOERROR);
}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : mivarsize
@INPUT      : fd  - file id
              varid  - variable id
@OUTPUT     : size_ptr - dimension sizes
@RETURNS    : MI_ERROR (=-1) if an error occurs.
@DESCRIPTION: Copies the lengths of the variable's dimensions to the
              size_ptr array.  size_ptr must point to a buffer large
              enough to hold the data.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF routines.
@CREATED    : 
@MODIFIED   : 
---------------------------------------------------------------------------- */
int
mivarsize(int fd, int varid, long *size_ptr)
{
    int i;
    int ndims;
    int dimids[MAX_VAR_DIMS];

    if (ncvarinq(fd, varid, NULL, NULL, &ndims, dimids, NULL) == MI_ERROR) {
        return (MI_ERROR);
    }

    /* Get the dimension sizes and check for compatibility */
    for (i = 0; i < ndims; i++) {
        if (ncdiminq(fd, dimids[i], NULL, &size_ptr[i]) == MI_ERROR) {
            size_ptr[i] = 0;
        }
    }
    return (MI_NOERROR);
}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : micopy_var_values
@INPUT      : incdfid  - input cdf file id
              invarid  - input variable id
              outcdfid - output cdf file id
              outvarid - output variable id (usually returned by 
                 micopy_var_def)
@OUTPUT     : (none)
@RETURNS    : MI_ERROR (=-1) if an error occurs.
@DESCRIPTION: Copies the values of a variable from one cdf file to another.
              outcdfid must be in data mode. The two variables must have
              the same shape.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF routines.
@CREATED    : 
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI int micopy_var_values(int incdfid, int invarid, 
                             int outcdfid, int outvarid)
{
   nc_type intype, outtype;   /* Data types */
   int inndims, outndims;     /* Number of dimensions */
   long insize[MAX_VAR_DIMS]; /* Dimension sizes */
   long outsize[MAX_VAR_DIMS];
   long start[MAX_VAR_DIMS];  /* First coordinate of variable */
   int indim[MAX_VAR_DIMS];   /* Input dimensions */
   int outdim[MAX_VAR_DIMS];  /* Output dimensions */
   mi_vcopy_type stc;
   int i;
   int status;

   MI_SAVE_ROUTINE_NAME("micopy_var_values");

   /* Get the dimensions of the two variables and check for compatibility */
   if ((ncvarinq(incdfid, invarid, NULL, &intype, &inndims, indim, NULL)
	== MI_ERROR) ||
       (ncvarinq(outcdfid, outvarid, NULL, &outtype, &outndims, outdim, NULL)
	          == MI_ERROR) ||
       (intype != outtype) || (inndims != outndims)) {
       milog_message(MI_MSG_VARMISMATCH);
       MI_RETURN(MI_ERROR);
   }

   /* Get the dimension sizes and check for compatibility */

   mivarsize(incdfid, invarid, insize);
   mivarsize(outcdfid, outvarid, outsize);
   for (i = 0; i < inndims; i++) {
     if (insize[i] != 0 && outsize[i] != 0 && insize[i] != outsize[i]) {
	 milog_message(MI_MSG_VARDIFFSIZE);
	 MI_RETURN(MI_ERROR);
     }
   }

   /* Copy the values */
   stc.incdfid =incdfid;
   stc.outcdfid=outcdfid;
   stc.invarid =invarid;
   stc.outvarid=outvarid;
   stc.value_size=nctypelen(intype);
   status = MI_var_loop(inndims, miset_coords(MAX_VAR_DIMS, 0L, start),
			insize, stc.value_size, NULL, 
			MI_MAX_VAR_BUFFER_SIZE, &stc,
			MI_vcopy_action);
   if (status < 0) {
       milog_message(MI_MSG_COPYVAR);
   }
   MI_RETURN(status);

}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : MI_vcopy_action
@INPUT      : ndims       - number of dimensions
              var_start   - coordinate vector of corner of hyperslab
              var_count   - vector of edge lengths of hyperslab
              nvalues     - number of values in hyperslab
              var_buffer  - pointer to variable buffer
              caller_data - pointer to data from micopy_var_values
@OUTPUT     : (none)
@RETURNS    : MI_ERROR if an error occurs
@DESCRIPTION: Buffer action routine to be called by MI_var_loop, for
              use by micopy_var_values.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF and MINC routines
@CREATED    : August 3, 1992 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
PRIVATE int MI_vcopy_action(int ndims, long start[], long count[], 
                            long nvalues, void *var_buffer, void *caller_data)
     /* ARGSUSED */
{
   mi_vcopy_type *ptr;       /* Pointer to data from micopy_var_values */
   int status;

   MI_SAVE_ROUTINE_NAME("MI_vcopy_action");

   ptr=(mi_vcopy_type *) caller_data;

   /* Get values from input variable */
   status = ncvarget(ptr->incdfid, ptr->invarid, start, count, var_buffer);
   if (status < 0) {
       MI_RETURN(MI_ERROR);
   }

   /* Put values to output variable */
   status = ncvarput(ptr->outcdfid, ptr->outvarid, start, count, var_buffer);
   if (status < 0) {
       MI_RETURN(MI_ERROR);
   }
   MI_RETURN(MI_NOERROR);

}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : micopy_all_var_defs
@INPUT      : incdfid       - input cdf file id
              outcdfid      - output cdf file id
              nexclude      - number of values in array excluded_vars
              excluded_vars - array of variable id's in incdfid that should
                 not be copied
@OUTPUT     : (none)
@RETURNS    : MI_ERROR (=-1) if an error occurs.
@DESCRIPTION: Copies all variable definitions in file incdfid to file outcdfid
              (including attributes), excluding the variable id's listed in
              array excluded_vars. File outcdfid must be in define mode.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF routines.
@CREATED    : August 3, 1992 (Peter Neelin)
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI int micopy_all_var_defs(int incdfid, int outcdfid, int nexclude,
                               int excluded_vars[])
{
   int num_vars;          /* Number of variables in input file */
   int varid;             /* Variable id counter */
   int i;
   int status;

   MI_SAVE_ROUTINE_NAME("micopy_all_var_defs");

   /* Find out how many variables there are in the file and loop through
      them */
   status = ncinquire(incdfid, NULL, &num_vars, NULL, NULL);
   if (status < 0) {
       MI_RETURN(MI_ERROR);
   }

   /* Loop through variables, copying them */
   for (varid=0; varid<num_vars; varid++) {

      /* Check list of excluded variables */
      for (i=0; i<nexclude; i++) {
         if (varid==excluded_vars[i]) 
	     break;
      }

      /* If the variable is not excluded, copy its definition */
      if (i>=nexclude) {
	  status = micopy_var_def(incdfid, varid, outcdfid);
	  if (status < 0) {
	      MI_RETURN(MI_ERROR);
	  }
      }
   }

   /* Copy global attributes */
   for (i=0; i<nexclude; i++) {
      if (NC_GLOBAL==excluded_vars[i]) break;
   }
   if (i>=nexclude) {
       status = micopy_all_atts(incdfid, NC_GLOBAL, outcdfid, NC_GLOBAL);
   }

   MI_RETURN(status);
       
}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : micopy_all_var_values
@INPUT      : incdfid       - input cdf file id
              outcdfid      - output cdf file id
              nexclude      - number of values in array excluded_vars
              excluded_vars - array of variable id's in incdfid that should
                 not be copied
@OUTPUT     : (none)
@RETURNS    : MI_ERROR (=-1) if an error occurs.
@DESCRIPTION: Copies all variable values in file incdfid to file outcdfid,
              excluding the variable id's listed in array excluded_vars. 
              File outcdfid must be in data mode. Usually called after
              micopy_all_var_defs with the same arguments. If a variable
              to be copied is not defined properly in outcdfid, then an
              error occurs.
@METHOD     : 
@GLOBALS    : 
@CALLS      : NetCDF routines.
@CREATED    : 
@MODIFIED   : 
---------------------------------------------------------------------------- */
MNCAPI int micopy_all_var_values(int incdfid, int outcdfid, int nexclude,
                                 int excluded_vars[])
{
   int num_vars;           /* Number of variables in input file */
   int varid;              /* Variable id counter */
   int outvarid;           /* Output variable id */
   char name[MAX_NC_NAME]; /*Variable name */
   int i;
   int status;

   MI_SAVE_ROUTINE_NAME("micopy_all_var_values");

   /* Find out how many variables there are in the file and loop through
      them */
   status = ncinquire(incdfid, NULL, &num_vars, NULL, NULL);
   if (status < 0) {
       milog_message(MI_MSG_VARCOUNT);
       MI_RETURN(MI_ERROR);
   }

   /* Loop through variables, copying them */
   for (varid=0; varid<num_vars; varid++) {

      /* Check list of excluded variables */
      for (i=0; i<nexclude; i++) {
         if (varid==excluded_vars[i]) break;
      }

      /* If the variable is not excluded, copy its values */
      if (i>=nexclude) {
	  /* Get the input variable's name */
	  status = ncvarinq(incdfid, varid, name, NULL, NULL, NULL, NULL);
	  if (status < 0) {
              milog_message(MI_MSG_VARINQ);
	      MI_RETURN(MI_ERROR);
	  }
	  /* Look for it in the output file */
	  outvarid = ncvarid(outcdfid, name);
	  if (outvarid < 0) {
	      milog_message(MI_MSG_OUTPUTVAR, name);
	      MI_RETURN(MI_ERROR);
	  }
	  /* Copy the values */
	  status = micopy_var_values(incdfid, varid, outcdfid, outvarid);
	  if (status < 0) {
	      MI_RETURN(MI_ERROR);
	  }
      }
   }

   MI_RETURN(MI_NOERROR);
       
}

/* ----------------------------- MNI Header -----------------------------------
@NAME       : micreate_tempfile
@INPUT      : void
@OUTPUT     : (none)
@RETURNS    : Pointer to filename (which must be freed), or NULL if an error
              occurs.
@DESCRIPTION: Creates a temporary file (which is initially CLOSED).
@METHOD     : Unnecessarily convoluted, I suppose... See comments.
@GLOBALS    : 
@CALLS      : Standard POSIX/UNIX routines
@CREATED    : 07-March-2003 by bert@bic.mni.mcgill.ca
@MODIFIED   : 
---------------------------------------------------------------------------- */

/* Force P_tmpdir to be something reasonable. */
#if !defined(P_tmpdir)
#define P_tmpdir "/var/tmp"
#endif /* P_tmpdir not defined */

MNCAPI char *
micreate_tempfile(void)
{
  int tmp_fd;
  char *tmpfile_ptr;

#if defined (HAVE_MKSTEMP)

  /* Best-case scenario (so far...)
   * mkstemp() creates a file immediately, minimizing the race
   * conditions that exist when using the other functions.  These race
   * conditions can lead to small security holes (and large, annoying
   * GNU linker messages).
   *
   * The only catch is that mkstemp() does not automatically put the 
   * file in the TMPDIR directory (or some other appropriate place).
   * So I more-or-less emulate that behavior here.
   */
  const char pat_str[] = "/minc-XXXXXX";
  char *tmpdir_ptr;

  if ((tmpdir_ptr = getenv("TMPDIR")) == NULL) {
    tmpdir_ptr = P_tmpdir;
  }
  tmpfile_ptr = malloc(strlen(tmpdir_ptr) + sizeof (pat_str));
  if (tmpfile_ptr == NULL) {
    return (NULL);
  }
  strcpy(tmpfile_ptr, tmpdir_ptr);
  strcat(tmpfile_ptr, pat_str);
  tmp_fd = mkstemp(tmpfile_ptr); /* Creates the file if possible. */

#elif defined (HAVE_TEMPNAM)

  /* Second-best case.  While not completely avoiding the race condition,
   * this approach should at least have the nice property of putting the
   * tempfile in the right directory (on IRIX and Linux, at least - on
   * some systems tempnam() may not consult the TMPDIR environment variable).
   */
  tmpfile_ptr = tempnam(NULL, "minc-");
  if (tmpfile_ptr == NULL) {
    return (NULL);
  }
  tmp_fd = open(tmpfile_ptr, O_CREAT | O_EXCL | O_RDWR, S_IWRITE | S_IREAD);

#elif defined (HAVE_TMPNAM)
  /* Worst case.  tmpnam() is apparently the worst of all possible worlds
   * here.  It doesn't allow any way to force a particular directory,
   * and it doesn't avoid the race condition.  But volume_io used it for
   * years, so I see no reason to disallow this case for systems that 
   * might not define the above two functions (whether any such systems
   * exist is unclear to me).
   */
  tmpfile_ptr = malloc(L_tmpnam + 1);
  if (tmpfile_ptr == NULL) {
    return (NULL);
  }
  if (tmpnam(tmpfile_ptr) == NULL) {
    free(tmpfile_ptr);
    return (NULL);
  }
  tmp_fd = open(tmpfile_ptr, O_CREAT | O_EXCL | O_RDWR, S_IWRITE | S_IREAD);

#else
#error "System defines neither mkstemp(), tempnam(), nor tmpnam()"
#endif /* Neither HAVE_MKSTEMP, HAVE_TEMPNAM, or HAVE_TMPNAM defined. */

  /* If we get here, tmp_fd should have been opened and the file
   * created.  Now go ahead and close the file.
   */
  if (tmp_fd >= 0) {
    close(tmp_fd);
  }
  else {
    free(tmpfile_ptr);
    tmpfile_ptr = NULL;
  }
  return (tmpfile_ptr);
}

/** Simple function to read a user's .mincrc file, if present.
 */
static int
miread_cfg(const char *name, char *buffer, int maxlen)
{
    FILE *fp;
    int result = 0;
    char *home_ptr = getenv("HOME");
    char path[256];

    if (home_ptr != NULL) {
      strcpy(path, home_ptr);
    }
    else {
      path[0] = '\0';
    }
    strcat(path, "/.mincrc");
    
    if ((fp = fopen(path, "r")) != NULL) {
        while (fgets(buffer, maxlen, fp)) {
            if (buffer[0] == '#') {
                continue;
            }
            if (!strncasecmp(buffer, name, strlen(name))) {
                char *tmp = strchr(buffer, '=');
                if (tmp != NULL) {
                    tmp++;
                    while (isspace(*tmp)) {
                        tmp++;
                    }
                    strncpy(buffer, tmp, maxlen);
                    result = 1;
                    break;
                }
            }
        }
        fclose(fp);
    }
    return (result);
}

int
miget_cfg_bool(const char *name)
{
    char buffer[128];
    char *var_ptr;

    if ((var_ptr = getenv(name)) != NULL) {
        strncpy(buffer, var_ptr, sizeof (buffer));
    }
    else {
        if (!miread_cfg(name, buffer, sizeof (buffer))) {
            return (0);
        }
    }
    return (atoi(buffer) != 0);
}

int
miget_cfg_int(const char *name)
{
    char buffer[128];
    char *var_ptr;
    
    if ((var_ptr = getenv(name)) != NULL) {
        strncpy(buffer, var_ptr, sizeof (buffer));
    }
    else {
        if (!miread_cfg(name, buffer, sizeof(buffer))) {
            return (0);
        }
    }
    return (atoi(buffer));
}

char *
miget_cfg_str(const char *name)
{
    char buffer[256];
    char *var_ptr;

    if ((var_ptr = getenv(name)) != NULL) {
        strncpy(buffer, var_ptr, sizeof(buffer));
    }
    else {
        if (!miread_cfg(name, buffer, sizeof(buffer))) {
            return (NULL);
        }
    }
    return (strdup(buffer));
}