int ex_get_partial_node_set (int   exoid,
                       ex_entity_id node_set_id,
                       int64_t   start_node_num,
                       int64_t   num_nodes,
                       void_int  *node_set_node_list)
{
  int     dimid, node_list_id, node_set_id_ndx, status;
  size_t  num_nodes_in_set, start[1], count[1];
  char errmsg[MAX_ERR_LENGTH];

  exerrval = 0; /* clear error code */

  /* first check if any node sets are specified */

  if ((status = nc_inq_dimid (exoid, DIM_NUM_NS, &dimid))  != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Warning: no node sets defined in file id %d",
            exoid);
    ex_err("ex_get_partial_node_set",errmsg,exerrval);
    return (EX_WARN);
  }

  /* Lookup index of node set id in VAR_NS_IDS array */
  if ((node_set_id_ndx = ex_id_lkup(exoid, EX_NODE_SET, node_set_id)) < 0) {
    if (exerrval == EX_NULLENTITY) {
      sprintf(errmsg,
              "Warning: node set %"PRId64" is NULL in file id %d",
              node_set_id,exoid);
      ex_err("ex_get_partial_node_set",errmsg,EX_NULLENTITY);
      return (EX_WARN);
    } 

      sprintf(errmsg,
              "Error: failed to locate node set %"PRId64" in %s in file id %d",
              node_set_id,VAR_NS_IDS,exoid);
      ex_err("ex_get_partial_node_set",errmsg,exerrval);
      return (EX_FATAL);
    
  }

  /* inquire id's of previously defined dimensions and variables */
  if ((status = nc_inq_dimid (exoid, DIM_NUM_NOD_NS(node_set_id_ndx), &dimid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
         "Error: failed to locate number of nodes in node set %"PRId64" in file id %d",
            node_set_id,exoid);
    ex_err("ex_get_partial_node_set",errmsg,exerrval);
    return (EX_FATAL);
  }

  if ((status = nc_inq_dimlen(exoid, dimid, &num_nodes_in_set)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Error: failed to get number of nodes in set %"PRId64" in file id %d",
            node_set_id, exoid);
    ex_err("ex_get_partial_node_set",errmsg,exerrval);
    return (EX_FATAL);
  }

  /* Check input parameters for a valid range of numbers */
  if (start_node_num < 0 || start_node_num > num_nodes_in_set) {
    exerrval = EX_BADPARAM;
    sprintf(errmsg, "Error: Invalid input");
    ex_err("ex_get_partial_node_set",errmsg,exerrval);
    return (EX_FATAL);
  }

  if (num_nodes < 0) {
    exerrval = EX_BADPARAM;
    sprintf(errmsg, "Error: Invalid number of nodes in nodes set!");
    ex_err("ex_get_partial_node_set",errmsg,exerrval);
    return (EX_FATAL);
  }

  /* start_node_num now starts at 1, not 0 */
  if ((start_node_num + num_nodes - 1) > num_nodes_in_set) {
    exerrval = EX_BADPARAM;
    sprintf(errmsg, "Error: request larger than number of nodes in set!");
    ex_err("ex_get_partial_node_set",errmsg,exerrval);
    return (EX_FATAL);
  }

  if ((status = nc_inq_varid (exoid, VAR_NODE_NS(node_set_id_ndx), &node_list_id)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Error: failed to locate node set %"PRId64" node list in file id %d",
            node_set_id,exoid);
    ex_err("ex_get_partial_node_set",errmsg,exerrval);
    return (EX_FATAL);
  }

  /* read in the node list array */
  start[0] = --start_node_num;
  count[0] = num_nodes;

  if (ex_int64_status(exoid) & EX_BULK_INT64_API) {
    status = nc_get_vara_longlong(exoid, node_list_id, start, count, node_set_node_list);
  } else {
    status = nc_get_vara_int(exoid, node_list_id, start, count, node_set_node_list);
  }

  if (status != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Error: failed to get node set node list in file id %d",
            exoid);
    ex_err("ex_get_partial_node_set",errmsg,exerrval);
    return (EX_FATAL);
  }
  return (EX_NOERR);
}
 int ex_get_coordinate_frames( int exoid,
			       int *nframes,
			       void_int *cf_ids,
			       void* pt_coordinates,
			       char* tags)

{
  int status;
  int dimid; /* ID of the dimension of # frames */
  char errmsg[MAX_ERR_LENGTH];
  int varids;                    /* variable id for the frame ids  */
  size_t start=0;                /* start value for varputs        */
  size_t count=0;                /* number vars to put in varput   */

  /* get the dimensions */
  assert( nframes !=NULL );
  status = nc_inq_dimid(exoid, DIM_NUM_CFRAMES, &dimid);
  if (status != NC_NOERR){
    *nframes=0;
    return EX_NOERR;
  }

  (void)nc_inq_dimlen(exoid,dimid,&count);
  *nframes=(int)count;

  if ( count==0 )
    return (EX_NOERR);

  if ( cf_ids ) {
    if ((status = nc_inq_varid(exoid,VAR_FRAME_IDS, &varids))!= NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
              "Error: failed to read number coordinate ids from file id %d",
              exoid);
      ex_err(PROCNAME,errmsg,exerrval);
      return (EX_FATAL);
    }

    if (ex_int64_status(exoid) & EX_IDS_INT64_API) {
      status = nc_get_var_longlong(exoid,varids,cf_ids);
    } else {
      status = nc_get_var_int(exoid,varids,cf_ids);
    }

    if (status != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
              "Error: failed to read coordinate frame ids from file id %d",
              exoid);
      ex_err(PROCNAME,errmsg,exerrval);
      return (EX_FATAL);
    }
  }

  if ( tags )
    if ( (status = nc_inq_varid(exoid,VAR_FRAME_TAGS,&varids))!= NC_NOERR  ||
         (nc_get_vara_text(exoid,varids,&start,&count,tags) != NC_NOERR)) {
      exerrval = status;
      sprintf(errmsg,
              "Error: failed to read number coordinate tags from file id %d",
              exoid);
      ex_err(PROCNAME,errmsg,exerrval);
      return (EX_FATAL);
    }

  if (pt_coordinates ){
    if ( (status = nc_inq_varid(exoid,VAR_FRAME_COORDS,&varids))!= NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
              "Error: failed to read number coordinate tags from file id %d",
              exoid);
      ex_err(PROCNAME,errmsg,exerrval);
      return (EX_FATAL);
    }

    if (ex_comp_ws(exoid) == 4) {
      status = nc_get_var_float(exoid,varids,pt_coordinates);
    } else {
      status = nc_get_var_double(exoid,varids,pt_coordinates);
    }

    if (status != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
              "Error: failed to read number coordinate tags from file id %d",
              exoid);
      ex_err(PROCNAME,errmsg,exerrval);
      return (EX_FATAL);
    }
  }

  return (EX_NOERR);
}
Example #3
0
int ex_put_set_param (int exoid,
                      ex_entity_type set_type,
                      int set_id,
                      int num_entries_in_set,
                      int num_dist_fact_in_set)
{
  int status;
  size_t temp;
  int dimid, varid, set_id_ndx, dims[1]; 
  size_t start[1]; 
  int num_sets;
  int ldum;
  int cur_num_sets, set_stat;
  char *cdum;
  char errmsg[MAX_ERR_LENGTH];
  char* dimptr;
  char* idsptr;
  char* statptr;
  char* numentryptr = NULL;
  char* numdfptr = NULL;
  char* factptr = NULL;
  char* entryptr = NULL;
  char* extraptr = NULL;

  exerrval = 0; /* clear error code */

  cdum = 0;

  /* setup pointers based on set_type 
     NOTE: there is another block that sets more stuff later ... */
  if (set_type == EX_NODE_SET) {
    dimptr = DIM_NUM_NS;
    idsptr = VAR_NS_IDS;
    statptr = VAR_NS_STAT;
  }
  else if (set_type == EX_EDGE_SET) {
    dimptr = DIM_NUM_ES;
    idsptr = VAR_ES_IDS;
    statptr = VAR_ES_STAT;
  }
  else if (set_type == EX_FACE_SET) {
    dimptr = DIM_NUM_FS;
    idsptr = VAR_FS_IDS;
    statptr = VAR_FS_STAT;
  }
  else if (set_type == EX_SIDE_SET) {
    dimptr = DIM_NUM_SS;
    idsptr = VAR_SS_IDS;
    statptr = VAR_SS_STAT;
  }
  else if (set_type == EX_ELEM_SET) {
    dimptr = DIM_NUM_ELS;
    idsptr = VAR_ELS_IDS;
    statptr = VAR_ELS_STAT;
  }
  else {
    exerrval = EX_FATAL;
    sprintf(errmsg,
	    "Error: invalid set type (%d)", set_type);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }

  /* first check if any of that set type is specified */

  if ((status = nc_inq_dimid(exoid, dimptr, &dimid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Error: no %ss specified in file id %d", ex_name_of_object(set_type),
	    exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }

  /* Check for duplicate set id entry */
  ex_id_lkup(exoid, set_type, set_id);
  if (exerrval != EX_LOOKUPFAIL) {  /* found the side set id */
    sprintf(errmsg,
	    "Error: %s %d already defined in file id %d", ex_name_of_object(set_type),
	    set_id,exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return(EX_FATAL);
  }

  /* Get number of sets specified for this file */
  if ((status = nc_inq_dimlen(exoid,dimid,&temp)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Error: failed to get number of %ss in file id %d",
	    ex_name_of_object(set_type), exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }
  num_sets = temp;


  /* Keep track of the total number of sets defined using a counter stored
     in a linked list keyed by exoid.
     NOTE: ex_get_file_item finds the maximum number of sets defined
     for a specific file and returns that value.
  */
  cur_num_sets=ex_get_file_item(exoid, ex_get_counter_list(set_type));
  if (cur_num_sets >= num_sets) {
    exerrval = EX_FATAL;
    sprintf(errmsg,
	    "Error: exceeded number of %ss (%d) defined in file id %d",
	    ex_name_of_object(set_type), num_sets,exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }

  /*   NOTE: ex_inc_file_item finds the current number of sets defined
       for a specific file and returns that value incremented. */

  cur_num_sets=ex_inc_file_item(exoid, ex_get_counter_list(set_type));
  set_id_ndx = cur_num_sets + 1;

  /* setup more pointers based on set_type */
  if (set_type == EX_NODE_SET) {
    numentryptr = DIM_NUM_NOD_NS(set_id_ndx);
    entryptr = VAR_NODE_NS(set_id_ndx);
    extraptr = NULL;
    /* note we are using DIM_NUM_NODE_NS instead of DIM_NUM_DF_NS */
    numdfptr = DIM_NUM_NOD_NS(set_id_ndx);
    factptr = VAR_FACT_NS(set_id_ndx);
  }
  else if (set_type == EX_EDGE_SET) {
    numentryptr = DIM_NUM_EDGE_ES(set_id_ndx);
    entryptr = VAR_EDGE_ES(set_id_ndx);
    extraptr = VAR_ORNT_ES(set_id_ndx);
    numdfptr = DIM_NUM_DF_ES(set_id_ndx);
    factptr = VAR_FACT_ES(set_id_ndx);
  }
  else if (set_type == EX_FACE_SET) {
    numentryptr = DIM_NUM_FACE_FS(set_id_ndx);
    entryptr = VAR_FACE_FS(set_id_ndx);
    extraptr = VAR_ORNT_FS(set_id_ndx);
    numdfptr = DIM_NUM_DF_FS(set_id_ndx);
    factptr = VAR_FACT_FS(set_id_ndx);
  }
  else if (set_type == EX_SIDE_SET) {
    numentryptr = DIM_NUM_SIDE_SS(set_id_ndx);
    entryptr = VAR_ELEM_SS(set_id_ndx);
    extraptr = VAR_SIDE_SS(set_id_ndx);
    numdfptr = DIM_NUM_DF_SS(set_id_ndx);
    factptr = VAR_FACT_SS(set_id_ndx);
  }
  if (set_type == EX_ELEM_SET) {
    numentryptr = DIM_NUM_ELE_ELS(set_id_ndx);
    entryptr = VAR_ELEM_ELS(set_id_ndx);
    extraptr = NULL;
    numdfptr = DIM_NUM_DF_ELS(set_id_ndx);
    factptr = VAR_FACT_ELS(set_id_ndx);
  }

  /* write out information to previously defined variable */

  /* first: get id of set id variable */
  if ((status = nc_inq_varid(exoid, idsptr, &varid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Error: failed to locate %s %d in file id %d", ex_name_of_object(set_type),
	    set_id, exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }

  /* write out set id */
  start[0] = cur_num_sets;

  ldum = (int)set_id;
  if ((status = nc_put_var1_int(exoid, varid, start, &ldum)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Error: failed to store %s id %d in file id %d", ex_name_of_object(set_type),
	    set_id, exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }

  if (num_entries_in_set == 0) /* Is this a NULL  set? */
    set_stat = 0; /* change set status to NULL */
  else
    set_stat = 1; /* change set status to TRUE */

  if ((status = nc_inq_varid(exoid, statptr, &varid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Error: failed to locate %s status in file id %d", ex_name_of_object(set_type),
	    exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }

  ldum = (int)set_stat;
  if ((status = nc_put_var1_int(exoid, varid, start, &ldum)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Error: failed to store %s %d status to file id %d", ex_name_of_object(set_type),
	    set_id, exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }

  if (num_entries_in_set == 0) {/* Is this a NULL set? */
    return(EX_NOERR);
  }

  /* put netcdf file into define mode  */
  if ((status = nc_redef (exoid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Error: failed to put file id %d into define mode",
	    exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }


  /* define dimensions and variables */
  if ((status = nc_def_dim(exoid, numentryptr,
			   num_entries_in_set, &dimid)) != NC_NOERR) {
    exerrval = status;
    if (status == NC_ENAMEINUSE)
      {
	sprintf(errmsg,
		"Error: %s %d size already defined in file id %d",
		ex_name_of_object(set_type), set_id,exoid);
	ex_err("ex_put_set_param",errmsg,exerrval);
      }
    else {
      sprintf(errmsg,
	      "Error: failed to define number of entries in %s %d in file id %d",
	      ex_name_of_object(set_type), set_id,exoid);
      ex_err("ex_put_set_param",errmsg,exerrval);
    }
    goto error_ret;
  }

  /* create variable array in which to store the entry lists */

  dims[0] = dimid;
  if ((status = nc_def_var(exoid, entryptr, NC_INT, 1, dims, &varid)) != NC_NOERR) {
    exerrval = status;
    if (status == NC_ENAMEINUSE) {
      sprintf(errmsg,
	      "Error: entry list already exists for %s %d in file id %d",
	      ex_name_of_object(set_type), set_id,exoid);
      ex_err("ex_put_set_param",errmsg,exerrval);
    } else {
      sprintf(errmsg,
	      "Error: failed to create entry list for %s %d in file id %d",
	      ex_name_of_object(set_type), set_id,exoid);
      ex_err("ex_put_set_param",errmsg,exerrval);
    }
    goto error_ret;            /* exit define mode and return */
  }

  if (extraptr) {
    if ((status = nc_def_var(exoid, extraptr, NC_INT, 1, dims, &varid)) != NC_NOERR) {
      exerrval = status;
      if (status == NC_ENAMEINUSE) {
	sprintf(errmsg,
		"Error: extra list already exists for %s %d in file id %d",
		ex_name_of_object(set_type), set_id, exoid);
	ex_err("ex_put_set_param",errmsg,exerrval);
      } else {
	sprintf(errmsg,
		"Error: failed to create extra list for %s %d in file id %d",
		ex_name_of_object(set_type), set_id,exoid);
	ex_err("ex_put_set_param",errmsg,exerrval);
      }
      goto error_ret;         /* exit define mode and return */
           
    }
  }

  /* Create distribution factors variable if required */

  if (num_dist_fact_in_set > 0) {

    if (set_type == EX_NODE_SET) {
      /* but num_dist_fact_in_set must equal number of nodes */
      if (num_dist_fact_in_set != num_entries_in_set) {
	exerrval = EX_FATAL;
	sprintf(errmsg,
		"Error: # dist fact (%d) not equal to # nodes (%d) in node  set %d file id %d",
		num_dist_fact_in_set, num_entries_in_set, set_id, exoid);
	ex_err("ex_put_set_param",errmsg,exerrval);
	goto error_ret;    /* exit define mode and return */
      }

      /* resuse dimid from entry lists */

    } else {
      if ((status = nc_def_dim(exoid, numdfptr, 
			       num_dist_fact_in_set, &dimid)) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to define number of dist factors in %s %d in file id %d",
		ex_name_of_object(set_type), set_id,exoid);
	ex_err("ex_put_set_param",errmsg,exerrval);
	goto error_ret;          /* exit define mode and return */
      }
    }

    /* create variable array in which to store the set distribution factors
     */
    dims[0] = dimid;
    if ((status = nc_def_var(exoid, factptr, nc_flt_code(exoid), 1, dims, &varid)) != NC_NOERR) {
      exerrval = status;
      if (status == NC_ENAMEINUSE) {
	sprintf(errmsg,
		"Error: dist factors list already exists for %s %d in file id %d",
		ex_name_of_object(set_type), set_id,exoid);
	ex_err("ex_put_set_param",errmsg,exerrval);
      } else {
	sprintf(errmsg,
		"Error: failed to create dist factors list for %s %d in file id %d",
		ex_name_of_object(set_type), set_id,exoid);
	ex_err("ex_put_set_param",errmsg,exerrval);
      }
      goto error_ret;            /* exit define mode and return */
    }
  }

  /* leave define mode  */
  if ((status = nc_enddef (exoid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Error: failed to complete definition in file id %d", exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }

  return (EX_NOERR);

  /* Fatal error: exit definition mode and return */
 error_ret:
  if (nc_enddef (exoid) != NC_NOERR) {    /* exit define mode */
    sprintf(errmsg,
	    "Error: failed to complete definition for file id %d",
	    exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
  }
  return (EX_FATAL);
}
Example #4
0
static int open_mmtk_cdf_read(cdfdata *cdf, int conventionsknown) {
  int rc;
  size_t len; 
  mmtkdata *mmtk = &cdf->mmtk;

  /* If conventions specify MMTK then we're safe to continue */
  /* and we know what we're dealing with */
  if (conventionsknown) {
    cdf->type = CDF_TYPE_MMTK;
  }

  /* global attrib: "trajectory_type" (new format) */
  rc = nc_get_att_int(cdf->ncid, NC_GLOBAL, "trajectory_type", &mmtk->trajectorytype);
  if (rc == NC_NOERR) {
    printf("netcdfplugin) MMTK trajectory type: %d\n", mmtk->trajectorytype);
  } else {
    printf("netcdfplugin) Assuming MMTK trajectory type: %d\n", mmtk->trajectorytype);
    mmtk->trajectorytype = 0;
  }

  /* read in spatial dimension */
  rc = nc_inq_dimid(cdf->ncid, "xyz", &mmtk->xyzdimid);
  if (rc == NC_NOERR) {
    rc = nc_inq_dimlen(cdf->ncid, mmtk->xyzdimid, &mmtk->xyzdim);
    if (rc == NC_NOERR)
      printf("netcdfplugin) MMTK: xyz dimension: %ld\n", (long)mmtk->xyzdim);
    else 
      return CDF_ERR;
  } else {
    return CDF_ERR;
  }

  /* read in atom dimension */
  rc = nc_inq_dimid(cdf->ncid, "atom_number", &mmtk->atom_numberdimid); 
  if (rc == NC_NOERR) {
    rc = nc_inq_dimlen(cdf->ncid, mmtk->atom_numberdimid, &mmtk->atom_numberdim);
    if (rc == NC_NOERR) {
      printf("netcdfplugin) MMTK: atom_number dimension: %ld\n", (long)mmtk->atom_numberdim);
      cdf->natoms = mmtk->atom_numberdim; /* copy to format independent part */
    } else {
      return CDF_ERR;
    }
  } else {
    return CDF_ERR;
  }


  /* read in frame dimension */
  rc = nc_inq_dimid(cdf->ncid, "step_number", &mmtk->step_numberdimid);
  if (rc == NC_NOERR) {
    rc = nc_inq_dimlen(cdf->ncid, mmtk->step_numberdimid, &mmtk->step_numberdim);
    if (rc == NC_NOERR)
      printf("netcdfplugin) MMTK: step_number dimension: %ld\n", (long)mmtk->step_numberdim);
    else 
      return CDF_ERR;
  } else {
    return CDF_ERR;
  }


  /* read in minor step number dimension */
  rc = nc_inq_dimid(cdf->ncid, "minor_step_number", &mmtk->minor_step_numberdimid);
  if (rc == NC_NOERR) {
    rc = nc_inq_dimlen(cdf->ncid, mmtk->minor_step_numberdimid, &mmtk->minor_step_numberdim);
    if (rc == NC_NOERR)
      printf("netcdfplugin) MMTK: minor_step_number dimension: %ld\n", (long)mmtk->minor_step_numberdim);
    else 
      return CDF_ERR;
  } else if (rc == NC_EBADDIM) {
    printf("netcdfplugin) MMTK: no minor_step_number dimension\n");
    mmtk->minor_step_numberdim = 0;
  } else {
    return CDF_ERR;
  }


  /* read in description_length dimension */
  rc = nc_inq_dimid(cdf->ncid, "description_length", &mmtk->description_lengthdimid); 
  if (rc == NC_NOERR) {
    rc = nc_inq_dimlen(cdf->ncid, mmtk->description_lengthdimid, &mmtk->description_lengthdim);
    if (rc == NC_NOERR)
      printf("netcdfplugin) MMTK: description_length dimension: %ld\n", (long)mmtk->description_lengthdim);
    else
      return CDF_ERR;
  } else {
    return CDF_ERR;
  }


  /* get ID values for all of the variables we're interested in */
  rc = nc_inq_varid(cdf->ncid, "configuration", &mmtk->configuration_id);
  if (rc != NC_NOERR)
    return CDF_ERR;

  rc = nc_inq_varid(cdf->ncid, "description", &mmtk->description_id);
  if (rc != NC_NOERR)
    return CDF_ERR;

  /* check for PBC */
  rc = nc_inq_varid(cdf->ncid, "box_size", &mmtk->box_size_id);
  if (rc == NC_NOERR) {
    mmtk->has_box = 1;
    printf("netcdfplugin) MMTK: system has periodic boundary conditions\n");
  }
  else if (rc == NC_ENOTVAR)
    mmtk->has_box = 0;
  else
    return CDF_ERR;


  /* global attrib: "comment" -- optional */
  rc = nc_inq_attlen(cdf->ncid, NC_GLOBAL, "comment", &len);
  if (rc == NC_NOERR && len > 0) {
    mmtk->comment = (char *) malloc((len+1) * sizeof(char));
    nc_get_att_text(cdf->ncid, NC_GLOBAL, "comment", mmtk->comment);
    mmtk->comment[len] = '\0';
    printf("netcdfplugin) MMTK: comment '%s'\n", mmtk->comment);
  } 

  /* at this point we know that this is an MMTK trajectory */
  if (!conventionsknown) {
    printf("netcdfplugin) File is an old format MMTK trajectory without conventions\n");    
    cdf->type = CDF_TYPE_MMTK;
  }

  return CDF_SUCCESS;
}
Example #5
0
/*
 * reads the attribute names for an element block
 */
int ex_get_attr_names( int   exoid,
                       ex_entity_type obj_type,
                       ex_entity_id   obj_id,
                       char **names)
{
  int status;
  int varid, numattrdim, obj_id_ndx;
  size_t num_attr, i;
  char errmsg[MAX_ERR_LENGTH];
  const char* dnumobjatt;
  const char* vattrbname;

  exerrval = 0; /* clear error code */

  /* Determine index of obj_id in vobjids array */
  if (obj_type != EX_NODAL) {
    obj_id_ndx = ex_id_lkup(exoid,obj_type,obj_id);
    if (exerrval != 0) {
      if (exerrval == EX_NULLENTITY) {
	sprintf(errmsg,
		"Warning: no attributes found for NULL %s %"PRId64" in file id %d",
		ex_name_of_object(obj_type), obj_id, exoid);
	ex_err("ex_get_attr_names",errmsg,EX_NULLENTITY);
	return (EX_WARN);              /* no attributes for this object */
      } else {
	sprintf(errmsg,
		"Warning: failed to locate %s id %"PRId64" in id array in file id %d",
		ex_name_of_object(obj_type), obj_id, exoid);
	ex_err("ex_get_attr_names",errmsg,exerrval);
	return (EX_WARN);
      }
    }
  }

  switch (obj_type) {
  case EX_NODE_SET:
    dnumobjatt = DIM_NUM_ATT_IN_NS(obj_id_ndx);
    vattrbname = VAR_NAME_NSATTRIB(obj_id_ndx);
    break;
  case EX_SIDE_SET:
    dnumobjatt = DIM_NUM_ATT_IN_SS(obj_id_ndx);
    vattrbname = VAR_NAME_SSATTRIB(obj_id_ndx);
    break;
  case EX_EDGE_SET:
    dnumobjatt = DIM_NUM_ATT_IN_ES(obj_id_ndx);
    vattrbname = VAR_NAME_ESATTRIB(obj_id_ndx);
    break;
  case EX_FACE_SET:
    dnumobjatt = DIM_NUM_ATT_IN_FS(obj_id_ndx);
    vattrbname = VAR_NAME_FSATTRIB(obj_id_ndx);
    break;
  case EX_ELEM_SET:
    dnumobjatt = DIM_NUM_ATT_IN_ELS(obj_id_ndx);
    vattrbname = VAR_NAME_ELSATTRIB(obj_id_ndx);
    break;
  case EX_NODAL:
    dnumobjatt = DIM_NUM_ATT_IN_NBLK;
    vattrbname = VAR_NAME_NATTRIB;
    break;
  case EX_EDGE_BLOCK:
    dnumobjatt = DIM_NUM_ATT_IN_EBLK(obj_id_ndx);
    vattrbname = VAR_NAME_EATTRIB(obj_id_ndx);
    break;
  case EX_FACE_BLOCK:
    dnumobjatt = DIM_NUM_ATT_IN_FBLK(obj_id_ndx);
    vattrbname = VAR_NAME_FATTRIB(obj_id_ndx);
    break;
  case EX_ELEM_BLOCK:
    dnumobjatt = DIM_NUM_ATT_IN_BLK(obj_id_ndx);
    vattrbname = VAR_NAME_ATTRIB(obj_id_ndx);
    break;
  default:
    exerrval = 1005;
    sprintf(errmsg,
	    "Internal Error: unrecognized object type in switch: %d in file id %d",
	    obj_type,exoid);
    ex_err("ex_get_attr_names",errmsg,EX_MSG);
    return (EX_FATAL);              /* number of attributes not defined */
  }
  /* inquire id's of previously defined dimensions  */

  if ((status = nc_inq_dimid(exoid, dnumobjatt, &numattrdim)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Warning: no attributes found for %s %"PRId64" in file id %d",
	    ex_name_of_object(obj_type),obj_id,exoid);
    ex_err("ex_get_attr_names",errmsg,EX_MSG);
    return (EX_WARN);              /* no attributes for this object */
  }

  if ((status = nc_inq_dimlen(exoid, numattrdim, &num_attr)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Error: failed to get number of attributes for %s %"PRId64" in file id %d",
	    ex_name_of_object(obj_type),obj_id,exoid);
    ex_err("ex_get_attr_names",errmsg,exerrval);
    return (EX_FATAL);
  }

  /* It is OK if we don't find the attribute names since they were
     added at version 4.26; earlier databases won't have the names.
  */
  status = nc_inq_varid(exoid, vattrbname, &varid);

  /* read in the attributes */

  if (status == NC_NOERR) {
    /* read the names */
    status = ex_get_names_internal(exoid, varid, num_attr, names, obj_type, "ex_get_attr_names");
    if (status != NC_NOERR) {
      return (EX_FATAL);
    }
  } else {
    /* Names variable does not exist on the database; probably since this is an
     * older version of the database.  Return an empty array...
     */
    for (i=0; i<num_attr; i++) {
      names[i][0] = '\0';
    }
  }
  return(EX_NOERR);
}
int ex_get_set_param (int  exoid,
		      ex_entity_type set_type, 
		      int  set_id,
		      int *num_entry_in_set, 
		      int *num_dist_fact_in_set)
{
  int status;
  int varid, dimid, set_id_ndx;
  size_t lnum_entry_in_set;
  size_t lnum_dist_fact_in_set;
  char errmsg[MAX_ERR_LENGTH];
  char* numentryptr = NULL;
  char* numdfptr = NULL;

  exerrval = 0; /* clear error code */


  /* first check if any sets are specified */
  if ((status = nc_inq_dimid(exoid, ex_dim_num_objects(set_type), &dimid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Warning: no %ss stored in file id %d",
	    ex_name_of_object(set_type), exoid);
    ex_err("ex_get_set_param",errmsg,exerrval);
    return (EX_WARN);
  }

  /* Lookup index of set id in VAR_*S_IDS array */
  set_id_ndx = ex_id_lkup(exoid,set_type,set_id);
  if (exerrval != 0) {
    if (exerrval == EX_NULLENTITY)     /* NULL set? */
      {
	*num_entry_in_set = 0;
	*num_dist_fact_in_set = 0;
	return (EX_NOERR);
      } else {
      sprintf(errmsg,
	      "Error: failed to locate %s id %d in id array in file id %d",
	      ex_name_of_object(set_type), set_id,exoid);
      ex_err("ex_get_set_param",errmsg,exerrval);
      return (EX_FATAL);
    }
  }

  /* setup more pointers based on set_type */
  if (set_type == EX_NODE_SET) {
    numentryptr = DIM_NUM_NOD_NS(set_id_ndx);
    /* note we are using DIM_NUM_NODE_NS instead of DIM_NUM_DF_NS */
    numdfptr = DIM_NUM_NOD_NS(set_id_ndx);
  }
  else if (set_type == EX_EDGE_SET) {
    numentryptr = DIM_NUM_EDGE_ES(set_id_ndx);
    numdfptr = DIM_NUM_DF_ES(set_id_ndx);
  }
  else if (set_type == EX_FACE_SET) {
    numentryptr = DIM_NUM_FACE_FS(set_id_ndx);
    numdfptr = DIM_NUM_DF_FS(set_id_ndx);
  }
  else if (set_type == EX_SIDE_SET) {
    numentryptr = DIM_NUM_SIDE_SS(set_id_ndx);
    numdfptr = DIM_NUM_DF_SS(set_id_ndx);
  }
  if (set_type == EX_ELEM_SET) {
    numentryptr = DIM_NUM_ELE_ELS(set_id_ndx);
    numdfptr = DIM_NUM_DF_ELS(set_id_ndx);
  }

  /* inquire values of dimension for number of entities in set */
  if (ex_get_dimension(exoid, numentryptr,"entries", &lnum_entry_in_set,
		       &dimid, "ex_get_set_param") != NC_NOERR)
    return EX_FATAL;
  *num_entry_in_set = lnum_entry_in_set;

  /* Inquire value of dimension of number of dist factors for this set. 
     NOTE: For node sets, because DIM_NUM_DF_NS is not used, we check to see
     if the dist factor variable for a node set index exits. If it does not,
     the dist factor count is assumed to be zero, otherwise the dist factor 
     count will be the same as the number of nodes in the set. */

  if (set_type == EX_NODE_SET) {
    if ((status = nc_inq_varid(exoid, VAR_FACT_NS(set_id_ndx), &varid)) != NC_NOERR) {
      *num_dist_fact_in_set = 0;        /* signal dist factor doesn't exist */
      if (status == NC_ENOTVAR)
	return (EX_NOERR);
      else {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to locate the dist factors for %s %d in file id %d",
		ex_name_of_object(set_type), set_id,exoid);
	ex_err("ex_get_set_param",errmsg,exerrval);
	return (EX_FATAL);
      }
    }
    *num_dist_fact_in_set = lnum_entry_in_set;   /* # of df = # of nodes */
  }
  else {/* all other set types */
    if ((status = nc_inq_dimid(exoid, numdfptr, &dimid)) != NC_NOERR) {
      *num_dist_fact_in_set = 0; /* no distribution factors for this set*/
      if (status == NC_EBADDIM)
	return (EX_NOERR);
      else {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to locate number of dist factors in %s %d in file id %d",
		ex_name_of_object(set_type), set_id, exoid);
	ex_err("ex_get_set_param",errmsg,exerrval);
	return (EX_FATAL);
      }
    }

    if ((status = nc_inq_dimlen(exoid, dimid, &lnum_dist_fact_in_set)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
	      "Error: failed to get number of dist factors in %s %d in file id %d",
	      ex_name_of_object(set_type), set_id, exoid);
      ex_err("ex_get_set_param",errmsg,exerrval);
      return (EX_FATAL);
    }
    *num_dist_fact_in_set = lnum_dist_fact_in_set;
  }

  return (EX_NOERR);
}
int ex_get_partial_coord(int exoid, int64_t start_node_num, int64_t num_nodes, void *x_coor,
                         void *y_coor, void *z_coor)
{
  int status;
  int coordid;
  int coordidx, coordidy, coordidz;

  int    numnoddim, ndimdim;
  size_t num_nod;
  size_t num_dim, start[2], count[2], i;
  char   errmsg[MAX_ERR_LENGTH];

  EX_FUNC_ENTER();
  ex_check_valid_file_id(exoid, __func__);

  /* inquire id's of previously defined dimensions  */

  if (nc_inq_dimid(exoid, DIM_NUM_NODES, &numnoddim) != NC_NOERR) {
    /* If not found, then this file is storing 0 nodes.
       Return immediately */
    EX_FUNC_LEAVE(EX_NOERR);
  }

  if ((status = nc_inq_dimlen(exoid, numnoddim, &num_nod)) != NC_NOERR) {
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get number of nodes in file id %d", exoid);
    ex_err(__func__, errmsg, status);
    EX_FUNC_LEAVE(EX_FATAL);
  }

  --start_node_num;
  if (start_node_num + num_nodes > num_nod) {
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: start index (%" PRId64 ") + node count (%" PRId64
             ") is larger than total number of nodes (%" ST_ZU ") in file id %d",
             start_node_num, num_nodes, num_nod, exoid);
    ex_err(__func__, errmsg, EX_BADPARAM);
    EX_FUNC_LEAVE(EX_FATAL);
  }

  if (ex_get_dimension(exoid, DIM_NUM_DIM, "dimension count", &num_dim, &ndimdim, __func__) !=
      NC_NOERR) {
    EX_FUNC_LEAVE(EX_FATAL);
  }

  /* read in the coordinates  */
  if (ex_large_model(exoid) == 0) {
    if ((status = nc_inq_varid(exoid, VAR_COORD, &coordid)) != NC_NOERR) {
      snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate nodal coordinates in file id %d",
               exoid);
      ex_err(__func__, errmsg, status);
      EX_FUNC_LEAVE(EX_FATAL);
    }

    for (i = 0; i < num_dim; i++) {
      char *which;
      start[0] = i;
      start[1] = start_node_num;

      count[0] = 1;
      count[1] = num_nodes;
      if (count[1] == 0) {
        start[1] = 0;
      }

      if (i == 0 && x_coor != NULL) {
        which = "X";
        if (ex_comp_ws(exoid) == 4) {
          status = nc_get_vara_float(exoid, coordid, start, count, x_coor);
        }
        else {
          status = nc_get_vara_double(exoid, coordid, start, count, x_coor);
        }
      }
      else if (i == 1 && y_coor != NULL) {
        which = "Y";
        if (ex_comp_ws(exoid) == 4) {
          status = nc_get_vara_float(exoid, coordid, start, count, y_coor);
        }
        else {
          status = nc_get_vara_double(exoid, coordid, start, count, y_coor);
        }
      }
      else if (i == 2 && z_coor != NULL) {
        which = "Z";
        if (ex_comp_ws(exoid) == 4) {
          status = nc_get_vara_float(exoid, coordid, start, count, z_coor);
        }
        else {
          status = nc_get_vara_double(exoid, coordid, start, count, z_coor);
        }
      }

      if (status != NC_NOERR) {
        snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get %s coord array in file id %d", which,
                 exoid);
        ex_err(__func__, errmsg, status);
        EX_FUNC_LEAVE(EX_FATAL);
      }
    }
  }
  else {
    if ((status = nc_inq_varid(exoid, VAR_COORD_X, &coordidx)) != NC_NOERR) {
      snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate x nodal coordinates in file id %d",
               exoid);
      ex_err(__func__, errmsg, status);
      EX_FUNC_LEAVE(EX_FATAL);
    }

    if (num_dim > 1) {
      if ((status = nc_inq_varid(exoid, VAR_COORD_Y, &coordidy)) != NC_NOERR) {
        snprintf(errmsg, MAX_ERR_LENGTH,
                 "ERROR: failed to locate y nodal coordinates in file id %d", exoid);
        ex_err(__func__, errmsg, status);
        EX_FUNC_LEAVE(EX_FATAL);
      }
    }
    else {
      coordidy = 0;
    }

    if (num_dim > 2) {
      if ((status = nc_inq_varid(exoid, VAR_COORD_Z, &coordidz)) != NC_NOERR) {
        snprintf(errmsg, MAX_ERR_LENGTH,
                 "ERROR: failed to locate z nodal coordinates in file id %d", exoid);
        ex_err(__func__, errmsg, status);
        EX_FUNC_LEAVE(EX_FATAL);
      }
    }
    else {
      coordidz = 0;
    }

    /* write out the coordinates  */
    for (i = 0; i < num_dim; i++) {
      void *coor  = NULL;
      char *which = NULL;

      start[0] = start_node_num;
      count[0] = num_nodes;
      if (count[0] == 0) {
        start[0] = 0;
      }

      if (i == 0) {
        coor    = x_coor;
        which   = "X";
        coordid = coordidx;
      }
      else if (i == 1) {
        coor    = y_coor;
        which   = "Y";
        coordid = coordidy;
      }
      else if (i == 2) {
        coor    = z_coor;
        which   = "Z";
        coordid = coordidz;
      }

      if (coor != NULL && coordid != 0) {
        if (ex_comp_ws(exoid) == 4) {
          status = nc_get_vara_float(exoid, coordid, start, count, coor);
        }
        else {
          status = nc_get_vara_double(exoid, coordid, start, count, coor);
        }

        if (status != NC_NOERR) {
          snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get %s coord array in file id %d",
                   which, exoid);
          ex_err(__func__, errmsg, status);
          EX_FUNC_LEAVE(EX_FATAL);
        }
      }
    }
  }
  EX_FUNC_LEAVE(EX_NOERR);
}
int ex_put_elem_var_slab (int   exoid,
		          int   time_step,
		          int   elem_var_index,
		          ex_entity_id   elem_blk_id,
                          int64_t   start_pos,
		          int64_t   num_vals,
		          void *elem_var_vals)
{
  int status;
  int varid, dimid,time_dim, numelbdim, dims[2], elem_blk_id_ndx;
  size_t num_elem_blk, num_elem_var, start[2], count[2];
  int *elem_var_tab;
  char errmsg[MAX_ERR_LENGTH];

  exerrval = 0; /* clear error code */

  /* Determine index of elem_blk_id in VAR_ID_EL_BLK array */
  if ((elem_blk_id_ndx = ex_id_lkup(exoid, EX_ELEM_BLOCK, elem_blk_id)) < 0) {
    if (exerrval == EX_NULLENTITY) {
      sprintf(errmsg,
	      "Warning: no variables allowed for NULL block %"PRId64" in file id %d",
	      elem_blk_id, exoid);
      ex_err("ex_put_elem_var_slab", errmsg, EX_NULLENTITY);
      return (EX_WARN);
    } 
      sprintf(errmsg,
	      "Error: failed to locate element block id %"PRId64" in %s array in file id %d",
	      elem_blk_id, VAR_ID_EL_BLK, exoid);
      ex_err("ex_put_elem_var_slab", errmsg, exerrval);
      return (EX_FATAL);
    
  }

  if ((status = nc_inq_varid (exoid,
			      VAR_ELEM_VAR(elem_var_index, elem_blk_id_ndx), &varid)) != NC_NOERR) {
    if (status == NC_ENOTVAR) { /* variable doesn't exist, create it! */

      /*    inquire previously defined dimensions */

      /* check for the existance of an element variable truth table */
      if ((status = nc_inq_varid (exoid, VAR_ELEM_TAB, &varid)) == NC_NOERR) {
	/* find out number of element blocks and element variables */
	if ((status = nc_inq_dimid (exoid, DIM_NUM_EL_BLK, &dimid)) != NC_NOERR) {
	  exerrval = status;
	  sprintf(errmsg,
		  "Error: failed to locate number of element blocks in file id %d",
		  exoid);
	  ex_err("ex_put_elem_var_slab", errmsg, exerrval);
	  return (EX_FATAL);
	}

	if ((status = nc_inq_dimlen(exoid, dimid, &num_elem_blk)) != NC_NOERR) {
	  exerrval = status;
	  sprintf(errmsg,
		  "Error: failed to get number of element blocks in file id %d",
		  exoid);
	  ex_err("ex_put_elem_var_slab", errmsg, exerrval);
	  return (EX_FATAL);
	}

	if ((status = nc_inq_dimid (exoid, DIM_NUM_ELE_VAR, &dimid)) != NC_NOERR) {
	  exerrval = EX_BADPARAM;
	  sprintf(errmsg,
		  "Error: no element variables stored in file id %d",
		  exoid);
	  ex_err("ex_put_elem_var_slab", errmsg, exerrval);
	  return (EX_FATAL);
	}

	if ((status = nc_inq_dimlen(exoid, dimid, &num_elem_var)) != NC_NOERR) {
	  exerrval = status;
	  sprintf(errmsg,
		  "Error: failed to get number of element variables in file id %d",
		  exoid);
	  ex_err("ex_put_elem_var_slab", errmsg, exerrval);
	  return (EX_FATAL);
	}

	if (!(elem_var_tab =
	      (int *)malloc(num_elem_blk*num_elem_var*sizeof(int)))) {
	  exerrval = EX_MEMFAIL;
	  sprintf(errmsg,
		  "Error: failed to allocate memory for element variable truth table in file id %d",
		  exoid);
	  ex_err("ex_put_elem_var_slab", errmsg, exerrval);
	  return (EX_FATAL);
	}

	/*   read in the element variable truth table */
	if ((status = nc_get_var_int(exoid, varid, elem_var_tab)) != NC_NOERR) {
	  exerrval = status;
	  sprintf(errmsg,
		  "Error: failed to get truth table from file id %d", exoid);
	  ex_err("ex_put_elem_var_slab", errmsg, exerrval);
	  return (EX_FATAL);
	}

	if (elem_var_tab[num_elem_var*(elem_blk_id_ndx-1)+elem_var_index-1] == 0L) {
	  free(elem_var_tab);
	  exerrval = EX_BADPARAM;
	  sprintf(errmsg,
		  "Error: Invalid element variable %d, block %"PRId64" in file id %d",
		  elem_var_index, elem_blk_id, exoid);
	  ex_err("ex_put_elem_var_slab", errmsg, exerrval);
	  return (EX_FATAL);
	}
	free(elem_var_tab);
      }

      if ((status = nc_inq_dimid (exoid, DIM_TIME, &time_dim)) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to locate time dimension in file id %d", exoid);
	ex_err("ex_put_elem_var_slab", errmsg, exerrval);
	goto error_ret;		/* exit define mode and return */
      }

      if ((status = nc_inq_dimid(exoid, DIM_NUM_EL_IN_BLK(elem_blk_id_ndx), &numelbdim)) != NC_NOERR) {
	if (status == NC_EBADDIM) {
	  exerrval = status;
	  sprintf(errmsg,
		  "Error: number of elements in element block %"PRId64" not defined in file id %d",
		  elem_blk_id, exoid);
	  ex_err("ex_put_elem_var_slab", errmsg, exerrval);
	} else {
	  exerrval = status;
	  sprintf(errmsg,
		  "Error: failed to locate number of elements in element block %"PRId64" in file id %d",
		  elem_blk_id, exoid);
	  ex_err("ex_put_elem_var_slab", errmsg, exerrval);
	}
	goto error_ret;
      }

      /*    variable doesn't exist so put file into define mode  */
      if ((status = nc_redef (exoid)) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to put file id %d into define mode", exoid);
	ex_err("ex_put_elem_var_slab", errmsg, exerrval);
	return (EX_FATAL);
      }


      /*    define netCDF variable to store element variable values */
      dims[0] = time_dim;
      dims[1] = numelbdim;
      if ((status = nc_def_var(exoid, VAR_ELEM_VAR(elem_var_index, elem_blk_id_ndx),
			       nc_flt_code(exoid), 2, dims, &varid)) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to define element variable %d in file id %d",
		elem_var_index, exoid);
	ex_err("ex_put_elem_var_slab", errmsg, exerrval);
	goto error_ret;
      }
      ex_compress_variable(exoid, varid, 2);


      /*    leave define mode  */
      if ((status = nc_enddef(exoid)) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to complete element variable %s definition to file id %d",
		VAR_ELEM_VAR(elem_var_index, elem_blk_id_ndx), exoid);
	ex_err("ex_put_elem_var_slab", errmsg, exerrval);
	return (EX_FATAL);
      }
    } else {
      exerrval = status;
      sprintf(errmsg,
	      "Error: failed to locate element variable %s in file id %d",
	      VAR_ELEM_VAR(elem_var_index, elem_blk_id_ndx),exoid);
      ex_err("ex_put_elem_var_slab", errmsg, exerrval);
      return (EX_FATAL);
    }
  }

  /* store element variable values */
  start[0] = --time_step;
  start[1] = --start_pos;

  count[0] = 1;
  count[1] = num_vals;

  if (ex_comp_ws(exoid) == 4) {
    status = nc_put_vara_float(exoid, varid, start, count, elem_var_vals);
  } else {
    status = nc_put_vara_double(exoid, varid, start, count, elem_var_vals);
  }

  if (status != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Error: failed to store element variable %d in file id %d", 
	    elem_var_index, exoid);
    ex_err("ex_put_elem_var_slab", errmsg, exerrval);
    return (EX_FATAL);
  }

  return (EX_NOERR);

  /* Fatal error: exit definition mode and return */
 error_ret:
  if (nc_enddef (exoid) != NC_NOERR)     /* exit define mode */
    {
      sprintf(errmsg,
	      "Error: failed to complete definition for file id %d", exoid);
      ex_err("ex_put_elem_var_slab", errmsg, exerrval);
    }
  return (EX_FATAL);
}
Example #9
0
int ex_get_block_param( int exoid,
			ex_block *block )
{
  int dimid, connid, blk_id_ndx;
  size_t len, i;
  char  errmsg[MAX_ERR_LENGTH];
  int status;
  const char* dnument;
  const char* dnumnod;
  const char* dnumedg;
  const char* dnumfac;
  const char* dnumatt;
  const char* ablknam;
  const char* vblkcon;

  struct ex_file_item* file = ex_find_file_item(exoid);
  if (!file ) {
    char errmsg[MAX_ERR_LENGTH];
    exerrval = EX_BADFILEID;
    sprintf(errmsg,"Error: unknown file id %d in ex_get_block_param().",exoid);
    ex_err("ex_get_block_param",errmsg,exerrval);
  }
  
  exerrval = 0;

  /* First, locate index of element block id in VAR_ID_EL_BLK array */
  blk_id_ndx = ex_id_lkup(exoid,block->type,block->id);
  if (exerrval != 0)  {
    strcpy(block->topology, "NULL");     	/* NULL element type name */
    block->num_entry = 0;  /* no elements            */
    block->num_nodes_per_entry = 0;   /* no nodes               */
    block->num_edges_per_entry = 0;
    block->num_faces_per_entry = 0;
    block->num_attribute = 0;    /* no attributes          */
    if (exerrval == EX_NULLENTITY) {    /* NULL element block?    */
      return (EX_NOERR);
    } 
      sprintf(errmsg,
	      "Error: failed to locate %s id  %"PRId64" in id array in file id %d",
	      ex_name_of_object(block->type), block->id,exoid);
      ex_err("ex_get_block_param",errmsg,exerrval);
      return (EX_FATAL);
    
  }

  switch (block->type) {
  case EX_EDGE_BLOCK:
    dnument = DIM_NUM_ED_IN_EBLK(blk_id_ndx);
    dnumnod = DIM_NUM_NOD_PER_ED(blk_id_ndx);
    dnumedg = 0;
    dnumfac = 0;
    dnumatt = DIM_NUM_ATT_IN_EBLK(blk_id_ndx);
    vblkcon = VAR_EBCONN(blk_id_ndx);
    ablknam = ATT_NAME_ELB;
    break;
  case EX_FACE_BLOCK:
    dnument = DIM_NUM_FA_IN_FBLK(blk_id_ndx);
    dnumnod = DIM_NUM_NOD_PER_FA(blk_id_ndx);
    dnumedg = 0; /* it is possible this might be non-NULL some day */
    dnumfac = 0;
    dnumatt = DIM_NUM_ATT_IN_FBLK(blk_id_ndx);
    vblkcon = VAR_FBCONN(blk_id_ndx);
    ablknam = ATT_NAME_ELB;
    break;
  case EX_ELEM_BLOCK:
    dnument = DIM_NUM_EL_IN_BLK(blk_id_ndx);
    dnumnod = DIM_NUM_NOD_PER_EL(blk_id_ndx);
    dnumedg = DIM_NUM_EDG_PER_EL(blk_id_ndx);
    dnumfac = DIM_NUM_FAC_PER_EL(blk_id_ndx);
    dnumatt = DIM_NUM_ATT_IN_BLK(blk_id_ndx);
    vblkcon = VAR_CONN(blk_id_ndx);
    ablknam = ATT_NAME_ELB;
    break;
  default:
    exerrval = EX_BADPARAM;
    sprintf( errmsg, "Bad block type parameter (%d) specified for file id %d.",
	     block->type, exoid );
    return (EX_FATAL);
  }

  /* inquire values of some dimensions */
  if ((status = nc_inq_dimid (exoid, dnument, &dimid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Error: failed to locate number of entities in %s  %"PRId64" in file id %d",
	    ex_name_of_object(block->type),block->id,exoid);
    ex_err("ex_get_block_param",errmsg, exerrval);
    return(EX_FATAL);
  }
  
  if ((status = nc_inq_dimlen (exoid, dimid, &len)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Error: failed to get number of %ss in block  %"PRId64" in file id %d",
	    ex_name_of_object(block->type),block->id, exoid);
    ex_err("ex_get_block_param",errmsg, exerrval);
    return(EX_FATAL);
  }
  block->num_entry = len;

  if ((status = nc_inq_dimid (exoid, dnumnod, &dimid)) != NC_NOERR) {
    /* undefined => no node entries per element */
    len = 0;
  } else {
    if ((status = nc_inq_dimlen (exoid, dimid, &len)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
	      "Error: failed to get number of nodes/entity in %s  %"PRId64" in file id %d",
	      ex_name_of_object(block->type),block->id, exoid);
      ex_err("ex_get_block_param",errmsg, exerrval);
      return(EX_FATAL);
    }
  }
  block->num_nodes_per_entry = len;

  if (!file->has_edges || block->type != EX_ELEM_BLOCK) {
    block->num_edges_per_entry = 0;
  } else {
    if ((status = nc_inq_dimid (exoid, dnumedg, &dimid)) != NC_NOERR) {
      /* undefined => no edge entries per element */
      len = 0;
    } else {
      if ((status = nc_inq_dimlen (exoid, dimid, &len)) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to get number of edges/entry in %s  %"PRId64" in file id %d",
		ex_name_of_object(block->type),block->id, exoid);
	ex_err("ex_get_block_param",errmsg, exerrval);
	return(EX_FATAL);
      }
    }
    block->num_edges_per_entry = len;
  }

  if (!file->has_faces || block->type != EX_ELEM_BLOCK ) {
    block->num_faces_per_entry = 0;
  } else {
    if ((status = nc_inq_dimid (exoid, dnumfac, &dimid)) != NC_NOERR) {
      /* undefined => no face entries per element */
      len = 0;
    } else {
      if ((status = nc_inq_dimlen(exoid, dimid, &len)) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to get number of faces/entity in %s  %"PRId64" in file id %d",
		ex_name_of_object(block->type),block->id, exoid);
	ex_err("ex_get_block_param",errmsg, exerrval);
	return(EX_FATAL);
      }
    }
    block->num_faces_per_entry = len;
  }

  if ((status = nc_inq_dimid (exoid, dnumatt, &dimid)) != NC_NOERR) {
    /* dimension is undefined */
    block->num_attribute = 0;
  } else {
    if ((status = nc_inq_dimlen(exoid, dimid, &len)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
	      "Error: failed to get number of attributes in %s  %"PRId64" in file id %d",
	      ex_name_of_object(block->type),block->id, exoid);
      ex_err("ex_get_block_param",errmsg, exerrval);
      return(EX_FATAL);
    }
    block->num_attribute = len;
  }

  if (block->num_nodes_per_entry > 0) {
    ; /* Do nothing, vblkcon should be correctly set already */
  } else if (block->num_edges_per_entry > 0) {
    vblkcon = VAR_EBCONN(blk_id_ndx);
  } else if (block->num_faces_per_entry > 0) {
    vblkcon = VAR_FCONN(blk_id_ndx);
  }

  if (vblkcon) {
    /* look up connectivity array for this element block id */
    if ((status = nc_inq_varid (exoid, vblkcon, &connid)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
	      "Error: failed to locate connectivity array for %s  %"PRId64" in file id %d",
	      ex_name_of_object(block->type), block->id,exoid);
      ex_err("ex_get_block_param",errmsg, exerrval);
      return(EX_FATAL);
    }
    
    if ((status = nc_inq_attlen (exoid, connid, ablknam, &len)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
	      "Error: failed to get %s  %"PRId64" type in file id %d",
	      ex_name_of_object(block->type), block->id,exoid);
      ex_err("ex_get_block_param",errmsg, exerrval);
      return(EX_FATAL);
    }
    
    if (len > (MAX_STR_LENGTH+1)) {
      len = MAX_STR_LENGTH;
      sprintf (errmsg,
	       "Warning: %s  %"PRId64" type will be truncated to %ld chars", 
	       ex_name_of_object(block->type), block->id, (long)len);
      ex_err("ex_get_block_param",errmsg,EX_MSG);
    }
    
    for (i=0; i < MAX_STR_LENGTH+1; i++) {
      block->topology[i] = '\0';

    /* get the element type name */
    
}if ((status = nc_get_att_text (exoid, connid, ablknam, block->topology)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,"Error: failed to get %s  %"PRId64" type in file id %d",
	      ex_name_of_object(block->type), block->id, exoid);
      ex_err("ex_get_block_param",errmsg, exerrval);
      return(EX_FATAL);
    }
    
    /* get rid of trailing blanks */
    ex_trim_internal(block->topology);
  }
  return (EX_NOERR);
}
Example #10
0
int ex_get_conn(int exoid, ex_entity_type blk_type, ex_entity_id blk_id, void_int *nodeconn,
                void_int *edgeconn, void_int *faceconn)
{
  int connid  = -1;
  int econnid = -1;
  int fconnid = -1;

  int blk_id_ndx, status;

  int numnodperentdim = -1;
  int numedgperentdim = -1;
  int numfacperentdim = -1;

  int iexit = (EX_NOERR); /* exit status */

  size_t num_nodes_per_entry = 0;
  size_t num_edges_per_entry = 0;
  size_t num_faces_per_entry = 0;

  char errmsg[MAX_ERR_LENGTH];

  const char *dnumnodent = NULL;
  const char *dnumedgent = NULL;
  const char *dnumfacent = NULL;
  const char *vnodeconn  = NULL;
  const char *vedgeconn  = NULL;
  const char *vfaceconn  = NULL;

  /* Should we warn if edgeconn or faceconn are non-NULL?
   * No, fail silently so the same code can be used to read any type of block
   * info.
   * However, we will warn if edgeconn or faceconn are NULL but
   * num_edges_per_entry
   * or num_faces_per_entry (respectively) are positive.
   */
  exerrval = 0; /* clear error code */

  /* Locate index of element block id in VAR_ID_EL_BLK array */

  blk_id_ndx = ex_id_lkup(exoid, blk_type, blk_id);
  if (exerrval != 0) {
    if (exerrval == EX_NULLENTITY) {
      snprintf(errmsg, MAX_ERR_LENGTH,
               "Warning: no connectivity array for NULL %s %" PRId64 " in file id %d",
               ex_name_of_object(blk_type), blk_id, exoid);
      ex_err("ex_get_conn", errmsg, EX_NULLENTITY);
      return (EX_WARN); /* no connectivity array for this element block */
    }

    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to locate %s id %" PRId64 " in id array in file id %d",
             ex_name_of_object(blk_type), blk_id, exoid);
    ex_err("ex_get_conn", errmsg, exerrval);
    return (EX_FATAL);
  }

  switch (blk_type) {
  case EX_EDGE_BLOCK:
    dnumnodent = DIM_NUM_NOD_PER_ED(blk_id_ndx);
    dnumedgent = 0;
    dnumfacent = 0;
    vnodeconn  = VAR_EBCONN(blk_id_ndx);
    vedgeconn  = 0;
    vfaceconn  = 0;
    break;
  case EX_FACE_BLOCK:
    dnumnodent = DIM_NUM_NOD_PER_FA(blk_id_ndx);
    dnumedgent = 0;
    dnumfacent = 0;
    vnodeconn  = VAR_FBCONN(blk_id_ndx);
    vedgeconn  = 0;
    vfaceconn  = 0;
    break;
  case EX_ELEM_BLOCK:
    dnumnodent = DIM_NUM_NOD_PER_EL(blk_id_ndx);
    dnumedgent = DIM_NUM_EDG_PER_EL(blk_id_ndx);
    dnumfacent = DIM_NUM_FAC_PER_EL(blk_id_ndx);
    vnodeconn  = VAR_CONN(blk_id_ndx);
    vedgeconn  = VAR_ECONN(blk_id_ndx);
    vfaceconn  = VAR_FCONN(blk_id_ndx);
    break;
  default:
    exerrval = 1005;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "Internal ERROR: unrecognized block type in switch: %d in file id %d", blk_type,
             exoid);
    ex_err("ex_get_conn", errmsg, EX_MSG);
    return (EX_FATAL); /* number of attributes not defined */
  }
  /* inquire id's of previously defined dimensions  */

  num_nodes_per_entry = 0;
  if (nodeconn && dnumnodent) {
    if ((status = nc_inq_dimid(exoid, dnumnodent, &numnodperentdim)) != NC_NOERR) {
      numnodperentdim = -1;
    }
    else {
      if ((status = nc_inq_dimlen(exoid, numnodperentdim, &num_nodes_per_entry)) != NC_NOERR) {
        exerrval = status;
        snprintf(errmsg, MAX_ERR_LENGTH,
                 "ERROR: failed to get number of nodes/entity for %s %" PRId64 " in file id %d",
                 ex_name_of_object(blk_type), blk_id, exoid);
        ex_err("ex_get_conn", errmsg, exerrval);
        return (EX_FATAL);
      }
    }
  }

  if (edgeconn && dnumedgent) {
    num_edges_per_entry = 0;
    if ((status = nc_inq_dimid(exoid, dnumedgent, &numedgperentdim)) != NC_NOERR) {
      numedgperentdim = -1;
    }
    else {
      if ((status = nc_inq_dimlen(exoid, numedgperentdim, &num_edges_per_entry)) != NC_NOERR) {
        exerrval = status;
        snprintf(errmsg, MAX_ERR_LENGTH,
                 "ERROR: failed to get number of edges/entry for %s %" PRId64 " in file id %d",
                 ex_name_of_object(blk_type), blk_id, exoid);
        ex_err("ex_get_conn", errmsg, exerrval);
        return (EX_FATAL);
      }
    }
  }

  if (faceconn && dnumfacent) {
    num_faces_per_entry = 0;
    if ((status = nc_inq_dimid(exoid, dnumfacent, &numfacperentdim)) != NC_NOERR) {
      numfacperentdim = -1;
    }
    else {
      if ((status = nc_inq_dimlen(exoid, numfacperentdim, &num_faces_per_entry)) != NC_NOERR) {
        exerrval = status;
        snprintf(errmsg, MAX_ERR_LENGTH,
                 "ERROR: failed to get number of faces/entry for %s %" PRId64 " in file id %d",
                 ex_name_of_object(blk_type), blk_id, exoid);
        ex_err("ex_get_conn", errmsg, exerrval);
        return (EX_FATAL);
      }
    }
  }

  status = 0;
  if (nodeconn && (numnodperentdim >= 0) &&
      ((status = nc_inq_varid(exoid, vnodeconn, &connid)) != NC_NOERR)) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to locate node connectivity array for %s %" PRId64 " in file id %d",
             ex_name_of_object(blk_type), blk_id, exoid);
    ex_err("ex_get_conn", errmsg, exerrval);
    return (EX_FATAL);
  }

  status = 0;
  if (edgeconn && (numedgperentdim >= 0) &&
      ((status = nc_inq_varid(exoid, vedgeconn, &econnid)) != NC_NOERR)) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to locate edge connectivity array for %s %" PRId64 " in file id %d",
             ex_name_of_object(blk_type), blk_id, exoid);
    ex_err("ex_get_conn", errmsg, exerrval);
    return (EX_FATAL);
  }

  if (faceconn && (numfacperentdim >= 0) &&
      ((status = nc_inq_varid(exoid, vfaceconn, &fconnid)) != NC_NOERR)) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to locate face connectivity array for %s %" PRId64 " in file id %d",
             ex_name_of_object(blk_type), blk_id, exoid);
    ex_err("ex_get_conn", errmsg, exerrval);
    return (EX_FATAL);
  }

  /* read in the connectivity array */
  if (edgeconn && num_edges_per_entry > 0) {
    if (ex_int64_status(exoid) & EX_BULK_INT64_API) {
      status = nc_get_var_longlong(exoid, econnid, edgeconn);
    }
    else {
      status = nc_get_var_int(exoid, econnid, edgeconn);
    }

    if (status != NC_NOERR) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH,
               "ERROR: failed to get edge connectivity array for %s %" PRId64 " in file id %d",
               ex_name_of_object(blk_type), blk_id, exoid);
      ex_err("ex_get_conn", errmsg, exerrval);
      return (EX_FATAL);
    }
  }

  if (faceconn && num_faces_per_entry > 0) {
    if (ex_int64_status(exoid) & EX_BULK_INT64_API) {
      status = nc_get_var_longlong(exoid, fconnid, faceconn);
    }
    else {
      status = nc_get_var_int(exoid, fconnid, faceconn);
    }

    if (status != NC_NOERR) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH,
               "ERROR: failed to get face connectivity array for %s %" PRId64 " in file id %d",
               ex_name_of_object(blk_type), blk_id, exoid);
      ex_err("ex_get_conn", errmsg, exerrval);
      return (EX_FATAL);
    }
  }

  if (nodeconn && num_nodes_per_entry > 0) {
    if (ex_int64_status(exoid) & EX_BULK_INT64_API) {
      status = nc_get_var_longlong(exoid, connid, nodeconn);
    }
    else {
      status = nc_get_var_int(exoid, connid, nodeconn);
    }

    if (status != NC_NOERR) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH,
               "ERROR: failed to get node connectivity array for %s %" PRId64 " in file id %d",
               ex_name_of_object(blk_type), blk_id, exoid);
      ex_err("ex_get_conn", errmsg, exerrval);
      return (EX_FATAL);
    }
  }

  return iexit;
}
Example #11
0
/**
 * Convert a Version 2 Fortran IMAP vector into a Version 3 C imap vector.
 */
static ptrdiff_t*
f2c_v2imap(int ncid, int varid, const int* fimap, ptrdiff_t* cimap)
{
    int		rank;
    nc_type	datatype;

    if (nc_inq_vartype(ncid, varid, &datatype) ||
	nc_inq_varndims(ncid, varid, &rank) || rank <= 0)
    {
	return NULL;
    }

    /* else */
    if (fimap[0] == 0)
    {
	/*
	 * Special Fortran version 2 semantics: use external netCDF variable 
	 * structure.
	 */
	int		dimids[NC_MAX_VAR_DIMS];
	int		idim;
	size_t	total;

	if (nc_inq_vardimid(ncid, varid, dimids) != NC_NOERR)
	    return NULL;

	for (total = 1, idim = rank - 1; idim >= 0; --idim)
	{
	    size_t	length;

	    cimap[idim] = total;

	    if (nc_inq_dimlen(ncid, dimids[idim], &length) != NC_NOERR)
		return NULL;

	    total *= length;
	}
    }
    else
    {
	/*
	 * Regular Fortran version 2 semantics: convert byte counts to
	 * element counts.
	 */
	int	idim;
	size_t	size;

	switch (datatype)
	{

	    case NC_CHAR:
		size = sizeof(char);
		break;
	    case NC_BYTE:
#		if NF_INT1_IS_C_SIGNED_CHAR
		    size = sizeof(signed char);
#		elif NF_INT1_IS_C_SHORT
		    size = sizeof(short);
#		elif NF_INT1_IS_C_INT
		    size = sizeof(int);
#		elif NF_INT1_IS_C_LONG
		    size = sizeof(long);
#		endif
		break;
	    case NC_SHORT:
#		if NF_INT2_IS_C_SHORT
		    size = sizeof(short);
#		elif NF_INT2_IS_C_INT
		    size = sizeof(int);
#		elif NF_INT2_IS_C_LONG
		    size = sizeof(long);
#		endif
		break;
	    case NC_INT:
#		if NF_INT_IS_C_INT
		    size = sizeof(int);
#		elif NF_INT_IS_C_LONG
		    size = sizeof(long);
#		endif
		break;
	    case NC_FLOAT:
#		if NF_REAL_IS_C_FLOAT
		    size = sizeof(float);
#		elif NF_REAL_IS_C_DOUBLE
		    size = sizeof(double);
#		endif
		break;
	    case NC_DOUBLE:
#		if NF_DOUBLEPRECISION_IS_C_FLOAT
		    size = sizeof(float);
#		elif NF_DOUBLEPRECISION_IS_C_DOUBLE
		    size = sizeof(double);
#		endif
		break;
	    default:
		return NULL;
	}

	for (idim = 0; idim < rank; ++idim)
	    cimap[idim] = fimap[rank - 1 - idim] / size;
    }

    return cimap;
}
Example #12
0
int
main(int argc, char **argv)
{
   printf("\n*** Testing netcdf-4 dimensions.\n");
   printf("*** Testing that netcdf-4 dimids inq works on netcdf-3 file...");
   {
      int ncid, dimid;
      int ndims_in, dimids_in[MAX_DIMS];

      /* Create a netcdf-3 file with one dim. */
      if (nc_create(FILE_NAME, 0, &ncid)) ERR;
      if (nc_def_dim(ncid, LAT_NAME, LAT_LEN, &dimid)) ERR;
      if (nc_close(ncid)) ERR;

      /* Open the file and make sure nc_inq_dimids yeilds correct
       * result. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_unlimdims(ncid, &ndims_in, dimids_in)) ERR;
      if (ndims_in != 0) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Testing that netcdf-4 dimids inq works on more complex netcdf-3 file...");
   {
      int ncid, dimid;
      int lon_dimid;
      int ndims_in, dimids_in[MAX_DIMS];

      /* Create a netcdf-3 file with three dim. */
      if (nc_create(FILE_NAME, 0, &ncid)) ERR;
      if (nc_def_dim(ncid, LEVEL_NAME, NC_UNLIMITED, &dimid)) ERR;
      if (nc_def_dim(ncid, LAT_NAME, LAT_LEN, &dimid)) ERR;
      if (nc_def_dim(ncid, LON_NAME, LON_LEN, &lon_dimid)) ERR;
      if (nc_close(ncid)) ERR;

      /* Open the file and make sure nc_inq_dimids yeilds correct
       * result. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 3 || dimids_in[0] != 0 || dimids_in[1] != 1 ||
	 dimids_in[2] != 2) ERR;
      if (nc_inq_unlimdims(ncid, &ndims_in, dimids_in)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** Testing file with just one dimension...");
   {
      int ncid, dimid;
      int ndims_in, dimids_in[MAX_DIMS];
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      int dimid_in;

      /* Create a file with one dim and nothing else. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, LAT_NAME, LAT_LEN, &dimid)) ERR;

      /* Check out what we've got. */
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != LAT_LEN || strcmp(name_in, LAT_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1) ERR;
      if (nc_inq_dimid(ncid, LAT_NAME, &dimid_in)) ERR;
      if (dimid_in != 0) ERR;
      if (nc_inq_dimname(ncid, 0, name_in)) ERR;
      if (strcmp(name_in, LAT_NAME)) ERR;
      if (nc_inq_dimlen(ncid, 0, &len_in)) ERR;
      if (len_in != LAT_LEN) ERR;
      if (nc_inq_unlimdims(ncid, &ndims_in, dimids_in)) ERR;
      if (ndims_in != 0) ERR;
      if (nc_close(ncid)) ERR;

      /* Reopen and check it out again. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != LAT_LEN || strcmp(name_in, LAT_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1) ERR;
      if (nc_inq_dimid(ncid, LAT_NAME, &dimid_in)) ERR;
      if (dimid_in != 0) ERR;
      if (nc_inq_dimname(ncid, 0, name_in)) ERR;
      if (strcmp(name_in, LAT_NAME)) ERR;
      if (nc_inq_dimlen(ncid, 0, &len_in)) ERR;
      if (len_in != LAT_LEN) ERR;
      if (nc_inq_unlimdims(ncid, &ndims_in, dimids_in)) ERR;
      if (ndims_in != 0) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** Testing renaming of one dimension...");
   {
      int ncid, dimid, dimid_in;
      char name_in[NC_MAX_NAME + 1];
      size_t len_in;
      int ndims_in, dimids_in[MAX_DIMS];

      /* Reopen the file with one dim, and change the name of the dim. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_rename_dim(ncid, 0, BUBBA)) ERR;

      /* Check out what we've got. */
      dimid = 0;
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != LAT_LEN || strcmp(name_in, BUBBA)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1) ERR;
      if (dimids_in[0] != 0) ERR;
      if (nc_inq_dimid(ncid, BUBBA, &dimid_in)) ERR;
      if (dimid_in != 0) ERR;
      if (nc_inq_dimname(ncid, 0, name_in)) ERR;
      if (strcmp(name_in, BUBBA)) ERR;
      if (nc_inq_dimlen(ncid, 0, &len_in)) ERR;
      if (len_in != LAT_LEN) ERR;
      if (nc_close(ncid)) ERR;

      /* Reopen and check out what we've got again. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != LAT_LEN || strcmp(name_in, BUBBA)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_dimid(ncid, BUBBA, &dimid_in)) ERR;
      if (dimid_in != 0) ERR;
      if (nc_inq_dimname(ncid, 0, name_in)) ERR;
      if (strcmp(name_in, BUBBA)) ERR;
      if (nc_inq_dimlen(ncid, 0, &len_in)) ERR;
      if (len_in != LAT_LEN) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Testing renaming dimensions and vars...");
   {
#define FILE_NAME1 "foo1.nc"
#define FILE_NAME2 "foo2.nc"
#define FILE_NAME3 "foo3.nc"
#define FILE_NAME4 "foo4.nc"
#define DIM_NAME "lat_T42"
#define VAR_NAME DIM_NAME
#define DIM_NAME2 "lat"
#define VAR_NAME2 DIM_NAME2
#define RANK_lat_T42 1
      int  ncid, varid, dimid;
      int lat_T42_dim;
      size_t lat_T42_len = 3;
      int lat_T42_id;
      int lat_T42_dims[RANK_lat_T42];
      char name[NC_MAX_NAME + 1];

    /* =========== */
    /* Sub-test #1 */
    /* =========== */
      /* create file with dimension and associated coordinate variable */
      if (nc_create(FILE_NAME1, NC_CLOBBER|NC_NETCDF4|NC_CLASSIC_MODEL, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM_NAME, lat_T42_len, &lat_T42_dim)) ERR;
      lat_T42_dims[0] = lat_T42_dim;
      if (nc_def_var(ncid, VAR_NAME, NC_INT, RANK_lat_T42, lat_T42_dims, &lat_T42_id)) ERR;
      if (nc_close(ncid)) ERR;


      /* reopen file, rename coordinate dimension and then associated variable */
      if (nc_open(FILE_NAME1, NC_WRITE, &ncid)) ERR;
      if (nc_inq_dimid(ncid, DIM_NAME, &dimid)) ERR;
      if (nc_inq_varid(ncid, VAR_NAME, &varid)) ERR;
      if (nc_rename_dim(ncid, dimid, DIM_NAME2)) ERR;
      if (nc_rename_var(ncid, varid, VAR_NAME2)) ERR;
      if (nc_close(ncid)) ERR;


      /* reopen file, check coordinate dimension and associated variable names */
      /* Should be just like they created the file with DIM_NAME2 & VAR_NAME2 to
       *  begin with.
       */
      if (nc_open(FILE_NAME1, NC_WRITE, &ncid)) ERR;
      if (nc_inq_dimid(ncid, DIM_NAME2, &dimid)) ERR;
      if (nc_inq_varid(ncid, VAR_NAME2, &varid)) ERR;
      if (nc_inq_dimname(ncid, dimid, name)) ERR;
      if (strcmp(name, DIM_NAME2)) ERR;
      if (nc_inq_varname(ncid, varid, name)) ERR;
      if (strcmp(name, VAR_NAME2)) ERR;
      if (nc_close(ncid)) ERR;


    /* =========== */
    /* Sub-test #2 */
    /* =========== */
      /* create file with dimension and associated coordinate variable */
      if (nc_create(FILE_NAME1, NC_CLOBBER|NC_NETCDF4|NC_CLASSIC_MODEL, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM_NAME, lat_T42_len, &lat_T42_dim)) ERR;
      lat_T42_dims[0] = lat_T42_dim;
      if (nc_def_var(ncid, VAR_NAME, NC_INT, RANK_lat_T42, lat_T42_dims, &lat_T42_id)) ERR;
      if (nc_close(ncid)) ERR;


      /* reopen file, just rename coordinate dimension */
      if (nc_open(FILE_NAME1, NC_WRITE, &ncid)) ERR;
      if (nc_inq_dimid(ncid, DIM_NAME, &dimid)) ERR;
      if (nc_rename_dim(ncid, dimid, DIM_NAME2)) ERR;
      if (nc_close(ncid)) ERR;


      /* reopen file, check coordinate dimension and associated variable names */
      /* Should be just like the file was created with DIM_NAME2 to begin with */
      if (nc_open(FILE_NAME1, NC_WRITE, &ncid)) ERR;
      if (nc_inq_dimid(ncid, DIM_NAME2, &dimid)) ERR;
      if (nc_inq_varid(ncid, VAR_NAME, &varid)) ERR;
      if (nc_inq_dimname(ncid, dimid, name)) ERR;
      if (strcmp(name, DIM_NAME2)) ERR;
      if (nc_inq_varname(ncid, varid, name)) ERR;
      if (strcmp(name, VAR_NAME)) ERR;
      if (nc_close(ncid)) ERR;


    /* =========== */
    /* Sub-test #3 */
    /* =========== */
      /* create file with dimension and associated coordinate variable */
      if (nc_create(FILE_NAME1, NC_CLOBBER|NC_NETCDF4|NC_CLASSIC_MODEL, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM_NAME, lat_T42_len, &lat_T42_dim)) ERR;
      lat_T42_dims[0] = lat_T42_dim;
      if (nc_def_var(ncid, VAR_NAME, NC_INT, RANK_lat_T42, lat_T42_dims, &lat_T42_id)) ERR;
      if (nc_close(ncid)) ERR;


      /* reopen file, just rename variable */
      if (nc_open(FILE_NAME1, NC_WRITE, &ncid)) ERR;
      if (nc_inq_varid(ncid, VAR_NAME, &varid)) ERR;
      if (nc_rename_var(ncid, varid, VAR_NAME2)) ERR;
      if (nc_close(ncid)) ERR;


      /* reopen file, check coordinate dimension and associated variable names */
      /* Should be just like the file was created with VAR_NAME2 to begin with */
      if (nc_open(FILE_NAME1, NC_WRITE, &ncid)) ERR;
      if (nc_inq_dimid(ncid, DIM_NAME, &dimid)) ERR;
      if (nc_inq_varid(ncid, VAR_NAME2, &varid)) ERR;
      if (nc_inq_dimname(ncid, dimid, name)) ERR;
      if (strcmp(name, DIM_NAME)) ERR;
      if (nc_inq_varname(ncid, varid, name)) ERR;
      if (strcmp(name, VAR_NAME2)) ERR;
      if (nc_close(ncid)) ERR;


    /* =========== */
    /* Sub-test #4 */
    /* =========== */
      /* create file with dimension and associated coordinate variable */
      if (nc_create(FILE_NAME1, NC_CLOBBER|NC_NETCDF4|NC_CLASSIC_MODEL, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM_NAME, lat_T42_len, &lat_T42_dim)) ERR;
      lat_T42_dims[0] = lat_T42_dim;
      if (nc_def_var(ncid, VAR_NAME, NC_INT, RANK_lat_T42, lat_T42_dims, &lat_T42_id)) ERR;
      if (nc_close(ncid)) ERR;


      /* reopen file, rename associated variable and then coordinate dimension */
      if (nc_open(FILE_NAME1, NC_WRITE, &ncid)) ERR;
      if (nc_inq_dimid(ncid, DIM_NAME, &dimid)) ERR;
      if (nc_inq_varid(ncid, VAR_NAME, &varid)) ERR;
      if (nc_rename_var(ncid, varid, VAR_NAME2)) ERR;
      if (nc_rename_dim(ncid, dimid, DIM_NAME2)) ERR;
      if (nc_close(ncid)) ERR;


      /* reopen file, check coordinate dimension and associated variable names */
      /* Should be just like they created the file with DIM_NAME2 & VAR_NAME2 to
       *  begin with.
       */
      if (nc_open(FILE_NAME1, NC_WRITE, &ncid)) ERR;
      if (nc_inq_dimid(ncid, DIM_NAME2, &dimid)) ERR;
      if (nc_inq_varid(ncid, VAR_NAME2, &varid)) ERR;
      if (nc_inq_dimname(ncid, dimid, name)) ERR;
      if (strcmp(name, DIM_NAME2)) ERR;
      if (nc_inq_varname(ncid, varid, name)) ERR;
      if (strcmp(name, VAR_NAME2)) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Testing file with just one unlimited dimension...");
   {
      int ncid, dimid;
      int ndims_in, dimids_in[MAX_DIMS];
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      int unlimdimid_in;
      int nunlimdims_in;

      /* Create a file with one unlimied dim and nothing else. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, LEVEL_NAME, NC_UNLIMITED, &dimid)) ERR;

      /* Check it out before the enddef. */
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != NC_UNLIMITED || strcmp(name_in, LEVEL_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_unlimdim(ncid, &unlimdimid_in)) ERR;
      if (unlimdimid_in != 0) ERR;
      if (nc_inq_unlimdims(ncid, &nunlimdims_in, &unlimdimid_in)) ERR;
      if (nunlimdims_in != 1 || unlimdimid_in != 0) ERR;

      /* Automatically enddef and close. */
      if (nc_close(ncid)) ERR;

      /* Reopen and check it out. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != NC_UNLIMITED || strcmp(name_in, LEVEL_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_unlimdim(ncid, &unlimdimid_in)) ERR;
      if (unlimdimid_in != 0) ERR;
      if (nc_inq_unlimdims(ncid, &nunlimdims_in, &unlimdimid_in)) ERR;
      if (nunlimdims_in != 1 || unlimdimid_in != 0) ERR;
      if (unlimdimid_in != 0) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
#define ROMULUS "Romulus"
#define REMUS "Remus"
#define DIMS2 2
   printf("*** Testing file with two unlimited dimensions...");
   {
      int ncid, dimid[DIMS2];
      int ndims_in, dimids_in[DIMS2];
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      int unlimdimid_in[DIMS2];
      int nunlimdims_in;

      /* Create a file with two unlimited dims and nothing else. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, REMUS, NC_UNLIMITED, &dimid[0])) ERR;
      if (nc_def_dim(ncid, ROMULUS, NC_UNLIMITED, &dimid[1])) ERR;

      /* Check it out before the enddef. */
      if (nc_inq_dim(ncid, dimid[0], name_in, &len_in)) ERR;
      if (len_in != NC_UNLIMITED || strcmp(name_in, REMUS)) ERR;
      if (nc_inq_dim(ncid, dimid[1], name_in, &len_in)) ERR;
      if (len_in != NC_UNLIMITED || strcmp(name_in, ROMULUS)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 2 || dimids_in[0] != 0 || dimids_in[1] != 1) ERR;
      if (nc_inq_unlimdim(ncid, &unlimdimid_in[0])) ERR;
      if (unlimdimid_in[0] != 0) ERR;
      if (nc_inq_unlimdims(ncid, &nunlimdims_in, unlimdimid_in)) ERR;
      if (nunlimdims_in != 2 || unlimdimid_in[0] != 0 || unlimdimid_in[1] != 1) ERR;

      /* Automatically enddef and close. */
      if (nc_close(ncid)) ERR;

      /* Reopen and check it out. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Testing ordering of dimensions...");
   {
#define A_NAME "a"
#define B_NAME "b"
#define A_LEN 50
#define B_LEN 92
#define A_DIMID 1
#define B_DIMID 0

      int ncid;
      int ndims_in, dimids_in[MAX_DIMS];
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      int dimid_a, dimid_b;

      /* Create a file with two dims and nothing else. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, B_NAME, B_LEN, &dimid_b)) ERR;
      if (nc_def_dim(ncid, A_NAME, A_LEN, &dimid_a)) ERR;
      if (dimid_b != B_DIMID || dimid_a != A_DIMID) ERR;

      /* Check out what we've got. */
      if (nc_inq_dim(ncid, dimid_a, name_in, &len_in)) ERR;
      if (len_in != A_LEN || strcmp(name_in, A_NAME)) ERR;
      if (nc_inq_dim(ncid, dimid_b, name_in, &len_in)) ERR;
      if (len_in != B_LEN || strcmp(name_in, B_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 2 || dimids_in[0] != 0 || dimids_in[1] != 1) ERR;

      if (nc_close(ncid)) ERR;

      /* Reopen and check it out again. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;

      if (nc_inq_dim(ncid, B_DIMID, name_in, &len_in)) ERR;
      if (len_in != B_LEN || strcmp(name_in, B_NAME)) ERR;
      if (nc_inq_dim(ncid, A_DIMID, name_in, &len_in)) ERR;
      if (len_in != A_LEN || strcmp(name_in, A_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 2 || dimids_in[0] != 0 ||
	  dimids_in[1] != 1) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Testing file with just one unlimited dimension and one var...");
   {
      int ncid, dimid, dimids[MAX_DIMS];
      int level_varid;
      int natts_in, ndims_in, dimids_in[MAX_DIMS];
      nc_type xtype_in;
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      int unlimdimid_in;
      size_t start[MAX_DIMS], count[MAX_DIMS];
      int varid_in, nvars_in, nunlimdims_in;
      unsigned long long uint64_data[1] = {42};

      /* Create a file with one unlimied dim and nothing else. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, LEVEL_NAME, NC_UNLIMITED, &dimid)) ERR;
      if (dimid != 0) ERR;
      dimids[0] = dimid;
      if (nc_def_var(ncid, LEVEL_NAME, NC_UINT64, 1, dimids, &level_varid)) ERR;
      if (level_varid != 0) ERR;

      /* Check it out before enddef. */
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != 0 || strcmp(name_in, LEVEL_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_unlimdim(ncid, &unlimdimid_in)) ERR;
      if (unlimdimid_in != 0) ERR;
      if (nc_inq_unlimdims(ncid, &nunlimdims_in, &unlimdimid_in)) ERR;
      if (nunlimdims_in != 1 || unlimdimid_in != 0) ERR;
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 1 || natts_in != 0 || unlimdimid_in != 0) ERR;
      if (nc_inq_varid(ncid, LEVEL_NAME, &varid_in)) ERR;
      if (varid_in != 0) ERR;
      if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, LEVEL_NAME) || xtype_in != NC_UINT64 || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;
      if (nc_inq_varname(ncid, 0, name_in)) ERR;
      if (strcmp(name_in, LEVEL_NAME)) ERR;

      /* Now write one record of data to the var. */
      start[0] = 0;
      count[0] = 1;
      if (nc_put_vara_ulonglong(ncid, 0, start, count, uint64_data)) ERR;

      /* Check dimension informaiton again. Now the length of this
       * dimension should be one. */
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != 1 || strcmp(name_in, LEVEL_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_dimlen(ncid, 0, &len_in)) ERR;
      if (len_in != 1) ERR;
      if (nc_inq_unlimdim(ncid, &unlimdimid_in)) ERR;
      if (unlimdimid_in != 0) ERR;
      if (nc_inq_unlimdims(ncid, &nunlimdims_in, &unlimdimid_in)) ERR;
      if (nunlimdims_in != 1 || unlimdimid_in != 0) ERR;
      if (unlimdimid_in != 0) ERR;
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 1 || natts_in != 0 || unlimdimid_in != 0) ERR;
      if (nc_inq_varid(ncid, LEVEL_NAME, &varid_in)) ERR;
      if (varid_in != 0) ERR;
      if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, LEVEL_NAME) || xtype_in != NC_UINT64 || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;
      if (nc_inq_varname(ncid, 0, name_in)) ERR;
      if (strcmp(name_in, LEVEL_NAME)) ERR;

      /* Close the file. */
      if (nc_close(ncid)) ERR;

      /* Check it out. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != 1 || strcmp(name_in, LEVEL_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_unlimdim(ncid, &unlimdimid_in)) ERR;
      if (unlimdimid_in != 0) ERR;
      if (nc_inq_unlimdims(ncid, &nunlimdims_in, &unlimdimid_in)) ERR;
      if (nunlimdims_in != 1 || unlimdimid_in != 0) ERR;
      if (unlimdimid_in != 0) ERR;
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 1 || natts_in != 0 || unlimdimid_in != 0) ERR;
      if (nc_inq_varid(ncid, LEVEL_NAME, &varid_in)) ERR;
      if (varid_in != 0) ERR;
      if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, LEVEL_NAME) || xtype_in != NC_UINT64 || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;
      if (nc_inq_varname(ncid, 0, name_in)) ERR;
      if (strcmp(name_in, LEVEL_NAME)) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Testing adding a coordinate var to file with dimension...");
   {
      int ncid, dimid, dimids[MAX_DIMS];
      int natts_in, ndims_in, dimids_in[MAX_DIMS];
      nc_type xtype_in;
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      int unlimdimid_in;
      int nvars_in, dim5_varid;

      /* Create a file with one dim and nothing else. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM5_NAME, DIM5_LEN, &dimid)) ERR;

      /* Check out what we've got. */
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 0 || natts_in != 0 ||
	 unlimdimid_in != -1) ERR;
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != DIM5_LEN || strcmp(name_in, DIM5_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;

      if (nc_close(ncid)) ERR;

      /* Reopen and check it out again. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 0 || natts_in != 0 ||
	 unlimdimid_in != -1) ERR;
      if (nc_inq_dim(ncid, 0, name_in, &len_in)) ERR;
      if (len_in != DIM5_LEN || strcmp(name_in, DIM5_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;

      /* Add a coordinate var for this dimension. */
      dimids[0] = 0;
      if (nc_def_var(ncid, DIM5_NAME, NC_FLOAT, 1, dimids, &dim5_varid)) ERR;

      /* Check it out. */
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 1 || natts_in != 0 ||
	 unlimdimid_in != -1) ERR;
      if (nc_inq_dim(ncid, 0, name_in, &len_in)) ERR;
      if (len_in != DIM5_LEN || strcmp(name_in, DIM5_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, DIM5_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;

      if (nc_close(ncid)) ERR;

      /* Reopen and check it out again. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 1 || natts_in != 0 ||
	 unlimdimid_in != -1) ERR;
      if (nc_inq_dim(ncid, 0, name_in, &len_in)) ERR;
      if (len_in != DIM5_LEN || strcmp(name_in, DIM5_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, DIM5_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;

      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Testing adding a coordinate var to file with unlimited dimension...");
   {
      int ncid, dimid, dimids[MAX_DIMS];
      int natts_in, ndims_in, dimids_in[MAX_DIMS];
      nc_type xtype_in;
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      int unlimdimid_in;
      size_t start[MAX_DIMS], count[MAX_DIMS], index[MAX_DIMS];
      unsigned short data[2] = {42, 24}, data_in[2];
      int nvars_in, hp_varid, dim5_varid;

      /* Create a file with one dim and one var. This time make
       * it an unlimited dim. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM5_NAME, NC_UNLIMITED, &dimid)) ERR;
      if (dimid != 0) ERR;
      dimids[0] = dimid;
      if (nc_def_var(ncid, HP_NAME, NC_USHORT, 1, dimids, &hp_varid)) ERR;
      if (hp_varid != 0) ERR;

      /* Check out what we've got. */
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 1 || natts_in != 0 ||
	 unlimdimid_in != 0) ERR;
      if (nc_inq_dim(ncid, 0, name_in, &len_in)) ERR;
      if (len_in != 0 || strcmp(name_in, DIM5_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, HP_NAME) || xtype_in != NC_USHORT || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;

      /* Add a record to the HP variable. */
      start[0] = 0;
      count[0] = 1;
      if (nc_put_vara(ncid, hp_varid, start, count, data)) ERR;

      /* Check to ensure dimension grew. */
      if (nc_inq_dim(ncid, 0, name_in, &len_in)) ERR;
      if (len_in != 1 || strcmp(name_in, DIM5_NAME)) ERR;

      /* Reread the value just written. */
      index[0] = 0;
      if (nc_get_var1_ushort(ncid, hp_varid, index, data_in)) ERR;
      if (data_in[0] != data[0]) ERR;

      if (nc_close(ncid)) ERR;

      /* Reopen and check it out again. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 1 || natts_in != 0 ||
	 unlimdimid_in != 0) ERR;
      if (nc_inq_dim(ncid, 0, name_in, &len_in)) ERR;
      if (len_in != 1 || strcmp(name_in, DIM5_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;

      /* Add a coordinate var for this dimension. */
      dimids[0] = 0;
      if (nc_def_var(ncid, DIM5_NAME, NC_FLOAT, 1, dimids, &dim5_varid)) ERR;

      /* Check it out. */
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 2 || natts_in != 0 ||
	 unlimdimid_in != 0) ERR;
      if (nc_inq_dim(ncid, 0, name_in, &len_in)) ERR;
      if (len_in != 1 || strcmp(name_in, DIM5_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_var(ncid, dim5_varid, name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, DIM5_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;

      if (nc_close(ncid)) ERR;

      /* Reopen and check it out again. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 2 || natts_in != 0 ||
	 unlimdimid_in != 0) ERR;
      if (nc_inq_dim(ncid, 0, name_in, &len_in)) ERR;
      if (len_in != 1 || strcmp(name_in, DIM5_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_var(ncid, dim5_varid, name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, DIM5_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;

      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Creating file with 1 data var, 2 dims, and 2 coord. vars...");

   {
      int ncid, dimids[MAX_DIMS];
      int lat_dimid, lon_dimid, lat_varid, lon_varid;
      int pres_varid;
      char name_in[NC_MAX_NAME + 1];
      int natts_in, ndims_in, dimids_in[MAX_DIMS];
      nc_type xtype_in;
      size_t len_in;
      float lat[LAT_LEN], lon[LON_LEN];
      float lat_in[LAT_LEN], lon_in[LON_LEN];
      double pres[LAT_LEN][LON_LEN], pres_in[LAT_LEN][LON_LEN];
      int i, j;

      /* Lats and lons suitable for some South American data. */
      for (lat[0] = 40.0, i = 1; i < LAT_LEN; i++)
	 lat[i] = lat[i - 1] + .5;
      for (lon[0] = 20.0, i = 1; i < LON_LEN; i++)
	 lon[i] = lon[i - 1] + 1.5;

      /* Some phoney 2D pressure data. */
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    pres[i][j] = 1013.1 + j;

      /* Create a file. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;

      /* Define lat and lon dimensions, with associated variables. */
      if (nc_def_dim(ncid, LAT_NAME, LAT_LEN, &lat_dimid)) ERR;
      dimids[0] = lat_dimid;
      if (nc_def_var(ncid, LAT_NAME, NC_FLOAT, 1, dimids, &lat_varid)) ERR;
      if (nc_def_dim(ncid, LON_NAME, LON_LEN, &lon_dimid)) ERR;
      dimids[0] = lon_dimid;
      if (nc_def_var(ncid, LON_NAME, NC_FLOAT, 1, dimids, &lon_varid)) ERR;

      /* Define a 2D variable called pressure, with NC_DOUBLE on a lat
       * lon grid. */
      dimids[0] = lat_dimid;
      dimids[1] = lon_dimid;
      if (nc_def_var(ncid, PRES_NAME, NC_DOUBLE, 2, dimids, &pres_varid)) ERR;

      /* Check our dimensions. */
      if (nc_inq_dim(ncid, lat_dimid, name_in, &len_in)) ERR;
      if (len_in != LAT_LEN || strcmp(name_in, LAT_NAME)) ERR;
      if (nc_inq_dim(ncid, lon_dimid, name_in, &len_in)) ERR;
      if (len_in != LON_LEN || strcmp(name_in, LON_NAME)) ERR;
      if (nc_inq_var(ncid, lat_varid, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, LAT_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != lat_dimid || natts_in != 0) ERR;
      if (nc_inq_var(ncid, lon_varid, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, LON_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != lon_dimid || natts_in != 0) ERR;

      /* Check our data variable. */
      if (nc_inq_var(ncid, pres_varid, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, PRES_NAME) || xtype_in != NC_DOUBLE || ndims_in != 2 ||
	  dimids_in[0] != lat_dimid || dimids_in[1] != lon_dimid || natts_in != 0) ERR;

      /* Write our latitude and longitude values. This writes all
       * metadata to disk too. */
      if (nc_put_var_float(ncid, lat_varid, lat)) ERR;
      if (nc_put_var_float(ncid, lon_varid, lon)) ERR;

      /* Write our 2D pressure values. */
      if (nc_put_var_double(ncid, pres_varid, (double *)pres)) ERR;

      /* Check our latitude and longitude values. */
      if (nc_get_var(ncid, lat_varid, lat_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 if (lat[i] != lat_in[i]) ERR;
      if (nc_get_var_float(ncid, lon_varid, lon_in)) ERR;
      for (i = 0; i < LON_LEN; i++)
	 if (lon[i] != lon_in[i]) ERR;

      /* Check our pressure values. */
      if (nc_get_var_double(ncid, pres_varid, (double *)pres_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    if (pres[i][j] != pres_in[i][j]) ERR;

      /* Close the file. */
      if (nc_close(ncid)) ERR;

      /* Reopen the file and check it out again. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;

      /* Check our dimensions. */
      if (nc_inq_dim(ncid, lat_dimid, name_in, &len_in)) ERR;
      if (len_in != LAT_LEN || strcmp(name_in, LAT_NAME)) ERR;
      if (nc_inq_dim(ncid, lon_dimid, name_in, &len_in)) ERR;
      if (len_in != LON_LEN || strcmp(name_in, LON_NAME)) ERR;
      if (nc_inq_var(ncid, lat_varid, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, LAT_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != lat_dimid || natts_in != 0) ERR;
      if (nc_inq_var(ncid, lon_varid, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, LON_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != lon_dimid || natts_in != 0) ERR;

      /* Check our data variable. */
      if (nc_inq_var(ncid, pres_varid, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, PRES_NAME) || xtype_in != NC_DOUBLE || ndims_in != 2 ||
	  dimids_in[0] != lat_dimid || dimids_in[1] != lon_dimid || natts_in != 0) ERR;

      /* Check our latitude and longitude values. */
      if (nc_get_var(ncid, lat_varid, lat_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 if (lat[i] != lat_in[i]) ERR;
      if (nc_get_var_float(ncid, lon_varid, lon_in)) ERR;
      for (i = 0; i < LON_LEN; i++)
	 if (lon[i] != lon_in[i]) ERR;

      /* Check our pressure values. */
      if (nc_get_var_double(ncid, pres_varid, (double *)pres_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    if (pres[i][j] != pres_in[i][j]) ERR;

      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Creating file with 3 data vars, 4 dims, and 2 coord. vars...");

   {
      int ncid, lat_dimid, dimids[MAX_DIMS];
      int level_dimid, time_dimid, elev_varid;
      int lat_varid, lon_dimid, lon_varid, pres_varid, hp_varid;
      double pres[LAT_LEN][LON_LEN][LEVEL_LEN][TIME_LEN];
      double pres_in[LAT_LEN][LON_LEN][LEVEL_LEN][TIME_LEN];
      unsigned short hp[LAT_LEN][LON_LEN][TIME_LEN];
      unsigned short hp_in[LAT_LEN][LON_LEN][TIME_LEN];
      unsigned long long elev[LAT_LEN][LON_LEN], elev_in[LAT_LEN][LON_LEN];
      size_t start[4], count[4];
      int nvars, ndims, natts, unlimdimid;
      int natts_in, ndims_in, dimids_in[MAX_DIMS];
      nc_type xtype_in;
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      float lat[LAT_LEN], lon[LON_LEN];
      float lat_in[LAT_LEN], lon_in[LON_LEN];
      int i, j, k, l;

      /* Some phony 4D pressure data. */
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    for (k = 0; k < LEVEL_LEN; k++)
	       for (l = 0; l <TIME_LEN; l++)
		  pres[i][j][k][l] = 1013.1 + j;

      /* Some phony 3D hp data. */
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    for (l = 0; l <TIME_LEN; l++)
	       hp[i][j][l] = 100 + l;

      /* Some phony 2D elevaton data. */
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    elev[i][j] = 1010101022223333ULL  + i + j;

      /* Some phony 1D lats and lons. */
      for (i = 0; i < LAT_LEN; i++)
	 lat[i] = i * 5.;
      for (i = 0; i < LON_LEN; i++)
	 lon[i] = i * 5.;

      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;

      /* Define lat, lon, level, and timestep dimensions, with
       * associated coordinate variables for lat and lon only. Time is
       * an unlimited dimension. */
      if (nc_def_dim(ncid, LAT_NAME, LAT_LEN, &lat_dimid)) ERR;
      if (lat_dimid != LAT_DIMID) ERR;
      dimids[0] = lat_dimid;
      if (nc_def_var(ncid, LAT_NAME, NC_FLOAT, 1, dimids, &lat_varid)) ERR;
      if (lat_varid != LAT_VARID) ERR;
      if (nc_def_dim(ncid, LON_NAME, LON_LEN, &lon_dimid)) ERR;
      if (lon_dimid != LON_DIMID) ERR;
      dimids[0] = lon_dimid;
      if (nc_def_var(ncid, LON_NAME, NC_FLOAT, 1, dimids, &lon_varid)) ERR;
      if (lon_varid != LON_VARID) ERR;
      if (nc_def_dim(ncid, LEVEL_NAME, LEVEL_LEN, &level_dimid)) ERR;
      if (level_dimid != LEVEL_DIMID) ERR;
      if (nc_def_dim(ncid, TIME_NAME, NC_UNLIMITED, &time_dimid)) ERR;
      if (time_dimid != TIME_DIMID) ERR;

      /* Define a 4D NC_DOUBLE variable called pressure. */
      dimids[0] = lat_dimid;
      dimids[1] = lon_dimid;
      dimids[2] = level_dimid;
      dimids[3] = time_dimid;
      if (nc_def_var(ncid, PRES_NAME, NC_DOUBLE, 4, dimids, &pres_varid)) ERR;
      if (pres_varid != PRES_VARID) ERR;

      /* Define a 2D variable for surface elevation. Use NC_INT64
       * because our units for this is Angstroms from Earth's
       * Center. */
      if (nc_def_var(ncid, ELEV_NAME, NC_INT64, 2, dimids, &elev_varid)) ERR;
      if (elev_varid != ELEV_VARID) ERR;

      /* Define a 3D NC_USHORT variable to store the number of Harry
       * Potter books in this grid square at this time (ignore HP
       * books in airplanes, dirigibles, hot air balloons, space
       * capsules, hang-gliders, parachutes, and flying on brooms). */
      dimids[2] = time_dimid;
      if (nc_def_var(ncid, HP_NAME, NC_USHORT, 3, dimids, &hp_varid)) ERR;
      if (hp_varid != HP_VARID) ERR;

      /* Did all our stuff make it into the internal metadata model
       * intact? */
      /* Check our dimensions. */
      if (nc_inq_dim(ncid, LAT_DIMID, name_in, &len_in)) ERR;
      if (len_in != LAT_LEN || strcmp(name_in, LAT_NAME)) ERR;
      if (nc_inq_dim(ncid, LON_DIMID, name_in, &len_in)) ERR;
      if (len_in != LON_LEN || strcmp(name_in, LON_NAME)) ERR;
      if (nc_inq_dim(ncid, LEVEL_DIMID, name_in, &len_in)) ERR;
      if (len_in != LEVEL_LEN || strcmp(name_in, LEVEL_NAME)) ERR;
      if (nc_inq_dim(ncid, TIME_DIMID, name_in, &len_in)) ERR;
      if (len_in != 0 || strcmp(name_in, TIME_NAME)) ERR;

      /* Check our coordinate variables. */
      if (nc_inq_var(ncid, LAT_VARID, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, LAT_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != LAT_DIMID || natts_in != 0) ERR;
      if (nc_inq_var(ncid, LON_VARID, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, LON_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != LON_DIMID || natts_in != 0) ERR;

      /* Check our data variables. */
      if (nc_inq_var(ncid, PRES_VARID, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, PRES_NAME) || xtype_in != NC_DOUBLE || ndims_in != 4 ||
	  dimids_in[0] != LAT_DIMID || dimids_in[1] != LON_DIMID ||
	  dimids_in[2] != LEVEL_DIMID || dimids_in[3] != TIME_DIMID ||
	  natts_in != 0) ERR;
      if (nc_inq_var(ncid, ELEV_VARID, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, ELEV_NAME) || xtype_in != NC_INT64 || ndims_in != 2 ||
	  dimids_in[0] != LAT_DIMID || dimids_in[1] != LON_DIMID ||
	  natts_in != 0) ERR;
      if (nc_inq_var(ncid, HP_VARID, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, HP_NAME) || xtype_in != NC_USHORT || ndims_in != 3 ||
	  dimids_in[0] != LAT_DIMID || dimids_in[1] != LON_DIMID ||
	  dimids_in[2] != TIME_DIMID || natts_in != 0) ERR;

      /* Write our latitude and longitude values. This writes all
       * metadata to disk too. */
      if (nc_put_var_float(ncid, lat_varid, lat)) ERR;
      if (nc_put_var_float(ncid, lon_varid, lon)) ERR;

      /* Write our 4D pressure, elevation, and hp data. But this
       * should do nothing for pressure and hp, because these are
       * record vars, and nc_put_var_* doesn't do anything to record
       * vars, because it doesn't know how big the var is supposed to
       * be. */
      if (nc_put_var_double(ncid, pres_varid, (double *)pres)) ERR;
      if (nc_put_var_ulonglong(ncid, elev_varid, (unsigned long long *)elev)) ERR;
      if (nc_put_var_ushort(ncid, hp_varid, (unsigned short *)hp)) ERR;

      /* Check our latitude and longitude values. */
      if (nc_get_var(ncid, lat_varid, lat_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 if (lat[i] != lat_in[i]) ERR;
      if (nc_get_var_float(ncid, lon_varid, lon_in)) ERR;
      for (i = 0; i < LON_LEN; i++)
	 if (lon[i] != lon_in[i]) ERR;

      /* Make sure our pressure and hp variables are still
       * empty. get_var calls will return no error, but fetch no
       * data. */
      if (nc_inq_var(ncid, pres_varid, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (nc_inq_dim(ncid, dimids_in[3], NULL, &len_in)) ERR;
      if (len_in != 0) ERR;
      memset(pres_in, 0, sizeof(pres_in));
      if (nc_get_var_double(ncid, pres_varid, (double *)pres_in)) ERR;

      /* Check our pressure values. */
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    for (k = 0; k < LEVEL_LEN; k++)
	       for (l = 0; l <TIME_LEN; l++)
		  if (0 != pres_in[i][j][k][l]) ERR;

      if (nc_inq_var(ncid, hp_varid, NULL, NULL, &ndims_in,
		     dimids_in, NULL)) ERR;
      if (nc_inq_dim(ncid, dimids_in[2], NULL, &len_in)) ERR;
      if (len_in != 0) ERR;
      memset(hp_in, 0, sizeof(hp_in));
      if (nc_get_var_ushort(ncid, hp_varid, (unsigned short *)hp_in)) ERR;

      /* Check our hp values. */
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    for (l = 0; l <TIME_LEN; l++)
	       if (0 != hp_in[i][j][l]) ERR;

      /* Now use nc_put_vara to really write pressure and hp
       * data. Write TIME_LEN (4) records of each. */
      start[0] = start[1] = start[2] = start[3] = 0;
      count[0] = LAT_LEN;
      count[1] = LON_LEN;
      count[2] = LEVEL_LEN;
      count[3] = TIME_LEN;
      if (nc_put_vara(ncid, pres_varid, start, count,
		      (double *)pres)) ERR;
      count[2] = TIME_LEN;
      if (nc_put_vara(ncid, hp_varid, start, count,
		      (double *)hp)) ERR;

      /* Check our pressure values. */
      if (nc_get_var_double(ncid, pres_varid, (double *)pres_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    for (k = 0; k < LEVEL_LEN; k++)
	       for (l = 0; l <TIME_LEN; l++)
		  if (pres[i][j][k][l] != pres_in[i][j][k][l]) ERR;

      /* Check our elevation values. */
      if (nc_get_var_ulonglong(ncid, elev_varid, (unsigned long long *)elev_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    if (elev[i][j] != elev_in[i][j]) ERR;

      /* Check our hp values. */
      if (nc_get_var_ushort(ncid, hp_varid, (unsigned short *)hp_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    for (l = 0; l <TIME_LEN; l++)
	       if (hp[i][j][l] != hp_in[i][j][l]) ERR;

      /* Close the file. */
      if (nc_close(ncid)) ERR;

      /* Reopen the file and check it out again. At the moment, we
       * can't count on the varids and dimids being the same. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != 4 || nvars != 5 || natts != 0) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Testing file with dims and only some coordinate vars...");
#define NDIMS_EX 4
#define NLAT 6
#define NLON 12
#define LAT_NAME_EX "latitude"
#define LON_NAME_EX "longitude"
#define NREC 2
#define REC_NAME "time"
#define LVL_NAME "level"
#define NLVL 2

/* Names of things. */
#define PRES_NAME "pressure"
#define TEMP_NAME "temperature"
#define UNITS "units"
#define DEGREES_EAST "degrees_east"
#define DEGREES_NORTH "degrees_north"

/* There are 4 vars, two for data, two for coordinate data. */
#define NVARS_EX 4

/* These are used to construct some example data. */
#define SAMPLE_PRESSURE 900
#define SAMPLE_TEMP 9.0
#define START_LAT 25.0
#define START_LON -125.0

/* For the units attributes. */
#define UNITS "units"
#define PRES_UNITS "hPa"
#define TEMP_UNITS "celsius"
#define LAT_UNITS "degrees_north"
#define LON_UNITS "degrees_east"
#define MAX_ATT_LEN 80
   {
      /* IDs for the netCDF file, dimensions, and variables. */
      int ncid, lon_dimid, lat_dimid;
      int lon_varid;
      int ndims_in;
      int dimid[NDIMS_EX];
      char dim_name_in[NDIMS_EX][NC_MAX_NAME];
      int i;

      /* Create the file. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;

      /* Define the dimensions. */
      if (nc_def_dim(ncid, LAT_NAME_EX, NLAT, &lat_dimid)) ERR;
      if (nc_def_dim(ncid, LON_NAME_EX, NLON, &lon_dimid)) ERR;

      /* Define a coordinate var. */
      if (nc_def_var(ncid, LON_NAME_EX, NC_FLOAT, 1, &lon_dimid,
			       &lon_varid)) ERR;

      /* Close the file. */
      if (nc_close(ncid)) ERR;

      if (nc_open(FILE_NAME, 0, &ncid)) ERR;

      /* Check dimensions. */
      ndims_in = 0;
      if (nc_inq_dimids(ncid, &ndims_in, dimid, 0)) ERR;
      if (ndims_in != 2) ERR;
      for (i = 0; i < 2; i++)
      {
	 if (dimid[i] != i) ERR;
	 if (nc_inq_dimname(ncid, i, dim_name_in[i])) ERR;
      }
      if (strcmp(dim_name_in[0], LAT_NAME_EX) ||
	  strcmp(dim_name_in[1], LON_NAME_EX)) ERR;

      /* Close the file. */
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** Testing file with just one very long dimension...");
   {
#define VERY_LONG_LEN (size_t)4500000000LL
      int ncid, dimid;
      int ndims_in, dimids_in[MAX_DIMS];
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      int varid_in;

      if (SIZEOF_SIZE_T == 8)
      {
	 /* Create a file with one dim and nothing else. */
	 if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
	 if (nc_def_dim(ncid, LAT_NAME, VERY_LONG_LEN, &dimid)) ERR;

	 /* Check it out. */
	 if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
	 if (len_in != ((SIZEOF_SIZE_T == 8) ? VERY_LONG_LEN : NC_MAX_UINT) ||
	     strcmp(name_in, LAT_NAME)) ERR;
	 if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
	 if (ndims_in != 1) ERR;
	 if (nc_inq_dimid(ncid, LAT_NAME, &varid_in)) ERR;
	 if (varid_in != 0) ERR;
	 if (nc_inq_dimname(ncid, 0, name_in)) ERR;
	 if (strcmp(name_in, LAT_NAME)) ERR;
	 if (nc_inq_dimlen(ncid, 0, &len_in)) ERR;
	 if (len_in != ((SIZEOF_SIZE_T == 8) ? VERY_LONG_LEN : NC_MAX_UINT)) ERR;
	 if (nc_inq_unlimdims(ncid, &ndims_in, dimids_in)) ERR;
	 if (ndims_in != 0) ERR;
	 if (nc_close(ncid)) ERR;

	 /* Reopen and check it out again. */
	 if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
	 /* Check it out. */
	 if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
	 if (len_in != ((SIZEOF_SIZE_T == 8) ? VERY_LONG_LEN : NC_MAX_UINT) ||
	     strcmp(name_in, LAT_NAME)) ERR;
	 if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
	 if (ndims_in != 1) ERR;
	 if (nc_inq_dimid(ncid, LAT_NAME, &varid_in)) ERR;
	 if (varid_in != 0) ERR;
	 if (nc_inq_dimname(ncid, 0, name_in)) ERR;
	 if (strcmp(name_in, LAT_NAME)) ERR;
	 if (nc_inq_dimlen(ncid, 0, &len_in)) ERR;
	 if (len_in != ((SIZEOF_SIZE_T == 8) ? VERY_LONG_LEN : NC_MAX_UINT)) ERR;
	 if (nc_inq_unlimdims(ncid, &ndims_in, dimids_in)) ERR;
	 if (ndims_in != 0) ERR;
	 if (nc_close(ncid)) ERR;
      }
   }
   SUMMARIZE_ERR;
   printf("*** Testing reference file with just one very long dimension...");
   {
#define REF_FILE_NAME "ref_tst_dims.nc"
      int ncid, dimid = 0;
      int ndims_in, dimids_in[MAX_DIMS];
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      int varid_in;
      char file_in[NC_MAX_NAME + 1];
      int ret;

      strcpy(file_in, "");
      if (getenv("srcdir"))
      {
	 strcat(file_in, getenv("srcdir"));
	 strcat(file_in, "/");
      }
      strcat(file_in, REF_FILE_NAME);

      /* Reopen and check it out again. */
      if (nc_open(file_in, NC_NOWRITE, &ncid)) ERR;

      /* Check it out. */
      ret = nc_inq_dim(ncid, dimid, name_in, &len_in);
      if ((SIZEOF_SIZE_T >= 8 && ret) ||
	  (SIZEOF_SIZE_T < 8 && ret != NC_EDIMSIZE)) ERR;
      if (SIZEOF_SIZE_T < 8)
      {
	 if (len_in != NC_MAX_UINT) ERR;
      }
      else
      {
	 if (len_in != VERY_LONG_LEN) ERR;
      }
      if (strcmp(name_in, LAT_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1) ERR;
      if (nc_inq_dimid(ncid, LAT_NAME, &varid_in)) ERR;
      if (varid_in != 0) ERR;
      if (nc_inq_unlimdims(ncid, &ndims_in, dimids_in)) ERR;
      if (ndims_in != 0) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   FINAL_RESULTS;
}
int ex_get_partial_node_set_df  (int   exoid,
                           ex_entity_id node_set_id,
                           int64_t   start_num,
                           int64_t   num_df_to_get,
                           void *node_set_dist_fact)
{
  int status;
  int dimid, dist_id, node_set_id_ndx;
  size_t num_nodes_in_set, start[1], count[1];
  char errmsg[MAX_ERR_LENGTH];

  exerrval = 0; /* clear error code */

  /* first check if any node sets are specified */

  if ((status = nc_inq_dimid (exoid, DIM_NUM_NS, &dimid))  != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Warning: no node sets defined in file id %d",
            exoid);
    ex_err("ex_get_partial_node_set_df",errmsg,exerrval);
    return (EX_WARN);
  }

  /* Lookup index of node set id in VAR_NS_IDS array */
  if ((node_set_id_ndx = ex_id_lkup(exoid,EX_NODE_SET,node_set_id)) < 0) {
    if (exerrval == EX_NULLENTITY) {
      sprintf(errmsg,
              "Warning: node set %"PRId64" is NULL in file id %d",
              node_set_id,exoid);
      ex_err("ex_get_partial_node_set_df",errmsg,EX_MSG);
      return (EX_WARN);
    } else {

      sprintf(errmsg,
              "Error: failed to locate node set %"PRId64" in %s in file id %d",
              node_set_id,VAR_NS_IDS,exoid);
      ex_err("ex_get_partial_node_set_df",errmsg,exerrval);
      return (EX_FATAL);
    }
  }

  /* inquire id's of previously defined dimensions and variables */
  if ((status = nc_inq_dimid (exoid, DIM_NUM_NOD_NS(node_set_id_ndx), &dimid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
         "Error: failed to locate number of nodes in node set %"PRId64" in file id %d",
            node_set_id,exoid);
    ex_err("ex_get_partial_node_set_df",errmsg,exerrval);
    return (EX_FATAL);
  }

  if ((status = nc_inq_dimlen(exoid, dimid, &num_nodes_in_set)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Error: failed to get number of nodes in node set %"PRId64" in file id %d",
            node_set_id, exoid);
    ex_err("ex_get_partial_node_set_df",errmsg,exerrval);
    return (EX_FATAL);
  }

  /* Check input parameters for a valid range of numbers */
  if (start_num < 0 || start_num > num_nodes_in_set) {
    exerrval = EX_BADPARAM;
    sprintf(errmsg, "Error: Invalid input");
    ex_err("ex_get_partial_node_set_df",errmsg,exerrval);
    return (EX_FATAL);
  }

  if (num_df_to_get < 0) {
    exerrval = EX_BADPARAM;
    sprintf(errmsg, "Error: Invalid number of nodes in nodes set!");
    ex_err("ex_get_partial_node_set_df",errmsg,exerrval);
    return (EX_FATAL);
  }

  /* start_num now starts at 1, not 0 */
  if ((start_num + num_df_to_get - 1) > num_nodes_in_set) {
    exerrval = EX_BADPARAM;
    sprintf(errmsg, "Error: request larger than number of nodes in set!");
    ex_err("ex_get_partial_node_set_df",errmsg,exerrval);
    return (EX_FATAL);
  }

  if ((status = nc_inq_varid (exoid, VAR_FACT_NS(node_set_id_ndx), &dist_id)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Warning: dist factors not stored for node set %"PRId64" in file id %d",
            node_set_id,exoid);
    ex_err("ex_get_partial_node_set_df",errmsg,exerrval);
    return (EX_WARN);          /* complain - but not too loud */
  }


  /* read in the distribution factors array */
  start[0] = --start_num;
  count[0] = num_df_to_get;

  if (ex_comp_ws(exoid) == 4) {
    status = nc_get_vara_float(exoid, dist_id, start, count, node_set_dist_fact);
  } else {
    status = nc_get_vara_double(exoid, dist_id, start, count, node_set_dist_fact);
  }

  if (status != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Error: failed to get distribution factors in file id %d",
            exoid);
    ex_err("ex_get_partial_node_set_df",errmsg,exerrval);
    return (EX_FATAL);
  }
  return (EX_NOERR);
}
Example #14
0
/*+++++++++++++++++++++++++
.IDENTifer   SCIA_RD_NC_H2O_REC
.PURPOSE     read records from IMLM-H2O product in netCDF-4 (ADAGUC standard)
.INPUT/OUTPUT
  call as   numRec = SCIA_RD_NC_H2O_REC( ncid, &rec );
     input:
            int ncid              :  netCDF file ID
    output:
	    struct imlm_rec **rec :  IMLM-H2O records

.RETURNS     number of IMLM-H2O records (unsigned int)
.COMMENTS    static function
-------------------------*/
unsigned int SCIA_RD_NC_H2O_REC( int ncid, struct imlm_rec **rec_out )
{
     register unsigned int ni, nr;

     unsigned int numRec = 0;

     int    retval;
     int    time_id;
     int    var_id;
     size_t indx, length;

     float  *rbuff = NULL;
     double *dbuff = NULL;

     struct imlm_rec *rec = NULL;

     const size_t nr_byte = NUM_CORNERS * sizeof(float);

     rec_out[0] = NULL;
/*
 * get size of dimension scale "time"
 */
     if ( (retval = nc_inq_dimid( ncid, "time", &time_id )) != NC_NOERR )
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     if ( (retval = nc_inq_dimlen( ncid, time_id, &length )) != NC_NOERR )
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     numRec = (unsigned int) length;

     rec = (struct imlm_rec *) malloc( numRec * sizeof(struct imlm_rec) );
     if ( rec == NULL ) NADC_GOTO_ERROR( NADC_ERR_ALLOC, "rec" );
/*
 * read Julian date of measurements
 */
     dbuff = (double *) malloc( numRec * sizeof(double) );
     if ( dbuff == NULL ) NADC_GOTO_ERROR( NADC_ERR_ALLOC, "dbuff" );

     if ( (retval = nc_inq_varid( ncid, "time", &var_id )) != NC_NOERR )
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     retval = nc_get_var_double( ncid, var_id, dbuff );
     for ( nr = 0; nr < numRec; nr++ ) rec[nr].dsr_time = dbuff[nr];
/*
 * read longitude and latitude of measurements
 */
     rbuff = (float *) malloc( numRec * sizeof(float) );
     if ( rbuff == NULL ) NADC_GOTO_ERROR( NADC_ERR_ALLOC, "rbuff" );

     if ( (retval = nc_inq_varid( ncid, "lon", &var_id )) != NC_NOERR )
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     retval = nc_get_var_float( ncid, var_id, rbuff );
     for ( nr = 0; nr < numRec; nr++ ) rec[nr].lon_center = rbuff[nr];

     if ( (retval = nc_inq_varid( ncid, "lat", &var_id )) != NC_NOERR )
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     retval = nc_get_var_float( ncid, var_id, rbuff );
     for ( nr = 0; nr < numRec; nr++ ) rec[nr].lat_center = rbuff[nr];
/*
 * read datasets (H2O, CH4)
 */
     if ( (retval = nc_inq_varid( ncid, "H2O", &var_id )) != NC_NOERR )
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     retval = nc_get_var_float( ncid, var_id, rbuff );
     for ( nr = 0; nr < numRec; nr++ ) rec[nr].H2O = rbuff[nr];
     if ( (retval = nc_inq_varid( ncid, "H2O_error", &var_id )) != NC_NOERR )
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     retval = nc_get_var_float( ncid, var_id, rbuff );
     for ( nr = 0; nr < numRec; nr++ ) rec[nr].H2O_err = rbuff[nr];

     if ( (retval = nc_inq_varid( ncid, "CH4", &var_id )) != NC_NOERR )
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     retval = nc_get_var_float( ncid, var_id, rbuff );
     for ( nr = 0; nr < numRec; nr++ ) rec[nr].CH4 = rbuff[nr];
     if ( (retval = nc_inq_varid( ncid, "CH4_error", &var_id )) != NC_NOERR )
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     retval = nc_get_var_float( ncid, var_id, rbuff );
     for ( nr = 0; nr < numRec; nr++ ) rec[nr].CH4_err = rbuff[nr];
#ifdef _IMLM_WHOLE_PRODUCT                /* additional species H2O, N2O */
     if ( (retval = nc_inq_varid( ncid, "H2O", &var_id )) != NC_NOERR )
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     retval = nc_get_var_float( ncid, var_id, rbuff );
     for ( nr = 0; nr < numRec; nr++ ) rec[nr].H2O = rbuff[nr];
     if ( (retval = nc_inq_varid( ncid, "H2O_error", &var_id )) != NC_NOERR )
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     retval = nc_get_var_float( ncid, var_id, rbuff );
     for ( nr = 0; nr < numRec; nr++ ) rec[nr].H2O_err = rbuff[nr];

     if ( (retval = nc_inq_varid( ncid, "N2O", &var_id )) != NC_NOERR )
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     retval = nc_get_var_float( ncid, var_id, rbuff );
     for ( nr = 0; nr < numRec; nr++ ) rec[nr].N2O = rbuff[nr];
     if ( (retval = nc_inq_varid( ncid, "N2O_error", &var_id )) != NC_NOERR )
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     retval = nc_get_var_float( ncid, var_id, rbuff );
     for ( nr = 0; nr < numRec; nr++ ) rec[nr].N2O_err = rbuff[nr];
#endif
     if ( (retval = nc_inq_varid( ncid, "albedo", &var_id )) != NC_NOERR )
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     retval = nc_get_var_float( ncid, var_id, rbuff );
     for ( nr = 0; nr < numRec; nr++ ) rec[nr].albedo = rbuff[nr];

     retval = nc_inq_varid( ncid, "cloudFraction", &var_id );
     if ( retval != NC_NOERR )
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     retval = nc_get_var_float( ncid, var_id, rbuff );
     for ( nr = 0; nr < numRec; nr++ ) rec[nr].cl_fr = rbuff[nr];

     retval = nc_inq_varid( ncid, "meanElevation", &var_id );
     if ( retval != NC_NOERR )
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     retval = nc_get_var_float( ncid, var_id, rbuff );
     for ( nr = 0; nr < numRec; nr++ ) rec[nr].mean_elev = rbuff[nr];
/*
 * read longitude and latitude bounding boxes
 */
     rbuff = (float *) realloc( rbuff, NUM_CORNERS * numRec * sizeof(float) );
     if ( rbuff == NULL ) NADC_GOTO_ERROR( NADC_ERR_ALLOC, "rbuff" );

     if ( (retval = nc_inq_varid( ncid, "lon_bnds", &var_id )) != NC_NOERR )
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     retval = nc_get_var_float( ncid, var_id, rbuff );
     for ( ni = nr = 0; nr < numRec; nr++, ni += NUM_CORNERS )
	  (void) memcpy( rec[nr].lon_corner, rbuff+ni, nr_byte );

     if ( (retval = nc_inq_varid( ncid, "lat_bnds", &var_id )) != NC_NOERR )
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     retval = nc_get_var_float( ncid, var_id, rbuff );
     for ( ni = nr = 0; nr < numRec; nr++, ni += NUM_CORNERS )
	  (void) memcpy( rec[nr].lat_corner, rbuff+ni, nr_byte );
/*
 * read pixel meta-data as compound dataset
 */
     retval = nc_inq_varid( ncid, "tile_properties", &var_id );
     if ( retval != NC_NOERR ) 
	  NADC_GOTO_ERROR( NADC_ERR_FATAL, nc_strerror(retval) );
     for ( indx = 0; indx < (size_t) numRec; indx++ ) {
	  retval = nc_get_var1( ncid, var_id, &indx, &rec[indx].meta );
     }

     free( rbuff );
     free( dbuff );
     rec_out[0] = rec;
     return numRec;
 done:
     if ( rec != NULL ) free( rec );
     if ( rbuff != NULL ) free( rbuff );
     if ( dbuff != NULL ) free( dbuff );
     return 0;
}
int main(int argc, char *argv[]) {

  fprintf(stdout, "start\n");
  
  int varid;
  int ndims;
  int dimids[NC_MAX_VAR_DIMS];
  
  size_t nx, ny, size, var_size, var_offset, i;
  
  int shm_id, shm_key;
  int nhours, nvars, var_i, frame;
  
  float* shm_p;
  float* data_p;
  


  if (argc != 9) {
    fprintf(stdout, "usage: ./load-dap {SHM_KEY} {NHOURS} {NVARS} {VAR_ID} {FRAME} {URL} {VAR_NAME} {Z_LEVEL}\n");
    exit(EXIT_FAILURE);
  }
  
  fprintf(stdout, "nc_open %s\n", argv[URL]);

  ne(nc_open(argv[URL], 0, &ncid));
  fprintf(stdout, "nc_inq\n");

  ne(nc_inq_varid (ncid, argv[VAR_NAME], &varid));
  ne(nc_inq_varndims(ncid, varid, &ndims));
  ne(nc_inq_vardimid(ncid, varid, dimids));
 
  fprintf(stdout, "ndims\n");
 
  if (ndims==2) {
    ne(nc_inq_dimlen(ncid, dimids[0], &ny));
    ne(nc_inq_dimlen(ncid, dimids[1], &nx));
  } else if (ndims==3) {
    ne(nc_inq_dimlen(ncid, dimids[1], &ny));
    ne(nc_inq_dimlen(ncid, dimids[2], &nx));
  }
  


  shm_key=atoi(argv[SHM_KEY]);
  shm_id=shmget(shm_key, 0, 0644);
  if (shm_id == -1) {
    fprintf(stderr, "Shared memory shmget() failed\n");
    exit(EXIT_FAILURE);
  }

  shm_p = shmat(shm_id, NULL, 0);
  if (shm_p == (void *)-1) {
    fprintf(stderr, "Shared memory shmat() failed\n");
    exit(EXIT_FAILURE);
  }
  
  size=nx*ny;
  data_p=malloc(size*sizeof(float));
  if (data_p == NULL) {
    fprintf(stderr, "malloc() failed\n");
    exit(EXIT_FAILURE);
  }
  
  if (ndims==2) {
    ne(nc_get_var_float(ncid, varid, data_p));
  } else {
    size_t start[3]={0,0,0};
    size_t count[3]={1,ny,nx};
    start[0]=atoi(argv[Z_LEVEL]);
    ne(nc_get_vara_float(ncid, varid, start, count, data_p));
  }
  
  // run[point[var[frames[]]]]
  nhours=atoi(argv[NHOURS]);
  nvars=atoi(argv[NVARS]);
  frame=atoi(argv[FRAME]);
  var_i=atoi(argv[VAR_ID]);
  size_t index;
  var_size=nhours*nvars;
  var_offset=var_i*nhours+frame;
  for (i=0; i<size; i++) {
    index=i*var_size+var_offset;
    shm_p[index]=data_p[i];
  }  
  
  free(data_p);
  
  if(shmdt(shm_p)==-1){
    fprintf(stderr, "Shared memory shmdt() failed\n");
    exit(EXIT_FAILURE);
  }
  
  nc_close(ncid);
  
  return 0;
}
int ex_put_partial_side_set_df(int exoid, ex_entity_id side_set_id, int64_t start_num,
                               int64_t num_df_to_get, void *side_set_dist_fact)
{
  int    status;
  int    dimid, side_set_id_ndx;
  int    dist_id;
  size_t num_df_in_set, start[1], count[1];
  char   errmsg[MAX_ERR_LENGTH];

  exerrval = 0; /* clear error code */

  /* first check if any side sets are specified */

  if ((status = nc_inq_dimid(exoid, DIM_NUM_SS, &dimid)) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: no side sets specified in file id %d", exoid);
    ex_err("ex_put_partial_side_set_df", errmsg, exerrval);
    return (EX_FATAL);
  }

  /* Lookup index of side set id in VAR_SS_IDS array */

  if ((side_set_id_ndx = ex_id_lkup(exoid, EX_SIDE_SET, side_set_id)) < 0) {
    if (exerrval == EX_NULLENTITY) {
      snprintf(errmsg, MAX_ERR_LENGTH,
               "Warning: no data allowed for NULL side set %" PRId64 " in file id %d", side_set_id,
               exoid);
      ex_err("ex_put_side_set_fact", errmsg, EX_NULLENTITY);
      return (EX_WARN);
    }
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to locate side set id %" PRId64 " in VAR_SS_IDS array in file id %d",
             side_set_id, exoid);
    ex_err("ex_put_partial_side_set_df", errmsg, exerrval);
    return (EX_FATAL);
  }

  /* inquire id's of previously defined dimension and variable */

  if ((status = nc_inq_dimid(exoid, DIM_NUM_DF_SS(side_set_id_ndx), &dimid)) != NC_NOERR) {
    if (status == NC_EBADDIM) {
      exerrval = EX_BADPARAM;
      snprintf(errmsg, MAX_ERR_LENGTH,
               "Warning: no dist factors defined for side set %" PRId64 " in file id %d",
               side_set_id, exoid);
      ex_err("ex_put_partial_side_set_df", errmsg, exerrval);
      return (EX_WARN);
    }
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to locate number of dist factors in side set %" PRId64 " in file id %d",
             side_set_id, exoid);
    ex_err("ex_put_partial_side_set_df", errmsg, exerrval);
    return (EX_FATAL);
  }

  if ((status = nc_inq_dimlen(exoid, dimid, &num_df_in_set)) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to get number of dist factors in side set %" PRId64 " in file id %d",
             side_set_id, exoid);
    ex_err("ex_put_partial_side_set_df", errmsg, exerrval);
    return (EX_FATAL);
  }

  /* Check input parameters for a valid range of numbers */
  if (start_num < 0 || (num_df_to_get > 0 && start_num > num_df_in_set)) {
    exerrval = EX_BADPARAM;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: Invalid input");
    ex_err("ex_put_partial_side_set_df", errmsg, exerrval);
    return (EX_FATAL);
  }

  if (num_df_to_get < 0) {
    exerrval = EX_BADPARAM;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: Invalid number of df's to put!");
    ex_err("ex_put_partial_side_set_df", errmsg, exerrval);
    return (EX_FATAL);
  }

  /* start_num now starts at 1, not 0 */
  if ((start_num + num_df_to_get) > num_df_in_set + 1) {
    exerrval = EX_BADPARAM;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: request larger than number of df's in set!");
    ex_err("ex_put_partial_side_set_df", errmsg, exerrval);
    return (EX_FATAL);
  }

  if ((status = nc_inq_varid(exoid, VAR_FACT_SS(side_set_id_ndx), &dist_id)) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to locate dist factors list for side set %" PRId64 " in file id %d",
             side_set_id, exoid);
    ex_err("ex_put_partial_side_set_df", errmsg, exerrval);
    return (EX_FATAL);
  }

  /* write out the distribution factors array */
  start[0] = --start_num;
  count[0] = num_df_to_get;
  if (num_df_to_get == 0) {
    start[0] = 0;
  }

  if (ex_comp_ws(exoid) == 4) {
    status = nc_put_vara_float(exoid, dist_id, start, count, side_set_dist_fact);
  }
  else {
    status = nc_put_vara_double(exoid, dist_id, start, count, side_set_dist_fact);
  }

  if (status != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to store dist factors for side set %" PRId64 " in file id %d",
             side_set_id, exoid);
    ex_err("ex_put_partial_side_set_df", errmsg, exerrval);
    return (EX_FATAL);
  }
  return (EX_NOERR);
}
Example #17
0
int
main(int argc, char **argv) 
{/* create file that caused seg fault in ncdump */

    int  ncid;  /* netCDF id */

    /* dimension ids */
    int Time_dim;
    int X_dim;
    int Y_dim;

    /* dimension lengths */
    size_t Time_len = NC_UNLIMITED;
    size_t X_len = 4;
    size_t Y_len = 3;

    /* variable ids */
    int Time_id;
    int P_id;

    /* rank (number of dimensions) for each variable */
#   define RANK_Time 1
#   define RANK_P 3

    /* variable shapes */
    int Time_dims[RANK_Time];
    int P_dims[RANK_P];

   printf("\n*** Testing preparation of fillbug test.\n");
   printf("*** creating fillbug test file %s...", FILENAME);

    /* enter define mode */
    if (nc_create(FILENAME, NC_CLOBBER|NC_NETCDF4, &ncid)) ERR;

    /* define dimensions */
    if (nc_def_dim(ncid, "Time", Time_len, &Time_dim)) ERR;
    if (nc_def_dim(ncid, "X", X_len, &X_dim)) ERR;
    if (nc_def_dim(ncid, "Y", Y_len, &Y_dim)) ERR;

    /* define variables */

    Time_dims[0] = Time_dim;
    if (nc_def_var(ncid, "Time", NC_DOUBLE, RANK_Time, Time_dims, &Time_id)) ERR;

    P_dims[0] = Time_dim;
    P_dims[1] = Y_dim;
    P_dims[2] = X_dim;
    if (nc_def_var(ncid, "P", NC_FLOAT, RANK_P, P_dims, &P_id)) ERR;

    /* leave define mode */
    if (nc_enddef (ncid)) ERR;

    {/* assign variable data */
    static double Time_data[1]={3.14159};
    static size_t Time_startset[1] = {0};
    static size_t Time_countset[1] = {1};
    if (nc_put_vara(ncid, Time_id, Time_startset, Time_countset, Time_data)) ERR;
    }

    if (nc_close(ncid)) ERR;

    /* Try to duplicate segfault ncdump gets by making the same calls
     * to the netCDF-4 library, in the same order.  This doesn't
     * result in the same segfault, so either we have missed a call
     * made by ncdump, or an earlier ncdump bug masks the real problem
     * until a call is made into the netCDF-4 library ...  */
    if (nc_open(FILENAME, NC_NOWRITE, &ncid)) ERR;
    
    {   		
	/* We declare local arrays with small constant sizes to avoid
	 * all the mallocs and frees used in ncdump.  For the example
	 * above, the fixed-size arrays are ample. */
	int format, ndims, nvars, ngatts, xdimid, ndims_grp, dimids_grp[3],
	    unlimids[1], d_grp, nunlim, nvars_grp, varids_grp[3], v_grp,
	    varid, varndims, vardims[3], varnatts, vartype, dimids[3], is_recvar,
	    vdims[3], id, ntypes, numgrps, atttype, nc_status;
	size_t dimsize, len, attlen;
	char dimname[20], varname[20];
	if ( nc_inq_format(ncid, &format)) ERR;
	ntypes = count_udtypes(ncid);
	if ( nc_inq_typeids(ncid, &ntypes, NULL) ) ERR;
	if ( nc_inq_format(ncid, &format)) ERR;
	if ( nc_inq_grps(ncid, &numgrps, NULL) ) ERR;
	if ( nc_inq_typeids(ncid, &ntypes, NULL) ) ERR;
	if ( nc_inq(ncid, &ndims, &nvars, &ngatts, &xdimid) ) ERR;
	if ( nc_inq_ndims(ncid, &ndims_grp) ) ERR;
	if ( nc_inq_dimids(ncid, 0, dimids_grp, 0) ) ERR;
	if ( nc_inq_unlimdims(ncid, &nunlim, NULL) ) ERR;
	if ( nc_inq_unlimdims(ncid, &nunlim, unlimids) ) ERR;
	for (d_grp = 0; d_grp < ndims_grp; d_grp++) {
	    int dimid = dimids_grp[d_grp];
	    if ( nc_inq_dim(ncid, dimid, dimname, &dimsize) ) ERR;
	}
	if ( nc_inq_format(ncid, &format) ) ERR;
	if ( nc_inq_varids(ncid, &nvars_grp, varids_grp) ) ERR;
	for (v_grp = 0; v_grp < nvars_grp; v_grp++) {
	    varid = varids_grp[v_grp];
	    if ( nc_inq_varndims(ncid, varid, &varndims) ) ERR;
	    if ( nc_inq_var(ncid, varid, varname, &vartype, 0, vardims, 
			    &varnatts) ) ERR;
	    for (id = 0; id < varndims; id++) {
		if ( nc_inq_dimname(ncid, vardims[id], dimname) ) ERR;
	    }
	}
	for (v_grp = 0; v_grp < nvars_grp; v_grp++) {
	    varid = varids_grp[v_grp];
	    if( nc_inq_varndims(ncid, varid, &varndims) ) ERR;
	    if( nc_inq_var(ncid, varid, varname, &vartype, 0, vardims, 
			   &varnatts) ) ERR;
	    {
		is_recvar = 0;
		if ( nc_inq_varndims(ncid, varid, &ndims) ) ERR;
		if (ndims > 0) {
		    int nunlimdims;
		    int recdimids[3];
		    int dim, recdim;
		    if ( nc_inq_vardimid(ncid, varid, dimids) ) ERR;
		    if ( nc_inq_unlimdims(ncid, &nunlimdims, NULL) ) ERR;
		    if ( nc_inq_unlimdims(ncid, NULL, recdimids) ) ERR;
		    for (dim = 0; dim < ndims && is_recvar == 0; dim++) {
			for(recdim = 0; recdim < nunlimdims; recdim++) {
			    if(dimids[dim] == recdimids[recdim]) {
				is_recvar = 1;
				break;
			    }		
			}
		    }
		}
	    }
	    for (id = 0; id < varndims; id++) {
		if( nc_inq_dimlen(ncid, vardims[id], &len) ) ERR;
		vdims[id] = len;
	    }
	    nc_status = nc_inq_att(ncid,varid,_FillValue,&atttype,&attlen);
	    nc_status = nc_inq_att(ncid, varid, "units", &atttype, &attlen);
	    nc_status = nc_inq_att(ncid, varid, "C_format", &atttype, &attlen);
	    if (varid == 0) {
		/* read Time variable */
		static double Time_data;
		static size_t cor[RANK_Time] = {0};
		static size_t edg[RANK_Time] = {1};
		if (nc_get_vara(ncid, varid, cor, edg, &Time_data)) ERR;
	    } else {
		/* read data slices from P variable, should get fill values */
		static float P_data[4];
		static size_t cor[RANK_P] = {0, 0, 0};
		static size_t edg[RANK_P] = {1, 1, 4};

		/* first slice retrieved OK */
		if (nc_get_vara(ncid, varid, cor, edg, P_data)) ERR;
		
		/* In ncdump, reading second slice gets seg fault in
		 * nc4_open_var_grp(), but this attempt to do all the
		 * same netCDF calls as ncdump can't duplicate the
		 * error, which would seem to implicate ncdump rather
		 * than HDF5 or netCDF-4 library ... */
		cor[1] = 1;
		if (nc_get_vara(ncid, varid, cor, edg, P_data)) ERR;
	    }
	}
    }
    if (nc_close(ncid)) ERR;
      
   SUMMARIZE_ERR;
   FINAL_RESULTS;
}
void
avtLODIParticleFileFormat::PopulateDatabaseMetaData(avtDatabaseMetaData *md)
{
    const char *mName = "avtLODIParticleFileFormat::PopulateDatabaseMetaData: ";
    debug4 << mName << endl;
    if(DebugStream::Level4())
        fileObject->PrintFileContents(DebugStream::Stream4());

    // Assemble a database title.
    std::string comment(GetType()), titleString, create_version, 
                create_date_time;
    if(fileObject->ReadStringAttribute("title", titleString))
    {
        comment += (std::string(" database: title=") + titleString);

        if(fileObject->ReadStringAttribute("create_version", create_version))
            comment += (std::string(", create_version=") + create_version);

        if(fileObject->ReadStringAttribute("create_date_time", create_date_time))
            comment += (std::string(", create_date_time=") + create_date_time);

        md->SetDatabaseComment(comment);
    }

    //
    // Add a point mesh for the particles
    //
    avtMeshMetaData *mmd = new avtMeshMetaData("particles", 1, 0, 1, 0, 3, 0,
        AVT_POINT_MESH);
    // Read the mesh units
    std::string meshUnits;
    if(fileObject->ReadStringAttribute("part_posn", "units", meshUnits))
    {
        mmd->xUnits = meshUnits;
        mmd->yUnits = meshUnits;
        mmd->zUnits = meshUnits;
    }
    // Read the mesh labels
    TypeEnum t = NO_TYPE;
    int ndims = 0, *dims = 0;
    void *values = 0;
    debug4 << mName << "Trying to read dimnum_labels" << endl;
    if(fileObject->ReadVariable("dimnum_labels", &t, &ndims, &dims, &values))
    {
        if(ndims == 2 && t == CHARARRAY_TYPE)
        {
            int len = dims[1];
            char *cptr = (char *)values;

            char *labels = new char[3 * (len+1)];
            char *xL = labels;
            char *yL = labels + len + 1;
            char *zL = yL + len + 1;
            memset(labels, 0, 3 * (len+1));
            memcpy(xL, cptr,       len);
            memcpy(yL, cptr+len,   len);
            memcpy(zL, cptr+len*2, len);

            mmd->xLabel = xL;
            debug4 << mName << "xLabel = " << xL << endl;

            mmd->yLabel = yL;
            debug4 << mName << "yLabel = " << yL << endl;

            mmd->zLabel = zL;
            debug4 << mName << "zLabel = " << zL << endl;

            delete [] labels;
        }

        delete [] dims;
        free_void_mem(values, t);
    }
    md->Add(mmd);

    //
    // Read the sourceid variable and create material names from it.
    //
    sourceids.clear();
    if(fileObject->ReadVariable("sourceid", &t, &ndims, &dims, &values))
    {
        if(t == CHARARRAY_TYPE && ndims == 2)
        {
            int nsrcs = dims[0];
            int len = dims[1];
            char *name = new char[len+1];
            char *start = (char *)values;

            debug4 << mName << "sourceid={";
            for(int i = 0; i < nsrcs; ++i)
            {
                char *namestart = start + len * i;
                memcpy((void*)name, (void*)namestart, len);
                name[len] = '\0';

                char *end = name + len - 1;
                while(end >= name && *end == ' ')
                    *end-- = '\0';

                sourceids.push_back(name);

                if(i > 0)
                    debug4 << ", ";
                debug4 << name;
            }
            debug4 << "}" << endl;
            delete [] name;

            // Add the material to the metadata.
            avtMaterialMetaData *matmd = new avtMaterialMetaData("sourceid",
                "particles", (int)sourceids.size(), sourceids);
            md->Add(matmd);
        }

        delete [] dims;
        free_void_mem(values, t);
    }

    //
    // Look for variables defined on the particles mesh.
    //
    if(fileObject->InqVariable("part_posn", &t, &ndims, &dims))
    {
        // Iterate over all of the variables and pick those that have
        // the same number of elements as nPts.
        int status, nDims, nVars, nGlobalAtts, unlimitedDimension;
        status = nc_inq(fileObject->GetFileHandle(), &nDims, &nVars, &nGlobalAtts,
                        &unlimitedDimension);
        if(status != NC_NOERR)
        {
            fileObject->HandleError(status);
            return;
        }

        // Get the sizes of all dimensions.
        int i;
        size_t *dimSizes = new size_t[nDims];
        for(i = 0; i < nDims; ++i)
        {
            int status = nc_inq_dimlen(fileObject->GetFileHandle(), i, &dimSizes[i]);
            if(status != NC_NOERR)
                fileObject->HandleError(status);
        }

        // Determine the maximum number of points in the particle mesh.
        int nElems = 1;
        for(i = 0; i < ndims; ++i)
            nElems *= dims[i];
        int nPts = nElems / 3;
        delete [] dims;

        // Look for variables with the same number of values as nPts.
        for(i = 0; i < nVars; ++i)
        {
            char varname[NC_MAX_NAME+1];
            nc_type vartype;
            int  varndims;
            int  vardims[NC_MAX_VAR_DIMS];
            int  varnatts;
            if((status = nc_inq_var(fileObject->GetFileHandle(), i, varname,
                                    &vartype, &varndims, 
                                    vardims, &varnatts)) == NC_NOERR)
            {
                nElems = 1;
                for(int j = 0; j < varndims; ++j)
                    nElems *= dimSizes[vardims[j]];
                if(nElems == nPts)
                {
                    avtScalarMetaData *smd = new avtScalarMetaData(varname,
                        "particles", AVT_NODECENT);
                    smd->hasUnits = fileObject->ReadStringAttribute(
                        varname, "units", smd->units);
                    md->Add(smd);
                }
            }
        }

        delete [] dimSizes;
    }
}
Example #19
0
int
main(int argc, char **argv)
{
nc_set_log_level(0);
   printf("\n*** Testing netcdf-4 dimensions even more.\n");
   printf("*** testing netcdf-4 dimension inheritance...");
   {
#define FILE_NAME "tst_dims3.nc"
#define RANK_time 1
#define GRP_NAME  "G"
#define TIME_NAME "time"
#define VAR2_NAME "z"
#define TIME_RANK 1
#define NUM_TIMES 2
      int ncid, grpid;
      int time_dim, time_dim_in;
      int time_var, z_var;
      size_t len;
      int time_data[NUM_TIMES] = {1, 2} ;
      size_t time_startset[TIME_RANK] = {0} ;
      size_t time_countset[TIME_RANK] = {NUM_TIMES} ;

      /* Create file with unlimited dim and associated coordinate
       * variable in root group, another variable that uses unlimited
       * dim in subgroup. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_grp(ncid, GRP_NAME, &grpid)) ERR;
      if (nc_def_dim(ncid, TIME_NAME, NC_UNLIMITED, &time_dim)) ERR;
      if (nc_def_var(ncid, TIME_NAME, NC_INT, TIME_RANK, &time_dim, 
		     &time_var)) ERR;
      if (nc_def_var(grpid, VAR2_NAME, NC_INT, TIME_RANK, &time_dim, 
		     &z_var)) ERR;
      if (nc_enddef(ncid)) ERR;

      /* Assign data to time variable, creating two times */
      if (nc_put_vara(ncid, time_dim, time_startset, time_countset, 
		      time_data)) ERR;

      /* Check the dim len from the root group */
      if (nc_inq_dimlen(ncid, time_dim, &len)) ERR;
      if (len != NUM_TIMES) ERR;

      /* Check the dim len from the sub group */
      if (nc_inq_dimlen(grpid, time_dim, &len)) ERR;
      if (len != NUM_TIMES) ERR;
      if (nc_close(ncid)) ERR;

      /* Now check how many times there are from the subgroup */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq_ncid(ncid, GRP_NAME, &grpid)) ERR;
      if (nc_inq_dimid(ncid, TIME_NAME, &time_dim)) ERR;

      /* Check the dim len from the root group */
      if (nc_inq_dimlen(ncid, time_dim, &len)) ERR;
      if (len != NUM_TIMES) ERR;

      /* Check the dim len from the sub group */
      if (nc_inq_dimlen(grpid, time_dim, &len)) ERR;
      if (len != NUM_TIMES) ERR;

      /* Find the dimension by name. */
      if (nc_inq_dimid(grpid, TIME_NAME, &time_dim_in)) ERR;
      if (time_dim_in != time_dim) ERR;

      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** testing a scalar coordinate dimension...");
   {
      int ncid, dimid, varid, stat;
      float data = 42.5;
      
      /* Create a scalar coordinate dimension. The only reason that
       * the user can ever possibly have for doing this is just
       * because they like to make life difficult for poor, poor
       * netCDF programmers, trapped in this horrible place, in a
       * Rocky Mountain valley, drenched in sunlight, with a stream
       * quietly gurgling, deer feeding on the grasses, and all those
       * damn birds chirping! */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR_RET;
      if (nc_def_dim(ncid, "scalar", 0, &dimid)) ERR_RET;
      if (nc_def_var(ncid, "scalar", NC_FLOAT, 0, &dimid, &varid)) ERR_RET;
      if (nc_put_var_float(ncid, varid, &data)) ERR_RET;
      if (nc_close(ncid))
	ERR_RET;
   }
   SUMMARIZE_ERR;
   FINAL_RESULTS;
}
Example #20
0
sta_struct *decode_fsl2(int cdfid, long miss, int *iret)
{
int ndims,nvars,natts,nunlim;
int tmpint[20];
int ier,i,j,unlimsiz;
int wmoStaNum_id,wmoStaNum,staName_id;
char staName[20];
int staLat_id,staLon_id,staElev_id,timeObs_id,levels_id;
int uwnd_id,vwnd_id,wwnd_id,uv_qual_id,w_qual_id,levelMode_id;
int sigma_uv_id,sigma_w_id;
int sfc_sped_id,sfc_drct_id,sfc_pres_id,sfc_temp_id,sfc_relh_id,sfc_rain_id;
float staLat,staLon,staElev,level;
float uwnd,vwnd,wwnd,sigma_uv,sigma_w;
int uv_qual,w_qual,levelMode;
float sfc_sped,sfc_drct,sfc_pres,sfc_temp,sfc_relh,sfc_rain;
double timeObs;
nc_type xtype;
int nvdims,nvatts,time_interval;
size_t dimsiz,var_i[5],vc[5],namelen;
float ufill,vfill,wfill;
float pfill,tfill,dfill,sfill,rfill,rrfill;
float fmiss,e;

time_t obs_time;
char timestr[80],*atttext;
int year,month,day,hour,minute;
struct tm *gmt_time=NULL,new_time;
sta_struct *stadat,*head=NULL;
prof_data *plev,*plast;


udebug("decoding fsl2\0");
fmiss = (float)miss;

ier = nc_inq(cdfid,&ndims,&nvars,&natts,&nunlim);

ier = nc_inq_atttype(cdfid,NC_GLOBAL,"avgTimePeriod",&xtype);
if(xtype == NC_CHAR)
   {
   ier = nc_inq_attlen(cdfid,NC_GLOBAL,"avgTimePeriod",&namelen);
   udebug("AvgTimPeriod name len is %d",namelen);
   atttext = (char *)malloc(namelen + 1);
   ier = nc_get_att_text(cdfid,NC_GLOBAL,"avgTimePeriod",atttext);
   sscanf(atttext,"%d",tmpint);
   udebug("AvgTimPeriod type is NC_CHAR %s VAL %d",atttext,tmpint[0]);
   free(atttext);
   }
else
   {
   ier = nc_get_att_int(cdfid,NC_GLOBAL,"avgTimePeriod",tmpint);
   }
udebug("AvgTimPeriod is %d\0",tmpint[0]);
time_interval = tmpint[0];

ier = 0;
ier += nc_inq_varid(cdfid,"wmoStaNum",&wmoStaNum_id);
ier += nc_inq_varid(cdfid,"staName",&staName_id);
ier += nc_inq_varid(cdfid,"staLat",&staLat_id);
ier += nc_inq_varid(cdfid,"staLon",&staLon_id);
ier += nc_inq_varid(cdfid,"staElev",&staElev_id);
ier += nc_inq_varid(cdfid,"timeObs",&timeObs_id);
ier += nc_inq_varid(cdfid,"levels",&levels_id);
ier += nc_inq_varid(cdfid,"uComponent",&uwnd_id);
ier += nc_inq_varid(cdfid,"vComponent",&vwnd_id);
ier += nc_inq_varid(cdfid,"wComponent",&wwnd_id);
ier += nc_get_att_float(cdfid,uwnd_id,"_FillValue",&ufill);
ier += nc_get_att_float(cdfid,vwnd_id,"_FillValue",&vfill);
ier += nc_get_att_float(cdfid,wwnd_id,"_FillValue",&wfill);

ier += nc_inq_varid(cdfid,"uvQualityCode",&uv_qual_id);
ier += nc_inq_varid(cdfid,"wQualityCode",&w_qual_id);
ier += nc_inq_varid(cdfid,"windSpeedStdDev",&sigma_uv_id);
ier += nc_inq_varid(cdfid,"wStdDev",&sigma_w_id);
ier += nc_inq_varid(cdfid,"levelMode",&levelMode_id);

ier += nc_inq_varid(cdfid,"windSpeedSfc",&sfc_sped_id);
ier += nc_inq_varid(cdfid,"windDirSfc",&sfc_drct_id);
ier += nc_inq_varid(cdfid,"pressure",&sfc_pres_id);
ier += nc_inq_varid(cdfid,"temperature",&sfc_temp_id);
ier += nc_inq_varid(cdfid,"relHumidity",&sfc_relh_id);
ier += nc_inq_varid(cdfid,"rainRate",&sfc_rain_id);
ier += nc_get_att_float(cdfid,sfc_sped_id,"_FillValue",&sfill);
ier += nc_get_att_float(cdfid,sfc_drct_id,"_FillValue",&dfill);
ier += nc_get_att_float(cdfid,sfc_pres_id,"_FillValue",&pfill);
ier += nc_get_att_float(cdfid,sfc_temp_id,"_FillValue",&tfill);
ier += nc_get_att_float(cdfid,sfc_relh_id,"_FillValue",&rfill);
ier += nc_get_att_float(cdfid,sfc_rain_id,"_FillValue",&rrfill);

if(ier != 0)
   {
   uerror("could not get station information\0");
   *iret = -1;
   return(NULL);
   }

ier = nc_inq_vardimid(cdfid,staName_id,tmpint);
ier += nc_inq_dimlen(cdfid,tmpint[1],&namelen);

tmpint[0] = 0;tmpint[1] = 0;
ier += nc_inq_var(cdfid,wmoStaNum_id,NULL, &xtype, &nvdims, tmpint, &nvatts);
ier += nc_inq_dimlen(cdfid,tmpint[0],&dimsiz);
if(ier == 0)
   unlimsiz = dimsiz;
   for(i=0;i<unlimsiz;i++)
      {
      var_i[0] = i; var_i[1] = 0; vc[0] = 1; vc[1] = namelen-1;
      memset(staName,'\0',20);
      ier = nc_get_vara_text(cdfid,staName_id,var_i,vc,staName);
      ier = nc_get_var1_int(cdfid,wmoStaNum_id,var_i,&wmoStaNum);
      ier = nc_get_var1_float(cdfid,staLat_id,var_i,&staLat);
      ier = nc_get_var1_float(cdfid,staLon_id,var_i,&staLon);
      ier = nc_get_var1_float(cdfid,staElev_id,var_i,&staElev);
      ier = nc_get_var1_float(cdfid,sfc_sped_id,var_i,&sfc_sped);
      ier = nc_get_var1_float(cdfid,sfc_drct_id,var_i,&sfc_drct);
      ier = nc_get_var1_float(cdfid,sfc_pres_id,var_i,&sfc_pres);
      ier = nc_get_var1_float(cdfid,sfc_temp_id,var_i,&sfc_temp);
      ier = nc_get_var1_float(cdfid,sfc_relh_id,var_i,&sfc_relh);
      ier = nc_get_var1_float(cdfid,sfc_rain_id,var_i,&sfc_rain);
      ier = nc_get_var1_double(cdfid,timeObs_id,var_i,&timeObs);
      obs_time = (time_t) timeObs;
      gmt_time = gmtime(&obs_time);
      new_time = *gmt_time;
      timestr[0] = '\0';
      strftime(timestr,80,"%Y %m %d %H %M",&new_time);
      sscanf(timestr,"%d %d %d %d %d",&year,&month,&day,&hour,&minute);
      udebug("Station %3d %8d %s = %6.2f %7.2f %5.0f %s\0",i,wmoStaNum,
         staName,staLat,staLon,staElev,timestr);

      stadat = (sta_struct *)malloc(sizeof(sta_struct));
      if(stadat == NULL)
         {
         uerror("Could not allocate station data structure\0");
         exit(-2);
         }
      stadat->wmoStaNum = wmoStaNum;
      stadat->staName = (char *)malloc(strlen(staName)+1);
      strcpy(stadat->staName,staName);
      stadat->staLat = staLat;      
      stadat->staLon = staLon;      
      stadat->staElev = staElev;      
      stadat->timeObs = timeObs;      
      stadat->year = year;
      stadat->month = month;
      stadat->day = day;
      stadat->hour = hour;
      stadat->minute = minute;
      stadat->time_interval = time_interval;
      stadat->pdata = NULL;
      stadat->rdata = NULL;
      stadat->sfc_pres = fmiss;
      stadat->sfc_temp = fmiss;
      stadat->sfc_sped = fmiss;
      stadat->sfc_drct = fmiss;
      stadat->sfc_relh = fmiss;
      stadat->sfc_rain_rate = fmiss;
      stadat->sfc_rain_amt = fmiss;
      stadat->sfc_dwpc = fmiss;
      if(sfc_pres != pfill) stadat->sfc_pres = sfc_pres;
      if(sfc_temp != tfill) stadat->sfc_temp = sfc_temp - 273.15;
      if(sfc_sped != sfill) stadat->sfc_sped = sfc_sped;
      if(sfc_drct != dfill) stadat->sfc_drct = sfc_drct;
      if(sfc_relh != rfill) stadat->sfc_relh = sfc_relh;
      if(sfc_rain != rrfill) stadat->sfc_rain_rate = sfc_rain;
      if((stadat->sfc_temp != fmiss)&&(stadat->sfc_relh != fmiss))
         {
         VAPOR_PRES(stadat->sfc_temp+273.15,&e);
         e = e * (stadat->sfc_relh / 100.);
         t_from_e(e,&stadat->sfc_dwpc);
         stadat->sfc_dwpc = stadat->sfc_dwpc - 273.15;
         }

      ier = nc_inq_var(cdfid,levels_id,NULL, &xtype, &nvdims, tmpint, &nvatts);
      if(ier == 0)
         {
         ier = nc_inq_dimlen(cdfid,tmpint[0],&dimsiz);
         stadat->numlevs = dimsiz;
         plast = stadat->pdata;
         for(j=0;j<stadat->numlevs;j++)
            {
            var_i[0] = j;
            ier = nc_get_var1_float(cdfid,levels_id,var_i,&level);
            ier = nc_get_var1_int(cdfid,levelMode_id,var_i,&levelMode);
            var_i[0] = i;
            var_i[1] = j;
            ier = nc_get_var1_float(cdfid,uwnd_id,var_i,&uwnd);
            ier = nc_get_var1_float(cdfid,vwnd_id,var_i,&vwnd);
            ier = nc_get_var1_float(cdfid,wwnd_id,var_i,&wwnd);
            ier = nc_get_var1_int(cdfid,uv_qual_id,var_i,&uv_qual);
            ier = nc_get_var1_int(cdfid,w_qual_id,var_i,&w_qual);
            ier = nc_get_var1_float(cdfid,sigma_uv_id,var_i,&sigma_uv);
            ier = nc_get_var1_float(cdfid,sigma_w_id,var_i,&sigma_w);
            plev = (prof_data *)malloc(sizeof(prof_data));
            if(plev != NULL)
               {
               plev->level = level;
               if(uwnd == ufill) uwnd = fmiss;
               if(vwnd == vfill) vwnd = fmiss;
               if(wwnd == wfill) wwnd = fmiss;
               if(uv_qual != 0) 
                  {
                  uwnd = fmiss;
                  vwnd = fmiss;
                  }
               if(w_qual != 0) wwnd = fmiss;
               if((uwnd == fmiss)||(vwnd == fmiss))
                  sigma_uv = fmiss;
               if(wwnd == fmiss) sigma_w = fmiss;
               plev->u = uwnd; plev->v = vwnd; plev->w = wwnd;
               plev->sigma_uv = sigma_uv;
               plev->sigma_w = sigma_w;
               plev->levmode = levelMode;
               plev->nextlev = NULL;
               if(plast == NULL)
                  stadat->pdata = plev;
               else
                  plast->nextlev = plev;
               plast = plev;
               }
            }
         }
      else
         stadat->numlevs = 0;

      stadat->next = head;
      head = stadat;
      }

return(head);

} 
Example #21
0
static int open_amber_cdf_read(cdfdata *cdf) {
  int rc;
  size_t len; 
  amberdata *amber = &cdf->amber;

  /* global attrib: "ConventionVersion" -- required */
  rc = nc_inq_attlen(cdf->ncid, NC_GLOBAL, "ConventionVersion", &len);
  if (rc == NC_NOERR && len > 0) {
    amber->conventionversion = (char *) malloc((len+1) * sizeof(char));
    nc_get_att_text(cdf->ncid, NC_GLOBAL, "ConventionVersion", amber->conventionversion);
    amber->conventionversion[len] = '\0';
    printf("netcdfplugin) trajectory follows AMBER conventions version '%s'\n", amber->conventionversion);
  } else {
    return CDF_ERR;
  }

  /* at this point we know that this is an AMBER trajectory */
  cdf->type = CDF_TYPE_AMBER;

  /* initialize default scaling factors so they are always set to a sane */
  /* value even if problems occur later */
  amber->coordinates_scalefactor = 1.0;
  amber->cell_lengths_scalefactor = 1.0;
  amber->cell_angles_scalefactor = 1.0;


  /* global attrib: "program" -- required */
  rc = nc_inq_attlen(cdf->ncid, NC_GLOBAL, "program", &len);
  if (rc == NC_NOERR && len > 0) {
    amber->program = (char *) malloc((len+1) * sizeof(char));
    nc_get_att_text(cdf->ncid, NC_GLOBAL, "program", amber->program);
    amber->program[len] = '\0';
    printf("netcdfplugin) AMBER: program '%s'\n", amber->program);
  } else {
    printf("netcdfplugin) AMBER: Missing required 'program' global attribute, corrupt file?\n");
  }


  /* global attrib: "programVersion" -- required */
  rc = nc_inq_attlen(cdf->ncid, NC_GLOBAL, "programVersion", &len);
  if (rc == NC_NOERR && len > 0) {
    amber->programversion = (char *) malloc((len+1) * sizeof(char));
    nc_get_att_text(cdf->ncid, NC_GLOBAL, "programVersion", amber->programversion);
    amber->programversion[len] = '\0';
    printf("netcdfplugin) AMBER: program version '%s'\n", amber->programversion);
  } else {
    printf("netcdfplugin) AMBER: Missing required 'programVersion' global attribute, corrupt file?\n");
  }


  /* global attrib: "title" -- optional */
  rc = nc_inq_attlen(cdf->ncid, NC_GLOBAL, "title", &len);
  if (rc == NC_NOERR && len > 0) {
    amber->title = (char *) malloc((len+1) * sizeof(char));
    nc_get_att_text(cdf->ncid, NC_GLOBAL, "title", amber->title);
    amber->title[len] = '\0';
    printf("netcdfplugin) AMBER: title '%s'\n", amber->title);
  } 


  /* global attrib: "application" -- optional */
  rc = nc_inq_attlen(cdf->ncid, NC_GLOBAL, "application", &len);
  if (rc == NC_NOERR && len > 0) {
    amber->application = (char *) malloc((len+1) * sizeof(char));
    nc_get_att_text(cdf->ncid, NC_GLOBAL, "application", amber->application);
    amber->application[len] = '\0';
    printf("netcdfplugin) AMBER: application '%s'\n", amber->application);
  } 


/* XXX lots of additional error checking is needed below... */

  /* read in spatial dimension */
  rc = nc_inq_dimid(cdf->ncid, "spatial", &amber->spatialdimid);
  if (rc == NC_NOERR) {    
    rc = nc_inq_dimlen(cdf->ncid, amber->spatialdimid, &amber->spatialdim);
    if (rc == NC_NOERR) {
      printf("netcdfplugin) AMBER: spatial dimension: %ld\n", (long)amber->spatialdim);
    } else {
      printf("netcdfplugin) AMBER: Missing spatial dimension, corrupt file?\n");
      printf("netcdfplugin) AMBER: Fixing by guessing spatialdim as '3'\n");
      amber->spatialdim = 3;
    }
  } else {
    printf("netcdfplugin) AMBER: Missing spatial dimension, corrupt file?\n");
    printf("netcdfplugin) AMBER: Fixing by guessing spatialdim as '3'\n");
    amber->spatialdim = 3;
  }
 
  /* read in atom dimension */
  rc = nc_inq_dimid(cdf->ncid, "atom", &amber->atomdimid);
  if (rc == NC_NOERR) {    
    rc = nc_inq_dimlen(cdf->ncid, amber->atomdimid, &amber->atomdim);
    if (rc == NC_NOERR) {
      printf("netcdfplugin) AMBER: atom dimension: %ld\n", (long)amber->atomdim);
      cdf->natoms = amber->atomdim; /* copy to format independent part */
    } else  {
      printf("netcdfplugin) AMBER: missing atom dimension, aborting\n");
      return CDF_ERR;
    }
  } else {
    printf("netcdfplugin) AMBER: missing atom dimension, aborting\n");
    return CDF_ERR;
  }
 

  /* read in frame dimension */
  rc = nc_inq_dimid(cdf->ncid, "frame", &amber->framedimid);
  if (rc == NC_NOERR) {    
    rc = nc_inq_dimlen(cdf->ncid, amber->framedimid, &amber->framedim);
    if (rc == NC_NOERR) {
      printf("netcdfplugin) AMBER: frame dimension: %ld\n", (long)amber->framedim);
    } else {
      printf("netcdfplugin) AMBER: missing frame dimension, aborting\n");
      return CDF_ERR;
    }
  } else {
    printf("netcdfplugin) AMBER: missing frame dimension, aborting\n");
    return CDF_ERR;
  }

  /* 
   * get ID values for all of the variables we're interested in 
   */
#if 0
  /* VMD can live without the various human readable label variables. */
  rc = nc_inq_varid(cdf->ncid, "spatial", &amber->spatial_id);
  if (rc != NC_NOERR)
    return CDF_ERR;

  rc = nc_inq_varid(cdf->ncid, "cell_spatial", &amber->cell_spatial_id);
  if (rc != NC_NOERR)
    return CDF_ERR;

  rc = nc_inq_varid(cdf->ncid, "cell_angular", &amber->cell_angular_id);
  if (rc != NC_NOERR)
    return CDF_ERR;
#endif

  /* VMD requires coordinates at a minimum */
  rc = nc_inq_varid(cdf->ncid, "coordinates", &amber->coordinates_id);
  if (rc != NC_NOERR) {
    printf("netcdfplugin) AMBER: no coordinates variable, nothing to load\n");
    return CDF_ERR;
  }

  /* Coordinate units */
  rc = nc_inq_attlen(cdf->ncid, amber->coordinates_id, "units", &len);
  if (rc == NC_NOERR && len > 0) {
    amber->coordinates_units = (char *) malloc((len+1) * sizeof(char));
    nc_get_att_text(cdf->ncid, amber->coordinates_id, "units", amber->coordinates_units);
    amber->coordinates_units[len] = '\0';
    printf("netcdfplugin) AMBER: coordinates units: '%s'\n", amber->coordinates_units);
  } else {
    printf("netcdfplugin) AMBER: no coordinates units attribute, Angstroms assumed\n");
  }

  /* Coordinate scaling factor to get to Angstroms */
  rc = nc_get_att_float(cdf->ncid, amber->coordinates_id, "scale_factor", &amber->coordinates_scalefactor);
  if (rc == NC_NOERR) {
    printf("netcdfplugin) AMBER: coordinates scalefactor: %f\n", amber->coordinates_scalefactor);
  } else {
    amber->coordinates_scalefactor = 1.0;
  }

#if 0
  /* we don't need velocities at this time */
  rc = nc_inq_varid(cdf->ncid, "velocities", &amber->velocities_id);
  if (rc != NC_NOERR) {
    printf("netcdfplugin) AMBER: missing velocities variable, aborting\n");
    return CDF_ERR;
  }
#endif

  /* optional periodic cell info */
  rc = nc_inq_varid(cdf->ncid, "cell_lengths", &amber->cell_lengths_id);
  if (rc == NC_NOERR) {
    rc = nc_inq_varid(cdf->ncid, "cell_angles", &amber->cell_angles_id);
    if (rc == NC_NOERR) {
      printf("netcdfplugin) AMBER trajectory contains periodic cell information\n");
      amber->has_box = 1;

      /* Cell lengths units */
      rc = nc_inq_attlen(cdf->ncid, amber->cell_lengths_id, "units", &len);
      if (rc == NC_NOERR && len > 0) {
        amber->cell_lengths_units = (char *) malloc((len+1) * sizeof(char));
        nc_get_att_text(cdf->ncid, amber->cell_lengths_id, "units", amber->cell_lengths_units);
        amber->cell_lengths_units[len] = '\0';
        printf("netcdfplugin) AMBER: cell lengths units: '%s'\n", amber->cell_lengths_units);
      } else {
        printf("netcdfplugin) AMBER: no cell lengths units attribute, Angstroms assumed\n");
      }

      /* Cell lengths scaling factor to get to Angstroms */
      rc = nc_get_att_float(cdf->ncid, amber->cell_lengths_id, "scale_factor", &amber->cell_lengths_scalefactor);
      if (rc == NC_NOERR) {
        printf("netcdfplugin) AMBER: cell lengths scalefactor: %f\n", amber->cell_lengths_scalefactor);
      } else {
        amber->cell_lengths_scalefactor = 1.0;
      }

      /* Cell angles units */
      rc = nc_inq_attlen(cdf->ncid, amber->cell_angles_id, "units", &len);
      if (rc == NC_NOERR && len > 0) {
        amber->cell_angles_units = (char *) malloc((len+1) * sizeof(char));
        nc_get_att_text(cdf->ncid, amber->cell_angles_id, "units", amber->cell_angles_units);
        amber->cell_angles_units[len] = '\0';
        printf("netcdfplugin) AMBER: cell angles units: '%s'\n", amber->cell_angles_units);
      } else {
        printf("netcdfplugin) AMBER: no cell angles units attribute, Degrees assumed\n");
      }

      /* Cell angles scaling factor to get to degrees */
      rc = nc_get_att_float(cdf->ncid, amber->cell_angles_id, "scale_factor", &amber->cell_angles_scalefactor);
      if (rc == NC_NOERR) {
        printf("netcdfplugin) AMBER: cell angles scalefactor: %f\n", amber->cell_angles_scalefactor);
      } else {
        amber->cell_angles_scalefactor = 1.0;
      }
    }
  }

  return CDF_SUCCESS;
}
Example #22
0
NCtable_t *NCtableOpen(int ncid, char *tablename)
{
	int status, *dimids, dimid, i = 0, j = 0;
	int ndims, nvars;
	size_t nrecords;
	size_t len;
	char varname [NC_MAX_NAME];
	nc_type type;
	NCfield_t *field = (NCfield_t *) NULL;
	NCtable_t *tbl   = (NCtable_t *) NULL;

	if((status = nc_inq_dimid  (ncid,tablename,&dimid)) != NC_NOERR)
	{ NCprintNCError (status,"NCtableOpen"); return ((NCtable_t *) NULL); }
	if((status = nc_inq_dimlen (ncid,dimid,&nrecords))  != NC_NOERR)
	{ NCprintNCError (status,"NCtableOpen"); return ((NCtable_t *) NULL); }
	if((status = nc_inq_nvars  (ncid,&nvars))           != NC_NOERR)
	{ NCprintNCError (status,"NCtableOpen"); return ((NCtable_t *) NULL); }
	if(nc_inq_ndims(ncid,&ndims) != NC_NOERR)
	{ NCprintNCError (status,"NCtableOpen"); return ((NCtable_t *) NULL); }
	if ((dimids = (int *) malloc(sizeof(int) * ndims)) == (int *) NULL)
	{ CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return (NCtable_t *) NULL; }

	if ((tbl = (NCtable_t *) malloc(sizeof(NCtable_t))) == (NCtable_t *) NULL)
	{ CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); free (dimids); return ((NCtable_t *) NULL); }
	if ((tbl->Name = (char *) malloc (strlen(tablename) + 1)) == (char *) NULL)
	{ CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); free (dimids); free (tbl); return ((NCtable_t *) NULL); }
	strcpy(tbl->Name,tablename);
	tbl->NFields  = 0;
	tbl->Fields   = (NCfield_t *) NULL;

	for(i = 0; i < nvars; i++)
	{
		if ((status = nc_inq_vartype(ncid,i,&type)) != NC_NOERR)
		{ NCprintNCError (status,"NCtableOpen"); free (dimids); NCtableClose (tbl); return ((NCtable_t *) NULL); }
		if ((len = _NCtableVarLen(ncid,i,dimid,dimids)) == NCfailed) continue;
		if ((type != NC_CHAR) && (len > 1)) continue;

		if((status = nc_inq_varname(ncid,i,varname)) != NC_NOERR)
		{ NCprintNCError (status,"NCtableOpen"); free (dimids); NCtableClose (tbl); return ((NCtable_t *) NULL); }

		if ((tbl->Fields = (NCfield_t *) realloc (tbl->Fields, sizeof (NCfield_t) * (tbl->NFields + 1))) == (NCfield_t *) NULL)
		{ CMmsgPrint (CMmsgSysError, "Error allocating memory in: %s %d",__FILE__,__LINE__); free (dimids); NCtableClose (tbl); return ((NCtable_t *) NULL); }
		field = tbl->Fields + tbl->NFields;
		tbl->NFields += 1;
		field->NRecords = nrecords;
		field->Data = (void *) NULL;
		field->Name = (char *) NULL;
		field->Type = type;
		field->Len  = len;

		if ((field->Name = malloc (strlen (varname) + 1)) == (char *) NULL)
		{ CMmsgPrint (CMmsgSysError, "Error allocating memory in: %s %d",__FILE__,__LINE__); free (dimids); NCtableClose (tbl); return ((NCtable_t *) NULL); }
		strcpy (field->Name,varname);

		if (nc_get_att_double (ncid,i,NCnameVAScaleFactor,&field->Scale)      != NC_NOERR) field->Scale      = 1.0;
		if (nc_get_att_double (ncid,i,NCnameVAAddOffset,  &field->Offset)     != NC_NOERR) field->Offset     = 0.0;

		switch(field->Type)
		{
			case NC_CHAR:
				if ((field->Data = (void *) malloc(field->NRecords * field->Len * sizeof (char)))   == (void *) NULL)
				{ CMmsgPrint (CMmsgSysError, "Error allocating memory in: %s %d",__FILE__,__LINE__); free (dimids); NCtableClose (tbl); return ((NCtable_t *) NULL); }
				if((status = nc_get_var_text(ncid,i,(char *) (field->Data))) != NC_NOERR)
				{ NCprintNCError (status,"NCtableOpen"); free (dimids); NCtableClose (tbl); return ((NCtable_t *) NULL); }
				break;
			case NC_BYTE:
			case NC_SHORT:
			case NC_INT:
				if ((field->Data = (void *) malloc(field->NRecords * field->Len * sizeof (int)))   == (void *) NULL)
				{ CMmsgPrint (CMmsgSysError, "Error allocating memory in: %s %d",__FILE__,__LINE__); free (dimids); NCtableClose (tbl); return ((NCtable_t *) NULL); }
				if((status = nc_get_var_int(ncid,i,(int *) (field->Data))) != NC_NOERR)
				{ NCprintNCError (status,"NCtableOpen"); free (dimids); NCtableClose (tbl); return ((NCtable_t *) NULL); }
				if (nc_get_att_int    (ncid,i,NCnameVAFillValue,  &field->FillValue.Int)  != NC_NOERR) field->FillValue.Int  = INT_NOVALUE;
				if (nc_get_att_double (ncid,i,NCnameVAMissingVal, &field->MissingVal)     != NC_NOERR) field->MissingVal     = FLOAT_NOVALUE;
				break;
			case NC_FLOAT:
			case NC_DOUBLE:
				if ((field->Data = (void *) malloc(field->NRecords * field->Len * sizeof (double))) == (void *) NULL)
				{ CMmsgPrint (CMmsgSysError, "Error allocating memory in: %s %d",__FILE__,__LINE__); free (dimids); NCtableClose (tbl); return ((NCtable_t *) NULL); }
				if((status = nc_get_var_double(ncid,i,(double *) (field->Data))) != NC_NOERR)
				{ NCprintNCError (status,"NCtableOpen"); free (dimids); NCtableClose (tbl); return ((NCtable_t *) NULL); }
				if (nc_get_att_double (ncid,i,NCnameVAFillValue,  &field->FillValue.Float)  != NC_NOERR) field->FillValue.Float = FLOAT_NOVALUE;
				if (nc_get_att_double (ncid,i,NCnameVAMissingVal, &field->MissingVal)       != NC_NOERR) field->MissingVal      = FLOAT_NOVALUE;
				break;
			default:        field->Data = (void *) NULL; break;
		}
		if(GetDebug()) CMmsgPrint (CMmsgUsrError, "Loaded: %s(dimid: %d)\n",field->Name,dimid);
	}

	if(GetDebug())
	{
		CMmsgPrint (CMmsgUsrError, "Dim: %d Name: %s Cols: %d Rows: %d\n",dimid,tbl->Name,tbl->NFields,field->NRecords);
		for(i = 0; i < tbl->NFields; i++)
		{
			field = tbl->Fields + i;
			CMmsgPrint (CMmsgUsrError, "\tField: %d Name: %s ",i,field->Name);
			switch(field->Type)
			{
				case NC_CHAR:
					if(field->Len == 1)
					{
						CMmsgPrint (CMmsgUsrError, "Type: char\n");
						for(j = 0; j < 5; j++) CMmsgPrint (CMmsgUsrError, "\t\t%d %c\n",j,((char *) (field->Data)) [j]);
					}
					else
					{
						CMmsgPrint (CMmsgUsrError, "Type: string\n");
						for(j = 0; j < 5; j++) CMmsgPrint (CMmsgUsrError, "\t\t%d %s\n",j,((char *) (field->Data)) + j * field->Len);
					}
					break;
				case NC_BYTE:
				case NC_SHORT:
				case NC_INT:
					CMmsgPrint (CMmsgUsrError, "Type: int\n");
					for(j = 0; j < 5; j++) CMmsgPrint (CMmsgUsrError, "\t\t%d %i\n",j,((int *)    (field->Data)) [j]);
					break;
				case NC_FLOAT:
				case NC_DOUBLE:
					CMmsgPrint (CMmsgUsrError, "Type: double\n");
					for(j = 0; j < 5; j++) CMmsgPrint (CMmsgUsrError, "\t\t%d %f\n",j,((double *) (field->Data)) [j]);
					break;
				default: break;
			}
		}
	}
	return (tbl);
}
int ex_get_processor_node_maps(int exoid, void_int *node_mapi, void_int *node_mapb,
                               void_int *node_mape, int processor)
{
  const char *func_name = "ex_get_processor_node_maps";

  char    ftype[2];
  int     status, varid, dimid;
  size_t  start[1], count[1];
  int64_t varidx[2];
  int     nmstat;

  char errmsg[MAX_ERR_LENGTH];
  /*-----------------------------Execution begins-----------------------------*/

  ex_check_valid_file_id(exoid);

  exerrval = 0; /* clear error code */

  /* Get the file type */
  if (ex_get_file_type(exoid, ftype) != EX_NOERR) {
    exerrval = EX_MSG;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: unable to find file type for file ID %d", exoid);
    ex_err(func_name, errmsg, exerrval);

    return (EX_FATAL);
  }

  /* Get the status of this node map */
  if ((status = nc_inq_varid(exoid, VAR_INT_N_STAT, &varid)) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to find variable ID for \"%s\" from file ID %d",
             VAR_INT_N_STAT, exoid);
    ex_err(func_name, errmsg, exerrval);
    return (EX_FATAL);
  }

  if (ftype[0] == 'p') {
    start[0] = 0;
  }
  else {
    start[0] = processor;
  }

  if (nc_get_var1_int(exoid, varid, start, &nmstat) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get status for \"%s\" in file ID %d",
             VAR_INT_N_STAT, exoid);
    ex_err(func_name, errmsg, exerrval);
    return (EX_FATAL);
  }

  if (nmstat == 1) {
    /* get the index */
    if (ex_get_idx(exoid, VAR_NODE_MAP_INT_IDX, varidx, processor) == -1) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH,
               "ERROR: failed to find index variable, \"%s\", in file ID %d", VAR_NODE_MAP_INT_IDX,
               exoid);
      ex_err(func_name, errmsg, exerrval);

      return (EX_FATAL);
    }

    /* check if I need to get the dimension */
    if (varidx[1] == -1) {
      if ((status = nc_inq_dimid(exoid, DIM_NUM_INT_NODES, &dimid)) != NC_NOERR) {
        exerrval = status;
        snprintf(errmsg, MAX_ERR_LENGTH,
                 "ERROR: failed to find dimension ID for \"%s\" in file ID %d", DIM_NUM_INT_NODES,
                 exoid);
        ex_err(func_name, errmsg, exerrval);
        return (EX_FATAL);
      }

      if ((status = nc_inq_dimlen(exoid, dimid, count)) != NC_NOERR) {
        exerrval = status;
        snprintf(errmsg, MAX_ERR_LENGTH,
                 "ERROR: failed to find length of dimension \"%s\" in file ID %d",
                 DIM_NUM_INT_NODES, exoid);
        ex_err(func_name, errmsg, exerrval);
        return (EX_FATAL);
      }
      varidx[1] = count[0];
    }

    if ((status = nc_inq_varid(exoid, VAR_NODE_MAP_INT, &varid)) != NC_NOERR) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to find variable ID for \"%s\" in file ID %d",
               VAR_NODE_MAP_INT, exoid);
      ex_err(func_name, errmsg, exerrval);
      return (EX_FATAL);
    }

    start[0] = varidx[0];
    count[0] = varidx[1] - varidx[0];
    if (ex_int64_status(exoid) & EX_MAPS_INT64_API) {
      status = nc_get_vara_longlong(exoid, varid, start, count, node_mapi);
    }
    else {
      status = nc_get_vara_int(exoid, varid, start, count, node_mapi);
    }
    if (status != NC_NOERR) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get variable \"%s\" from file ID %d",
               VAR_NODE_MAP_INT, exoid);
      ex_err(func_name, errmsg, exerrval);
      return (EX_FATAL);
    }

  } /* End "if (nmstat == 1)" */

  /* Get the status of this node map */
  if ((status = nc_inq_varid(exoid, VAR_BOR_N_STAT, &varid)) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to find variable ID for \"%s\" from file ID %d",
             VAR_BOR_N_STAT, exoid);
    ex_err(func_name, errmsg, exerrval);
    return (EX_FATAL);
  }

  if (ftype[0] == 'p') {
    start[0] = 0;
  }
  else {
    start[0] = processor;
  }

  if (nc_get_var1_int(exoid, varid, start, &nmstat) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get status for \"%s\" from file ID %d",
             VAR_BOR_N_STAT, exoid);
    ex_err(func_name, errmsg, exerrval);
    return (EX_FATAL);
  }

  if (nmstat == 1) {
    /* get the index */
    if (ex_get_idx(exoid, VAR_NODE_MAP_BOR_IDX, varidx, processor) == -1) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH,
               "ERROR: failed to find index variable, \"%s\", in file ID %d", VAR_NODE_MAP_BOR_IDX,
               exoid);
      ex_err(func_name, errmsg, exerrval);

      return (EX_FATAL);
    }

    /* check if I need to get the dimension */
    if (varidx[1] == -1) {
      if ((status = nc_inq_dimid(exoid, DIM_NUM_BOR_NODES, &dimid)) != NC_NOERR) {
        exerrval = status;
        snprintf(errmsg, MAX_ERR_LENGTH,
                 "ERROR: failed to find dimension ID for \"%s\" in file ID %d", DIM_NUM_BOR_NODES,
                 exoid);
        ex_err(func_name, errmsg, exerrval);
        return (EX_FATAL);
      }

      if ((status = nc_inq_dimlen(exoid, dimid, count)) != NC_NOERR) {
        exerrval = status;
        snprintf(errmsg, MAX_ERR_LENGTH,
                 "ERROR: failed to find length of dimension \"%s\" in file ID %d",
                 DIM_NUM_BOR_NODES, exoid);
        ex_err(func_name, errmsg, exerrval);
        return (EX_FATAL);
      }
      varidx[1] = count[0];
    }

    if ((status = nc_inq_varid(exoid, VAR_NODE_MAP_BOR, &varid)) != NC_NOERR) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to find variable ID for \"%s\" in file ID %d",
               VAR_NODE_MAP_BOR, exoid);
      ex_err(func_name, errmsg, exerrval);
      return (EX_FATAL);
    }

    start[0] = varidx[0];
    count[0] = varidx[1] - varidx[0];
    if (ex_int64_status(exoid) & EX_MAPS_INT64_API) {
      status = nc_get_vara_longlong(exoid, varid, start, count, node_mapb);
    }
    else {
      status = nc_get_vara_int(exoid, varid, start, count, node_mapb);
    }
    if (status != NC_NOERR) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get variable \"%s\" from file ID %d",
               VAR_NODE_MAP_BOR, exoid);
      ex_err(func_name, errmsg, exerrval);
      return (EX_FATAL);
    }
  } /* End "if (nmstat == 1)" */

  /* Get the status of this node map */
  if ((status = nc_inq_varid(exoid, VAR_EXT_N_STAT, &varid)) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to find variable ID for \"%s\" from file ID %d",
             VAR_EXT_N_STAT, exoid);
    ex_err(func_name, errmsg, exerrval);
    return (EX_FATAL);
  }

  if (ftype[0] == 'p') {
    start[0] = 0;
  }
  else {
    start[0] = processor;
  }

  if (nc_get_var1_int(exoid, varid, start, &nmstat) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get status for \"%s\" from file ID %d",
             VAR_EXT_N_STAT, exoid);
    ex_err(func_name, errmsg, exerrval);
    return (EX_FATAL);
  }

  if (nmstat == 1) {
    /* get the index */
    if (ex_get_idx(exoid, VAR_NODE_MAP_EXT_IDX, varidx, processor) == -1) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH,
               "ERROR: failed to find index variable, \"%s\", in file ID %d", VAR_NODE_MAP_EXT_IDX,
               exoid);
      ex_err(func_name, errmsg, exerrval);

      return (EX_FATAL);
    }

    /* check if I need to get the dimension */
    if (varidx[1] == -1) {
      if ((status = nc_inq_dimid(exoid, DIM_NUM_EXT_NODES, &dimid)) != NC_NOERR) {
        exerrval = status;
        snprintf(errmsg, MAX_ERR_LENGTH,
                 "ERROR: failed to find dimension ID for \"%s\" in file ID %d", DIM_NUM_EXT_NODES,
                 exoid);
        ex_err(func_name, errmsg, exerrval);
        return (EX_FATAL);
      }

      if ((status = nc_inq_dimlen(exoid, dimid, count)) != NC_NOERR) {
        exerrval = status;
        snprintf(errmsg, MAX_ERR_LENGTH,
                 "ERROR: failed to find length of dimension \"%s\" in file ID %d",
                 DIM_NUM_EXT_NODES, exoid);
        ex_err(func_name, errmsg, exerrval);
        return (EX_FATAL);
      }
      varidx[1] = count[0];
    }

    if ((status = nc_inq_varid(exoid, VAR_NODE_MAP_EXT, &varid)) != NC_NOERR) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to find variable ID for \"%s\" in file ID %d",
               VAR_NODE_MAP_EXT, exoid);
      ex_err(func_name, errmsg, exerrval);
      return (EX_FATAL);
    }

    start[0] = varidx[0];
    count[0] = varidx[1] - varidx[0];
    if (ex_int64_status(exoid) & EX_MAPS_INT64_API) {
      status = nc_get_vara_longlong(exoid, varid, start, count, node_mape);
    }
    else {
      status = nc_get_vara_int(exoid, varid, start, count, node_mape);
    }
    if (status != NC_NOERR) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get variable \"%s\" from file ID %d",
               VAR_NODE_MAP_EXT, exoid);
      ex_err(func_name, errmsg, exerrval);
      return (EX_FATAL);
    }
  } /* End "if (nmstat == 1)" */
  return (EX_NOERR);
}
Example #24
0
void CTAI_SObs_netcdf_Create_Init(



/*
   Allocate the memory which is neccesary to store the data necessary for a
   netcdf-observer
*/
     // IN-OUTPUTS
        CTAI_SObs_netcdf *x,   // The netcdf-observer for which the memory must 
                                //     be allocated
     // INPUTS:
        CTA_Handle userdata,   // User data: database-name. Note: the string ends with the date
                               // It is possible that userdata is vector of two handles: (name,timeoffset)
     // OUTPUTS
        int *retval)            // Error code. Possible error: Illegal data type
{
#if HAVE_LIBNETCDF
  char *dbname;
  int   ncid, varid, nmeasr, intNStations;
  size_t nstations;
  int ierr, i, len;
  int dimids[1];
  CTA_Time tspan0;
  float lon1,lon2,lat1,lat2;
  int *flag;
  CTAI_OMI_database *database;
  double timeoffset;
  CTA_Handle  userdata1, userdata2;

  database = CTA_Malloc(sizeof(CTAI_OMI_database));  

  // Get the name of the database file:

  // Check if userdata is a string (database name) or a vector (name and timeoffset)
   ierr=CTA_Handle_Check((CTA_Handle) userdata,CTA_VECTOR);
   if (ierr!=CTA_OK) {
     //then it should be only the string with the database name
     ierr=CTA_Handle_Check((CTA_Handle) userdata,CTA_STRING);
     if (ierr!=CTA_OK) { printf("sobs_netcdf: create :: userdata is neither a database name or vector\n");exit(-1);}
     userdata1 = userdata; timeoffset = 0.0;

     if (IDEBUG>0) {printf("sobs_netcdf_create 1: timeoffset %f ",timeoffset);}

   } else { //it is a vector: deconstruct it into the database string and the timeoffset
   
     CTA_Vector_GetVal(userdata,1,&userdata1,CTA_HANDLE);
     CTA_Vector_GetVal(userdata,2,&userdata2,CTA_HANDLE);
     ierr=CTA_Vector_GetVal(userdata2,1,&timeoffset,CTA_DOUBLE);
     if (ierr!=CTA_OK) {
       printf("CTAI_SObs_netcdf :: Create: userdata2 is not a vector of doubles! \n");
   }
     if (IDEBUG>0) {printf("sobs_netcdf_create 2: timeoffset %f ",timeoffset);}
   }


  // Allocate a name-string 
  *retval = CTA_String_GetLength(userdata1, &len);
  if (*retval!=CTA_OK) return;
  // Get the name of the database
  dbname = CTA_Malloc((len+1)*sizeof(char));
  *retval = CTA_String_Get(userdata1, dbname);
  if (*retval!=CTA_OK) return;

  // Open the database
  ierr = nc_open(dbname, NC_NOWRITE, &ncid);
  if (ierr != CTA_OK)
    {printf("Error: could not open netcdf-file \n");
      *retval = -1;
      return;}

   // Count the stations in this observer. 
  // Note: we denote each valid observation of the satellite as one station with a specific pace and time. 
  // The number of valid observations is O(10^4), while the total grid is typical O(10^5), in the case of 
  //   OMI-data and our part of Europe: 350x501 and a time series of length 8000.
  ierr = nc_inq_varid(ncid, "longitude", &varid);
  if (ierr != CTA_OK)
    {printf("Error: could not find datetime \n");*retval = -1; return;}

  ierr = nc_inq_vardimid(ncid, varid, dimids); // get ID of time dimension
  if (ierr != CTA_OK)
    {printf("Error: could not find dimension ID \n");*retval = -1; return;}

  ierr = nc_inq_dimlen(ncid, dimids[0], &nstations); /* get length of time series */
  if (ierr != CTA_OK)
    {printf("Error: could not length of time series \n");*retval = -1; return;}

 
  // initialise the selection relation table
  CTA_RelTable_Create(&(x->selectionReltab));

  flag=CTA_Malloc(nstations*sizeof(int));
  for (i=0; i < (int) nstations; i++) {flag[i] = i+1;}

  intNStations=(int) nstations; 
  CTA_RelTable_SetSelectVal(x->selectionReltab, flag, intNStations,CTA_INTEGER);
  if (IDEBUG>0) {printf("ctai_sobs_netcdf_init: number of stations/length of time series: %d \n",intNStations);}
  

  // initialise the time
   CTA_Time_Create(&tspan0);
   CTA_Time_SetSpan(tspan0, 0.0, 24.0);

   // initialise the spatial window. Maybe it should be read from netcdf-file (global attribute)
   lon1 = -90.0; // far west
   lon2 = 90.0;  // far east
   lat1 = 0.0;  //equator
   lat2= 90.0;  //north pole   

   // Measurements in this observer = Number of stations in our case! 
   nmeasr = nstations;

   // Set the observer-fields
   x->tspan = tspan0;    
   x->bb_lon[0] = lon1;   x->bb_lon[1] = lon2;
   x->bb_lat[0] = lat1;   x->bb_lat[1] = lat2;



   database->dbname = dbname;
   database->ncid = ncid;
   database->nusers = 1;

   x->database = database;
   x->nstations = nstations;
   x->nmeasr    = nmeasr;
   x->nmeasr_orig = nmeasr;


   x->timeoffset = timeoffset;

if (IDEBUG>0) {printf("END of cta_sobs_netcdf_create_init \n");}
   *retval=CTA_OK;

#else
   printf("Error: CTAI_SObs_netcdf_Create_Init: COSTA is compiled without NETCDF support\n");
  *retval=CTA_NOT_IMPLEMENTED;
#endif

};
Example #25
0
int ex_id_lkup(int exoid, ex_entity_type id_type, ex_entity_id num)
{

  char *   id_table;
  char *   id_dim;
  char *   stat_table;
  int      varid, dimid;
  size_t   dim_len, i;
  int64_t *id_vals   = NULL;
  int *    stat_vals = NULL;

  static int        filled = EX_FALSE;
  struct obj_stats *tmp_stats;
  int               status;
  char              errmsg[MAX_ERR_LENGTH];

  exerrval = 0; /* clear error code */

  switch (id_type) {
  case EX_NODAL: return 0;
  case EX_GLOBAL: return 0;
  case EX_ELEM_BLOCK:
    id_table   = VAR_ID_EL_BLK;   /* id array name */
    id_dim     = DIM_NUM_EL_BLK;  /* id array dimension name*/
    stat_table = VAR_STAT_EL_BLK; /* id status array name */
    tmp_stats  = ex_get_stat_ptr(exoid, &exoII_eb);
    break;
  case EX_NODE_SET:
    id_table   = VAR_NS_IDS;
    id_dim     = DIM_NUM_NS;
    stat_table = VAR_NS_STAT;
    tmp_stats  = ex_get_stat_ptr(exoid, &exoII_ns);
    break;
  case EX_SIDE_SET:
    id_table   = VAR_SS_IDS;
    id_dim     = DIM_NUM_SS;
    stat_table = VAR_SS_STAT;
    tmp_stats  = ex_get_stat_ptr(exoid, &exoII_ss);
    break;
  case EX_EDGE_BLOCK:
    id_table   = VAR_ID_ED_BLK;
    id_dim     = DIM_NUM_ED_BLK;
    stat_table = VAR_STAT_ED_BLK;
    tmp_stats  = ex_get_stat_ptr(exoid, &exoII_ed);
    break;
  case EX_FACE_BLOCK:
    id_table   = VAR_ID_FA_BLK;
    id_dim     = DIM_NUM_FA_BLK;
    stat_table = VAR_STAT_FA_BLK;
    tmp_stats  = ex_get_stat_ptr(exoid, &exoII_fa);
    break;
  case EX_EDGE_SET:
    id_table   = VAR_ES_IDS;
    id_dim     = DIM_NUM_ES;
    stat_table = VAR_ES_STAT;
    tmp_stats  = ex_get_stat_ptr(exoid, &exoII_es);
    break;
  case EX_FACE_SET:
    id_table   = VAR_FS_IDS;
    id_dim     = DIM_NUM_FS;
    stat_table = VAR_FS_STAT;
    tmp_stats  = ex_get_stat_ptr(exoid, &exoII_fs);
    break;
  case EX_ELEM_SET:
    id_table   = VAR_ELS_IDS;
    id_dim     = DIM_NUM_ELS;
    stat_table = VAR_ELS_STAT;
    tmp_stats  = ex_get_stat_ptr(exoid, &exoII_els);
    break;
  case EX_NODE_MAP:
    id_table   = VAR_NM_PROP(1);
    id_dim     = DIM_NUM_NM;
    stat_table = "";
    tmp_stats  = ex_get_stat_ptr(exoid, &exoII_nm);
    break;
  case EX_EDGE_MAP:
    id_table   = VAR_EDM_PROP(1);
    id_dim     = DIM_NUM_EDM;
    stat_table = "";
    tmp_stats  = ex_get_stat_ptr(exoid, &exoII_edm);
    break;
  case EX_FACE_MAP:
    id_table   = VAR_FAM_PROP(1);
    id_dim     = DIM_NUM_FAM;
    stat_table = "";
    tmp_stats  = ex_get_stat_ptr(exoid, &exoII_fam);
    break;
  case EX_ELEM_MAP:
    id_table   = VAR_EM_PROP(1);
    id_dim     = DIM_NUM_EM;
    stat_table = "";
    tmp_stats  = ex_get_stat_ptr(exoid, &exoII_em);
    break;
  default:
    exerrval = EX_BADPARAM;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: unsupported id array type %d for file id %d", id_type,
             exoid);
    ex_err("ex_id_lkup", errmsg, exerrval);
    return (EX_FATAL);
  }

  if ((tmp_stats->id_vals == NULL) || (!(tmp_stats->valid_ids))) {

    /* first time thru or id arrays haven't been completely filled yet */

    /* get size of id array */

    /* First get dimension id of id array */
    if ((status = nc_inq_dimid(exoid, id_dim, &dimid)) != NC_NOERR) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate id array dimension in file id %d",
               exoid);
      ex_err("ex_id_lkup", errmsg, exerrval);
      return (EX_FATAL);
    }

    /* Next get value of dimension */
    if ((status = nc_inq_dimlen(exoid, dimid, &dim_len)) != NC_NOERR) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate %s array length in file id %d",
               id_table, exoid);
      ex_err("ex_id_lkup", errmsg, exerrval);
      return (EX_FATAL);
    }

    /* get variable id of id array */
    if ((status = nc_inq_varid(exoid, id_table, &varid)) != NC_NOERR) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate %s array in file id %d", id_table,
               exoid);
      ex_err("ex_id_lkup", errmsg, exerrval);
      return (EX_FATAL);
    }

    /* allocate space for id array and initialize to zero to ensure
       that the higher bits don't contain garbage while copy from ints */
    if (!(id_vals = calloc(dim_len, sizeof(int64_t)))) {
      exerrval = EX_MEMFAIL;
      snprintf(errmsg, MAX_ERR_LENGTH,
               "ERROR: failed to allocate memory for %s array for file id %d", id_table, exoid);
      ex_err("ex_id_lkup", errmsg, exerrval);
      return (EX_FATAL);
    }

    if (ex_int64_status(exoid) & EX_IDS_INT64_API) {
      status = nc_get_var_longlong(exoid, varid, (long long *)id_vals);
    }
    else {
      int *id_vals_int;
      if (!(id_vals_int = malloc(dim_len * sizeof(int)))) {
        exerrval = EX_MEMFAIL;
        snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to allocate memory for temporary array "
                                         "id_vals_int for file id %d",
                 exoid);
        ex_err("ex_id_lkup", errmsg, exerrval);
        free(id_vals);
        return (EX_FATAL);
      }
      status = nc_get_var_int(exoid, varid, (int *)id_vals_int);
      if (status == NC_NOERR) {
        for (i = 0; i < dim_len; i++) {
          id_vals[i] = (int64_t)id_vals_int[i];
        }
      }
      free(id_vals_int);
    }

    if (status != NC_NOERR) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get %s array from file id %d", id_table,
               exoid);
      ex_err("ex_id_lkup", errmsg, exerrval);
      free(id_vals);
      return (EX_FATAL);
    }

    /* check if values in stored arrays are filled with non-zeroes */
    filled = EX_TRUE;
    for (i = 0; i < dim_len; i++) {
      if (id_vals[i] == EX_INVALID_ID || id_vals[i] == NC_FILL_INT) {
        filled = EX_FALSE;
        break; /* id array hasn't been completely filled with valid ids yet */
      }
    }

    if (filled) {
      tmp_stats->valid_ids = EX_TRUE;
      tmp_stats->num       = dim_len;
      tmp_stats->id_vals   = id_vals;
    }
  }
  else {
    id_vals = tmp_stats->id_vals;
    dim_len = tmp_stats->num;
  }

  /* Do a linear search through the id array to find the array value
     corresponding to the passed index number */

  for (i = 0; i < dim_len; i++) {
    if (id_vals[i] == num) {
      break; /* found the id requested */
    }
  }
  if (i >= dim_len) /* failed to find id number */
  {
    if (!(tmp_stats->valid_ids)) {
      free(id_vals);
    }
    exerrval = EX_LOOKUPFAIL;
    return (EX_LOOKUPFAIL); /*if we got here, the id array value doesn't exist */
  }

  /* Now check status array to see if object is null */

  /* get variable id of status array */
  if (nc_inq_varid(exoid, stat_table, &varid) == NC_NOERR) {
    /* if status array exists, use it, otherwise assume object exists
       to be backward compatible */

    if ((tmp_stats->stat_vals == NULL) || (!(tmp_stats->valid_stat))) {
      /* first time thru or status arrays haven't been filled yet */

      /* allocate space for new status array */

      if (!(stat_vals = malloc(dim_len * sizeof(int)))) {
        exerrval = EX_MEMFAIL;
        free(id_vals);
        snprintf(errmsg, MAX_ERR_LENGTH,
                 "ERROR: failed to allocate memory for %s array for file id %d", id_table, exoid);
        ex_err("ex_id_lkup", errmsg, exerrval);
        return (EX_FATAL);
      }

      if ((status = nc_get_var_int(exoid, varid, stat_vals)) != NC_NOERR) {
        exerrval = status;
        free(id_vals);
        free(stat_vals);
        snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get %s array from file id %d",
                 stat_table, exoid);
        ex_err("ex_id_lkup", errmsg, exerrval);
        return (EX_FATAL);
      }

      if (tmp_stats->valid_ids) {
        /* status array is valid only if ids are valid */
        tmp_stats->valid_stat = EX_TRUE;
        tmp_stats->stat_vals  = stat_vals;
      }
    }
    else {
      stat_vals = tmp_stats->stat_vals;
    }

    if (stat_vals[i] == 0) /* is this object null? */ {
      exerrval = EX_NULLENTITY;
      if (!(tmp_stats->valid_stat)) {
        free(stat_vals);
      }
      if (!(tmp_stats->valid_ids)) {
        free(id_vals);
      }
      return (-((int)i + 1)); /* return index into id array (1-based) */
    }
  }
  if (!(tmp_stats->valid_ids)) {
    free(id_vals);
    free(stat_vals);
  }
  return (i + 1); /* return index into id array (1-based) */
}
Example #26
0
int ex_put_num_map ( int exoid,
                     ex_entity_type map_type,
                     int map_id,
                     const int *map )
{
   int dimid, varid;
   size_t start[1]; 
   int ldum;
   int num_maps;
   size_t num_entries;
   int cur_num_maps;
   char errmsg[MAX_ERR_LENGTH];
   const char* dnumentries;
   const char* dnummaps;
   const char* vmapids;
   const char* vmap;
   int status;
   
   exerrval = 0; /* clear error code */

   switch ( map_type ) {
   case EX_NODE_MAP:
     dnumentries = DIM_NUM_NODES;
     dnummaps = DIM_NUM_NM;
     vmapids = VAR_NM_PROP(1);
     break;
   case EX_EDGE_MAP:
     dnumentries = DIM_NUM_EDGE;
     dnummaps = DIM_NUM_EDM;
     vmapids = VAR_EDM_PROP(1);
     break;
   case EX_FACE_MAP:
     dnumentries = DIM_NUM_FACE;
     dnummaps = DIM_NUM_FAM;
     vmapids = VAR_FAM_PROP(1);
     break;
   case EX_ELEM_MAP:
     dnumentries = DIM_NUM_ELEM;
     dnummaps = DIM_NUM_EM;
     vmapids = VAR_EM_PROP(1);
     break;
   default:
     exerrval = EX_BADPARAM;
     sprintf( errmsg,
       "Error: Bad map type (%d) specified for file id %d",
       map_type, exoid );
     ex_err( "ex_put_num_map", errmsg, exerrval );
     return (EX_FATAL);
   }

   /* Make sure the file contains entries */
   if (nc_inq_dimid (exoid, dnumentries, &dimid) != NC_NOERR )
   {
     return (EX_NOERR);
   }

   /* first check if any maps are specified */
   if ((status = nc_inq_dimid (exoid, dnummaps, &dimid)) != NC_NOERR )
   {
     exerrval = status;
     sprintf(errmsg,
            "Error: no %ss specified in file id %d",
             ex_name_of_object(map_type),exoid);
     ex_err("ex_put_num_map",errmsg,exerrval);
     return (EX_FATAL);
   }

   /* Check for duplicate map id entry */
   ex_id_lkup(exoid,map_type,map_id); 
   if (exerrval != EX_LOOKUPFAIL)   /* found the map id */
   {
     sprintf(errmsg,
            "Error: %s %d already defined in file id %d",
             ex_name_of_object(map_type),map_id,exoid);
     ex_err("ex_put_num_map",errmsg,exerrval);
     return(EX_FATAL);
   }

   /* Get number of maps initialized for this file */
   if ((status = nc_inq_dimlen(exoid,dimid,&num_entries)) != NC_NOERR)
   {
     exerrval = status;
     sprintf(errmsg,
            "Error: failed to get number of %ss in file id %d",
             ex_name_of_object(map_type),exoid);
     ex_err("ex_put_num_map",errmsg,exerrval);
     return (EX_FATAL);
   }
   num_maps = num_entries;

   /* Keep track of the total number of maps defined using a counter stored
      in a linked list keyed by exoid.
      NOTE: ex_get_file_item  is used to find the number of maps
      for a specific file and returns that value.
   */
   cur_num_maps = ex_get_file_item(exoid, ex_get_counter_list(map_type));
   if (cur_num_maps >= num_maps) {
     exerrval = EX_FATAL;
     sprintf(errmsg,
          "Error: exceeded number of %ss (%d) specified in file id %d",
             ex_name_of_object(map_type),num_maps,exoid);
     ex_err("ex_put_num_map",errmsg,exerrval);
     return (EX_FATAL);
   }

   /*   NOTE: ex_inc_file_item  is used to find the number of maps
	for a specific file and returns that value incremented. */
   cur_num_maps = ex_inc_file_item(exoid, ex_get_counter_list(map_type));

   /* write out information to previously defined variable */

   /* first get id of variable */
   if ((status = nc_inq_varid (exoid, vmapids, &varid)) == -1)
   {
     exerrval = status;
     sprintf(errmsg,
            "Error: failed to locate %s ids in file id %d",
             ex_name_of_object(map_type),exoid);
     ex_err("ex_put_num_map",errmsg,exerrval);
     return (EX_FATAL);
   }

   /* then, write out map id */
   start[0] = cur_num_maps;

   ldum = (int)map_id;
   if ((status = nc_put_var1_int(exoid, varid, start, &ldum)) != NC_NOERR)
   {
     exerrval = status;
     sprintf(errmsg,
            "Error: failed to store %s id %d in file id %d",
             ex_name_of_object(map_type),map_id,exoid);
     ex_err("ex_put_num_map",errmsg,exerrval);
     return (EX_FATAL);
   }

   switch ( map_type ) {
   case EX_NODE_MAP:
     vmap = VAR_NODE_MAP(cur_num_maps+1);
     break;
   case EX_EDGE_MAP:
     vmap = VAR_EDGE_MAP(cur_num_maps+1);
     break;
   case EX_FACE_MAP:
     vmap = VAR_FACE_MAP(cur_num_maps+1);
     break;
   case EX_ELEM_MAP:
     vmap = VAR_ELEM_MAP(cur_num_maps+1);
     break;
  default:
    exerrval = 1005;
    sprintf(errmsg,
	    "Internal Error: unrecognized map type in switch: %d in file id %d",
	    map_type,exoid);
    ex_err("ex_putt_n_one_attr",errmsg,EX_MSG);
    return (EX_FATAL);
   }

   /* locate variable array in which to store the map */
   if ((status = nc_inq_varid(exoid,vmap,&varid)) != NC_NOERR)
     {
       int dims[2];

       /* determine number of entries */
       if ((status = nc_inq_dimid (exoid, dnumentries, &dimid)) == -1 )
	 {
	   exerrval = status;
	   sprintf(errmsg,
		   "Error: couldn't determine number of %s entries in file id %d",
		   ex_name_of_object(map_type),exoid);
	   ex_err("ex_put_num_map",errmsg,exerrval);
	   return (EX_FATAL);
	 }
       
       status = 0;
       
       if ((status = nc_redef( exoid )) != NC_NOERR ) {
         exerrval = status;
         sprintf(errmsg, "Error: failed to place file id %d into define mode", exoid);
         ex_err("ex_put_num_map",errmsg,exerrval);
         return (EX_FATAL);
       }

       dims[0] = dimid;
       if ((status = nc_def_var( exoid, vmap, NC_INT, 1, dims, &varid )) == -1 ) {
         exerrval = status;
         sprintf(errmsg, "Error: failed to define map %s in file id %d", vmap, exoid);
         ex_err("ex_put_num_map",errmsg,exerrval);
       }

       if ((status = nc_enddef(exoid)) != NC_NOERR ) { /* exit define mode */
         sprintf( errmsg, "Error: failed to complete definition for file id %d", exoid );
         ex_err( "ex_put_num_map", errmsg, exerrval );
         varid = -1; /* force early exit */
       }

       if ( varid == -1 ) /* we couldn't define variable and have prepared error message. */
         return (EX_FATAL);
     }

   /* write out the map  */
   if ((status = nc_put_var_int(exoid, varid, map)) != NC_NOERR)
   {
     exerrval = status;
     sprintf(errmsg,
            "Error: failed to store %s in file id %d",
             ex_name_of_object(map_type),exoid);
     ex_err("ex_put_num_map",errmsg,exerrval);
     return (EX_FATAL);
   }

   return (EX_NOERR);
}
Example #27
0
int main(int argc,char *argv[]) {
  struct DataMap *ptr;
  struct DataMapScalar *sx,*sy;
  struct DataMapArray *ax,*ay;
  size_t index[256];
  size_t start[256];
  size_t count[256];

  int s;
  unsigned char vbflg=0;
  unsigned char help=0;
  unsigned char option=0;
  unsigned char zflg=0;

  FILE *fp=NULL;
  gzFile zfp=0;

  FILE *mapfp;
  int n,c,x;
  int ncid;
  int block=0;
 
  int varid;
  
  int strsze;
  char **strptr;
  char *tmpbuf=NULL;

  OptionAdd(&opt,"-help",'x',&help);
  OptionAdd(&opt,"-option",'x',&option);
  OptionAdd(&opt,"vb",'x',&vbflg);
  OptionAdd(&opt,"z",'x',&zflg);


  if (argc>1) {
    arg=OptionProcess(1,argc,argv,&opt,NULL); 
    if (help==1) {
      OptionPrintInfo(stdout,hlpstr);
      exit(0);
    }
    if (option==1) {
      OptionDump(stdout,&opt);
      exit(0);
    }

    if (zflg) {
      zfp=gzopen(argv[arg],"r");
      if (zfp==0) {
        fprintf(stderr,"File not found.\n");
        exit(-1);
      }
    } else {
      fp=fopen(argv[arg],"r");
      if (fp==NULL) {
        fprintf(stderr,"File not found.\n");
        exit(-1);
      }
    }  

  } else {
    OptionPrintInfo(stdout,errstr);
    exit(-1);
  }


  /* load the map */

  mapfp=fopen(argv[arg+1],"r");
  loadmap(mapfp);
  fclose(mapfp);

 

  s=nc_open(argv[arg+2],NC_WRITE,&ncid);
  if (s !=NC_NOERR) {
    fprintf(stderr,"Error opening CDF file.\n");
    exit(-1);
  }


   


  block=0;
  while (1) {

    if (zflg) ptr=DataMapReadZ(zfp);
    else ptr=DataMapFread(fp);

    if (ptr==NULL) break;

    for (c=0;c<ptr->snum;c++) {
      sx=ptr->scl[c];
      for (n=0;n<snum;n++) {
        sy=sptr[n];
        if (strcmp(sx->name,sy->name) !=0) continue;
        if (sx->type !=sy->type) continue;
        break;
      }
      if (n !=snum) { /* mapped variable */
        s=nc_inq_varid(ncid,cdfsname[n],&varid);
        if (s !=NC_NOERR) {
          fprintf(stderr,"Error accessing CDF file.\n");
          exit(-1);
        }
        index[0]=block;
        switch (sx->type) {
        case DATACHAR:
          s=nc_put_var1_text(ncid,varid,index,sx->data.cptr);
          break;
        case DATASHORT:
          s=nc_put_var1_short(ncid,varid,index,sx->data.sptr);
          break;
        case DATAINT:
          s=nc_put_var1_int(ncid,varid,index,sx->data.iptr);
          break;
        case DATAFLOAT:
          s=nc_put_var1_float(ncid,varid,index,sx->data.fptr);
          break;
        case DATADOUBLE:
          s=nc_put_var1_double(ncid,varid,index,sx->data.dptr);
          break;
        case DATASTRING:
          start[0]=block;
          start[1]=0;
          count[0]=1;
          count[1]=strlen(*((char **) sx->data.vptr))+1;
          s=nc_put_vara_text(ncid,varid,start,count,
                             *((char **) sx->data.vptr));
          break;
	}
        if (s !=NC_NOERR) {
          fprintf(stderr,"Error writing CDF file (%d).\n",s);
          exit(-1);
        }
       
      }
    }

    for (c=0;c<ptr->anum;c++) {
      ax=ptr->arr[c];
      for (n=0;n<anum;n++) {
        ay=aptr[n];
      
        if (strcmp(ax->name,ay->name) !=0) continue;
        if (ax->type !=ay->type) continue;
        if (ax->dim !=ay->dim) continue;
        break;
      }
      if (n !=anum) { /* mapped variable */
      
        s=nc_inq_varid(ncid,cdfaname[n],&varid);
        if (s !=NC_NOERR) {
          fprintf(stderr,"Error accessing CDF file.\n");
          exit(-1);
        }
        start[0]=block;
        count[0]=1;
        n=1;
        for (x=0;x<ax->dim;x++) {
          start[1+x]=0;
          count[1+x]=ax->rng[x];
          n=n*ax->rng[x];
	}

        if (ax->type==DATASTRING) {
          int ndims;
          int dimids[NC_MAX_VAR_DIMS];
          size_t dimlen;
          s=nc_inq_varndims(ncid,varid,&ndims);
          if (s !=NC_NOERR) {
            fprintf(stderr,"Error accessing CDF file.\n");
            exit(-1);
          }
          s=nc_inq_vardimid(ncid,varid,dimids);
          if (s !=NC_NOERR) {
            fprintf(stderr,"Error accessing CDF file.\n");
            exit(-1);
          }
          if (ndims-2!=ax->dim) {
            fprintf(stderr,"Error matching dimensions.\n");
            exit(-1);
	  }
          
          s=nc_inq_dimlen(ncid,dimids[ndims-1],&dimlen);
          if (s !=NC_NOERR) {
            fprintf(stderr,"Error accessing CDF file.\n");
            exit(-1);
          }
          strsze=dimlen;
          tmpbuf=malloc(n*strsze);
          if (tmpbuf==NULL) {
            fprintf(stderr,"Failed to allocate buffer.\n");
            exit(-1);
	  }
          memset(tmpbuf,0,n*strsze);
          start[1+ax->dim]=0;
          count[1+ax->dim]=strsze;
          strptr=(char **) ax->data.vptr;
          for (x=0;x<n;x++) strncpy(tmpbuf+x*strsze,strptr[x],strsze);
	}               

        switch (ax->type) { 
        case DATACHAR:
           s=nc_put_vara_text(ncid,varid,start,count,ax->data.cptr);
           break;
        case DATASHORT:
           s=nc_put_vara_short(ncid,varid,start,count,ax->data.sptr);
           break;
        case DATAINT:
           s=nc_put_vara_int(ncid,varid,start,count,ax->data.iptr);
           break;
        case DATAFLOAT:
           s=nc_put_vara_float(ncid,varid,start,count,ax->data.fptr);
           break;
        case DATADOUBLE:
           s=nc_put_vara_double(ncid,varid,start,count,ax->data.dptr);
           break;
        case DATASTRING:
           s=nc_put_vara_text(ncid,varid,start,count,tmpbuf);
	   break;
	}
        if (tmpbuf !=NULL) {
	  free(tmpbuf);
          tmpbuf=NULL;
	}

        if (s !=NC_NOERR) {
          fprintf(stderr,"Error writing CDF file (%d).\n",s);
          exit(-1);
        }
 
      }
    }
  

    DataMapFree(ptr);
    block++;
  }
  nc_close(ncid);
  if (zflg) gzclose(zfp);
  else fclose(fp);
  return 0;
}
Example #28
0
int ex_put_coord (int   exoid,
                  const void *x_coor,
                  const void *y_coor,
                  const void *z_coor)
{
  int status;
  int coordid;
  int coordidx, coordidy, coordidz;

  int numnoddim, ndimdim;
  size_t i, num_nod, num_dim, start[2], count[2];
  char errmsg[MAX_ERR_LENGTH];

  exerrval = 0; /* clear error code */

  /* inquire id's of previously defined dimensions  */

  if ((status = nc_inq_dimid(exoid, DIM_NUM_NODES, &numnoddim)) != NC_NOERR) {
    /* If not found, then this file is storing 0 nodes.
       Return immediately */
    return (EX_NOERR);
  }

  if ((status = nc_inq_dimlen(exoid, numnoddim, &num_nod)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Error: inquire failed to return number of nodes in file id %d",
	    exoid);
    ex_err("ex_put_coord",errmsg,exerrval);
    return (EX_FATAL);
  }

  if ((status = nc_inq_dimid(exoid, DIM_NUM_DIM, &ndimdim)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Error: failed to locate number of dimensions in file id %d",
	    exoid);
    ex_err("ex_put_coord",errmsg,exerrval);
    return (EX_FATAL);
  }

  if ((status = nc_inq_dimlen(exoid, ndimdim, &num_dim)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Error: failed to get number of dimensions in file id %d",
	    exoid);
    ex_err("ex_put_coord",errmsg,exerrval);
    return (EX_FATAL);
  }

  /* write out the coordinates  */
  if (ex_large_model(exoid) == 0) {
    if ((status = nc_inq_varid(exoid, VAR_COORD, &coordid)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
              "Error: failed to locate nodal coordinates in file id %d", exoid);
      ex_err("ex_put_coord",errmsg,exerrval);
      return (EX_FATAL);
    } 

    for (i=0; i<num_dim; i++) {
      char *which = 0;
      start[0] = i;
      start[1] = 0;

      count[0] = 1;
      count[1] = num_nod;

      if (i == 0 && x_coor != NULL) {
	which = "X";
	if (ex_comp_ws(exoid) == 4) {
	  status = nc_put_vara_float(exoid, coordid, start, count, x_coor);
	} else {
	  status = nc_put_vara_double(exoid, coordid, start, count, x_coor);
	}
      }	  
      else if (i == 1 && y_coor != NULL) {
	which = "Y";
	if (ex_comp_ws(exoid) == 4) {
	  status = nc_put_vara_float(exoid, coordid, start, count, y_coor);
	} else {
	  status = nc_put_vara_double(exoid, coordid, start, count, y_coor);
	}
      }
      else if (i == 2 && z_coor != NULL) {
	which = "Z";
	if (ex_comp_ws(exoid) == 4) {
	  status = nc_put_vara_float(exoid, coordid, start, count, z_coor);
	} else {
	  status = nc_put_vara_double(exoid, coordid, start, count, z_coor);
	}
      }
	  
      if (status != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to put %s coord array in file id %d", which, exoid);
	ex_err("ex_put_coord",errmsg,exerrval);
	return (EX_FATAL);
      }
    }
  } else {
    if ((status = nc_inq_varid(exoid, VAR_COORD_X, &coordidx)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
	      "Error: failed to locate x nodal coordinates in file id %d", exoid);
      ex_err("ex_put_coord",errmsg,exerrval);
      return (EX_FATAL);
    }

    if (num_dim > 1) {
      if ((status = nc_inq_varid(exoid, VAR_COORD_Y, &coordidy)) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to locate y nodal coordinates in file id %d", exoid);
	ex_err("ex_put_coord",errmsg,exerrval);
	return (EX_FATAL);
      }
    } else {
      coordidy = 0;
    }
    if (num_dim > 2) {
      if ((status = nc_inq_varid(exoid, VAR_COORD_Z, &coordidz)) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to locate z nodal coordinates in file id %d", exoid);
	ex_err("ex_put_coord",errmsg,exerrval);
	return (EX_FATAL);
      }
    } else {
      coordidz = 0;
    }

    /* write out the coordinates  */
    for (i=0; i<num_dim; i++) {
      const void *coor = NULL;
      char *which = NULL;
       
      if (i == 0) {
	coor = x_coor;
	which = "X";
	coordid = coordidx;
      } else if (i == 1) {
	coor = y_coor;
	which = "Y";
	coordid = coordidy;
      } else if (i == 2) {
	coor = z_coor;
	which = "Z";
	coordid = coordidz;
      }

      if (coor != NULL && coordid != 0) {
	if (ex_comp_ws(exoid) == 4) {
	  status = nc_put_var_float(exoid, coordid, coor);
	} else {
	  status = nc_put_var_double(exoid, coordid, coor);
	}

	if (status != NC_NOERR) {
	  exerrval = status;
	  sprintf(errmsg,
		  "Error: failed to put %s coord array in file id %d", which, exoid);
	  ex_err("ex_put_coord",errmsg,exerrval);
	  return (EX_FATAL);
	}
      }
    }
  }
  return (EX_NOERR);
}
int ex_get_attr_param (int   exoid,
		       ex_entity_type obj_type,
		       ex_entity_id   obj_id,
		       int*  num_attrs)
{
  int status;
  int dimid;
  
  char errmsg[MAX_ERR_LENGTH];
  const char *dnumobjatt;

  int obj_id_ndx;
  size_t lnum_attr_per_entry;
  
  /* Determine index of obj_id in vobjids array */
  if (obj_type == EX_NODAL) {
    obj_id_ndx = 0;
  } else {
    obj_id_ndx = ex_id_lkup(exoid,obj_type,obj_id);
    
    if (exerrval != 0) {
      if (exerrval == EX_NULLENTITY) {
	*num_attrs = 0;
	return (EX_NOERR);
      } 
	sprintf(errmsg,
		"Warning: failed to locate %s id %"PRId64" in id array in file id %d",
		ex_name_of_object(obj_type),obj_id,exoid);
	ex_err("ex_get_attr_param",errmsg,exerrval);
	return (EX_WARN);
      
    }
  }

  switch (obj_type) {
  case EX_SIDE_SET:
    dnumobjatt = DIM_NUM_ATT_IN_SS(obj_id_ndx);
    break;
  case EX_NODE_SET:
    dnumobjatt = DIM_NUM_ATT_IN_NS(obj_id_ndx);
    break;
  case EX_EDGE_SET:
    dnumobjatt = DIM_NUM_ATT_IN_ES(obj_id_ndx);
    break;
  case EX_FACE_SET:
    dnumobjatt = DIM_NUM_ATT_IN_FS(obj_id_ndx);
    break;
  case EX_ELEM_SET:
    dnumobjatt = DIM_NUM_ATT_IN_ELS(obj_id_ndx);
    break;
  case EX_NODAL:
    dnumobjatt = DIM_NUM_ATT_IN_NBLK;
    break;
  case EX_EDGE_BLOCK:
    dnumobjatt = DIM_NUM_ATT_IN_EBLK(obj_id_ndx);
    break;
  case EX_FACE_BLOCK:
    dnumobjatt = DIM_NUM_ATT_IN_FBLK(obj_id_ndx);
    break;
  case EX_ELEM_BLOCK:
    dnumobjatt = DIM_NUM_ATT_IN_BLK(obj_id_ndx);
    break;
  default:
    exerrval = EX_BADPARAM;
    sprintf(errmsg, "Error: Bad block type (%d) specified for file id %d",
	    obj_type, exoid );
    ex_err("ex_get_attr_param",errmsg,exerrval);
    return (EX_FATAL);
  }

  exerrval = 0; /* clear error code */

  if ((status = nc_inq_dimid(exoid, dnumobjatt, &dimid)) != NC_NOERR) {
    /* dimension is undefined */
    *num_attrs = 0;
  } else {
    if ((status = nc_inq_dimlen(exoid, dimid, &lnum_attr_per_entry)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
	      "Error: failed to get number of attributes in %s %"PRId64" in file id %d",
	      ex_name_of_object(obj_type),obj_id, exoid);
      ex_err("ex_get_attr_param",errmsg, exerrval);
      return(EX_FATAL);
    }
    *num_attrs = lnum_attr_per_entry;
  }
  return (EX_NOERR);
}
OSErr NetCDFWindMoverCurv::TextRead(char *path, TMap **newMap, char *topFilePath) // don't want a map  
{
	// this code is for curvilinear grids
	OSErr err = 0;
	long i,j, numScanned, indexOfStart = 0;
	int status, ncid, latIndexid, lonIndexid, latid, lonid, recid, timeid, numdims;
	size_t latLength, lonLength, recs, t_len, t_len2;
	float timeVal;
	char recname[NC_MAX_NAME], *timeUnits=0, month[10];	
	char dimname[NC_MAX_NAME], s[256], topPath[256];
	WORLDPOINTFH vertexPtsH=0;
	float *lat_vals=0,*lon_vals=0,yearShift=0.;
	static size_t timeIndex,ptIndex[2]={0,0};
	static size_t pt_count[2];
	Seconds startTime, startTime2;
	double timeConversion = 1.;
	char errmsg[256] = "",className[256]="";
	char fileName[64],*modelTypeStr=0;
	Point where;
	OSType typeList[] = { 'NULL', 'NULL', 'NULL', 'NULL' };
	MySFReply reply;
	Boolean bTopFile = false, fIsNavy = false;	// for now keep code around but probably don't need Navy curvilinear wind
	//VelocityFH velocityH = 0;
	char outPath[256];
	
	if (!path || !path[0]) return 0;
	strcpy(fPathName,path);
	
	strcpy(s,path);
	SplitPathFile (s, fileName);
	strcpy(fFileName, fileName); // maybe use a name from the file
	status = nc_open(path, NC_NOWRITE, &ncid);
	//if (status != NC_NOERR) {err = -1; goto done;}
	if (status != NC_NOERR) 
	{
#if TARGET_API_MAC_CARBON
		err = ConvertTraditionalPathToUnixPath((const char *) path, outPath, kMaxNameLen) ;
		status = nc_open(outPath, NC_NOWRITE, &ncid);
#endif
		if (status != NC_NOERR) {err = -1; goto done;}
	}
	// check number of dimensions - 2D or 3D
	status = nc_inq_ndims(ncid, &numdims);
	if (status != NC_NOERR) {err = -1; goto done;}
	
	status = nc_inq_attlen(ncid,NC_GLOBAL,"generating_model",&t_len2);
	if (status != NC_NOERR) {fIsNavy = false; /*goto done;*/}	
	else 
	{
		fIsNavy = true;
		// may only need to see keyword is there, since already checked grid type
		modelTypeStr = new char[t_len2+1];
		status = nc_get_att_text(ncid, NC_GLOBAL, "generating_model", modelTypeStr);
		if (status != NC_NOERR) {fIsNavy = false; goto done;}	
		modelTypeStr[t_len2] = '\0';
		
		strcpy(fFileName, modelTypeStr); 
	}
	GetClassName(className);
	if (!strcmp("NetCDF Wind",className))
		SetClassName(fFileName); //first check that name is now the default and not set by command file ("NetCDF Wind")
	
	//if (fIsNavy)
	{
		status = nc_inq_dimid(ncid, "time", &recid); //Navy
		//if (status != NC_NOERR) {err = -1; goto done;}
		if (status != NC_NOERR) 
		{	status = nc_inq_unlimdim(ncid, &recid);	// issue of time not being unlimited dimension
			if (status != NC_NOERR) {err = -1; goto done;}
		}			
	}
	/*else
	 {
	 status = nc_inq_unlimdim(ncid, &recid);	// issue of time not being unlimited dimension
	 if (status != NC_NOERR) {err = -1; goto done;}
	 }*/
	
	//if (fIsNavy)
	status = nc_inq_varid(ncid, "time", &timeid); 
	if (status != NC_NOERR) 
	{	
		status = nc_inq_varid(ncid, "ProjectionHr", &timeid); 
		if (status != NC_NOERR) {err = -1; goto done;}
	}			
	//	if (status != NC_NOERR) {/*err = -1; goto done;*/timeid=recid;} 
	
	//if (!fIsNavy)
	//status = nc_inq_attlen(ncid, recid, "units", &t_len);	// recid is the dimension id not the variable id
	//else	// LAS has them in order, and time is unlimited, but variable/dimension names keep changing so leave this way for now
	status = nc_inq_attlen(ncid, timeid, "units", &t_len);
	if (status != NC_NOERR) 
	{
		timeUnits = 0;	// files should always have this info
		timeConversion = 3600.;		// default is hours
		startTime2 = model->GetStartTime();	// default to model start time
		//err = -1; goto done;
	}
	else
	{
		DateTimeRec time;
		char unitStr[24], junk[10];
		
		timeUnits = new char[t_len+1];
		//if (!fIsNavy)
		//status = nc_get_att_text(ncid, recid, "units", timeUnits);	// recid is the dimension id not the variable id
		//else
		status = nc_get_att_text(ncid, timeid, "units", timeUnits);
		if (status != NC_NOERR) {err = -1; goto done;} 
		timeUnits[t_len] = '\0'; // moved this statement before StringSubstitute, JLM 5/2/10
		StringSubstitute(timeUnits, ':', ' ');
		StringSubstitute(timeUnits, '-', ' ');
		StringSubstitute(timeUnits, 'T', ' ');
		StringSubstitute(timeUnits, 'Z', ' ');
		
		numScanned=sscanf(timeUnits, "%s %s %hd %hd %hd %hd %hd %hd",
						  unitStr, junk, &time.year, &time.month, &time.day,
						  &time.hour, &time.minute, &time.second) ;
		if (numScanned==5)	
		{time.hour = 0; time.minute = 0; time.second = 0; }
		else if (numScanned==7) // has two extra time entries ??	
			time.second = 0;
		else if (numScanned<8)	
		//else if (numScanned!=8)	
		{ 
			//timeUnits = 0;	// files should always have this info
			//timeConversion = 3600.;		// default is hours
			//startTime2 = model->GetStartTime();	// default to model start time
			err = -1; TechError("NetCDFWindMoverCurv::TextRead()", "sscanf() == 8", 0); goto done;
		}
		else
		{
			// code goes here, trouble with the DAYS since 1900 format, since converts to seconds since 1904
			if (time.year ==1900) {time.year += 40; time.day += 1; /*for the 1900 non-leap yr issue*/ yearShift = 40.;}
			DateToSeconds (&time, &startTime2);	// code goes here, which start Time to use ??
			if (!strcmpnocase(unitStr,"HOURS") || !strcmpnocase(unitStr,"HOUR"))
				timeConversion = 3600.;
			else if (!strcmpnocase(unitStr,"MINUTES") || !strcmpnocase(unitStr,"MINUTE"))
				timeConversion = 60.;
			else if (!strcmpnocase(unitStr,"SECONDS") || !strcmpnocase(unitStr,"SECOND"))
				timeConversion = 1.;
			else if (!strcmpnocase(unitStr,"DAYS") || !strcmpnocase(unitStr,"DAY"))
				timeConversion = 24.*3600.;
		}
	} 
	
	if (fIsNavy)
	{
		status = nc_inq_dimid(ncid, "gridy", &latIndexid); //Navy
		if (status != NC_NOERR) {err = -1; goto done;}
		status = nc_inq_dimlen(ncid, latIndexid, &latLength);
		if (status != NC_NOERR) {err = -1; goto done;}
		status = nc_inq_dimid(ncid, "gridx", &lonIndexid);	//Navy
		if (status != NC_NOERR) {err = -1; goto done;}
		status = nc_inq_dimlen(ncid, lonIndexid, &lonLength);
		if (status != NC_NOERR) {err = -1; goto done;}
		// option to use index values?
		status = nc_inq_varid(ncid, "grid_lat", &latid);
		if (status != NC_NOERR) {err = -1; goto done;}
		status = nc_inq_varid(ncid, "grid_lon", &lonid);
		if (status != NC_NOERR) {err = -1; goto done;}
	}
	else
	{
		for (i=0;i<numdims;i++)
		{
			if (i == recid) continue;
			status = nc_inq_dimname(ncid,i,dimname);
			if (status != NC_NOERR) {err = -1; goto done;}
			if (!strncmpnocase(dimname,"X",1) || !strncmpnocase(dimname,"LON",3) || !strncmpnocase(dimname,"nx",2))
			{
				lonIndexid = i;
			}
			if (!strncmpnocase(dimname,"Y",1) || !strncmpnocase(dimname,"LAT",3) || !strncmpnocase(dimname,"ny",2))
			{
				latIndexid = i;
			}
		}
		
		status = nc_inq_dimlen(ncid, latIndexid, &latLength);
		if (status != NC_NOERR) {err = -1; goto done;}
		status = nc_inq_dimlen(ncid, lonIndexid, &lonLength);
		if (status != NC_NOERR) {err = -1; goto done;}
		
		status = nc_inq_varid(ncid, "LATITUDE", &latid);
		if (status != NC_NOERR) 
		{
			status = nc_inq_varid(ncid, "lat", &latid);
			if (status != NC_NOERR) 
			{
				status = nc_inq_varid(ncid, "latitude", &latid);
				if (status != NC_NOERR) {err = -1; goto done;}
			}
		}
		status = nc_inq_varid(ncid, "LONGITUDE", &lonid);
		if (status != NC_NOERR) 
		{
			status = nc_inq_varid(ncid, "lon", &lonid);
			if (status != NC_NOERR) 
			{
				status = nc_inq_varid(ncid, "longitude", &lonid);
				if (status != NC_NOERR) {err = -1; goto done;}
			}
		}
	}
	
	pt_count[0] = latLength;
	pt_count[1] = lonLength;
	vertexPtsH = (WorldPointF**)_NewHandleClear(latLength*lonLength*sizeof(WorldPointF));
	if (!vertexPtsH) {err = memFullErr; goto done;}
	lat_vals = new float[latLength*lonLength]; 
	lon_vals = new float[latLength*lonLength]; 
	if (!lat_vals || !lon_vals) {err = memFullErr; goto done;}
	status = nc_get_vara_float(ncid, latid, ptIndex, pt_count, lat_vals);
	if (status != NC_NOERR) {err = -1; goto done;}
	status = nc_get_vara_float(ncid, lonid, ptIndex, pt_count, lon_vals);
	if (status != NC_NOERR) {err = -1; goto done;}
	for (i=0;i<latLength;i++)
	{
		for (j=0;j<lonLength;j++)
		{
			//if (lat_vals[(latLength-i-1)*lonLength+j]==fill_value)	// this would be an error
			//lat_vals[(latLength-i-1)*lonLength+j]=0.;
			//if (lon_vals[(latLength-i-1)*lonLength+j]==fill_value)
			//lon_vals[(latLength-i-1)*lonLength+j]=0.;
			INDEXH(vertexPtsH,i*lonLength+j).pLat = lat_vals[(latLength-i-1)*lonLength+j];	
			INDEXH(vertexPtsH,i*lonLength+j).pLong = lon_vals[(latLength-i-1)*lonLength+j];
		}
	}
	fVertexPtsH	 = vertexPtsH;
	
	status = nc_inq_dim(ncid, recid, recname, &recs);
	if (status != NC_NOERR) {err = -1; goto done;}
	if (recs<=0) {strcpy(errmsg,"No times in file. Error opening NetCDF wind file"); err =  -1; goto done;}
	
	fTimeHdl = (Seconds**)_NewHandleClear(recs*sizeof(Seconds));
	if (!fTimeHdl) {err = memFullErr; goto done;}
	for (i=0;i<recs;i++)
	{
		Seconds newTime;
		// possible units are, HOURS, MINUTES, SECONDS,...
		timeIndex = i;
		//if (!fIsNavy)
		//status = nc_get_var1_float(ncid, recid, &timeIndex, &timeVal);	// recid is the dimension id not the variable id
		//else
		status = nc_get_var1_float(ncid, timeid, &timeIndex, &timeVal);
		if (status != NC_NOERR) {err = -1; goto done;}
		newTime = RoundDateSeconds(round(startTime2+timeVal*timeConversion));
		//INDEXH(fTimeHdl,i) = startTime2+(long)(timeVal*timeConversion -yearShift*3600.*24.*365.25);	// which start time where?
		//if (i==0) startTime = startTime2+(long)(timeVal*timeConversion -yearShift*3600.*24.*365.25);
		INDEXH(fTimeHdl,i) = newTime-yearShift*3600.*24.*365.25;	// which start time where?
		if (i==0) startTime = newTime-yearShift*3600.*24.*365.25;
	}
	if (model->GetStartTime() != startTime || model->GetModelTime()!=model->GetStartTime())
	{
		if (true)	// maybe use NOAA.ver here?
		{
			short buttonSelected;
			//buttonSelected  = MULTICHOICEALERT(1688,"Do you want to reset the model start time to the first time in the file?",FALSE);
			if(!gCommandFileRun)	// also may want to skip for location files...
				buttonSelected  = MULTICHOICEALERT(1688,"Do you want to reset the model start time to the first time in the file?",FALSE);
			else buttonSelected = 1;	// TAP user doesn't want to see any dialogs, always reset (or maybe never reset? or send message to errorlog?)
			switch(buttonSelected){
				case 1: // reset model start time
					//bTopFile = true;
					model->SetModelTime(startTime);
					model->SetStartTime(startTime);
					model->NewDirtNotification(DIRTY_RUNBAR); // must reset the runbar
					break;  
				case 3: // don't reset model start time
					//bTopFile = false;
					break;
				case 4: // cancel
					err=-1;// user cancel
					goto done;
			}
		}
		//model->SetModelTime(startTime);
		//model->SetStartTime(startTime);
		//model->NewDirtNotification(DIRTY_RUNBAR); // must reset the runbar
	}
	
	fNumRows = latLength;
	fNumCols = lonLength;
	
	status = nc_close(ncid);
	if (status != NC_NOERR) {err = -1; goto done;}
	
	//err = this -> SetInterval(errmsg);
	//if(err) goto done;
	
	// look for topology in the file
	// for now ask for an ascii file, output from Topology save option
	// need dialog to ask for file
	//if (fIsNavy)	// for now don't allow for wind files
	{if (topFilePath[0]) {err = ReadTopology(topFilePath,newMap); goto done;}}
	if (!gCommandFileRun)
	{
		short buttonSelected;
		buttonSelected  = MULTICHOICEALERT(1688,"Do you have an extended topology file to load?",FALSE);
		switch(buttonSelected){
			case 1: // there is an extended top file
				bTopFile = true;
				break;  
			case 3: // no extended top file
				bTopFile = false;
				break;
			case 4: // cancel
				err=-1;// stay at this dialog
				goto done;
		}
	}
	if(bTopFile)
	{
#if TARGET_API_MAC_CARBON
		mysfpgetfile(&where, "", -1, typeList,
					 (MyDlgHookUPP)0, &reply, M38c, MakeModalFilterUPP(STDFilter));
		if (!reply.good)/* return USERCANCEL;*/
		{
			/*if (recs>0)
				err = this -> ReadTimeData(indexOfStart,&velocityH,errmsg);
			else {strcpy(errmsg,"No times in file. Error opening NetCDF file"); err =  -1;}
			if(err) goto done;*/
			err = dynamic_cast<NetCDFWindMoverCurv *>(this)->ReorderPoints(newMap,errmsg);	
			//err = ReorderPoints(fStartData.dataHdl,newMap,errmsg);	// if u, v input separately only do this once?
	 		goto done;
		}
		else
			strcpy(topPath, reply.fullPath);
		
#else
		where = CenteredDialogUpLeft(M38c);
		sfpgetfile(&where, "",
				   (FileFilterUPP)0,
				   -1, typeList,
				   (DlgHookUPP)0,
				   &reply, M38c,
				   (ModalFilterUPP)MakeUPP((ProcPtr)STDFilter, uppModalFilterProcInfo));
		if (!reply.good) 
		{
			/*if (recs>0)
				err = this -> ReadTimeData(indexOfStart,&velocityH,errmsg);
			else {strcpy(errmsg,"No times in file. Error opening NetCDF file"); err =  -1;}
			if(err) goto done;*/
			err = dynamic_cast<NetCDFWindMoverCurv *>(this)->ReorderPoints(newMap,errmsg);	
			//err = ReorderPoints(fStartData.dataHdl,newMap,errmsg);	
	 		/*if (err)*/ goto done;
		}
		
		my_p2cstr(reply.fName);
		
#ifdef MAC
		GetFullPath(reply.vRefNum, 0, (char *)reply.fName, topPath);
#else
		strcpy(topPath, reply.fName);
#endif
#endif		
		strcpy (s, topPath);
		err = ReadTopology(topPath,newMap);	
		goto done;
	}
	
	/*if (recs>0)
		err = this -> ReadTimeData(indexOfStart,&velocityH,errmsg);
	else {strcpy(errmsg,"No times in file. Error opening NetCDF wind file"); err =  -1;}
	if(err) goto done;*/
	err = dynamic_cast<NetCDFWindMoverCurv *>(this)->ReorderPoints(newMap,errmsg);	
	//err = ReorderPoints(fStartData.dataHdl,newMap,errmsg);	
	
done:
	if (err)
	{
		printNote("Error opening NetCDF wind file");
		if(fGrid)
		{
			fGrid ->Dispose();
			delete fGrid;
			fGrid = 0;
		}
		if(vertexPtsH) {DisposeHandle((Handle)vertexPtsH); vertexPtsH = 0;	fVertexPtsH	 = 0;}
	}
	
	if (timeUnits) delete [] timeUnits;
	if (lat_vals) delete [] lat_vals;
	if (lon_vals) delete [] lon_vals;
	if (modelTypeStr) delete [] modelTypeStr;
	//if (velocityH) {DisposeHandle((Handle)velocityH); velocityH = 0;}
	return err;
}