cdfnew2nc.c 73.9 KB
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
/********************************************************** 
 * Usage : amda-cdf-to-netcdf-w-false FileName [varToKeep1 varToKeep2 .....]
 * No 'false dims' suppression
 *********************************************************/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "netcdf.h"
#include "cdf.h"

#define MAX_FILE_NAME_LEN  120      /* Max. file name length              */
#define MAX_ATTRS          3000     /* Max # of CDF attributes            */
#define UNKNOWN_DT         -99      /* Unsupported CDF datatype indicator */

#define DEFAULT_MAPPING_FILE   "cdf_to_netcdf_mapping.dat"
#define MAX_REC_LENGTH         NC_MAX_NAME+CDF_ATTR_NAME_LEN256+2
                                 /* Max record length of DEFAULT_MAPPING_FILE */

#define TRUE               1
#define FALSE              0

/*************************************
   Global variables and structures
**************************************/
CDFid    id;        /* CDF file ID      */ 
int      ncid;      /* netCDF file ID   */

long nZvars,        /* Number of zVariables in a CDF file                     */
     nAttrs;        /* Number of attributes (global & variable) in a CDF file */

typedef struct ncdim {          /* netCDF dimension structure */
    char name[NC_MAX_NAME+1];           /* Dimension name */
    int  size;                          /* Dimension size */
    int  id;                            /* Dimension id   */
} netcdfDimension;

netcdfDimension ncDims[NC_MAX_DIMS];       /* max dimensions per netCDF file */
int  totNCdims = 0;         /* Total # of netCDF dimensions created          */

typedef struct cdfvar {           /* CDF variable structure */
     char name[CDF_VAR_NAME_LEN256+1];   
     long datatype;                   
     long numElements;            /* string length for CDF_CHAR, 1 otherwise */
     long dimensionality;             /* variable dimensionality             */
     long dimSizes[CDF_MAX_DIMS];     /* variable dimension sizes            */
     long recVariance;                /* record variance                     */
     long numRecs;                    /* # of records this variable contains */
} CDFvar;

/****************************************************************************
 *   Arrays to hold the CDF-to-netCDF mapping information that are loaded
 *   from the default or user-define mapping file.
 ****************************************************************************/
char netcdfAttrNames[MAX_ATTRS][NC_MAX_NAME];
char cdfAttrNames[MAX_ATTRS][CDF_ATTR_NAME_LEN256+1];
char comments[MAX_ATTRS][CDF_ATTR_NAME_LEN256+1];

int  totAttrsInMappingFile;           /* # of attributes in the mapping file */
char mappingFile[CDF_PATHNAME_LEN];  /* Mapping file name                   */

int DEBUG = FALSE;



/**************************
   Function prototypes
**************************/
int endsWith(char *, char *);
char * strlaststr(char *, char *);
void get_cdf_attribute(long, long, long, int);
void get_cdf_attr_data(char *, long, long, long, int);
char * cdf_str_datatype (long);
char * NC_datatype (nc_type);
nc_type get_netcdf_datatype (long);
void usage();
CDFid cdf_open(char *);
void read_cdf_file_info();
void get_zVariables(long *, int);
int create_netcdf_dimensions_attribute (int *);
void create_netcdf_dimensions_variable (CDFvar, long, int *, int *);
int create_netcdf_variable (CDFvar, long, int);
void get_cdf_variable_data (long, CDFvar, long);
void read_cdf_variable_data (long, long, long, long, long [], void *);
void removeFilepath();
void handle_netcdf_error (int);
void memory_error(char *, char *);
void cdf_status_handler (CDFstatus, char *);
void insufficient_memory();    /* used for debug */
char * getNextArgument (int, char *[], int);
void parseCmdLine (int, char *[]);
void errorMsg (char *);
void map_CDF_attr_to_netCDF (char *, char *);
void breakdown_DIMENSIONS_entry (char *, char **);

#define	AMDA
#ifdef	AMDA

#include "tools.h"

char	start_time [DD_TIME_STRING_LEN+1];	
char	stop_time  [DD_TIME_STRING_LEN+1];

#endif

/**************************************************************************** 
   NOTE:

   CDF has the following features that are not supported by netCDF:

   - CDF_EPOCH datatype (8-byte real number) that is used to store time 
     values referenced from a particular epoch that is 
     01-Jan-0000 00:00:00.000.  CDF_EPOCH values are the number of 
     milliseconds since the epoch described above.

   - CDF_EPOCH16 datatype (16-byte real number) that is used to store time 
     values referenced from a particular epoch that is 
     01-Jan-0000 00:00:00.000.000.000.000.  CDF_EPOCH16 values are the 
     number of milliseconds since the epoch described above.

   - CDF global attribute (not variable attribute) can have multiple
     attribute entries and each entry can have a different datatype.
*****************************************************************************/
int main(int argc, char *argv[])
{
    FILE  *inFile;             /* Pointer to the CDF-to-netCDF mapping file */
    char  rec[MAX_REC_LENGTH];     /* CDF-to-netCDF mapping record */

    /************************/
    /*  netCDF declaration  */
    /************************/
    int  status,                  /* netCDF status code */
         dummy, i; 

    char *ptr, fileName[CDF_PATHNAME_LEN];

    /**********************/
    /*  CDF declaration   */
    /**********************/
    CDFstatus   cstatus;           /* CDF status code */
    long        attrId;            /* CDF attribute ID */
    long        varId;
    long        *varsToGet;
    int         nVarsToGet;
    
    if (argc <= 1) 
        usage();                   /* CDF input file name not specified */
    else {
        strcpy(fileName, argv[1]);       /* Get the input file name */
        strcpy(mappingFile, "UNSPECIFIED");
        parseCmdLine(argc, argv);
        if (strcmp(mappingFile, fileName) == 0)
            errorMsg("** Error - either input file or mapping file is missing");
        if (strcmp(mappingFile,"UNSPECIFIED") == 0)  
            strcpy(mappingFile, DEFAULT_MAPPING_FILE);
    }

#ifdef	AMDA


    status = check_version();
#endif
    /***********************************************/
    /*  Load the CDF-to-netCDF mapping information */
    /***********************************************/
    if ((inFile = fopen(mappingFile, "r")) == NULL) {
         printf ("WARNING : Cannot open file: %s  **\n", mappingFile);
	 totAttrsInMappingFile = 0;
    }
    else {
        totAttrsInMappingFile = 0;
        while (fgets(rec, MAX_REC_LENGTH, inFile) != NULL) {
            rec[strlen(rec)-1] = '\0';       /* Remove the newline character */

	    /* Process the mapping record if it's not a comment */
	    if (rec[0] != '#'  &&  rec[0] != ' ' && strlen(rec) > 0) {
	        sscanf(rec, "%s %s",
		       netcdfAttrNames[totAttrsInMappingFile],
		       cdfAttrNames[totAttrsInMappingFile]);
	        ptr = (char *) strstr(rec, "//");
	        if (ptr != NULL) {
		    ptr += 3;
		    strcpy (comments[totAttrsInMappingFile], ptr);
	        }
                if (DEBUG)
		    printf("%s %s %s\n",
		           netcdfAttrNames[totAttrsInMappingFile],
		           cdfAttrNames[totAttrsInMappingFile],
		           comments[totAttrsInMappingFile]);
	        totAttrsInMappingFile++;
	    }
        }
    }
    /***********************************************************
     *  Process the CDF information and create a netCDF file
     ***********************************************************/
/*    printf ("\nInput file name: %s\n", fileName); */
    id = cdf_open (fileName);

    /* Remove the file path if it exists (/home/mydata.cdf => mydata.cdf). */
    removeFilepath(fileName);

    if (endsWith(fileName,".cdf")) {
        /* Strip off the .cdf file extension. */
        ptr = (char *) strlaststr(fileName, ".cdf");
        if (ptr != NULL) *ptr = '\0'; 
    }
    strcat(fileName, ".nc");
    status = nc_create(fileName, NC_CLOBBER, &ncid);
    if (status != NC_NOERR) handle_netcdf_error(status);
    printf ("Output file name: %s\n", fileName);

    /***********************************************************************
     * Get the number of dimensions, number of variables, number of global
     * attributes.
     *
     * Note that the information retrieved from read_cdf_file_info are stored
     * into the global variables defined at the top.
     ***********************************************************************/
    read_cdf_file_info ();
    if (DEBUG) printf ("nAttrs=%ld, nZvars=%ld\n", nAttrs, nZvars);

    /* Get the CDF global attributes and create netCDF global attributes. */
    if (DEBUG) printf ("Global attributes:\n");
    dummy = -1; 
    for (attrId = 0; attrId < nAttrs; attrId++) 
         get_cdf_attribute(attrId, GLOBAL_SCOPE, (long) dummy, dummy);

    /* Write the placeholder attributes. */
    for (i=0; i < totAttrsInMappingFile; i++) {
        if (strcmp(cdfAttrNames[i],"*") == 0) {
           status = nc_put_att_text (ncid, 
                                     NC_GLOBAL,           /* vavriable ID */
                                     netcdfAttrNames[i],  /* Attribute name */
                                     strlen(comments[i]), /* # of attr values */
                                     comments[i]);                            
         }
    }


    /* Process CDF variables and create netCDF variables */
    if (argc > 2) {
        varsToGet = (long *) malloc(sizeof(long)*(argc-2));
        for (i = 2; i < argc; i++ ) {
              status = CDFlib ( GET_, zVAR_NUMBER_, argv[i], &varId);
              varsToGet[i-2] = varId;
        }
        nVarsToGet = argc-2;
    }
    else {
        varsToGet = (long *) malloc(sizeof(long)*nZvars);
        for (i = 0; i <  nZvars; i++) varsToGet[i] = (long)i;
        nVarsToGet = nZvars;
    }
    printf("NVARS %d\n",nVarsToGet);
    if (nZvars > 0) get_zVariables(varsToGet, nVarsToGet);


    /* Close the netCDF and CDF files */
    cstatus = CDFlib (CLOSE_, CDF_, NULL_);
    if (cstatus != CDF_OK) cdf_status_handler (cstatus, "CLOSE_, CDF_");

    status = nc_close(ncid);
    if (status != NC_NOERR) handle_netcdf_error(status);
}


/*----------------------------------------------------------------------------
 *  TRUE if s1 ends with s2.  Otherwise, FALSE is returned.
 *---------------------------------------------------------------------------*/
int endsWith (char *s1, char *s2)
{ 
    int  i;
    char *ps1, *ps2;

    if (strlen(s2) > strlen(s1))
        return FALSE;

    ps1 = s1 + strlen(s1) - strlen(s2); 
    ps2 = s2;

    for (i=0; i < strlen(s2); i++) 
        if (*(ps1++) != *(ps2++))
            return FALSE;
     
    return TRUE;
}


/*---------------------------------------------------------------------------------
 *  Find the last occurence of s2 in s1.  If s21 is not found, s1 is returned. 
 *--------------------------------------------------------------------------------*/
char * strlaststr (char *s1, char *s2)
{
    char *sc2, *psc1, *ps1;

    if (*s2 == '\0')
        return((char *)s1);

    ps1 = s1 + strlen(s1);

    while(ps1 != s1) {
        --ps1;
        for (psc1 = ps1, sc2 = s2; ; )
                if (*(psc1++) != *(sc2++))
                        break;
                else if (*sc2 == '\0')
                        return ((char *)ps1);
    }
    return ((char *)NULL);
}


/*--------------------------------------------------------------------------
 *  This routine opens a CDF file
 *-------------------------------------------------------------------------*/
CDFid cdf_open (char *fileName)     
{
   CDFstatus status;
   CDFid     id;
   char      msg[500];

   status = CDFlib (OPEN_, CDF_, fileName,    /* in - file name to be opened */
                                 &id,         /* out - CDF file ID           */
                    NULL_);

   if (status != CDF_OK)  {
       strcpy(msg, "OPEN_, CDF_, ");       
       strcat(msg, fileName);
       cdf_status_handler (status, msg);
   }
   return id;
}


/*---------------------------------------------------------------------------
 *   This routine retrievs the following information:
 *
 *      nAttr - number of attributes (including global and variable)
 *      nZvars - number of zVariables
 *
 *   CDF file can have both rVariables (old style) and zVariables (new style)
 *   simultaneously.  zVariable is a superset of rVariable, and it is a lot
 *   more efficient and offers all the functionality a rVariable offers and 
 *   more.  Treat all CDF variables as zVariables.
 *--------------------------------------------------------------------------*/
void read_cdf_file_info ()
{
    CDFstatus status;

    status = CDFlib (SELECT_, CDF_zMODE_, zMODEon2,
                     GET_, CDF_NUMATTRS_,  &nAttrs, 
                           CDF_NUMzVARS_,  &nZvars, 
                     NULL_);
    if (status != CDF_OK) cdf_status_handler (status, "GET_, CDF_FILEINFO_");
}


/*----------------------------------------------------------------------------
 *  This routine retrieves the CDF attribute (global or variable) name
 *  and its data for the given CDF attribute ID.  
 *---------------------------------------------------------------------------*/
void get_cdf_attribute(long attrNum,        /* in - CDF attribute number/id */
                       long scope,          /* in - CDF attribute scope     */
                       long cdfVarId,       /* in - CDF variable number/id  */
                       int  netcdfVarId)    /* in - netCDF variable ID      */
{
    int           ncstatus, i, len;
    long          status, numEntries, datatype, attrScope, entryNum, 
                  numElements;
    nc_type       ncDatatype;      /* netCDF datatype */
    
    char          *cPtr, attrName[CDF_ATTR_NAME_LEN256+1],
                  mappedAttrName[CDF_ATTR_NAME_LEN256+1];

    status = CDFlib (SELECT_, ATTR_, attrNum,
                     GET_,    ATTR_NAME_, attrName,
                              ATTR_SCOPE_, &attrScope,
                     NULL_);
    if (status != CDF_OK) cdf_status_handler (status, "SELECT_, ATTR_");      

    /****************************************************************/
    /* If the attribute scope is not the requested attribute scope  */
    /* (VARIABLE_SCOPE or GLOBAL_SCOPE), do not process the current */
    /* attribute.                                                   */
    /****************************************************************/
    if (attrScope != scope) return;
    if (strcmp(attrName, "DIMENSIONS_G") == 0 ||
        strcmp(attrName, "DIMENSIONS_V") == 0) return;
    map_CDF_attr_to_netCDF(attrName, mappedAttrName);
    strcpy(attrName, mappedAttrName);

    if (attrScope == GLOBAL_SCOPE) {
        status = CDFlib (GET_,  ATTR_NUMgENTRIES_, &numEntries, NULL_);
        if (status != CDF_OK) 
            cdf_status_handler (status, "GET_, ATTR_NUMgENTRIES_");
        if (DEBUG) printf ("\t%s", attrName);

        /*********************************************************************
         * While the CDF global attribute can have multiple entries of 
         * of different datatypes, the CDF variable attribute can only have 
         * one attribute entry.  netCDF doesn't allow more than 1 attribute
         * entry - handle this case 
         ********************************************************************/
        for (entryNum=0; entryNum < numEntries; entryNum++) {
             if (entryNum > 0)            /* Attribute has more than 1 entry */
                 sprintf (attrName, "%s_%ld", mappedAttrName, entryNum);
             status = CDFlib (SELECT_, gENTRY_, entryNum,
                              GET_,    gENTRY_DATATYPE_, &datatype,
                                       gENTRY_NUMELEMS_, &numElements,
                              NULL_);
             if (status == NO_SUCH_ENTRY) return;
             if (status != CDF_OK) cdf_status_handler(status,"GET_ATTR_INFO_");
             get_cdf_attr_data (attrName, gENTRY_DATA_, datatype, numElements,
                                netcdfVarId);
        }
    }
    else {
        /*********************************************************************
         * IMPORTANT NOTE:
         *     For the variable attribute, entry number is the variable ID.
         *********************************************************************/
        status = CDFlib (SELECT_, zENTRY_, cdfVarId,
                         GET_,    zENTRY_DATATYPE_, &datatype,
                                  zENTRY_NUMELEMS_, &numElements,
                         NULL_);
        /******************************************************************/
        /* If there's no attribute entry for the current attribute number */
        /* selected, process the next attribute.                          */
        /******************************************************************/
        if (status == NO_SUCH_ENTRY) return;    

        if (status != CDF_OK) cdf_status_handler (status,"GET_ATTR_INFO_");
        if (DEBUG) printf ("\t%s", attrName);
        if (attrName[strlen(attrName)-1] == (char) '_') {
           char name2[CDF_ATTR_NAME_LEN256+1];
           strcpy(name2, attrName);
           name2[strlen(name2)-1] = (char) '\0';
           status = CDFlib (GET_, ATTR_NUMBER_, name2, &attrNum,
                            NULL_);
           if (status == CDF_OK) {
             strcpy(attrName, name2);
             map_CDF_attr_to_netCDF(attrName, mappedAttrName);
             strcpy(attrName, mappedAttrName);
           }
        }
        get_cdf_attr_data (attrName, zENTRY_DATA_, datatype, numElements,
                           netcdfVarId);
    }
}


/*--------------------------------------------------------------------------
 *  This routine retrieves the CDF attribute data (a.k.a. attribute entries)
 *  and write its values to the target netCDF file.
 *--------------------------------------------------------------------------*/
void get_cdf_attr_data (char *attrName,    /* in - attribute name          */
                        long entryData,    /* in - type of attr entry data */
                        long datatype,     /* in - attribute datatype      */ 
                        long numElements,  /* in - # of attribute values   */
                        int netcdfVarId)   /* in - netCDF variable ID      */
{
    char     entryDataType[20], msg[100],
             epString[EPOCH4_STRING_LEN+1],
             ep16String[EPOCH16_4_STRING_LEN+1],
             mappedAttrName[CDF_ATTR_NAME_LEN256+1],
             tt2000String[TT2000_3_STRING_LEN+1];
    double   epoch16[2];

    nc_type  ncDatatype;                  /* netCDF datatype    */
    int      nc_status,                   /* netCDF status code */
             varId;                       /* netCDF variable ID */
    long     status;                      /* CDF status code    */

    char          *cPtr;
    signed char   *scPtr;
    unsigned char *uscPtr;
    short         *sPtr;
    unsigned short *usPtr;
    int           *iPtr, i;
    unsigned int  *uiPtr;
    long long     *jPtr, aLonglong;
    float         *fPtr;
    double        *dPtr;

    /*************************************************
     * entryData has one of following values: 
     * 
     *    gENTRY_DATA_ - global attribute entry
     *    rENTRY_DATA_ - rVariable attribute entry
     *    zENTRY_DATA_ - zVariable attribute entry
     *************************************************/
    if (entryData == gENTRY_DATA_) {
        varId = NC_GLOBAL;
        strcpy(entryDataType, "gENTRY_DATA_");
    }
    else {
        varId = netcdfVarId;
        strcpy(entryDataType, "zENTRY_DATA_");
    }
    strcpy (msg, "get_cdf_attr_data, GET_, ");
    strcat (msg, entryDataType);
    strcat (msg, cdf_str_datatype(datatype));

    /*  Map the CDF datatype to an appropriate netCDF datatype. */
    ncDatatype = get_netcdf_datatype (datatype);

    /* Remove trailing blank spaces if there are any */
    for (i=strlen(attrName)-1; i >= 0; i--) {
         if (attrName[i] != ' ') {
             attrName[i+1] = '\0';
             break;
         }
    }
    /* Replace blanks space(s) with underscore(s). */
    for (i=0; i < strlen(attrName); i++) {
         if (attrName[i] == ' ') attrName[i] = '_';
    }

    switch (datatype) {
    case CDF_CHAR:
    case CDF_UCHAR:
        cPtr = (char *) malloc(numElements * sizeof(char) + 1);
        if (cPtr == NULL) memory_error("get_cdf_attr_data", "NC_CHAR");
        status = CDFlib (GET_, entryData, cPtr, NULL_);
        if (status != CDF_OK) cdf_status_handler (status, msg);
        *(cPtr+numElements) = '\0';               /* End of string mark */
        if (DEBUG) printf (" = \"%s\"", cPtr);
        nc_status = nc_put_att_text(ncid, varId, attrName, numElements, cPtr);
        if (nc_status != NC_NOERR) handle_netcdf_error(nc_status);
        free(cPtr);
        break;

    case CDF_BYTE:
    case CDF_INT1:
        scPtr = (signed char *) malloc (sizeof(signed char) * numElements);
        if (scPtr == NULL) memory_error("get_cdf_attr_data", "NC_BYTE");
        status = CDFlib (GET_, entryData, scPtr, NULL_);
        if (status != CDF_OK) cdf_status_handler (status, msg);
        if (DEBUG) {
            printf (" = ");
            for (i=0; i < numElements; i++) {
                 if (i > 0) printf (", ");
                 printf ("%d", *(scPtr+i));
            }
        }
        nc_status = nc_put_att_schar(ncid, varId, attrName, ncDatatype, 
                                     numElements, scPtr);
        if (nc_status != NC_NOERR) handle_netcdf_error(nc_status);
        free (scPtr);
        break;

    case CDF_UINT1:
        uscPtr = (unsigned char *) malloc (sizeof(unsigned char) * numElements);
        if (uscPtr == NULL) memory_error("get_cdf_attr_data", "NC_BYTE");
        sPtr = (short *) malloc (sizeof(short) * numElements);
        if (sPtr == NULL) memory_error("get_cdf_attr_data", "NC_SHORT");
        status = CDFlib (GET_, entryData, uscPtr, NULL_);
        if (status != CDF_OK) cdf_status_handler (status, msg);
        if (DEBUG) {
            printf (" = ");
            for (i=0; i < numElements; i++) {
                 if (i > 0) printf (", ");
                 printf ("%d", *(uscPtr+i));
            }
        }
        for (i = 0; i < numElements; ++i) {
          *(sPtr+i) = (short) *(uscPtr+i);
        }
        nc_status = nc_put_att_short(ncid, varId, attrName, ncDatatype, 
                                     numElements, sPtr);
        if (nc_status != NC_NOERR) handle_netcdf_error(nc_status);
        free (uscPtr);
        free (sPtr);
        break;

    case CDF_INT2:
        sPtr = (short *) malloc (sizeof(short) * numElements);
        if (sPtr == NULL) memory_error("get_cdf_attr_data", "NC_SHORT");
        status = CDFlib (GET_, entryData, sPtr, NULL_);
        if (status != CDF_OK) cdf_status_handler (status, msg);
        if (DEBUG) {    
            printf (" = ");    
            for (i=0; i < numElements; i++) {    
                 if (i > 0) printf (", ");    
                 printf ("%hd", *(sPtr+i));   
            }    
        }    
        nc_status = nc_put_att_short(ncid, varId, attrName, ncDatatype, 
                                     numElements, sPtr);
        if (nc_status != NC_NOERR) handle_netcdf_error(nc_status);
        free (sPtr);
        break;

    case CDF_UINT2:
        usPtr = (unsigned short *) malloc (sizeof(unsigned short) * numElements);
        if (usPtr == NULL) memory_error("get_cdf_attr_data", "NC_SHORT");
        iPtr = (int *) malloc (sizeof(int) * numElements);
        if (iPtr == NULL) memory_error("get_cdf_attr_data", "NC_INT");
        status = CDFlib (GET_, entryData, usPtr, NULL_);
        if (status != CDF_OK) cdf_status_handler (status, msg);
        if (DEBUG) {    
            printf (" = ");    
            for (i=0; i < numElements; i++) {    
                 if (i > 0) printf (", ");    
                 printf ("%hu", *(usPtr+i));   
            }    
        }    
        for (i = 0; i < numElements; ++i) {
          *(iPtr+i) = (int) *(usPtr+i);
        }   
        nc_status = nc_put_att_int(ncid, varId, attrName, ncDatatype, 
                                   numElements, iPtr);
        if (nc_status != NC_NOERR) handle_netcdf_error(nc_status);
        free (usPtr);
        free (iPtr);
        break;

    case CDF_INT4:
        iPtr = (int *) malloc (sizeof(int) * numElements);
        if (iPtr == NULL) memory_error("get_cdf_attr_data", "NC_INT");
        status = CDFlib (GET_, entryData, iPtr, NULL_);
        if (status != CDF_OK) cdf_status_handler (status, msg);
        if (DEBUG) {
            printf (" = ");
            for (i=0; i < numElements; i++) {
                 if (i > 0) printf (", ");
                 printf ("%d", *(iPtr+i));
            }
        }
        nc_status = nc_put_att_int(ncid, varId, attrName, ncDatatype, 
                                   numElements, iPtr);
        if (nc_status != NC_NOERR) handle_netcdf_error(nc_status);
        free (iPtr);
        break;

    case CDF_UINT4:
        uiPtr = (unsigned int *) malloc (sizeof(unsigned int) * numElements);
        if (uiPtr == NULL) memory_error("get_cdf_attr_data", "NC_INT");
        dPtr = (double *) malloc (sizeof(double) * numElements);
        if (dPtr == NULL) memory_error("get_cdf_attr_data", "NC_DOUBLE");
        status = CDFlib (GET_, entryData, uiPtr, NULL_);
        if (status != CDF_OK) cdf_status_handler (status, msg);
        if (DEBUG) {
            printf (" = ");
            for (i=0; i < numElements; i++) {
                 if (i > 0) printf (", ");
                 printf ("%ud", *(uiPtr+i));
            }
        }
        for (i = 0; i < numElements; ++i) {
          *(dPtr+i) = (double) *(uiPtr+i);
        }   
        nc_status = nc_put_att_double(ncid, varId, attrName, ncDatatype, 
                                      numElements, dPtr);
        if (nc_status != NC_NOERR) handle_netcdf_error(nc_status);
        free (uiPtr);
        free (dPtr);
        break;

    case CDF_INT8:
        jPtr = (long long *) malloc (sizeof(long long) * numElements);
        if (jPtr == NULL) memory_error("get_cdf_attr_data", "NC_INT64");
        dPtr = (double *) malloc (sizeof(double) * numElements);
        if (dPtr == NULL) memory_error("get_cdf_attr_data", "NC_DOUBLE");
        status = CDFlib (GET_, entryData, jPtr, NULL_);
        if (status != CDF_OK) cdf_status_handler (status, msg);
        if (DEBUG) {
            printf (" = ");
            for (i=0; i < numElements; i++) {
                 if (i > 0) printf (", ");
                 printf ("%lld", *(jPtr+i));
            }
        }
        for (i = 0; i < numElements; ++i) {
          *(dPtr+i) = (double) *(jPtr+i);
        } 
        nc_status = nc_put_att_double(ncid, varId, attrName, ncDatatype, 
                                      numElements, dPtr);
        if (nc_status != NC_NOERR) handle_netcdf_error(nc_status);
        free (jPtr);
        free (dPtr);
        break;

    case CDF_FLOAT:
    case CDF_REAL4:
        fPtr = (float *) malloc (sizeof(float) * numElements);
        if (fPtr == NULL) memory_error("get_cdf_attr_data", "NC_FLOAT");
        status = CDFlib (GET_, entryData, fPtr, NULL_);
        if (status != CDF_OK) cdf_status_handler (status, msg);
        if (DEBUG) {
            printf (" = ");
            for (i=0; i < numElements; i++) {
                 if (i > 0) printf (", ");
                 printf ("%g", *(fPtr+i));
            }
        }
        nc_status = nc_put_att_float(ncid, varId, attrName, ncDatatype, 
                                     numElements, fPtr);
        if (nc_status != NC_NOERR) handle_netcdf_error(nc_status);
        free (fPtr);
        break;

    case CDF_DOUBLE:
    case CDF_REAL8:
        dPtr = (double *) malloc (sizeof(double) * numElements);
        if (dPtr == NULL) memory_error("get_cdf_attr_data", "NC_DOUBLE");
        status = CDFlib (GET_, entryData, dPtr, NULL_);
        if (status != CDF_OK) cdf_status_handler (status, msg);
        if (DEBUG) {
            printf (" = ");
            for (i=0; i < numElements; i++) {
                 if (i > 0) printf (", ");
                 printf ("%g", *(dPtr+i));
            }
        }
        nc_status = nc_put_att_double(ncid, varId, attrName,
                                      ncDatatype, numElements, dPtr);
        if (nc_status != NC_NOERR) handle_netcdf_error(nc_status);
        free (dPtr);
        break;

    case CDF_EPOCH:       /* 8-byte real number */ 
        dPtr = (double *) malloc (sizeof(double) * numElements);
        if (dPtr == NULL) memory_error("get_cdf_attr_data", "CDF_EPOCH");
        status = CDFlib (GET_, entryData, dPtr, NULL_);
        if (status != CDF_OK) cdf_status_handler (status, msg);
        if (DEBUG) printf (" = ");
        for (i=0; i < numElements; i++) {
             encodeEPOCH4 (* (dPtr+i), epString);
             nc_status = nc_put_att_text(ncid, varId, attrName, EPOCH4_STRING_LEN, epString);
             if (nc_status != NC_NOERR) handle_netcdf_error(nc_status);
             if (DEBUG)  {
                 if (i > 0) printf (", ");
                 printf ("%s", epString);
                 if (i == (numElements -1)) printf ("\n");
             }
        }
        free (dPtr);
        break;

    case CDF_EPOCH16:       /* 16-byte real number */
        dPtr = (double *) malloc (sizeof(double) * numElements * 2);
        if (dPtr == NULL) memory_error("get_cdf_attr_data", "CDF_EPOCH16");
        status = CDFlib (GET_, entryData, dPtr, NULL_);
        if (status != CDF_OK) cdf_status_handler (status, msg);
        if (DEBUG) printf (" = "); 
        for (i=0; i < numElements; i++) {
             epoch16[0] = *(dPtr+i*2);
             epoch16[1] = *(dPtr+i*2+1);
             encodeEPOCH16_4 (epoch16, ep16String);
             nc_status = nc_put_att_text(ncid, varId, attrName,
                                         strlen(ep16String), ep16String);
             if (nc_status != NC_NOERR) handle_netcdf_error(nc_status);
             if (DEBUG)  {
                 if (i > 0) printf (", "); 
                 printf ("%s", ep16String);
                 if (i == (numElements -1)) printf ("\n");
             }   
        }
        free (dPtr);
        break;

    case CDF_TIME_TT2000:       /* 8-byte integer number */ 
        jPtr = (long long *) malloc (sizeof(long long) * numElements);
        if (jPtr == NULL) memory_error("get_cdf_attr_data", "CDF_TIME_TT2000");
        status = CDFlib (GET_, entryData, jPtr, NULL_);
        if (status != CDF_OK) cdf_status_handler (status, msg);
        if (DEBUG) printf (" = ");
        for (i=0; i < numElements; i++) {
             encodeTT2000 (*(jPtr+i), tt2000String);
             nc_status = nc_put_att_text(ncid, varId, attrName,
                                         TT2000_3_STRING_LEN, tt2000String);
             if (nc_status != NC_NOERR) handle_netcdf_error(nc_status);
             if (DEBUG)  {
                 if (i > 0) printf (", ");
                 printf ("%s", tt2000String);
                 if (i == (numElements -1)) printf ("\n");
             }
        }
        free (jPtr);
        break;

    default:
            printf ("** Error in get_cdf_attribute: bad data type");
    }
    if (DEBUG) printf (" ;\n");
}


/*--------------------------------------------------------------------------
 *  Get the zVariables in the CDF file.
 *--------------------------------------------------------------------------*/
void get_zVariables(long *vars, int nvars) 
{
   CDFstatus status;
   int       i, ncstatus, createUnlimitedDim, unlimitedDimId, 
             attrId, netcdfVarId, bypass; 
   char      netcdfDimName[NC_MAX_NAME+1];       /* netCDF dimension name */
   long      holdDim, holdDim0;
   long      varId, ncVarId;
   CDFvar    var;

   if (DEBUG) printf ("\n");

   createUnlimitedDim = TRUE;
   bypass = FALSE;
   
   for (i = 0; i < nvars; i++) {
       
        varId = vars[i];
        ncVarId = (long)i;
        status = CDFlib (SELECT_,zVAR_, varId,
                         GET_, zVAR_NAME_, var.name,
                               zVAR_DATATYPE_, &var.datatype,
                               zVAR_NUMELEMS_, &var.numElements,
                               zVAR_NUMDIMS_, &var.dimensionality,
                               zVAR_DIMSIZES_, var.dimSizes,
                               zVAR_NUMRECS_, &var.numRecs,
                               zVAR_RECVARY_, &var.recVariance,
                         NULL_);   
        if (status != CDF_OK) cdf_status_handler (status, "GET_, zVARS_");

        if (DEBUG) {
            printf ("var name = %s, %s/%ld, %ld:[", 
                    var.name, cdf_str_datatype(var.datatype), 
                    var.numElements, var.dimensionality); 
            for (i=0; i < var.dimensionality; i++) {
                 if (i > 0) printf (",");
                 printf ("%ld", var.dimSizes[i]);
            }
            printf("], numRecs = %ld\n", var.numRecs);
        }

        if (varId == 0)
          bypass = create_netcdf_dimensions_attribute (&unlimitedDimId);
        if (!bypass)
          create_netcdf_dimensions_variable (var, ncVarId, &createUnlimitedDim,
                                             &unlimitedDimId);
        netcdfVarId = create_netcdf_variable (var, ncVarId, unlimitedDimId);

        /* Leave the define mode before adding data */
        ncstatus = nc_enddef(ncid);
        if (ncstatus != NC_NOERR) handle_netcdf_error(ncstatus);

        get_cdf_variable_data (varId, var, ncVarId);

        /* Enter the define mode before writing netCDF variable attributes */
        /* and creating a variable.                                        */
        ncstatus = nc_redef(ncid);
        if (ncstatus != NC_NOERR) handle_netcdf_error(ncstatus);

        /* Get the variable attributes */
        for (attrId = 0; attrId < nAttrs; attrId++)
             get_cdf_attribute(attrId, VARIABLE_SCOPE, varId, netcdfVarId);
   }
#ifdef	AMDA

    if (set_file_time_coverage() == -1) {

	printf ("ERROR : unable to compute file time coverage\n");
    }

    if (rename_time_variable () == -1) {

        printf ("ERROR : uname to rename time variable\n");
    }


#endif
}


/*--------------------------------------------------------------------------
 *  This routine creates all netCDF dimensions from a global attribute if
 *  such attribute exists (likely the CDF is created by netcdf-to-cdf
 *  converter). It returns TRUE if dimensions are creaated, FLASE otherwise.
 *--------------------------------------------------------------------------*/
int create_netcdf_dimensions_attribute (int *unlimitedDimId)
{
   int     status,                             /* netCDF status code */
           i, id, value, len;                  
   long    numElems, numEntries;
   char    netcdfDimName[NC_MAX_NAME+1];       /* netCDF dimension name */
   char    valueStr[20+1];
   char    *ptr, entry[NC_MAX_NAME + 20 + 1];
   CDFstatus statusC;
   
   statusC = CDFlib (SELECT_, ATTR_NAME_, "DIMENSIONS_G",
                     GET_, ATTR_NUMgENTRIES_, &numEntries,
                     NULL_);
   if (statusC != CDF_OK) return FALSE;
   /* A CDF file that was created by netCDF-to-cdf */
   for (i = 0; i < (int) numEntries; ++i) {
       statusC = CDFlib (SELECT_, ATTR_NAME_, "DIMENSIONS_G",
                                  gENTRY_, (long) i,
                         GET_, gENTRY_DATA_, entry,
                               gENTRY_NUMELEMS_, &numElems,
                         NULL_);
       if (statusC != CDF_OK) continue;
       entry[numElems] = (char) '\0';
       ptr = strstr(entry, "=");
       if (ptr == NULL) continue;
       len = (int) (ptr - entry);
       strncpy(netcdfDimName, entry, len);
       strcpy(valueStr, ptr+1);
       netcdfDimName[len] = (char) '\0';
       if (strcmp(valueStr, "UNLIMITED") == 0) {
           status = nc_def_dim(ncid,               /* in  */
                               netcdfDimName,      /* in  */
                               NC_UNLIMITED,       /* in  */
                               unlimitedDimId);    /* out */
       } else {
           if (sscanf(valueStr, "%d", &value) != 1) continue;
           status = nc_def_dim(ncid,               /* in  */
                               netcdfDimName,      /* in  */
                               value,              /* in  */
                               &id);               /* out */
       }
       if (status != NC_NOERR) handle_netcdf_error(status);
   }
   return TRUE;
}


/*--------------------------------------------------------------------------
 *  This routine creates a netCDF dimension(s) from a variable.
 *--------------------------------------------------------------------------*/
void create_netcdf_dimensions_variable (CDFvar var, long varNum,
                                        int *createUnlimitedDim,
                                        int *unlimitedDimId)
{
   int     status,                             /* netCDF status code */
           i, j, dimensionCreated, id;
   long    dimensionality;
   char    netcdfDimName[NC_MAX_NAME+1];       /* netCDF dimension name */
   CDFstatus statusC;

   dimensionality = var.dimensionality;

   if (var.datatype == CDF_CHAR) {
       var.dimSizes[dimensionality] = var.numElements;
       dimensionality++;
   }
   else if (var.datatype == CDF_EPOCH) {
       var.dimSizes[dimensionality] = DD_TIME_STRING_LEN;
       dimensionality++;
   }
   else if (var.datatype == CDF_EPOCH16) {
       var.dimSizes[dimensionality] = DD_TIME_STRING_LEN;
       dimensionality++;
   }
   else if (var.datatype == CDF_TIME_TT2000) {
       var.dimSizes[dimensionality] = DD_TIME_STRING_LEN;
       dimensionality++;
   }

   if (*createUnlimitedDim) {
       if (var.recVariance == VARY) {
           status = nc_def_dim(ncid, "Time", NC_UNLIMITED,unlimitedDimId);
           if (status != NC_NOERR) handle_netcdf_error(status);
           *createUnlimitedDim = FALSE;
       }
   }
   for (i=0; i < dimensionality; i++) {
        dimensionCreated = FALSE;
        for (j=0; j < totNCdims; j++) {
             if (ncDims[j].size == var.dimSizes[i]) {
                 dimensionCreated = TRUE;
                 break;
             }
        }
        if (!dimensionCreated && var.dimSizes[i] > 1) {
            ncDims[totNCdims].size = var.dimSizes[i];
            sprintf (netcdfDimName, "dim%d", totNCdims);
            strcpy(ncDims[totNCdims].name, netcdfDimName);
            status = nc_def_dim(ncid,                      /* in  */
                                ncDims[totNCdims].name,    /* in  */
                                ncDims[totNCdims].size,    /* in  */
                                &ncDims[totNCdims].id);    /* out */
            if (status != NC_NOERR) handle_netcdf_error(status);
            totNCdims++;
        }
   }
}


/*--------------------------------------------------------------------------
 *  This routine creates a netCDF variable.
 *--------------------------------------------------------------------------*/
int create_netcdf_variable (CDFvar var,          /* in - CDF variable     */
                            long varNum,         /* in - CDF variable id  */
                            int unlimitedDimId)  /* in - unlimited dim ID */
{
   int     status,                       /* netCDF status code */
           i, j, k, id,
           varId,                        /* netCDF variable ID */
           nc_dimensionality,
           dimensionality,               /* netCDF dimensionality */
           dims[NC_MAX_DIMS];            /* netCDF dimensions */
   nc_type datatype;
   char *entry;
   char **dimStrings;
   int count = 0;
   long numElems;
   CDFstatus statusC;

   dimensionality = var.dimensionality;
   datatype = get_netcdf_datatype (var.datatype);

   /*********************************************************************
    * While the string value is treated as 0-d in CDF, it is treated as 
    * 1-D in netCDF.                                                   
    *********************************************************************/
   if (var.datatype == CDF_CHAR) {
       var.dimSizes[dimensionality] = var.numElements;
       dimensionality++;
   }

   /*********************************************************************
    * In CDF, CDF_EPOCH, CDF_EPOCH16 and CDF_TIME_TT2000 are used to
    * store a date and time value into a 8-byte real, 16-byte real or
    * 8-byte integer value, respectively.  Since netCDF 
    * doesn't support EPOCH, the CDF EPOCH variable needs to be translated 
    * as a string value. 
    *********************************************************************/
   else if (var.datatype == CDF_EPOCH) {
       var.dimSizes[dimensionality] = DD_TIME_STRING_LEN;
       dimensionality++;
   }
   else if (var.datatype == CDF_EPOCH16) {
       var.dimSizes[dimensionality] = DD_TIME_STRING_LEN;
       dimensionality++;
   }
   else if (var.datatype == CDF_TIME_TT2000) {
       var.dimSizes[dimensionality] = DD_TIME_STRING_LEN;
       dimensionality++;
   }

   /************************************************************************
    *  If CDF's record variance is true, then the netCDF's first dimension 
    *  reflects the record number.                               
    ************************************************************************/
   k = 0;
   if (var.recVariance == VARY) { 
       dims[k++] = unlimitedDimId;
       dimensionality++;
   }

   entry = (char *) malloc ((size_t) (dimensionality+1) * NC_MAX_NAME +
                            dimensionality + 1 );
   statusC = CDFlib (SELECT_, ATTR_NAME_, "DIMENSIONS_V",
                              zENTRY_, varNum,
                     GET_, zENTRY_DATA_, entry,
                           zENTRY_NUMELEMS_, &numElems,
                     NULL_);
   if (statusC == CDF_OK) { /* A CDF converted from netCDF-to-cdf. */
      entry[numElems] = (char) '\0';
      for (i = 0; i < strlen(entry); ++i) if (entry[i] == (char) ',') ++ count;
      ++count;
      dimStrings = (char **) malloc (sizeof(char *) * count);
      for (i = 0; i < count; ++i) {
        dimStrings[i] = (char *) malloc(NC_MAX_NAME + 1);
      }
      breakdown_DIMENSIONS_entry(entry, dimStrings);
      k = 0;
      for (j = 0; j < count; ++j) {
        status = nc_inq_dimid(ncid, dimStrings[j], &id);
        if (status != NC_NOERR) handle_netcdf_error(status);
        dims[k++] = id;
      }
      for (i = 0; i < count; ++i) free (dimStrings[i]);
      free (dimStrings);
   } else {
      for (i=0; i < dimensionality; i++) {
        for (j=0; j < totNCdims; j++) {
             if (ncDims[j].size == var.dimSizes[i]) {
                 dims[k++] = ncDims[j].id;
                 break;
             }
        }
      }
   }
   free (entry);
   /* Remove trailing blank spaces if there are any */
   for (i=strlen(var.name)-1; i >= 0; i--) {
        if (var.name[i] != ' ') {
            var.name[i+1] = '\0'; 
            break;
        }
   }

   /* Replace blank space(s) with underscore(s). */
   for (i=0; i < strlen(var.name); i++) {
        if (var.name[i] == ' ') var.name[i] = '_'; 
   }

/*  Exclude "false" dimension  */
   nc_dimensionality = dimensionality;
//    for (i=0; i < dimensionality; i++) {
//     if (  var.dimSizes[i] == 1 ) { 
//              nc_dimensionality--;
//              j = i;
//              break;
//         }
//   }
   
   /* Create a netCDF variable. */
   status = nc_def_var(ncid, var.name, datatype, nc_dimensionality, dims, &varId); 
   if (status != NC_NOERR) handle_netcdf_error(status);
   return varId;
}


/*--------------------------------------------------------------------------
 *  Get the CDF variable data and write the data just read into the 
 *  netCDF variable created in create_netcdf_variable.
 *--------------------------------------------------------------------------*/
void get_cdf_variable_data (long varId,      /* in - variable ID/number     */
                            CDFvar var,     /* in - CDF variable structure */
                            long ncVarId)  /* in - netCDF variable ID/number  */
{
   CDFstatus status;                         /* CDF status code    */
   int       ncstatus;                       /* netCDF status code */
   char      epString[EPOCH4_STRING_LEN+1];
   char      ep16String[EPOCH16_4_STRING_LEN+1];
   char      tt2000String[TT2000_3_STRING_LEN+1];
   double    epoch16[2];

    size_t start[NC_MAX_DIMS],              /* index for where to read first */ 
           count[NC_MAX_DIMS];              /* # of values to read           */

    int     i, j, k, divide, 
                  dimensionality,
                  numValues;                /* # of values on each record */
char	* ptr;
    char          *cPtr;
    signed char   *scPtr;
    unsigned char *ucPtr;
    short         *sPtr;
    unsigned short *usPtr;
    int           *iPtr;
    unsigned int  *uiPtr;
    long long     *jPtr, aLonglong;
    float         *fPtr;
    double        *dPtr;
    long          recNo, 
                  totRecs,              /* total # of records to read */
                  numRecsLeftToRead,
                  numRecs;       /* # of records to read and write at a time */ 

    j = 0;
    start[0]  = 0;
    numValues = 1;                      /* # of values on each CDF record */

    if (var.recVariance == VARY) {   /* Treat it as a netCDF record variable */
        start[j] = 0;                         /* start record #        */
        count[j++] = var.numRecs;             /* # of records to write */
    }

   dimensionality = var.dimensionality;

   if (var.datatype == CDF_CHAR) {
       var.dimSizes[dimensionality] = var.numElements;
       dimensionality++;
   }

   /*********************************************************************
    * In CDF, CDF_EPOCH and CDF_EPOCH16 are used to store a date and time
    * value into a 8-byte and 16-byte real value, respectively.  Since netCDF
    * doesn't support EPOCH, the CDF EPOCH variable needs to be translated
    * as a string value. Added newer 8-byte integer CDF_TIME_TT2000 data.
    *********************************************************************/
   else if (var.datatype == CDF_EPOCH) { 
       var.dimSizes[dimensionality] = DD_TIME_STRING_LEN;
       dimensionality++;
   }
   else if (var.datatype == CDF_EPOCH16) { 
       var.dimSizes[dimensionality] = DD_TIME_STRING_LEN;
       dimensionality++;
   }
   else if (var.datatype == CDF_TIME_TT2000) { 
       var.dimSizes[dimensionality] = DD_TIME_STRING_LEN;
       dimensionality++;
   }

    for (i=0; i < dimensionality; i++) {
         start[j] = 0;
         if (var.dimSizes[i] > 1) count[j++] = var.dimSizes[i];
         numValues *= var.dimSizes[i];
    }

    if (var.datatype == CDF_EPOCH)
        numValues /= DD_TIME_STRING_LEN;
    else if (var.datatype == CDF_EPOCH16)
        numValues /= DD_TIME_STRING_LEN;
    else if (var.datatype == CDF_TIME_TT2000)
        numValues /= DD_TIME_STRING_LEN;

    totRecs           = var.numRecs;      /* total # of records for this var */
    numRecsLeftToRead = var.numRecs;

    while (numRecsLeftToRead > 0) {
        recNo   = start[0];               /* record # to start reading */
        divide  = 1;
        numRecs = numRecsLeftToRead;      /* # of records to read at a time */

        switch (var.datatype) {
        case CDF_CHAR:
        case CDF_UCHAR:
            cPtr = NULL;
            while (cPtr == NULL) {
               cPtr = (char *) malloc (sizeof(char) * numValues * numRecs);
               if (cPtr == NULL) {
                   if (DEBUG) insufficient_memory();
                   divide *= 2;
                   numRecs = totRecs / divide;
               }
            }
            read_cdf_variable_data (varId,
                                    recNo,          /* starting record # */
                                    numRecs,        /* # of records to read */
                                    var.dimensionality,
                                    var.dimSizes,   /* dimesion sizes */
                                    cPtr);          /* data pointer   */
            if (DEBUG) {
                printf ("   retrieved CDF data = \n");
                for (k=0; k < numRecs; k++) {
                  printf("\"");
                  for (i=0; i < numValues; i++) 
                    printf ("%c", *(cPtr+(k*numValues+i)));
                  printf("\"\n");
                }
            }

            start[0] = 0;
            start[1] = 0;
            if (var.recVariance == VARY) {
                count[0] = numRecs;
            }

            if (DEBUG) {
                for (i=0; i < dimensionality; i++)
                     printf ("   start[%d] = %ld, count[%d] = %ld\n",
                             i, start[i], i, count[i]);
            }
            ncstatus = nc_put_vara_text(ncid, ncVarId, start, count, cPtr);
            if (ncstatus != NC_NOERR) handle_netcdf_error(ncstatus);
            if (DEBUG && ncstatus != NC_NOERR) {
                if (ncstatus != NC_NOERR) 
                    printf ("   Error putting data...\n");
                else
                    printf ("   Done putting data...\n");
            }
            free (cPtr);
            break;

        case CDF_BYTE:
        case CDF_INT1:
            scPtr = NULL;
            while (scPtr == NULL) {
               scPtr = 
                 (signed char *) malloc (sizeof(signed char)*numValues*numRecs);
               if (scPtr == NULL) {
                   if (DEBUG) insufficient_memory();
                   divide *= 2;
                   numRecs = totRecs / divide;
               }
            }
            read_cdf_variable_data (varId,
                                    recNo,           /* starting record # */
                                    numRecs,         /* # of records to read */
                                    var.dimensionality,
                                    var.dimSizes,    /* dimesion sizes */
                                    scPtr);          /* data pointer   */
            if (var.recVariance == VARY)
                count[0] = numRecs;
            ncstatus = nc_put_vara_schar(ncid, ncVarId, start, count, scPtr);
            if (ncstatus != NC_NOERR) handle_netcdf_error(ncstatus);
            free (scPtr);
            break;

        case CDF_UINT1:
            ucPtr = NULL;
            sPtr = NULL;
            while (ucPtr == NULL || sPtr == NULL) {
               ucPtr = 
                 (unsigned char *) malloc (sizeof(unsigned char)*numValues*numRecs);
               sPtr = 
                 (short *) malloc (sizeof(short)*numValues*numRecs);
               if (ucPtr == NULL || sPtr == NULL) {
                   if (DEBUG) insufficient_memory();
                   divide *= 2;
                   numRecs = totRecs / divide;
               }
            }
            read_cdf_variable_data (varId,
                                    recNo,           /* starting record # */
                                    numRecs,         /* # of records to read */
                                    var.dimensionality,
                                    var.dimSizes,    /* dimesion sizes */
                                    ucPtr);          /* data pointer   */
            if (var.recVariance == VARY)
                count[0] = numRecs;
            for (j = 0; j < numValues*numRecs; ++j) {
              *(sPtr+j) = (short) *(ucPtr+j);
            }
            ncstatus = nc_put_vara_short(ncid, ncVarId, start, count, sPtr);
            if (ncstatus != NC_NOERR) handle_netcdf_error(ncstatus);
            free (ucPtr);
            free (sPtr);
            break;

        case CDF_INT2:
            sPtr = NULL;
            while (sPtr == NULL) {
               sPtr = (short *) malloc (sizeof(short) * numValues * numRecs);
               if (sPtr == NULL) {
                   if (DEBUG) insufficient_memory();
                   divide *= 2;
                   numRecs = totRecs / divide;
               }
            }
            read_cdf_variable_data (varId,
                                    recNo,          /* starting record #    */
                                    numRecs,        /* # of records to read */
                                    var.dimensionality,
                                    var.dimSizes,   /* dimesion sizes */
                                    sPtr);          /* data pointer   */
            if (var.recVariance == VARY)
                count[0] = numRecs;
            ncstatus = nc_put_vara_short(ncid, ncVarId, start, count, sPtr);
            if (ncstatus != NC_NOERR) handle_netcdf_error(ncstatus);
            free (sPtr);
            break;

        case CDF_UINT2:
            usPtr = NULL;
            iPtr = NULL;
            while (usPtr == NULL || iPtr == NULL) {
               usPtr = (unsigned short *) malloc (sizeof(unsigned short) * numValues * numRecs);
               iPtr = (int *) malloc (sizeof(int) * numValues * numRecs);
               if (usPtr == NULL || iPtr == NULL) {
                   if (DEBUG) insufficient_memory();
                   divide *= 2;
                   numRecs = totRecs / divide;
               }
            }
            read_cdf_variable_data (varId,
                                    recNo,          /* starting record #    */
                                    numRecs,        /* # of records to read */
                                    var.dimensionality,
                                    var.dimSizes,   /* dimesion sizes */
                                    usPtr);         /* data pointer   */
            if (var.recVariance == VARY)
                count[0] = numRecs;
            for (j = 0; j < numValues*numRecs; ++j) {
              *(iPtr+j) = (int) *(usPtr+j);
            }
            ncstatus = nc_put_vara_int(ncid, ncVarId, start, count, iPtr);
            if (ncstatus != NC_NOERR) handle_netcdf_error(ncstatus);
            free (usPtr);
            free (iPtr);
            break;

        case CDF_INT4:
            iPtr = NULL;
            while (iPtr == NULL) {
               iPtr = (int *) malloc (sizeof(int) * numValues * numRecs);
               if (iPtr == NULL) {
                   if (DEBUG) insufficient_memory();
                   divide *= 2;
                   numRecs = totRecs / divide;
               }
            }
            read_cdf_variable_data (varId,
                                    recNo,          /* starting record #    */
                                    numRecs,        /* # of records to read */
                                    var.dimensionality,
                                    var.dimSizes,   /* dimesion sizes */
                                    iPtr);          /* data pointer   */
            if (var.recVariance == VARY)
                count[0] = numRecs;
            ncstatus = nc_put_vara_int(ncid, ncVarId, start, count, iPtr);
            if (ncstatus != NC_NOERR) handle_netcdf_error(ncstatus);
            free (iPtr);
            break;

        case CDF_UINT4:
            uiPtr = NULL;
            dPtr = NULL;
            while (uiPtr == NULL || dPtr == NULL) {
               uiPtr = (unsigned int *) malloc (sizeof(unsigned int) * numValues * numRecs);
               dPtr = (double *) malloc (sizeof(double) * numValues * numRecs);
               if (uiPtr == NULL) {
                   if (DEBUG) insufficient_memory();
                   divide *= 2;
                   numRecs = totRecs / divide;
               }
            }
            read_cdf_variable_data (varId,
                                    recNo,          /* starting record #    */
                                    numRecs,        /* # of records to read */
                                    var.dimensionality,
                                    var.dimSizes,   /* dimesion sizes */
                                    uiPtr);          /* data pointer   */
            if (var.recVariance == VARY)
                count[0] = numRecs;
            for (j = 0; j < numValues*numRecs; ++j) {
              *(dPtr+j) = (double) *(uiPtr+j);
            }
            ncstatus = nc_put_vara_double(ncid, ncVarId, start, count, dPtr);
            if (ncstatus != NC_NOERR) handle_netcdf_error(ncstatus);
            free (uiPtr);
            free (dPtr);
            break;

        case CDF_INT8:
            jPtr = NULL;
            dPtr = NULL;
            while (jPtr == NULL || dPtr == NULL) {
               jPtr = (long long *) malloc (sizeof(long long) * numValues * numRecs);
               dPtr = (double *) malloc (sizeof(double) * numValues * numRecs);
               if (jPtr == NULL || dPtr == NULL) {
                   if (DEBUG) insufficient_memory();
                   divide *= 2;
                   numRecs = totRecs / divide;
               }
            }
            read_cdf_variable_data (varId,
                                    recNo,          /* starting record #    */
                                    numRecs,        /* # of records to read */
                                    var.dimensionality,
                                    var.dimSizes,   /* dimesion sizes */
                                    jPtr);          /* data pointer   */
            if (var.recVariance == VARY)
                count[0] = numRecs;
            for (j = 0; j < numValues*numRecs; ++j) {
              *(dPtr+j) = (double) *(jPtr+j);
            }
            ncstatus = nc_put_vara_double(ncid, ncVarId, start, count, dPtr);
            if (ncstatus != NC_NOERR) handle_netcdf_error(ncstatus);
            free (jPtr);
            free (dPtr);
            break;

        case CDF_FLOAT:
        case CDF_REAL4:
            fPtr = NULL;
            while (fPtr == NULL) {
               fPtr = (float *) malloc (sizeof(float) * numValues * numRecs);
               if (fPtr == NULL) {
                   if (DEBUG) insufficient_memory();
                   divide *= 2;
                   numRecs = totRecs / divide;
               }
            }
            read_cdf_variable_data (varId,
                                    recNo,          /* starting record #    */
                                    numRecs,        /* # of records to read */
                                    var.dimensionality,
                                    var.dimSizes,   /* dimesion sizes */
                                    fPtr);          /* data pointer   */
            if (var.recVariance == VARY)
                count[0] = numRecs;
            ncstatus = nc_put_vara_float(ncid, ncVarId, start, count, fPtr);
            if (ncstatus != NC_NOERR) handle_netcdf_error(ncstatus);
            free (fPtr);
            break;

        case CDF_DOUBLE:
        case CDF_REAL8:
            dPtr = NULL;
            while (dPtr == NULL) {
               dPtr = (double *) malloc (sizeof(double) * numValues * numRecs);
               if (dPtr == NULL) {
                   if (DEBUG) insufficient_memory();
                   divide *= 2;
                   numRecs = totRecs / divide;
               }
            }
            read_cdf_variable_data (varId,
                                    recNo,           /* starting record # */
                                    numRecs,         /* # of records to read */
                                    var.dimensionality,
                                    var.dimSizes,    /* dimesion sizes */
                                    dPtr);           /* data pointer   */
            if (var.recVariance == VARY)
                count[0] = numRecs;

            ncstatus = nc_put_vara_double(ncid, ncVarId, start, count, dPtr);
            if (ncstatus != NC_NOERR) handle_netcdf_error(ncstatus);
            free (dPtr);
            break;

        case CDF_EPOCH:
            dPtr = NULL;
            while (dPtr == NULL) {
               dPtr = (double *) malloc (sizeof(double)*numValues*numRecs);
               if (dPtr == NULL) {
                   if (DEBUG) insufficient_memory();
                   divide *= 2;
                   numRecs = totRecs / divide;
               }
            }
            read_cdf_variable_data (varId,
                                    recNo,           /* starting record # */
                                    numRecs,         /* # of records to read */
                                    var.dimensionality,
                                    var.dimSizes,    /* dimesion sizes */
                                    dPtr);           /* data pointer   */
            if (var.recVariance == VARY)
                count[0] = numRecs;

            cPtr = (char *) malloc (sizeof(char) * numValues * numRecs *
                                    DD_TIME_STRING_LEN + 1);
            if (cPtr == NULL)
                memory_error("get_cdf_variable_data", "CDF_EPOCH");

            ptr = cPtr;

            /* Get all the EPOCH values into a single string. */
            for (i=0; i < numRecs * numValues; i++) {
                 encodeEPOCH4 (*(dPtr+i), epString); 
                 strcpy (ptr, isotime_to_dd_time (epString));
                 ptr += DD_TIME_STRING_LEN;
            }
            ncstatus = nc_put_vara_text(ncid, ncVarId, start, count, cPtr);
            if (ncstatus != NC_NOERR) handle_netcdf_error(ncstatus);
            free (cPtr);
            free (dPtr);
            break;

        case CDF_EPOCH16:
            dPtr = NULL;
            while (dPtr == NULL) {
               dPtr = (double *) malloc (sizeof(double) * numValues*numRecs*2);
               if (dPtr == NULL) {
                   if (DEBUG) insufficient_memory();
                   divide *= 2;
                   numRecs = totRecs / divide;
               }
            }
            read_cdf_variable_data (varId,
                                    recNo,           /* starting record # */
                                    numRecs,         /* # of records to read */
                                    var.dimensionality,
                                    var.dimSizes,    /* dimesion sizes */
                                    dPtr);           /* data pointer   */
            if (var.recVariance == VARY)
                count[0] = numRecs;

            cPtr = (char *) malloc (sizeof(char) * numValues * numRecs *
                                    DD_TIME_STRING_LEN + 1);
            if (cPtr == NULL)
                memory_error("get_cdf_variable_data", "CDF_EPOCH16");

            ptr = cPtr;

            /* Get all the EPOCH16 values into a single string. */
            for (i=0; i < numRecs * numValues; i++) {
                 epoch16[0] = *(dPtr+i*2);
                 epoch16[1] = *(dPtr+i*2+1);
                 encodeEPOCH16_4 (epoch16, ep16String);
                 strcpy (ptr, isotime_to_dd_time (ep16String));
                 ptr += DD_TIME_STRING_LEN;
            }
            printf(" %d %d\n", count[0], count[1]);
            ncstatus = nc_put_vara_text(ncid, ncVarId, start, count, cPtr);
            if (ncstatus != NC_NOERR) handle_netcdf_error(ncstatus);
            free (cPtr);
            free (dPtr);
            break;

        case CDF_TIME_TT2000:
            jPtr = NULL;
            while (jPtr == NULL) {
               jPtr = (long long *) malloc (sizeof(long long)*numValues*numRecs);
               if (jPtr == NULL) {
                   if (DEBUG) insufficient_memory();
                   divide *= 2;
                   numRecs = totRecs / divide;
               }
            }
            read_cdf_variable_data (varId,
                                    recNo,           /* starting record # */
                                    numRecs,         /* # of records to read */
                                    var.dimensionality,
                                    var.dimSizes,    /* dimesion sizes */
                                    jPtr);           /* data pointer   */
            if (var.recVariance == VARY)
                count[0] = numRecs;

            cPtr = (char *) malloc (sizeof(char) * numValues * numRecs *
                                    DD_TIME_STRING_LEN + 1);
            if (cPtr == NULL)
                memory_error("get_cdf_variable_data", "CDF_EPOCH");

            ptr = cPtr;

            /* Get all the TT2000 values into a single string. */
            for (i=0; i < numRecs * numValues; i++) {
              //   encodeTT2000 (*(jPtr+i), tt2000String);
                 CDF_TT2000_to_UTC_string(*(jPtr+i), tt2000String, 3);
                 strcpy (ptr, isotime_to_dd_time (tt2000String));
                 ptr += DD_TIME_STRING_LEN;
            }
            ncstatus = nc_put_vara_text(ncid, ncVarId, start, count, cPtr);
            if (ncstatus != NC_NOERR) handle_netcdf_error(ncstatus);
            free (cPtr);
            free (jPtr);
            break;

        default:
            printf ("** Error in getVarData: bad type");
        }    

        numRecsLeftToRead = totRecs - numRecs;
        if (numRecsLeftToRead > 0) {
            totRecs  = numRecsLeftToRead;
            start[0] = numRecs;
        }
    }       /* end of the 'while' loop */

}


/*--------------------------------------------------------------------------
 *  This routine returns the string representation of the given CDF 
 *  datatype.
 *--------------------------------------------------------------------------*/
char *  cdf_str_datatype (long type)
{
    switch (type) {
      case CDF_BYTE:
         return "CDF_BYTE";

      case CDF_INT1:
         return "CDF_INT1";

      case CDF_CHAR:
         return "CDF_CHAR";

      case CDF_INT2:
         return "CDF_INT2";

      case CDF_UCHAR:
         return "CDF_UCHAR";

      case CDF_UINT1:
         return "CDF_UINT1";

      case CDF_INT4:
         return "CDF_INT4";

      case CDF_INT8:
         return "CDF_INT8";

      case CDF_UINT2:
         return "CDF_UINT2";

      case CDF_FLOAT:
         return "CDF_FLOAT";

      case CDF_REAL4:
         return "CDF_REAL4";

      case CDF_DOUBLE:
         return "CDF_DOUBLE";

      case CDF_REAL8:
         return "CDF_REAL8";

      case CDF_UINT4:
         return "CDF_UINT4";

      case CDF_EPOCH:
         return "CDF_EPOCH";

      case CDF_EPOCH16:
         return "CDF_EPOCH16";

      case CDF_TIME_TT2000:
         return "CDF_TIME_TT2000";
      
      default:
         return "BAD_CDF_TYPE";

    }
}


/*--------------------------------------------------------------------------
 *  This routine returns the string representation of the given netCDF 
 *  datatype.
 *--------------------------------------------------------------------------*/
char *  NC_datatype (nc_type type)
{
    switch (type) {
      case NC_BYTE:
        return "byte";
      case NC_CHAR:
        return "char";
      case NC_SHORT:
        return "short";   
      case NC_INT:
        return "int";
      case NC_FLOAT:
        return "float";
      case NC_DOUBLE:      
        return "double";
      default:
        return "UNKNOWN";
    }
}


/*--------------------------------------------------------------------------
 *  This routine returns the netCDF datatype for the given CDF datatype.
 *  All unsigned types are bumped up, either to double the size, or to
 *  a double. CDF's epoch types are converted to string.
 *--------------------------------------------------------------------------*/
nc_type get_netcdf_datatype (long type)
{
    nc_type  netcdf_type;

    switch (type) {
      case CDF_BYTE:
      case CDF_INT1:
        netcdf_type = NC_BYTE;
        break;

      case CDF_CHAR:
      case CDF_UCHAR:
      case CDF_EPOCH:
      case CDF_EPOCH16:
      case CDF_TIME_TT2000:
        netcdf_type = NC_CHAR;
        break;

      case CDF_UINT1:
        netcdf_type = NC_SHORT;
        break;

      case CDF_INT2:
        netcdf_type = NC_SHORT;
        break;

      case CDF_UINT2:
        netcdf_type = NC_INT;
        break;

      case CDF_INT4:
        netcdf_type = NC_INT;
        break;

      case CDF_UINT4:
        netcdf_type = NC_DOUBLE;
        break;

      case CDF_INT8:
        netcdf_type = NC_DOUBLE;
        break;

      case CDF_FLOAT:
      case CDF_REAL4:
        netcdf_type = NC_FLOAT;
        break;

      case CDF_DOUBLE:
      case CDF_REAL8:
        netcdf_type = NC_DOUBLE;
        break;

      default: { 
        printf ("** ERROR: Unknown CDF datatype\n");
        exit (1);
      }
    }
    return netcdf_type;
}


/*---------------------------------------------------------------------------
 *  Read the CDF variable data for the given CDF variable number.
 *---------------------------------------------------------------------------*/
void read_cdf_variable_data (long varNum,      /* CDF variable number        */
                             long recNo,       /* record # for start reading */
                             long recCount,    /* # of records to read       */
                             long dim,         /* CDF dimensionality         */
                             long dimSizes[],  /* CDF dimesion sizes         */
                             void *data)       /* data pointer               */
{
   CDFstatus status;
   int       i;
   long      recInterval,                /* No. of recors to skip            */
             dimIndices[CDF_MAX_DIMS],   /* Beginning location of the array  */
                                         /* to be dumped                     */
             dimIntervals[CDF_MAX_DIMS]; /* No. of elements to skip          */

   recInterval = 1L;             /* # of records to skip between writes   */

   for (i=0; i < dim; i++) {
        dimIndices[i]   = 0;     /* Dump data from the beginning of array */
        dimIntervals[i] = 1;     /* Dump all the elements in the array    */
   }

   status = CDFlib (SELECT_,zVAR_, varNum,
                            zVAR_RECNUMBER_, recNo,
                            zVAR_RECCOUNT_, recCount,
                            zVAR_RECINTERVAL_, recInterval,
                            zVAR_DIMINDICES_, dimIndices,
                            zVAR_DIMCOUNTS_, dimSizes,
                            zVAR_DIMINTERVALS_, dimIntervals,
                    GET_, zVAR_HYPERDATA_, data,
                    NULL_);
   if (status != CDF_OK) cdf_status_handler (status, "GET_, zVAR_HYPERDATA_");
}



/*--------------------------------------------------------------------------
 *  Remove the filepath from a file name.
 *
 *  Example:
 *      /home/data/mydata.txt => mydata.txt
 *--------------------------------------------------------------------------*/
void removeFilepath (char *fileName) {
    char *ptr;

    ptr = (char *) strrchr(fileName, '/');        /* Unix file path separator */
    if (ptr != NULL) {
        ptr++;
        strcpy(fileName, ptr);
    }
    else {
       ptr = (char *) strrchr(fileName, '\\');     /* Windows file separator */
       if (ptr != NULL) {
           ptr++;
           strcpy(fileName, ptr);
       }
    }
}


/*--------------------------------------------------------------------------
 *  Handles a CDF error.
 *--------------------------------------------------------------------------*/
void cdf_status_handler (CDFstatus status, char *source)
{
   char  message[CDF_STATUSTEXT_LEN+1];

   CDFerror (status, message);              /* Get the appropriate message */

   if (status < CDF_WARN) {
       printf ("An error has occurred, halting...\n"); 
       printf ("%s\n", message);
       printf ("** Error source: %s\n", source);
       exit (status);
   }
   else if (status < CDF_OK) {
       printf ("Warning, function may not have compeleted as expected...\n");
       printf ("%s\n", message);
   }
   else if (status > CDF_OK) {
       printf ("Function compeleted successfully, but be advised that...\n");
       printf ("%s\n", message);
   }
}


/*--------------------------------------------------------------------------
 *  Handles a netCDF error.
 *--------------------------------------------------------------------------*/
void handle_netcdf_error(int status) {
  fprintf(stderr, "%s\n", nc_strerror(status));
}


/*--------------------------------------------------------------------------
 *  Handles a memory allocation error.
 *--------------------------------------------------------------------------*/
void memory_error(char *source, char *datatype) {
   printf ("** Memory allocation error occurred in %s. data type = %s", 
           source, datatype);
   exit (1);
}

void insufficient_memory () {
   printf("Insufficient memory to load all the records at once");
}


/*--------------------------------------------------------------------------*/
void usage()
{
   printf ("\nDescription:\n");
   printf ("    This program converts a CDF file into a netCDF file.");
   printf ("\n");
   printf ("Usage: cdf-to-netCDF -[Options] <CDF file name>\n");
   printf ("\n");
   printf ("Options:\n");
   printf ("    -map <mapfile>    Use the user-supplied mapping file.\n");
   printf ("    -debug            Show debug information.\n");
   printf ("\n");
   printf ("Examples of usage: \n");
   printf ("1) cdf-to-netCDF test.cdf\n");
   printf ("   will convert the test.cdf file into the test.nc file.\n\n");
   printf ("2) cdf-to-netCDF -map mymap.dat test.cdf\n");
   printf ("   will convert the test.cdf file into the test.nc file using\n");
   printf ("   the user-supplied mapping file called 'mymap.dat' instead\n");
   printf ("   of using the default cdf-to-netCDF mapping file.\n");
   printf ("\n");
   exit(1);
}

void parseCmdLine (int argc, char *argv[])
{
   int  i;
   char *nextArg;

   for (i=0; i < argc; i++) {
        if (strcmp(argv[i],"-map") == 0) {
            nextArg = getNextArgument(argc, argv, i);
            if (strcmp(nextArg, "No next argument") == 0 ||
                *(nextArg+0) == '-')
                errorMsg("** Error - mapping file is not defined");
            else
                 strcpy(mappingFile, nextArg);
        }
        else if (strcmp(argv[i],"-debug") == 0)
            DEBUG = TRUE;
   }
}


char * getNextArgument (int argc, char *argv[], int currentIndex)
{
    char *nextArg, msg[30];
    int  nextIndex;

    nextIndex  = currentIndex+1;
    if (nextIndex == argc) {
        strcpy (msg, "No next argument");
        nextArg = msg;
    }
    else
        nextArg = argv[nextIndex];

    return nextArg;
}

void errorMsg (char *msg)
{
   printf ("%s\n", msg);
   exit (1);
}


void map_CDF_attr_to_netCDF (char *searchAttr,     /* in - CDF attr name     */
                             char *mappedAttrName) /* out - netCDF attr name */
{
   int i;

   strcpy(mappedAttrName, searchAttr);

   for (i=0; i < totAttrsInMappingFile; i++) {
        if (strcmp(cdfAttrNames[i], searchAttr) == 0) {
            strcpy(mappedAttrName, netcdfAttrNames[i]);
            break;
        }
   }
}

void breakdown_DIMENSIONS_entry (char *entry,     /* in -  a DIMENSIONS entry */
                                 char **dimStrings) /* out - dimesion names */
{
   char *ptr, *ptr1;
   int i = 0, j;

   ptr = entry;
   ptr1 = strstr(ptr, ",");
   i = 0;
   while (ptr1 != NULL) {
     j = ptr1 - ptr;
     strncpy (dimStrings[i], ptr, (size_t)j);
     dimStrings[i][j] = (char) '\0';
     ptr = ptr1 + 1;
     ptr1 = strstr(ptr, ",");
     ++i;
   }
   if (ptr != NULL) strcpy (dimStrings[i], ptr);
}