/*
 * $Id$
 *
 * Routines to write/append to a cdf file from Splus
 *
 * $Log$
 */

#include "stdio.h"
#include "math.h"
#include "netcdf.h"
#include <S.h>

#define MAX_LEN 128
#define FAIL -1
#define chk_cdf(rtn_val, mesg) if(rtn_val==FAIL) { fprintf(stderr,"CDF error: %s\n",mesg);return;}

/*
 * cdf_write_data - Write out a hyperslab of data to a netcdf file.
 */

void
cdf_write_data(int *ncid, int *var_id, int *type, long start_dims[],
	       long slice_dims[], void *data)
{
  chk_cdf(ncvarput(*ncid, *var_id, start_dims, slice_dims, data), "Writing data");
}

/*
 * cdf_create - Create a new netcdf file.  If clobber is true then any existing file
 *              by that name is erased, otherwise ncid is -1.
 */

void
cdf_create(char *file_name[], int *ncid, int *clobber)
{
  ncopts = NC_VERBOSE;
  
  *ncid = nccreate(*file_name, (*clobber == TRUE) ? NC_CLOBBER : NC_NOCLOBBER);
  if(*ncid == FAIL)
    {
      fprintf(stderr, "CDF error: Creating data file\n");
      return;
    }
}

/*
 * cdf_add_dim - Create a new dimension.  If unlim is TRUE it is made unlimited.
 */

void
cdf_add_dim(int *ncid, int *dim_id, char *dname[], int *size, int *unlim)
{
  *dim_id = ncdimdef(*ncid, *dname, (*unlim == TRUE) ? NC_UNLIMITED : *size);
  if(*dim_id == FAIL)
    {
      fprintf(stderr, "CDF error: Creating dimension\n");
      return;
    }
}

/*
 * cdf_add_attr - Create a new attribute.  If var_id is -1 then it is a global
 *                attribute.
 */

void
cdf_add_attr(int *ncid, int *var_id, char *aname[], int *type, int *len, void *data)
{
  char **temp=data;
  
  if(*type == NC_CHAR)
    data = *temp;
  
  chk_cdf(ncattput(*ncid, *var_id, *aname, *type, *len, data), "Adding Attribute");
}


/*
 * cdf_add_var - Create a new variable with the given dimensions.
 */

void 
cdf_add_var(int *ncid, int *var_id, char *vname[], int *type, int *ndims, long dims[])
{
  *var_id = ncvardef(*ncid, *vname, *type, *ndims, dims);
  if(*var_id == FAIL)
    {
      fprintf(stderr, "CDF error: Creating variable\n");
      return;
    }
}

/*
 * cdf_data_mode - Put netCDF file into data mode.
 */

void
cdf_data_mode(int *ncid)
{
  chk_cdf(ncendef(*ncid),"Entering Data mode\n");
}
