Example #1
0
CPLErr HDF4Dataset::ReadGlobalAttributes( int32 iHandler )
{
/* -------------------------------------------------------------------- */
/*     Obtain number of SDSs and global attributes in input file.       */
/* -------------------------------------------------------------------- */
    int32 nDatasets = 0;
    int32 nAttributes = 0;
    if ( SDfileinfo( iHandler, &nDatasets, &nAttributes ) != 0 )
        return CE_Failure;

    char szAttrName[H4_MAX_NC_NAME] = {};  // TODO: Get this off the stack.

    // Loop through the all attributes
    for( int32 iAttribute = 0; iAttribute < nAttributes; iAttribute++ )
    {
        int32 iNumType = 0;
        int32 nValues = 0;

        // Get information about the attribute. Note that the first
        // parameter is an SD interface identifier.
        SDattrinfo( iHandler, iAttribute, szAttrName, &iNumType, &nValues );

        if ( STARTS_WITH_CI(szAttrName, "coremetadata")    ||
             STARTS_WITH_CI(szAttrName, "archivemetadata.") ||
             STARTS_WITH_CI(szAttrName, "productmetadata.") ||
             STARTS_WITH_CI(szAttrName, "badpixelinformation") ||
             STARTS_WITH_CI(szAttrName, "product_summary") ||
             STARTS_WITH_CI(szAttrName, "dem_specific") ||
             STARTS_WITH_CI(szAttrName, "bts_specific") ||
             STARTS_WITH_CI(szAttrName, "etse_specific") ||
             STARTS_WITH_CI(szAttrName, "dst_specific") ||
             STARTS_WITH_CI(szAttrName, "acv_specific") ||
             STARTS_WITH_CI(szAttrName, "act_specific") ||
             STARTS_WITH_CI(szAttrName, "etst_specific") ||
             STARTS_WITH_CI(szAttrName, "level_1_carryover") )
        {
            bIsHDFEOS = true;
            papszGlobalMetadata
                = TranslateHDF4EOSAttributes(
                    iHandler, iAttribute, nValues, papszGlobalMetadata );
        }

        // Skip "StructMetadata.N" records. We will fetch information
        // from them using HDF-EOS API
        else if ( STARTS_WITH_CI(szAttrName, "structmetadata.") )
        {
            bIsHDFEOS = true;
            continue;
        }

        else
        {
            papszGlobalMetadata = TranslateHDF4Attributes(
                iHandler, iAttribute, szAttrName, iNumType, nValues,
                papszGlobalMetadata );
        }
    }

    return CE_None;
}
Example #2
0
/* Given the file ID and variable ID, retrieve information about the
 * specified attribute. Return success (0) if the attribute information 
 * was obtained sucessfully, otherwise this function returns the failure 
 * status (-1).
 */
int cuattinq_hdf(CuFile* file, int varid, const char* name, CuType* datatype, int* len){
	int err, saveopts;
	hdf_type dtype;
	int t_len;

	int32 sds_id, attr_index;
	char attr_name[H4_MAX_NC_NAME];

	/* Get the identifier for the first data set or file. */
	if (varid == CU_GLOBAL)
		sds_id = file->internid1;
	else
		sds_id = SDselect(file->internid1, varid);

        /* Find the data set attribute name index. */
        attr_index = SDfindattr(sds_id, name);

        /* Get information about the data set attribute. */
        if((err = SDattrinfo(sds_id, 
                            attr_index, 
                            attr_name, 
                            &dtype, 
                            (len ? len : &t_len))) != -1)
		if(datatype) {
			cumapdatatype_hdf(dtype, datatype);
			if (*datatype==CuInvalidType)
				return -1;
		}

	/* Return success ( 0 ), or failure ( -1 ). */
	return (err == -1 ? -1 : CU_SUCCESS);
}
Example #3
0
void ossimHdf4SubDataset::initMeta()
{
   m_meta.clear();

   //insert name first
   m_meta.push_back("name: " + ossimString(m_hdfDataType + ":" + m_sd_name));

   char	attrName[100];
   int32 numValues;
   int32 dataType;

   for (ossim_int32 i = 0; i < m_attributes; i++ )
   {
      // Get information about the attribute. Note that the first
      // parameter is an SD interface identifier.
      SDattrinfo(m_sds_id, i, attrName, &dataType, &numValues);
      
      ossim_int32 size = getDataTypeSize(dataType);
      char* attrValue = new char[size * numValues + 1];
      
      SDreadattr(m_sds_id, i, attrValue);

      if ( dataType == DFNT_CHAR8 || dataType == DFNT_UCHAR8 )
      {
         attrValue[numValues] = '\0';
         m_meta.push_back(ossimString(attrName) + ": " + ossimString(attrValue).trim());
      }
      else
      {
         ossimString values = getAttribuitValues(dataType, numValues, attrValue);
         m_meta.push_back(ossimString(attrName) + ": " + values);
      }
      delete [] attrValue;
   }
}
Example #4
0
/* Read metadata from hdfFile and write temp file. */
intn readAttr(int32 hdfFile, FILE *metadataFile, char *attr)
{
  intn status = 0;
  int32 attr_index, data_type, n_values;
  char *metadata, attr_name[MAX_NC_NAME];

  /* Look for attribute */
  attr_index = SDfindattr(hdfFile, attr);
  if (attr_index == -1) 
  {
/*    fprintf(stdout, "Unable to find attribute %s.\n", attr);
    fflush(stdout); 
*/
    return (1);
  }
 
  /* Get size of attribute  */
  status = SDattrinfo(hdfFile, attr_index, attr_name, &data_type, &n_values);
  if (status == -1) 
  {
    fprintf(stdout, "SDattrinfo failed for existing attribute %s.\n", attr);
    fflush(stdout);
    return (1);
  }
 
  /* Allocate memory for attribute contents (add one character for the end
     of string character) */
  metadata = (char *) malloc(n_values+1);
  if (metadata == NULL) 
  {
    fprintf(stdout, "Unable to allocate %d bytes for %s.\n", (int) n_values,
        attr);
    fflush(stdout);
    return (1);
  }
 
  /* Read attribute */
  status = SDreadattr(hdfFile, attr_index, metadata);
  if (status == -1 || !strcmp (metadata, "")) 
  {
    fprintf(stdout, "Unable to read attribute %s.\n", attr);
    fflush(stdout);
    free(metadata);
    return (1);
  }

  fprintf(metadataFile, "%s", metadata);

  /* Clean up and return success */
  free(metadata);
  return (0);
}
Example #5
0
/* Given the file ID and variable ID, get information about the 
 * data set attribute.
 */
int cuattname_hdf(CuFile* file, int varid, int attnum, char* name){
        int32 sds_id, num_type, count, status;
        char attr_name[H4_MAX_NC_NAME];

        /* Get the identifier for the data set or file. */
	if (varid == CU_GLOBAL)
		sds_id = file->internid1;
	else
		sds_id = SDselect(file->internid1, varid);

        /* Get information about the data set attribute. */
        status = SDattrinfo(sds_id, attnum, name, &num_type, &count);

	/* Return success ( 0 ), or failure ( -1 ). */
	return (status == -1 ? -1 : CU_SUCCESS);

}
Example #6
0
static SDSAttInfo *read_attributes(const char *path, int obj_id, int natts)
{
    SDSAttInfo *att, *att_list = NULL;
    char buf[H4_MAX_NC_NAME + 1];
    int32 type, nvalues;
    int i, status;

    for (i = 0; i < natts; i++) {
        memset(buf, 0, sizeof(buf));
        status = SDattrinfo(obj_id, i, buf, &type, &nvalues);
        CHECK_HDF_ERROR(path, status);

        if (!strncasecmp("coremetadata",     buf, 12) ||
            !strncasecmp("structmetadata",   buf, 14) ||
            !strncasecmp("archivemetadata",  buf, 15) ||
            !strncasecmp("archivedmetadata", buf, 16))
            continue; // skip these useless attributes

        // read attribute data
        size_t typesize = h4_typesize(type);
        if (type == DFNT_CHAR8 || type == DFNT_UCHAR8)
            nvalues++;
        void *data = xmalloc(typesize * nvalues);
        status = SDreadattr(obj_id, i, data);
        CHECK_HDF_ERROR(path, status);
        if (type == DFNT_CHAR8 || type == DFNT_UCHAR8)
            ((char *)data)[nvalues - 1] = '\0';

        // stick attribute in struct in list
        att = NEW(SDSAttInfo);
        att->name = xstrdup(buf);
        att->type = h4_to_sdstype(type);
        att->count = (size_t)nvalues;
        att->bytes = typesize;
        att->data.v = data;

        att->next = att_list;
        att_list = att;
    }
    return (SDSAttInfo *)list_reverse((List *)att_list);
}
Example #7
0
/* Given the file ID, variable ID, and attribute name, retrieve attribute 
 * values. Return success (0) if the attribute information was obtained 
 * sucessfully, otherwise this function returns the failure status (-1).
 */
int cuattget_hdf(CuFile* file, int varid, const char* name, void* value){
	int32 sds_id, attr_index, num_type, count;
	int32 status;
	int8 *buffer;
	char attr_name[H4_MAX_NC_NAME];

        /* Get the identifier for the data set or file. */
	if (varid == CU_GLOBAL)
		sds_id = file->internid1;
	else
		sds_id = SDselect(file->internid1, varid);

        /* Find the data set attribute name index. */
        attr_index = SDfindattr(sds_id, name);

        /* Get information about the data set attribute. */
        SDattrinfo(sds_id, attr_index, attr_name, &num_type, &count);

        /* Read the attribute data and return success ( 0 ),
 	 * or failure ( -1 ).
	 */
        return (SDreadattr(sds_id, attr_index, value) == -1 ? -1 : CU_SUCCESS);
}
Example #8
0
/* Get information about the dimension. Return success (0) if the 
 * dimension information  was obtained sucessfully, otherwise this 
 * function returns the failure status (-1).
 */
int cudiminq_hdf(CuFile* file, int dimidx, char* dimname, char* dimunits, CuType* dataType, CuDimType* dimtype, int* varid, long* length){
	char dname[H4_MAX_NC_NAME+1];
	int cdfid;
	int dimvarid; /* HDF ID of variable associated with this dimension. */
	int found;   /* True iff a dimension variable was found. */
	int ndims;
	int get_dimid;
	int saveopts;
	long len;
	hdf_type hdftype, hdfunitstype;
	int natts;
	char varname[H4_MAX_NC_NAME+1];
	int attlen;

	int32 sds_id, attr_index, datatype, nattrs;
	int32 dim_sizes[H4_MAX_VAR_DIMS];
	char attr_name[H4_MAX_NC_NAME];
	int32 dimid;

	cdfid = file->internid1;
	if((dimid = cudimid2hdf(file, dimidx))==-1)
		return -1;

	/* Get information about the selected dimension. */
	if(SDdiminfo(dimid, dname, &len, &datatype, &nattrs)==-1){
           	cuerrorreport_hdf();
                return -1;
        }

	if(dimname) strncpy(dimname,dname,CU_MAX_NAME);
	if(length) *length = len;

        /* HDF dimensions are always global */
	if(varid) *varid = CU_GLOBAL;
	if(dimtype) *dimtype = CuGlobalDim;

        /* Inquire a variable with */
        /* - the same name as dimname, */
        /* - a single dimension, and */
        /* - a dimension name which equals the variable name. */
	if((dimvarid = SDnametoindex(cdfid, dname)) != -1){
                sds_id = SDselect(cdfid, dimvarid);
                if (SDgetinfo(sds_id, varname, &ndims, dim_sizes,
                                   &hdftype, &natts) == -1){
           	        cuerrorreport_hdf();
			return -1;
		}

                /* pass back the dimension id */
                if ((get_dimid = SDgetdimid(sds_id, 0)) == -1){
           	        cuerrorreport_hdf();
                        return -1;
                }

		found = (ndims == 1 && get_dimid == dimid);
	}
	else
		found = 0;

	/* If dimension variable was found, */
	/* inquire the units attribute (if any) */
	if(found){
                sds_id = SDselect(cdfid, dimvarid);

		/* Set the length of an unlimited dimension. */
		if (len==0 && length) *length = dim_sizes[0];

        	/* Find the data set attribute name index. */
        	attr_index = SDfindattr(sds_id, "units");

        	/* Get information about the data set attribute. */
        	if(SDattrinfo(sds_id, attr_index, attr_name, &hdfunitstype, 
                    &attlen) != -1 && hdfunitstype == DFNT_CHAR) {
			if(dimunits && SDreadattr(sds_id, attr_index, dimunits)==-1)
				return -1;
		}
	    /* Dimension variable was found, but no character units string */
		else{
			if(dimunits) strcpy(dimunits,"");
		}
		if(dataType) {
			cumapdatatype_hdf(hdftype, dataType);
			if (*dataType==CuInvalidType)
				return -1;
		}
	}
	else{
		/* The dimension variable was not found: */
		/* return default units and datatype */
		if(dimunits) strcpy(dimunits,"");
		if(dataType) *dataType = CuFloat;
	}

	/* Return success ( 0 ). */
	return CU_SUCCESS;
}
Example #9
0
bool GetAttrString(int32 sds_id, Myhdf_attr_t *attr, char *string)
/* 
!C******************************************************************************

!Description: 'GetAttrString' reads an string (char8) attribute.

!Input Parameters:
 sds_id         SDS id
 attr           Attribute data structure; the following field is used:
                   name

!Output Parameters:
 attr           Attribute data structure; the following field is updated:
                   id, type, nval
 val            An array of values from the HDF attribute (converted from the
                  native type to type 'double'.
 (returns)      Status:
                  'true' = okay
		  'false' = error reading the attribute information

!Team Unique Header:

 ! Design Notes:
   1. The values in the attribute are converted from the stored type to 
      'double' type.
   2. The HDF file is assumed to be open for SD (Science Data) access.
   3. If the attribute has more than 'MYHDF_MAX_NATTR_VAL' values, an error
      status is returned.
   4. Error messages are handled with the 'RETURN_ERROR' macro.
!END****************************************************************************
*/
{
  char8 val_char8[MYHDF_MAX_NATTR_VAL];
  int i,i_length;
  char z_name[80];
  void *buf;
  
  if ((attr->id = SDfindattr(sds_id, attr->name)) == HDF_ERROR)
    RETURN_ERROR("getting attribute id", "GetAttrString", false);
  if (SDattrinfo(sds_id, attr->id, z_name, &attr->type, &attr->nval) == 
      HDF_ERROR)
    RETURN_ERROR("getting attribute info", "GetAttrString", false);
  /* printf("attr name: %s\n", z_name); */

  if (attr->nval < 1)
    RETURN_ERROR("no attribute value", "GetAttrString", false);
  if (attr->nval > MYHDF_MAX_NATTR_VAL) 
    RETURN_ERROR("too many attribute values", "GetAttrString", false);
  if (attr->type != DFNT_CHAR8) 
    RETURN_ERROR("invalid type - not string (char8)", "GetAttrString", false);

  if (sizeof(char8) == sizeof(char))
    buf = (void *)string;
  else
    buf = (void *)val_char8;

  if (SDreadattr(sds_id, attr->id, buf) == HDF_ERROR) 
    RETURN_ERROR("reading attribute", "GetAttrString", false);

  if (sizeof(char8) != sizeof(char)) {
    for (i = 0; i < attr->nval; i++) 
      string[i] = (char)val_char8[i];
  }

  i_length= (int)attr->nval;
  string[i_length]= '\0';

  return true;
}
Example #10
0
bool GetAttrDouble(int32 sds_id, Myhdf_attr_t *attr, double *val)
/* 
!C******************************************************************************

!Description: 'GetAttrDouble' reads an attribute into a parameter of type
 'double'.
 
!Input Parameters:
 sds_id         SDS id
 attr           Attribute data structure; the following field is used:
                   name

!Output Parameters:
 attr           Attribute data structure; the following field is updated:
                   id, type, nval
 val            An array of values from the HDF attribute (converted from the
                  native type to type 'double'.
 (returns)      Status:
                  'true' = okay
		  'false' = error reading the attribute information

!Team Unique Header:

 ! Design Notes:
   1. The values in the attribute are converted from the stored type to 
      'double' type.
   2. The HDF file is assumed to be open for SD (Science Data) access.
   3. If the attribute has more than 'MYHDF_MAX_NATTR_VAL' values, an error
      status is returned.
   4. Error messages are handled with the 'RETURN_ERROR' macro.
!END****************************************************************************
*/
{
  char8 val_char8[MYHDF_MAX_NATTR_VAL];
  uint8 val_int8[MYHDF_MAX_NATTR_VAL];
  uint8 val_uint8[MYHDF_MAX_NATTR_VAL];
  int16 val_int16[MYHDF_MAX_NATTR_VAL];
  uint16 val_uint16[MYHDF_MAX_NATTR_VAL];
  int32 val_int32[MYHDF_MAX_NATTR_VAL];
  uint32 val_uint32[MYHDF_MAX_NATTR_VAL];
  float32 val_float32[MYHDF_MAX_NATTR_VAL];
  float64 val_float64[MYHDF_MAX_NATTR_VAL];
  int i;
  char z_name[80];
  
  if ((attr->id = SDfindattr(sds_id, attr->name)) == HDF_ERROR)
    RETURN_ERROR("getting attribute id", "GetAttrDouble", false);
  if (SDattrinfo(sds_id, attr->id, z_name, &attr->type, &attr->nval) == 
      HDF_ERROR)
    RETURN_ERROR("getting attribute info", "GetAttrDouble", false);
  /* printf("attr name: %s\n", z_name); */

  if (attr->nval < 1)
    RETURN_ERROR("no attribute value", "GetAttrDouble", false);
  if (attr->nval > MYHDF_MAX_NATTR_VAL) 
    RETURN_ERROR("too many attribute values", "GetAttrDouble", false);

  switch (attr->type) {
  case DFNT_CHAR8:
    if (SDreadattr(sds_id, attr->id, val_char8) == HDF_ERROR) 
      RETURN_ERROR("reading attribute (char8)", "GetAttrDouble", false);
    for (i = 0; i < attr->nval; i++) 
      val[i] = (double)val_char8[i];
    break;
  case DFNT_INT8:
    if (SDreadattr(sds_id, attr->id, val_int8) == HDF_ERROR) 
      RETURN_ERROR("reading attribute (int8)", "GetAttrDouble", false);
    for (i = 0; i < attr->nval; i++) 
      val[i] = (double)val_int8[i];
    break;
  case DFNT_UINT8:
    if (SDreadattr(sds_id, attr->id, val_uint8) == HDF_ERROR) 
      RETURN_ERROR("reading attribute (uint8)", "GetAttrDouble", false);
    for (i = 0; i < attr->nval; i++) 
      val[i] = (double)val_uint8[i];
    break;
  case DFNT_INT16:
    if (SDreadattr(sds_id, attr->id, val_int16) == HDF_ERROR) 
      RETURN_ERROR("reading attribute (int16)", "GetAttrDouble", false);
    for (i = 0; i < attr->nval; i++) 
      val[i] = (double)val_int16[i];
    break;
  case DFNT_UINT16:
    if (SDreadattr(sds_id, attr->id, val_uint16) == HDF_ERROR) 
      RETURN_ERROR("reading attribute (uint16)", "GetAttrDouble", false);
    for (i = 0; i < attr->nval; i++) 
      val[i] = (double)val_uint16[i];
    break;
  case DFNT_INT32:
    if (SDreadattr(sds_id, attr->id, val_int32) == HDF_ERROR) 
      RETURN_ERROR("reading attribute (int32)", "GetAttrDouble", false);
    for (i = 0; i < attr->nval; i++) 
      val[i] = (double)val_int32[i];
    break;
  case DFNT_UINT32:
    if (SDreadattr(sds_id, attr->id, val_uint32) == HDF_ERROR) 
      RETURN_ERROR("reading attribute (uint32)", "GetAttrDouble", false);
    for (i = 0; i < attr->nval; i++) 
      val[i] = (double)val_uint32[i];
    break;
  case DFNT_FLOAT32:
    if (SDreadattr(sds_id, attr->id, val_float32) == HDF_ERROR) 
      RETURN_ERROR("reading attribute (float32)", "GetAttrDouble", false);
    for (i = 0; i < attr->nval; i++) 
      val[i] = (double)val_float32[i];
    break;
  case DFNT_FLOAT64:
    if (SDreadattr(sds_id, attr->id, val_float64) == HDF_ERROR) 
      RETURN_ERROR("reading attribute (float64)", "GetAttrDouble", false);
    for (i = 0; i < attr->nval; i++) 
      val[i] = (double)val_float64[i];
    break;
  default:
    RETURN_ERROR("unknown attribute type", "GetAttrDouble", false);
  }

  return true;
}
Example #11
0
void metareader(int32 sd_id, char *type_of_meta, char *metastring, int32 *count, char *data)
{
#define XMAXLENGTH 1000
int32 i, ii, j, n_attr1, n_sets1, count1, number_type1, n_val;
int start,within,wasjustobject;
int obj_offset[10],n_obj;
char attrib[XMAXLENGTH], attrib1[XMAXLENGTH];
char *charattr;
char line[XMAXLENGTH], objs[XMAXLENGTH];
char lhs[XMAXLENGTH], rhs[XMAXLENGTH];
char uppers[XMAXLENGTH];
void get_a_line(char *text, int lengthoftext, int *start, char line[XMAXLENGTH]);

SDfileinfo(sd_id, &n_sets1, &n_attr1);
for (j=0;j<n_attr1;j++) {
     SDattrinfo(sd_id, j, attrib1, &number_type1, &count1);
     attrib[0] = '\0';  
     for (i=0;i<strlen(attrib1);i++) attrib[i] = toupper(attrib1[i]);  
     attrib[i] = '\0';  
     start = 0;
     if (strstr(attrib,type_of_meta)) {
         if ((charattr = (char *)malloc((count1+1)*sizeof(char))) == NULL) {
	         printf("Out of memory, array 'charattr'\n");
		 return;
	                                                                   }
         SDreadattr(sd_id, j, charattr);
         count1 = strlen(charattr);
         if (!strcmp(type_of_meta, metastring)) {  /* signal for no need to parse metadata */
	    strcpy(data, charattr);
	    return;
	    }


	 n_obj=0;
	 wasjustobject=0;
	 objs[0] = '\0';
	 do { 
	      line[0] = '\0';
	      get_a_line(charattr,count1+1,&start,line);

	      /* Get rid of whitespace, if not inside "..." characters. */
	      within=0;
              for (i=0,ii=0;i<strlen(line);i++) {
	          if (line[i] == '"') {
		     if (!within) within=1;
		     else if (within) within=0;
		     }
	          if (within) line[ii++] = line[i]; 
		  else {
		     if (line[i] != ' ') line[ii++] = line[i];  
		     }
		  }
	      line[ii] = '\0';

	      /* Get left-hand-side, rhs of equation */
	      lhs[0] = rhs[0] = '\0';
	      if (strchr(line,'=')) {
                 for (i=0,ii=0;i<(strchr(line,'=')-line);i++) {
		        lhs[ii++]=line[i];
	             }
	         lhs[ii] = '\0';
		 i++;
                 for (ii=0;i<strlen(line)-1;i++,ii++) {
		        rhs[ii]=line[i];
	             }
	         rhs[ii] = '\0';
		 }
	
	      if (!strcmp(lhs,"OBJECT")) {
	           wasjustobject=1;
	           obj_offset[n_obj++]=strlen(objs);
	           strcat(objs,rhs);
	          }
	      if (!strcmp(lhs,"GROUP")) wasjustobject=0;
	      if ((!strcmp(lhs,"CLASS"))&&(wasjustobject)) {
		   for (i=0;i<strlen(rhs)-1;i++) rhs[i]=rhs[i+1];
	           rhs[i-1] = '\0';
	           strcat(objs,rhs);
	          }
	      if (!strcmp(lhs,"END_OBJECT")) {
	           if (n_obj > 0)
	              objs[obj_offset[--n_obj]] = '\0';
	          }
	      if (!strcmp(lhs,"NUM_VAL")) {
	           n_val=atoi(rhs);
	          }
	      
	      if (!strcmp(lhs,"VALUE")) {
		     /*printf("!%s! %d *%s*%s*\n", objs,n_obj,lhs,rhs);*/
	         if (!strcmp(objs, metastring)) {
	             strcpy(data,rhs);
		     *count=n_val;
		     /*printf("!%s! %d *%s*%s*\n", objs,n_obj,lhs,rhs);*/
	                }
	            }
	      if ((!strcmp(lhs,"\0"))&&(wasjustobject)) {
		     /*printf("!%s! %d *%s*%s*\n", objs,n_obj,lhs,rhs);*/
	         if (!strcmp(objs, metastring)) {
	             strcat(data,line);
		     *count+=n_val;
		     /*printf("!%s! %d *%s*%s*\n", objs,n_obj,lhs,rhs);*/
	                }
	            }
		    
	      /* special case for StructMetadata */
	      if  ( (strstr(type_of_meta, "STRUCTMETADATA")) && ( strstr(lhs, metastring))  ) strcat(data, rhs);
	      	    
	    } while ( line[0] != '\0') ;
	 
	 
	 free(charattr);  
                                      }


                        }  /* for (j=0;j<n_attr1;j++) */

}
Example #12
0
int main(int ac, char **av)
{

  char input_file_path[256], output_file_path[256];
  char hdf4sds_name[256], hdf4sds_attr_name[256];
  char hdf4sds_str_attr_buff[256];
  
  
  int hdf4sd_id, hdf4access_mode, hdf4status, hdf4n_datasets, hdf4n_file_attrs,
    hdf4sds_id, hdf4sds_index, hdf4sds_rank, hdf4sds_data_type,
    hdf4sds_n_attrs, hdf4sds_attr_data_type, hdf4sds_attr_n_values,
    hdf4sds_num_elements;

  int hdf4sds_dim_sizes[8], hdf4sds_read_start[8], hdf4sds_read_stride[8];

  float *hdf4sds_flt_buff;

  hid_t hdf5file_id, hdf5dataset_id, hdf5space_id, hdf5attr_id,
    hdf5attr_space_id, hdf5str_type;
  herr_t hdf5status;
  hsize_t hdf5dataset_dims[8], hdf5attr_size;


  /* Get input file name from the command line, and create output file name */

  if (ac < 2) {
    fprintf(stderr, "Usage is: hdf4tohdf5 inputfile outputfile\n");
    fprintf(stderr, "If no output file is given, inputfile.h5 will be produced.\n");
    return 1;
  }
  strcpy(input_file_path, av[1]);

  if (ac > 2) {
    strcpy(output_file_path, av[2]);
  } else {
    strcpy(output_file_path, input_file_path);
    strcat(output_file_path, ".h5");
  }

  /* Open hdf4 file */

  hdf4access_mode = DFACC_READ;
  hdf4sd_id = SDstart(input_file_path, hdf4access_mode);

  hdf4status = SDfileinfo(hdf4sd_id, &hdf4n_datasets, &hdf4n_file_attrs);
  if (hdf4status == FAIL) {
    fprintf(stderr, "Reading hdf4 file failed.  Returning.\n");
    return 1;
  }

  
#ifdef DEBUG
  printf("Id: %i, Datasets: %i, File_attrs: %i\n", hdf4sd_id, hdf4n_datasets,
	 hdf4n_file_attrs);
#endif



  /* Open hdf5 file */
 
  hdf5file_id = H5Fcreate(output_file_path, H5F_ACC_TRUNC, H5P_DEFAULT, 
			  H5P_DEFAULT);
  
  if (hdf5file_id < 0) {
    fprintf(stderr, "Failed to open HDF5 file %s for writing.\n",
	    output_file_path);
    return 1;
  }


  /* Loop through datasets */

  for(hdf4sds_index = 0; hdf4sds_index < hdf4n_datasets; hdf4sds_index++) {
    hdf4sds_id = SDselect(hdf4sd_id, hdf4sds_index);
    hdf4status = SDgetinfo(hdf4sds_id, hdf4sds_name, &hdf4sds_rank,
			 hdf4sds_dim_sizes, &hdf4sds_data_type,
			 &hdf4sds_n_attrs);
#ifdef DEBUG    
    printf("\nsds_id: %i, sds_name: %s, sds_rank: %i, sds_data_type: %i,\nn_attrs_: %i, dim_sizes: %i %i %i\n", hdf4sds_id, hdf4sds_name, hdf4sds_rank, hdf4sds_data_type, hdf4sds_n_attrs, hdf4sds_dim_sizes[0], hdf4sds_dim_sizes[1], hdf4sds_dim_sizes[2]);
#endif

    /* Get data from SDS into buffer */
    hdf4sds_num_elements = hdf4sds_dim_sizes[0];
    hdf4sds_read_start[0] = 0;
    hdf4sds_read_stride[0] = 1;
    if (hdf4sds_rank > 1){
      for(int i=1; i < hdf4sds_rank; i++) {
	hdf4sds_num_elements = hdf4sds_num_elements*hdf4sds_dim_sizes[i];
	hdf4sds_read_start[i] = 0;
	hdf4sds_read_stride[i] = 1;
      }
    }
#ifdef DEBUG
    printf("Total number of elements for this sds: %i\n",
	   hdf4sds_num_elements);      
#endif    

    /* Allocate the buffer to read in the data */
    hdf4sds_flt_buff = malloc((sizeof (float))*hdf4sds_num_elements);

    hdf4status = SDreaddata(hdf4sds_id, hdf4sds_read_start,
			    hdf4sds_read_stride, hdf4sds_dim_sizes,
			    (VOIDP)hdf4sds_flt_buff);
    

    /* Have all of the data from the hdf4 file,
       now need to load it into hdf5 */

    for (int i=0; i < hdf4sds_rank; i++) {
          hdf5dataset_dims[i] = (hsize_t)hdf4sds_dim_sizes[i];
    }

    hdf5space_id = H5Screate_simple(hdf4sds_rank, hdf5dataset_dims,
				    hdf5dataset_dims);
    if (hdf4sds_data_type == 5) { //Floats
      hdf5dataset_id = H5Dcreate(hdf5file_id, hdf4sds_name, H5T_IEEE_F32LE,
				 hdf5space_id, H5P_DEFAULT);
      
      hdf5status = H5Dwrite(hdf5dataset_id, H5T_IEEE_F32LE, H5S_ALL, H5S_ALL, 
			    H5P_DEFAULT, hdf4sds_flt_buff);

      /* We've finished reading in the data. Free the hdf4 data buffer. */
      free(hdf4sds_flt_buff);

      /*Assign the HDF5 attributes */
      
      for(int i=0; i < hdf4sds_n_attrs; i++) {
	hdf4status = SDattrinfo(hdf4sds_id, i, hdf4sds_attr_name,
			      &hdf4sds_attr_data_type, &hdf4sds_attr_n_values);
#ifdef DEBUG
	printf("Attribute %i: Name = %s, Data type = %i, N_values = %i\n", 
	       i, hdf4sds_attr_name, hdf4sds_attr_data_type,
	       hdf4sds_attr_n_values);
#endif	
	if(hdf4sds_attr_data_type == 4) { /* Read the string attributes */
	  hdf4status = SDreadattr(hdf4sds_id, i, (VOIDP)hdf4sds_str_attr_buff);
	  hdf4sds_str_attr_buff[hdf4sds_attr_n_values]='\0'; 
#ifdef DEBUG
	  printf("Value: %s\n", hdf4sds_str_attr_buff);
#endif
	  hdf5attr_size = (hsize_t)hdf4sds_attr_n_values;
	  
	  hdf5attr_space_id = H5Screate(H5S_SCALAR);
	  hdf5str_type = H5Tcopy(H5T_C_S1);
	  hdf5status = H5Tset_size(hdf5str_type,
				   (size_t)hdf4sds_attr_n_values);
	  hdf5attr_id = H5Acreate(hdf5dataset_id, hdf4sds_attr_name,
				  hdf5str_type, hdf5attr_space_id,
				  H5P_DEFAULT);
	  hdf5status =  H5Awrite(hdf5attr_id, hdf5str_type,
				 hdf4sds_str_attr_buff);
	  hdf5status = H5Aclose(hdf5attr_id);
	}
      }
      hdf5status = H5Dclose(hdf5dataset_id);        
    }
    hdf5status = H5Sclose(hdf5space_id);				
    hdf4status = SDendaccess(hdf4sds_id);
  }



  /* Close access to hdf4 file */

  hdf4status = SDend(hdf4sd_id);



  /* Close access to HDF5 file */
  
  hdf5status = H5Fclose(hdf5file_id);

  return 0;
}
Example #13
0
/*************************************************************************

MODULE: TransferAttr

PURPOSE: 
    This module reads the user-defined core, archive, and structural metadata
    from the original (input) HDF file and writes it as new user-defined
    metadata in the new HDF file.  The new file-level attribute namefields in
    the output HDF file are of the form "Old+<original field name>" and can 
    be extracted from the output HDF file using the SDfindattr and SDattrinfo
    commands from the HDf library.

RETURN VALUE:
Type = bool
Value    	Description
-----		-----------
true            Successful completion
false           Error processing

HISTORY:
Version    Date     Programmer      Code     Reason
-------    ----     ----------      ----     ------
           01/04    Gail Schmidt             Original Development based on
                                             Doug Ilg's metadmp.c program.

NOTES:

**************************************************************************/
bool TransferAttr
(
    int32 fid_old,	/* I: SDS id # for the old HDF file */ 
    int32 fid_new,	/* I: SDS id # for the new HDF file */ 
    char *attr		/* I: Filename handle of the attribute to move */ 
)

{
    intn status;            /* this is the var that holds return val */
    int32 my_attr_index;    /* holds return val from SDfindattr */ 
    int32 data_type;	    /* holds attribute's data type */ 
    int32 n_values;         /* stores # of vals of the attribute */
    char *file_data = NULL;         /* char ptr used to allocate temp space
                                       during transfer of attribute info */
    char attr_name[MAX_NC_NAME];    /* holds attribute's name */
    char new_attr_name[MAX_NC_NAME + 3];    /* holds new attr name */

    /* look for attribute in the old HDF file */
    my_attr_index = SDfindattr( fid_old, attr );

    /* only proceed if the attribute was found */
    if ( my_attr_index == -1 )
        return( false );
 
    /* get size of old HDF file attribute  */
    status = SDattrinfo( fid_old, my_attr_index, attr_name, &data_type,
        &n_values );

    /* only proceed if successful read of attribute info */
    if ( status == -1 )
        return( false );

    /* attempt to allocate memory for old HDF file attribute contents (add
       one character for the end of string character) */
    file_data = ( char * ) calloc( n_values+1, sizeof(char) );
    if ( file_data == NULL )
        LOG_RETURN_ERROR( "unable to allocate memory for reading old HDF file "
            "metadata", "TransferAttr", false);

    /* read attribute from the old HDF file */
    status = SDreadattr( fid_old, my_attr_index, file_data );
    if(status == -1 )
    {
        free( file_data );
        return( false );
    }

    /* modify the attribute name from old HDF file prior to appending
       metadata to new HDF file; put prefix "Old" in front of old name */
    strcpy( new_attr_name, "Old" );
    strcat( new_attr_name, attr_name );
    new_attr_name[ strlen(new_attr_name) + 1 ] = '\0';

    /* attempt to write old metadata to output HDF file */
    status = SDsetattr( fid_new, new_attr_name, DFNT_CHAR8, strlen(file_data),
        (VOIDP)file_data );
 
    /* free dynamically allocated memory */
    free( file_data );

    return ( true );
}
Example #14
0
bool TransferAttributes( Param_t *param, int32 old_fid, int32 new_fid,
  int proc_sds )
{
    int j = 0;
    int curr_band, curr_sds;
    int32 old_sds, new_sds;
    int32 sds_index;
    int32 nattr, attr_index;
    int32 data_type, n_values;
    char attr_name[1024], sds_name[1024], *buffer = NULL;
    int32 rank;
    int32 dims[10];

    /* loop through the remaining SDS's and add them only if their output
       resolution is the same as the current SDSs resolution */
    for ( curr_sds = proc_sds; curr_sds < param->num_input_sds; curr_sds++ )
    {
        /* if this SDS is not the same resolution as proc_sds, then do not
           output metadata attributes for the SDS */
        if ( param->output_pixel_size[curr_sds] !=
             param->output_pixel_size[proc_sds] )
            continue;

        /* get the SDS index */
        sds_index = SDnametoindex( old_fid,
            param->input_sds_name_list[curr_sds] );

        /* open old SDS */
        old_sds = SDselect( old_fid, sds_index );

        /* get various SDS info */
        SDgetinfo( old_sds, sds_name, &rank, dims, &data_type, &nattr );

        /* loop through the bands in this SDS, writing the same info
           to each band that was processed */
        for ( curr_band = 0; curr_band < param->input_sds_nbands[curr_sds];
              curr_band++ )
        {
            /* if this band wasn't processed, skip to the next band */
            if (param->input_sds_bands[curr_sds][curr_band] == 0)
                continue;

            /* open new SDS, for this SDS/band combination */
            new_sds = SDselect( new_fid, j++ );

            /* for each SDS attribute */
            for ( attr_index = 0; attr_index < nattr; attr_index++ )
            {
                /* get SDS attribute info */
                SDattrinfo( old_sds, attr_index, attr_name, &data_type,
                    &n_values );

                /* allocate memory */
                switch (data_type)
                {
                    case 6:
                    case 26:
                    case 27:
                        buffer = calloc(n_values, 8);
                        break;

                    case 5:
                    case 24:
                    case 25:
                        buffer = calloc(n_values, 4);
                        break;

                    case 22:
                    case 23:
                        buffer = calloc(n_values, 2);
                        break;

                    default:
                        buffer = calloc(n_values, 1);
                        break;
                }

                /* make sure the buffer was allocated */
                if ( buffer == NULL )
                    LOG_RETURN_ERROR( "unable to allocate space for buffer",
                        "TransferAttributes", false);

                /* get SDS attribute values */
                if ( SDreadattr( old_sds, attr_index, buffer ) == -1 )
                    LOG_RETURN_ERROR("unable to find attribute in old HDF file",
                        "TransferAttributes", false);

                /* write SDS attribute to output file */
                if (SDsetattr( new_sds, attr_name, data_type, n_values,
                    buffer ) == -1 )
                    LOG_RETURN_ERROR( "unable to write attribute to new HDF "
                        "file", "TransferAttributes", false);
            } /* for attr_index */

            /* free memory */
            free(buffer);

            /* close current SDS */
            SDendaccess( new_sds );
        } /* for curr_band */

        /* close current SDS */
        SDendaccess( old_sds );
    } /* for curr_sds */

    return true;
}
Example #15
0
int main(int argc, char *argv[])
{
	char *MOD021KMfile, *MOD02HKMfile, *MOD02QKMfile;
	char *filename;	/* output file */

	FILE *fp;
	int outfile_exists;

	char *ancpath;
	SDS sds[Nitems], outsds[Nbands], dem, height;
	int32 MOD02QKMfile_id, MOD02HKMfile_id, MOD021KMfile_id;
	int32 sd_id, attr_index, count, num_type;

	int ib, j, iscan, Nscans, irow, jcol, idx, crsidx;
	int nbands;

	char *SDSlocatorQKM[Nitems] = {"EV_250_RefSB", "EV_250_RefSB",
		"EV_500_RefSB", "EV_500_RefSB", "EV_500_RefSB",
		"EV_500_RefSB", "EV_500_RefSB","EV_1KM_RefSB", "EV_1KM_RefSB",
		"EV_1KM_RefSB", "EV_1KM_RefSB", "EV_1KM_RefSB", "EV_1KM_RefSB",
		"EV_1KM_RefSB", "EV_1KM_RefSB", "EV_1KM_RefSB", "SolarZenith",
		"SensorZenith", "SolarAzimuth", "SensorAzimuth", "Longitude",
		"Latitude"};

	char *SDSlocatorHKM[Nitems] = {"EV_500_RefSB",
		"EV_500_RefSB", "EV_500_RefSB", "EV_500_RefSB",
		"EV_500_RefSB", "EV_500_RefSB", "EV_500_RefSB",
		"Reflectance_Img_I1","Reflectance_Img_I2","Reflectance_Img_I3",
		"EV_1KM_RefSB","EV_1KM_RefSB","EV_1KM_RefSB", "EV_1KM_RefSB",
		"EV_1KM_RefSB", "EV_1KM_RefSB","SolZenAng_Mod",
		"SenZenAng_Mod", "SolAziAng_Mod", "SenAziAng_Mod", "Longitude",
		"Latitude" };

	char *SDSlocator1KM[Nitems] = {"Reflectance_Mod_M5",
		"Reflectance_Mod_M7", "Reflectance_Mod_M3",
		"Reflectance_Mod_M4", "Reflectance_Mod_M8",
		"Reflectance_Mod_M10",  "Reflectance_Mod_M11",
		"EV_1KM_RefSB", "EV_1KM_RefSB", "EV_1KM_RefSB", "EV_1KM_RefSB",
		"EV_1KM_RefSB", "EV_1KM_RefSB",
		"EV_1KM_RefSB", "EV_1KM_RefSB", "EV_1KM_RefSB", "SolZenAng_Mod",
		"SenZenAng_Mod", "SolAziAng_Mod", "SenAziAng_Mod", "Longitude",
		"Latitude"};

	char indexlocator[Nitems] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 7,
		9, 10, 0, 0, 0, 0, 0, 0};

	char numtypelocator[Nitems] = {DFNT_UINT16, DFNT_UINT16, DFNT_UINT16,
		DFNT_UINT16, DFNT_UINT16, DFNT_UINT16, DFNT_UINT16,
		DFNT_UINT16, DFNT_UINT16, DFNT_UINT16, DFNT_UINT16,
		DFNT_UINT16, DFNT_UINT16, DFNT_UINT16, DFNT_UINT16,
		DFNT_UINT16,DFNT_FLOAT32 ,DFNT_FLOAT32 ,DFNT_FLOAT32 ,DFNT_FLOAT32 ,
		DFNT_FLOAT32, DFNT_FLOAT32};

	uint16 *l1bdata[Nbands];
	float32 *sola, *solz, *sena, *senz, *solzfill;
	float32 *lon, *lat, *lonfill, *latfill;
	char *attr_name;
	float64 scale_factor[Nitems], add_offset[Nitems];

	unsigned char process[Nbands];

	float refl, *mus, muv, phi;
	float *rhoray, *sphalb, *TtotraytH2O, *tOG;
	int aggfactor, crsrow1, crsrow2, crscol1, crscol2;
	int crsidx11, crsidx12, crsidx21, crsidx22;
	float mus0, mus11, mus12, mus21, mus22;
	float fractrow, fractcol, t, u;
	float rhoray0, rhoray11, rhoray12, rhoray21, rhoray22;
	float sphalb0, sphalb11, sphalb12, sphalb21, sphalb22;
	float reflmin=REFLMIN, reflmax=REFLMAX, maxsolz=MAXSOLZ;
	int bad;

	int write_mode = DFACC_CREATE;

	int st;

	size_t nbytes;

	int ftype;

	extern char *optarg;
	extern int optind, opterr;
	int option_index = 0;

	static int verbose, overwrite;
	static int gzip, append;

	static int output500m, output1km;
	static int sealevel, TOA, nearest;

	char dummy[H4_MAX_NC_NAME];

	enum{OPT_BANDS = 1, OPT_RANGE, OPT_OUTFILE, OPT_MAXSOLZ};

	static struct option long_options[] = {
		{"1km",		no_argument,		&output1km, 1},
		{"500m",	no_argument,		&output500m, 1},
		{"append",	no_argument,		&append, 1},
		{"bands",	required_argument,	(int *) NULL, OPT_BANDS},
		{"gzip",	no_argument,		&gzip,	1},
		{"maxsolz",	required_argument,	(int *) NULL, OPT_MAXSOLZ},
		{"nearest",	no_argument,		&nearest, 1},
		{"of",		required_argument,	(int *) NULL, OPT_OUTFILE},
		{"overwrite",	no_argument,		&overwrite, 1},
		{"range",	required_argument,	(int *) NULL, OPT_RANGE},
		{"sealevel",	no_argument,		&sealevel, 1},
		{"toa",		no_argument,		&TOA, 1},
		{"verbose",	no_argument,		&verbose, 1},
		{(char *) NULL, 0, (int *) NULL, 0}
		};

	int c;

	static char dem_filename_buff[MAXNAMELENGTH];


	MOD021KMfile = MOD02HKMfile = MOD02QKMfile = (char *) NULL;
	filename = (char *) NULL;

	for (ib = 0; ib < Nbands; ib++) process[ib] = FALSE;

	/* default settings */
	output500m = output1km = 0;
	append = gzip = nearest = sealevel = TOA = verbose = overwrite = 0;


	while ((c = getopt_long(argc, argv, "", long_options,
		&option_index)) >= 0) {

		switch (c) {
			case 0:
				/* do nothing for options which will have a
				flag set automatically by getopt_long() */
				break;

			case OPT_BANDS:
				if (parse_bands(optarg, process)) {
					fputs("Invalid band(s) specified.\n",
						stderr);
					exit(1);
					}
				break;

			case OPT_RANGE:
				if (sscanf(optarg, "%g,%g", &reflmin, &reflmax) != 2) {
					fputs("Error parsing reflectance range.\n", stderr);
					exit(1);
					}

				if ( range_check(reflmin, 0.0F, 1.0F) ||
					range_check(reflmax, 0.0F, 1.0F) ||
					(reflmin >= reflmax) ) {
					fputs("Invalid reflectance range.\n", stderr);
					exit(1);
					}

				printf("Output reflectance range [%.3f,%.3f] requested.\n",
					reflmin, reflmax);
				break;

			case OPT_MAXSOLZ:
				maxsolz = (float) atof(optarg);
				if (range_check(maxsolz, 0.0F, 90.0F)) {
					fputs("Invalid max. solar zenith angle.\n", stderr);
					exit(1);
					}
				break;

			case OPT_OUTFILE:
				filename = optarg;
				break;

			default:
				usage();
				exit(1);
			}
		}

	if (append) write_mode = DFACC_RDWR;

	/* at least one input file must follow */
	if (optind >= argc) {
		usage();
		exit(1);
		}


	/* check for conflicting options */
	if (overwrite && append) {
		fputs("Options --overwrite and --append are mutually exclusive.\n",
			stderr);
		exit(1);
		}
	if (sealevel && TOA) {
		fputs("Options --sealevel and --toa are mutually exclusive.\n",
			stderr);
		exit(1);
		}

#ifdef DEBUG
printf("append = %d\n", append);
if (filename) printf("output filename = %s\n", filename);
printf("output1km = %d\n", (int) output1km);
printf("output500m = %d\n", (int) output500m);
printf("gzip = %d\n", gzip);
printf("nearest = %d\n", nearest);
printf("sealevel = %d\n", sealevel);
printf("TOA = %d\n", TOA);
printf("Max. solar zenith angle: %g degrees\n", maxsolz);
if (filename) printf("Output file: %s.", filename);
#endif



	if (verbose) puts("Verbose mode requested.");
	if (overwrite) puts("Overwriting existing output file.");
	if (gzip) puts("Gzip compression requested.");
	if (sealevel) puts("Sea-level atmospheric correction requested. Terrain height ignored.");
	if (TOA) puts("Top-of-the-atmosphere reflectance requested. No atmospheric correction.");
	if (output1km) puts("1km-resolution output requested.");
	if (nearest) puts("Interpolation disabled.");



	/* parse input file names */
	for (j = optind; j < argc; j++) {
		ftype = input_file_type(argv[j]);

		switch (ftype) {
			case INPUT_1KM:
				MOD021KMfile = argv[j];
				break;

			case INPUT_500M:
				MOD02HKMfile = argv[j];
				break;

			case INPUT_250M:
				MOD02QKMfile = argv[j];
				break;

			default:
				fprintf(stderr,
					"Unrecognized input file \"%s\".\n",
					argv[j]);
					MOD021KMfile = argv[j];
/*				exit(1); I commented that*/
				break;
			}
		}



	if (verbose && MOD021KMfile)
		printf("Input geolocation file: %s\n", MOD021KMfile);


	/* output file name is mandatory */
	if (!filename) {
		fputs("Missing output file name.\n", stderr);
		exit(1);
		}

#ifdef DEBUG
if (MOD021KMfile) printf("MOD/MYD021KMfile = %s\n", MOD021KMfile);
if (MOD02HKMfile) printf("MOD/MYD02HKMfile = %s\n", MOD02HKMfile);
if (MOD02QKMfile) printf("MOD/MYD02QKMfile = %s\n", MOD02QKMfile);
#endif


	/*
	1KM file is mandatory for angles.
	HKM file is mandatory unless 1-km output is requested.
	QKM file is mandatory unless 500-m or 1-km output is requested.
	*/
/*	if ( (!MOD021KMfile) ||
		(!MOD02HKMfile && !output1km) ||
		(!MOD02QKMfile && !output500m && !output1km) ) {
		fputs("Invalid combination of input files.\n", stderr);
		exit(1);
		}
commented that too Eric*/

	/* count number of bands to process */
	for (ib = nbands = 0; ib < Nbands; ib++) if (process[ib]) nbands++;
	if (nbands < 1) {
		process[BAND1] = process[BAND3] = process[BAND4] = TRUE;
		if (verbose)
			puts("No band(s) specified.  Default is bands 1, 3, and 4.");
		}


	/* open input files */
  if ( MOD02QKMfile && (!output500m)  &&
       !output1km &&
       (MOD02QKMfile_id = SDstart(MOD02QKMfile, DFACC_READ)) == -1 ) {
    fprintf(stderr, "Cannot open input file %s.\n", MOD02QKMfile);
    exit(1);
  }
  if ( MOD02HKMfile && (!output1km) &&
       (MOD02HKMfile_id = SDstart(MOD02HKMfile, DFACC_READ)) == -1 ) {
    fprintf(stderr, "Cannot open input file %s.\n", MOD02HKMfile);
    exit(1);
  }
  if ( MOD021KMfile &&
       (MOD021KMfile_id = SDstart(MOD021KMfile, DFACC_READ)) == -1 ) {
    fprintf(stderr, "Cannot open input file %s.\n", MOD021KMfile);
    exit(1);
  }


	if (!sealevel && !TOA) {
		dem.filename = dem_filename_buff;

		if ((ancpath = getenv("ANCPATH")) == NULL)
			sprintf(dem.filename, "%s/%s", ANCPATH, DEMFILENAME);
		else
			sprintf(dem.filename, "%s/%s", ancpath, DEMFILENAME);

		if ( (dem.file_id = SDstart(dem.filename, DFACC_READ)) == -1 ) {
			fprintf(stderr, "Cannot open file %s.\n", dem.filename);
			exit(1);
			}
		}


	if ( (fp = fopen(filename, "r")) ) {
		(void) fclose(fp);
		outfile_exists = 1;
		}
	else
		outfile_exists = 0;

	if ((write_mode == DFACC_CREATE)  &&  !overwrite  && outfile_exists) {
		fprintf(stderr, "File \"%s\" already exits.\n", filename);
		exit(1);
		}

	if (output500m) {
		sds[BAND10].file_id =sds[BAND8].file_id = sds[BAND9].file_id = MOD02HKMfile_id;
		sds[BAND10].filename =sds[BAND8].filename = sds[BAND9].filename = MOD02HKMfile;
		}
	else {
		if (output1km) {
			sds[BAND1].file_id = sds[BAND2].file_id = MOD021KMfile_id;
			sds[BAND1].filename = sds[BAND2].filename = MOD021KMfile;
			}
		else {
			sds[BAND1].file_id = sds[BAND2].file_id = MOD02QKMfile_id;
			sds[BAND1].filename = sds[BAND2].filename = MOD02QKMfile;
			}
		}

	if (output1km) {
		sds[BAND3].file_id = sds[BAND4].file_id =
			sds[BAND5].file_id = sds[BAND6].file_id =
			sds[BAND7].file_id = MOD021KMfile_id;
		sds[BAND3].filename = sds[BAND4].filename =
			sds[BAND5].filename = sds[BAND6].filename =
			sds[BAND7].filename = MOD021KMfile;
		}
	else {
		sds[BAND3].file_id = sds[BAND4].file_id =
			sds[BAND5].file_id = sds[BAND6].file_id =
			sds[BAND7].file_id = MOD02HKMfile_id;
		sds[BAND3].filename = sds[BAND4].filename =
			sds[BAND5].filename = sds[BAND6].filename =
			sds[BAND7].filename = MOD02HKMfile;
		}

	 sds[SOLZ].file_id = sds[SOLA].file_id =
		sds[SENZ].file_id = sds[SENA].file_id = sds[LON].file_id =
		sds[LAT].file_id = MOD021KMfile_id;
	 sds[SOLZ].filename = sds[SOLA].filename =
		sds[SENZ].filename = sds[SENA].filename = sds[LON].filename =
		sds[LAT].filename = MOD021KMfile;

	 sds[BAND11].file_id =
		sds[BAND12].file_id = sds[BAND13].file_id =
		sds[BAND14].file_id = sds[BAND15].file_id =
		sds[BAND16].file_id = MOD021KMfile_id;
	  sds[BAND11].filename =
		sds[BAND12].filename = sds[BAND13].filename =
		sds[BAND14].filename = sds[BAND15].filename =
		sds[BAND16].filename = MOD021KMfile;

  for (ib=0; ib < Nitems; ib++) {
	/* initializing these fields will simplify releasing memory later */
	sds[ib].data = sds[ib].fillvalue = (void *) NULL;

    if ( ib < Nbands  &&
         ! process[ib] ) {
      sds[ib].id = -1;
      continue;
    }
    if (output500m)
      sds[ib].name = SDSlocatorHKM[ib];
    else if (output1km)
      sds[ib].name = SDSlocator1KM[ib];
    else
      sds[ib].name = SDSlocatorQKM[ib];

    if ( (sds[ib].index = SDnametoindex(sds[ib].file_id, sds[ib].name)) == -1 ) {
      fprintf(stderr, "Cannot find SDS %s in file %s.\n", sds[ib].name, sds[ib].filename);
      continue;
    }
    if ( (sds[ib].id = SDselect(sds[ib].file_id, sds[ib].index)) == -1 ) {
      fprintf(stderr, "Cannot select SDS no. %d\n", sds[ib].index);
      if (ib < Nbands)
        process[ib] = FALSE;
      continue;
    }

    /*
    Original code passed sds[ib].name as destination for SDS name in call to SDgetinfo().
    This was causing a core dump, apparently because SDgetinfo() writes some additional
    characters beyond the terminating null at the end of the SDS name, so I replaced
    the argument with a dummy character array.
    */
    if (SDgetinfo(sds[ib].id, dummy, &sds[ib].rank, sds[ib].dim_sizes, &sds[ib].num_type, &sds[ib].n_attr) == -1) {
      fprintf(stderr, "Can't get info from SDS \"%s\" in file %s.\n", sds[ib].name, sds[ib].filename);
      SDendaccess(sds[ib].id);
      sds[ib].id = -1;
      if (ib < Nbands)
        process[ib] = FALSE;
      continue;
    }


    sds[ib].factor = 1;
    if (ib < 5 ) sds[ib].factor = 2.441742e-05;
    attr_name = "scale_factor";
    printf("band %d \n",ib);
    if ( (attr_index = SDfindattr(sds[ib].id, attr_name)) != -1  &&
         SDattrinfo(sds[ib].id, attr_index, dummy, &num_type, &count) != -1  &&
         SDreadattr(sds[ib].id, attr_index, scale_factor) != -1 ) 
      sds[ib].factor = ((float32 *)scale_factor)[indexlocator[ib]];
    else {
	attr_name = "Scale";
	if ((attr_index = SDfindattr(sds[ib].id, attr_name)) != -1  &&
		SDattrinfo(sds[ib].id, attr_index, dummy, &num_type, &count) != -1  &&
		SDreadattr(sds[ib].id, attr_index, scale_factor) != -1 )
		sds[ib].factor = *scale_factor;
	}

    sds[ib].offset = 0;
    attr_name = "reflectance_offsets";
    if ( (attr_index = SDfindattr(sds[ib].id, attr_name)) != -1  &&
         SDattrinfo(sds[ib].id, attr_index, dummy, &num_type, &count) != -1  &&
         SDreadattr(sds[ib].id, attr_index, add_offset) != -1 )
      sds[ib].offset = ((float32 *)add_offset)[indexlocator[ib]];
    else {
	attr_name = "add_offset";
	if ( (attr_index = SDfindattr(sds[ib].id, attr_name)) != -1  &&
		SDattrinfo(sds[ib].id, attr_index, dummy, &num_type, &count) != -1  &&
		SDreadattr(sds[ib].id, attr_index, add_offset) != -1 )
		sds[ib].offset = *add_offset;
	}


    sds[ib].fillvalue = (void *) malloc(1 * DFKNTsize(sds[ib].num_type));
    if ( SDgetfillvalue(sds[ib].id, sds[ib].fillvalue) != 0 ) {
      fprintf(stderr, "Cannot read fill value of SDS \"%s\".\n", sds[ib].name);
/*      exit(1); commmented that*/
    }

    switch (sds[ib].rank) {
      case 2:
        sds[ib].Nl = sds[ib].dim_sizes[0];
        sds[ib].Np = sds[ib].dim_sizes[1];
        sds[ib].rowsperscan = (int)(NUM1KMROWPERSCAN * sds[ib].Np / (float)NUM1KMCOLPERSCAN + 0.5);
        sds[ib].start[1] = 0;
        sds[ib].edges[0] = sds[ib].rowsperscan;
        sds[ib].edges[1] = sds[ib].Np;
        break;
      case 3:
        sds[ib].Nl = sds[ib].dim_sizes[1];
        sds[ib].Np = sds[ib].dim_sizes[2];
        sds[ib].rowsperscan = (int)(NUM1KMROWPERSCAN * sds[ib].Np / (float)NUM1KMCOLPERSCAN + 0.5);
        sds[ib].start[0] = indexlocator[ib];
        sds[ib].start[2] = 0;
        sds[ib].edges[0] = 1;
        sds[ib].edges[1] = sds[ib].rowsperscan;
        sds[ib].edges[2] = sds[ib].Np;
        break;
      default:
        fprintf(stderr, "SDS rank must be 2 or 3.\n");
        continue;
    }
    if (verbose)
      printf("SDS \"%s\": %dx%d   scale factor: %g  offset: %g\n", sds[ib].name, sds[ib].Np, sds[ib].Nl, sds[ib].factor, sds[ib].offset);
    if (sds[ib].num_type != numtypelocator[ib]) {
      fprintf(stderr, "SDS \"%s\" has not the expected data type.\n", sds[ib].name);
      exit(-1);
    }
    sds[ib].data = malloc(sds[ib].Np * sds[ib].rowsperscan * DFKNTsize(sds[ib].num_type));
    if (!sds[ib].data) {
      (void) fputs("Error allocating memory.\n", stderr);
      exit(1);
      }
  }

	if (sealevel || TOA) {
		dem.id = -1;
		dem.Nl = dem.Np = 0;
		}
	else {
		/* dem.name = strdup(DEMSDSNAME); */
		dem.name = DEMSDSNAME;

		if ( (dem.index = SDnametoindex(dem.file_id, dem.name)) == -1 ) {
			fprintf(stderr, "Cannot find SDS %s in file %s.\n", dem.name, dem.filename);
			exit(1);
			}

		if ( (dem.id = SDselect(dem.file_id, dem.index)) == -1 ) {
			fprintf(stderr, "Cannot select SDS no. %d\n", dem.index);
			exit(1);
			}
		if (SDgetinfo(dem.id, dummy, &dem.rank, dem.dim_sizes, &dem.num_type, &dem.n_attr) == -1) {
			fprintf(stderr, "Can't get info from SDS \"%s\" in file %s.\n", dem.name, dem.filename);
			SDendaccess(dem.id);
			exit(1);
			}

		dem.Nl = dem.dim_sizes[0];
		dem.Np = dem.dim_sizes[1];
		dem.rowsperscan = (int)(NUM1KMROWPERSCAN * dem.Np / (float)NUM1KMCOLPERSCAN + 0.5);
		}

  if ( sds[SOLZ].id == -1 ||
       sds[SOLA].id == -1 ||
       sds[SENZ].id == -1 ||
       sds[SENA].id == -1 ||
       sds[LON].id == -1 ||
       sds[LAT].id == -1 ||
       ((dem.id == -1) && !sealevel && !TOA) ) {
    fprintf(stderr, "Solar and Sensor angles and DEM are necessary to process granule.\n");
    exit(1);
  }

  if ( sds[REFSDS].Np != sds[SOLZ].Np ||
       sds[REFSDS].Np != sds[SOLA].Np ||
       sds[REFSDS].Np != sds[SENZ].Np ||
       sds[REFSDS].Np != sds[SENA].Np ||
       sds[REFSDS].Np != sds[LON].Np ||
       sds[REFSDS].Np != sds[LAT].Np ) {
    fprintf(stderr, "Solar and Sensor angles must have identical dimensions.\n");
    exit(1);
  }

	ib = 0;
	while (sds[ib].id == -1) ib++;
	if (ib >= Nbands) {
		fprintf(stderr, "No L1B SDS can be read successfully.\n");
		exit(1);
		}
 
	Nscans = sds[ib].Nl / sds[ib].rowsperscan;


	/* finally, open output file */
	if ( (sd_id = SDstart(filename, write_mode)) == -1 ) {
		fprintf(stderr, "Cannot open output file %s.\n", filename);
		exit(1);
		}

	if (!append) {
		if (write_global_attributes(sd_id, MOD021KMfile, MOD02HKMfile,
			MOD02QKMfile, maxsolz, sealevel, TOA, nearest)) {
			fputs("Error writing global attributes.\n", stderr);
			exit(1);
			}
		}

	/* create output SDSs and set SDS-specific attributes and dimension names */
	if (init_output_sds(sd_id, process, outsds, sds, gzip, verbose)) exit(1);


	mus = (float *) malloc(sds[REFSDS].rowsperscan * sds[REFSDS].Np * sizeof(float));
	height.data = (int16 *) malloc(sds[REFSDS].rowsperscan * sds[REFSDS].Np * sizeof(int16));
	if (!mus || !height.data) {
		(void) fputs("Error allocating memory.\n", stderr);
		exit(1);
		}

	if (sealevel || TOA)
		dem.data = (void *) NULL;
	else {
		dem.data = (int16 *) malloc(dem.Nl * dem.Np * sizeof(int16));
		if (!dem.data) {
			(void) fputs("Error allocating memory.\n", stderr);
			exit(1);
			}
		}

	if (!TOA) {
		nbytes = Nbands * sds[REFSDS].rowsperscan * sds[REFSDS].Np * sizeof(float);

		rhoray =      (float *) malloc(nbytes);
		sphalb =      (float *) malloc(nbytes);
		TtotraytH2O = (float *) malloc(nbytes);
		tOG =         (float *) malloc(nbytes);

		if (!rhoray || !sphalb || !TtotraytH2O || !tOG) {
			(void) fputs("Error allocating memory.\n", stderr);
			exit(1);
			}
		}

	solz = sds[SOLZ].data;
	sola = sds[SOLA].data;
	senz = sds[SENZ].data;
	sena = sds[SENA].data;
	solzfill = sds[SOLZ].fillvalue;
	lon = sds[LON].data;
	lat = sds[LAT].data;
	lonfill = sds[LON].fillvalue;
	latfill = sds[LAT].fillvalue;
	for (ib = 0; ib < Nbands; ib++) l1bdata[ib] = sds[ib].data;

	/* don't need DEM if --sealevel or --toa specified */
	if (!sealevel && !TOA) {
		dem.start[0] = 0;
		dem.start[1] = 0;
		dem.edges[0] = dem.Nl;
		dem.edges[1] = dem.Np;
		if (SDreaddata(dem.id, dem.start, NULL, dem.edges, dem.data) == -1) {
			fprintf(stderr, "  Can't read DEM SDS \"%s\"\n", dem.name);
			exit(-1);
			}
		(void) SDendaccess(dem.id);
		(void) SDend(dem.file_id);
		}

	/* loop over each MODIS scan */
	for (iscan = 0; iscan < Nscans; iscan++) {
		if ((iscan % NUM1KMROWPERSCAN == 0) && verbose)
			printf("Processing scan %d...\n", iscan);

		/* Fill scan buffer for each band to be processed.
		Exit scan loop if error occurred while reading. */
		if (read_scan(iscan, sds)) break;

		for (idx = 0; idx < sds[REFSDS].rowsperscan*sds[REFSDS].Np; idx++) {
			if (solz[idx] * sds[SOLZ].factor >= maxsolz)
				solz[idx] = *solzfill;

			if (!sealevel &&
				(lon[idx] == *lonfill || lat[idx] == *latfill))
				solz[idx] = *solzfill;

			if (solz[idx] != *solzfill) {
				mus[idx] = cos(solz[idx] * sds[SOLZ].factor * DEG2RAD);

				if (sealevel || TOA)
					((int16 *)height.data)[idx] = 0;
				else
					((int16 *)height.data)[idx] =
						(int16) interp_dem(lat[idx],
						lon[idx], &dem);
				}
			}


		if (!TOA) {
			for (irow=0; irow<sds[REFSDS].rowsperscan; irow++) {
				for (jcol=0; jcol<sds[REFSDS].Np; jcol++) {
					idx = irow * sds[REFSDS].Np + jcol;
					if (solz[idx] == *solzfill) continue;
					phi = sola[idx] * sds[SOLA].factor - sena[idx] * sds[SENA].factor;
					muv = cos(senz[idx] * sds[SENZ].factor * DEG2RAD);
					if ( getatmvariables(mus[idx], muv, phi, ((int16 *)height.data)[idx],
						process,
						&sphalb[idx * Nbands], &rhoray[idx * Nbands],
						&TtotraytH2O[idx * Nbands], &tOG[idx * Nbands]) == -1 )
						solz[idx] = *solzfill;
/*						printf(" some data %f %f %f %f %f \n",senz[idx],phi,mus[idx],rhoray[idx * Nbands],tOG[idx * Nbands]);*/
					}
				}
			}

		for (ib=0; ib<Nbands; ib++) {
			if (! process[ib]) continue;
			aggfactor = outsds[ib].rowsperscan / sds[REFSDS].rowsperscan;
			for (irow=0; irow<outsds[ib].rowsperscan; irow++) {
				if (!nearest) {
					fractrow = (float)irow / aggfactor - 0.5;	/* We want fractrow integer on coarse pixel center */
					crsrow1 = floor(fractrow);
					crsrow2 = crsrow1 + 1;
					if (crsrow1 < 0) crsrow1 = crsrow2 + 1;
					if (crsrow2 > sds[REFSDS].rowsperscan - 1) crsrow2 = crsrow1 - 1;
					t = (fractrow - crsrow1) / (crsrow2 - crsrow1);
					}

				for (jcol=0; jcol<outsds[ib].Np; jcol++) {
					idx = irow * outsds[ib].Np + jcol;
					crsidx = (int)(irow / aggfactor) * sds[REFSDS].Np + (int)(jcol / aggfactor);
					if ( solz[crsidx] == *solzfill  ||	/* Bad geolocation or night pixel */
						l1bdata[ib][idx] >= 65528 ) {	/* VIIRS SDR is read as uint16, fills start at 65528 */
						if (l1bdata[ib][idx] == (65536 + MISSING))
							((int16 *)outsds[ib].data)[idx] = 32768 + MISSING;
						else
							((int16 *)outsds[ib].data)[idx] = *(int16 *)outsds[ib].fillvalue;

						continue;
						}

					if (nearest) {
						mus0 = mus[crsidx];
						if (! TOA) {
							rhoray0 = rhoray[crsidx * Nbands + ib];
							sphalb0 = sphalb[crsidx * Nbands + ib];
							if ( sphalb0 <= 0.0F ) {	/* Atm variables not computed successfully in this band */
								((int16 *)outsds[ib].data)[idx] = *(int16 *)outsds[ib].fillvalue;
								continue;
								}
							}
						}
					else {
						fractcol = ((float) jcol) / aggfactor - 0.5F;	/* We want fractcol integer on coarse pixel center */
						crscol1 = (int) floor(fractcol);
						crscol2 = crscol1 + 1;
						if (crscol1 < 0) crscol1 = crscol2 + 1;
						if (crscol2 > sds[REFSDS].Np - 1) crscol2 = crscol1 - 1;
						u = (fractcol - crscol1) / (crscol2 - crscol1);		/* We want u=0 on coarse pixel center */
						crsidx11 = crsrow1 * sds[REFSDS].Np + crscol1;
						crsidx12 = crsrow1 * sds[REFSDS].Np + crscol2;
						crsidx21 = crsrow2 * sds[REFSDS].Np + crscol1;
						crsidx22 = crsrow2 * sds[REFSDS].Np + crscol2;
/*						mus0 = t * u * mus[crsidx22] + (1.0F - t) * u * mus[crsidx12] + t * (1.0F - u) * mus[crsidx21] + (1.0F - t) * (1.0F - u) * mus[crsidx11];

						bad = (solz[crsidx11] == *solzfill) ||
							(solz[crsidx12] == *solzfill) ||
							(solz[crsidx21] == *solzfill) ||
							(solz[crsidx22] == *solzfill);
commented by eric to handle the viirs fill value hardcoding */ 

						bad = (solz[crsidx11] <-900.) ||
							(solz[crsidx12] <-900.) ||
							(solz[crsidx21] <-900.) ||
							(solz[crsidx22] <-900.);
 
						if (bad) {
							((int16 *)outsds[ib].data)[idx] = *(int16 *)outsds[ib].fillvalue;
							continue;
							}

						if (! TOA) {
							rhoray11 = rhoray[crsidx11 * Nbands + ib];
							rhoray12 = rhoray[crsidx12 * Nbands + ib];
							rhoray21 = rhoray[crsidx21 * Nbands + ib];
							rhoray22 = rhoray[crsidx22 * Nbands + ib];
							rhoray0 = t * u * rhoray22 + (1.0F - t) * u * rhoray12 + t * (1.0F - u) * rhoray21 + (1.0F - t) * (1.0F - u) * rhoray11;
							sphalb11 = sphalb[crsidx11 * Nbands + ib];
							sphalb12 = sphalb[crsidx12 * Nbands + ib];
							sphalb21 = sphalb[crsidx21 * Nbands + ib];
							sphalb22 = sphalb[crsidx22 * Nbands + ib];

							bad = (sphalb11 <= 0.0F) ||
								(sphalb12 <= 0.0F) ||
								(sphalb21 <= 0.0F) ||
								(sphalb22 <= 0.0F);

							if (bad) {
								((int16 *)outsds[ib].data)[idx] = *(int16 *)outsds[ib].fillvalue;
								continue;
								}
							sphalb0 = t * u * sphalb22 + (1.0F - t) * u * sphalb12 + t * (1.0F - u) * sphalb21 + (1.0F - t) * (1.0F - u) * sphalb11;
							}
						}

					/* TOA reflectance */
					/*printf(" mus0 is %f\n",mus0);*/
					refl = (l1bdata[ib][idx] - sds[ib].offset) * sds[ib].factor /*/ mus0 commented by Eric who suspected something*/;

					/* corrected reflectance */
					if (!TOA)
						refl = correctedrefl(refl, TtotraytH2O[crsidx * Nbands + ib],
							tOG[crsidx * Nbands + ib], rhoray0, sphalb0);

					/* reflectance bounds checking */
					if (refl > reflmax) refl = reflmax;
					if (refl < reflmin) refl = reflmin;

					((int16 *)outsds[ib].data)[idx] = (int16) (refl / outsds[ib].factor + 0.5);
					}
				}
			}


		/* write current scan line for all processed bands */
		if (write_scan(iscan, process, outsds)) {
			fprintf(stderr, "Cannot write scan %d of SDS %s\n",
				iscan, outsds[ib].name);
			exit(1);
			}

		} /* end of scan loop */


	for (ib = 0; ib < Nitems; ib++)
		if (sds[ib].id != -1) SDendaccess(sds[ib].id);

	for (ib = 0; ib < Nbands; ib++)
		if (process[ib]) SDendaccess(outsds[ib].id);

	SDend(MOD02QKMfile_id);
	SDend(MOD02HKMfile_id);
	SDend(MOD021KMfile_id);
	SDend(sd_id);


	/* ----- free memory ----- */

	for (ib = 0; ib < Nitems; ib++) {
		if (sds[ib].fillvalue) free(sds[ib].fillvalue);
		if (sds[ib].data) free(sds[ib].data);
		}

	free(height.data);
	free(mus);

	if (!TOA) {
		free(tOG);
		free(TtotraytH2O);
		free(sphalb);
		free(rhoray);
		}

	/* not allocated if --sealevel specified */
	if (dem.data) free(dem.data);


	return 0;
}
Example #16
0
static intn test_dim1_SDS1(void)
{
    char  sds_name[20];
    float32 sds1_data[] = {0.1, 2.3, 4.5, 6.7, 8.9};
    float32 out_data[5];
    int32 dimsize[1];
    int32 sds_id, file_id, dim_id, index;
    int32 start=0, stride=1;
    int32 scale1 [5] = {101,102,103,104,105}, scale1_out[5];
    int32 num_type, array_rank, count;
    int32 n_datasets, n_file_attrs, n_local_attrs, n_vars = 0;
    intn  datanum, ranknum, status =0, i, idx, idx1, idx2;
    hdf_varlist_t* var_list;
    intn  is_coord = FALSE;
    char  attr_name[H4_MAX_NC_NAME], attr_values[80];
    intn  num_errs = 0;         /* number of errors so far */

    file_id = SDstart(FILE1, DFACC_CREATE);
    CHECK(file_id, FAIL, "SDstart");

    /* Create a one-dim dataset named VAR1_NAME, of type DFNT_FLOAT32. */
    dimsize[0] = 5;
    sds_id = SDcreate(file_id, VAR1_NAME, DFNT_FLOAT32, 1, dimsize);
    CHECK(sds_id, FAIL, "SDcreate");

    /* Set the dimension name to be the same as its dataset. */
    dim_id = SDgetdimid(sds_id, 0);
    CHECK(dim_id, FAIL, "SDgetdimid");
    status = SDsetdimname(dim_id, VAR1_NAME);
     /* status = SDsetdimname(dim_id, VAR1_NAME);
 */ 
    CHECK(status, FAIL, "SDsetdimname");

    /* Get file info and verify that there is 1 dataset in the file. */
    status = SDfileinfo(file_id, &n_datasets, &n_file_attrs);
    CHECK(status, FAIL, "SDfileinfo");
    VERIFY(n_datasets, 1, "SDfileinfo");

    /* Set an attribute to dimension VAR1_NAME. */
    status = SDsetattr(dim_id, ATTR1_NAME, DFNT_CHAR8, ATTR1_LEN, ATTR1_VAL);
    CHECK(status, FAIL, "SDsetattr");

    /* Set an attribute to dataset VAR1_NAME. */
    status = SDsetattr(sds_id, ATTR2_NAME, DFNT_CHAR8, ATTR2_LEN, ATTR2_VAL);
    CHECK(status, FAIL, "SDsetattr");

    /* Get file info and verify that there are 2 datasets in the file:
       1 SDS and 1 coordinate variable (because of SDsetattr dim) */
    status = SDfileinfo(file_id, &n_datasets, &n_file_attrs);
    CHECK(status, FAIL, "SDfileinfo");
    VERIFY(n_datasets, 2, "SDfileinfo");

    /* Write data to the SDS */
    status = SDwritedata(sds_id, &start, &stride, dimsize, (VOIDP)sds1_data);
    CHECK(status, FAIL, "SDwritedata");

    /* Close dataset and file. */
    status = SDendaccess(sds_id);
    CHECK(status, FAIL, "SDendaccess");
    status = SDend(file_id); 
    CHECK(status, FAIL, "SDend");

    /* Open the file again to check its data */
    file_id = SDstart(FILE1, DFACC_RDWR);
    CHECK(file_id, FAIL, "SDstart");

    /* Check variable type and attributes of each element in the file */

    /* Get the number of variables of name VAR1_NAME */
    status = SDgetnumvars_byname(file_id, VAR1_NAME, &n_vars);

    if (n_vars == 1)
    {
	/* Get index of dataset VAR1_NAME */
	index = SDnametoindex(file_id, VAR1_NAME);
	CHECK(index, FAIL, "SDnametoindex");
    }
    else
    {
	/* Get the list of all variables of named VAR1_NAME */
	var_list = (hdf_varlist_t *)HDmalloc(n_vars * sizeof(hdf_varlist_t));
	status = SDnametoindices(file_id, VAR1_NAME, var_list);

	/* In this case, the first variable is a dataset */
	for (idx = 0; idx < n_vars; idx++)
	{
	    if (var_list[idx].var_type == IS_SDSVAR)
	    {
		index = var_list[idx].var_index;
		VERIFY(index, 0, "SDnametoindices");
	    }
	}
    }

    sds_id = SDselect(file_id, index);
    CHECK(sds_id, FAIL, "SDselect");

    /* Verify that this variable is a dataset. */
    is_coord = SDiscoordvar(sds_id);
    VERIFY(is_coord, FALSE, "SDiscoordvar");

    /* Read and verify the information of the SDS' first attribute. */
    status = SDattrinfo(sds_id, 0, attr_name, &num_type, &count);
    CHECK(status, FAIL, "SDattrinfo");
    VERIFY(count, ATTR2_LEN, "SDattrinfo");
    VERIFY(HDstrncmp(attr_name, ATTR2_NAME, 14), 0, "SDattrinfo");

    /* Read and verify the values of the SDS' first attribute. */
    status = SDreadattr(sds_id, 0, attr_values);
    CHECK(status, FAIL, "SDreadattr");

    if (HDstrncmp(attr_values, ATTR2_VAL, ATTR2_LEN) != 0)
    {
	fprintf(stderr, "Unmatched attribute values for SDS %s: is <%s>, should be <%s>\n", VAR1_NAME, attr_values, ATTR2_VAL);
	num_errs++;
    }

    /* Get access to the SDS' first dimension. */
    dim_id = SDgetdimid(sds_id, 0);
    CHECK(dim_id, FAIL, "SDgetdimid");

    /* Read and verify the information of the dimension's first attribute. */
    status = SDattrinfo(dim_id, 0, attr_name, &num_type, &count);
    CHECK(status, FAIL, "SDattrinfo");
    VERIFY(count, 19, "SDattrinfo");
    VERIFY(HDstrncmp(attr_name, ATTR1_NAME, 21), 0, "SDattrinfo");

    /* Read and verify the values of the dimension's first attribute. */
    status = SDreadattr(dim_id, 0, attr_values);
    CHECK(status, FAIL, "SDreadattr");

    if (HDstrncmp(attr_values, ATTR1_VAL, ATTR1_LEN) != 0)
    {
	fprintf(stderr, "Unmatched attribute values for dimension %s: is <%s>, should be <%s>\n", VAR1_NAME, attr_values, ATTR1_VAL);
	num_errs++;
    }

    /* Verify again that the number of datasets in the file is 2, 1 SDS and
       1 coordinate variable */
    status = SDfileinfo(file_id, &n_datasets, &n_file_attrs);
    CHECK(status, FAIL, "SDfileinfo");
    VERIFY(n_datasets, 2, "SDfileinfo");
    VERIFY(n_file_attrs, 0, "SDfileinfo");

    /* Read and verify the dataset's data */
    status = SDreaddata (sds_id, &start, NULL, dimsize, &out_data);
    CHECK(status, FAIL, "SDreaddata");

    for (idx1 = 0; idx1 < dimsize[0]; idx1++)
        if (out_data[idx1] != sds1_data[idx1])
	{
	    fprintf(stderr, "Read value (%f) differs from written (%f) at [%d]\n", out_data[idx1], sds1_data[idx1], idx1);
		num_errs++;
	}

    /* Close dataset and file. */
    status = SDendaccess(sds_id);
    CHECK(status, FAIL, "SDendaccess");

    status = SDend(file_id); 
    CHECK(status, FAIL, "SDend");

    /* Return the number of errors that's been kept track of so far */
    return num_errs;
}   /* test_dim1_SDS1 */
Example #17
0
int get_data(char *filename, int *zonecode, int *sphercode, float *orientationangle, float *pixelsize, 
             float *upperleftx, float *upperlefty, int *rows, int *cols)
{
int32 i, j, n, sd, n_sets, n_gattr, count, structmetadata_exists, number_type;
float floatattr;
double doubleattr;
char projection[256];
char coordinate[256];
char attrib[256];
char attribu[256];
void metareader(int32 sd_id, char *type_of_meta, char *metastring, int32 *count, char *data);


*zonecode = *sphercode = *rows = *cols = -1;
*orientationangle = *pixelsize = -999.0;

/* Make sure input file is HDF, is 
 * readable, has SDSs, et cetera
 ***********************************/
if ((sd = SDstart(filename, DFACC_RDONLY)) == -1) {
     printf("Error: file '%s' can't be opened with SDstart(): cannot continue...\n", filename);
     exit(-2);
    }
       
n_sets = 0;
SDfileinfo(sd, &n_sets, &n_gattr);
if (n_sets == 0) {
    printf("Error: file %s doesn't seem to have any SDSs: cannot continue...\n", filename);
    SDend(sd);
    exit(-4);
   } 
if (n_gattr == 0) {
    printf("Error: file %s doesn't seem to have any global attributes: cannot continue...\n", filename);
    SDend(sd);
    exit(-4);
   } 
   
structmetadata_exists = 0;
for (j=0;j<n_gattr;j++) {
     SDattrinfo(sd, j, attrib, &number_type, &count);
     n = strlen(attrib);
     for (i=0;i<n;i++) attribu[i] = toupper(attrib[i]);
     
     if (strstr(attribu, "ORIENTATIONANGLE")) {
        SDreadattr(sd, j, &doubleattr);
	*orientationangle = (float)doubleattr;
	}
     if (strstr(attribu, "PIXELSIZE")) {
        SDreadattr(sd, j, &doubleattr);
	*pixelsize = (float)doubleattr;
	}
	
     if (strstr(attribu, "STRUCTMETADATA")) {
        structmetadata_exists = 1;
	}
    }

if (structmetadata_exists == 0) {
    printf("Error: file %s doesn't seem to have any StructMetadata: cannot continue...\n", filename);
    SDend(sd);
    exit(-4);
   } 

metareader(sd, "STRUCTMETADATA\0", "Projection\0", &count, projection);

if (  !strstr(projection, "GCTP_UTM\0") ) {
    printf("Error: file %s has projection %s, not UTM: cannot continue...\n", filename, projection);
    SDend(sd);
    exit(-4);
   } 

metareader(sd, "STRUCTMETADATA", "UpperLeftPointMtrs\0", &count, coordinate);
parse_comma_sep(coordinate, upperleftx, upperlefty);
    
coordinate[0] = '\0';    
metareader(sd, "STRUCTMETADATA", "XDim\0", &count, coordinate);
*cols = atoi(coordinate);

coordinate[0] = '\0';    
metareader(sd, "STRUCTMETADATA", "YDim\0", &count, coordinate);
*rows = atoi(coordinate);

coordinate[0] = '\0';    
metareader(sd, "STRUCTMETADATA", "ZoneCode\0", &count, coordinate);
*zonecode = atoi(coordinate);

coordinate[0] = '\0';    
metareader(sd, "STRUCTMETADATA", "SphereCode\0", &count, coordinate);
*sphercode = atoi(coordinate);

SDend(sd);

if ( *zonecode == -1) {
    printf("Error reading zone code, cannot continue...\n");
    exit(-5);
  } 
if ( *sphercode == -1) {
    printf("Error reading sphere code, cannot continue...\n");
    exit(-5);
  }
if ( *rows == -1) {
    printf("Error reading number of rows, cannot continue...\n");
    exit(-5);
   }
if ( *cols == -1) {
    printf("Error reading number of columns, cannot continue...\n");
    exit(-5);
  }
if ( *orientationangle < -998.0 )  {
    printf("Error reading orientation angle, cannot continue...\n");
    exit(-5);
  }
if ( *pixelsize < 0.0 )  {
    printf("Error reading pixel size, cannot continue...\n");
    exit(-5);
  }

/*printf("As read from file %s (%d rows  by %d columns)\n", filename, *rows, *cols);
printf("Zonecode %d: sphere code %d; Orientation angle %f; Pixelsize %f; UL: %f, %f\n", 
        *zonecode, *sphercode, *orientationangle, *pixelsize, *upperleftx, *upperlefty); */
	
return(0);
}