/*
 ----------------------------------------------------------------------------
 |    Copyright (C) 1999  Emergent IT Inc.  and Raytheon Systems Company    |
 |                                                                          |
 |  Permission to use, modify, and distribute this software and its         |
 |  documentation for any purpose without fee is hereby granted, provided   |
 |  that the above copyright notice appear in all copies and that both that |
 |  copyright notice and this permission notice appear in supporting        |
 |                          documentation.                                  |
 ----------------------------------------------------------------------------
 */

#include <HE5_HdfEosDef.h>

#define HE5_SWIDOFFSET 671088642
#define HE5_NSWATH           400
#define HE5_NSWATHREGN       512
#define HE5_MAXNREGIONS     2048

int  HE5_timeflag = 0;

/* Swath Structure External Arrays */
struct HE5_swathStructure 
{
  hid_t         fid;                     /* HDF-EOS file ID                   */
  hid_t         obj_id;                  /* "SWATHS" group ID                 */
  hid_t         sw_id;                   /* specified swath group ID          */
  hid_t         data_id;                 /* "Data Fields" group ID            */
  hid_t         geo_id;                  /* "Geo Fields" group ID             */
  hid_t         prof_id;                 /* "Profile Fields" group ID         */
  hid_t         plist;                   /* current dataset creation property */
  
  int           active;                  /* Flag: file active or not          */
  int           compcode;                /* compression mode                  */
  int           compparm[5];             /* compression level                 */

  HE5_DTSinfo   *gdataset;               /* pointer to Geo field info         */
  HE5_DTSinfo   *ddataset;               /* pointter to Data field info       */
  HE5_DTSinfo   *pdataset;               /* pointer to Profile field info     */

  long          nGFLD;                   /* number of geo fields              */
  long          nDFLD;                   /* number of data fields             */
  long          nPROF;                   /* number of profile fields          */
  
  char          swname[HE5_OBJNAMELENMAX];/* swath name                       */
};

struct HE5_swathStructure HE5_SWXSwath[HE5_NSWATH];

struct HE5_swathRegion
{
  hid_t        fid;
  hid_t        swathID;
  
  long         nRegions;
  long         StartRegion[HE5_MAXNREGIONS];
  long         StopRegion[HE5_MAXNREGIONS];
  long         StartVertical[HE5_DTSETRANKMAX];
  long         StopVertical[HE5_DTSETRANKMAX];
  
  char         *DimNamePtr[HE5_DTSETRANKMAX];
};

struct HE5_swathRegion *HE5_SWXRegion[HE5_NSWATHREGN];

struct HE5_dtsIDs
{
  hid_t        type_id;
  hid_t        space_id;
  hid_t        plist_id;
};

struct HE5_dtsIDs  profile;


/* INTERNAL FUNCTION PROTOTYPES */
int HE5_szip_can_encode(void );
static herr_t  
HE5_SWchkswid(hid_t swathID, const char *routname, hid_t *fid, hid_t *gid,  long *idx);
static long  
HE5_SWinqfields(hid_t swathID, char *fieldtype, char *fieldlist, int rank[], hid_t ntype[]);
static size_t 
HE5_SWfieldsizeID(hid_t swathID, char *fieldname, hid_t *fieldID);
static herr_t 
HE5_SWdefinefield(hid_t swathID, char *fieldtype, const char *fieldname, char *dimlist, char *maxdimlist, hid_t typeID, int merge);
static herr_t 
HE5_SWwrrdfield(hid_t swathID, char *fieldname, char *code, const hssize_t start[], const hsize_t stride[], const hsize_t count[],  void * datbuf);
static herr_t 
HE5_SWfinfo(hid_t swathID, char *fieldtype, char *fieldname, int *rank, hsize_t dims[], hid_t ntype[], char *dimlist, char *maxdimlist);
static int 
HE5_SWfldnameinfo(hid_t swathID, char *fieldname, char *fldactualname);
static herr_t
HE5_SWupdatedim(hid_t swathID,  char *dimname, hsize_t dim);
static herr_t
HE5_SWllmapedidxinfo(hid_t swathID, char *object, long *index0, long *index1);

static herr_t
HE5_SWflddiminfo(hid_t SwathID, char *fieldname, int *rank,  hsize_t dims[], hsize_t maxdims[]);


/* CUSTOM MEMORY MANAGEMENT ROUTINES */

/*
  void *
  vltypes_alloc_custom(size_t size, void *info);
  void  
  vltypes_free_custom(void *mem, void *info);
*/


/* FORTRAN WRAPPER PROTOTYPES */


/* File/Swath access routines */

int
HE5_SWopenF(char *filename, int flags);
int 
HE5_SWcreateF(int fileID, char *swathname);
int 
HE5_SWattachF(int fileID, char *swathname);
int
HE5_SWdetachF(int swathID);
int 
HE5_SWcloseF(int fileID);


/* Definition routines */

int
HE5_SWdefdimF(int swathID,  char *dimname, long dim);
int
HE5_SWdefdimmapF(int swathID, char *geodim, char *datadim, long offset, long increment);
int
HE5_SWdefidxmapF(int swathID, char *geodim, char *datadim, long index[]);
int 
HE5_SWdefgfld(int swathID, char *fieldname, char *fortdimlist, char *fortmaxdimlist, int numtype, int create_plist_id);
int 
HE5_SWdefdfld(int swathID, char *fieldname, char *fortdimlist, char *fortmaxdimlist, int numtype, int create_plist_id);
int
HE5_SWdefchunkF(int swathID, int ndims, long *dim);
int   
HE5_SWdefcompF(int swathID, int compcode,  int *compparm);
int   
HE5_SWdefcomchunkF(int swathID, int compcode, int *compparm, int rank, long *dim);
long 
HE5_SWupimap(int swathID, int regionID, long indexin[], long indexout[], long indicies[]);
int    
HE5_SWfldrenameF(int swathID, char *oldfieldname, char *newfieldname);


/* I/O routines */

int
HE5_SWwrfld(int swathID, char *fieldname, long fortstart[], long fortstride[], long fortedge[], void *data);
int
HE5_SWwrcharfld(int swathID, char *fieldname, int elemlen, int numelem, long fortstart[], long fortstride[], long fortedge[], void *data);
int
HE5_SWrdfld(int swathID, char *fieldname, long fortstart[],  long fortstride[], long fortedge[], void *buffer);
int
HE5_SWrdcharfld(int swathID, char *fieldname, int elemlen, int numelem, long fortstart[], long fortstride[], long fortedge[], void *buffer);
int
HE5_SWsetfill(int swathID, char *fieldname, int ntype, void *fillval);
int
HE5_SWgetfill(int swathID, char *fieldname, void *fillval);
int
HE5_SWwrattr(int swathID, char *attrname, int ntype, long fortcount[], void * datbuf);
int
HE5_SWwrgattr(int swathID, char *attrname, int ntype, long fortcount[], void *datbuf);
int
HE5_SWwrgeogattr(int swathID, char *attrname, int ntype, long fortcount[], void *datbuf);
int
HE5_SWwrlattr(int swathID, char *fieldname, char *attrname, int ntype, long fortcount[], void *datbuf);
int    
HE5_SWrdattr(int swathID, char *attrname, void *datbuf);
int    
HE5_SWrdgattr(int swathID, char *attrname, void *datbuf);
int
HE5_SWrdgeogattr(int swathID, char *attrname, void *datbuf);
int    
HE5_SWrdlattr(int swathID, char *fieldname, char *attrname, void *datbuf);
int    
HE5_SWsetaliasF(int swathID, char *fieldname, char *fortaliaslist);
int    
HE5_SWdropaliasF(int swathID, int fldgroup, char *aliasname);


/* Inquiry routines */

long 
HE5_SWinqswathF(char *filename, char *swathlist, long *strbufsize);
long 
HE5_SWnentriesF(int swathID, int entrycode, long *strbufsize);
long 
HE5_SWdiminfoF(int swathID, char *dimname);
int
HE5_SWfldinfoF(int swathID, char *fieldname, int *rank, long dims[], int *ntype, char *fortdimlist, char *fortmaxdimlist);
long
HE5_SWinqmapsF(int swathID, char *dimmaps, long offset[], long increment[]);
long
HE5_SWinqimapsF(int swathID, char *idxmaps, long idxsizes[]);
long
HE5_SWinqdimsF(int swathID, char *dimnames, long dims[]);
long 
HE5_SWinqgflds(int swathID, char *fieldlist, int rank[], int ntype[]);
long 
HE5_SWinqdflds(int swathID, char *fieldlist, int rank[], int ntype[]);
int
HE5_SWmapinfoF(int swathID, char *geodim, char *datadim, long *offset, long *increment);
int    
HE5_SWgmapinfo(int swathID, char *geodim);
long
HE5_SWidxmapinfoF(int swathID, char *geodim, char *datadim, long index[]);
int
HE5_SWatinfo(int swathID, char *attrname, int *ntype, long *fortcount);
int
HE5_SWgatinfo(int swathID, char *attrname, int *ntype, long *fortcount);
int
HE5_SWgeogatinfo(int swathID, char *attrname, int *ntype, long *fortcount);
int
HE5_SWlatinfo(int swathID, char *fieldname, char *attrname, int *ntype, long *fortcount);
int
HE5_SWatinfo2(int swathID, char *attrname, int *ntype, long *fortcount, long *fortsize);
int
HE5_SWgatinfo2(int swathID, char *attrname, int *ntype, long *fortcount, long *fortsize);
int
HE5_SWgeogatinfo2(int swathID, char *attrname, int *ntype, long *fortcount, long *fortsize);
int
HE5_SWlatinfo2(int swathID, char *fieldname, char *attrname, int *ntype, long *fortcount, long *fortsize);
long 
HE5_SWinqattrsF(int swathID, char *attrnames, long *strbufsize);
long 
HE5_SWinqgattrs(int swathID, char *attrnames, long *strbufsize);
long
HE5_SWinqgeogattrs(int swathID, char *attrnames, long *strbufsize);
long 
HE5_SWinqlattrs(int swathID, char *fieldname, char *attrnames, long *strbufsize);
int 
HE5_SWcompinfoF(int swathID, char *fieldname, int *compcode, int compparm[]);
int 
HE5_SWreginfo(int swathID, int regionID, char *fieldname, int *ntype, int *rank, long dims[], long *size);
int
HE5_SWperinfo(int swathID, int periodID, char *fieldname, int *ntype, int *rank, long dims[], long *size);
int   
HE5_SWidtype(int swathID, char *fieldname, char *attrname, int fieldgroup, int *Type, int *Class, int *Order, long *size);
int    
HE5_SWaliasinfoF(int swathID, int fldgroup, char *aliasname, int *length, char *buffer);
long
HE5_SWinqdfldaliasF(int swathID, char *fldalias, long *strbufsize);
long
HE5_SWinqgfldaliasF(int swathID, char *fldalias, long *strbufsize);
int
HE5_SWchunkinfoF(int swathID, char *fieldname, int *ndims, long dims[]);
long
HE5_SWgetaliaslistF(int swathID, int fldgroup, char *aliaslist, long *strbufsize);


/* Subsetting routines */

int
HE5_SWdefboxreg(int swathID, double  cornerlon[], double cornerlat[], int mode);
int
HE5_SWdefvrtreg(int rwathID, int regionID, char *vertObj, double fortrange[]);
int
HE5_SWdeftmeper(int swathID, double starttime, double stoptime, int mode);
int    
HE5_SWextreg(int swathID, int regionID, char *fieldname, int externalflag, void *buffer);
int    
HE5_SWextper(int swathID, int periodID, char *fieldname, int externalflag, void *buffer);
int
HE5_SWregidx(int swathID, double cornerlon[], double cornerlat[], int mode, char *geodim, long idxrange[]);
int 
HE5_SWdupreg(int oldregionID);
int    
HE5_SWupscene(int swathID, int regionID);
int
HE5_SWindexinfoF(int regionID, char *object, int *rank, char *fortdimlist, long *fortindices);


/* PROFILE INTERFACE */

int  
HE5_PRdefineF(int swathID, char *profilename, char *fortdimlist, char *fortmaxdimlist, int datatype_id);
int    
HE5_PRwriteF(int swathID, char *profilename, long fortstart[], long fortstride[], long fortedge[], long size, long len[], void *buffer);
int     
HE5_PRreadF(int swathID, char *profilename, long fortstart[], long fortstride[], long fortedge[], long len[], void *buffer);
long  
HE5_PRinquireF(int swathID, char *profnames, int *rank, int *ntype);
int      
HE5_PRinfoF(int swathID, char *profname, int *rank, long dims[], long maxdims[], int *ntype, char *fortdimlist, char *fortmaxdimlist);
int
HE5_PRwrgattrF(int swathID, char *attrname, int ntype, long fortcount[], void *datbuf);
int
HE5_PRrdgattrF(int swathID, char *attrname, void *datbuf);
int
HE5_PRgattrinfoF(int swathID, char *attrname, int *ntype, long *fortcount);
int
HE5_PRgattrinfoF2(int swathID, char *attrname, int *ntype, long *fortcount, long *fortsize);
long
HE5_PRinqgattrsF(int swathID, char *attrnames, long *strbufsize);


/* EXTERNAL DATA FILE INTERFACE */

int   
HE5_SWsetextdataF(int swathID, char *fortfilelist, long offset[], long size[]);
int   
HE5_SWgetextdataF(int swathID, char *fieldname, long namelength, char *fortfilelist, long offset[], long size[]);

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWopen                                                       |
|                                                                             |
|  DESCRIPTION:                                                               |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|     fid          hid_t    None       HDF-EOS file ID                        |
|                                                                             |
|  INPUTS:                                                                    |
|     filename    char*    None       File name string                        |
|     flags       uintn    None       File access code                        |
|                                                                             |
|  OUTPUTS:                                                                   |
|     None                                                                    |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date       Programmer   Description                                       |
|  ========   ============  ================================================= |
|  July  00   A.Muslimov    Unmasked hdf5 data types.                         |
|                                                                             |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
hid_t 
HE5_SWopen(const char *filename, uintn flags)
{
  hid_t     fid      = FAIL;/* hdf5 type file ID      */ 

  char      *errbuf  = NULL;/* Error message buffer   */


  /* Allocate memory for error buffer */
  /* -------------------------------- */
  errbuf  = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWopen", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory to error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);

      return(FAIL);
    }  

  /* Call HE5_EHopen to open file */
  /* ---------------------------- */
  fid = HE5_EHopen(filename,flags, H5P_DEFAULT );
  if(fid == FAIL)
    {
      sprintf(errbuf, "Cannot open the file \"%s\". Check the file name. \n", filename);
      H5Epush(__FILE__, "HE5_SWopen", __LINE__, H5E_FILE, H5E_CANTOPENFILE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }  
  
  free(errbuf);

  return (fid);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWcreate                                                     |
|                                                                             |
|  DESCRIPTION: Creates a new swath structure and returns swath ID            |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|   swathID       hid_t        None        Swath ID                           |
|                                                                             |
|  INPUTS:                                                                    |
|   fid           hid_t        None        HDF-EOS file ID                    |
|   swathname     const char*  None        Swath name string                  |
|                                                                             |
|  OUTPUTS:                                                                   |
|   None                                                                      |
|                                                                             |
|  NOTES:                                                                     |
|                              ___________                                    |
|                              |  Swath  |                                    |
|                              -----------                                    |
|                             /     |     \                                   |
|                           Data  Profile Geolocation                         |
|                          Fields  Fields    Fields                           |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  7/20/99  A. Muslimov   Replaced parameter gid by fid in the call to        |
|                         EHinsertmeta().                                     |
|  8/20/99  A. Muslimov   Fixed a bug associated with a swath numbering:      |
|                         within the 'if(nswathopen < NSWATH ){}' block       |
|                         initialized NSWATH to NSWATHopen. Checked for the   |
|                         statuses returned by H5Gclose() calls.              |
|  8/31/99  A. Muslimov   Disabled assignment NSWATH = NSWATHopen. Replaced   |
|                         the call to EHattrcat() by EHdatasetcat(). Added    |
|                         error hadling after the calls to EHinsertmeta() and |
|                         EHdatasetcat().                                     |
|  02/08/00 A. Muslimov   Added more error checkings.                         |
|  04/05/00 A. Muslimov   Removed "Ragged Arrays" group.                      |
|  July  00 A. Muslimov   Unmasked hdf5 data types.                           |
|  Sep   00 A. Muslimov   Added "PRofile Fields" group.                       |
|  Dec   00 A. Muslimov   Added "ProfileField" section to the metadata.       |
|  Sep   01 A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|  Feb   03 S. Zhao       Removed the creation of the "Profile Fields" group  |
|                         to HE5_PRdefine().                                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
hid_t 
HE5_SWcreate(hid_t fid, const char *swathname)
{
  hid_t           swathID        = FAIL;/* return value of Swath ID        */
  hid_t           HDFfid         = FAIL;/* HDF-EOS file ID                 */
  hid_t           gid            = FAIL;/* "HDFEOS" group ID               */
  hid_t           sw_id          = FAIL;/* HDF-EOS swath ID                */
  hid_t           geo_id         = FAIL;/* "Geolocation Fields" group ID   */
  hid_t           data_id        = FAIL;/* "Data Fields" group ID          */
  hid_t           prof_id        = FAIL;/* "Profile Fields" group ID       */
  hid_t           SWATHS_ID      = FAIL;/* "SWATHS" group ID               */
  hid_t           i;                    /* Loop index                      */

  int             nswathopen     = 0;   /* # of swath structures open      */

  herr_t          status         = FAIL;/* routine return status variable  */
  
  uintn           access         = 0;   /* Read/Write file access code     */
  
  long            nSwath         = FAIL;/* Swath counter                   */
  
  char            *errbuf =(char *)NULL;/* Buffer for error message        */
  char            *utlbuf =(char *)NULL;/* Utility buffer                  */
  char            *utlbuf2=(char *)NULL;/* Utility buffer 2                */
  
  HE5_LOCK;
  CHECKNAME(swathname);

  /* Allocate memory for error buffer */
  /* -------------------------------- */
  errbuf = (char *)calloc( HE5_HDFE_DIMBUFSIZE, sizeof(char ) ) ;
  if ( errbuf == NULL )
    {
      H5Epush(__FILE__, "HE5_SWcreate", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
  

  /*
   * Check HDF-EOS file ID, get  HDFEOS group ID  and
   * access code
   */
  status = HE5_EHchkfid(fid, "HE5_SWcreate", &HDFfid,  &gid, &access);
  /* Check file access */
  /* ------------------*/
  if ( access == 0 )
    {
      status = FAIL;
      sprintf(errbuf, "Cannot call HE5_SWcreate on a file opened read-only.\n");
      H5Epush(__FILE__, "HE5_SWcreate", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for file ID failed.\n");
      H5Epush(__FILE__, "HE5_SWcreate", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
	
      return(FAIL);
    }
  
  /* Check swathname for length */
  /* -------------------------- */
  if ( strlen(swathname) > HE5_OBJNAMELENMAX)
    {
      sprintf(errbuf, "Swath name \"%s\" must be less than %d characters.\n", swathname, HE5_OBJNAMELENMAX);
      H5Epush(__FILE__, "HE5_SWcreate", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
	
      return(FAIL);
    }
  
  
  /* Determine number of swaths currently opened */
  /* ------------------------------------------- */
  for (i = 0; i < HE5_NSWATH; i++)
    nswathopen += HE5_SWXSwath[i].active;
  
  if(nswathopen <  HE5_NSWATH)
    {

      /* Probe , check if "SWATHS" group exists */
      /* -------------------------------------- */
      H5E_BEGIN_TRY {
	SWATHS_ID = H5Gopen(gid, "SWATHS");
      }
      H5E_END_TRY;

      if(SWATHS_ID == FAIL )
	{
	  nSwath = 0;

	  /* Create the "SWATHS" group */
	  /* ------------------------- */
	  SWATHS_ID = H5Gcreate(gid,"SWATHS",0);
	  if(SWATHS_ID == FAIL)
	    {
	      sprintf(errbuf,"Cannot create the \"SWATHS\" group.\n");
	      H5Epush(__FILE__, "HE5_SWcreate", __LINE__, H5E_OHDR, H5E_CANTCREATE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(errbuf);
			    
	      return(FAIL);
	    }
		
	}
      else
	{
	  /* Probe , check if swathname group exist */
	  /* -------------------------------------- */
	  H5E_BEGIN_TRY{
	    sw_id = H5Gopen(SWATHS_ID, swathname);
	  }
	  H5E_END_TRY;

	  if( sw_id == FAIL ) 
	    {
	      /* Get the number of swaths in "SWATHS" group */
	      /* ------------------------------------------ */
	      nSwath = HE5_EHdatasetcat(fid, "/HDFEOS/SWATHS", NULL, NULL);
	      if (nSwath == FAIL)
		{
		  sprintf(errbuf,"Cannot retrieve the number of swaths.\n");
		  H5Epush(__FILE__, "HE5_SWcreate", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  status = H5Gclose(SWATHS_ID);
		  free(errbuf);
			    
		  return(FAIL);
		}

	    }
	  else
	    {
	      sprintf(errbuf, "Swath \"%s\" already exists.\n", swathname);
	      H5Epush(__FILE__, "HE5_SWcreate", __LINE__, H5E_OHDR, H5E_EXISTS, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      status = H5Gclose(SWATHS_ID);
	      free(errbuf);
			
	      return(FAIL);
	    }

	}


      /* Swath does not exist */
      /* -------------------- */
	 

      /* Create swathname group */
      /* ---------------------- */
      sw_id = H5Gcreate( SWATHS_ID, swathname, 0);
      if(sw_id == FAIL)
	{
	  sprintf(errbuf,"Cannot create the \"%s\" group.\n", swathname);
	  H5Epush(__FILE__, "HE5_SWcreate", __LINE__, H5E_OHDR, H5E_CANTCREATE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  status = H5Gclose(SWATHS_ID);
	  free(errbuf);
	     
	  return(FAIL);
	}

      /* Create "/SWATH/swathname/Geolocation Fields" group */
      /* -------------------------------------------------- */
      geo_id = H5Gcreate( sw_id, "Geolocation Fields", 0);
      if(geo_id == FAIL)
	{
	  sprintf(errbuf,"Cannot create the \"Geolocation Fields\" group.\n");
	  H5Epush(__FILE__, "HE5_SWcreate", __LINE__, H5E_OHDR, H5E_CANTCREATE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  status = H5Gclose(SWATHS_ID);
	  free(errbuf);
	     
	  return(FAIL);
	}

      /* Create /SWATH/swathname/Data Fields group */
      /* ----------------------------------------- */
      data_id = H5Gcreate( sw_id, "Data Fields", 0);
      if(data_id == FAIL)
	{
	  sprintf(errbuf,"Cannot create the \"Data Fields\" group.\n");
	  H5Epush(__FILE__, "HE5_SWcreate", __LINE__, H5E_OHDR, H5E_CANTCREATE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  status = H5Gclose(SWATHS_ID);
	  free(errbuf);
	     
	  return(FAIL);
	}

      /* Create /SWATH/swathname/Profile Fields group */
      /* -------------------------------------------- */
      /*
	prof_id = H5Gcreate( sw_id, "Profile Fields", 0);
	if(prof_id == FAIL)
	{
	sprintf(errbuf,"Cannot create the \"Profile Fields\" group.\n");
	H5Epush(__FILE__, "HE5_SWcreate", __LINE__, H5E_OHDR, H5E_CANTCREATE, errbuf);
	HE5_EHprint(errbuf, __FILE__, __LINE__);
	status = H5Gclose(SWATHS_ID);
	free(errbuf);
	     
	return(FAIL);
	}
      */


      /* Allocate memory for utility buffers */
      /* ----------------------------------- */
      utlbuf  = (char *)calloc(HE5_HDFE_UTLBUFSIZE, sizeof(char ) ) ;
      if ( utlbuf == NULL )
	{
	  H5Epush(__FILE__, "HE5_SWcreate", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for utility buffer.\n");
	  HE5_EHprint("Error: Cannot allocate memory for utility buffer, occured", __FILE__, __LINE__);
	  status = H5Gclose(SWATHS_ID);
	  free(errbuf);
	     
	  return(FAIL);
	}
      utlbuf2 = (char *)calloc(HE5_HDFE_UTLBUFSIZE,  sizeof(char ) ) ;	 
      if ( utlbuf2 == NULL )
	{
	  H5Epush(__FILE__, "HE5_SWcreate", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for utility buffer2.\n");
	  HE5_EHprint("Error: Cannot allocate memory for utility buffer2, occured", __FILE__, __LINE__);
	  status = H5Gclose(SWATHS_ID);
	  free(errbuf);
	  free(utlbuf);
	     
	  return(FAIL);
	}


      /* Establish Swath in "Structural MetaData" Block */
      /* ---------------------------------------------- */
      sprintf(utlbuf, "%s%li%s%s%s", "\tGROUP=SWATH_", nSwath + 1, "\n\t\tSwathName=\"", swathname, "\"\n");
      strcat(utlbuf, "\t\tGROUP=Dimension\n");
      strcat(utlbuf, "\t\tEND_GROUP=Dimension\n");
      strcat(utlbuf, "\t\tGROUP=DimensionMap\n");
      strcat(utlbuf, "\t\tEND_GROUP=DimensionMap\n");
      strcat(utlbuf, "\t\tGROUP=IndexDimensionMap\n");
      strcat(utlbuf, "\t\tEND_GROUP=IndexDimensionMap\n");
      strcat(utlbuf, "\t\tGROUP=GeoField\n");
      strcat(utlbuf, "\t\tEND_GROUP=GeoField\n");
      strcat(utlbuf, "\t\tGROUP=DataField\n");
      strcat(utlbuf, "\t\tEND_GROUP=DataField\n");
      strcat(utlbuf, "\t\tGROUP=ProfileField\n");
      strcat(utlbuf, "\t\tEND_GROUP=ProfileField\n");
      strcat(utlbuf, "\t\tGROUP=MergedFields\n");
      strcat(utlbuf, "\t\tEND_GROUP=MergedFields\n");
      sprintf(utlbuf2, "%s%li%s","\tEND_GROUP=SWATH_", nSwath + 1, "\n");
      strcat(utlbuf, utlbuf2);
	 
      /* Insert metadata buffer to the "StructMetadata" */
      /* ---------------------------------------------- */
      status = HE5_EHinsertmeta(fid, (char*)swathname, "s", 1001L, utlbuf, NULL);
      if (status == FAIL )
	{
	  sprintf(errbuf,"Cannot insert metadata buffer to \"StructMetadata\".\n");
	  H5Epush(__FILE__, "HE5_SWcreate", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  status = H5Gclose(SWATHS_ID);
	  free(errbuf);
	  free(utlbuf);
	  free(utlbuf2);
	    
	  return(FAIL);
	}

      /* Release "SWATHS" group ID */
      /* ------------------------- */

      status = H5Gclose(SWATHS_ID);
      if(status == FAIL )
	{
	  sprintf(errbuf,"Cannot release the \"SWATHS\" group ID.\n");
	  H5Epush(__FILE__, "HE5_SWcreate", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  status = H5Gclose(SWATHS_ID);
	  free(utlbuf);
	  free(utlbuf2);
	  free(errbuf);
	     
	  return(FAIL);
	}	 


      /* Assign swathID & Load swath and SWXSwath table entries */
      /* ------------------------------------------------------ */
      for (i = 0; i < HE5_NSWATH; i++)
	{
	  if (HE5_SWXSwath[i].active == 0)
	    {
	      /*
	       * Set sw_id, Set swath entry active, Store root group
	       * ID, Store sub group IDs, Store HDF-EOS file ID
	       */
	      HE5_SWXSwath[i].active                     = 1;
	      HE5_SWXSwath[i].sw_id                      = sw_id;
	      HE5_SWXSwath[i].data_id                    = data_id;
	      HE5_SWXSwath[i].prof_id                    = prof_id;
	      HE5_SWXSwath[i].geo_id                     = geo_id;
	      HE5_SWXSwath[i].fid                        = fid;
	      HE5_SWXSwath[i].obj_id                     = SWATHS_ID;
	      HE5_SWXSwath[i].plist                      = FAIL;
	      strcpy(HE5_SWXSwath[i].swname, swathname);
	      HE5_SWXSwath[i].compcode                   = HE5_HDFE_COMP_NONE;
	      swathID                                    = i + HE5_SWIDOFFSET;
	      break;
	    }
	}
    }
  else
    {
      /* Too many files opened */
      /* --------------------- */
      swathID = FAIL;
      sprintf(errbuf,"\n Illegal attempt to open more than %d swaths simultaneously.\n", HE5_NSWATH);
      H5Epush(__FILE__, "HE5_SWcreate", __LINE__, H5E_OHDR, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
  
  
  /* Release allocated memory */
  /* ------------------------ */
  free(errbuf);
  free(utlbuf);
  free(utlbuf2);

 COMPLETION: 
  
  HE5_UNLOCK;
  return (swathID);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWattach                                                     |
|                                                                             |
|  DESCRIPTION:  Attaches to an existing swath within the file.               |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  swathID        hid_t               swath structure ID                      |
|                                                                             |
|  INPUTS:                                                                    |
|  fid            hid_t               HDF-EOS file ID                         |
|  swathname      char                swath structure name                    |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|             (02/23/00 A.M.) The iteration over the "Data Fields" group has  |
|             the followings side effect:  it counts as an object (which is   |
|             supposed to be a dataset) the group "Ragged Arrays". So the     |
|             external structure "ddataset" gets filled with  a fake member   |
|             and nDFLD gets incremented by one. This shouldn't affect the    |
|             other interfacing routines unless someone tries to  access the  |
|             datasets in "Data Fields" group directly through their IDs      |
|             retrieved from external "ddataset" structure, or use "nDFLD"    |
|             data member of to retrieve the actual number of data sets       |
|             (fields).  To avoid potential problems, the dataset counter is  |
|             decremented by one and the corresponding error checking are     |
|             inserted to handle this case.                                   |
|                                                                             |
|                                                                             |
|                                                                             |
|   Date        Programmer    Description                                     |
|  =========   ============  ==============================================   |
|  Aug 6,99    A. Muslimov   In the first block if( inout.name != NULL){}     |
|                            changed the statement next to the last one from  |
|                            "if(inout.name==NULL) free(inout.name);" onto    |
|                            "if(inout.name!=NULL) free(inout.name);".Changed |
|                            the type of datid from int32_t to hid_t.         |
| 10/18/99     A.Muslimov    Replaced memcpy() by memmove() to avoid a problem|
|                            when arguments 1 and 2 overlap in memory.        |
| 10/28/99     A.Muslimov    Added ragged array stuff.                        |
| 02/08/00     A.Muslimov    Added more error checkings.                      |
| 04/05/00     A.Muslimov    Removed "Ragged Arrays" group.                   |
| July  00     A.Muslimov    Unmasked hdf5 data types.                        |
| Sep   00     A.Muslimov    Added "PRofile Fields group" and stuff           |
| Sep   01     A. Muslimov   Added mutex "lock"/"unlock" calls.               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
hid_t 
HE5_SWattach(hid_t fid, const char *swathname)
{

  hid_t           swathID    = FAIL;/* Swath ID (return value)       */ 
  hid_t           i;			    /* Loop index                    */
  hid_t           emptyslot  =  0;  /* Spare swath index             */

  herr_t          status     = FAIL;/* Return status variable        */

  int             nswathopen =  0;  /* # of swath structures open    */
  int             idx        = FAIL;/* return value from an operator */

  uintn           acs        = 0;   /* Read/Write file access code   */

  hid_t           HDFfid     = FAIL;/* HDF-EOS file ID               */
  hid_t           datid      = FAIL;/* Dataset ID                    */
  hid_t           profid     = FAIL;/* Profile dataset ID            */
  hid_t           gid        = FAIL;/* "HDFEOS" group ID             */
  hid_t           geo_id     = FAIL;/* "Geolocation Fields" Group ID */
  hid_t           data_id    = FAIL;/* "Data Fields" Group ID        */
  hid_t           prof_id    = FAIL;/* "PRofile Fields" Group ID     */
  hid_t           sw_id      = FAIL;/* Swath ID                      */
  
    
  HE5_OBJINFO     inout;		 /* IN/OUT operator data             */

  char            *grpname =NULL;/* Ptr to a group  name string      */
  char            *tmpname1=NULL;/* ..... temporary name 1  ...      */
  char            *tmpname2=NULL;/* ..... temporary name 2  ...      */
  char            *tmpname3=NULL;/* ..... temporary name 3  ...      */
  char            *namebuf =NULL;/* ..... temporary name    ...      */
  char            *fldname =NULL;/* ..... temporary field name ...   */
  char            *comma   =NULL;
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer*/


  HE5_LOCK;
  CHECKPOINTER(swathname);

  /* Check HDF-EOS file ID, get back HDF file ID and access code */
  /* ----------------------------------------------------------- */
  status = HE5_EHchkfid(fid, "HE5_SWattach", &HDFfid, &gid, &acs);
  if ( status == FAIL )
    {
      H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_ARGS, H5E_BADRANGE, "Checking for file ID failed.\n");
      HE5_EHprint("Error: Checking for file ID failed, occured", __FILE__, __LINE__);
      return(FAIL);
    }

  /* Determine number of swaths currently opened */
  /* ------------------------------------------- */
  for (i = 0; i < HE5_NSWATH; i++)
    nswathopen += HE5_SWXSwath[i].active;

  /* Is there a room for more ? */
  /* -------------------------- */
  if (nswathopen < HE5_NSWATH)
    {
      /* Search for group "/SWATHS/swathname" */
      /* ==================================== */ 
      grpname = (char *) calloc( (strlen(swathname)+40), sizeof(char) );
      if (grpname == NULL)
	{
	  sprintf(errbuf, "Cannot allocate memory for grpname.\n") ;
	  H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);

	  return(FAIL);
	}
	      
      strcpy( grpname, "/HDFEOS/SWATHS/");
      strcat( grpname, swathname);

      /*
       * If group with swathname found, open the group, load tables
       */
      H5E_BEGIN_TRY{
	sw_id = H5Gopen(HDFfid, grpname);
      }
      H5E_END_TRY;

      if( sw_id == FAIL )
	{
	  sprintf(errbuf, "Swath \"%s\" does not exist within HDF-EOS file.\n",swathname) ;
	  H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);

	  return(FAIL);
	}

      /* Attach to "Geolocation Fields" */
      /* =============================  */
      geo_id  = H5Gopen( sw_id, "Geolocation Fields");
      if (geo_id == FAIL)
	{
	  sprintf(errbuf, "Cannot open the \"Geolocation Fields\" group.\n") ;
	  H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);

	  return(FAIL);
	}
	      
      /* Attach to "Data Fields" */
      /* ======================= */
      data_id = H5Gopen( sw_id, "Data Fields");
      if (data_id == FAIL)
	{
	  sprintf(errbuf, "Cannot open the \"Data Fields\" group. \n") ;
	  H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);

	  return(FAIL);
	}


      /* Attach to "Profile Fields" */
      /* ========================== */
      H5Eset_auto(NULL, NULL);
      prof_id = H5Gopen( sw_id, "Profile Fields");
      /*
	if (prof_id == FAIL)
	{
	sprintf(errbuf, "Cannot open the \"Profile Fields\" group. \n") ;
	H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	HE5_EHprint(errbuf, __FILE__, __LINE__);
	free(grpname);

	return(FAIL);
	}
      */


      /* Setup External Arrays */
      /* --------------------- */
      for (i = 0; i < HE5_NSWATH; i++)
	{
	  /* Find empty entry in array */
	  /* ------------------------- */
	  if (HE5_SWXSwath[i].active == 0)
	    {
	      /* Set IDs, codes., etc */
	      /* ==================== */ 
	      HE5_SWXSwath[i].active           = 1;
	      HE5_SWXSwath[i].data_id          = data_id;
	      HE5_SWXSwath[i].prof_id          = prof_id;
	      HE5_SWXSwath[i].geo_id           = geo_id;
	      HE5_SWXSwath[i].fid              = fid;
	      HE5_SWXSwath[i].sw_id            = sw_id;
	      HE5_SWXSwath[i].plist            = FAIL;
	      HE5_SWXSwath[i].compcode         = HE5_HDFE_COMP_NONE;

	      swathID                          = i + HE5_SWIDOFFSET;
	      strcpy(HE5_SWXSwath[i].swname, swathname);
	      break;
	    }
	}
      emptyslot = i;

      /*  Access swath "Data Fields" datasets   */
      /* -------------------------------------- */
      tmpname1 = (char *) calloc( (strlen(grpname)+ 20), sizeof(char));
      if (tmpname1 == NULL)
	{
	  sprintf(errbuf, "Cannot allocate memory for tmpname1. \n") ;
	  H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);

	  return(FAIL);
	}

      strcpy(tmpname1,grpname);
      strcat(tmpname1,"/Data Fields");


      /* Get the number of OBJECTS in "Data Fields" group */
      /* ================================================ */ 
      inout.count   = 0;
      inout.name    = NULL;
      inout.strsize = 0;

      idx = H5Giterate(data_id, tmpname1 , NULL, HE5_EHobj_info, &inout);
      if ( idx == FAIL )
	{
	  sprintf(errbuf, "Iteration of \"HE5_EHobj_info()\" operation failed. \n") ;
	  H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  free(tmpname1);

	  return(FAIL);
	}

      free(tmpname1);
 
      /* Set the data members of external structure */
      /* ========================================== */  
      HE5_SWXSwath[emptyslot].nDFLD = inout.count;

      /*------------------------------------------------------*/ 
      /* Loop through all data field datasets and open it     */
      /* Allocate space for namebuf, copy inout.name into it, */
      /*              and append comma                        */
      /*------------------------------------------------------*/
      if( inout.name != NULL && inout.count > 0 )
	{
	  /* Allocate memory to ddataset struct */
	  /* ---------------------------------- */
	  HE5_SWXSwath[emptyslot].ddataset = (HE5_DTSinfo *)realloc((void *)HE5_SWXSwath[emptyslot].ddataset,(HE5_SWXSwath[emptyslot].nDFLD) * sizeof(HE5_DTSinfo));

	  /* Allocate memory to the list of dataset names */
	  /* -------------------------------------------- */
	  namebuf = (char *) calloc(strlen(inout.name) + 2, sizeof(char));
	  if (namebuf == NULL)
	    {
	      sprintf(errbuf, "Cannot allocate memory for namebuf. \n") ;
	      H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(grpname);
		       
	      return(FAIL);
	    }

	  strcpy(namebuf, inout.name);
	  strcat(namebuf, ",");

	  /* Find comma */
	  /* ---------- */
	  comma = strchr(namebuf, ',');

	  i = 0;

	  /* Parse the list of dataset names */
	  /* ------------------------------- */
	  while (comma != NULL)
	    {
	      /* Allocate memory for fldname buffer */
	      /* ---------------------------------- */
	      fldname = (char *) calloc(comma - namebuf + 1, sizeof(char));
	      if (fldname == NULL)
		{
		  sprintf(errbuf, "Cannot allocate memory for fldname. \n") ;
		  H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  free(grpname);
		  free(namebuf);
				  
		  return(FAIL);
		}

	      /* Copy field list entry to fldname */
	      /* -------------------------------- */
	      memmove(fldname, namebuf, comma - namebuf);
	      fldname[comma-namebuf]=0;
  
	      /* open dataset fldname */
	      /* -------------------- */
	      H5E_BEGIN_TRY{
		datid = H5Dopen(data_id, fldname);
	      }H5E_END_TRY;
	      if ( datid == FAIL )
		{
		  sprintf(errbuf, "Cannot open the dataset \"%s\". \n",fldname );
		  H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  free(grpname);
		  free(namebuf);
		  free(fldname);
		       
		  return(FAIL);
		}

	      /* allocate memory to the dataset name */
	      /* ----------------------------------- */
	      HE5_SWXSwath[emptyslot].ddataset[i].name = (char *)calloc((strlen(fldname)+1), sizeof(char) );
	      if (HE5_SWXSwath[emptyslot].ddataset[i].name == NULL)
		{
		  sprintf(errbuf, "Cannot allocate memory for the dataset name. \n") ;
		  H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  free(grpname);
		  free(namebuf);
		  free(fldname);
		       
		  return(FAIL);
		}

	      /* Set the data members of external structure */
	      /* ========================================== */  
	      HE5_SWXSwath[emptyslot].ddataset[i].ID = datid;
	      strcpy(HE5_SWXSwath[emptyslot].ddataset[i].name, fldname);


	      /* Go to next field entry, find next comma, ... */
	      /* ============================================ */ 
	      memmove(namebuf, comma + 1, strlen(comma + 1) + 1); 
	      comma = strchr(namebuf, ',');
	      if (fldname != NULL) free(fldname);
	      i++;

	    }

	  if (namebuf != NULL) free(namebuf);
	  if(inout.name != NULL ) free( inout.name);

	} /* end if(inout.name!=NULL) */



	  /*  Access swath "Geolocation Fields" datasets  */
	  /*  ------------------------------------------- */
      tmpname2 = (char *)calloc( (strlen(grpname)+60), sizeof(char) );
      if (tmpname2 == NULL)
	{
	  sprintf(errbuf, "Cannot allocate memory for tmpname2. \n") ;
	  H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
		       
	  return(FAIL);
	}

      strcpy(tmpname2,grpname);
      strcat(tmpname2,"/Geolocation Fields");

      /* Get the number of OBJECTS in "Geolocation Fileds" group */
      /* ======================================================= */ 
      inout.count   = 0;
      inout.name    = NULL;
      inout.strsize = 0;

      idx = H5Giterate(geo_id, tmpname2 , NULL, HE5_EHobj_info, &inout);
      if ( idx == FAIL )
	{
	  sprintf(errbuf, "Iteration of \"HE5_EHobj_info()\" operation failed. \n") ;
	  H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  free(tmpname2);

	  return(FAIL);
	}

      /* Set the data members of external structure */
      /* ========================================== */  
      HE5_SWXSwath[emptyslot].nGFLD = inout.count;

      if (tmpname2 != NULL) free(tmpname2);

      /*-----------------------------------------------------*/
      /* Loop through all data fileds dataset and open it    */
      /* Allocate space for namebuf, copy inout.name into it */
      /*    and  append comma                                */
      /*-----------------------------------------------------*/
      if( inout.name != NULL && inout.count > 0)
	{
	  /* allocate memory to gdataset struct */
	  /* ---------------------------------- */
	  HE5_SWXSwath[emptyslot].gdataset = (HE5_DTSinfo *)realloc((void *)HE5_SWXSwath[emptyslot].gdataset, (HE5_SWXSwath[emptyslot].nGFLD) * sizeof(HE5_DTSinfo));


	  /* Allocate memory to the list of dataset names */
	  /* -------------------------------------------- */
	  namebuf = (char *) calloc(strlen(inout.name) + 2, sizeof(char));
	  if (namebuf == NULL)
	    {
	      sprintf(errbuf, "Cannot allocate memory for namebuf. \n") ;
	      H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(grpname);
		       
	      return(FAIL);
	    }

	  strcpy(namebuf, inout.name);
	  strcat(namebuf, ",");

	  /* Find comma */
	  /* ---------- */
	  comma = strchr(namebuf, ',');

	  i = 0;

	  /* Parse the list of dataset names */
	  /* ------------------------------- */
	  while (comma != NULL)
	    {
	      /* Copy field list entry to fldname */
	      /* -------------------------------- */
	      fldname = (char *) calloc(comma - namebuf + 1, sizeof(char));
	      if (fldname == NULL)
		{
		  sprintf(errbuf, "Cannot allocate memory for fldname. \n") ;
		  H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  free(grpname);
		  free(namebuf);
		       
		  return(FAIL);
		}

	      memmove(fldname, namebuf, comma - namebuf);
	      fldname[comma-namebuf]='\0';

	      /* open dataset fldname */
	      /* -------------------- */
	      datid = H5Dopen(geo_id,fldname);
	      if ( datid == FAIL )
		{
		  sprintf(errbuf, "Cannot open the dataset \"%s\". \n",fldname );
		  H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  free(grpname);
		  free(namebuf);
		  free(fldname);
		       
		  return(FAIL);
		}

	      /* Allocate memory to the dataset name */
	      /* ----------------------------------- */
	      HE5_SWXSwath[emptyslot].gdataset[i].name = (char *)calloc( (strlen(fldname)+1), sizeof(char) );
	      if (HE5_SWXSwath[emptyslot].gdataset[i].name == NULL)
		{
		  sprintf(errbuf, "Cannot allocate memory for name. \n") ;
		  H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  free(grpname);
		  free(namebuf);
		  free(fldname);
		       
		  return(FAIL);
		}

	      /* Set the data members of external structure */
	      /* ========================================== */  
	      HE5_SWXSwath[emptyslot].gdataset[i].ID = datid;
	      strcpy(HE5_SWXSwath[emptyslot].gdataset[i].name, fldname);


	      /*  Go to next field entry, ...   */
	      /* =============================  */ 
	      memmove(namebuf, comma + 1, strlen(comma + 1) + 1); 
	      comma = strchr(namebuf, ',');
	      if (fldname != NULL) free(fldname);
	      i++;
	    }

	  if (namebuf != NULL) free(namebuf);
	  if(inout.name != NULL) free(inout.name);
	  inout.name = NULL;

	} /* end if(inout.name!==NULL) */


	  /*  Access swath "Profile Fields" datasets   */
	  /* ----------------------------------------- */
      if (prof_id != FAIL)
	{

	  tmpname3 = (char *) calloc( (strlen(grpname)+ 20), sizeof(char));
	  if (tmpname3 == NULL)
	    {
	      sprintf(errbuf, "Cannot allocate memory for tmpname3. \n") ;
	      H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(grpname);

	      return(FAIL);
	    }

	  strcpy(tmpname3,grpname);
	  strcat(tmpname3,"/Profile Fields");


	  /* Get the number of OBJECTS in "PRofile Fields" group */
	  /* =================================================== */ 
	  inout.count   = 0;
	  inout.name    = NULL;
	  inout.strsize = 0;

	  idx = H5Giterate(HE5_SWXSwath[emptyslot].prof_id, tmpname3 , NULL, HE5_EHobj_info, &inout);
	  if ( idx == FAIL )
	    {
	      sprintf(errbuf, "Iteration of \"HE5_EHobj_info()\" operation failed. \n") ;
	      H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(grpname);
	      free(tmpname3);

	      return(FAIL);
	    }

	  free(tmpname3);
 
	  /* Set the data members of external structure */
	  /* ========================================== */  
	  HE5_SWXSwath[emptyslot].nPROF = inout.count;

	  /*-----------------------------------------------------------*/ 
	  /* Loop through all "Profile Field" datasets and open it     */
	  /* Allocate space for namebuf, copy inout.name into it,      */
	  /*              and append comma                             */
	  /*-----------------------------------------------------------*/
	  if( inout.name != NULL && inout.count > 0 )
	    {
	      /* Allocate memory to ddataset struct */
	      /* ---------------------------------- */
	      HE5_SWXSwath[emptyslot].pdataset = (HE5_DTSinfo *)realloc((void *)HE5_SWXSwath[emptyslot].pdataset,(HE5_SWXSwath[emptyslot].nPROF) * sizeof(HE5_DTSinfo));
	      /* Allocate memory to the list of dataset names */
	      /* -------------------------------------------- */
	      namebuf = (char *) calloc(strlen(inout.name) + 2, sizeof(char));
	      if (namebuf == NULL)
		{
		  sprintf(errbuf, "Cannot allocate memory for namebuf. \n") ;
		  H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  free(grpname);
		       
		  return(FAIL);
		}

	      strcpy(namebuf, inout.name);
	      strcat(namebuf, ",");
		  
	      /* Find comma */
	      /* ---------- */
	      comma = strchr(namebuf, ',');

	      i = 0;

	      /* Parse the list of dataset names */
	      /* ------------------------------- */
	      while (comma != NULL)
		{
		  /* Allocate memory for fldname buffer */
		  /* ---------------------------------- */
		  fldname = (char *) calloc(comma - namebuf + 1, sizeof(char));
		  if (fldname == NULL)
		    {
		      sprintf(errbuf, "Cannot allocate memory for fldname buffer. \n") ;
		      H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      free(grpname);
		      free(namebuf);
		       
		      return(FAIL);
		    }
		  /* Copy field list entry to fldname */
		  /* -------------------------------- */
		  memmove(fldname, namebuf, comma - namebuf);
		  fldname[comma-namebuf]=0;
  
		  /* open dataset fldname */
		  /* -------------------- */
		  H5E_BEGIN_TRY{
		    profid = H5Dopen(prof_id, fldname);
		  }H5E_END_TRY;
		  if ( profid == FAIL )
		    {
		      sprintf(errbuf, "Cannot open the profile dataset \"%s\". \n",fldname );
		      H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      free(grpname);
		      free(namebuf);
		      free(fldname);
		       
		      return(FAIL);
		    }

		  /* allocate memory to the dataset name */
		  /* ----------------------------------- */
		  HE5_SWXSwath[emptyslot].pdataset[i].name = (char *)calloc((strlen(fldname)+1), sizeof(char) );
		  if (HE5_SWXSwath[emptyslot].pdataset[i].name == NULL)
		    {
		      sprintf(errbuf, "Cannot allocate memory for profile name. \n") ;
		      H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      free(grpname);
		      free(namebuf);
		      free(fldname);
				  
		      return(FAIL);
		    }

		  /* Set the data members of external structure */
		  /* ========================================== */  
		  HE5_SWXSwath[emptyslot].pdataset[i].ID = profid;
		  strcpy(HE5_SWXSwath[emptyslot].pdataset[i].name, fldname);

		  /* Go to next field entry, find next comma, ... */
		  /* ============================================ */ 
		  memmove(namebuf, comma + 1, strlen(comma + 1) + 1); 
		  comma = strchr(namebuf, ',');
		  if (fldname != NULL) free(fldname);
		  i++;
		}
		  
	      if (namebuf != NULL) free(namebuf);
	      if(inout.name != NULL ) free( inout.name);
		  
	    } /* end if(inout.name!=NULL) */
	}
	  
      if (grpname != NULL) free(grpname);
	  
    }
  else
    {
      /* Too many swaths opened */
      /* ---------------------- */
      swathID = FAIL;
      sprintf(errbuf,"\n Illegal attempt to open more than %d swaths simultaneously. \n", HE5_NSWATH);
      H5Epush(__FILE__, "HE5_SWattach", __LINE__, H5E_OHDR, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

 COMPLETION:
  HE5_UNLOCK;
  return(swathID);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWchkswid                                                    |
|                                                                             |
|  DESCRIPTION: Checks for valid swathID and returns file ID and              |
|               "HDFEOS" group ID                                             |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|                                                                             |
|  OUTPUTS:                                                                   |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  8/23/99  A. Muslimov   Checked for the status returned by EHchkfid().      |
|                         Initialized status to -1.                           |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
static herr_t
HE5_SWchkswid(hid_t swathID, const char *routname, hid_t *fid, hid_t *gid, long *idx )
{
  herr_t            status    = FAIL;/* routine return status variable */

  uintn             access    =  0;	 /* Read/Write access code         */

  hid_t             HDFfid    = FAIL;/* HDF-EOS file ID                */
  hid_t             idOffset  = HE5_SWIDOFFSET;

  char              message1[] = "Invalid swath id: %d in routine \"%s\".  ID must be >= %d and < %d.\n";
  char              message2[] = "Swath id %d in routine \"%s\" not active.\n";
  char              errbuf[HE5_HDFE_ERRBUFSIZE]; /* Error message buffer */


  /* Check for valid swath ID */
  /* ------------------------ */
  if (swathID < idOffset || swathID >= HE5_NSWATH + idOffset)
    {
      status = FAIL;
      sprintf(errbuf, message1, swathID, routname, idOffset, HE5_NSWATH + idOffset);
      H5Epush(__FILE__, "HE5_SWchkswid", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
  else
    {
      /* Check for active swath ID */
      /* ------------------------- */
      if (HE5_SWXSwath[swathID % idOffset].active == 0)
        {
	  status = FAIL;
	  sprintf(errbuf,  message2, swathID, routname);
	  H5Epush(__FILE__, "HE5_SWchkswid", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
        }
      else
        {
	  *idx = HE5_EHhid2long(swathID % idOffset);
	  if (*idx == FAIL)
	    {
	      status = FAIL;
	      sprintf(errbuf,"Cannot set up the swath index.\n");
	      H5Epush(__FILE__, "HE5_SWchkswid", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
            
	  /* Get HDF file ID &  "HDFEOS" group ID */
	  /* ------------------------------------ */
	  *fid   = HE5_SWXSwath[*idx].fid;
	  status = HE5_EHchkfid(*fid,"", &HDFfid, gid, &access);
	  if (status == FAIL)
	    {
	      sprintf(errbuf,"Checking for file ID failed.\n");
	      H5Epush(__FILE__, "HE5_SWchkswid", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
        }
    }
  return (status);
}




/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefdim                                                     |
|                                                                             |
|  DESCRIPTION: Defines numerical value of dimension                          |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  dimname        char                Dimension name                          |
|  dim            hsize_t             Dimension size                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  7/16/99  A.Muslimov    In call to EHinsertmeta() replaced 'gid' by 'fid'.  |
|  01/06/00 A.Muslimov    Changed the datatype of "dim" parameter from int32_t|
|                         to hsize_t to handle an Unlimited dimension size.   |
|  02/08/00 A.Muslimov    Added error checking after the EHinsertmeta() call. |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t
HE5_SWdefdim(hid_t swathID,  char *dimname, hsize_t dim)
{
  herr_t       status    = FAIL;/* routine return status variable  */
  
  hid_t        fid       = FAIL;/* HDF-EOS file ID                 */
  hid_t        gid       = FAIL;/* "HDFEOS" group ID               */
  
  long         idx       = FAIL;/* Swath index                     */
  
  char         errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */
  
  HE5_LOCK;
  CHECKNAME(dimname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWdefdim", &fid, &gid, &idx); 
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for Swath ID failed.\n");
      H5Epush(__FILE__, "HE5_SWdefdim", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Make certain that dim != 0 */
  /* -------------------------- */
  if ( dim == 0 )
    {
      status = FAIL;
      sprintf(errbuf, "Invalid (zero) dimension size.\n");
      H5Epush(__FILE__, "HE5_SWdefdim", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Write dimension to the dataset "StructMetadata.0" */
  /* ------------------------------------------------- */
  status = HE5_EHinsertmeta(fid, HE5_SWXSwath[idx].swname,"s", 0L, dimname, &dim);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Cannot insert the value for \"%s\" dimension into Metadata.\n", dimname);
      H5Epush(__FILE__, "HE5_SWdefdim", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }


 COMPLETION:
  HE5_UNLOCK;
  return(status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWupdatedim                                                  |
|                                                                             |
|  DESCRIPTION: Updates numerical value of dimension                          |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  dimname        char*               Dimension name                          |
|  dim            hsize_t             Dimension size                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Oct 02    S. ZHAO      Original development                                |
|  Dec 02    H. LO        Update the dimension size                           |
|  Feb 03    H. LO        Update the dimension size                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
static herr_t
HE5_SWupdatedim(hid_t swathID,  char *dimname, hsize_t dim)
{
  herr_t       status    = FAIL;/* routine return status variable  */
 
  hid_t        fid       = FAIL;/* HDF-EOS file ID                 */
  hid_t        gid       = FAIL;/* "HDFEOS" group ID               */
 
  long         idx       = FAIL;/* Swath index                     */
 
  char         errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */

  hsize_t      predims;
 
 
  HE5_LOCK;
  CHECKNAME(dimname);
 

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWupdatedim", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for Swath ID failed.\n");
      H5Epush(__FILE__, "HE5_SWupdatedim", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }
 
  /* Make certain that dim != 0 */
  /* -------------------------- */
  if ( dim == 0 )
    {
      status = FAIL;
      sprintf(errbuf, "Invalid (zero) dimension size.\n");
      H5Epush(__FILE__, "HE5_SWupdatedim", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  predims = HE5_SWdiminfo(swathID, dimname);
  if (predims == 0)
    {
      status = FAIL;
      sprintf(errbuf, "Failed to retrieve the size of \"%s\" dimension. \n", dimname);
      H5Epush(__FILE__, "HE5_SWupdatedim", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }
 

  /* Write updated dimension back to the dataset "StructMetadata.0" */
  /* -------------------------------------------------------------- */
  if (dim > predims)
    {
      status = HE5_EHupdatemeta(fid, HE5_SWXSwath[idx].swname,"s", 0L, dimname, &dim);
      if ( status == FAIL )
	{
	  sprintf(errbuf, "Cannot update the value for \"%s\" dimension in Metadata.\n", dimname);
	  H5Epush(__FILE__, "HE5_SWupdatedim", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	}
    }
 
 COMPLETION:
  HE5_UNLOCK;
  return(status);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefdimscale                                                |
|                                                                             |
|  DESCRIPTION: Defines dimension scale for all fields that use the given     |
|               dimesion                                                      |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  dimname        char                dim name                                |
|  dimsize        hsize_t             Dimemsion size value                    |
|  numbertype_in  hid_t               dim scale data type such as DFNT_INT32, |
|                                     DFNT_FLOAT64, DFNT_FLOAT32, etc.        |
|  data           void                data buffer for write                   |
|                                                                             |
|                                                                             |
|  OUTPUTS:                                                                   |
|                                                                             |
|  NOTES: This function finds out which field in a swath has the dimension    |
|         and sets dimension scale for that field calling HE5_SWsetdimscale() |
|         User must detach swath after creating fields and attach again before|
|         calling the routine.                                                |
|                                                                             |
|                                                                             |
|   Date      Programmer    Description                                       |
|  ========   ============  ===============================================   |
|  Dec 2013   Abe Taaheri   Original Programmer                               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t
HE5_SWdefdimscale(hid_t swathID,  char *dimname,
		  const hsize_t dimsize, hid_t numbertype_in, void * data)
{
  herr_t       status    = FAIL;/* routine return status variable  */
  hid_t        fid       = FAIL;/* HDF-EOS file ID                 */
  hid_t        gid       = FAIL;/* "HDFEOS" group ID               */
  long         idx       = FAIL;/* Swath index                     */
  char         errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */
  char         *fieldlist = NULL;
  long         strbufsize;
  long         nflds   = FAIL;

  HE5_LOCK;
  CHECKNAME(dimname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWdefdimscale", &fid, &gid, &idx); 
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for Swath ID failed.\n");
      H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Make certain that dimsize != 0 */
  /* ------------------------------ */
  if ( dimsize == 0 )
    {
      status = FAIL;
      sprintf(errbuf, "Invalid (zero) dimension size.\n");
      H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Loop over all fields in the swath and find out if 
     field's dimension list  has the dimension name. 
     If true then set the dimension scale for the dim 
     in that field
  */

  /* Inquire Data Fields first*/
  /* ------------------------ */
  nflds = HE5_SWnentries(swathID, HE5_HDFE_NENTDFLD, &strbufsize);
  if (nflds == FAIL)
    {
      sprintf(errbuf, "Cannot get the number of fields in \"Data Fields\" group. \n");
      H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, 
	      H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  else
    {
      fieldlist = (char *) calloc(strbufsize + 1, sizeof(char));
      if(fieldlist == NULL)
	{
	  sprintf(errbuf,"Cannot allocate memory.\n");
	  H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, 
		  H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}

      nflds = HE5_SWinqdatafields(swathID, fieldlist, NULL, NULL);
      if (nflds == FAIL)
	{
	  sprintf(errbuf, "Cannot get the list of fields in \"Data Fields\" group. \n");
	  H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, 
		  H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(fieldlist);
	  return(FAIL);
	}

      if(nflds > 0)
	{
	  size_t        fldnmlen[HE5_FLDNUMBERMAX];      /* Array of namelengths */
	  char          *fldnm[HE5_FLDNUMBERMAX];        /* Array of names       */
	  char          tempdimlist[HE5_HDFE_DIMBUFSIZE];/* Dimension list       */
	  int           rank     = FAIL;                 /* Rank of dataset       */
	  hsize_t	tempdims[HE5_DTSETRANKMAX];      /* Dimension sizes array*/
	  hid_t         dtype[1] = {FAIL};               /* Data type            */
	  long          ntflds   =  0;                   /* field counter        */
	  int           i;
	  char          *tempfield = NULL;
	  unsigned int  Dimindex;

	  ntflds = HE5_EHparsestr(fieldlist, ',', fldnm,fldnmlen);
	  if(ntflds != FAIL)
	    {
	      for(i = 0; i < ntflds; i++)
		{
		  tempfield      = (char *)calloc(fldnmlen[i] + 1, sizeof(char));
		  memmove(tempfield,fldnm[i],fldnmlen[i]);
		  tempfield[fldnmlen[i]]='\0';

		  /* for this field see if the dimlist contains dimname */
		  status = HE5_SWfieldinfo(swathID, tempfield, &rank, tempdims, 
					   dtype, tempdimlist, NULL);

		  if (status != SUCCEED)
		    {
		      sprintf(errbuf, "Field \"%s\" not found.\n", tempfield);
		      H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, H5E_ARGS, 
			      H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      free(tempfield);
		      free(fieldlist);
		      return(FAIL);
		    }

		  Dimindex = FAIL;
		  Dimindex = HE5_EHstrwithin(dimname, tempdimlist, ',');
		  if (Dimindex == FAIL) /* dimension not found */
		    {
		      continue; /*dimlist does not contain dim name */
		    }
		  else
		    {
		      /* call HE5_SWsetdimscle */
		      status = HE5_SWsetdimscale(swathID, (char *)tempfield, 
						 dimname,
						 dimsize, 
						 numbertype_in, 
						 data);
		      if ( status == FAIL )
			{
			  sprintf(errbuf,"Cannot set dimension scale %s for the field %s. \n", 
				  dimname, tempfield);
			  H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, 
				  H5E_OHDR, H5E_NOTFOUND, errbuf);
			  HE5_EHprint(errbuf, __FILE__, __LINE__);
			  free(tempfield);
			  free(fieldlist);
			  return(status);
			}
		    }
		}
	      free(tempfield);
	      tempfield = NULL;
	    }
	}
      free(fieldlist);
      fieldlist = NULL;
    }

  /* Inquire Geo Fields */
  /* -------------------*/
  nflds = HE5_SWnentries(swathID, HE5_HDFE_NENTGFLD, &strbufsize);
  if (nflds == FAIL)
    {
      sprintf(errbuf, "Cannot get the number of fields in \"Geo Fields\" group. \n");
      H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, 
	      H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  else
    {
      fieldlist = (char *) calloc(strbufsize + 1, sizeof(char));
      if(fieldlist == NULL)
	{
	  sprintf(errbuf,"Cannot allocate memory.\n");
	  H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, 
		  H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}

      nflds = HE5_SWinqgeofields(swathID, fieldlist, NULL, NULL);
      if (nflds == FAIL)
	{
	  sprintf(errbuf, "Cannot get the list of fields in \"Geo Fields\" group. \n");
	  H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, 
		  H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(fieldlist);
	  return(FAIL);
	}
      
      if(nflds > 0)
	{
	  size_t        fldnmlen[HE5_FLDNUMBERMAX];      /* Array of namelengths */
	  char          *fldnm[HE5_FLDNUMBERMAX];        /* Array of names       */
	  char          tempdimlist[HE5_HDFE_DIMBUFSIZE];/* Dimension list       */
	  int           rank     = FAIL;                 /* Rank of dataset       */
	  hsize_t	tempdims[HE5_DTSETRANKMAX];      /* Dimension sizes array*/
	  hid_t         dtype[1] = {FAIL};               /* Data type            */
	  long          ntflds   =  0;                   /* field counter        */
	  int           i;
	  char          *tempfield = NULL;
	  unsigned int  Dimindex;

	  ntflds = HE5_EHparsestr(fieldlist, ',', fldnm,fldnmlen);
	  if(ntflds != FAIL)
	    {
	      for(i = 0; i < ntflds; i++)
		{
		  tempfield      = (char *)calloc(fldnmlen[i] + 1, sizeof(char));
		  memmove(tempfield,fldnm[i],fldnmlen[i]);
		  
		  /* for this field see if the dimlist contains dimname */
		  status = HE5_SWfieldinfo(swathID, tempfield, &rank, tempdims, 
					   dtype, tempdimlist, NULL);
		  if (status != SUCCEED)
		    {
		      sprintf(errbuf, "Field \"%s\" not found.\n", tempfield);
		      H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, H5E_ARGS, 
			      H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      free(tempfield);
		      free(fieldlist);
		      return(FAIL);
		    }
		  
		  Dimindex = FAIL;
		  Dimindex = HE5_EHstrwithin(dimname, tempdimlist, ',');
		  if (Dimindex == FAIL) /* dimension not found */
		    {
		      continue;
		    }
		  else
		    {
		      /* call HE5_SWsetdimscle */
		      status = HE5_SWsetdimscale(swathID, (char *)tempfield, 
						 dimname,
						 dimsize, 
						 numbertype_in, 
						 data);
		      if ( status == FAIL )
			{
			  sprintf(errbuf,"Cannot set dimension scale %s for the field %s. \n", 
				  dimname, tempfield);
			  H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, 
				  H5E_OHDR, H5E_NOTFOUND, errbuf);
			  HE5_EHprint(errbuf, __FILE__, __LINE__);
			  free(tempfield);
			  free(fieldlist);
			  return(status);
			}
		    }
		}
	      free(tempfield);
	      tempfield = NULL;
	    }
	}
      free(fieldlist);
      fieldlist = NULL;
    }
  

 COMPLETION:
  HE5_UNLOCK;
  return(status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefdimscale2                                               |
|                                                                             |
|  DESCRIPTION: Defines dimension scale for all fields that use the given     |
|               dimesion (with user defined dimension scale name)             |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  dimname        char                dim name                                |
|  dimscalename   char                dimension scale name                                |
|  dimsize        hsize_t             Dimemsion size value                    |
|  numbertype_in  hid_t               dim scale data type such as DFNT_INT32, |
|                                     DFNT_FLOAT64, DFNT_FLOAT32, etc.        |
|  data           void                data buffer for write                   |
|                                                                             |
|                                                                             |
|  OUTPUTS:                                                                   |
|                                                                             |
|  NOTES: This function finds out which field in a swath has the dimension    |
|         and sets dimension scale for that field calling HE5_SWsetdimscale2()|
|         User must detach swath after creating fields and attach again before|
|         calling the routine.                                                |
|                                                                             |
|                                                                             |
|   Date      Programmer    Description                                       |
|  ========   ============  ===============================================   |
|  Mar 2017   Abe Taaheri   Original Programmer                               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t
HE5_SWdefdimscale2(hid_t swathID,  char *dimname, char *dimscalename,
		  const hsize_t dimsize, hid_t numbertype_in, void * data)
{
  herr_t       status    = FAIL;/* routine return status variable  */
  hid_t        fid       = FAIL;/* HDF-EOS file ID                 */
  hid_t        gid       = FAIL;/* "HDFEOS" group ID               */
  long         idx       = FAIL;/* Swath index                     */
  char         errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */
  char         *fieldlist = NULL;
  long         strbufsize;
  long         nflds   = FAIL;

  HE5_LOCK;
  CHECKNAME(dimname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWdefdimscale", &fid, &gid, &idx); 
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for Swath ID failed.\n");
      H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Make certain that dimsize != 0 */
  /* ------------------------------ */
  if ( dimsize == 0 )
    {
      status = FAIL;
      sprintf(errbuf, "Invalid (zero) dimension size.\n");
      H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Loop over all fields in the swath and find out if 
     field's dimension list  has the dimension name. 
     If true then set the dimension scale for the dim 
     in that field
  */

  /* Inquire Data Fields first*/
  /* ------------------------ */
  nflds = HE5_SWnentries(swathID, HE5_HDFE_NENTDFLD, &strbufsize);
  if (nflds == FAIL)
    {
      sprintf(errbuf, "Cannot get the number of fields in \"Data Fields\" group. \n");
      H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, 
	      H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  else
    {
      fieldlist = (char *) calloc(strbufsize + 1, sizeof(char));
      if(fieldlist == NULL)
	{
	  sprintf(errbuf,"Cannot allocate memory.\n");
	  H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, 
		  H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}

      nflds = HE5_SWinqdatafields(swathID, fieldlist, NULL, NULL);
      if (nflds == FAIL)
	{
	  sprintf(errbuf, "Cannot get the list of fields in \"Data Fields\" group. \n");
	  H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, 
		  H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(fieldlist);
	  return(FAIL);
	}

      if(nflds > 0)
	{
	  size_t        fldnmlen[HE5_FLDNUMBERMAX];      /* Array of namelengths */
	  char          *fldnm[HE5_FLDNUMBERMAX];        /* Array of names       */
	  char          tempdimlist[HE5_HDFE_DIMBUFSIZE];/* Dimension list       */
	  int           rank     = FAIL;                 /* Rank of dataset       */
	  hsize_t	tempdims[HE5_DTSETRANKMAX];      /* Dimension sizes array*/
	  hid_t         dtype[1] = {FAIL};               /* Data type            */
	  long          ntflds   =  0;                   /* field counter        */
	  int           i;
	  char          *tempfield = NULL;
	  unsigned int  Dimindex;

	  ntflds = HE5_EHparsestr(fieldlist, ',', fldnm,fldnmlen);
	  if(ntflds != FAIL)
	    {
	      for(i = 0; i < ntflds; i++)
		{
		  tempfield      = (char *)calloc(fldnmlen[i] + 1, sizeof(char));
		  memmove(tempfield,fldnm[i],fldnmlen[i]);
		  tempfield[fldnmlen[i]]='\0';

		  /* for this field see if the dimlist contains dimname */
		  status = HE5_SWfieldinfo(swathID, tempfield, &rank, tempdims, 
					   dtype, tempdimlist, NULL);

		  if (status != SUCCEED)
		    {
		      sprintf(errbuf, "Field \"%s\" not found.\n", tempfield);
		      H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, H5E_ARGS, 
			      H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      free(tempfield);
		      free(fieldlist);
		      return(FAIL);
		    }

		  Dimindex = FAIL;
		  Dimindex = HE5_EHstrwithin(dimname, tempdimlist, ',');
		  if (Dimindex == FAIL) /* dimension not found */
		    {
		      continue; /*dimlist does not contain dim name */
		    }
		  else
		    {
		      /* call HE5_SWsetdimscle */
		      status = HE5_SWsetdimscale2(swathID, (char *)tempfield, 
						 dimname, dimscalename,
						 dimsize, 
						 numbertype_in, 
						 data);
		      if ( status == FAIL )
			{
			  sprintf(errbuf,"Cannot set dimension scale %s for the field %s. \n", 
				  dimscalename, tempfield);
			  H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, 
				  H5E_OHDR, H5E_NOTFOUND, errbuf);
			  HE5_EHprint(errbuf, __FILE__, __LINE__);
			  free(tempfield);
			  free(fieldlist);
			  return(status);
			}
		    }
		}
	      free(tempfield);
	      tempfield = NULL;
	    }
	}
      free(fieldlist);
      fieldlist = NULL;
    }

  /* Inquire Geo Fields */
  /* -------------------*/
  nflds = HE5_SWnentries(swathID, HE5_HDFE_NENTGFLD, &strbufsize);
  if (nflds == FAIL)
    {
      sprintf(errbuf, "Cannot get the number of fields in \"Geo Fields\" group. \n");
      H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, 
	      H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  else
    {
      fieldlist = (char *) calloc(strbufsize + 1, sizeof(char));
      if(fieldlist == NULL)
	{
	  sprintf(errbuf,"Cannot allocate memory.\n");
	  H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, 
		  H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}

      nflds = HE5_SWinqgeofields(swathID, fieldlist, NULL, NULL);
      if (nflds == FAIL)
	{
	  sprintf(errbuf, "Cannot get the list of fields in \"Geo Fields\" group. \n");
	  H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, 
		  H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(fieldlist);
	  return(FAIL);
	}
      
      if(nflds > 0)
	{
	  size_t        fldnmlen[HE5_FLDNUMBERMAX];      /* Array of namelengths */
	  char          *fldnm[HE5_FLDNUMBERMAX];        /* Array of names       */
	  char          tempdimlist[HE5_HDFE_DIMBUFSIZE];/* Dimension list       */
	  int           rank     = FAIL;                 /* Rank of dataset       */
	  hsize_t	tempdims[HE5_DTSETRANKMAX];      /* Dimension sizes array*/
	  hid_t         dtype[1] = {FAIL};               /* Data type            */
	  long          ntflds   =  0;                   /* field counter        */
	  int           i;
	  char          *tempfield = NULL;
	  unsigned int  Dimindex;

	  ntflds = HE5_EHparsestr(fieldlist, ',', fldnm,fldnmlen);
	  if(ntflds != FAIL)
	    {
	      for(i = 0; i < ntflds; i++)
		{
		  tempfield      = (char *)calloc(fldnmlen[i] + 1, sizeof(char));
		  memmove(tempfield,fldnm[i],fldnmlen[i]);
		  
		  /* for this field see if the dimlist contains dimname */
		  status = HE5_SWfieldinfo(swathID, tempfield, &rank, tempdims, 
					   dtype, tempdimlist, NULL);
		  if (status != SUCCEED)
		    {
		      sprintf(errbuf, "Field \"%s\" not found.\n", tempfield);
		      H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, H5E_ARGS, 
			      H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      free(tempfield);
		      free(fieldlist);
		      return(FAIL);
		    }
		  
		  Dimindex = FAIL;
		  Dimindex = HE5_EHstrwithin(dimname, tempdimlist, ',');
		  if (Dimindex == FAIL) /* dimension not found */
		    {
		      continue;
		    }
		  else
		    {
		      /* call HE5_SWsetdimscle */
		      status = HE5_SWsetdimscale2(swathID, (char *)tempfield, 
						 dimname, dimscalename,
						 dimsize, 
						 numbertype_in, 
						 data);
		      if ( status == FAIL )
			{
			  sprintf(errbuf,"Cannot set dimension scale %s for the field %s. \n", 
				  dimscalename, tempfield);
			  H5Epush(__FILE__, "HE5_SWdefdimscale", __LINE__, 
				  H5E_OHDR, H5E_NOTFOUND, errbuf);
			  HE5_EHprint(errbuf, __FILE__, __LINE__);
			  free(tempfield);
			  free(fieldlist);
			  return(status);
			}
		    }
		}
	      free(tempfield);
	      tempfield = NULL;
	    }
	}
      free(fieldlist);
      fieldlist = NULL;
    }
  

 COMPLETION:
  HE5_UNLOCK;
  return(status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWsetdimscale                                                |
|                                                                             |
|  DESCRIPTION: Defines a dimension scale for a fields dimension in a swath   |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  fieldname      char                field name                              |
|  dimname        char                Dimension name                          |
|  dimsize        hsize_t             Dimemsion size value                    |
|  numbertype_in  hid_t               dim scale data type such as DFNT_INT32, |
|                                     DFNT_FLOAT64, DFNT_FLOAT32, etc.        |
|  data           void                data buffer for write                   |
|                                                                             |
|                                                                             |
|  OUTPUTS:                                                                   |
|             None                                                            |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  May 10    Abe Taaheri  Original Programmer                                 |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t
HE5_SWsetdimscale(hid_t swathID, char *fieldname, char *dimname,
		  const hsize_t dimsize, hid_t numbertype_in, void * data)
{
  herr_t         status;
  hid_t          ntype;
  hsize_t        dims[HE5_DTSETRANKMAX];
  int            rankSDS;
  hid_t          field_ntype[1]={FAIL}; 
  char           dimlist[HE5_HDFE_DIMBUFSIZE];
  char           maxdimlist[HE5_HDFE_DIMBUFSIZE];

  hid_t          fid    = FAIL; 	       /* HDF-EOS file ID     */
  hid_t          gid    = FAIL;	               /* "HDFEOS"  group ID  */
  hid_t          did;
  hid_t          dsid;
  hid_t          fspace   = FAIL;              /* File dataspace ID   */
  unsigned int   Dimindex;
  hid_t          dsplist  = FAIL;              /* Property list ID     */
  H5D_layout_t   layout   = H5D_LAYOUT_ERROR;  /* Type of storage      */
  hid_t          data_space  = FAIL;           /* dataspace ID         */
  long           idx         = FAIL;           /* Swath index           */
  char          *errbuf      = (char *)NULL;   /* buffer for error message*/
  void          *data_buff;
  int            i, found = 0;
  int            rankds;
  int            num_index_found;
  int           *index_found_ptr;
  int           *temp_index_ptr;
  hsize_t        dimsds[1];

  i = 0;
  found = 0;
  num_index_found = 0;
  index_found_ptr = NULL;

  HE5_LOCK;
  CHECKNAME(fieldname);
  CHECKNAME(dimname);
  /* Allocate memory for error buffer */
  /* -------------------------------- */
  errbuf = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_FILE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer ", __FILE__, __LINE__);
      return(FAIL);
    }

  /* Convert HDF-EOS5 datatype to HDF5 datatype */
  if (
      H5Tequal(numbertype_in, H5T_NATIVE_CHAR)   == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_SCHAR)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_UCHAR)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_SHORT)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_USHORT) == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_INT)    == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_UINT)   == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_LONG)   == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_ULONG)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_LLONG)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_ULLONG) == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_FLOAT)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_DOUBLE) == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_LDOUBLE)== SUCCEED ||
      H5Tequal(numbertype_in, H5T_C_S1) == SUCCEED)
    {
      ntype = numbertype_in;
    }
  else
    {
      ntype = HE5_EHconvdatatype((int) numbertype_in);
    }

  if(ntype == FAIL)
    {
      sprintf(errbuf,"Cannot convert to HDF5 type data type ID for dimscale\n");
      H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /*
**********************************************************
*  Check for proper swath ID and return HDF-EOS file ID,  * 
*        "HDFEOS" group ID and Swath index                *  
**********************************************************
*/
  status = HE5_SWchkswid(swathID, "HE5_SWsetdimscale", &fid, &gid, &idx);
  if(status == FAIL)
    {
      sprintf(errbuf,"Checking for Swath ID failed.\n");
      H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }

  if (status == 0)
    {
      /* Check that field exists */
      /* ----------------------- */

      status = HE5_SWfieldinfo(swathID, fieldname, &rankSDS, dims, field_ntype, dimlist, maxdimlist);
      if (status != 0)
	{
	  sprintf(errbuf, "Fieldname \"%s\" does not exist.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__,  H5E_ARGS, H5E_BADRANGE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(errbuf);
	  return(FAIL);
	}
      
      data_buff = data;
      
      /* Loop through all datasets in swath */
      /* ------------------------------ */
	for (i = 0; i < HE5_SWXSwath[idx].nDFLD; i++)
	  {
	    /* Get dataset name */
	    if( strcmp(fieldname, HE5_SWXSwath[ idx ].ddataset[ i ].name) == 0 )
	      {
		found = 1; 
		did = HE5_SWXSwath[ idx ].ddataset[ i ].ID;
		break;
	      } 
	  }

	if(found != 1) /* did not find fieldname */
	  {
	    /* did not find Data-field name, lets look for Geo-fieldname */

	    for (i = 0; i < HE5_SWXSwath[idx].nGFLD; i++)
	      {
		/* Get dataset name */
		if(strcmp(fieldname,HE5_SWXSwath[idx].gdataset[i].name)==0) {
		  found = 1; 
		  did = HE5_SWXSwath[ idx ].gdataset[ i ].ID;
		  break;
		  
		}
	      }
	  }

	if(found != 1) /* did not find fieldname */
	  {
	    sprintf(errbuf, "Fieldname \"%s\" does not exist.\n", fieldname);
	    H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__,  H5E_ARGS, H5E_BADRANGE, errbuf);
	    HE5_EHprint(errbuf, __FILE__, __LINE__);
	    free(errbuf);
	    return(FAIL);
	  }
	/* Dimension index */

	Dimindex = FAIL;
	Dimindex = HE5_EHstrwithin(dimname, dimlist, ',');

        /*// obtain number of the index for dimname. This is for the case temp[dimname][dimname][..] case. */
        num_index_found = HE5_EHstrwithin_index(dimname,dimlist,',',NULL);
       
	/*// if we find the dimname is used multiple times, we need to retrieve all the indexes. */
        if(num_index_found >1) {
	  index_found_ptr =(int*)calloc(num_index_found,sizeof(int));
	  num_index_found = HE5_EHstrwithin_index(dimname,dimlist,',',index_found_ptr);
        }
	
	if (Dimindex == FAIL) /* dimension not found */
	  {
	    status = FAIL;
	    sprintf( errbuf, "Dimname \"%s\" does not exist for field \"%s\".\n", 
		     dimname, fieldname );
	    H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_IO, H5E_SEEKERROR, errbuf);
	    HE5_EHprint(errbuf, __FILE__, __LINE__);
	    free(errbuf);
	    return(status);
	  }

	/* If dimension found ... */
	/* Found the dimname; Use its dimid to set Dimension Scale*/
	
	/* See if dimscale dataset already exist */
	
	dsid = H5Dopen(HE5_SWXSwath[idx].sw_id, dimname);
	if(dsid < 0)
	  {
	    /* create Dim Scale dataset */
	    /* Try to open the " group  */
	    /* ======================== */
	    
	    dsplist = H5Pcreate(H5P_DATASET_CREATE);
	    if(dsplist == FAIL)
	      {
		sprintf(errbuf,"Cannot create a new property list.\n");  
		H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
		HE5_EHprint(errbuf, __FILE__, __LINE__);
		free(errbuf);
		return(FAIL);
	      }
	    /* Get layout information */
	    /* ---------------------- */		
	    layout = H5Pget_layout(dsplist);
	    if(layout == H5D_LAYOUT_ERROR)
	      {
		sprintf(errbuf,"Cannot get layout information for the dataset.\n");  
		H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
		HE5_EHprint(errbuf, __FILE__, __LINE__);
		free(errbuf);
		return(FAIL);
	      }

	    rankds = 1;
	    dimsds[0] = dims[Dimindex];

	    data_space = H5Screate_simple(rankds, dimsds, NULL);
	    if(data_space == FAIL)
	      {
		sprintf(errbuf,"Cannot create dataspace for the dimension scale dataset.\n");  
		H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
		HE5_EHprint(errbuf, __FILE__, __LINE__);
		free(errbuf);
		return(FAIL);
	      }
	    
	    dsid = H5Dcreate(HE5_SWXSwath[idx].sw_id,dimname,ntype, data_space, dsplist);
	    
	    if( dsid == FAIL )
	      {
		sprintf(errbuf, "Cannot create dataset for Dimension Scale \"%s\" field. \n", dimname);
		H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
		HE5_EHprint(errbuf, __FILE__, __LINE__);
		free(errbuf);
		return(FAIL);
	      }

	    /* write data_buff to it */

	    /* Get the field space ID */
	    /* --------------------- */
	    fspace = H5Dget_space(dsid);
	    if ( fspace == FAIL)
	      {
		sprintf(errbuf, "Cannot get the file data space ID.\n");
		H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_DATASPACE, H5E_NOTFOUND, errbuf);
		HE5_EHprint(errbuf, __FILE__, __LINE__);
		free(errbuf);
		return(FAIL);
	      }

	    status = H5Dwrite(dsid, ntype, data_space, fspace,  H5P_DEFAULT, data_buff);
	    if( status == FAIL )
	      {
		sprintf(errbuf,"Cannot write data to the dataset.\n");
		H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
		HE5_EHprint(errbuf, __FILE__, __LINE__);
		free(errbuf);
		return(FAIL);
	      }
	  }

	/* Dataset exist. See if it is Dimension Scale already. If not make it */

	if((H5DSis_scale(dsid)) <= 0 )
	  {
	    status = H5DSset_scale(dsid, dimname);
	    if( status < 0)
	      {
		status = -1;
		free(errbuf);
		goto COMPLETION;
	      }
	    
            if(num_index_found <= 1) {
	      if(H5DSattach_scale(did, dsid, Dimindex) < 0)
	      {
		status = -1;
		free(errbuf);
		goto COMPLETION;
	      }
            }
            else 
	      {/*// dimname is used multiple times for this variable. Need to attach them.  */
		temp_index_ptr = index_found_ptr;
		for(i = 0; i<num_index_found;i++) 
		  {
		    if(H5DSattach_scale(did, dsid, *temp_index_ptr) < 0)
		      {
			status = -1;
			free(errbuf);
			goto COMPLETION;
		      }
		    temp_index_ptr++;
		  }
	      } 
	  }
	else
	  {
	    if(num_index_found <= 1) {
	      if(H5DSattach_scale(did, dsid, Dimindex) < 0)
		{
		  status = -1;
		  free(errbuf);
		  goto COMPLETION;
		}
	    }
            else 
	      {/*// dimname is used multiple times, need to provide all indexes. */
		temp_index_ptr = index_found_ptr;
		for(i = 0; i<num_index_found;i++) 
		  {
		    if(H5DSattach_scale(did, dsid, *temp_index_ptr) < 0)
		      {
			status = -1;
			free(errbuf);
			goto COMPLETION;
		      }
		    temp_index_ptr++;
		  }
	      }
	  }
    
	if( H5Dclose(dsid) < 0)
	  {
	    status = -1;
	    free(errbuf);
	    goto COMPLETION;
	  }
    }
  free(errbuf);
  if(index_found_ptr != NULL)
    free(index_found_ptr);
 COMPLETION:  
  HE5_UNLOCK;
  return (status);
}




/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWsetdimscale2                                               |
|                                                                             |
|  DESCRIPTION: Defines a dimension scale for a fields dimension in a swath   |
|               using user defined dimension scale name                       |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  fieldname      char                field name                              |
|  dimname        char                Dimension name                          |
|  dimscalename   char                Dimension scale name                          |
|  dimsize        hsize_t             Dimemsion size value                    |
|  numbertype_in  hid_t               dim scale data type such as DFNT_INT32, |
|                                     DFNT_FLOAT64, DFNT_FLOAT32, etc.        |
|  data           void                data buffer for write                   |
|                                                                             |
|                                                                             |
|  OUTPUTS:                                                                   |
|             None                                                            |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  May 10    Abe Taaheri  Original Programmer                                 |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t
HE5_SWsetdimscale2(hid_t swathID, char *fieldname, char *dimname, char *dimscalename,
		  const hsize_t dimsize, hid_t numbertype_in, void * data)
{
  herr_t         status;
  hid_t          ntype;
  hsize_t        dims[HE5_DTSETRANKMAX];
  int            rankSDS;
  hid_t          field_ntype[1]={FAIL}; 
  char           dimlist[HE5_HDFE_DIMBUFSIZE];
  char           maxdimlist[HE5_HDFE_DIMBUFSIZE];

  hid_t          fid    = FAIL; 	       /* HDF-EOS file ID     */
  hid_t          gid    = FAIL;	               /* "HDFEOS"  group ID  */
  hid_t          did;
  hid_t          dsid;
  hid_t          fspace   = FAIL;              /* File dataspace ID   */
  unsigned int   Dimindex;
  hid_t          dsplist  = FAIL;              /* Property list ID     */
  H5D_layout_t   layout   = H5D_LAYOUT_ERROR;  /* Type of storage      */
  hid_t          data_space  = FAIL;           /* dataspace ID         */
  long           idx         = FAIL;           /* Swath index           */
  char          *errbuf      = (char *)NULL;   /* buffer for error message*/
  void          *data_buff;
  int            i, found = 0;
  int            rankds;
  int            num_index_found;
  int           *index_found_ptr;
  int           *temp_index_ptr;
  hsize_t        dimsds[1];

  i = 0;
  found = 0;
  num_index_found = 0;
  index_found_ptr = NULL;

  HE5_LOCK;
  CHECKNAME(fieldname);
  CHECKNAME(dimname);
  /* Allocate memory for error buffer */
  /* -------------------------------- */
  errbuf = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_FILE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer ", __FILE__, __LINE__);
      return(FAIL);
    }

  /* Convert HDF-EOS5 datatype to HDF5 datatype */
  if (
      H5Tequal(numbertype_in, H5T_NATIVE_CHAR)   == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_SCHAR)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_UCHAR)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_SHORT)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_USHORT) == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_INT)    == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_UINT)   == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_LONG)   == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_ULONG)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_LLONG)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_ULLONG) == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_FLOAT)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_DOUBLE) == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_LDOUBLE)== SUCCEED ||
      H5Tequal(numbertype_in, H5T_C_S1) == SUCCEED)
    {
      ntype = numbertype_in;
    }
  else
    {
      ntype = HE5_EHconvdatatype((int) numbertype_in);
    }

  if(ntype == FAIL)
    {
      sprintf(errbuf,"Cannot convert to HDF5 type data type ID for dimscale\n");
      H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /*
**********************************************************
*  Check for proper swath ID and return HDF-EOS file ID,  * 
*        "HDFEOS" group ID and Swath index                *  
**********************************************************
*/
  status = HE5_SWchkswid(swathID, "HE5_SWsetdimscale", &fid, &gid, &idx);
  if(status == FAIL)
    {
      sprintf(errbuf,"Checking for Swath ID failed.\n");
      H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }

  if (status == 0)
    {
      /* Check that field exists */
      /* ----------------------- */

      status = HE5_SWfieldinfo(swathID, fieldname, &rankSDS, dims, field_ntype, dimlist, maxdimlist);
      if (status != 0)
	{
	  sprintf(errbuf, "Fieldname \"%s\" does not exist.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__,  H5E_ARGS, H5E_BADRANGE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(errbuf);
	  return(FAIL);
	}
      
      data_buff = data;
      
      /* Loop through all datasets in swath */
      /* ------------------------------ */
	for (i = 0; i < HE5_SWXSwath[idx].nDFLD; i++)
	  {
	    /* Get dataset name */
	    if( strcmp(fieldname, HE5_SWXSwath[ idx ].ddataset[ i ].name) == 0 )
	      {
		found = 1; 
		did = HE5_SWXSwath[ idx ].ddataset[ i ].ID;
		break;
	      } 
	  }

	if(found != 1) /* did not find fieldname */
	  {
	    /* did not find Data-field name, lets look for Geo-fieldname */

	    for (i = 0; i < HE5_SWXSwath[idx].nGFLD; i++)
	      {
		/* Get dataset name */
		if(strcmp(fieldname,HE5_SWXSwath[idx].gdataset[i].name)==0) {
		  found = 1; 
		  did = HE5_SWXSwath[ idx ].gdataset[ i ].ID;
		  break;
		  
		}
	      }
	  }

	if(found != 1) /* did not find fieldname */
	  {
	    sprintf(errbuf, "Fieldname \"%s\" does not exist.\n", fieldname);
	    H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__,  H5E_ARGS, H5E_BADRANGE, errbuf);
	    HE5_EHprint(errbuf, __FILE__, __LINE__);
	    free(errbuf);
	    return(FAIL);
	  }
	/* Dimension index */

	Dimindex = FAIL;
	Dimindex = HE5_EHstrwithin(dimname, dimlist, ',');

        /* obtain number of the index for dimname. This is for the case temp[dimname][dimname][..] case. */
        num_index_found = HE5_EHstrwithin_index(dimname,dimlist,',',NULL);
       
	/* if we find the dimname is used multiple times, we need to retrieve all the indexes. */
        if(num_index_found >1) {
	  index_found_ptr =(int*)calloc(num_index_found,sizeof(int));
	  num_index_found = HE5_EHstrwithin_index(dimname,dimlist,',',index_found_ptr);
        }
	
	if (Dimindex == FAIL) /* dimension not found */
	  {
	    status = FAIL;
	    sprintf( errbuf, "Dimname \"%s\" does not exist for field \"%s\".\n", 
		     dimname, fieldname );
	    H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_IO, H5E_SEEKERROR, errbuf);
	    HE5_EHprint(errbuf, __FILE__, __LINE__);
	    free(errbuf);
	    return(status);
	  }

	/* If dimension found ... */
	/* Found the dimname; Use its dimid to set Dimension Scale*/
	
	/* See if dimscale dataset already exist */
	
	dsid = H5Dopen(HE5_SWXSwath[idx].sw_id, dimscalename);
	if(dsid < 0)
	  {
	    /* create Dim Scale dataset */
	    /* Try to open the " group  */
	    /* ======================== */
	    
	    dsplist = H5Pcreate(H5P_DATASET_CREATE);
	    if(dsplist == FAIL)
	      {
		sprintf(errbuf,"Cannot create a new property list.\n");  
		H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
		HE5_EHprint(errbuf, __FILE__, __LINE__);
		free(errbuf);
		return(FAIL);
	      }
	    /* Get layout information */
	    /* ---------------------- */		
	    layout = H5Pget_layout(dsplist);
	    if(layout == H5D_LAYOUT_ERROR)
	      {
		sprintf(errbuf,"Cannot get layout information for the dataset.\n");  
		H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
		HE5_EHprint(errbuf, __FILE__, __LINE__);
		free(errbuf);
		return(FAIL);
	      }

	    rankds = 1;
	    /*dimsds[0] = dims[Dimindex]; */
	    dimsds[0] = dimsize;

	    data_space = H5Screate_simple(rankds, dimsds, NULL);
	    if(data_space == FAIL)
	      {
		sprintf(errbuf,"Cannot create dataspace for the dimension scale dataset.\n");  
		H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
		HE5_EHprint(errbuf, __FILE__, __LINE__);
		free(errbuf);
		return(FAIL);
	      }
	    
	    dsid = H5Dcreate(HE5_SWXSwath[idx].sw_id,dimscalename,ntype, data_space, dsplist);
	    
	    if( dsid == FAIL )
	      {
		sprintf(errbuf, "Cannot create dataset for Dimension Scale \"%s\" field. \n", dimscalename);
		H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
		HE5_EHprint(errbuf, __FILE__, __LINE__);
		free(errbuf);
		return(FAIL);
	      }

	    /* write data_buff to it */

	    /* Get the field space ID */
	    /* --------------------- */
	    fspace = H5Dget_space(dsid);
	    if ( fspace == FAIL)
	      {
		sprintf(errbuf, "Cannot get the file data space ID.\n");
		H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_DATASPACE, H5E_NOTFOUND, errbuf);
		HE5_EHprint(errbuf, __FILE__, __LINE__);
		free(errbuf);
		return(FAIL);
	      }

	    status = H5Dwrite(dsid, ntype, data_space, fspace,  H5P_DEFAULT, data_buff);
	    if( status == FAIL )
	      {
		sprintf(errbuf,"Cannot write data to the dataset.\n");
		H5Epush(__FILE__, "HE5_SWsetdimscale", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
		HE5_EHprint(errbuf, __FILE__, __LINE__);
		free(errbuf);
		return(FAIL);
	      }
	  }

	/* Dataset exist. See if it is Dimension Scale already. If not make it */

	if((H5DSis_scale(dsid)) <= 0 )
	  {
	    status = H5DSset_scale(dsid, dimscalename);
	    if( status < 0)
	      {
		status = -1;
		free(errbuf);
		goto COMPLETION;
	      }
	    
            if(num_index_found <= 1) {
	      if(H5DSattach_scale(did, dsid, Dimindex) < 0)
	      {
		status = -1;
		free(errbuf);
		goto COMPLETION;
	      }
            }
            else 
	      {/*// dimname is used multiple times for this variable. Need to attach them.  */
		temp_index_ptr = index_found_ptr;
		for(i = 0; i<num_index_found;i++) 
		  {
		    if(H5DSattach_scale(did, dsid, *temp_index_ptr) < 0)
		      {
			status = -1;
			free(errbuf);
			goto COMPLETION;
		      }
		    temp_index_ptr++;
		  }
	      } 
	  }
	else
	  {
	    if(num_index_found <= 1) {
	      if(H5DSattach_scale(did, dsid, Dimindex) < 0)
		{
		  status = -1;
		  free(errbuf);
		  goto COMPLETION;
		}
	    }
            else 
	      {/*// dimname is used multiple times, need to provide all indexes. */
		temp_index_ptr = index_found_ptr;
		for(i = 0; i<num_index_found;i++) 
		  {
		    if(H5DSattach_scale(did, dsid, *temp_index_ptr) < 0)
		      {
			status = -1;
			free(errbuf);
			goto COMPLETION;
		      }
		    temp_index_ptr++;
		  }
	      }
	  }
    
	if( H5Dclose(dsid) < 0)
	  {
	    status = -1;
	    free(errbuf);
	    goto COMPLETION;
	  }
    }
  free(errbuf);
  if(index_found_ptr != NULL)
    free(index_found_ptr);
 COMPLETION:  
  HE5_UNLOCK;
  return (status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWgetdimscale                                                |
|                                                                             |
|  DESCRIPTION: Get dimension scale for a dimension of a field in a swath     |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         long                return databuffsize  SUCCEED, (-1) FAIL |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID         hid_t               swath structure ID                     |
|  fieldname      char                field name                              |
|  dimname        char                dim name                                |
|                                                                             |
|                                                                             |
|  OUTPUTS:                                                                   |
|  dimsize        hsize_t             dimension size                          |
|  ntype          hid_t               dtata type of dimension scale           |
|  databuff       void                data buffer for read                    |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  May 10    Abe Taaheri  Original Programmer                                 |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long
HE5_SWgetdimscale(hid_t swathID, char *fieldname, char *dimname, 
		  hsize_t *dimsize, hid_t *ntype, void * databuff)
{
  int             i,j;		                   /* Loop index             */
  long            status;	                   /* routine return status  */
  long            idx    = FAIL;                   /* Swath index            */
  hid_t           fid    = FAIL; 	           /* HDF-EOS file ID        */
  hid_t           gid    = FAIL;	           /* "HDFEOS" group ID      */
  hid_t           did    = FAIL;                   /* dataset ID             */
  hid_t           dsid   = FAIL;                   /* dimscale dataset ID    */
  hid_t           dspace = FAIL;                   /* data space ID          */
  hid_t           mspace = FAIL;                   /* memory data space ID   */
  hid_t           dtype  = FAIL;                   /* data type ID           */
  hid_t           mtype  = FAIL;                   /* memory data type ID    */
  H5T_class_t     classid = H5T_NO_CLASS;          /* Data type class ID     */
  hsize_t         dimsds[HE5_DTSETRANKMAX];        /* Field dimensions       */
  char           *errbuf = (char *)NULL;           /* buff for error message */
  long            size   = 0;                      /* data buffer size(bytes)*/
  int             rankds;
  size_t          sd_type_size = 0;	           /* Size of a data type    */
  unsigned int    Dimindex;
  int             rankSDS;
   hid_t          field_ntype[1]={FAIL};           /* number types           */
  char            dimlist[HE5_HDFE_DIMBUFSIZE];
  char            maxdimlist[HE5_HDFE_DIMBUFSIZE];
  /*hid_t           ntype   = FAIL;*/
  hsize_t         dims[HE5_DTSETRANKMAX];
  int             found = 0;
  htri_t          str_is_variable; /* boolean: TRUE if string is variable 
				      lengeth FALSE if string is fixed length
				      -1 if error in H5Tis_variavle_str() */
  HE5_LOCK;
  CHECKNAME(fieldname);
  CHECKNAME(dimname);


  /* Allocate memory for error buffer */
  /* -------------------------------- */
  errbuf = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_FILE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }

  /*
**********************************************************
*  Check for proper swath ID and return HDF-EOS file ID,  * 
*        "HDFEOS" group ID and Swath index                *  
**********************************************************
*/
  status = HE5_SWchkswid(swathID, "HE5_SWgetdimscale", &fid, &gid, &idx);
  if(status == FAIL)
    {
      sprintf(errbuf,"Checking for Swath ID failed.\n");
      H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }

  /* See if dimscale dataset exist */

  dsid = H5Dopen(HE5_SWXSwath[idx].sw_id, dimname);
  if(dsid < 0)
    {
      status = FAIL;
      sprintf( errbuf, "Dimension scale dataset \"%s\" does not exist.\n", 
	       dimname);
      H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_IO, H5E_SEEKERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(status);
    }

  /* Loop through all datasets in swath */
  /* ------------------------------ */
  for (i = 0; i < HE5_SWXSwath[idx].nDFLD; i++)
    {
      /* Get dataset name */
      if( strcmp(fieldname, HE5_SWXSwath[ idx ].ddataset[ i ].name) == 0 )
	{
	  found = 1; 
	  did = HE5_SWXSwath[ idx ].ddataset[ i ].ID;
	  break;
	}
    }

  if(found != 1) /* did not find fieldname */
    {
      /* did not find Data-field name, lets look for Geo-fieldname */
      
      for (i = 0; i < HE5_SWXSwath[idx].nGFLD; i++)
	{
	  /* Get dataset name */
	  if(strcmp(fieldname,HE5_SWXSwath[idx].gdataset[i].name)==0) {
	    found = 1; 
	    did = HE5_SWXSwath[ idx ].gdataset[ i ].ID;
	    break;
	    
	  }
	}
    }

  if(found != 1) /* did not find fieldname */
    {
      sprintf(errbuf, "Fieldname \"%s\" does not exist.\n", fieldname);
      H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__,  H5E_ARGS, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }

  /* Check that field exists */
  /* ----------------------- */
  status = HE5_SWfieldinfo(swathID, fieldname, &rankSDS, dims, field_ntype, dimlist, maxdimlist);
  
  if (status != 0)
    {
      sprintf(errbuf, "Fieldname \"%s\" does not exist.\n", fieldname);
      H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__,  H5E_ARGS, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }

  /* find the index of the dimension in the field */

  Dimindex = FAIL;
  Dimindex = HE5_EHstrwithin(dimname, dimlist, ',');
  if (Dimindex == FAIL) /* dimension not found */
    {
      status = FAIL;
      sprintf( errbuf, "Dimname \"%s\" does not exist for field \"%s\".\n", 
	       dimname, fieldname );
      H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_IO, H5E_SEEKERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(status);
    }

  /* check that dimname is dimension scale name for the field dimname */
  status = H5DSis_attached(did, dsid, Dimindex);

  if( status < 0)
    {
      status = FAIL;
      sprintf( errbuf, "Dimname \"%s\" is not dimension scale for a dimension in the field \"%s\".\n", dimname, fieldname );
      H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_IO, H5E_SEEKERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(status);
    }

  /* OK. dsid is a dimension scale for did. It is time to read Dimension 
     Scale dataset for output */

  /* get size first ... */
  /* ------------------ */
  dtype = H5Dget_type(dsid);
  if ( dtype == FAIL )
    {
      size = 0;
      sprintf(errbuf, "Cannot get data type ID.\n");
      H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }

  /* Get data type size (bytes) */
  /* -------------------------- */   
  sd_type_size = H5Tget_size(dtype);
  if ( sd_type_size == 0 )
    {
      sprintf(errbuf, "Cannot retrieve data type size.\n");
      H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }

  /* Get data space ID */
  /* ----------------- */
  dspace = H5Dget_space( dsid );
  if (dspace == FAIL)
    {
      sprintf(errbuf, "Cannot get the dataspace ID for the \"%s\" dataset.\n", dimname);
      H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  
  /* Get dataset rank */
  /* ---------------- */
  rankds = H5Sget_simple_extent_ndims(dspace);
  if ( rankds == FAIL )
    {
      sprintf(errbuf, "Cannot get the dataset rank for the \"%s\" dataset.\n", dimname);
      H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  
  /* Get dataset dimension sizes */
  /* --------------------------- */
  status = H5Sget_simple_extent_dims(dspace,dimsds, NULL);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Cannot get the dataset dimension sizes for the \"%s\" dataset.\n", dimname);
      H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(status);
    }
  
  /*----------------------------------------------------------------------*/

  /* Get data class ID */
  /* ----------------- */
  classid       = H5Tget_class(dtype);
  if (classid == H5T_NO_CLASS)
    {
      sprintf(errbuf, "Cannot get the data type class ID for \"%s\" dataset.",
	      dimname);
      H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_DATATYPE, 
	      H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      if (errbuf  != NULL) free(errbuf);
      return(FAIL);
    }
  
  if (classid == H5T_STRING)
    {
      /* HE5T_CHARSTRING has variable length for data fields */
      str_is_variable = H5Tis_variable_str(dtype);
      if(str_is_variable == TRUE)
	{
	  *ntype = HE5T_CHARSTRING;
	}
      else if(str_is_variable == FALSE)
	{
	  *ntype = HE5T_NATIVE_CHAR;
	}
      else
	{
	  sprintf(errbuf, "Failed to see if string field is varaible or fixed length for the \"%s\" field.\n",dimname);
	  H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_DATATYPE, 
		  H5E_NOTFOUND, errbuf);
	  
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  if (errbuf  != NULL) free(errbuf);
	  return(FAIL);
	}
    }
  else
    {
      *ntype = HE5_EHdtype2numtype(dtype);
      if (*ntype == FAIL)
	{
	  sprintf(errbuf, "Cannot get the number type for \"%s\" dataset.", 
		  dimname);
	  H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_DATATYPE, 
		  H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  if (errbuf  != NULL) free(errbuf);
	  return(FAIL);
	}
    }
  /*----------------------------------------------------------------------*/

  status = H5Tclose(dtype);
  if ( status == FAIL )
    {
      sprintf(errbuf,"Cannot release the datatype ID.\n");
      H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  
  /* Release the dataspace ID */
  /* ------------------------ */
  status = H5Sclose(dspace);
  if ( status == FAIL)
    {
      sprintf(errbuf, "Cannot release the dataset ID for the \"%s\" dataset.\n", dimname);
      H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(status);
    }

  size = (long)dimsds[ 0 ];
  *dimsize = (hsize_t)size;

  for (j = 1; j < rankds; j++)
    size *= (long)dimsds[j];
 
  size *= (long)sd_type_size;

  /* If data values are requested ... */
  /* -------------------------------- */
  if (databuff != NULL)
    {
      /* Create a data space in memory */
      /* ----------------------------- */ 		
      mspace = H5Screate_simple(rankds, (const hsize_t *)dimsds, NULL);
      if ( mspace == FAIL )
	{
	  sprintf(errbuf,"Cannot create the data space.\n");
	  H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_DATASPACE, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(errbuf);
	  return(FAIL);
	}

      dspace = H5Dget_space(dsid );
      if (dspace == FAIL)
	{
	  sprintf(errbuf, "Cannot get the dataspace ID for the \"%s\" dataset.\n", dimname);
	  H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(errbuf);
	  return(FAIL);
	}
		
      dtype = H5Dget_type(dsid);
      if ( dtype == FAIL )
	{
	  sprintf(errbuf,"Cannot get the datatype ID.\n");
	  H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(errbuf);
	  return(FAIL);
	}

      /* Get the memory data type ID */
      /* --------------------------- */
      mtype = HE5_EHdtype2mtype(dtype);
      if ( mtype == FAIL )
	{
	  sprintf(errbuf,"Cannot get the memory data type.\n");
	  H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(errbuf);
	  return(FAIL);
	}

      /* Read the selected points into the buffer */
      /* ---------------------------------------  */
      status = H5Dread(dsid, mtype, mspace, dspace, H5P_DEFAULT, databuff);
      if ( status == FAIL )
	{
	  sprintf(errbuf,"Cannot read out the data from the dataset.\n");
	  H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_DATASET, H5E_READERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(errbuf);
	  return(FAIL);
	}
				
      status = H5Tclose(dtype);
      if ( status == FAIL )
	{
	  sprintf(errbuf,"Cannot release the datatype ID.\n");
	  H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(errbuf);
	  return(FAIL);
	}
		
      status = H5Sclose(mspace);
      if ( status == FAIL )
	{
	  sprintf(errbuf,"Cannot release the memory data space ID.\n");
	  H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_DATASPACE, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(errbuf);
	  return(FAIL);
	}
		
      status = H5Sclose(dspace);
      if ( status == FAIL )
	{
	  sprintf(errbuf,"Cannot release the file data space ID.\n");
	  H5Epush(__FILE__, "HE5_SWgetdimscale", __LINE__, H5E_DATASPACE, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(errbuf);
	  return(FAIL);
	}
    }

  free(errbuf);
 COMPLETION:
  HE5_UNLOCK;
  return (size);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWreaddscaleattr                                             |
|                                                                             |
|  DESCRIPTION: Reads attribute associated with a dimension scale field       |
|               from a swath.                                                 |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t   None        HDF-EOS type swath  ID                  |
|  fieldname      char                field name                              |
|  attrname       char                attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Jun 10   Abe Taaheri   Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t  
HE5_SWreaddscaleattr(hid_t swathID, const char *fieldname, const char *attrname, void *datbuf)
{
  herr_t     status        = FAIL;/* routine return status variable */

  hid_t      ntype         = FAIL;/* hdf5 type data type ID         */
  hid_t      fid           = FAIL;/* HDF-EOS file ID                */
  hid_t      gid           = FAIL;/* "HDFEOS" group ID              */
  hid_t      fieldID       = FAIL;/* Field-related dataset ID       */
     
  long       idx           = FAIL;/* Swath index                    */
     
  hsize_t    count[]={0};	   /* array with the number of elements */

  char       errbuf[HE5_HDFE_ERRBUFSIZE]; /* Error message buffer   */


  HE5_LOCK;
  CHECKPOINTER(fieldname);
  CHECKPOINTER(attrname);

  /*
**********************************************************
*  Check for proper swath ID and return HDF-EOS file ID,  * 
*        "HDFEOS" group ID and Swath index                *  
**********************************************************
*/
  status = HE5_SWchkswid(swathID, "HE5_SWreaddscaleattr", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Get field ID */
      /* ------------ */
      fieldID = H5Dopen(HE5_SWXSwath[idx].sw_id, fieldname);
      if(fieldID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"%s\" field dataset ID.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWreaddscaleattr", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
		
      /* Call EHattr to perform I/O */
      /* -------------------------- */
      status = HE5_EHattr(fieldID, attrname, ntype, count, "r", datbuf);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot read Attribute \"%s\" associated wth the \"%s\" field.\n", attrname,fieldname);
	  H5Epush(__FILE__, "HE5_SWreaddscaleattr", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
        
      /* Release dataset ID */
      /* ------------------ */
      status = H5Dclose(fieldID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"%s\" field dataset ID.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWreaddscaleattr", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}			
    }

 COMPLETION:
  HE5_UNLOCK;
  return (status);
}




/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION:  HE5_SWwritedscaleattr                                           |
|                                                                             |
|  DESCRIPTION: Writes/updates attribute associated with a dimension scale    |
|               field in a swath.                                             |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  fieldname      char*               dimension scale SDS name                |
|  attrname       char*               attribute name                          |
|  numtype        hid_t               attribute datatype ID                   |
|  count[]        hsize_t             Number of attribute elements            |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  May 10   Abe Taaheri   Original development.                               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWwritedscaleattr(hid_t swathID, const char *fieldname, const char *attrname, 
		      hid_t numtype, hsize_t  count[],  void *datbuf)
{
  herr_t     status        = FAIL;/* routine return status variable */
  
  hid_t      fid           = FAIL;/* HDF-EOS file ID                */
  hid_t      gid           = FAIL;/* "HDFEOS" group ID              */
  hid_t      fieldID       = FAIL;/* Field-related dataset ID       */
  
  long       idx           = FAIL;/* Swath index                     */
  
  char       errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer    */
  hid_t      ntype;
  
  HE5_LOCK;
  CHECKPOINTER(fieldname);
  CHECKNAME(attrname);
  CHECKPOINTER(count);
  CHECKPOINTER(datbuf);
  
  /* 
     if numtype is HE5 numbertype, rather than H5 numbertype, then convert
     it, otherwise use ntype itself
  */
  ntype = HE5_EHconvdatatype(numtype);
  if(ntype == FAIL)
    {
      ntype = numtype;
    }
  
  /*
**********************************************************
*  Check for proper swath ID and return HDF-EOS file ID,  * 
*        "HDFEOS" group ID and Swath index                *  
**********************************************************
*/
  status = HE5_SWchkswid(swathID, "HE5_SWwritedscaleattr", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      
      /* Get field ID */
      /* ------------ */
      fieldID = H5Dopen(HE5_SWXSwath[idx].sw_id, fieldname);
      if(fieldID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"%s\" field dataset ID.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWwritedscaleattr", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
      
      /* Call EHattr to perform I/O */
      /* -------------------------- */
      status = HE5_EHattr(fieldID, attrname, ntype, count,"w", datbuf);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot write Attribute \"%s\" for the \"%s\" field.\n", attrname, fieldname);
	  H5Epush(__FILE__, "HE5_SWwritedscaleattr", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
      
      status = H5Dclose(fieldID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"%s\" field dataset ID.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWwritedscaleattr", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}	
    }
  
 COMPLETION:
  HE5_UNLOCK;
  return (status);
}
/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdscaleattrinfo                                             |
|                                                                             |
|  DESCRIPTION: Retrieves information about dimension scale attribute         |
|               (attribute associated with a specified dimension scale field) |
|                in a swath.                                                  |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t     None      HDF-EOS type swath  ID                  |
|  fieldname      char*               field name                              |
|  attrname       char*               attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  ntype          hid_t               attribute data type ID                  |
|  count          hsize_t             Number of attribute elements            |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  May 10   Abe Taaheri   Original Development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t 
HE5_SWdscaleattrinfo(hid_t swathID, const char *fieldname, const char *attrname, hid_t *ntype, hsize_t *count)
{
  herr_t     status        = FAIL;/* routine return status variable */
  hsize_t    *bufsize      = (hsize_t *)NULL;
  char       errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer    */
    
  status = HE5_SWdscaleattrinfo2(swathID, fieldname, attrname, ntype, count, bufsize);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot retrieve information about Attribute \"%s\" \n", attrname);
      H5Epush(__FILE__, "HE5_SWdscaleattrinfo", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }
  return(status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdscaleattrinfo2                                            |
|                                                                             |
|  DESCRIPTION: Retrieves information about dimension scale attribute         |
|               (attribute associated with a specified dimension scale field) |
|                in a swath.                                                  |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t     None      HDF-EOS type swath  ID                  |
|  fieldname      char*               field name                              |
|  attrname       char*               attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  ntype          hid_t               attribute data type ID                  |
|  count          hsize_t             Number of attribute elements            |
|  size           hsize_t             size of attribute elements              |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  May 10   Abe Taaheri   Original Development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t 
  HE5_SWdscaleattrinfo2(hid_t swathID, const char *fieldname, const char *attrname, hid_t *ntype, hsize_t *count, hsize_t *size)
{
  herr_t     status        = FAIL;/* routine return status variable */
  
  hid_t      fid           = FAIL;/* HDF-EOS file ID                */
  hid_t      gid           = FAIL;/* "HDFEOS" group ID              */
  hid_t      fieldID       = FAIL;/* Field-related dataset ID       */
  
  long       idx           = FAIL;/* Swath index                     */
  
  char       errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer    */
  
  CHECKPOINTER(fieldname);
  CHECKPOINTER(attrname);
  
  /*
**********************************************************
*  Check for proper swath ID and return HDF-EOS file ID,  * 
*        "HDFEOS" group ID and Swath index                *  
**********************************************************
*/
  status = HE5_SWchkswid(swathID, "HE5_SWdscaleattrinfo", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Get field ID */
      /* ------------ */
      fieldID = H5Dopen(HE5_SWXSwath[idx].sw_id, fieldname);
      if(fieldID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"%s\" field dataset ID.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWdscaleattrinfo", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
      
      /* Call EHattrinfo */
      /* --------------- */
      if(strcmp(attrname,"REFERENCE_LIST") !=0)/* do not need ntype for 
						  internal dimension
						  scale attribute */
	{
	  status = HE5_EHattrinfo(fieldID, attrname, ntype, count);
	  if(status == FAIL)
	    {
	      sprintf(errbuf,"Cannot retrieve information about Attribute \"%s\" associated with the \"%s\" field.\n", attrname, fieldname);
	      H5Epush(__FILE__, "HE5_SWdscaleattrinfo", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }
	}
      else
	{
	  status = -1;
	  *ntype = -1;
	  *count = 0;
	  sprintf(errbuf,"Will not retrieve information about internal Attribute \"%s\" associated with the dimension scale \"%s\" .\n", attrname, fieldname);
	  H5Epush(__FILE__, "HE5_SWdscaleattrinfo", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}

      status = H5Dclose(fieldID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"%s\" field dataset ID.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWdscaleattrinfo", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}	
    }

 COMPLETION:
  return (status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdiminfo                                                    |
|                                                                             |
|  DESCRIPTION: Returns size in bytes of named dimension                      |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  size           hsize_t             Size of dimension                       |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  dimname        char                Dimension name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  3/18/99                                                                    |
|  7/28/99  A.Muslimov    In the call to EHmetagroup() replaced gid by fid    |
|                         (file ID).                                          |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Apr  01  A.Muslimov    Initialized size to 0, but "Unlim" returns -1!,not 0|
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
hsize_t
HE5_SWdiminfo(hid_t swathID, char *dimname)
{
  hsize_t       size                = 0;   /* Dimension size (return value) */
  
  herr_t        status              = FAIL;/* status variable               */
  
  hid_t         fid                 = FAIL;/* HDF-EOS file ID               */
  hid_t         gid                 = FAIL;/* "HDFEOS" group ID             */
  
  long          idx                 = FAIL;/* Swath index                   */
  
  char          *metabuf=(char *)NULL;      /* Ptr to StrucMetadata (SM)    */
  char          *metaptrs[2]={NULL,NULL};   /* Ptrs to the start/end of SM  */
  char          utlstr[HE5_HDFE_UTLBUFSIZE];/* Utility string buffer        */
  char          errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer         */
  
  
  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWdiminfo", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Get pointers to "Dimension" section within SM */
      /* --------------------------------------------- */
      metabuf = (char *)HE5_EHmetagroup(fid, HE5_SWXSwath[idx].swname, "s", "Dimension", metaptrs);

      /* Search for dimension name (surrounded by quotes) */
      /* ------------------------------------------------ */
      sprintf(utlstr, "%s%s%s", "\"", dimname, "\"\n");
      metaptrs[0] = strstr(metaptrs[0], utlstr);

      /*
       * If dimension found within swath structure then get dimension value
       */
      if (metaptrs[0] < metaptrs[1] && metaptrs[0] != NULL)
        {
	  /* Set "end" ptr at the end of dimension definition entry */
	  /* ------------------------------------------------------ */
	  metaptrs[1] = strstr(metaptrs[0], "\t\t\tEND_OBJECT");
		  
	  /* Get the value of "Size" entry */
	  /* ----------------------------- */
	  status = HE5_EHgetmetavalue(metaptrs, "Size", utlstr);
	  if (status == SUCCEED)
	    {
	      size = atol(utlstr);
	      if (size == 0)
		{
		  sprintf(errbuf, "Returning zero \"Size\" value from Metadata.\n");
		  H5Epush(__FILE__, "HE5_SWdiminfo", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		}
	    }
	  else
            {
	      sprintf(errbuf, "The \"Size\" string not found in metadata. \n");
	      H5Epush(__FILE__, "HE5_SWdiminfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
        }
      else
        {
	  sprintf(errbuf, "The Dimension \"%s\" not found in metadata. \n", dimname);
	  H5Epush(__FILE__, "HE5_SWdiminfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
        }
		
      if (metabuf != NULL) free(metabuf);
    }
  
  return(size);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWmapinfo                                                    |
|                                                                             |
|  DESCRIPTION: Returns dimension mapping information                         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  geodim         char                geolocation dimension name              |
|  datadim        char                data dimension name                     |
|                                                                             |
|  OUTPUTS:                                                                   |
|  offset         long                mapping offset                          |
|  increment      long                mapping increment                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|                                                                             |
|  7/29/99  A.Muslimov    In the call to EHmetagroup() replace gid by fid.    |
|  8/20/99  A.Muslimov    Initialized statuses to -1. Disabled the last error |
|                         message:                                            |
|                         " sprintf(errbuf,                                   |
|                           "Mapping \"%s/%s\"not found.", geodim, datadim) ".|
|                         This error message shouldn't be issued, because     |
|                         the functions SWextractregion() and SWregioninfo()  |
|                         that call SWmapinfo() issue a proper error message  |
|                         upon receiving the error status = -1 from           |
|                         SWmapinfo().                                        |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t 
HE5_SWmapinfo(hid_t swathID, char *geodim, char *datadim, long *offset, long *increment)
{
  herr_t         status   = FAIL;	  /* Routine return status variable */
  herr_t         statmeta = FAIL;	  /* EHgetmetavalue return status   */

  hid_t          fid      = FAIL;	  /* HDF-EOS file ID                */
  hid_t          gid      = FAIL;	  /* "HDFEOS" group ID              */

  long           idx      = FAIL;	  /* Swath index                    */

  char           *metabuf    = (char *)NULL; /* Ptr to StrucMetadata    */
  char           *metaptrs[2]={NULL,NULL};   /* Ptrs to start/end of SM */
  char           utlstr[HE5_HDFE_UTLBUFSIZE];/* Utility string buffer   */
  char           errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer    */

  CHECKPOINTER(geodim);
  CHECKPOINTER(datadim);

  /* Initialize return values */
  /* ------------------------ */
  *offset    = FAIL;
  *increment = FAIL;


  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWmapinfo", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Get pointers to "DimensionMap" section within SM */
      /* ------------------------------------------------ */
      metabuf = (char *)HE5_EHmetagroup(fid, HE5_SWXSwath[idx].swname, "s", "DimensionMap", metaptrs);

      /* Search for mapping - GeoDim/DataDim (surrounded by quotes) */
      /* ---------------------------------------------------------- */
      sprintf(utlstr, "%s%s%s%s%s", "\t\t\t\tGeoDimension=\"", geodim, "\"\n\t\t\t\tDataDimension=\"", datadim, "\"\n");
      metaptrs[0] = strstr(metaptrs[0], utlstr);

      /*
       * If mapping found within swath structure then get offset and
       * increment value
       */
      if (metaptrs[0] < metaptrs[1] && metaptrs[0] != NULL)
        {
	  /* Get Offset */
	  /* ---------- */
	  statmeta = HE5_EHgetmetavalue(metaptrs, "Offset", utlstr);
	  if (statmeta == SUCCEED)
	    *offset = atol(utlstr);
	  else
            {
	      status = FAIL;
	      sprintf(errbuf, "The \"Offset\" string not found in metadata. \n");
	      H5Epush(__FILE__, "HE5_SWmapinfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
            }


	  /* Get Increment */
	  /* ------------- */
	  statmeta = HE5_EHgetmetavalue(metaptrs, "Increment", utlstr);
	  if (statmeta == SUCCEED)
	    *increment = atol(utlstr);
	  else
            {
	      status = FAIL;
	      H5Epush(__FILE__, "HE5_SWmapinfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, "The \"Increment\" string not found in metadata. \n");
	      HE5_EHprint("Error: The \"Increment\" string not found in metadata, occured", __FILE__, __LINE__);
            }
        }
      else
        {
	  status = FAIL;
        }

      if (metabuf != NULL) free(metabuf);
    }

 COMPLETION:  
  return(status);
}




/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWidxmapinfo                                                 |
|                                                                             |
|  DESCRIPTION: Returns indexed mapping information                           |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  gsize          hsize_t             Number of index values (sz of geo dim)  |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  geodim         char                geolocation dimension name              |
|  datadim        char                data dimension name                     |
|                                                                             |
|  OUTPUTS:                                                                   |
|  index          long                array of index values                   |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  02/08/00 A.Muslimov    Initialized gsize to -1, and added more error       |
|                          checkings.                                         |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  7/12/00  A.Muslimov    Added conversion from disk/file data type ID to     |
|                          memory data type ID before H5Dread() call.         |
|  Apr  01  A.Muslimov    Initialized gsize to 0, but "Unlim" returns -1!,    |
|                          not 0.                                             |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
hsize_t
HE5_SWidxmapinfo(hid_t swathID, char *geodim, char *datadim, long index[])
{
  hsize_t         gsize    = 0;   /* Size of geo dim (return)     */

  herr_t          status   = FAIL;/* Status variable              */

  hid_t           fid      = FAIL;/* HDF-EOS file ID              */
  hid_t           sw_id    = FAIL;/* Swath Attributes group ID    */
  hid_t           gid      = FAIL;/* "HDFEOS" group ID            */
  hid_t           id       = FAIL;/* Dataset ID                   */
  hid_t	          tid      = FAIL;/* File/Disk data type ID       */
  hid_t           mid      = FAIL;/* Memory data type ID          */

  long            idx      = FAIL;/* Swath index                  */

  char            utlbuf[HE5_HDFE_DIMBUFSIZE];/* Utility buffer   */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error buffer     */

  CHECKPOINTER(geodim);
  CHECKPOINTER(datadim);

  /* if field is empty bail out */
  if(strcmp(geodim,"") == 0)
    {
      sprintf(errbuf,"The geolocation dimension name \"%s\" is null.. \n", geodim);
      H5Epush(__FILE__, "HE5_SWidxmapinfo", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(gsize);
    }

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWidxmapinfo", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Find Index Mapping dataset  */
      /* --------------------------  */
      sprintf(utlbuf, "%s%s%s%s", "_INDEXMAP:", geodim, ",", datadim);
      sw_id = HE5_SWXSwath[idx].sw_id;
	  
      /* Open dataset "INDEXMAP:geodim,datadim" in swath group */
      /* ----------------------------------------------------- */
      id = H5Dopen(sw_id, utlbuf);
      if( id == FAIL )
        {
	  sprintf(errbuf,"The \"%s\" dataset not found. \n", utlbuf);
	  H5Epush(__FILE__, "HE5_SWidxmapinfo", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
        }
	  
      /* Get geodim size & read index mapping values */
      /* ------------------------------------------- */
      else
        {
	  /* Get data type ID */
	  /* ---------------- */
	  tid    = H5Dget_type(id);
	  if (tid == FAIL)
	    {
	      sprintf(errbuf, "Cannot get the data type ID. \n") ;
	      H5Epush(__FILE__, "HE5_SWidxmapinfo", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);

	      return(gsize);
	    }
          
	  /* Get memory data type ID */
	  /* ----------------------- */
	  mid    = HE5_EHdtype2mtype(tid);
	  if (mid == FAIL)
	    {
	      sprintf(errbuf, "Cannot convert to memory data type. \n") ;
	      H5Epush(__FILE__, "HE5_SWidxmapinfo", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
			  
	      return(gsize);
	    }

	  /* Read the dataset */
	  /* ---------------- */
	  status = H5Dread( id,mid , H5S_ALL, H5S_ALL, H5P_DEFAULT, index); 
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot read out the data. \n") ;
	      H5Epush(__FILE__, "HE5_SWidxmapinfo", __LINE__, H5E_DATASET, H5E_READERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
			  
	      return(gsize);
	    }
		  
	  /* Release the datatype ID */
	  /* ----------------------- */
	  status = H5Tclose(tid);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot release the data type ID. \n") ;
	      H5Epush(__FILE__, "HE5_SWidxmapinfo", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
			  
	      return(gsize);
	    }
		  
	  /* Release the dataset ID */
	  /* ---------------------- */
	  status = H5Dclose(id);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot release the dataset ID. \n") ;
	      H5Epush(__FILE__, "HE5_SWidxmapinfo", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
			  
	      return(gsize);
	    }

	  gsize = HE5_SWdiminfo(swathID, geodim);
	  if (gsize == 0)
	    {
	      sprintf(errbuf, "Failed to retrieve the size of \"%s\" dimension. \n", geodim) ;
	      H5Epush(__FILE__, "HE5_SWidxmapinfo", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
        }
    }
  
 COMPLETION:
  return (gsize);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWcompinfo                                                   |
|                                                                             |
|  DESCRIPTION:                                                               |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t  None        Return status  (0) SUCCEED, (-1) FAIL   |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t   None        Swath Object ID                         |
|  compcode       int                                                         |
|  compparm       int                                                         |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  7/29/99  A.Muslimov    In the call to EHmetagroup() replace gid by fid.    |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Oct  00  A.Muslimov    Added the case where fieldname is an alias, and     |
|                          updated to include profile dataset.                |
|  Dec  00  A.Muslimov    Updated to include retrieving compression related   |
|                          metadata information for profile.                  |
|  Aug  03  S.Zhao        Added Szip compression methods.                     |
|  Dec  13  Abe Taaheri   Added compression detection from field, if it is    |
|                          not found from the structure metadata              |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t 
HE5_SWcompinfo(hid_t swathID, char *fldname, int *compcode, int compparm[])
{
  herr_t          status   = FAIL;                   /* Return status variable      */
  herr_t          statmeta = FAIL;                   /* Status variable             */

  int             i;			             /* Loop Index                  */
  int             nameflag = FAIL;                   /* Name flag (0-alias,1-actual)*/
  int             fldgroup = FAIL;                   /* Field group flag            */

  hid_t           fid      = FAIL;                   /* HDF-EOS file ID             */
  hid_t           gid      = FAIL;                   /* "HDFEOS" group ID           */

  long            idx      = FAIL;                   /* Swath index                 */
  long            idOffset   = HE5_SWIDOFFSET;       /* HDF-EOS Grid ID offset      */
  char            fieldname[HE5_HDFE_NAMBUFSIZE];    /* Field name buffer           */ 
  char            fldactualname[HE5_HDFE_NAMBUFSIZE];/* Actual name of a field      */ 
  char            *metabuf = (char *)NULL;           /* Pntr to StrucMetadata (SM)  */
  char            *metaptrs[2]={NULL,NULL};          /* Ptrs to the start/end of SM */
  char            *utlstr = (char *)NULL;            /* Utility string buffer       */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];       /* Error message buffer        */
  hid_t           sdid,dcpl;
  size_t          nelmts;
  unsigned int    flags,filter_info;
  int             got_compparm = 0;
  int             found = 0;
  int             numfilt;
  hid_t           plist_id;
  int             done_loop = 0;
  H5Z_filter_t    filter_type;

  char            *HDFcomp[18] = {"HE5_HDFE_COMP_NONE", "HE5_HDFE_COMP_RLE", "HE5_HDFE_COMP_NBIT", "HE5_HDFE_COMP_SKPHUFF", "HE5_HDFE_COMP_DEFLATE", "HE5_HDFE_COMP_SZIP_CHIP", "HE5_HDFE_COMP_SZIP_K13", "HE5_HDFE_COMP_SZIP_EC", "HE5_HDFE_COMP_SZIP_NN", "HE5_HDFE_COMP_SZIP_K13orEC", "HE5_HDFE_COMP_SZIP_K13orNN", "HE5_HDFE_COMP_SHUF_DEFLATE", "HE5_HDFE_COMP_SHUF_SZIP_CHIP", "HE5_HDFE_COMP_SHUF_SZIP_K13", "HE5_HDFE_COMP_SHUF_SZIP_EC", "HE5_HDFE_COMP_SHUF_SZIP_NN", "HE5_HDFE_COMP_SHUF_SZIP_K13orEC", "HE5_HDFE_COMP_SHUF_SZIP_K13orNN"};  /* Compression method Codes    */


  CHECKPOINTER(fldname);
  
  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWcompinfo", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Allocate space for utility string */
      /* --------------------------------- */
      utlstr = (char *)calloc(HE5_HDFE_DIMBUFSIZE, sizeof(char));
      if ( utlstr == NULL )
	{
	  sprintf( errbuf,"Cannot allocate memory for utility string.\n");
	  H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  
	  return(FAIL);
	}

      /* Call HE5_SWfldnameinfo() to get actual field name */
      /* ------------------------------------------------- */
      nameflag = HE5_SWfldnameinfo(swathID, fldname, fldactualname);
      if ( nameflag == FAIL )
	{
	  sprintf(errbuf, "Cannot get the actual name of the field.\n");
	  H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  if (utlstr != NULL) free(utlstr);
	  return(FAIL);
	}
  
      /* If fieldname is alias, then change it to the actual name */
      /* -------------------------------------------------------- */
      if (nameflag == FALSE)
	{
	  strcpy(fieldname,"");
	  strcpy(fieldname,fldactualname);
	}

      if (nameflag == TRUE)
	{
	  strcpy(fieldname,"");
	  strcpy(fieldname,fldname);
	}

      /* Get the field group code */
      /* ------------------------ */
      fldgroup = HE5_SWfldsrch(swathID,fieldname,NULL,NULL,NULL,NULL);
      if (fldgroup == HE5_HDFE_DATAGROUP)
	{
	  /* Get pointers to "DataField" section within SM */
	  /* --------------------------------------------- */
	  metabuf = (char *)HE5_EHmetagroup(fid, HE5_SWXSwath[idx].swname, "s", "DataField", metaptrs);
		  
	  /* Search for field */
	  /* ---------------- */
	  sprintf(utlstr, "%s%s%s", "\"", fieldname, "\"\n");
	  metaptrs[0] = strstr(metaptrs[0], utlstr);
	  
	}
      else if (fldgroup == HE5_HDFE_GEOGROUP)
	{
	  /* Search in "GeoField" section */
	  /* ---------------------------- */
	  if (metaptrs[0] > metaptrs[1] || metaptrs[0] == NULL)
	    {
	      /* Get pointers to "GeoField" section within SM */
	      /* -------------------------------------------- */
	      metabuf = (char *)HE5_EHmetagroup(fid, HE5_SWXSwath[idx].swname, "s","GeoField", metaptrs);
			  
	      /* Search for field */
	      /* ---------------- */
	      sprintf(utlstr, "%s%s%s", "\"", fieldname, "\"\n");
	      metaptrs[0] = strstr(metaptrs[0], utlstr);
	    }
	}
      else if (fldgroup == HE5_HDFE_PROFGROUP)
	{

	  /* Get pointers to "ProfileField" section within SM */
	  /* ------------------------------------------------ */
	  metabuf = (char *)HE5_EHmetagroup(fid, HE5_SWXSwath[idx].swname, "s", "ProfileField", metaptrs);
		  
	  /* Search for profile */
	  /* ------------------ */
	  sprintf(utlstr, "%s%s%s", "\"", fieldname, "\"\n");
	  metaptrs[0] = strstr(metaptrs[0], utlstr);
	}
      else
	{
	  sprintf(errbuf , "Cannot get the field group code.\n");
	  H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  if (metabuf != NULL) free(metabuf);
	  if (utlstr != NULL) free(utlstr);
	  return(FAIL);
	}

	  
      /* If field found and user wants compression code ... */
      /* -------------------------------------------------- */
      if (metaptrs[0] < metaptrs[1] && metaptrs[0] != NULL)
	{
	  if (compcode != NULL)
	    {
	      /* Set endptr at end of field's definition entry */
	      /* --------------------------------------------- */
	      metaptrs[1] = strstr(metaptrs[0], "\t\t\tEND_OBJECT");
			  
	      /* Get compression type */
	      /* -------------------- */
	      statmeta = HE5_EHgetmetavalue(metaptrs, "CompressionType", utlstr);
			  
	      /*
	       * Default is no compression if "CompressionType" string not
	       * in metadata
	       */
	      *compcode = HE5_HDFE_COMP_NONE;
			  
	      /* If compression code is found ... */
	      /* -------------------------------- */
	      if (statmeta == SUCCEED)
		{
		  /* Loop through compression types until match */
		  /* ------------------------------------------ */
		  for (i = 0; i < 18; i++)
		    {
		      if (strcmp(utlstr, HDFcomp[i]) == 0)
			{
			  *compcode = i;
			  break;
			}
		    }
		}
	    }
			  
	  /* If user wants compression parameters ... */
	  
	  /* Compression is not listed in the structure metadata. 
	     Lets see if the field is compressed by other means such 
	     as herepack where the compression is done but does not 
	     show up in the structure metadata.
	  */
	  got_compparm = 0;
	  if(*compcode == HE5_HDFE_COMP_NONE)
	    {
	      if (HE5_SWXSwath[swathID % idOffset].active != 0)
		{
		  /* Get Swath index */
		  /* -------------- */
		  idx = HE5_EHhid2long(swathID) % idOffset;
		  if ( idx == FAIL)
		    {
		      status = FAIL;
		      sprintf(errbuf, "Cannot get the Swath index \n");
		      H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf) ;
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		    }
		}
	      /* Loop through all datasets in swath */
	      /* ------------------------------ */
	      for (i = 0; i < HE5_SWXSwath[idx].nDFLD; i++)
		{
		  /* Get dataset name */
		  if( strcmp(fieldname, HE5_SWXSwath[ idx ].ddataset[ i ].name) == 0 )
		    {
		      found = 1; 
		      sdid = HE5_SWXSwath[ idx ].ddataset[ i ].ID;
		      break;
		    } 
		}
	      
	      if(found == 1) /* did not find fieldname */
		{
		  /*
		   * Retrieve dataset creation property list.
		   */
		  dcpl = H5Dget_create_plist (sdid); 
		  numfilt = H5Pget_nfilters (plist_id);
		  
		  done_loop = 0;	      
		  for (i=0; i<numfilt; i++) {
		    nelmts = 0;
		    filter_type = H5Pget_filter2 (plist_id, (unsigned)i, &flags, &nelmts, 
						  NULL, 0, NULL,
						  &filter_info);
		    switch(filter_type)
		      {
			/*-------------------------------------------------------------------------
			 * H5Z_FILTER_DEFLATE      1 , deflation like gzip
			 *-------------------------------------------------------------------------
			 */
		      case H5Z_FILTER_DEFLATE:
			if(numfilt == 1)
			  {
			    *compcode = 4; /* HE5_HDFE_COMP_DEFLATE */
			    compparm[0] = 6; /* default value */
			    done_loop = 1;
			  }
			else
			  {
			    *compcode = 11; /* HE5_HDFE_COMP_SHUF_DEFLATE */
			    compparm[0] = 6; /* default value */
			    done_loop = 1;
			  }
			break;
			/*-------------------------------------------------------------------------
			 * H5Z_FILTER_NBIT
			 *-------------------------------------------------------------------------
			 */
		      case H5Z_FILTER_NBIT:
			*compcode = 2; /* HE5_HDFE_COMP_NBIT */
			/* Initialize to zero */
			for (i = 0; i < 4; i++)
			  {
			    compparm[i] = 0.0;
			  }
			done_loop = 1;
			break;
			/*-------------------------------------------------------------------------
			 * H5Z_FILTER_SZIP       4 , szip compression
			 *-------------------------------------------------------------------------
			 */
		      case H5Z_FILTER_SZIP:
			if(numfilt == 1)
			  {
			    *compcode = 7; /* HE5_HDFE_COMP_SZIP_CHIP */
			    compparm[0] = 16;
			    compparm[1] = 4;  /* SZ_EC */
			    done_loop = 1;
			  }
			else
			  {
			    *compcode = 8; /* HE5_HDFE_COMP_SZIP_K13 */
			    compparm[0] = 16;
			    compparm[1] = 32;  /* SZ_NN */
			    done_loop = 1;
			  }
			break;
			/*-------------------------------------------------------------------------
			 * H5Z_FILTER_SHUFFLE    2 , shuffle the data
			 *-------------------------------------------------------------------------
			 */
		      case H5Z_FILTER_SHUFFLE:
			if(numfilt == 2)
			  {
			    *compcode = 11; /* HE5_HDFE_COMP_SHUF_DEFLATE */
			    compparm[0] = 6;
			    done_loop = 1;
			  }
			else if(numfilt > 2)
			  {
			    *compcode = 12; /* HE5_HDFE_COMP_SHUF_SZIP_CHIP */
			    compparm[0] = 16;
			    done_loop = 1;
			  }
			break;
			/*-------------------------------------------------------------------------
			 * H5Z_FILTER_FLETCHER32 3 , fletcher32 checksum of EDC
			 *-------------------------------------------------------------------------
			 */
		      case H5Z_FILTER_FLETCHER32:
			done_loop =  1;
			break;
			
			/*-------------------------------------------------------------------------
			 * H5Z_FILTER_SCALEOFFSET
			 *-------------------------------------------------------------------------
			 */
		      case H5Z_FILTER_SCALEOFFSET:
			done_loop =  1;
			break;
		      }/*switch*/
		    if(done_loop ==  1) break;
		  }/*for*/
		}
	      got_compparm = 1;
	    }	  
	  
	  /* If user wants compression parameters ... */
	  /* ---------------------------------------- */
	  if (compparm != NULL && compcode != NULL && got_compparm != 1)
	    {
	      /* Initialize to zero */
	      /* ------------------ */
	      for (i = 0; i < 5; i++)
		compparm[i] = 0;
			  
	      /* Get compression parameters */
	      /* -------------------------- */
	      if (*compcode == HE5_HDFE_COMP_NBIT)
		{
		  statmeta = HE5_EHgetmetavalue(metaptrs, "CompressionParams", utlstr);
		  if (statmeta == SUCCEED)
		    {
		      sscanf(utlstr, "(%d,%d,%d,%d)", &compparm[0], &compparm[1], &compparm[2], &compparm[3]);
		    }
		  else
		    {
		      status = FAIL;
		      sprintf( errbuf,"\"CompressionParams\" string not found in metadata.\n");
		      H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		    }
		}
	      else if (*compcode == HE5_HDFE_COMP_DEFLATE)
		{
		  statmeta = HE5_EHgetmetavalue(metaptrs, "DeflateLevel", utlstr);
		  if (statmeta == SUCCEED)
		    {
		      sscanf(utlstr, "%d", &compparm[0]);
		    }
		  else
		    {
		      status = FAIL;
		      sprintf( errbuf,"The \"DeflateLevel\" string not found in metadata.\n");
		      H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		    }
		}
	      else if (*compcode == HE5_HDFE_COMP_SZIP_CHIP)
		{
		  statmeta = HE5_EHgetmetavalue(metaptrs, "BlockSize", utlstr);
		  if (statmeta == SUCCEED)
		    {
		      sscanf(utlstr, "%d", &compparm[0]);
		    }
		  else
		    {
		      status = FAIL;
		      sprintf( errbuf,"The \"BlockSize\" string not found in metadata.\n");
		      H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		    }
		}
	      else if (*compcode == HE5_HDFE_COMP_SZIP_K13)
		{
		  statmeta = HE5_EHgetmetavalue(metaptrs, "BlockSize", utlstr);
		  if (statmeta == SUCCEED)
		    {
		      sscanf(utlstr, "%d", &compparm[0]);
		    }
		  else
		    {
		      status = FAIL;
		      sprintf( errbuf,"The \"BlockSize\" string not found in metadata.\n");
		      H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		    }
		}
	      else if (*compcode == HE5_HDFE_COMP_SZIP_EC)
		{
		  statmeta = HE5_EHgetmetavalue(metaptrs, "BlockSize", utlstr);
		  if (statmeta == SUCCEED)
		    {
		      sscanf(utlstr, "%d", &compparm[0]);
		    }
		  else
		    {
		      status = FAIL;
		      sprintf( errbuf,"The \"BlockSize\" string not found in metadata.\n");
		      H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		    }
		}
	      else if (*compcode == HE5_HDFE_COMP_SZIP_NN)
		{
		  statmeta = HE5_EHgetmetavalue(metaptrs, "BlockSize", utlstr);
		  if (statmeta == SUCCEED)
		    {
		      sscanf(utlstr, "%d", &compparm[0]);
		    }
		  else
		    {
		      status = FAIL;
		      sprintf( errbuf,"The \"BlockSize\" string not found in metadata.\n");
		      H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		    }
		}
	      else if (*compcode == HE5_HDFE_COMP_SZIP_K13orEC)
		{
		  statmeta = HE5_EHgetmetavalue(metaptrs, "BlockSize", utlstr);
		  if (statmeta == SUCCEED)
		    {
		      sscanf(utlstr, "%d", &compparm[0]);
		    }
		  else
		    {
		      status = FAIL;
		      sprintf( errbuf,"The \"BlockSize\" string not found in metadata.\n");
		      H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		    }
		}
	      else if (*compcode == HE5_HDFE_COMP_SZIP_K13orNN)
		{
		  statmeta = HE5_EHgetmetavalue(metaptrs, "BlockSize", utlstr);
		  if (statmeta == SUCCEED)
		    {
		      sscanf(utlstr, "%d", &compparm[0]);
		    }
		  else
		    {
		      status = FAIL;
		      sprintf( errbuf,"The \"BlockSize\" string not found in metadata.\n");
		      H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		    }
		}
	      else if (*compcode == HE5_HDFE_COMP_SHUF_DEFLATE)
		{
		  statmeta = HE5_EHgetmetavalue(metaptrs, "DeflateLevel", utlstr);
		  if (statmeta == SUCCEED)
		    {
		      sscanf(utlstr, "%d", &compparm[0]);
		    }
		  else
		    {
		      status = FAIL;
		      sprintf( errbuf,"The \"DeflateLevel\" string not found in metadata.\n");
		      H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		    }
		}
	      else if (*compcode == HE5_HDFE_COMP_SHUF_SZIP_CHIP)
		{
		  statmeta = HE5_EHgetmetavalue(metaptrs, "BlockSize", utlstr);
		  if (statmeta == SUCCEED)
		    {
		      sscanf(utlstr, "%d", &compparm[0]);
		    }
		  else
		    {
		      status = FAIL;
		      sprintf( errbuf,"The \"BlockSize\" string not found in metadata.\n");
		      H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		    }
		}
	      else if (*compcode == HE5_HDFE_COMP_SHUF_SZIP_K13)
		{
		  statmeta = HE5_EHgetmetavalue(metaptrs, "BlockSize", utlstr);
		  if (statmeta == SUCCEED)
		    {
		      sscanf(utlstr, "%d", &compparm[0]);
		    }
		  else
		    {
		      status = FAIL;
		      sprintf( errbuf,"The \"BlockSize\" string not found in metadata.\n");
		      H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		    }
		}
	      else if (*compcode == HE5_HDFE_COMP_SHUF_SZIP_EC)
		{
		  statmeta = HE5_EHgetmetavalue(metaptrs, "BlockSize", utlstr);
		  if (statmeta == SUCCEED)
		    {
		      sscanf(utlstr, "%d", &compparm[0]);
		    }
		  else
		    {
		      status = FAIL;
		      sprintf( errbuf,"The \"BlockSize\" string not found in metadata.\n");
		      H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		    }
		}
	      else if (*compcode == HE5_HDFE_COMP_SHUF_SZIP_NN)
		{
		  statmeta = HE5_EHgetmetavalue(metaptrs, "BlockSize", utlstr);
		  if (statmeta == SUCCEED)
		    {
		      sscanf(utlstr, "%d", &compparm[0]);
		    }
		  else
		    {
		      status = FAIL;
		      sprintf( errbuf,"The \"BlockSize\" string not found in metadata.\n");
		      H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		    }
		}
	      else if (*compcode == HE5_HDFE_COMP_SHUF_SZIP_K13orEC)
		{
		  statmeta = HE5_EHgetmetavalue(metaptrs, "BlockSize", utlstr);
		  if (statmeta == SUCCEED)
		    {
		      sscanf(utlstr, "%d", &compparm[0]);
		    }
		  else
		    {
		      status = FAIL;
		      sprintf( errbuf,"The \"BlockSize\" string not found in metadata.\n");
		      H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		    }
		}
	      else if (*compcode == HE5_HDFE_COMP_SHUF_SZIP_K13orNN)
		{
		  statmeta = HE5_EHgetmetavalue(metaptrs, "BlockSize", utlstr);
		  if (statmeta == SUCCEED)
		    {
		      sscanf(utlstr, "%d", &compparm[0]);
		    }
		  else
		    {
		      status = FAIL;
		      sprintf( errbuf,"The \"BlockSize\" string not found in metadata.\n");
		      H5Epush(__FILE__, "HE5_SWcompinfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		    }
		}

	    }
		  
	}


      if (metabuf != NULL) free(metabuf);
      if (utlstr != NULL) free(utlstr);
    }

 COMPLETION:
  return(status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWfldnameinfo                                                |
|                                                                             |
|  DESCRIPTION: Retrieves actual name of the field                            |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nameFlag       int     None        return (1) actual name, (0) alias,      |
|                                                (-1) FAIL                    |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  fieldname      char                name of field                           |
|                                                                             |
|  OUTPUTS:                                                                   |
|  actualname     char                field actual name                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Oct 00   A.Muslimov    Original development.                               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
static int
HE5_SWfldnameinfo(hid_t swathID, char *fieldname, char *actualname)
{
  int         nameFlag       = FAIL;/* Return value of flag            */
  int         length         = 0;   /* String length                   */
  int         fldgroup       = FAIL;/* Field group code                */

  hid_t       fid            = FAIL;/* HDF-EOS file ID                 */
  hid_t       gid            = FAIL;/* "HDFEOS" group ID               */
  hid_t       groupID        = FAIL;/* data/geo/prof fields group ID   */

  long        idx            = FAIL;/* Swath index                     */

  H5G_stat_t  *statbuf = (H5G_stat_t *)NULL;/* buffer for link info    */

  herr_t      status         = FAIL;/* routine return status variable  */

  char        *namebuf       = NULL;/* Buffer for an actual field name */
  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer      */
   
  CHECKPOINTER(fieldname); 
  
  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWfldnameinfo", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for Swath ID failed.\n");
      H5Epush(__FILE__, "HE5_SWfldnameinfo", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  statbuf = (H5G_stat_t *)calloc(1, sizeof(H5G_stat_t ));

  /* Try to get information about specified field */
  /* -------------------------------------------- */
  H5E_BEGIN_TRY {
    groupID  = HE5_SWXSwath[idx].data_id;
    fldgroup = HE5_HDFE_DATAGROUP;
    status   = H5Gget_objinfo(groupID, fieldname, 0, statbuf);
  }
  H5E_END_TRY;
  if (status == FAIL)
    {
      H5E_BEGIN_TRY {
	groupID  = HE5_SWXSwath[idx].geo_id;
	fldgroup = HE5_HDFE_GEOGROUP;
	status   = H5Gget_objinfo(groupID, fieldname, 0, statbuf);
      }
      H5E_END_TRY;
      if (status == FAIL)
	{
	  H5E_BEGIN_TRY {
	    groupID  = HE5_SWXSwath[idx].prof_id;
	    fldgroup = HE5_HDFE_PROFGROUP;
	    status   = H5Gget_objinfo(groupID, fieldname, 0, statbuf);
	  }
	  H5E_END_TRY;
	  if (status == FAIL)
	    {
	      nameFlag = FAIL;
	      sprintf(errbuf, "Cannot find \"%s\" field.\n", fieldname);
	      H5Epush(__FILE__, "HE5_SWfldnameinfo", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(statbuf);
	      return(nameFlag);
	    }
		  
	}

    }
  
  /* If the field name is an alias */
  /* ----------------------------- */
  if (statbuf->type == H5G_LINK)
    nameFlag = FALSE;
  else
    nameFlag = TRUE;

  if (nameFlag == FALSE)
    {	
      if (actualname != NULL)
	{
	  status = HE5_SWaliasinfo(swathID, fldgroup, fieldname, &length, NULL);
	  if ( status == FAIL )
	    {
	      sprintf(errbuf, "Cannot get information about alias \"%s\".\n", fieldname);
	      H5Epush(__FILE__, "HE5_SWfldnameinfo", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(FAIL);
	    }
		  
	  namebuf = (char *)calloc(length, sizeof(char));
	  if ( namebuf == NULL )
	    {
	      sprintf(errbuf, "Cannot allocate memory for namebuf.\n");
	      H5Epush(__FILE__, "HE5_SWfldnameinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(FAIL);
	    }
		 
	  /* Retrieve information about alias */
	  /* -------------------------------- */
	  status = HE5_SWaliasinfo(swathID, fldgroup, fieldname, &length, namebuf);
	  if ( status == FAIL )
	    {
	      sprintf(errbuf, "Cannot get information about alias \"%s\".\n", fieldname);
	      H5Epush(__FILE__, "HE5_SWfldnameinfo", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(namebuf);
	      return(FAIL);
	    }
		  
	  strcpy(actualname,"");
	  strcpy(actualname,namebuf);  
	  free(namebuf);
	}
    }
  
  if (nameFlag == TRUE)
    {
      if (actualname != NULL)
	{
	  strcpy(actualname,"");
	  strcpy(actualname, fieldname);
	}
    }
  
  free(statbuf);

 COMPLETION:  
  return(nameFlag);
} 

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWfinfo                                                      |
|                                                                             |
|  DESCRIPTION: Returns field info                                            |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t  None        return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  fieldtype      char                fieldtype (geo or data)                 |
|  fldname        char                name of field                           |
|                                                                             |
|  OUTPUTS:                                                                   |
|  rank           int                 rank of field (# of dims)               |
|  dims           hsize_t             field dimensions                        |
|  numbertype     hid_t               field number type                       |
|  dimlist        char                field dimension list                    |
|  maxdimlist     char                field maximum dimension list            |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  7/29/99  A.Muslimov    In the call to EHmetagroup() replaced gid by fid.   |
|  7/30/99  A.Muslimov    Added *rank  = H5Sget_simple_extent_ndims(dspace);  |
|                         and checked for error status from H5Sget_simple_\   |
|                         extent_dims() and H5Sclose(). Replaced maxdims      |
|                         parameter by NULL in  H5Sget_simple_extent_dims().  |
|  8/11/99  A.Muslimov    Initialized status to -1 before "Get pointers       |
|                         to appropriate "Field" section within SM ".         |
|                         Moved the lines of code under the comments          |
|                         "Get field ID" and "Get actual dimension size "     |
|                         within the block "if (metaptrs[0] <                 |
|                         metaptrs[1] && metaptrs[0] != NULL) {} " to its end.|
|                         Initialized "statmeta" and "fieldID" to -1.         |
|                         Cleaned up some minor things (mostly cosmetic).     |
| 10/18/99  A.Muslimov    Replaced memcpy() by memmove() to avoid a problem|  |
|                            when arguments 1 and 2 overlap in memory.        |
|                                                                             |
| 01/13/00  A.Muslimov   Added "maxdimlist" parameter to make it possible     |
|                        working with the appendable datasets. Modified the   |
|                        blocks retrieving the dimension lists. Added proper  |
|                        error handlings after the function calls.            |
|02/04/00   A.Muslimov   H5Sget_simple_extent_ndims returns "int", so the     |
|                        data type of rank was changed from int32_t to int.   |
|04/19/00   A.Muslimov   Changed type of 'slen' from long to size_t.          |
| July 00   A.Muslimov   Unmasked hdf5 data types.                            |
|10/02/00   A.Muslimov   Updated to include alias field name.                 |
| June 02   S.Zhao       Changed the type of 'numbertype' from an H5T_class_t |
|                        to an hid_t.                                         |
| Oct. 03   S.Zhao       Added the H5Tclose(datatype) call.                   |
| Oct. 03   S.Zhao       Modified to enable a character string dataset.       |
| Mar  04   S.Zhao       Modified for a character string dataset.             |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
static herr_t
HE5_SWfinfo(hid_t swathID, char *fieldtype, char *fieldname, int *rank, hsize_t dims[], hid_t numbertype[], char *dimlist, char *maxdimlist)
{
  herr_t     status         = FAIL;/* routine return status variable                  */
  herr_t     statmeta       = FAIL;/* EHgetmetavalue return status                    */
  herr_t     Dstatus        = FAIL;/* Status for H5Dclose                             */

  int        groupflag      = FAIL;/* Flag for "Geo... Fields"/"Data Fields" group    */ 
  
  hid_t      fid            = FAIL;/* HDF-EOS file ID                                 */
  hid_t      gid            = FAIL;/* "HDFEOS" group ID                               */
  hid_t      dspace         = FAIL;/* "fieldname" Dataspace ID                        */
  hid_t      fieldID        = FAIL;/* "fieldname" Dataset ID                          */
  hid_t      groupid        = FAIL;/* group ID                                        */
  hid_t      datasetid      = FAIL;/* dataset ID                                      */
  hid_t      datatype       = FAIL;/* data type ID                                    */ 

  H5T_class_t  classid = H5T_NO_CLASS;/* data type class ID                           */
 
  long       ndims          = 0;   /* Number of dimensions                            */
  long       idx            = FAIL;/* Index of a swath                                */
  long       i              = 0;   /* Loop index                                      */

  size_t     slen[HE5_DTSETRANKMAX];            /* Length of each entry in parsed string  */

  char       *metabuf       = (char *)NULL;     /* Ptr to structural metadata (SM)        */
  char       *metaptrs[2]   = {NULL, NULL};     /* Ptrs to the begining and end of SM     */
  char       utlstr[HE5_HDFE_UTLBUFSIZE];       /* Utility string                         */
  char       *ptr[HE5_DTSETRANKMAX];            /* String pointers for parsed string      */
  char       dimstr[HE5_HDFE_DIMBUFSIZE];       /* Individual dimension entry string      */
  char       maxdimstr[HE5_HDFE_DIMBUFSIZE];    /* Individual max. dimension entry string */
  char       errbuf[HE5_HDFE_ERRBUFSIZE];       /* Error message buffer                   */
  htri_t     str_is_variable;                   /* boolean: TRUE if string is variable 
						   lengeth FALSE if string is fixed length
						   -1 if error in H5Tis_variavle_str()    */

  CHECKPOINTER(fieldtype);  
  CHECKPOINTER(fieldname);

  /* Initialize rank to FAIL (error) */
  /* ------------------------------- */
  *rank = FAIL;

  /* Initialize slen[] array */
  /* ----------------------- */
  for ( i = 0; i < HE5_DTSETRANKMAX; i++)
    slen[i] = 0;

  
  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWfinfo", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for Swath ID failed.\n");
      H5Epush(__FILE__, "HE5_SWfinfo", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }
  
  /* Reset status to FAIL */
  /* -------------------- */
  status = FAIL;
  
  /* Get pointers to appropriate "Field" section within SM */
  /* ----------------------------------------------------- */
  if (strcmp(fieldtype, "Geolocation Fields") == 0)
    {
      metabuf = (char *)HE5_EHmetagroup(fid, HE5_SWXSwath[idx].swname, "s", "GeoField", metaptrs);
      groupflag = 0;
    }
  else
    {
      metabuf = (char *)HE5_EHmetagroup(fid, HE5_SWXSwath[idx].swname, "s", "DataField", metaptrs);
      groupflag = 1;
    }
  
  if ( metabuf == NULL )
    {
      status = FAIL;
      sprintf(errbuf, "Cannot get pointer to  metabuf.\n");
      H5Epush(__FILE__, "HE5_SWfinfo", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }


  sprintf(utlstr, "%s%s%s", "\"", fieldname, "\"\n");
  
  metaptrs[0] = strstr(metaptrs[0], utlstr);
  
  /* If field is found either in "Geolocation Fields" or "Data Fields" group */
  /* ----------------------------------------------------------------------- */
  if (metaptrs[0] < metaptrs[1] && metaptrs[0] != NULL)
    {
      /* Get DataType string */
      /* ------------------- */
      statmeta = HE5_EHgetmetavalue(metaptrs, "DataType", utlstr);

      /* Convert to data type class ID */
      /* ----------------------------- */
      if (statmeta == SUCCEED)
        {
	  if(groupflag == 0)
	    groupid = HE5_SWXSwath[idx].geo_id; 
	  else
	    groupid = HE5_SWXSwath[idx].data_id;
		  
	  /* Open the field dataset */
	  /* ---------------------- */
	  datasetid     = H5Dopen(groupid, fieldname);
	  if (datasetid == FAIL)
	    {
	      status = FAIL;
	      sprintf(errbuf, "Cannot open the dataset for the \"%s\" field.\n",fieldname);
	      H5Epush(__FILE__, "HE5_SWfinfo", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
	      if (metabuf != NULL) free(metabuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }
		  
	  /* Get the data type ID */
	  /* -------------------- */
	  datatype      = H5Dget_type(datasetid);
	  if (datatype == FAIL)
	    {
	      status = FAIL;
	      sprintf(errbuf, "Cannot get the data type for the \"%s\" field.\n",fieldname);
	      H5Epush(__FILE__, "HE5_SWfinfo", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
	      if (metabuf != NULL) free(metabuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }
		  
	  /* Get the data type class ID */
	  /* -------------------------- */
	  classid       = H5Tget_class(datatype);
	  if (classid == H5T_NO_CLASS)
	    {
	      status = FAIL;
	      sprintf(errbuf, "Cannot get the data type class ID for the \"%s\" field.\n",fieldname);
	      H5Epush(__FILE__, "HE5_SWfinfo", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	      if (metabuf != NULL) free(metabuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }

	  if (classid == H5T_STRING)
	    {
	      /* HE5T_CHARSTRING has variable length for data fields */
	      str_is_variable = H5Tis_variable_str(datatype);
	      if(str_is_variable == TRUE)
		{
		  numbertype[0] = HE5T_CHARSTRING;
		}
	      else if(str_is_variable == FALSE)
		{
		  numbertype[0] = HE5T_NATIVE_CHAR;
		}
	      else
		{
		  status = FAIL;
		  sprintf(errbuf, "Failed to see if string field is varaible or fixed length for the \"%s\" field.\n",fieldname);
		  H5Epush(__FILE__, "HE5_SWfinfo", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
		  if (metabuf != NULL) free(metabuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}
		      
	      /*numbertype[0] = HE5_SWgetstringtype(swathID, fieldname,classid);*/
	      /*numbertype[0] = HE5T_CHARSTRING;*/
	    }
	  else
	    {
	      /*numbertype[0] = classid;*/
	      numbertype[0] = HE5_EHdtype2numtype(datatype);
	      if (numbertype[0] == FAIL)
		{
		  status = FAIL;
		  sprintf(errbuf, "Cannot get the number type for the \"%s\" field.\n",fieldname);
		  H5Epush(__FILE__, "HE5_SWfinfo", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
		  if (metabuf != NULL) free(metabuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}
	    }

	  /* Release the datatype ID */
	  /* ----------------------- */
	  status = H5Tclose(datatype);
	  if ( status == FAIL )
	    {
	      sprintf(errbuf, "Cannot release the datatype ID for the \"%s\" field.\n",fieldname);
	      H5Epush(__FILE__, "HE5_SWfinfo", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
	      if (metabuf != NULL) free(metabuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }

	  /* Release the dataset ID */
	  /* ---------------------- */
	  Dstatus       = H5Dclose(datasetid);
	  if (Dstatus == FAIL)
	    {
	      status = FAIL;
	      sprintf(errbuf, "Cannot release the dataset ID for the \"%s\" field.\n",fieldname);
	      H5Epush(__FILE__, "HE5_SWfinfo", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
	      if (metabuf != NULL) free(metabuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }
        }
      else
        {
	  status = FAIL;
	  sprintf(errbuf, "The \"DataType\" string not found in metadata. \n");
	  H5Epush(__FILE__, "HE5_SWfinfo", __LINE__, H5E_DATASET, H5E_SEEKERROR, errbuf);
	  if (metabuf != NULL) free(metabuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
        }

      /* Get "DimList" string, trim off "(" and ")" */
      /* ------------------------------------------ */
      statmeta = HE5_EHgetmetavalue(metaptrs, "DimList", utlstr);
      if (statmeta == SUCCEED)
        {
	  memmove(utlstr, utlstr + 1, strlen(utlstr) - 2);
	  utlstr[strlen(utlstr) - 2] = 0;

	  /* Parse trimmed "DimList" string and get rank */
	  /* ------------------------------------------- */
	  ndims = HE5_EHparsestr(utlstr, ',', ptr, slen);
	  *rank = HE5_EHlong2int(ndims);
	  if (*rank == FAIL)
	    {
	      sprintf(errbuf, "Cannot convert from \"long\" to \"int\" data type. \n");
	      H5Epush(__FILE__, "HE5_SWfinfo", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	      if (metabuf != NULL) free(metabuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(FAIL);
	    }
        }
      else
        {
	  status = FAIL;
	  sprintf(errbuf, "The \"DimList\" string not found in metadata. \n");
	  H5Epush(__FILE__, "HE5_SWfinfo", __LINE__, H5E_DATASET, H5E_SEEKERROR, errbuf);
	  if (metabuf != NULL) free(metabuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
        }

      /* If "DimList" IS REQUESTED ...  */
      /* -----------------------------  */
      if (dimlist != NULL) 
	{
	  strcpy(dimstr,"");
	  strcpy(dimlist,"");
			
	  /*
	   * Copy each entry in DimList and remove leading and trailing quotes.
	   * Get dimension sizes and concatenate dimension names to dimension list.
	   */
	  for (i = 0; i < ndims; i++)
	    {
	      memmove(dimstr, ptr[i] + 1, slen[i] - 2);
	      dimstr[slen[i] - 2] = 0;
	      if (i > 0)
		{
		  strcat(dimlist,",");
		}
	      strcat(dimlist, dimstr);
	    }
	}
		

      /* If "MaxdimList" IS REQUESTED  ...      */
      /* -------------------------------------- */
      if(maxdimlist != NULL)
	{
	  strcpy(utlstr,"");
	  statmeta = HE5_EHgetmetavalue(metaptrs,"MaxdimList", utlstr);
	  if (statmeta == SUCCEED)
	    {
	      memmove(utlstr, utlstr + 1, strlen(utlstr) - 2);
	      utlstr[strlen(utlstr) - 2] = 0;
	      ndims = HE5_EHparsestr(utlstr,',', ptr, slen);
	    }
	  else
	    {
	      status = FAIL;
	      sprintf(errbuf, "The \"MaxdimList\" string not found in metadata. \n");
	      H5Epush(__FILE__, "HE5_SWfinfo", __LINE__, H5E_DATASET, H5E_SEEKERROR, errbuf);
	      if (metabuf != NULL) free(metabuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }
			
	  strcpy(maxdimstr,"");
	  strcpy(maxdimlist,"");
			
	  for (i = 0; i < ndims; i++)
	    {
	      memmove(maxdimstr, ptr[i] + 1, slen[i] - 2);
	      maxdimstr[slen[i] - 2] = 0;
	      if (maxdimlist != NULL)
		{
		  if (i > 0)
		    {
		      strcat(maxdimlist,",");
		    }
		  strcat(maxdimlist, maxdimstr);
		}
	    }
	}
	  

      /* Get field ID */
      /* ------------ */
      HE5_SWfieldsizeID( swathID, fieldname, &fieldID);
	  
      /* Get the data space ID */
      /* --------------------- */
      dspace = H5Dget_space( fieldID );
      if(dspace == FAIL)
	{	    
	  status = FAIL;
	  sprintf(errbuf, "Cannot get the data space ID.\n");
	  H5Epush(__FILE__, "HE5_SWfinfo", __LINE__, H5E_DATASPACE, H5E_NOTFOUND, errbuf);
	  if (metabuf != NULL) free(metabuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
		
      /* Get the dataset rank */
      /* -------------------- */
      *rank  = H5Sget_simple_extent_ndims(dspace);
      if( *rank == FAIL)
	{	    
	  status = FAIL;
	  sprintf(errbuf, "Cannot get the rank of the dataset.\n");
	  H5Epush(__FILE__, "HE5_SWfinfo", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  if (metabuf != NULL) free(metabuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
		
      /* Get the dataset dimension sizes */
      /* ------------------------------- */
      status = H5Sget_simple_extent_dims(dspace, dims, NULL);
      if( status == FAIL)
	{	    
	  sprintf(errbuf, "Cannot get the dimension array of the dataset.\n");
	  H5Epush(__FILE__, "HE5_SWfinfo", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  if (metabuf != NULL) free(metabuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
    
      /* Release the data space ID */
      /* ------------------------- */
      status = H5Sclose(dspace);
      if( status == FAIL)
	{	    
	  sprintf(errbuf, "Cannot release the data space ID.\n");
	  H5Epush(__FILE__, "HE5_SWfinfo", __LINE__, H5E_DATASPACE, H5E_CLOSEERROR, errbuf);
	  if (metabuf != NULL) free(metabuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
    }
  
  if (metabuf != NULL) free(metabuf);

 COMPLETION:
  return(status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWfieldinfo                                                  |
|                                                                             |
|  DESCRIPTION: Wrapper around HE5_SWfinfo                                    |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        herr_t              swath structure ID                      |
|  fldname        char*               name of field                           |
|                                                                             |
|  OUTPUTS:                                                                   |
|  rank           int                 rank of field (# of dims)               |
|  dims           hsize_t             field dimensions                        |
|  ntype          hid_t               number types                            |
|  dimlist        char*               field dimension list                    |
|  maxdimlist     char*               field maximum dimension list            |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date       Programmer    Description                                      |
|  =========   ============  ================================================ |
|  01/13/00    A.Muslimov    Added "maxdimlist" parameter to make it possible |
|                            working with the appendable datasets.            |
|  05/10/00    A.Muslimov    Replaced 'H5T_class_t' type by 'int' data type.  |
|  July 00     A.Muslimov    Unmasked hdf5 data types.                        |
|  Oct 5 00    A.Muslimov    Added checking for actual field name (in case of |
|                             passing an alias name as 'fldname').            |
|  Jan 03      S.Zhao        Changed the type of 'ntype' from an H5T_class_t  |
|                            to an hid_t.                                     |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t 
HE5_SWfieldinfo(hid_t swathID, char *fldname, int *rank, hsize_t dims[], hid_t ntype[], char *dimlist, char *maxdimlist)
{

  herr_t       status      = FAIL;/* routine return status variable */

  int          nameflag    = FAIL;/* Actual(1)/Alias(0) field name  */   

  hid_t        fid         = FAIL;/* HDF-EOS file ID                */
  hid_t        gid         = FAIL;/* "HDFEOS" group ID              */
  
  long         idx         = FAIL;/* Swath index                    */

  char         fieldname[HE5_HDFE_NAMBUFSIZE];    /* field name buffer    */
  char         fldactualname[HE5_HDFE_NAMBUFSIZE];/* Actual field name    */  
  char         errbuf[HE5_HDFE_ERRBUFSIZE];       /* Error message buffer */
  
  CHECKPOINTER(fldname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWfieldinfo", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Call HE5_SWfldnameinfo() to get actual field name */
      /* ------------------------------------------------- */
      nameflag = HE5_SWfldnameinfo(swathID, fldname, fldactualname);
      if ( nameflag == FAIL )
	{
	  sprintf(errbuf, "Cannot get actual name of the field.\n");
	  H5Epush(__FILE__, "HE5_SWfieldinfo", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}

      /* Name is not alias */
      /* ----------------- */
      if (nameflag == TRUE)
	{
	  strcpy(fieldname,"");
	  strcpy(fieldname,fldname);
	}

      /* Name is alias */
      /* ------------- */
      if (nameflag == FALSE)
	{
	  strcpy(fieldname,"");
	  strcpy(fieldname,fldactualname);
	}

      /* Check for field within Geolocatation Fields */
      /* ------------------------------------------- */
      status = HE5_SWfinfo(swathID, "Geolocation Fields", fieldname, rank, dims, ntype, dimlist, maxdimlist);

      /* If not there then check within Data Fields */
      /* ------------------------------------------ */
      if (status == FAIL)
	status = HE5_SWfinfo(swathID, "Data Fields", fieldname, rank, dims, ntype, dimlist, maxdimlist);

      /* If not there either then can't be found */
      /* --------------------------------------- */
      if (status == FAIL)
        {
	  sprintf(errbuf,"Field \"%s\" not found. Check out the field name. \n", fieldname);
	  H5Epush(__FILE__, "HE5_SWfieldinfo", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
        }	  
    }

 COMPLETION:  
  return (status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWchunkinfo                                                  |
|                                                                             |
|  DESCRIPTION: Retrieves chunking information                                |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t  None        return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  fldname        char*               name of field                           |
|                                                                             |
|  OUTPUTS:                                                                   |
|  chunk_rank     int*                rank of a dataset                       |
|  chunk_dims     hsize_t             the array containing sizes              |
|                                     of each dimension of a chunk            |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|  Date        Programmer    Description                                      |
|  =========   ============  ==============================================   |
|  Dec 03      S.Zhao        Original development                             |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t
HE5_SWchunkinfo(hid_t swathID, char *fldname, int *chunk_rank,  hsize_t chunk_dims[])
{
  herr_t          status   = FAIL;/* Return status variable */

  hid_t           fid      = FAIL;/* HDF-EOS file ID        */
  hid_t           gid      = FAIL;/* "HDFEOS" group ID      */
  long            idx      = FAIL;/* Swath index            */
  hid_t           fieldID  = FAIL;/* field dataset ID       */
  hid_t           plist    = FAIL;/* field dataset property list ID   */
  hid_t           dspace   = FAIL;/* "fieldname" Dataspace ID         */

  int             ndims    = 0;   /* Number of dimensions   */

  H5D_layout_t    layout = H5D_LAYOUT_ERROR; /* Storage layout type   */
 
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */

 
  HE5_LOCK;
  CHECKPOINTER(fldname);
 
  /* Initialize chunk_rank to FAIL (error) */
  /* ------------------------------------- */
  *chunk_rank = FAIL;

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWchunkinfo", &fid, &gid, &idx);
  if (status == FAIL)
    {
      sprintf(errbuf,"Checking for valid swath ID failed.\n");
      H5Epush(__FILE__, "HE5_SWchunkinfo", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Check out the field group and get field ID */
  /* ------------------------------------------ */
  HE5_SWfldsrch(swathID,fldname,&fieldID,NULL,NULL,NULL);
  if(fieldID == FAIL)
    {
      sprintf(errbuf, "Cannot get the field ID for the \"%s\" field.\n", fldname);
      H5Epush(__FILE__, "HE5_SWchunkinfo", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
  /* Get the property list ID */
  /* ------------------------ */
  plist = H5Dget_create_plist(fieldID);
  if (plist == FAIL)
    {
      sprintf(errbuf, "Cannot get the property list ID for the \"%s\" data field.\n", fldname);
      H5Epush(__FILE__, "HE5_SWchunkinfo", __LINE__, H5E_PLIST, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Get the data space ID */
  /* --------------------- */
  dspace = H5Dget_space(fieldID);
  if(dspace == FAIL)
    {
      sprintf(errbuf, "Cannot get the data space ID for the \"%s\" data field.\n", fldname);
      H5Epush(__FILE__, "HE5_SWchunkinfo", __LINE__, H5E_DATASPACE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Get the dataset rank */
  /* -------------------- */
  ndims  = H5Sget_simple_extent_ndims(dspace);
  if(ndims == FAIL)
    {
      sprintf(errbuf, "Cannot get the rank of the dataset.\n");
      H5Epush(__FILE__, "HE5_SWchunkinfo", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Get Layout */
  /* ---------- */
  layout = H5Pget_layout(plist);
  if (layout == H5D_LAYOUT_ERROR)
    {
      sprintf(errbuf, "Cannot get the layout of the raw data. \n");
      H5Epush(__FILE__, "HE5_SWchunkinfo", __LINE__, H5E_PLIST, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  else if (layout == H5D_CHUNKED)
    {
      /* Get chunking */
      /* ------------ */
      *chunk_rank = H5Pget_chunk(plist, ndims, chunk_dims);
      if (*chunk_rank == FAIL)
	{
	  sprintf(errbuf, "Cannot get the sizes of chunks. \n");
	  H5Epush(__FILE__, "HE5_SWchunkinfo", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
    }
  else
    {
      *chunk_rank = 0;
    }

  /* Release property list ID */
  /* ------------------------ */
  status = H5Pclose(plist);
  if (status == FAIL )
    {
      sprintf(errbuf, "Cannot release property list ID. \n");
      H5Epush(__FILE__, "HE5_SWchunkinfo", __LINE__, H5E_PLIST, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Release the data space ID */
  /* ------------------------- */
  status = H5Sclose(dspace);
  if( status == FAIL)
    {
      sprintf(errbuf, "Cannot release the data space ID.\n");
      H5Epush(__FILE__, "HE5_SWchunkinfo", __LINE__, H5E_DATASPACE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

 
 COMPLETION:
  HE5_UNLOCK;
  return(status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefdimmap                                                  |
|                                                                             |
|  DESCRIPTION: Defines mapping between geolocation and data dimensions       |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|                                                                             |
|  INPUTS:                                                                    |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  3/18/99                                                                    |
|  7/29/99  A.Muslimov    In the call to EHinsertmeta() replaced gid by fid.  |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t  
HE5_SWdefdimmap(hid_t swathID, char *geodim, char *datadim, hsize_t offset, hsize_t increment)
{
  herr_t       status      = FAIL;          /* Routine return status */
  
  hid_t        fid         = FAIL;          /* HDF-EOS file ID       */
  hid_t        gid         = FAIL;          /* "HDFEOS" group ID     */
  
  hsize_t      size        = 0;             /* Size of geo dim       */
  hsize_t      metadata[2] = { 0, 0 };      /* Offset & Increment    */
  
  long         idx         = FAIL;          /* Swath index           */
  
  char         mapname[HE5_HDFE_NAMBUFSIZE];/* Mapping name buffer   */
  char         errbuf[HE5_HDFE_ERRBUFSIZE]; /* Error message buffer  */

  HE5_LOCK;  
  CHECKNAME(geodim);
  CHECKNAME(datadim);

  
  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWdefdimmap", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /*  Geolocation Dimension Search */
      /*  ---------------------------- */
      size = HE5_SWdiminfo(swathID, geodim);
      if (size == 0)
        {
	  status = FAIL;
	  sprintf(errbuf, "Geolocation dimension \"%s\" not found.", geodim);
	  H5Epush(__FILE__, "HE5_SWdefdimmap", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	}

      /* Data Dimension Search */
      /* --------------------- */
      if (status == SUCCEED)
        {
	  size = HE5_SWdiminfo(swathID, datadim);
	  if (size == 0)
            {
	      status = FAIL;
	      sprintf(errbuf, "Data dimension \"%s\" not found.", datadim);
	      H5Epush(__FILE__, "HE5_SWdefdimmap", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
        }
	  
      /* Write "DimensionMap" to Structural MetaData */
      /* ------------------------------------------- */
      if (status == SUCCEED)
        {
	  sprintf(mapname, "%s%s%s", geodim, "/", datadim);
	  metadata[0] = offset;
	  metadata[1] = increment;
	  status = HE5_EHinsertmeta(fid, HE5_SWXSwath[idx].swname, "s", 1L, mapname, metadata);
	  if (status == FAIL)
            {
	      sprintf(errbuf, "Cannot write \"Dimension Map\" offset and increment values to Structural Metadata.");
	      H5Epush(__FILE__, "HE5_SWdefdimmap", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
        }
    }

 COMPLETION:
  HE5_UNLOCK;
  return(status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefidxmap                                                  |
|                                                                             |
|  DESCRIPTION: Defines indexed (non-linear) mapping between geolocation      |
|               and data dimensions                                           |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  geodim         char                Geolocation dimension                   |
|  datadim        char                Data dimension                          |
|  index          long                Index mapping array                     |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  3/18/99                                                                    |
|  7/29/99  A.Muslimov    In the call to EHinsertmeta() replaced gid by fid.  |
|  8/23/99  A.Muslimov    Checked for the statuses returned by H5Dwrite(),    |
|                         H5Sclose(), and H5Dclose().                         |
|  2/08/00  A.Muslimov    Added more error checkings.                         |
|  3/03/00  A.Muslimov    Changed the datatype passed to H5Dcreate() and      |
|                         H5Dwrite() from H5T_NASTIVE_INT to H5T_NATIVE_LONG. |               
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t
HE5_SWdefidxmap(hid_t swathID, char *geodim, char *datadim, long index[])
{
  herr_t      status   = FAIL;             /* Return status variable */
  
  hid_t       fid      = FAIL;             /* HDF-EOS file ID        */
  hid_t       gid      = FAIL;             /* "HDFEOS" group ID      */
  hid_t       dspace   = FAIL;             /* dataspace ID           */
  hid_t       id       = FAIL;             /* dataset ID             */
  hid_t       sw_id    = FAIL;             /* Swath ID               */
  
  long        idx      = FAIL;             /* Swath index            */
  
  hsize_t     metadata =  0;               /* Dummy metadata buffer  */
  hsize_t     gsize    =  0;               /* Size of geo dim        */
  hsize_t     dsize    =  0;               /* Size of data dim       */
  
  char        mapname[HE5_HDFE_NAMBUFSIZE];/* Mapping name           */
  char        utlbuf[HE5_HDFE_DIMBUFSIZE]; /* Utility buffer         */
  char        errbuf[HE5_HDFE_ERRBUFSIZE]; /* Error message buffer   */
  

  HE5_LOCK;
  CHECKNAME(geodim);
  CHECKNAME(datadim);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWdefidxmap", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Geo Dimension Search */
      /* -------------------- */
      gsize = HE5_SWdiminfo(swathID, geodim);
      if (gsize == 0)
        {
	  status = FAIL;
	  sprintf(errbuf, "Geolocation dimension \"%s\" not found. \n", geodim);
	  H5Epush(__FILE__, "HE5_SWdefidxmap", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
        }

      /* Data Dimension Search */
      /* --------------------- */
      if (status == SUCCEED)
        {
	  dsize = HE5_SWdiminfo(swathID, datadim);
	  if (dsize == 0)
            {
	      status = FAIL;
	      sprintf(errbuf, "Data dimension \"%s\" not found. \n", datadim);
	      H5Epush(__FILE__, "HE5_SWdefidxmap", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
            }
        }

      /* Define Index  and Store Index Array */
      /* ----------------------------------- */
      if (status == SUCCEED)
        {
	  sw_id = HE5_SWXSwath[idx].sw_id;

	  /*  Name: "_INDEXMAP:" + geodim + "/" + datadim  */
	  /*  -------------------------------------------  */
	  sprintf(utlbuf, "%s%s%s%s", "_INDEXMAP:", geodim, ",", datadim);

	  /* Create dataspace */
	  /* ---------------- */
	  dspace = H5Screate_simple(1, &gsize, NULL);
	  if (dspace == FAIL)
            {
	      sprintf(errbuf, "Cannot create the data space. \n");
	      H5Epush(__FILE__, "HE5_SWdefidxmap", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(FAIL);
            }

	  /* create dataset */
	  /* -------------- */
	  id = H5Dcreate(sw_id, utlbuf, H5T_NATIVE_LONG, dspace, H5P_DEFAULT);
	  if (id == FAIL)
            {
	      sprintf(errbuf, "Cannot create the dataset. \n");
	      H5Epush(__FILE__, "HE5_SWdefidxmap", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(FAIL);
            }

	  /*  Write data buffer to dataset */
	  /*  ---------------------------- */
	  status = H5Dwrite(id, H5T_NATIVE_LONG, H5S_ALL, H5S_ALL, H5P_DEFAULT, index); 
	  if (status == FAIL)
            {
	      sprintf(errbuf, "Cannot write data to the dataset. \n");
	      H5Epush(__FILE__, "HE5_SWdefidxmap", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
            }

	  /* Write to Structural Metadata */
	  /* ---------------------------- */
	  sprintf(mapname, "%s%s%s", geodim, "/", datadim);
	  status = HE5_EHinsertmeta(fid, HE5_SWXSwath[idx].swname, "s", 2L, mapname, &metadata);
	  if (status == FAIL)
            {
	      sprintf(errbuf, "Cannot insert data to the Metadata. \n");
	      H5Epush(__FILE__, "HE5_SWdefidxmap", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
            }            

	  /* Release dataspace ID */
	  /* -------------------- */
	  status = H5Sclose(dspace);
	  if (status == FAIL)
            {
	      sprintf(errbuf, "Cannot release the data space ID. \n");
	      H5Epush(__FILE__, "HE5_SWdefidxmap", __LINE__, H5E_DATASPACE, H5E_CLOSEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
            }
		  
	  /* Release dataset ID */
	  /* ------------------ */         
	  status = H5Dclose(id);
	  if (status == FAIL)
            {
	      sprintf(errbuf, "Cannot release the dataset ID. \n");
	      H5Epush(__FILE__, "HE5_SWdefidxmap", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
            }
        }
    }

 COMPLETION:
  HE5_UNLOCK;
  return (status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefchunk                                                   |
|                                                                             |
|  DESCRIPTION: Defines size of chunk used to store a chunked layout dataset  |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t  None        return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  rank           int                 rank of a dataset                       |
|  *dim           const hsize_t       pointer to the array containing sizes   |
|                                     of each dimension of a chunk            |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|  Date        Programmer    Description                                      |
|  =========   ============  ==============================================   |
|  8/134/99    A.Muslimov    Checked the statuses for H5P... calls.           |
|  02/08/00    A.Muslimov    Added more error checkings.                      |
|  July 00     A.Muslimov    Unmasked hdf5 data types.                        |
|  Sep  01     A. Muslimov   Added mutex "lock"/"unlock" calls.               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t
HE5_SWdefchunk(hid_t swathID, int rank,  const hsize_t *dim)
{
  herr_t          status   = FAIL;/* Return status variable */

  hid_t           fid      = FAIL;/* HDF-EOS file ID        */
  hid_t           gid      = FAIL;/* "HDFEOS" group ID      */

  long            idx      = FAIL;/* Swath index            */

  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */

  HE5_LOCK;
  CHECKPOINTER(dim);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWdefchunk", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* get the current dataset creation property ID from external array  */
      /* if current property instance has not been created, then create it */
      if( HE5_SWXSwath[idx].plist == FAIL){
	HE5_SWXSwath[idx].plist = H5Pcreate(H5P_DATASET_CREATE);

	if (HE5_SWXSwath[idx].plist == FAIL){
	  sprintf(errbuf, "Cannot create the property list. \n");
	  H5Epush(__FILE__, "HE5_SWdefchunk", __LINE__, H5E_PLIST, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
      }

      /* Set layout */
      /* ---------- */
      status = H5Pset_layout( HE5_SWXSwath[idx].plist, H5D_CHUNKED);
      if (status == FAIL)
	{
	  sprintf(errbuf, "Cannot set the \"CHUNKED\" type of storage. \n");
	  H5Epush(__FILE__, "HE5_SWdefchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}

      /* Set chunking */
      /* ------------ */
      status = H5Pset_chunk( HE5_SWXSwath[idx].plist, rank, dim); 
      if (status == FAIL)
	{
	  sprintf(errbuf, "Cannot set the sizes of chunks. \n");
	  H5Epush(__FILE__, "HE5_SWdefchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	}
    }

 COMPLETION:
  HE5_UNLOCK;
  return(status);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefcomp                                                    |
|                                                                             |
|  DESCRIPTION: Defines compression type and parameters                       |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t  None        return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  compcode       int                 compression code                        |
|  compparm       int                 compression parameters                  |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:   Before calling this function, storage must be CHUNKED             |
|                      Values of compression code                             |
|                         HDFE_COMP_NONE                  0                   |
|                         HDFE_COMP_RLE                   1                   |
|                         HDFE_COMP_NBIT                  2                   |
|                         HDFE_COMP_SKPHUFF               3                   |
|                         HDFE_COMP_DEFLATE               4                   |
|                         HDFE_COMP_SZIP_EC               5                   |
|                         HDFE_COMP_SZIP_NN               6                   |
|                         HDFE_COMP_SZIP_K13              7                   |
|                         HDFE_COMP_SZIP_CHIP             8                   |
|                         HDFE_COMP_SZIP_K13orEC          9                   |
|                         HDFE_COMP_SZIP_K13orNN          10                  |
|                         HDFE_COMP_SHUF_DEFLATE          11                  |
|                         HDFE_COMP_SHUF_SZIP_CHIP        12                  |
|                         HDFE_COMP_SHUF_SZIP_K13         13                  |
|                         HDFE_COMP_SHUF_SZIP_EC          14                  |
|                         HDFE_COMP_SHUF_SZIP_NN          15                  |
|                         HDFE_COMP_SHUF_SZIP_K13orEC     16                  |
|                         HDFE_COMP_SHUF_SZIP_K13orNN     17                  |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|                                                                             |
|  8/13/99  A.Muslimov    Changed the return type of SWdefcomp from int       |
|                         to int   . Checked the statuses in the H5P... calls.|
|  02/08/00 A.Muslimov    Added more error checkings.                         |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  June 01  A.Muslimov    Added checking of the compression code/level.       |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|  Aug  03  S.Zhao        Added Szip compression methods.                     |
|  Oct  03  S.Zhao        Added the shuffling method.                         |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_SWdefcomp(hid_t swathID, int compcode,  int *compparm)
{
  herr_t          status   = FAIL; /* routine return status variable   */

  hid_t           fid      = FAIL; /* HDF-EOS file ID                  */
  hid_t           gid      = FAIL; /* "HDFEOS" group ID                */

  long            idx      = FAIL; /* Swath index                      */

  H5D_layout_t    layout = H5D_LAYOUT_ERROR; /* Storage layout type    */

  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer  */
  int             can_encode = 0;        /* szip encoder presence flag */

  HE5_LOCK;
  CHECKPOINTER(compparm);

  /* Check if compression code is valid */
  /* ---------------------------------- */
  if( compcode != HE5_HDFE_COMP_DEFLATE && compcode != HE5_HDFE_COMP_NONE &&
      compcode != HE5_HDFE_COMP_SZIP_CHIP && compcode != HE5_HDFE_COMP_SZIP_K13 &&
      compcode != HE5_HDFE_COMP_SZIP_EC && compcode != HE5_HDFE_COMP_SZIP_NN &&
      compcode != HE5_HDFE_COMP_SZIP_K13orEC && compcode != HE5_HDFE_COMP_SZIP_K13orNN &&
      compcode != HE5_HDFE_COMP_SHUF_DEFLATE && compcode != HE5_HDFE_COMP_SHUF_SZIP_CHIP &&
      compcode != HE5_HDFE_COMP_SHUF_SZIP_K13 && compcode != HE5_HDFE_COMP_SHUF_SZIP_EC &&
      compcode != HE5_HDFE_COMP_SHUF_SZIP_NN && compcode != HE5_HDFE_COMP_SHUF_SZIP_K13orEC &&
      compcode != HE5_HDFE_COMP_SHUF_SZIP_K13orNN )
    {
      status = FAIL;
      sprintf(errbuf,"Invalid/unsupported compression code. \n");
      H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  if( compcode == HE5_HDFE_COMP_DEFLATE || 
      compcode == HE5_HDFE_COMP_NONE    || 
      compcode == HE5_HDFE_COMP_SHUF_DEFLATE)
    {
      /* Check GZIP compression level */
      /* ---------------------------- */
      if( compparm[0] < 0 || compparm[0] > 9)
	{
	  status = FAIL;
	  sprintf(errbuf,"Invalid GZIP compression level. \n");
	  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
    }
  else
    {
      /* Check SZIP compression block size */
      /* --------------------------------- */
      if( compparm[0] != 2 && compparm[0] != 4 && compparm[0] != 6 && compparm[0] != 8 &&
	  compparm[0] != 10 && compparm[0] != 12 && compparm[0] != 14 && compparm[0] != 16 &&
	  compparm[0] != 18 && compparm[0] != 20 && compparm[0] != 22 && compparm[0] != 24 &&
	  compparm[0] != 26 && compparm[0] != 28 && compparm[0] != 30 && compparm[0] != 32)
	{
	  status = FAIL;
	  sprintf(errbuf,"Invalid SZIP compression block size. \n");
	  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
    }
  
#ifdef H5_HAVE_FILTER_SZIP
  can_encode = HE5_szip_can_encode();
#endif

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWdefcomp", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* If the current property list is not set up */
      /* ------------------------------------------ */
      if( HE5_SWXSwath[idx].plist == FAIL)
	{
	  status = FAIL;
	  sprintf(errbuf,"Unable to compress, dataset storage layout has not been set to CHUNKED. \n");
	  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_PLIST, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	}
      else 
	{
	  layout = H5Pget_layout(HE5_SWXSwath[idx].plist);
	  if (layout == H5D_LAYOUT_ERROR)
	    {
	      status = FAIL;
	      sprintf(errbuf, "Cannot get the layout of the raw data. \n");
	      H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_PLIST, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }
	  
	  if( layout != H5D_CHUNKED )
	    status =  H5Pset_layout(HE5_SWXSwath[idx].plist, H5D_CHUNKED);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot set the \"CHUNKED\" type of storage of the raw data. \n");
	      H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }
	  
	  
	  switch (compcode)
	    {
	      /* Set NBIT compression parameters in compression external array */
	      /* ------------------------------------------------------------- */ 
	    case HE5_HDFE_COMP_NBIT:
	      
	      HE5_SWXSwath[idx].compparm[0] = compparm[0];
	      HE5_SWXSwath[idx].compparm[1] = compparm[1];
	      HE5_SWXSwath[idx].compparm[2] = compparm[2];
	      HE5_SWXSwath[idx].compparm[3] = compparm[3];
	      
	      break;
	      
	    case HE5_HDFE_COMP_DEFLATE:
	      
	      /* ------------------------------------------------- */
	      /* Set compression method to H5D_COMPRESS_DEFLATE    */
	      /*       and compression level to "compparm[0]"      */
	      /* ------------------------------------------------- */
	      status = H5Pset_deflate(HE5_SWXSwath[idx].plist, compparm[0]);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set GZIP compresssion method and level. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}
	      
	      /* ------------------------------------------------- */
	      /* Set GZIP compression method and compression       */
	      /*    parameters in external array                   */
	      /* ------------------------------------------------- */
	      HE5_SWXSwath[idx].compcode = compcode; 
	      HE5_SWXSwath[idx].compparm[0] = compparm[0];
	      
	      break;
	      
	    case HE5_HDFE_COMP_SZIP_CHIP:
	      
#ifdef H5_HAVE_FILTER_SZIP
	      if(can_encode == 1)
		{
		  status = H5Pset_szip(HE5_SWXSwath[idx].plist, H5_SZIP_CHIP_OPTION_MASK, compparm[0]);
		  if (status == FAIL)
		    {
		      sprintf(errbuf, "Cannot set SZIP_CHIP compresssion method and block size. \n");
		      H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      return(status);
		    }
		} 
	      else
		{
		  sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		}
#endif
	      
	      /* ----------------------------------------------- */
	      /* Set SZIP_CHIP compression method and compression*/
	      /*    parameters in external array                 */
	      /* ----------------------------------------------- */
	      HE5_SWXSwath[idx].compcode = compcode;
	      HE5_SWXSwath[idx].compparm[0] = compparm[0];
	      
	      break;
	      
	    case HE5_HDFE_COMP_SZIP_K13:
	      
#ifdef H5_HAVE_FILTER_SZIP
	      if(can_encode == 1)
		{
		  status = H5Pset_szip(HE5_SWXSwath[idx].plist, 
				       H5_SZIP_ALLOW_K13_OPTION_MASK, compparm[0]);
		  if (status == FAIL)
		    {
		      sprintf(errbuf, "Cannot set SZIP_K13 compresssion method and block size. \n");
		      H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      return(status);
		    }
		} 
	      else
		{
		  sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		}
#endif
	      
	      /* ------------------------------------------------- */
	      /* Set SZIP_K13 compression method and compression   */
	      /*    parameters in external array                   */
	      /* ------------------------------------------------- */
	      HE5_SWXSwath[idx].compcode = compcode;
	      HE5_SWXSwath[idx].compparm[0] = compparm[0];
	      
	      break;
	      
	    case HE5_HDFE_COMP_SZIP_EC:

#ifdef H5_HAVE_FILTER_SZIP
	      if(can_encode == 1)
		{
		  status = H5Pset_szip(HE5_SWXSwath[idx].plist, H5_SZIP_EC_OPTION_MASK, compparm[0]);
		  if (status == FAIL)
		    {
		      sprintf(errbuf, "Cannot set SZIP_EC compresssion method and block size. \n");
		      H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      return(status);
		    }
		} 
	      else
		{
		  sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		}
#endif

	      /* ------------------------------------------------- */
	      /* Set SZIP_EC compression method and compression    */
	      /*    parameters in external array                   */
	      /* ------------------------------------------------- */
	      HE5_SWXSwath[idx].compcode = compcode;
	      HE5_SWXSwath[idx].compparm[0] = compparm[0];
	      
	      break;
	      
	    case HE5_HDFE_COMP_SZIP_NN:

#ifdef H5_HAVE_FILTER_SZIP
	      if(can_encode == 1)
		{
		  status = H5Pset_szip(HE5_SWXSwath[idx].plist, H5_SZIP_NN_OPTION_MASK, compparm[0]);
		  if (status == FAIL)
		    {
		      sprintf(errbuf, "Cannot set SZIP_NN compresssion method and block size. \n");
		      H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      return(status);
		    }
		} 
	      else
		{
		  sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		}
#endif

	      /* ------------------------------------------------- */
	      /* Set SZIP_NN compression method and compression    */
	      /*    parameters in external array                   */
	      /* ------------------------------------------------- */
	      HE5_SWXSwath[idx].compcode = compcode;
	      HE5_SWXSwath[idx].compparm[0] = compparm[0];
	      
	      break;
	      
	    case HE5_HDFE_COMP_SZIP_K13orEC:

#ifdef H5_HAVE_FILTER_SZIP
	      if(can_encode == 1)
		{
		  status = H5Pset_szip(HE5_SWXSwath[idx].plist, 
				       H5_SZIP_ALLOW_K13_OPTION_MASK|H5_SZIP_EC_OPTION_MASK, compparm[0]);
		  if (status == FAIL)
		    {
		      sprintf(errbuf, "Cannot set SZIP_K13orEC compresssion method and block size. \n");
		      H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      return(status);
		    }
		} 
	      else
		{
		  sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		}
#endif

	      /* ------------------------------------------------- */
	      /* Set SZIP_K13orEC compression method and           */
	      /*    compression parameters in external array       */
	      /* ------------------------------------------------- */
	      HE5_SWXSwath[idx].compcode = compcode;
	      HE5_SWXSwath[idx].compparm[0] = compparm[0];
	      
	      break;
	      
	    case HE5_HDFE_COMP_SZIP_K13orNN:

#ifdef H5_HAVE_FILTER_SZIP
	      if(can_encode == 1)
		{
		  status = H5Pset_szip(HE5_SWXSwath[idx].plist, 
				       H5_SZIP_ALLOW_K13_OPTION_MASK|H5_SZIP_NN_OPTION_MASK, compparm[0]);
		  if (status == FAIL)
		    {
		      sprintf(errbuf, "Cannot set SZIP_K13orNN compresssion method and block size. \n");
		      H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      return(status);
		    }
		} 
	      else
		{
		  sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		}
#endif

	      /* ------------------------------------------------- */
	      /* Set SZIP_K13orNN compression method and           */
	      /*    compression parameters in external array       */
	      /* ------------------------------------------------- */
	      HE5_SWXSwath[idx].compcode = compcode;
	      HE5_SWXSwath[idx].compparm[0] = compparm[0];
	      
	      break;
	      
	    case HE5_HDFE_COMP_SHUF_DEFLATE:
	      
	      status = H5Pset_shuffle(HE5_SWXSwath[idx].plist);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set the shuffling method. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}
	      
	      status = H5Pset_deflate(HE5_SWXSwath[idx].plist, compparm[0]);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set GZIP compresssion method and level. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}
	      
	      /* ------------------------------------------------- */
	      /* Set shuffling+GZIP method and compression         */
	      /*    parameters in external array                   */
	      /* ------------------------------------------------- */
	      HE5_SWXSwath[idx].compcode = compcode;
	      HE5_SWXSwath[idx].compparm[0] = compparm[0];
	      
	      break;
	      
	    case HE5_HDFE_COMP_SHUF_SZIP_CHIP:
	      
	      status = H5Pset_shuffle(HE5_SWXSwath[idx].plist);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set the shuffling method. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}

#ifdef H5_HAVE_FILTER_SZIP
	      if(can_encode == 1)
		{
		  status = H5Pset_szip(HE5_SWXSwath[idx].plist, H5_SZIP_CHIP_OPTION_MASK, compparm[0]);
		  if (status == FAIL)
		    {
		      sprintf(errbuf, "Cannot set SZIP_CHIP method and block size. \n");
		      H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      return(status);
		    }
		} 
	      else
		{
		  sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		}
#endif

	      /* ------------------------------------------------- */
	      /* Set shuffling+SZIP_CHIP method and compression    */
	      /*    parameters in external array                   */
	      /* ------------------------------------------------- */
	      HE5_SWXSwath[idx].compcode = compcode;
	      HE5_SWXSwath[idx].compparm[0] = compparm[0];
	      
	      break;
	      
	    case HE5_HDFE_COMP_SHUF_SZIP_K13:
	      
	      status = H5Pset_shuffle(HE5_SWXSwath[idx].plist);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set the shuffling method. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}

#ifdef H5_HAVE_FILTER_SZIP
	      if(can_encode == 1)
		{
		  status = H5Pset_szip(HE5_SWXSwath[idx].plist, H5_SZIP_ALLOW_K13_OPTION_MASK, compparm[0]);
		  if (status == FAIL)
		    {
		      sprintf(errbuf, "Cannot set SZIP_K13 compresssion method and block size. \n");
		      H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      return(status);
		    }
		} 
	      else
		{
		  sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		}
#endif

	      /* ------------------------------------------------- */
	      /* Set shuffling+SZIP_K13 method and compression     */
	      /*    parameters in external array                   */
	      /* ------------------------------------------------- */
	      HE5_SWXSwath[idx].compcode = compcode;
	      HE5_SWXSwath[idx].compparm[0] = compparm[0];
	      
	      break;
	      
	    case HE5_HDFE_COMP_SHUF_SZIP_EC:
	      
	      status = H5Pset_shuffle(HE5_SWXSwath[idx].plist);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set the shuffling method. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}

#ifdef H5_HAVE_FILTER_SZIP
	      if(can_encode == 1)
		{
		  status = H5Pset_szip(HE5_SWXSwath[idx].plist, H5_SZIP_EC_OPTION_MASK, compparm[0]);
		  if (status == FAIL)
		    {
		      sprintf(errbuf, "Cannot set SZIP_EC compresssion method and block size. \n");
		      H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      return(status);
		    }
		} 
	      else
		{
		  sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		}
#endif

	      /* ------------------------------------------------- */
	      /* Set shuffling+SZIP_EC method and compression      */
	      /*    parameters in external array                   */
	      /* ------------------------------------------------- */
	      HE5_SWXSwath[idx].compcode = compcode;
	      HE5_SWXSwath[idx].compparm[0] = compparm[0];
	      
	      break;
	      
	    case HE5_HDFE_COMP_SHUF_SZIP_NN:
	      
	      status = H5Pset_shuffle(HE5_SWXSwath[idx].plist);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set the shuffling method. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}

#ifdef H5_HAVE_FILTER_SZIP
	      if(can_encode == 1)
		{
		  status = H5Pset_szip(HE5_SWXSwath[idx].plist, H5_SZIP_NN_OPTION_MASK, compparm[0]);
		  if (status == FAIL)
		    {
		      sprintf(errbuf, "Cannot set SZIP_NN compresssion method and block size. \n");
		      H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      return(status);
		    }
		} 
	      else
		{
		  sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		}
#endif

	      /* ------------------------------------------------- */
	      /* Set shuffling+SZIP_NN method and compression      */
	      /*    parameters in external array                   */
	      /* ------------------------------------------------- */
	      HE5_SWXSwath[idx].compcode = compcode;
	      HE5_SWXSwath[idx].compparm[0] = compparm[0];
	      
	      break;
	      
	    case HE5_HDFE_COMP_SHUF_SZIP_K13orEC:
	      
	      status = H5Pset_shuffle(HE5_SWXSwath[idx].plist);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set the shuffling method. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}

#ifdef H5_HAVE_FILTER_SZIP
	      if(can_encode == 1)
		{
		  status = H5Pset_szip(HE5_SWXSwath[idx].plist, 
				       H5_SZIP_ALLOW_K13_OPTION_MASK|H5_SZIP_EC_OPTION_MASK, compparm[0]);
		  if (status == FAIL)
		    {
		      sprintf(errbuf, "Cannot set SZIP_K13orEC compresssion method and block size. \n");
		      H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      return(status);
		    }
		} 
	      else
		{
		  sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		}
#endif

	      /* ------------------------------------------------- */
	      /* Set shuffling+SZIP_K13orEC method and             */
	      /*    compression parameters in external array       */
	      /* ------------------------------------------------- */
	      HE5_SWXSwath[idx].compcode = compcode;
	      HE5_SWXSwath[idx].compparm[0] = compparm[0];
	      
	      break;
	      
	    case HE5_HDFE_COMP_SHUF_SZIP_K13orNN:
	      
	      status = H5Pset_shuffle(HE5_SWXSwath[idx].plist);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set the shuffling method. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}

#ifdef H5_HAVE_FILTER_SZIP
	      if(can_encode == 1)
		{
		  status = H5Pset_szip(HE5_SWXSwath[idx].plist, 
				       H5_SZIP_ALLOW_K13_OPTION_MASK|H5_SZIP_NN_OPTION_MASK, compparm[0]);
		  if (status == FAIL)
		    {
		      sprintf(errbuf, "Cannot set SZIP_K13orNN compresssion method and block size. \n");
		      H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      return(status);
		    }
		} 
	      else
		{
		  sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
		  H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		}
#endif

	      /* ------------------------------------------------- */
	      /* Set shuffling+SZIP_K13orNN method and             */
	      /*    compression parameters in external array       */
	      /* ------------------------------------------------- */
	      HE5_SWXSwath[idx].compcode = compcode;
	      HE5_SWXSwath[idx].compparm[0] = compparm[0];
	      
	      break;
	      
	    case HE5_HDFE_COMP_NONE:
	      
	      HE5_SWXSwath[idx].compparm[0] = compparm[0];
	      
	      break;
	      
	    default:
	      {
		status = FAIL;
		sprintf(errbuf, "Invalid compression method \"%d\" . \n", compcode);
		H5Epush(__FILE__, "HE5_SWdefcomp", __LINE__, H5E_ARGS, H5E_UNSUPPORTED, errbuf);
		HE5_EHprint(errbuf, __FILE__, __LINE__);
	      }
	      break;
	      
	    }
	}
      
    }
  
 COMPLETION:
  HE5_UNLOCK;
  return (status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefcomchunk                                                |
|                                                                             |
|  DESCRIPTION: Defines compression type and parameters and sets chunking     |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t  None        return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  compcode       int                 compression code                        |
|  compparm       int                 compression parameters                  |
|  rank           int                 rank of a dataset                       |
|  *dim           const hsize_t       pointer to the array containing sizes   |
|                                     of each dimension of a chunk            |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:   Before calling this function, storage must be CHUNKED             |
|                      Values of compression code                             |
|                         HDFE_COMP_NONE                  0                   |
|                         HDFE_COMP_RLE                   1                   |
|                         HDFE_COMP_NBIT                  2                   |
|                         HDFE_COMP_SKPHUFF               3                   |
|                         HDFE_COMP_DEFLATE               4                   |
|                         HDFE_COMP_SZIP_EC               5                   |
|                         HDFE_COMP_SZIP_NN               6                   |
|                         HDFE_COMP_SZIP_K13              7                   |
|                         HDFE_COMP_SZIP_CHIP             8                   |
|                         HDFE_COMP_SZIP_K13orEC          9                   |
|                         HDFE_COMP_SZIP_K13orNN          10                  |
|                         HDFE_COMP_SHUF_DEFLATE          11                  |
|                         HDFE_COMP_SHUF_SZIP_CHIP        12                  |
|                         HDFE_COMP_SHUF_SZIP_K13         13                  |
|                         HDFE_COMP_SHUF_SZIP_EC          14                  |
|                         HDFE_COMP_SHUF_SZIP_NN          15                  |
|                         HDFE_COMP_SHUF_SZIP_K13orEC     16                  |
|                         HDFE_COMP_SHUF_SZIP_K13orNN     17                  |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|                                                                             |
|  8/13/99  A.Muslimov    Changed the return type of SWdefcomp from int       |
|                         to int   . Checked the statuses in the H5P... calls.|
|  02/08/00 A.Muslimov    Added more error checkings.                         |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  July 00  A.Muslimov    Original tayloring from SWdefcomp() & SWdefchunk(). |
|  June 01  A.Muslimov    Added checking for validity of input parameters.    |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|  Aug  03  S.Zhao        Added Szip compression methods.                     |
|  Oct  03  S.Zhao        Added the shuffling method.                         |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_SWdefcomchunk(hid_t swathID, int compcode, int *compparm, int rank, const hsize_t *dim)
{
  herr_t          status   = FAIL;            /* Return status variable */

  int             i        = 0;               /* Loop index             */

  hid_t           fid      = FAIL;            /* HDF-EOS file ID        */
  hid_t           gid      = FAIL;            /* "HDFEOS" group ID      */

  hsize_t         dims[HE5_DTSETRANKMAX];     /* Default dim. sizes     */

  long            idx      = FAIL;            /* Swath index            */

  H5D_layout_t    layout = H5D_LAYOUT_ERROR;  /* Storage layout type    */

  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer   */
  int             can_encode;                 /* szip encoder presence flag */

  HE5_LOCK;
  CHECKPOINTER(compparm);
  CHECKPOINTER(dim);

  /* Check if compression code is valid */
  /* ---------------------------------- */
  if( compcode != HE5_HDFE_COMP_DEFLATE && compcode != HE5_HDFE_COMP_NONE &&
      compcode != HE5_HDFE_COMP_SZIP_CHIP && compcode != HE5_HDFE_COMP_SZIP_K13 &&
      compcode != HE5_HDFE_COMP_SZIP_EC && compcode != HE5_HDFE_COMP_SZIP_NN &&
      compcode != HE5_HDFE_COMP_SZIP_K13orEC && compcode != HE5_HDFE_COMP_SZIP_K13orNN &&
      compcode != HE5_HDFE_COMP_SHUF_DEFLATE && compcode != HE5_HDFE_COMP_SHUF_SZIP_CHIP &&
      compcode != HE5_HDFE_COMP_SHUF_SZIP_K13 && compcode != HE5_HDFE_COMP_SHUF_SZIP_EC &&
      compcode != HE5_HDFE_COMP_SHUF_SZIP_NN && compcode != HE5_HDFE_COMP_SHUF_SZIP_K13orEC &&
      compcode != HE5_HDFE_COMP_SHUF_SZIP_K13orNN )
    {
      status = FAIL;
      sprintf(errbuf, "Invalid/unsupported compression code. \n");
      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  if( compcode == HE5_HDFE_COMP_DEFLATE || 
      compcode == HE5_HDFE_COMP_NONE || 
      compcode == HE5_HDFE_COMP_SHUF_DEFLATE)
    {
      /* Check GZIP compression level */
      /* ---------------------------- */
      if( compparm[0] < 0 || compparm[0] > 9)
	{
	  status = FAIL;
	  sprintf(errbuf,"Invalid GZIP compression level. \n");
	  H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
    }
  else
    {
      /* Check SZIP compression block size */
      /* --------------------------------- */
      if( compparm[0] != 2 && compparm[0] != 4 && compparm[0] != 6 && compparm[0] != 8 &&
	  compparm[0] != 10 && compparm[0] != 12 && compparm[0] != 14 && compparm[0] != 16 &&
	  compparm[0] != 18 && compparm[0] != 20 && compparm[0] != 22 && compparm[0] != 24 &&
	  compparm[0] != 26 && compparm[0] != 28 && compparm[0] != 30 && compparm[0] != 32)
	{
	  status = FAIL;
	  sprintf(errbuf,"Invalid SZIP compression block size. \n");
	  H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
    }

#ifdef H5_HAVE_FILTER_SZIP
  can_encode = HE5_szip_can_encode();
#endif

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWdefcomchunk", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Initialize dims[] array */
      /* ----------------------- */
      for (i = 0; i < HE5_DTSETRANKMAX; i++)
	dims[i] = 0;
      
      /* get the current dataset creation property ID from external array  */
      /* ----------------------------------------------------------------- */
      if(HE5_SWXSwath[idx].plist == FAIL)
	{
	  /* create property list */
	  /* -------------------- */
	  HE5_SWXSwath[idx].plist = H5Pcreate(H5P_DATASET_CREATE);
	  
	  /* set layout to "H5D_CHUNKED" */
	  /* --------------------------- */
	  status = H5Pset_layout(HE5_SWXSwath[idx].plist, H5D_CHUNKED);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot set the \"CHUNKED\" type of storage. \n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_STORAGE, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }
	}
      else 
	{
	  /* Get layout of the raw data */
	  /* -------------------------- */
	  layout = H5Pget_layout(HE5_SWXSwath[idx].plist);
	  if (layout == H5D_LAYOUT_ERROR)
	    {
	      status = FAIL;
	      sprintf(errbuf, "Cannot get the layout of the raw data. \n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_STORAGE, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }
	  
	  if( layout != H5D_CHUNKED )
	    {
	      
	      /* set layout to "H5D_CHUNKED" */
	      /* --------------------------- */
	      status = H5Pset_layout( HE5_SWXSwath[idx].plist, H5D_CHUNKED);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set the \"CHUNKED\" type of storage. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_STORAGE, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}
	    }
	}
      
      /* set chunking */
      /* ------------ */
      if ( rank > 0 && dim != (hsize_t *)NULL)
	{
	  status = H5Pset_chunk(HE5_SWXSwath[idx].plist, rank, dim); 
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot set the sizes of chunks. \n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }
	}
      else if ( rank > 0 && dim == (hsize_t *)NULL)
	{
	  /* Set default chunk sizes */
	  /* ----------------------- */
	  for (i = 0; i < rank; i++)
	    dims[ i ] = HE5_CHUNKSIZE;
	  
	  status = H5Pset_chunk(HE5_SWXSwath[idx].plist, rank, dims); 
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot set the sizes of chunks. \n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }
	}
      else
	{
	  sprintf(errbuf, "Invalid dataset rank,\"%d\" . \n", rank);
	  H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
      
      
      switch (compcode)
	{
	  /* Set NBIT compression parameters in compression external array */
	  /* ------------------------------------------------------------- */ 
	case HE5_HDFE_COMP_NBIT:
	  
	  HE5_SWXSwath[idx].compparm[0] = compparm[0];
	  HE5_SWXSwath[idx].compparm[1] = compparm[1];
	  HE5_SWXSwath[idx].compparm[2] = compparm[2];
	  HE5_SWXSwath[idx].compparm[3] = compparm[3];
	  
	  break;
	  
	case HE5_HDFE_COMP_DEFLATE:
	  
	  /* ------------------------------------------------- */
	  /* Set compression method to H5D_COMPRESS_DEFLATE    */
	  /*       and compression level to "compparm[0]"      */
	  /* ------------------------------------------------- */
	  status = H5Pset_deflate(HE5_SWXSwath[idx].plist, compparm[0]);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot set GZIP compresssion method and level. \n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }
	  
	  /* ------------------------------------------------- */
	  /* Set GZIP compression method and compression       */
	  /*    parameters in external array                   */
	  /* ------------------------------------------------- */
	  HE5_SWXSwath[idx].compcode = compcode;
	  HE5_SWXSwath[idx].compparm[0] = compparm[0];
	  
	  break;
	  
	case HE5_HDFE_COMP_SZIP_CHIP:
	  
#ifdef H5_HAVE_FILTER_SZIP
	  if(can_encode == 1)
	    {
	      status = H5Pset_szip(HE5_SWXSwath[idx].plist, H5_SZIP_CHIP_OPTION_MASK, compparm[0]);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set SZIP_CHIP compresssion method and block size. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}
	    } 
	  else
	    {
	      sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
#endif
	  
	  /* ------------------------------------------------- */
	  /* Set SZIP_CHIP compression method and compression  */
	  /*    parameters in external array                   */
	  /* ------------------------------------------------- */
	  HE5_SWXSwath[idx].compcode = compcode;
	  HE5_SWXSwath[idx].compparm[0] = compparm[0];
	  
	  break;
	  
	case HE5_HDFE_COMP_SZIP_K13:

#ifdef H5_HAVE_FILTER_SZIP
	  if(can_encode == 1)
	    {
	      status = H5Pset_szip(HE5_SWXSwath[idx].plist, H5_SZIP_ALLOW_K13_OPTION_MASK, compparm[0]);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set SZIP_K13 compresssion method and block size. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}
	    } 
	  else
	    {
	      sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
#endif

	  /* ------------------------------------------------- */
	  /* Set SZIP_K13 compression method and compression   */
	  /*    parameters in external array                   */
	  /* ------------------------------------------------- */
	  HE5_SWXSwath[idx].compcode = compcode;
	  HE5_SWXSwath[idx].compparm[0] = compparm[0];
	  
	  break;
	  
	case HE5_HDFE_COMP_SZIP_EC:

#ifdef H5_HAVE_FILTER_SZIP
	  if(can_encode == 1)
	    {
	      status = H5Pset_szip(HE5_SWXSwath[idx].plist, H5_SZIP_EC_OPTION_MASK, compparm[0]);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set SZIP_EC compresssion method and block size. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}
	    } 
	  else
	    {
	      sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
#endif

	  /* ------------------------------------------------- */
	  /* Set SZIP_EC compression method and compression    */
	  /*    parameters in external array                   */
	  /* ------------------------------------------------- */
	  HE5_SWXSwath[idx].compcode = compcode;
	  HE5_SWXSwath[idx].compparm[0] = compparm[0];
	  
	  break;
	  
	case HE5_HDFE_COMP_SZIP_NN:

#ifdef H5_HAVE_FILTER_SZIP
	  if(can_encode == 1)
	    {
	      status = H5Pset_szip(HE5_SWXSwath[idx].plist, H5_SZIP_NN_OPTION_MASK, compparm[0]);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set SZIP_NN compresssion method and block size. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}
	    } 
	  else
	    {
	      sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
#endif

	  /* ------------------------------------------------- */
	  /* Set SZIP_NN compression method and compression    */
	  /*    parameters in external array                   */
	  /* ------------------------------------------------- */
	  HE5_SWXSwath[idx].compcode = compcode;
	  HE5_SWXSwath[idx].compparm[0] = compparm[0];
	  
	  break;
	  
	case HE5_HDFE_COMP_SZIP_K13orEC:

#ifdef H5_HAVE_FILTER_SZIP
	  if(can_encode == 1)
	    {
	      status = H5Pset_szip(HE5_SWXSwath[idx].plist, 
				   H5_SZIP_ALLOW_K13_OPTION_MASK|H5_SZIP_EC_OPTION_MASK, compparm[0]);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set SZIP_K13orSZIP_EC compresssion method and block size. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}
	    } 
	  else
	    {
	      sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
#endif

	  /* ------------------------------------------------- */
	  /* Set SZIP_K13orEC compression method and           */
	  /*    compression parameters in external array       */
	  /* ------------------------------------------------- */
	  HE5_SWXSwath[idx].compcode = compcode;
	  HE5_SWXSwath[idx].compparm[0] = compparm[0];
	  
	  break;
	  
	case HE5_HDFE_COMP_SZIP_K13orNN:

#ifdef H5_HAVE_FILTER_SZIP
	  if(can_encode == 1)
	    {
	      status = H5Pset_szip(HE5_SWXSwath[idx].plist, 
				   H5_SZIP_ALLOW_K13_OPTION_MASK|H5_SZIP_NN_OPTION_MASK, compparm[0]);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set SZIP_K13orNN compresssion method and block size. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}
	    } 
	  else
	    {
	      sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
#endif

	  /* ------------------------------------------------- */
	  /* Set SZIP_K13orNN compression method and           */
	  /*    compression parameters in external array       */
	  /* ------------------------------------------------- */
	  HE5_SWXSwath[idx].compcode = compcode;
	  HE5_SWXSwath[idx].compparm[0] = compparm[0];
	  
	  break;
	  
	case HE5_HDFE_COMP_SHUF_DEFLATE:
	  
	  status = H5Pset_shuffle(HE5_SWXSwath[idx].plist);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot set the shuffling method. \n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }
	  
	  status = H5Pset_deflate(HE5_SWXSwath[idx].plist, compparm[0]);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot set GZIP compresssion method and level. \n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }
	  
	  /* ------------------------------------------------- */
	  /* Set shuffling+GZIP method and compression         */
	  /*    parameters in external array                   */
	  /* ------------------------------------------------- */
	  HE5_SWXSwath[idx].compcode = compcode;
	  HE5_SWXSwath[idx].compparm[0] = compparm[0];
	  
	  break;
	  
	case HE5_HDFE_COMP_SHUF_SZIP_CHIP:
	  
	  status = H5Pset_shuffle(HE5_SWXSwath[idx].plist);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot set the shuffling method. \n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }

#ifdef H5_HAVE_FILTER_SZIP
	  if(can_encode == 1)
	    {
	      status = H5Pset_szip(HE5_SWXSwath[idx].plist, H5_SZIP_CHIP_OPTION_MASK, compparm[0]);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set SZIP_CHIP compresssion method and block size. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}
	    } 
	  else
	    {
	      sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
#endif

	  /* ------------------------------------------------- */
	  /* Set shuffling+SZIP_CHIP method and compression    */
	  /*    parameters in external array                   */
	  /* ------------------------------------------------- */
	  HE5_SWXSwath[idx].compcode = compcode;
	  HE5_SWXSwath[idx].compparm[0] = compparm[0];
	  
	  break;
	  
	case HE5_HDFE_COMP_SHUF_SZIP_K13:
	  
	  status = H5Pset_shuffle(HE5_SWXSwath[idx].plist);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot set the shuffling method. \n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }

#ifdef H5_HAVE_FILTER_SZIP
	  if(can_encode == 1)
	    {
	      status = H5Pset_szip(HE5_SWXSwath[idx].plist, H5_SZIP_ALLOW_K13_OPTION_MASK, compparm[0]);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set SZIP_K13 compresssion method and block size. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}
	    } 
	  else
	    {
	      sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
#endif

	  /* ------------------------------------------------- */
	  /* Set shuffling+SZIP_K13 method and compression     */
	  /*    parameters in external array                   */
	  /* ------------------------------------------------- */
	  HE5_SWXSwath[idx].compcode = compcode;
	  HE5_SWXSwath[idx].compparm[0] = compparm[0];
	  
	  break;
	  
	case HE5_HDFE_COMP_SHUF_SZIP_EC:
	  
	  status = H5Pset_shuffle(HE5_SWXSwath[idx].plist);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot set the shuffling method. \n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }

#ifdef H5_HAVE_FILTER_SZIP
	  if(can_encode == 1)
	    {
	      status = H5Pset_szip(HE5_SWXSwath[idx].plist, H5_SZIP_EC_OPTION_MASK, compparm[0]);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set SZIP_EC compresssion method and block size. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}
	    } 
	  else
	    {
	      sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
#endif

	  /* ------------------------------------------------- */
	  /* Set shuffling+SZIP_EC method and compression      */
	  /*    parameters in external array                   */
	  /* ------------------------------------------------- */
	  HE5_SWXSwath[idx].compcode = compcode;
	  HE5_SWXSwath[idx].compparm[0] = compparm[0];
	  
	  break;
	  
	case HE5_HDFE_COMP_SHUF_SZIP_NN:
	  
	  status = H5Pset_shuffle(HE5_SWXSwath[idx].plist);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot set the shuffling method. \n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }

#ifdef H5_HAVE_FILTER_SZIP
	  if(can_encode == 1)
	    {
	      status = H5Pset_szip(HE5_SWXSwath[idx].plist, H5_SZIP_NN_OPTION_MASK, compparm[0]);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set SZIP_NN compresssion method and block size. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}
	    } 
	  else
	    {
	      sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
#endif

	  /* ------------------------------------------------- */
	  /* Set shuffling+SZIP_NN method and compression      */
	  /*    parameters in external array                   */
	  /* ------------------------------------------------- */
	  HE5_SWXSwath[idx].compcode = compcode;
	  HE5_SWXSwath[idx].compparm[0] = compparm[0];
	  
	  break;
	  
	case HE5_HDFE_COMP_SHUF_SZIP_K13orEC:
 
	  status = H5Pset_shuffle(HE5_SWXSwath[idx].plist);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot set the shuffling method. \n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }

#ifdef H5_HAVE_FILTER_SZIP
	  if(can_encode == 1)
	    {
	      status = H5Pset_szip(HE5_SWXSwath[idx].plist, 
				   H5_SZIP_ALLOW_K13_OPTION_MASK|H5_SZIP_EC_OPTION_MASK, compparm[0]);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set SZIP_K13orEC compresssion method and block size. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}
	    } 
	  else
	    {
	      sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
#endif

	  /* ------------------------------------------------- */
	  /* Set shuffling+SZIP_K13orEC method and             */
	  /*    compression parameters in external array       */
	  /* ------------------------------------------------- */
	  HE5_SWXSwath[idx].compcode = compcode;
	  HE5_SWXSwath[idx].compparm[0] = compparm[0];
	  
	  break;
	  
	case HE5_HDFE_COMP_SHUF_SZIP_K13orNN:
	  
	  status = H5Pset_shuffle(HE5_SWXSwath[idx].plist);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot set the shuffling method. \n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }

#ifdef H5_HAVE_FILTER_SZIP
	  if(can_encode == 1)
	    {	  
	      status = H5Pset_szip(HE5_SWXSwath[idx].plist, 
				   H5_SZIP_ALLOW_K13_OPTION_MASK|H5_SZIP_NN_OPTION_MASK, compparm[0]);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot set SZIP_K13orNN compresssion method and block size. \n");
		  H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(status);
		}
	    } 
	  else
	    {
	      sprintf(errbuf, "Szip does not have encoder; szip compression won't apply to datafields.\n");
	      H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_RESOURCE, H5E_CANTENCODE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
#endif
	  
	  /* ------------------------------------------------- */
	  /* Set shuffling+SZIP_K13orNN method and             */
	  /*    compression parameters in external array       */
	  /* ------------------------------------------------- */
	  HE5_SWXSwath[idx].compcode = compcode;
	  HE5_SWXSwath[idx].compparm[0] = compparm[0];
	  
	  break;
	  
	case HE5_HDFE_COMP_NONE:
	  
	  HE5_SWXSwath[idx].compparm[0] = compparm[0];
	  
	  break;
	  
	default:
	  {
	    status = FAIL;
	    sprintf(errbuf, "Invalid (unsupported) compression method \"%d\". \n", compcode);
	    H5Epush(__FILE__, "HE5_SWdefcomchunk", __LINE__, H5E_ARGS, H5E_UNSUPPORTED, errbuf);
	    HE5_EHprint(errbuf, __FILE__, __LINE__);
	  }
	  break;
	  
	}
    }  
 COMPLETION:
  HE5_UNLOCK;
  return(status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefinefield                                                |
|                                                                             |
|  DESCRIPTION: Defines geolocation or data field within swath structure      |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  fieldtype      char                geo/data fieldtype                      |
|  fieldname      char                fieldname                               |
|  dimlist        char                Dimension (comma-separated)list         |
|  maxdimlist     char                Maximum Dimension (comma-separated) list|
|  numbertype     hid_t               field data type ID                      |
|  merge          int                 merge code                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:  H5S_UNLIMITED is -1, not 0  => unlimited extendiable dimention     |
|           size = -1.                                                        |
|          (A.M.) If maxdimlist = NULL, then dimlist string is copied to the  |
|          maxdimlist string, and corresponding information is written to     |
|          the metadata section.                                              |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  8/23/99  A.Muslimov    Checked for the statuse returned by H5Dclose() and  |
|                         H5Sclose().                                         |
| 10/18/99  A.Muslimov    Replaced memcpy() by memmove() to avoid a problem   |
|                            when arguments 1 and 2 overlap in memory.        |
| 12/3/99   A.Muslimov    Added a call (see last lines) to H5Pclose().        |
| 01/14/00  A.Muslimov    Modified setting up of the metadata strings to      |
|                         to enable the proper functioning of calls involving |
|                         appendable fields.                                  |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Nov  00  A.Muslimov    Updated a block checking if the data type is valid. |
|                         Modified to enable appendability of any dimension.  |
|  Aug  03  S.Zhao        Added Szip compression methods.                     |
|  Oct  03  S.Zhao        Added to create a character string dataset.         |
|  Mar  04  S.Zhao        Modified for a character string dataset.            |
|  Apr  04  S.Zhao        Modified for a character string dataset.            |
|  May  05  S.Zhao        Added HE5_EHdtype2numtype() function call.          |
|  Sep  11  Abe Taaheri   Modified for correcting Unlimited dimension         |
|                         behavior and extension, removing hardcoded name     |
|                         Unlim                                               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
static herr_t   
HE5_SWdefinefield(hid_t swathID, char *fieldtype, const char *fieldname, char *dimlist, char *maxdimlist, hid_t numbertype, int merge)
{
  herr_t          status      = FAIL; /* Return status variable             */
 
  int             i           = 0;    /* Loop index                         */
  int             foundAllDim = 1;    /* found all dimensions flag          */
  int             append      = FALSE;/* "Is field appendable?" flag        */
  int             first       = 1;    /* first entry flag                   */
  int             fac         = 0;    /* Data (1)/Geo (2) Field flag        */
  int             compcode    = FAIL; /* Compression code                   */
  int             rank        = 0;    /* Field rank                         */
  int             maxrank     = 0;    /* max dim  rank                      */

  hid_t           fid        = FAIL;/* HDF-EOS file ID                      */
  hid_t           gid        = FAIL;/* "HDFEOS" group ID                    */
  hid_t           data_space = FAIL;/* dataspace ID                         */
  hid_t           dataset    = FAIL;/* dataset ID                           */
  hid_t           heos_gid   = FAIL;/* "SWATHS" group ID                    */

  hsize_t         metavalue = 0;        /* Metavalue to insert              */
  hsize_t         dims[HE5_DTSETRANKMAX];   /* Dimension size array         */
  hsize_t         maxdims[HE5_DTSETRANKMAX];/* Dimension size array         */
  hsize_t         dimsize   = 0;        /* Dimension size                   */
  hsize_t         count[]   = { 1 };    /* number of elements to insert     */

  long            idx       = FAIL;     /* Swath index                      */

  H5D_layout_t    layout = H5D_LAYOUT_ERROR; /* Storage layout for raw data */

  void            *value;

  size_t          tsize     = 0;            /* Size of a datatype in bytes  */
  hid_t           ntype     = FAIL;         /* number type ID               */
  int             attr      = 0;            /* attribute value              */
  hid_t           numtype   = FAIL;

  H5D_fill_value_t fill_status;      /* to see if fill value is set or not  */

  char            *dimbuf   = (char *)NULL;	   /* Dimension buffer             */
  char            *comma    = (char *)NULL;	   /* Pointer to comma             */
  char            *dimcheck = (char *)NULL;        /* Dimension check buffer       */
  char            utlbuf[HE5_HDFE_UTLBUFSIZE];     /* Utility buffer               */
  char            utlbuf2[HE5_HDFE_UTLBUFSIZE];	   /* Utility buffer 2             */
  char            errbuf1[HE5_HDFE_ERRBUFSIZE];	   /* Error message buffer 1       */
  char            errbuf2[HE5_HDFE_ERRBUFSIZE];    /* Error message buffer 2       */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];     /* Error message buffer         */
  char            maxdimlstbuf[HE5_HDFE_DIMBUFSIZE];
  char            dimlstbuf[HE5_HDFE_DIMBUFSIZE];
  char            compparmbuf[HE5_HDFE_DIMBUFSIZE];/* Compression parmeter         */
  char            *HDFcomp[18] = {"HE5_HDFE_COMP_NONE", "HE5_HDFE_COMP_RLE", "HE5_HDFE_COMP_NBIT", "HE5_HDFE_COMP_SKPHUFF", "HE5_HDFE_COMP_DEFLATE", "HE5_HDFE_COMP_SZIP_CHIP", "HE5_HDFE_COMP_SZIP_K13", "HE5_HDFE_COMP_SZIP_EC", "HE5_HDFE_COMP_SZIP_NN", "HE5_HDFE_COMP_SZIP_K13orEC", "HE5_HDFE_COMP_SZIP_K13orNN", "HE5_HDFE_COMP_SHUF_DEFLATE", "HE5_HDFE_COMP_SHUF_SZIP_CHIP", "HE5_HDFE_COMP_SHUF_SZIP_K13", "HE5_HDFE_COMP_SHUF_SZIP_EC", "HE5_HDFE_COMP_SHUF_SZIP_NN", "HE5_HDFE_COMP_SHUF_SZIP_K13orEC", "HE5_HDFE_COMP_SHUF_SZIP_K13orNN"};   /* Compression code names       */

  CHECKNAME(fieldname);
  CHECKPOINTER(fieldtype);
  CHECKPOINTER(dimlist);

  /* Setup error message strings */
  /* --------------------------- */
  strcpy(errbuf1, "HE5_SWXSDname array too small.\nPlease increase ");
  strcat(errbuf1, "size of HE5_HDFE_NAMBUFSIZE in \"HE5_HdfEosDef.h\".\n");
  strcpy(errbuf2, "HE5_SWXSDdims array too small.\nPlease increase ");
  strcat(errbuf2, "size of HE5_HDFE_DIMBUFSIZE in \"HE5_HdfEosDef.h\".\n");
  	
  /* assuming that fillvalue is undefined for the field */
  fill_status = H5D_FILL_VALUE_UNDEFINED;

  
  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWdefinefield", &fid, &heos_gid, &idx);
  if(status == FAIL ) return(status);
	
  /* initialize dims and maxdims array */
  /* --------------------------------- */
  for(i = 0; i < HE5_DTSETRANKMAX; i++)
    {
      dims[i]    = 0;
      maxdims[i] = 0;
    }

	
  /* Allocate space for dimbuf, copy dimlist into it, & append comma */
  /* --------------------------------------------------------------- */
  dimbuf = (char *) calloc(strlen(dimlist) + 64, sizeof(char));
  if(dimbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_RESOURCE, H5E_NOSPACE, 
	      "Cannot allocate memory. \n");
      HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
      return(FAIL);
    }
	
  /*
********************************************************************
*   C H E C K  T H E   C O N T E N T   O F   dimlist  S T R I N G  *   
********************************************************************
*/
  
  strcpy(dimbuf, dimlist);
  strcat(dimbuf, ",");
  
  /* Find comma */
  /* ---------- */
  comma = strchr(dimbuf, ',');
	
  /*
   * Loop through entries in dimension list to make sure they are
   * defined in swath
   */
  while (comma != NULL)
    {
      /* Copy dimension list entry to dimcheck */
      /* ------------------------------------- */
      dimcheck = (char *) calloc(comma - dimbuf + 1, sizeof(char));
      if(dimcheck == NULL)
	{
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_RESOURCE, H5E_NOSPACE, 
		  "Cannot allocate memory. \n");
	  HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	  free(dimbuf);
	  return(FAIL);
	}
      memmove(dimcheck, dimbuf, comma - dimbuf);

      /* Get dimension size */
      /* ------------------ */
      dimsize = HE5_SWdiminfo(swathID, dimcheck);
      if (dimsize > 0)
	{
	  dims[rank] = dimsize;
	  rank++;
	}
      else
	{
	  /*
	   * If dimension list entry not found - set error return
	   * status, append name to utility buffer for error report
	   */
	  status = FAIL;
	  foundAllDim = 0;
	  if (first == 1)
	    strcpy(utlbuf, dimcheck);
	  else
	    {
	      strcat(utlbuf, ",");
	      strcat(utlbuf, dimcheck);
	    }
	  first = 0;
	}

      /*
       * Go to next dimension entry, find next comma, & free up
       * dimcheck buffer
       */
      memmove(dimbuf, comma + 1, strlen(comma + 1) + 1); 
      comma = strchr(dimbuf, ',');
      free(dimcheck);

    }
  free(dimbuf);
	
  /* If no dimensions found, report error */
  /* ------------------------------------ */
  if (foundAllDim == 0)
    {
      status = FAIL;
      sprintf(errbuf, "Dimension(s) \"%s\" not found for \"%s\" field. \n", utlbuf, fieldname);
      H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return (status); 
    }
	
	
  /*
************************************************************************
*   C H E C K  T H E   C O N T E N T   O F   maxdimlist   S T R I N G  *   
************************************************************************
*/
	
	
  /* Allocate space for dimbuf, copy maxdimlist into it, & append comma */
  /* ------------------------------------------------------------------ */
  if(maxdimlist != NULL) 
    {
      dimbuf = (char *) calloc(strlen(maxdimlist) + 64, sizeof(char));
      if(dimbuf == NULL)
	{
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_RESOURCE, H5E_NOSPACE, 
		  "Cannot allocate memory. \n");
	  HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	  return(FAIL);

	}
	  
      /* Copy "maxdimlist" to "dimbuf", & append comma */
      /* --------------------------------------------- */
      strcpy(dimbuf, maxdimlist);
      strcat(dimbuf, ",");

      /* Find comma */
      /* ---------- */
      comma = strchr(dimbuf, ',');

      /*
       * Loop through entries in dimension list to make sure they are
       *                     defined in swath
       */
      while (comma != NULL)
	{
	  /* Copy dimension list entry to dimcheck */
	  /* ------------------------------------- */
	  dimcheck = (char *) calloc(comma - dimbuf + 1, sizeof(char));
	  if(dimcheck == NULL)
	    {
	      H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory. \n");
	      HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	      free(dimbuf);
	      return(FAIL);
	    }
	  memmove(dimcheck, dimbuf, comma - dimbuf);

	  /* Get dimension size */
	  /* ------------------ */
	  dimsize = HE5_SWdiminfo(swathID, dimcheck);
	  if ( (dimsize > 0) || (dimsize == H5S_UNLIMITED) )
	    {
	      maxdims[maxrank] = dimsize;
	      maxrank++;
	    }
	  else
	    {
	      /*
	       * If dimension list entry not found - set error return
	       * status, append name to utility buffer for error report
	       */
	      status = FAIL;
	      foundAllDim = 0;
	      if (first == 1)
		strcpy(utlbuf, dimcheck);
	      else
		{
		  strcat(utlbuf, ",");
		  strcat(utlbuf, dimcheck);
		}
	      first = 0;
	    }

	  /*
	   * Go to next dimension entry, find next comma, & free up
	   * dimcheck buffer
	   */
	  memmove(dimbuf, comma + 1, strlen(comma + 1) + 1); 
	  comma = strchr(dimbuf, ',');
	  free(dimcheck);
	}

      free(dimbuf);

      /* If no dimensions found, report error */
      /* ------------------------------------ */
      if (foundAllDim == 0)
	{
	  status = FAIL;
	  sprintf(errbuf, "Dimension(s) \"%s\" not found for \"%s\" field. \n", utlbuf, fieldname);
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return (status);
	}


      /* If maxrank !=rank  then report error */
      /* ------------------------------------ */
      if ( maxrank != rank )
	{
	  status = FAIL;
	  sprintf(errbuf,"Dimension rank doesn't match Maximum dimension rank. \n");
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return (status);
	}
    } 
  /* "maxlist == NULL"  ==> maxdims[]= dims[] */
  /* ---------------------------------------- */
  else
    {
      for(i = 0; i < rank; i++ )
	maxdims[ i ] = dims[ i ];
    }
  
	
  /* Find out if the dataset dimension is appendable */
  /* ----------------------------------------------- */
  for(i = 0; i < rank; i++)
    {
      if( dims[i] == maxdims[i] )
	append = FALSE;
      else if ( (dims[i] < maxdims[i]) || (maxdims[i] == H5S_UNLIMITED))
	{
	  append = TRUE;
	  break;
	}
      else
	{
	  status = FAIL;
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_ARGS, H5E_BADRANGE, 
		  "Maximum dimension size is smaller than Dimension size. \n");
	  HE5_EHprint("Error: Maximum dimension size is smaller than Dimension size, occured", 
		      __FILE__, __LINE__);
	  return(status);
	}
    }
	
	
  /* Check for valid data type ID ("numbertype") */
  /* ------------------------------------------- */
  if (numbertype != HE5T_CHARSTRING)
    {
      if (
	  H5Tequal(numbertype, H5T_NATIVE_CHAR)   != SUCCEED &&
	  H5Tequal(numbertype, H5T_NATIVE_SCHAR)  != SUCCEED &&
	  H5Tequal(numbertype, H5T_NATIVE_UCHAR)  != SUCCEED &&
	  H5Tequal(numbertype, H5T_NATIVE_SHORT)  != SUCCEED &&
	  H5Tequal(numbertype, H5T_NATIVE_USHORT) != SUCCEED &&
	  H5Tequal(numbertype, H5T_NATIVE_INT)    != SUCCEED &&
	  H5Tequal(numbertype, H5T_NATIVE_UINT)   != SUCCEED &&
	  H5Tequal(numbertype, H5T_NATIVE_LONG)   != SUCCEED &&
	  H5Tequal(numbertype, H5T_NATIVE_ULONG)  != SUCCEED &&
	  H5Tequal(numbertype, H5T_NATIVE_LLONG)  != SUCCEED &&
	  H5Tequal(numbertype, H5T_NATIVE_ULLONG) != SUCCEED &&
	  H5Tequal(numbertype, H5T_NATIVE_FLOAT)  != SUCCEED &&
	  H5Tequal(numbertype, H5T_NATIVE_DOUBLE) != SUCCEED &&
	  H5Tequal(numbertype, H5T_NATIVE_LDOUBLE)!= SUCCEED &&
          H5Tequal(numbertype, H5T_C_S1) != SUCCEED
	  )
	{
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, 
		  "Invalid (unsupported) data type. \n");
	  HE5_EHprint("Error: Invalid (unsupported) data type, occured", __FILE__, __LINE__);
	  return(FAIL);
	}
    }
	
	
  /* Get the field group ID */
  /*----------------------- */
  if (strcmp(fieldtype, "Data Fields") == 0)
    {
      gid = HE5_SWXSwath[idx].data_id;
      fac = 1;
    }
  else if (strcmp(fieldtype, "Geolocation Fields") == 0)
    {
      gid = HE5_SWXSwath[idx].geo_id;
      fac = 2;
    }
  else
    {
      sprintf(errbuf,"Invalid (unsupported) field group. \n");
      H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return (FAIL);	  
    }
	
  /* Create dataspace then create dataset */
  /*------------------------------------ */
  if( HE5_SWXSwath[idx].plist == FAIL )  
    {   
      HE5_SWXSwath[idx].plist = H5Pcreate(H5P_DATASET_CREATE);
    }

  /* Get dataset layout */
  /* ------------------ */
  layout = H5Pget_layout(HE5_SWXSwath[idx].plist);
  if( layout == H5D_LAYOUT_ERROR)
    {
      H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_ARGS, H5E_BADVALUE, 
	      "Cannot get dataset layout.\n");
      HE5_EHprint("Error: Cannot get dataset layout, occured", __FILE__, __LINE__);
      return(FAIL);
    }	

  if(append == FALSE)
    data_space = H5Screate_simple(rank, dims, NULL);
  else
    {
      if( layout == H5D_CHUNKED)
	data_space = H5Screate_simple(rank, dims, maxdims);
      else
	{
	  status = FAIL;
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_ARGS, H5E_BADVALUE, 
		  "Appendable dataset MUST BE CHUNKED first.\n");
	  HE5_EHprint("Error: Appendable dataset MUST BE CHUNKED first, occured", __FILE__, __LINE__);
	  return(status);
	}
    }
	
  /* Get current compression code */
  /* ---------------------------- */
  compcode = HE5_SWXSwath[idx].compcode;

  /* Note: in inquiry routines HE5T_CHARSTRING is distinguished 
     from HE5T_NATIVE_CHAR for the field data (not attributes) based
     on whether string has variable or fixed length as set below.
     The field data of type HE5T_NATIVE_CHAR has fixed length of 1, and
     the field is array of characters, not strings. However, HE5T_CHARSTRING
     sets array of vaiable length strings for the field data.
     Currently HE5_EHattr treats HE5T_NATIVE_CHAR, HE5T_CHARSTRING, and
     H5T_C_S1 as fixed (any size) for attributes. 
  */
  ntype = numbertype;
  if ((numbertype == HE5T_CHARSTRING) || (numbertype == H5T_C_S1))
    {
      ntype = H5Tcopy(H5T_C_S1);
      status = H5Tset_size(ntype, H5T_VARIABLE);
      if( status == FAIL)
	{
	  sprintf(errbuf, "Cannot set HDF5 datatype size for \"%s\" field. \n", fieldname);
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}

      /* Create dataset */
      /* -------------- */
      dataset = H5Dcreate(gid, fieldname, ntype, data_space, HE5_SWXSwath[idx].plist);
      if (dataset == FAIL)
        {
          status = FAIL;
          sprintf(errbuf, "Cannot create dataset for \"%s\" field. \n", fieldname);
          H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          return(status);
        }

    }
  else if (numbertype == H5T_NATIVE_CHAR)
    {
      ntype = H5Tcopy(H5T_C_S1);
      status = H5Tset_size(ntype, 1);
      if( status == FAIL)
	{
	  sprintf(errbuf, "Cannot set HDF5 datatype size for \"%s\" field. \n", fieldname);
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
 
      /* Create dataset */
      /* -------------- */
      dataset = H5Dcreate(gid, fieldname, ntype, data_space, HE5_SWXSwath[idx].plist);
      if (dataset == FAIL)
        {
          status = FAIL;
          sprintf(errbuf, "Cannot create dataset for \"%s\" field. \n", fieldname);
          H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          return(status);
        }
 
    }
  else
    {
      /* Create dataset */
      /* -------------- */
      dataset = H5Dcreate(gid, fieldname, numbertype, data_space, HE5_SWXSwath[idx].plist);
      if (dataset == FAIL)
	{
	  status = FAIL;
	  sprintf(errbuf, "Cannot create dataset for \"%s\" field. \n", fieldname);
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);   
	}
    }
    
  /* Extend the dataset. assure that dataset is at least dims */
  /* -------------------------------------------------------- */
  if( append == TRUE)
    {
      status = H5Dextend(dataset,dims);
      if (status == FAIL)
	{
	  sprintf(errbuf, "Cannot extend the dataset for \"%s\" field.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);   
	}
    }
    
	
  /* load external array */
  /* ------------------- */
  if ( fac == 2 )				/*"Geo fields"*/
    {
      /* Store dataset IDs and dataset name */
      /* ---------------------------------- */
      if (HE5_SWXSwath[idx].nGFLD > 0)
	{
	  /* allocate memory to gdataset struct */
	  /* ---------------------------------- */
	  HE5_SWXSwath[idx].gdataset = (HE5_DTSinfo *)realloc((void *)HE5_SWXSwath[idx].gdataset, (HE5_SWXSwath[idx].nGFLD + 1) * sizeof(HE5_DTSinfo));
	}
      else
	{
	  HE5_SWXSwath[idx].gdataset = (HE5_DTSinfo *)calloc(1, sizeof(HE5_DTSinfo));
	  if (HE5_SWXSwath[idx].gdataset == NULL )
	    {
	      status = FAIL;
	      H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_RESOURCE, H5E_NOSPACE, 
		      "Cannot allocate memory. \n");
	      HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	      return(status);
	    }
	}
		
		
      /* Allocate memory to name */
      /* ----------------------- */
      HE5_SWXSwath[idx].gdataset[HE5_SWXSwath[idx].nGFLD].name = 
	(char *)calloc( (strlen(fieldname)+1), sizeof(char) );
      if (HE5_SWXSwath[idx].gdataset[HE5_SWXSwath[idx].nGFLD].name == NULL)
	{
	  status = FAIL;
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_RESOURCE, H5E_NOSPACE, 
		  "Cannot allocate memory.\n");
	  HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	  return(status);
	}
		
      /* Load table */
      /* ---------- */
      HE5_SWXSwath[idx].gdataset[HE5_SWXSwath[idx].nGFLD].ID = dataset;
      strcpy(HE5_SWXSwath[idx].gdataset[HE5_SWXSwath[idx].nGFLD].name, fieldname);
		
      HE5_SWXSwath[idx].nGFLD++;
    }
  else	 /* "Data Fields" */
    {
      /* store dataset IDs and dataset name */
      /* ---------------------------------- */
      if (HE5_SWXSwath[idx].nDFLD > 0)
	{
	  /* Allocate memory to ddataset struct */
	  /* ---------------------------------- */
	  HE5_SWXSwath[idx].ddataset = (HE5_DTSinfo *)realloc((void *)HE5_SWXSwath[idx].ddataset,(HE5_SWXSwath[idx].nDFLD + 1) * sizeof(HE5_DTSinfo));
			
	}
      else
	{
	  HE5_SWXSwath[idx].ddataset = (HE5_DTSinfo *)calloc(1, sizeof(HE5_DTSinfo));
	  if (HE5_SWXSwath[idx].ddataset == NULL )
	    {
	      status = FAIL;
	      H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_RESOURCE, H5E_NOSPACE, 
		      "Cannot allocate memory. \n");
	      HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	      return(status);
	    }	  
			
	}
		
      /* Allocate memory to name */
      /* ----------------------- */
      HE5_SWXSwath[idx].ddataset[HE5_SWXSwath[idx].nDFLD].name = 
	(char *)calloc( (strlen(fieldname)+1), sizeof(char) );
      if (HE5_SWXSwath[idx].ddataset[HE5_SWXSwath[idx].nDFLD].name == NULL)
	{
	  status = FAIL;
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_RESOURCE, H5E_NOSPACE, 
		  "Cannot allocate memory.\n");
	  HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	  return(status);
	}

      /* load table */
      /* ---------- */
      HE5_SWXSwath[idx].ddataset[HE5_SWXSwath[idx].nDFLD].ID = dataset;
      strcpy(HE5_SWXSwath[idx].ddataset[HE5_SWXSwath[idx].nDFLD].name, fieldname);
      HE5_SWXSwath[idx].nDFLD++;
    }
	
  if ((numbertype != HE5T_CHARSTRING) && (numbertype != H5T_NATIVE_CHAR) && (numbertype != H5T_C_S1))
    {
      /* Get the size of a datatype in bytes */
      /* ----------------------------------- */ 
      tsize = H5Tget_size( numbertype);
      if( tsize == 0)
	{
	  sprintf(errbuf, "Cannot get the size of a datatype. \n");
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return (FAIL);
	}
  
      /* allocate memory for "fill" value */
      /* -------------------------------- */
      value = (void *)calloc(1, tsize);
      if( value == (void *)NULL)
	{
	  sprintf(errbuf, "Cannot allocate memory for fill value.\n");
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return (FAIL);
	}
	
      /* Try to retrieve the fill value (in case it's already defined) */
      /* ------------------------------------------------------------- */ 

      H5E_BEGIN_TRY {
	status = H5Pfill_value_defined(HE5_SWXSwath[idx].plist, &fill_status );
      }
      H5E_END_TRY;
      if (fill_status == H5D_FILL_VALUE_USER_DEFINED)
	{
	  H5E_BEGIN_TRY {
	    status = H5Pget_fill_value(HE5_SWXSwath[idx].plist,  numbertype,  value);
	  }
	  H5E_END_TRY;
	  
	  /* Store fill value in the dataset attribute "_FillValue" */
	  /* -----------------------------------------------------  */ 
	  if( status != FAIL)
	    {
	      status = HE5_EHattr( dataset, "_FillValue", numbertype, count, "w", value);
	      if( status == FAIL )
		{
		  sprintf(errbuf, "Cannot store fill value in the attribute \"_FillValue\".");
		  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  free(value);
		  return (status);
		}
	    }
	}
    
      free( value);

    }

	
  /*  
******************************************************************
*                  SET   UP  METADATA  STRINGS                   *
******************************************************************
*/
	
	
  /*  set up "DimList" string content */
  /*  ------------------------------- */
  strcpy(utlbuf,"");
  sprintf(utlbuf, "%s%s%s", fieldname,":",dimlist);
    
  /* set up "MaxdimList"  string content */
  /* ----------------------------------- */ 
  if ( maxdimlist != NULL)
    {
      status = HE5_EHmetalist(maxdimlist,maxdimlstbuf);
      if (status == FAIL)
	{
	  sprintf(errbuf, "Cannot convert the input \"%s\" list to the metadata list. \n", maxdimlist);
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return (status);
	}
      sprintf(utlbuf2,"%s%s",":\n\t\t\t\tMaxdimList=", maxdimlstbuf);
      strcat(utlbuf,utlbuf2);
		 
    }
  if (maxdimlist == NULL)
    {
      status = HE5_EHmetalist(dimlist,dimlstbuf);
      if (status == FAIL)
	{
	  sprintf(errbuf, "Cannot convert the input \"%s\" list to the metadata list.\n", dimlist);
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return (status);
	}
      sprintf(utlbuf2,"%s%s",":\n\t\t\t\tMaxdimList=", dimlstbuf);
      strcat(utlbuf,utlbuf2);       
		
    }
    
  /* setup "CompressionType" & "CompressionParams" strings content */
  /* ------------------------------------------------------------- */
  if (compcode != HE5_HDFE_COMP_NONE)
    {
      sprintf(utlbuf2,"%s%s","\n\t\t\t\tCompressionType=", HDFcomp[compcode]);
		
      switch (compcode)
	{
	case HE5_HDFE_COMP_NBIT:

	  sprintf(compparmbuf,
		  "%s%d,%d,%d,%d%s",
		  "\n\t\t\t\tCompressionParams=(",
		  HE5_SWXSwath[idx].compparm[0],
		  HE5_SWXSwath[idx].compparm[1],
		  HE5_SWXSwath[idx].compparm[2],
		  HE5_SWXSwath[idx].compparm[3], ")");
	  strcat(utlbuf2, compparmbuf);
	  break;
			
			
	case HE5_HDFE_COMP_DEFLATE:
			
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tDeflateLevel=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;

	case HE5_HDFE_COMP_SZIP_CHIP:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;

	case HE5_HDFE_COMP_SZIP_K13:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;

	case HE5_HDFE_COMP_SZIP_EC:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;

	case HE5_HDFE_COMP_SZIP_NN:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;

	case HE5_HDFE_COMP_SZIP_K13orEC:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;

	case HE5_HDFE_COMP_SZIP_K13orNN:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;

	case HE5_HDFE_COMP_SHUF_DEFLATE:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tDeflateLevel=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;
 
	case HE5_HDFE_COMP_SHUF_SZIP_CHIP:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;
 
	case HE5_HDFE_COMP_SHUF_SZIP_K13:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;
 
	case HE5_HDFE_COMP_SHUF_SZIP_EC:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;
 
	case HE5_HDFE_COMP_SHUF_SZIP_NN:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;
 
	case HE5_HDFE_COMP_SHUF_SZIP_K13orEC:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;
 
	case HE5_HDFE_COMP_SHUF_SZIP_K13orNN:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;

	default:
	  {
	    sprintf(errbuf,"Compression code \"%d\" is not supported. \n", compcode);
	    H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_ARGS, H5E_UNSUPPORTED, errbuf);
	    HE5_EHprint(errbuf, __FILE__, __LINE__);
	  }
			
	  break;		    
			
			
	}
		
      /* Concatanate compression parameters with compression code */
      /* -------------------------------------------------------- */
      strcat(utlbuf, utlbuf2);
    }
	
	
  /* 
******************************************************************
*   Insert metadata information to Structural Metadata section   *
******************************************************************
*/          
  numtype = HE5_EHdtype2numtype(numbertype);
  if (numtype == FAIL)
    {
      sprintf(errbuf, "Cannot get the number type ID. \n");
      H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  else if (numtype == 0)
    {
      metavalue = 0;
    }
  else
    {
      metavalue = HE5_EHhid2hsize(numtype);
      if (metavalue == 0)
	{
	  sprintf(errbuf, "Cannot convert \"hid_t\" to \"hsize_t\" data type. \n");
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
    }

  if (strcmp(fieldtype, "Geolocation Fields") == 0)
    status = HE5_EHinsertmeta(fid, HE5_SWXSwath[idx].swname, "s", 3L, utlbuf, &metavalue);
  else
    status = HE5_EHinsertmeta(fid, HE5_SWXSwath[idx].swname, "s", 4L, utlbuf, &metavalue);
	
  if (status == FAIL)
    {
      sprintf(errbuf, "Cannot insert metadata for \"%s\" field.\n", fieldname);
      H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);   
    }

  /* Release data space ID */
  /* --------------------- */
  status =  H5Sclose(data_space);
  if (status == FAIL)
    {
      H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_DATASPACE, H5E_CLOSEERROR, "Cannot release the data space ID.\n");
      HE5_EHprint("Error: Cannot release the data space ID, occured", __FILE__, __LINE__);
      return(status);   
    }

  /* Release property list ID */
  /* ------------------------ */
  status = H5Pclose(HE5_SWXSwath[idx].plist);
  if (status == FAIL)
    {
      H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_PLIST, H5E_CLOSEERROR, "Cannot release the property list ID.\n");
      HE5_EHprint("Error: Cannot release the property list ID, occured", __FILE__, __LINE__);
      return(status);
    }
	
  /* Reset external array entry for next dataset creation */
  /* ==================================================== */
  HE5_SWXSwath[idx].plist    = FAIL;
  HE5_SWXSwath[idx].compcode = HE5_HDFE_COMP_NONE; 

  if ((numbertype == HE5T_CHARSTRING) || (numbertype == H5T_C_S1))
    {
      attr = HE5T_CHARSTRING;
      status = HE5_SWwritelocattr(swathID, fieldname, "ARRAYOFSTRINGS", H5T_NATIVE_INT, count, &attr);
      if (status == FAIL)
	{
	  sprintf(errbuf, "Cannot write attribute to the field \"%s\".",fieldname) ;
	  H5Epush(__FILE__, "HE5_SWdefinefield", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}

    }

		
 COMPLETION:
  return(status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefgeofield                                                |
|                                                                             |
|  DESCRIPTION: Defines geolocation field within swath structure (wrapper)    |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t  None        return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWdefgeofield(hid_t swathID, const char *fieldname, char *dimlist, char *maxdimlist, hid_t numbertype_in , int merge)
{
  herr_t            status     = FAIL;          /* Return status variable   */
  hid_t             numbertype;
  char          errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer   */

  HE5_LOCK;
  CHECKNAME(fieldname);
  CHECKPOINTER(dimlist);

  /* Convert HDF-EOS5 datatype to HDF5 datatype */
  if (
      H5Tequal(numbertype_in, H5T_NATIVE_CHAR)   == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_SCHAR)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_UCHAR)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_SHORT)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_USHORT) == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_INT)    == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_UINT)   == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_LONG)   == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_ULONG)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_LLONG)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_ULLONG) == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_FLOAT)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_DOUBLE) == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_LDOUBLE)== SUCCEED ||
      H5Tequal(numbertype_in, H5T_C_S1) == SUCCEED)
    {
      numbertype = numbertype_in;
    }
  else
    {
      numbertype = HE5_EHconvdatatype((int) numbertype_in);
    }

  if(numbertype == FAIL)
    {
      sprintf(errbuf,"Cannot convert to HDF5 type data type ID for Geolocation Field.\n");
      H5Epush(__FILE__, "HE5_SWdefdatafield", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }


  /* Call HE5_SWdefinefield routine  */
  /* ==============================  */
  status = HE5_SWdefinefield(swathID, "Geolocation Fields", fieldname, dimlist, maxdimlist,  numbertype, merge);

 COMPLETION:
  HE5_UNLOCK;
  return (status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefdatafield                                               |
|                                                                             |
|  DESCRIPTION: Defines data field within swath structure (wrapper)           |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t  None        return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_SWdefdatafield(hid_t swathID, const char *fieldname, char *dimlist, char *maxdimlist, hid_t numbertype_in, int merge)
{
  herr_t       status     = FAIL;          /* routine return status variable */
  hid_t        numbertype;
  char         errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer   */

  HE5_LOCK;
  CHECKNAME(fieldname);
  CHECKPOINTER(dimlist);

  /* Convert HDF-EOS5 datatype to HDF5 datatype */
  if (
      H5Tequal(numbertype_in, H5T_NATIVE_CHAR)   == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_SCHAR)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_UCHAR)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_SHORT)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_USHORT) == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_INT)    == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_UINT)   == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_LONG)   == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_ULONG)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_LLONG)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_ULLONG) == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_FLOAT)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_DOUBLE) == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_LDOUBLE)== SUCCEED ||
      H5Tequal(numbertype_in, H5T_C_S1) == SUCCEED)
    {
      numbertype = numbertype_in;
    }
  else
    {
      numbertype = HE5_EHconvdatatype((int) numbertype_in);
    }

  if(numbertype == FAIL)
    {
      sprintf(errbuf,"Cannot convert to HDF5 type data type ID for Data Field.\n");
      H5Epush(__FILE__, "HE5_SWdefdatafield", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }



  /* Call HE5_SWdefinefield routine  */
  /* ==============================  */
  status = HE5_SWdefinefield(swathID, "Data Fields", fieldname, dimlist,maxdimlist,numbertype, merge);

 COMPLETION:
  HE5_UNLOCK;
  return (status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWwritedatameta                                              |
|                                                                             |
|  DESCRIPTION: Defines structural metadata for pre-existing data             |
|               field within swath structure                                  |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t  None        return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath object ID                         |
|  fieldname      char                fieldname                               |
|  dimlist        char                Dimension list (comma-separated list)   |
|  mvalue         hid_t               metavalue to insert                     |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|  May  05  S.Zhao        Added HE5_EHdtype2numtype() function call.          |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWwritedatameta(hid_t swathID, const char *fieldname, char *dimlist, hid_t mvalue)
{
  herr_t        status     = FAIL;          /* Return status variable */

  hid_t         fid        = FAIL;          /* HDF-EOS file ID        */
  hid_t         gid        = FAIL;          /* "HDFEOS" group ID      */

  hsize_t       metavalue  =  0;            /* Metavalue to insert    */

  long          idx        = FAIL;          /* Swath index            */

  char          errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer   */
  char          utlbuf[HE5_HDFE_DIMBUFSIZE];/* Utility buffer         */
  hid_t         numtype    = FAIL;          /* Number type ID         */

  HE5_LOCK;
  CHECKNAME(fieldname);
  CHECKPOINTER(dimlist);
 
  numtype = HE5_EHdtype2numtype(mvalue);
  if (numtype == FAIL)
    {
      sprintf(errbuf, "Cannot get the number type ID. \n");
      H5Epush(__FILE__, "HE5_SWwritedatameta", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  else if (numtype == 0)
    {
      metavalue = 0;
    }
  else
    {
      /* Convert 'numtype' to 'metavalue' */
      /* -------------------------------- */    
      metavalue = HE5_EHhid2hsize(numtype);
      if ( metavalue == 0 )
	{
	  sprintf(errbuf, "Cannot convert metadata value. \n");
	  H5Epush(__FILE__, "HE5_SWwritedatameta", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
    }


  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWwritedatameta", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Setup and write field metadata */
      /* ------------------------------ */
      sprintf(utlbuf, "%s%s%s", fieldname, ":", dimlist);
      status = HE5_EHinsertmeta(gid, HE5_SWXSwath[idx].swname, "s", 4L, utlbuf, &metavalue);
      if ( status == FAIL )
	{
	  sprintf(errbuf, "Cannot insert metadata value. \n");
	  H5Epush(__FILE__, "HE5_SWwritedatameta", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	}
    }

 COMPLETION:
  HE5_UNLOCK;
  return (status);
}





/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWwritegeometa                                               |
|                                                                             |
|  DESCRIPTION: Defines structural metadata for pre-existing data             |
|               field within swath structure                                  |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t  None        return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath object ID                         |
|  fieldname      char                fieldname                               |
|  dimlist        char                Dimension list (comma-separated list)   |
|  mvalue         hid_t               metadata value to write                 |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|  May  05  S.Zhao        Added HE5_EHdtype2numtype() function call.          |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_SWwritegeometa(hid_t swathID, const char *fieldname, char *dimlist, hid_t mvalue)
{
  herr_t        status     = FAIL;/* routine return status variable */

  hid_t         fid        = FAIL;/* HDF-EOS file ID                */
  hid_t         gid        = FAIL;/* "HDFEOS" group ID              */

  hsize_t       metavalue  =  0;  /* Metavalue to insert            */

  long          idx        = FAIL;/* Swath index                    */
  
  char          errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */ 
  char          utlbuf[HE5_HDFE_DIMBUFSIZE];/* Utility buffer       */
  hid_t         numtype    = FAIL;          /* Number type ID       */

  HE5_LOCK;
  CHECKNAME(fieldname);
  CHECKPOINTER(dimlist);

  numtype = HE5_EHdtype2numtype(mvalue);
  if (numtype == FAIL)
    {
      sprintf(errbuf, "Cannot get the number type ID. \n");
      H5Epush(__FILE__, "HE5_SWwritegeometa", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  else if (numtype == 0)
    {
      metavalue = 0;
    }
  else
    {
      /* Convert 'numtype' to 'metavalue' */
      /* -------------------------------- */
      metavalue = HE5_EHhid2hsize(numtype);
      if ( metavalue == 0 )
	{
	  sprintf(errbuf, "Cannot convert metadata value. \n");
	  H5Epush(__FILE__, "HE5_SWwritegeometa", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
    }


  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWwritegeometa", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Setup and write field metadata */
      /* ------------------------------ */
      sprintf(utlbuf, "%s%s%s", fieldname, ":", dimlist);
      status = HE5_EHinsertmeta(gid, HE5_SWXSwath[idx].swname, "s", 3L, utlbuf, &metavalue);
      if ( status == FAIL )
	{
	  sprintf(errbuf, "Cannot insert metadata value. \n");
	  H5Epush(__FILE__, "HE5_SWwritegeometa", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	}
    }

 COMPLETION:
  HE5_UNLOCK;
  return (status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWwriteattr                                                  |
|                                                                             |
|  DESCRIPTION: Writes/updates attribute in a swath.                          |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  attrname       char                attribute name                          |
|  numtype        hid_t               attribute dataset datatype ID           |
|  count[]        hsize_t             Number of attribute elements            |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_SWwriteattr(hid_t swathID, const char *attrname, hid_t numtype, hsize_t count[], void *datbuf)
{
  herr_t     status     = FAIL;          /* Return status variable  */

  hid_t      fid        = FAIL;          /* HDF-EOS file ID         */
  hid_t      gid        = FAIL;          /* "HDFEOS" group ID       */

  long       idx        = FAIL;          /* Swath index             */

  char       errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer    */
  hid_t      numbertype;

  HE5_LOCK;
  CHECKNAME(attrname);
  CHECKPOINTER(count);
  CHECKPOINTER(datbuf);

  /* if numtype is HE5 numbertype, rather than H5 numbertype, then convert
     it, otherwise use numtype itself
  */
  numbertype = HE5_EHconvdatatype(numtype);
  if(numbertype == FAIL)
    {
      numbertype = numtype;
    }

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWwriteattr", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Call HE5_EHattr to perform I/O */
      /* ------------------------------ */
      status = HE5_EHattr(HE5_SWXSwath[idx].sw_id, attrname, numbertype, count,"w", datbuf);
      if ( status == FAIL )
	{
	  sprintf(errbuf, "Cannot write the attribute value. \n");
	  H5Epush(__FILE__, "HE5_SWwriteattr", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	}
    }
  
 COMPLETION:
  HE5_UNLOCK;
  return (status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWrdadattr                                                   |
|                                                                             |
|  DESCRIPTION: Reads attribute from a swath.                                 |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  attrname       char                attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWreadattr(hid_t swathID, const char *attrname, void *datbuf)
{
  herr_t      status  = FAIL;             /* Return status variable  */

  hid_t       fid     = FAIL;             /* HDF-EOS file ID         */
  hid_t       gid     = FAIL;             /* "HDFEOS" group ID       */
  hid_t       ntype   = FAIL;             /* Data type ID            */  

  long        idx     = FAIL;             /* Swath index             */
  
  hsize_t     count[] ={0};               /* Number of elements      */

  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer    */

  HE5_LOCK;
  CHECKPOINTER(attrname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWreadattr", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Call HE5_EHattr to perform I/O */
      /* ------------------------------ */
      status = HE5_EHattr(HE5_SWXSwath[idx].sw_id, attrname, ntype, count,"r", datbuf);
      if ( status == FAIL )
	{
	  sprintf(errbuf, "Cannot read the attribute value. \n");
	  H5Epush(__FILE__, "HE5_SWreadattr", __LINE__, H5E_ATTR, H5E_READERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	}
    }

 COMPLETION:
  HE5_UNLOCK;
  return (status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWattrinfo                                                   |
|                                                                             |
|  DESCRIPTION:                                                               |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  attrname       const char*         attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  ntype          hid_t               Data type ID                            |
|  count          hsize_t             Number of attribute elements            |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date       Programmer   Description                                       |
|  ========   ============  ================================================= |
|  05/10/00   A.Muslimov    Replaced 'H5T_class_t' type by 'int' data type.   |
|  July 00    A.Muslimov    Unmasked hdf5 data types.                         |
|  Feb  03    S.Zhao        Changed the type of 'ntype' from an H5T_class_t   |
|                           to an hid_t.                                      |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWattrinfo(hid_t swathID, const char *attrname, hid_t *ntype, hsize_t *count)
{
  herr_t        status  = FAIL;             /* Return status variable  */

  hid_t         fid     = FAIL;             /* HDF-EOS file ID         */
  hid_t         gid     = FAIL;             /* "HDFEOS" group ID       */

  long          idx     = FAIL;             /* Swath index             */

  char          errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer    */

  CHECKPOINTER(attrname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWattrinfo", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Get attribute group ID and call HE5_EHattrinfo */
      /* ---------------------------------------------- */
      status = HE5_EHattrinfo(HE5_SWXSwath[idx].sw_id, attrname, ntype, count);
      if ( status == FAIL )
	{
	  sprintf(errbuf, "Cannot retrieve information about attribute. \n");
	  H5Epush(__FILE__, "HE5_SWattrinfo", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	}
    }

 COMPLETION:
  return (status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWattrinfo2                                                  |
|                                                                             |
|  DESCRIPTION:                                                               |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  attrname       const char*         attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  ntype          hid_t               Data type ID                            |
|  count          hsize_t             Number of attribute elements            |
|  size           hsize_t             buf size of attribute elements          |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date       Programmer   Description                                       |
|  ========   ============  ================================================= |
|  05/10/00   A.Muslimov    Replaced 'H5T_class_t' type by 'int' data type.   |
|  July 00    A.Muslimov    Unmasked hdf5 data types.                         |
|  Feb  03    S.Zhao        Changed the type of 'ntype' from an H5T_class_t   |
|                           to an hid_t.                                      |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWattrinfo2(hid_t swathID, const char *attrname, hid_t *ntype, hsize_t *count, hsize_t *size)
{
  herr_t        status  = FAIL;             /* Return status variable  */

  hid_t         fid     = FAIL;             /* HDF-EOS file ID         */
  hid_t         gid     = FAIL;             /* "HDFEOS" group ID       */

  long          idx     = FAIL;             /* Swath index             */

  char          errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer    */

  CHECKPOINTER(attrname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWattrinfo", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Get attribute group ID and call HE5_EHattrinfo */
      /* ---------------------------------------------- */
      status = HE5_EHattrinfo2(HE5_SWXSwath[idx].sw_id, attrname, ntype, count, size);
      if ( status == FAIL )
	{
	  sprintf(errbuf, "Cannot retrieve information about attribute. \n");
	  H5Epush(__FILE__, "HE5_SWattrinfo2", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	}
    }

 COMPLETION:
  return (status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqattrs                                                   |
|                                                                             |
|  DESCRIPTION:                                                               |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nattr          long                Number of attributes in swath struct    |
|                                                                             |
|  INPUTS:                                                                    |
|  swath ID       hid_t               Swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  attrnames      char                Attribute names in swath struct         |
|                                     (Comma-separated list)                  |
|  strbufsize     long                Attributes name list string length      |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWinqattrs(hid_t swathID, char *attrnames, long *strbufsize)
{
  long            nattr    = FAIL;/* Number of attributes (return)    */
  long            idx      = FAIL;/* Swath index                      */

  herr_t          status   = FAIL;/* routine return status variable   */

  hid_t           fid      = FAIL;/* HDF-EOS file ID                  */
  hid_t           gid      = FAIL;/* swath group ID                   */

  char            *grpname = (char *)NULL;/* Group name string        */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */


  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWinqattrs", &fid, &gid, &idx);
  if(status == SUCCEED )
    {
      grpname = (char *)calloc( HE5_HDFE_NAMBUFSIZE, sizeof(char) );
      if( grpname == NULL)
        {
          H5Epush(__FILE__, "HE5_SWinqattrs", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory");
          HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
          return(FAIL);
        }

      strcpy(grpname,"/HDFEOS/SWATHS/");
      strcat(grpname, HE5_SWXSwath[idx].swname);

      nattr = HE5_EHattrcat(fid,  grpname, attrnames, strbufsize);
      if ( nattr == FAIL )
	{
	  sprintf(errbuf, "Cannot find the attributes. \n");
	  H5Epush(__FILE__, "HE5_SWinqattrs", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	}

      if (grpname != NULL) free(grpname);

    }

  return (nattr);
}


#define REMQUOTE					\
							\
  memmove(utlstr, utlstr + 1, strlen(utlstr) - 2);	\
  utlstr[strlen(utlstr) - 2] = 0;


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqdims                                                    |
|                                                                             |
|  DESCRIPTION: Returns dimension names and values defined in swath structure |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nDim           long                Number of defined dimensions            |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  dimnames       char                Dimension names (comma-separated)       |
|  dims           hsize_t             Dimension values                        |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  3/22/99                                                                    |
|  7/29/99  A.Muslimov    In the call to EHmetagroup() replace gid by fid.    |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWinqdims(hid_t swathID, char *dimnames, hsize_t dims[])
{
  herr_t         status    = FAIL;/* routine return status variable      */

  hid_t          fid       = FAIL;/* HDF-EOS file ID                     */
  hid_t          gid       = FAIL;/* "HDFEOS" group ID                   */

  long           idx       = FAIL;/* Swath index                         */
  long           nDim      =  0;  /* Number of dimensions                */

  hsize_t        size      =  0;  /* Dimension size                      */

  char           *metabuf = (char *)NULL;     /* Pointer to SM           */
  char           *metaptrs[2]={NULL,NULL};    /* Ptrs to start/end of SM */
  char           utlstr[HE5_HDFE_UTLBUFSIZE]; /* Utility string          */
  char           errbuf[HE5_HDFE_ERRBUFSIZE]; /* Error message buffer    */


  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWinqdims", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for Swath ID failed.\n");
      H5Epush(__FILE__, "HE5_SWinqdims", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
  /* If dimension names or sizes are desired ... */
  /* ------------------------------------------- */
  if (dimnames != NULL || dims != NULL)
    {
      /* Get pointers to "Dimension" section within SM */
      /* --------------------------------------------- */
      metabuf = (char *)HE5_EHmetagroup(fid, HE5_SWXSwath[idx].swname, "s", "Dimension", metaptrs);
	  
      /* If dimension names are desired then "clear" name buffer */
      /* ------------------------------------------------------- */
      if (dimnames != NULL)
	dimnames[0] = 0;
	  
      /* Begin loop through dimension entries in metadata */
      /* ------------------------------------------------ */
      while (1)
	{
	  /* Search for OBJECT string */
	  /* ------------------------ */
	  metaptrs[0] = strstr(metaptrs[0], "\t\tOBJECT=");
	  /* If found within "Dimension" metadata section ... */
	  /* ------------------------------------------------ */
	  if (metaptrs[0] < metaptrs[1] && metaptrs[0] != NULL)
	    {
	      /* Get Dimension Name (if desired) */
	      /* ------------------------------- */
	      if (dimnames != NULL)
		{
		  /* Check 1st for old meta data then new */
		  /* ------------------------------------ */
		  HE5_EHgetmetavalue(metaptrs, "OBJECT", utlstr);
				  
		  /*
		   * If OBJECT value begins with double quote then old
		   * metadata, dimension name is OBJECT value.
		   * Otherwise search for "DimensionName" string
		   */
		  if (utlstr[0] != '"')
		    {
		      metaptrs[0] = strstr(metaptrs[0], "\t\t\t\tDimensionName=");
		      HE5_EHgetmetavalue(metaptrs, "DimensionName", utlstr);
		    }
				  
		  /* Strip off double quotes */
		  /* ----------------------- */
		  REMQUOTE
						
		    /* If not first name then add comma delimitor */
		    /* ------------------------------------------ */
		    if (nDim > 0)
		      {
			strcat(dimnames, ",");
		      }
				  
		  /* Add dimension name to dimension list */
		  /* ------------------------------------ */
		  strcat(dimnames, utlstr);
		}
			  
	      /* Get Dimension Size (if desired) */
	      /* ------------------------------- */
	      if (dims != NULL)
		{
		  HE5_EHgetmetavalue(metaptrs, "Size", utlstr);
		  size = (hsize_t)atol(utlstr);
		  dims[ nDim ] = size;
		}
	      /* Increment dimension counter */
	      /* --------------------------- */
	      nDim++;
	    }
	  else
	    /* No more dimensions found */
	    /* ------------------------ */
	    break;
	}
	  
      free(metabuf);
    }
  
  return(nDim);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqmaps                                                    |
|                                                                             |
|  DESCRIPTION: Returns dimension mappings and offsets and increments         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nMap           long                Number of dimension mappings            |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  dimmaps        char                dimension mappings (comma-separated)    |
|  offset         long                array of offsets                        |
|  increment      long                array of increments                     |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|                                                                             |
|  7/29/99  A.Muslimov    In the call to EHmetagroup() replace gid by fid.    |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWinqmaps(hid_t swathID, char *dimmaps, long offset[], long increment[])
{
  herr_t         status    = FAIL;           /* Return status variable  */

  hid_t          fid       = FAIL;           /* HDF-EOS file ID         */
  hid_t          gid       = FAIL;           /* "HDFEOS" group ID       */

  long           idx       = FAIL;           /* Swath index             */
  long           off       = 0;              /* Mapping Offset          */
  long           incr      = 0;	             /* Mapping Increment       */
  long           nMap      = 0;	             /* Number of mappings      */

  char           *metabuf = (char *)NULL;    /* Pntr to SM              */
  char           *metaptrs[2]={NULL,NULL};   /* Ptrs to start/end of SM */
  char           utlstr[HE5_HDFE_UTLBUFSIZE];/* Utility string          */
  char           errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer    */


  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWinqmaps", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for Swath ID failed.\n");
      H5Epush(__FILE__, "HE5_SWinqmaps", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* If mapping names or offsets or increments desired ... */
  /* ----------------------------------------------------- */
  if (dimmaps != NULL || offset != NULL || increment != NULL)
    {
      /* Get pointers to "DimensionMap" section within SM */
      /* ------------------------------------------------ */
      metabuf = (char *)HE5_EHmetagroup(fid, HE5_SWXSwath[idx].swname, "s", "DimensionMap", metaptrs);

      /* If mapping names are desired then "clear" name buffer */
      /* ----------------------------------------------------- */
      if (dimmaps != NULL)
	dimmaps[0] = 0;
	  
      /* Begin loop through mapping entries in metadata */
      /* ---------------------------------------------- */
      while (1)
	{
	  /* Search for OBJECT string */
	  /* ------------------------ */
	  metaptrs[0] = strstr(metaptrs[0], "\t\tOBJECT=");
		  
	  /* If found within "DimensionMap" metadata section ... */
	  /* --------------------------------------------------- */
	  if (metaptrs[0] < metaptrs[1] && metaptrs[0] != NULL)
	    {
	      /* Get Geo & Data Dimensions (if desired) */
	      /* -------------------------------------- */
	      if (dimmaps != NULL)
		{
		  /* Get Geo Dim, remove quotes, add "/" */
		  /* ----------------------------------- */
		  HE5_EHgetmetavalue(metaptrs, "GeoDimension", utlstr);
		  REMQUOTE
		    strcat(utlstr, "/");

		  /* if not first map then add comma delimitor */
		  /* ----------------------------------------- */
		  if (nMap > 0)
		    {
		      strcat(dimmaps, ",");
		    }
				  
		  /* Add to map list */
		  /* --------------- */
		  strcat(dimmaps, utlstr);
				  
		  /* Get Data Dim, remove quotes */
		  /* --------------------------- */
		  HE5_EHgetmetavalue(metaptrs, "DataDimension", utlstr);
		  REMQUOTE
					
		    /* Add to map list */
		    /* --------------- */
		    strcat(dimmaps, utlstr);
		}

	      /* Get Offset (if desired) */
	      /* ----------------------- */
	      if (offset != NULL)
		{
		  HE5_EHgetmetavalue(metaptrs, "Offset", utlstr);
		  off          = atol(utlstr);
		  offset[nMap] = off;
		}
			  
	      /* Get Increment (if desired) */
	      /* -------------------------- */
	      if (increment != NULL)
		{
		  HE5_EHgetmetavalue(metaptrs, "Increment", utlstr);
		  incr            = atol(utlstr);
		  increment[nMap] = incr;
		}
			  
	      /* Increment map counter */
	      /* --------------------- */
	      nMap++;
	    }
	  else
	    /* No more mappings found */
	    /* ---------------------- */
	    break;
	}
	  
      free(metabuf);
    }
  
  return (nMap);
}




/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqidxmaps                                                 |
|                                                                             |
|  DESCRIPTION: Returns indexed mappings and index sizes                      |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nMap           long                Number of indexed dimension mappings    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  idxmaps        char                indexed dimension mappings              |
|                                     (comma-separated)                       |
|  idxsizes       hsize_t             Number of elements in each mapping      |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|                                                                             |
|  7/29/99  A.Muslimov    In the call to EHmetagroup() replace gid by fid.    |
|  8/20/99  A.Muslimov    Checked for the statuses returned by EHgetmetavalue.|
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWinqidxmaps(hid_t swathID, char *idxmaps, hsize_t idxsizes[])
{
  herr_t          status   = FAIL;               /* Return status variable   */

  hid_t           fid      = FAIL;               /* HDF-EOS file ID          */
  hid_t           gid      = FAIL;               /* "HDFEOS" group ID        */

  long            idx      = FAIL;               /* Swath index              */
  long            nMap     =  0;                 /* Number of mappings       */

  char            *metabuf = (char *)NULL;       /* Pntr to SM               */
  char            *metaptrs[2]={NULL,NULL};      /* Pntrs to start/end of SM */
  char            *utlstr  = (char *)NULL;   	 /* Utility string           */
  char            *slash   = (char *)NULL;       /* Pointer to slash         */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];   /* Error message buffer     */


  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWinqidxmaps", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for Swath ID failed.\n");
      H5Epush(__FILE__, "HE5_SWinqidxmaps", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Allocate space for utility string */
  /* --------------------------------- */
  utlstr = (char *) calloc(HE5_HDFE_DIMBUFSIZE, sizeof(char));
  if ( utlstr == NULL )
    {
      sprintf( errbuf,"Cannot allocate memory for utility string.\n");
      H5Epush(__FILE__, "HE5_SWinqidxmaps", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
	  
      return(FAIL);
    }


  /* If mapping names or index sizes desired ... */
  /* ------------------------------------------- */
  if (idxmaps != NULL || idxsizes != NULL)
    {
      /* Get pointers to "IndexDimensionMap" section within SM */
      metabuf = (char *)HE5_EHmetagroup(fid, HE5_SWXSwath[idx].swname, "s", "IndexDimensionMap", metaptrs);
	  
      /* If mapping names are desired then "clear" name buffer */
      /* ----------------------------------------------------- */
      if (idxmaps != NULL)
	idxmaps[ 0 ] = 0;
	  
      /* Begin loop through mapping entries in metadata */
      /* ---------------------------------------------- */
      while (1)
	{
	  /* Search for OBJECT string */
	  /* ------------------------ */
	  metaptrs[0] = strstr(metaptrs[0], "\t\tOBJECT=");
	  /* If found within "IndexDimensionMap" metadata section ... */
	  /* -------------------------------------------------------- */
	  if (metaptrs[0] < metaptrs[1] && metaptrs[0] != NULL)
	    {
	      /* Get Geo & Data Dimensions and # of indices */
	      /* ------------------------------------------ */
	      if (idxmaps != NULL)
		{
		  /* Get Geo Dim, remove quotes, add "/" */
		  /* ----------------------------------- */
		  status = HE5_EHgetmetavalue(metaptrs, "GeoDimension", utlstr);
		  REMQUOTE
		    strcat(utlstr, "/");
				  
		  /* if not first map then add comma delimitor */
		  /* ----------------------------------------- */
		  if(nMap > 0)
		    strcat(idxmaps, ",");
				  
		  /* Add to map list */
		  /* --------------- */
		  strcat(idxmaps, utlstr);

		  /* Get Index size (if desired) */
		  /* --------------------------- */
		  if (idxsizes != NULL)
		    {
		      /* Parse off geo dimension and find its size */
		      /* ----------------------------------------- */
		      slash = strchr(utlstr, '/');
		      *slash = 0;
		      idxsizes[ nMap ] = HE5_SWdiminfo(swathID, utlstr);
		    }
				  
		  /* Get Data Dim, remove quotes */
		  /* --------------------------- */
		  status = HE5_EHgetmetavalue(metaptrs, "DataDimension", utlstr);
		  REMQUOTE
					
		    /* Add to map list */
		    /* --------------- */
		    strcat(idxmaps, utlstr);
		}
			  
	      /* Increment map counter */
	      /* --------------------- */
	      nMap++;
	    }
	  else
	    /* No more mappings found */
	    /* ---------------------- */
	    break;
	}
	  
      if (metabuf != NULL) free(metabuf);
    }
  
  if(utlstr != NULL) free(utlstr);
  
  return (nMap);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqfields                                                  |
|                                                                             |
|  DESCRIPTION: Returns fieldnames, ranks and numbertypes defined in swath.   |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nFld           long                Number of (geo/data) fields in swath    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  fieldtype      char                field type (geo or data)                |
|                                                                             |
|  OUTPUTS:                                                                   |
|  fieldlist      char                Field names (comma-separated)           |
|  rank           int                 Array of ranks                          |
|  numbertype     hid_t               Array of HDF number types               |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  7/29/99  A.Muslimov    In the call to EHmetagroup() replace gid by fid.    |
|  4/19/00  A.Muslimov    Changed type of 'slen' and 'fldnmlen' from long to  |
|                          size_t.                                            |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  June 02  S.Zhao        Changed the type of 'numbertype' from an H5T_class_t|
|                         to an hid_t.                                        |
|  Oct. 03  S.Zhao        Added the H5Tclose(datatype) call.                  |
|  Oct. 03  S.Zhao        Modified to enable a character string dataset.      |
|  Mar  04  S.Zhao        Modified for a character string dataset.            |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
static long 
HE5_SWinqfields(hid_t swathID, char *fieldtype, char *fieldlist, int rank[], hid_t numbertype[])
{
  long          nFld       =  0;       /* Return number of mappings  */
  long          i          =  0;       /* Loop index                 */
  long          idx        =  FAIL;    /* Swath index                */
  long          ntflds     =  0;       /* field counter              */

  herr_t        status     = FAIL;/* routine return status variable  */
  herr_t        Dstatus    = FAIL;/* Status for H5Dclose             */

  int           groupflag  = FAIL;/* "0" - geolocation, "1" - data   */
 
  hid_t         fid        = FAIL;/* HDF-EOS file ID                 */
  hid_t         gid        = FAIL;/* "HDFEOS" group ID               */
  hid_t         datasetid  = FAIL;/* Dataset ID                      */
  hid_t         datatype   = FAIL;/* Data type ID                    */
  hid_t         groupid    = FAIL;/* Group ID                        */

  H5T_class_t   classid    = H5T_NO_CLASS;   /* Data type class ID   */

  size_t        slen[HE5_DTSETRANKMAX];	     /* String length array  */
  size_t        fldnmlen[HE5_FLDNUMBERMAX];  /* Array of namelengths */

  char          *fldnm[HE5_FLDNUMBERMAX];    /* Array of names       */
  char          *metabuf = (char *)NULL;     /* Pntr to SM           */
  char          *metaptrs[2]={NULL,NULL};    /* Start/end of SM      */
  char          utlstr[HE5_HDFE_UTLBUFSIZE]; /* Utility string       */
  char          utlstr2[HE5_HDFE_UTLBUFSIZE];/* Utility string 2     */
  char          *ptr[HE5_DTSETRANKMAX];	     /* String pointer array */
  char          *tempfield = (char *)NULL;
  char          errbuf[HE5_HDFE_ERRBUFSIZE]; /* Error message buffer */
  htri_t     str_is_variable;                /* boolean: TRUE if 
						string is variable 
						lengeth FALSE if 
						string is fixed length
						-1 if error in 
						H5Tis_variavle_str() */
  
  CHECKPOINTER(fieldtype);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWinqfields", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for Swath ID failed.\n");
      H5Epush(__FILE__, "HE5_SWinqfields", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Initialize slen[] array */
  /* ----------------------- */
  for (i = 0; i < HE5_DTSETRANKMAX; i++)
    slen[i] = 0;

  /* Initialize fldnmlen[] array */
  /* --------------------------- */
  for (i = 0; i < HE5_FLDNUMBERMAX; i++)
    fldnmlen[i] = 0;


  /* If field names, ranks,  or number types desired ... */
  /* --------------------------------------------------- */
  if (fieldlist != NULL || rank != NULL || numbertype != NULL)
    {
      /* Get pointers to "GeoField" or "DataField" section within SM */
      /* ----------------------------------------------------------- */
      if (strcmp(fieldtype, "Geolocation Fields") == 0)
	{
	  metabuf = (char *)HE5_EHmetagroup(fid, HE5_SWXSwath[idx].swname, "s", "GeoField", metaptrs);
	  strcpy(utlstr2, "GeoFieldName");
	  groupflag = 0;
	}
      else
	{
	  metabuf = (char *)HE5_EHmetagroup( fid, HE5_SWXSwath[idx].swname, "s", "DataField", metaptrs);
	  strcpy(utlstr2, "DataFieldName");
	  groupflag = 1;
	}
	  
	  
      /* If field names are desired then "clear" name buffer */
      /* --------------------------------------------------- */
      if (fieldlist != NULL)
	fieldlist[0] = 0;
	  
      /* Begin loop through mapping entries in metadata */
      /* ---------------------------------------------- */
      while (1)
	{
	  /* Search for OBJECT string */
	  /* ------------------------ */
	  metaptrs[0] = strstr(metaptrs[0], "\t\tOBJECT=");
		  
	  /* If found within "Geo" or "Data" Field metadata section ... */
	  /* ---------------------------------------------------------- */
	  if (metaptrs[0] < metaptrs[1] && metaptrs[0] != NULL)
	    {
	      /* Get field names (if desired) */
	      /* ---------------------------- */
	      if (fieldlist != NULL)
		{
		  /* Check 1st for old meta data then new */
		  /* ------------------------------------ */
		  HE5_EHgetmetavalue(metaptrs, "OBJECT", utlstr);

		  /*
		   * If OBJECT value begins with double quote then old
		   * metadata, field name is OBJECT value. Otherwise
		   * search for "GeoFieldName" or "DataFieldName"
		   * string
		   */
				  
		  if (utlstr[0] != '"')
		    {
		      strcpy(utlstr, "\t\t\t\t");
		      strcat(utlstr, utlstr2);
		      strcat(utlstr, "=");
		      metaptrs[0] = strstr(metaptrs[0], utlstr);
		      HE5_EHgetmetavalue(metaptrs, utlstr2, utlstr);
		    }
				  
		  /* Strip off double quotes */
		  /* ----------------------- */
		  REMQUOTE
						
		    /* Add to fieldlist */
		    /* ---------------- */
		    if (nFld > 0)
		      strcat(fieldlist, ",");
				  
		  strcat(fieldlist, utlstr);
				  
		}
			  
	      /* If numbertype  are desired then "clear" name buffer */
	      /* --------------------------------------------------- */
	      if (numbertype != NULL)
		{
		  ntflds = HE5_EHparsestr(fieldlist, ',', fldnm,fldnmlen);
		  if(ntflds != FAIL)
		    {
		      if(groupflag == 0)
			groupid = HE5_SWXSwath[idx].geo_id;
		      else
			groupid = HE5_SWXSwath[idx].data_id;
					  
		      for(i = 0; i < ntflds; i++)
			{
			  tempfield      = (char *)calloc(fldnmlen[i] + 1, sizeof(char));
			  memmove(tempfield,fldnm[i],fldnmlen[i]);
						  
			  /* Open the dataset */
			  /* ---------------- */
			  datasetid = H5Dopen(groupid, tempfield);
			  if ( datasetid == FAIL )
			    {
			      sprintf(errbuf, "Cannot open the dataset \"%s\". \n", tempfield);
			      H5Epush(__FILE__, "HE5_SWinqfields", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
			      HE5_EHprint(errbuf, __FILE__, __LINE__);
			      if (metabuf != NULL) free(metabuf);
			      free(tempfield);
			      return(FAIL);
			    }
						  
			  /* Get the data type */
			  /* ----------------- */
			  datatype = H5Dget_type(datasetid);
			  if ( datatype == FAIL )
			    {
			      sprintf(errbuf, "Cannot get the data type ID. \n");
			      H5Epush(__FILE__, "HE5_SWinqfields", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
			      HE5_EHprint(errbuf, __FILE__, __LINE__);
			      if (metabuf != NULL) free(metabuf);
			      free(tempfield);
			      return(FAIL);
			    }
						  
			  /* Get the data type class ID */
			  /* -------------------------- */
			  classid = H5Tget_class(datatype);
			  if ( classid == H5T_NO_CLASS )
			    {
			      sprintf(errbuf, "Cannot get the data type class ID. \n");
			      H5Epush(__FILE__, "HE5_SWinqfields", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
			      HE5_EHprint(errbuf, __FILE__, __LINE__);
			      if (metabuf != NULL) free(metabuf);
			      free(tempfield);
			      return(FAIL);
			    }

			  if (classid == H5T_STRING)
			    {
			      /* HE5T_CHARSTRING has variable length for data fields */
			      str_is_variable = H5Tis_variable_str(datatype);
			      if(str_is_variable == TRUE)
				{
				  numbertype[i] = HE5T_CHARSTRING;
				}
			      else if(str_is_variable == FALSE)
				{
				  numbertype[i] = HE5T_NATIVE_CHAR;
				}
			      else
				{
				  status = FAIL;
				  sprintf(errbuf, "Failed to see if string field is varaible or fixed length.\n");
				  H5Epush(__FILE__, "HE5_SWinqfields", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
				  if (metabuf != NULL) free(metabuf);
				  HE5_EHprint(errbuf, __FILE__, __LINE__);
				  return(status);
				}

			      /*HE5_SWgetstringtype(swathID, fieldname,classid);*/
			      /*numbertype[i] = HE5T_CHARSTRING;*/
			    }
			  else
			    {
			      /*numbertype[i]  = classid;*/
			      numbertype[i] = HE5_EHdtype2numtype(datatype);
			      if ( numbertype[i] == FAIL )
				{
				  sprintf(errbuf, "Cannot get the number type ID. \n");
				  H5Epush(__FILE__, "HE5_SWinqfields", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
				  HE5_EHprint(errbuf, __FILE__, __LINE__);
				  if (metabuf != NULL) free(metabuf);
				  free(tempfield);
				  return(FAIL);
				}
			    }
						  
			  /* Release the datatype ID */
			  /* ----------------------- */
			  status = H5Tclose(datatype);
			  if ( status == FAIL )
			    {
			      sprintf(errbuf, "Cannot close the datatype \"%s\". \n", tempfield);
			      H5Epush(__FILE__, "HE5_SWinqfields", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
			      HE5_EHprint(errbuf, __FILE__, __LINE__);
			      if (metabuf != NULL) free(metabuf);
			      free(tempfield);
			      return(FAIL);
			    }

			  /* Release the dataset ID */
			  /* ---------------------- */
			  Dstatus = H5Dclose(datasetid);
			  if ( Dstatus == FAIL )
			    {
			      sprintf(errbuf, "Cannot close the dataset \"%s\". \n", tempfield);
			      H5Epush(__FILE__, "HE5_SWinqfields", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
			      HE5_EHprint(errbuf, __FILE__, __LINE__);
			      if (metabuf != NULL) free(metabuf);
			      free(tempfield);
			      return(FAIL);
			    }
			  free(tempfield);
			}
		    }
		}
			  
  
	      /*
	       * Get Rank (if desired) by counting # of dimensions in
	       * "DimList" string
	       */
	      if (rank != NULL)
		{
		  HE5_EHgetmetavalue(metaptrs, "DimList", utlstr);
		  rank[nFld] = HE5_EHlong2int(HE5_EHparsestr(utlstr, ',', ptr, slen) );
		  if (rank[nFld] == FAIL )
		    {
		      sprintf(errbuf, "Cannot convert data type. \n");
		      H5Epush(__FILE__, "HE5_SWinqfields", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      if(metabuf != NULL) free(metabuf);
		      return(FAIL);
		    } 
		}
			  
	      /* Increment field counter */
	      /* ----------------------- */
	      nFld++;
			  
	    }
	  else
	    /* No more fields found */
	    /* -------------------- */
	    break;
	}               
	  
      if (metabuf != NULL) free(metabuf);
    }
  
 COMPLETION:  
  return(nFld);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqdatafields                                              |
|                                                                             |
|  DESCRIPTION: Inquires about data fields in swath                           |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nflds          long                Number of data fields in swath          |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  fieldlist      char                Field names (comma-separated)           |
|  rank           int                 Array of ranks                          |
|  ntype          hid_t               number types                            |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  8/23/99  A.Muslimov    Changed datatype of nflds from int to int32_t.      |
|  05/10/00 A.Muslimov    Replaced 'H5T_class_t' type by 'int' data type.     |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Jan 03   S.Zhao        Changed the type of 'ntype' from an H5T_class_t to  |
|                         an hid_t.                                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWinqdatafields(hid_t swathID, char *fieldlist, int rank[], hid_t ntype[])
{
  long            nflds   = FAIL;             /* Number of Data fields */

  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer  */


  /* Call "HE5_SWinqfields" routine to get number of fields */
  /* ------------------------------------------------------ */
  nflds = HE5_SWinqfields(swathID, "Data Fields", fieldlist, NULL, NULL);
  if (nflds == FAIL)
    {
      sprintf(errbuf, "Cannot get the number of fields in \"Data Fields\" group. \n");
      H5Epush(__FILE__, "HE5_SWinqdatafields", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
        
  /* Call "HE5_SWinqfields" routine to get other parameters */
  /* ------------------------------------------------------ */
  nflds = HE5_SWinqfields(swathID, "Data Fields", fieldlist, rank, ntype);
  if (nflds == FAIL)
    {
      sprintf(errbuf, "Inquiry about fields in \"Data Fields\" group fails. \n");
      H5Epush(__FILE__, "HE5_SWinqdatafields", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
  return(nflds);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqgeofields                                               |
|                                                                             |
|  DESCRIPTION: Inquires about geo fields in swath                            |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nflds          long                Number of geo fields in swath           |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  fieldlist      char                Field names (comma-separated)           |
|  rank           int                 Array of ranks                          |
|  ntype          hid_t               number types                            |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  05/10/00 A.Muslimov    Replaced 'H5T_class_t' type by 'int' data type.     |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Jan 03   S.Zhao        Changed the type of 'ntype' from an H5T_class_t to  |
|                         an hid_t.                                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWinqgeofields(hid_t swathID, char *fieldlist, int rank[], hid_t ntype[])
{

  long            nflds   = FAIL;             /* Number of Geo  fields */

  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer  */

  /* Call "HE5_SWinqfields" routine to get number of fields */
  /* ------------------------------------------------------ */
  nflds = HE5_SWinqfields(swathID, "Geolocation Fields", fieldlist, NULL, NULL);
  if (nflds == FAIL)
    {
      sprintf(errbuf, "Cannot get the number of fields in \"Geolocation Fields\" group. \n");
      H5Epush(__FILE__, "HE5_SWinqgeofields", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Call "HE5_SWinqfields" routine to get other parameters */
  /* ------------------------------------------------------ */
  nflds = HE5_SWinqfields(swathID, "Geolocation Fields", fieldlist, rank, ntype);
  if (nflds == FAIL)
    {
      sprintf(errbuf, "Inquiry about fields in \"Geolocation Fields\" group fails. \n");
      H5Epush(__FILE__, "HE5_SWinqgeofields", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  return (nflds);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqdatatype                                                |
|                                                                             |
|  DESCRIPTION: Inquires about geo/data/prof fields in swath                  |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t               return status (0) SUCCEED, (-1) FAIL   |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t                                                       |
|  fieldname      char *                                                      |
|  attrname       char *                                                      |
|  group          int                 Group flag:                             |
|                                       ...GEOGROUP, ...DATAGROUP,            |
|                                       ...PROFGROUP    - for the field       |
|                                       ...ATTRGROUP, ...GRPATTRGROUP,        |
|                                       ...PROFGRPATTRGROUP,                  |
|                                       ...GEOGRPATTRGROUP,                   |
|                                       ...LOCATTRGROUP - for the attribute   |
|                                                                             |
|  OUTPUTS:                                                                   |
|  datatype       hid_t                                                       |
|  classid        H5T_class_t                                                 |
|  order          H5T_order_t                                                 |
|  size           size_t                                                      |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Oct 99   D.Wynne       Original Programmer                                 |
|  Dec 99   A.Muslimov    Changed the status data type from hid_t to int   .  |
|  Feb 00   A.Muslimov    Added error checking after the function calls.      |
|  Mar 00   A.Muslimov    Updated to include Group/Local Attributes options.  |
|  May 00   A.Muslimov    Replaced 'H5T_class_t' type by 'int' data type.     |
|  Jul 00   A.Muslimov    Unmasked hdf5 data types.                           |
|  Set 00   A.Muslimov    Updated to incorporate profile datasets.            |
|  Feb 04   S.Zhao        Added a group flag for the "Profile Fields" group   |
|                         attribute.                                          |
|  Feb 04   S.Zhao        Added a group flag for the "Geolocation Fields"     |
|                         group attribute.                                    |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWinqdatatype(hid_t swathID, const char *fieldname, const char *attrname, 
int group, hid_t *datatype, H5T_class_t *classid, H5T_order_t *order, size_t *size)
{
 
  herr_t      status     = FAIL;	      /* routine return status */

  int         fldgroup   = FAIL;          /* Field group flag      */

  hid_t       datasetid  = FAIL;	      /* Dataset ID            */
  hid_t       fid        = FAIL;	      /* HDF-EOS file ID       */
  hid_t       gid        = FAIL;	      /* "HDFEOS" group ID     */
  hid_t       attr       = FAIL;	      /* attribute dataset ID  */
  hid_t       fldgroupID = FAIL;	      /* Field group ID        */
  hid_t       fieldID    = FAIL;	      /* Field dataset ID      */         

  long        idx        = FAIL;	      /* swath index           */

  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer  */


  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWinqdatatype", &fid, &gid, &idx);
  if(status == SUCCEED)
    {
      if(group == HE5_HDFE_GEOGROUP)
	fldgroupID = HE5_SWXSwath[idx].geo_id;
      else if(group == HE5_HDFE_DATAGROUP)
	fldgroupID = HE5_SWXSwath[idx].data_id;
      else if(group == HE5_HDFE_PROFGROUP)
	fldgroupID = HE5_SWXSwath[idx].prof_id;
      else if(group == HE5_HDFE_ATTRGROUP)
	fldgroupID = HE5_SWXSwath[idx].sw_id;
      else if(group == HE5_HDFE_GRPATTRGROUP)
	fldgroupID = HE5_SWXSwath[idx].data_id;
      else if(group == HE5_HDFE_GEOGRPATTRGROUP)
	fldgroupID = HE5_SWXSwath[idx].geo_id;
      else if(group == HE5_HDFE_PROFGRPATTRGROUP)
	fldgroupID = HE5_SWXSwath[idx].prof_id;
      else if(group == HE5_HDFE_LOCATTRGROUP)
	{
	  /* Get the field group flag */
	  /* ------------------------ */
	  fldgroup = HE5_SWfldsrch(swathID,(char *)fieldname,NULL,NULL,NULL,NULL);
	  if(fldgroup == FAIL)
	    {
	      sprintf(errbuf,"Cannot get the group flag for \"%s\" field.\n",fieldname);
	      H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(FAIL);
	    }
		  
	  if (fldgroup == HE5_HDFE_DATAGROUP)
	    fldgroupID = HE5_SWXSwath[idx].data_id;

	  if (fldgroup == HE5_HDFE_GEOGROUP)
	    fldgroupID = HE5_SWXSwath[idx].geo_id;

	  if (fldgroup == HE5_HDFE_PROFGROUP)
	    fldgroupID = HE5_SWXSwath[idx].prof_id;		  
	}
      else
	{
	  sprintf(errbuf, "Invalid group flag (\"%d\"). \n", group);
	  H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_FUNC, H5E_BADVALUE , errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
		
      /* Get data type information for the field */
      /* --------------------------------------- */
      if( group == HE5_HDFE_GEOGROUP || group == HE5_HDFE_DATAGROUP || group == HE5_HDFE_PROFGROUP)
	{
	  datasetid = H5Dopen(fldgroupID, fieldname);
	  if (datasetid == FAIL)
	    {
	      sprintf(errbuf, "Cannot open the dataset for the \"%s\" field.\n", fieldname);
	      H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_DATASET, H5E_NOTFOUND , errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
				
	      return(FAIL);
	    }
			
	  *datatype = H5Dget_type(datasetid);
	  if (*datatype == FAIL)
	    {
	      sprintf(errbuf, "Cannot get the datatype for the \"%s\" field.\n", fieldname);
	      H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_DATATYPE, H5E_NOTFOUND , errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	   
	      return(FAIL);
	    }

	  *classid  = H5Tget_class(*datatype);
	  if (*classid == H5T_NO_CLASS)
	    {
	      sprintf(errbuf, "Cannot get the data type class ID for the \"%s\" field.\n", fieldname);
	      H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_FUNC, H5E_CANTINIT , errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	   
	      return(FAIL);
	    }

	  *order    = H5Tget_order(*datatype);
	  if (*order == H5T_ORDER_ERROR)
	    {
	      sprintf(errbuf, "Cannot get the data type order for the \"%s\" field.\n", fieldname);
	      H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_FUNC, H5E_CANTINIT , errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
				
	      return(FAIL);
	    }
			
	  if (*classid == H5T_STRING)
	    {
	      *size = H5Tget_size(*datatype);
	    }
	  else
	    {
	      *size     = H5Tget_size(*datatype);
	      if (*size == 0)
		{
		  sprintf(errbuf, "Cannot get the data type size for the \"%s\" field.\n", fieldname);
		  H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_FUNC, H5E_CANTINIT , errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
				
		  return(FAIL);
		}
	    }
			
	  status = H5Dclose(datasetid);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot release the dataset ID for the \"%s\" field.\n", fieldname);
	      H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_DATASET, H5E_CLOSEERROR , errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
				
	      return(FAIL);
	    }
	}
      /* Get data type information about global/group attribute */
      /* ------------------------------------------------------ */
      else if(group == HE5_HDFE_ATTRGROUP || group == HE5_HDFE_GRPATTRGROUP || 
	      group == HE5_HDFE_PROFGRPATTRGROUP || group == HE5_HDFE_GEOGRPATTRGROUP)
	{
	  attr      = H5Aopen_name(fldgroupID, attrname);
	  if (attr == FAIL)
	    {
	      sprintf(errbuf, "Cannot open the \"%s\" attribute.\n", attrname);
	      H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	   
	      return(FAIL);
	    }

	  *datatype = H5Aget_type(attr);
	  if (*datatype == FAIL)
	    {
	      sprintf(errbuf, "Cannot get the data type for the \"%s\" attribute.\n", attrname);
	      H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
				
	      return(FAIL);
	    }
			
	  *classid  = H5Tget_class(*datatype);
	  if (*classid == H5T_NO_CLASS)
	    {
	      sprintf(errbuf, "Cannot get the data type class ID for the \"%s\" attribute.\n", attrname);
	      H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	   
	      return(FAIL);
	    }

	  *order    = H5Tget_order(*datatype);
	  if (*order == H5T_ORDER_ERROR)
	    {
	      sprintf(errbuf, "Cannot get the data type order for the \"%s\" attribute.\n", attrname);
	      H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_FUNC, H5E_CANTINIT , errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
				
	      return(FAIL);
	    }

	  if (*classid == H5T_STRING)
	    {
	      *size = H5Tget_size(*datatype);
	    }
	  else
	    {
	      *size     = H5Tget_size(*datatype);
	      if (*size == 0)
		{
		  sprintf(errbuf, "Cannot get the data type size for the \"%s\" attribute.\n", attrname);
		  H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_FUNC, H5E_CANTINIT , errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
				
		  return(FAIL);
		}
	    }
			
	  status = H5Aclose(attr);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot release the dataset ID for the \"%s\" attribute.\n", attrname);
	      H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_DATASET, H5E_CLOSEERROR , errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
				
	      return(FAIL);
	    }
			
	}
      /* Get data type information for local attribute */
      /* --------------------------------------------- */
      else if(group == HE5_HDFE_LOCATTRGROUP)
	{

	  fieldID = H5Dopen(fldgroupID, fieldname);
	  if(fieldID == FAIL)
	    {
	      sprintf(errbuf,"Cannot open the \"%s\" field dataset.\n", fieldname);
	      H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(FAIL);
	    }

	  attr = H5Aopen_name(fieldID, attrname);
	  if (attr == FAIL)
	    {
	      sprintf(errbuf, "Cannot open the \"%s\" attribute.\n", attrname);
	      H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	   
	      return(FAIL);
	    }

	  *datatype = H5Aget_type(attr);
	  if (*datatype == FAIL)
	    {
	      sprintf(errbuf, "Cannot get the data type for the \"%s\" attribute.\n", attrname);
	      H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
				
	      return(FAIL);
	    }
			
	  *classid  = H5Tget_class(*datatype);
	  if (*classid == H5T_NO_CLASS)
	    {
	      sprintf(errbuf, "Cannot get the data type class ID for the \"%s\" attribute.\n", attrname);
	      H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	   
	      return(FAIL);
	    }

	  *order    = H5Tget_order(*datatype);
	  if (*order == H5T_ORDER_ERROR)
	    {
	      sprintf(errbuf, "Cannot get the data type order for the \"%s\" attribute.\n", attrname);
	      H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_FUNC, H5E_CANTINIT , errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
				
	      return(FAIL);
	    }

	  if (*classid == H5T_STRING)
	    {
	      *size = H5Tget_size(*datatype);
	    }
	  else
	    {
	      *size     = H5Tget_size(*datatype);
	      if (*size == 0)
		{
		  sprintf(errbuf, "Cannot get the data type size for the \"%s\" attribute.\n", attrname);
		  H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_FUNC, H5E_CANTINIT , errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
				
		  return(FAIL);
		}
	    }
			
	  status = H5Aclose(attr);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot release the dataset ID for the \"%s\" attribute.\n", attrname);
	      H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_DATASET, H5E_CLOSEERROR , errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
				
	      return(FAIL);
	    }

	  status = H5Dclose(fieldID);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot release the dataset ID for the \"%s\" attribute.\n", attrname);
	      H5Epush(__FILE__, "HE5_SWinqdatatype", __LINE__, H5E_DATASET, H5E_CLOSEERROR , errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
				
	      return(FAIL);
	    }		   
	}
    }

  return(status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWnentries                                                   |
|                                                                             |
|  DESCRIPTION: Returns number of entries and string buffer size              |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nEntries       long                Number of entries                       |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  entrycode      int                 Entry code:                             |
|                                                                             |
|                                     HDFE_NENTDIM  (0)                       |
|                                     HDFE_NENTMAP  (1)                       |
|                                     HDFE_NENTIMAP (2)                       |
|                                     HDFE_NENTGFLD (3)                       |
|                                     HDFE_NENTDFLD (4)                       |
|                                                                             |
|                                                                             |
|  OUTPUTS:                                                                   |
|  strbufsize     long                Length of comma-separated list          |
|                                     (Does not include null-terminator       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|                                                                             |
| 7/29/99   A.Muslimov    In the call to EHmetagroup() replace gid by fid.    |
| 9/01/99   A.Muslimov    Initialized metabuf pointer. Added error handling   |
|                         right after the calls to EHmetagroup() and          |
|                         EHmetavalue(). Initialized nEntries to -1, and set  |
|                         nEntries to 0 in 'if( status == 0 ){}' block.       |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWnentries(hid_t swathID, int entrycode, long *strbufsize)
{
  herr_t          status     = FAIL;/* routine return status variable  */  
  
  hid_t           fid        = FAIL;/* HDF-EOS file ID                 */
  hid_t           gid        = FAIL;/* "HDFEOS" group ID               */
  
  long            idx        = FAIL;/* Swath index                     */
  long            nEntries   = 0;   /* Number of entries               */
  long            metaflag   = FAIL;/* Old (0), New (1) metadata flag) */
  long            nVal       = 0;   /* Number of strings to search for */
  long            i;                /* Loop index                      */
  
  char            *metabuf = (char *)NULL;    /* Ptr to SM             */
  char            *metaptrs[2]={NULL,NULL};   /* Start/end of SM       */
  char            utlstr[HE5_HDFE_UTLBUFSIZE];/* Utility string        */
  char            valName[2][32];             /* Strings to search for */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer  */
  


  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWnentries", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Zero out string buffer size */
      /* --------------------------- */
      *strbufsize = 0;
       
      /*
       * Get pointer to relevant section within SM and Get names of
       * metadata strings to inquire about
       */
      switch (entrycode)
        {
        case HE5_HDFE_NENTDIM:
	  /* Dimensions */
	  /* ---------- */
	  {
	    metabuf = (char *)HE5_EHmetagroup(fid, HE5_SWXSwath[idx].swname, "s", "Dimension", metaptrs);
	    nVal = 1;
	    strcpy(&valName[0][0], "DimensionName");
	  }
	  break;
		  
        case HE5_HDFE_NENTMAP:
	  /* Dimension Maps */
	  /* -------------- */
	  {
	    metabuf = (char *)HE5_EHmetagroup(fid, HE5_SWXSwath[idx].swname, "s", "DimensionMap", metaptrs);
	    nVal = 2;
	    strcpy(&valName[0][0], "GeoDimension");
	    strcpy(&valName[1][0], "DataDimension");
	  }
	  break;

        case HE5_HDFE_NENTIMAP:
	  /* Indexed Dimension Maps */
	  /* ---------------------- */
	  {
	    metabuf = (char *)HE5_EHmetagroup(fid, HE5_SWXSwath[idx].swname, "s","IndexDimensionMap", metaptrs);
	    nVal = 2;
	    strcpy(&valName[0][0], "GeoDimension");
	    strcpy(&valName[1][0], "DataDimension");
	  }
	  break;
		  
        case HE5_HDFE_NENTGFLD:
	  /* Geolocation Fields */
	  /* ------------------ */
	  {
	    metabuf = (char *)HE5_EHmetagroup(fid, HE5_SWXSwath[idx].swname, "s", "GeoField", metaptrs);
	    nVal = 1;
	    strcpy(&valName[0][0], "GeoFieldName");
	  }
	  break;

        case HE5_HDFE_NENTDFLD:
	  /* Data Fields */
	  /* ----------- */
	  {
	    metabuf = (char *)HE5_EHmetagroup(fid, HE5_SWXSwath[idx].swname, "s", "DataField", metaptrs);
	    nVal = 1;
	    strcpy(&valName[0][0], "DataFieldName");
	  }
	  break;

	default:
	  {
	    sprintf(errbuf,"Invalid (unsupported) entry code \"%d\". \n", entrycode);       
	    H5Epush(__FILE__, "HE5_SWnentries", __LINE__, H5E_ARGS, H5E_UNSUPPORTED, errbuf);
	    HE5_EHprint(errbuf, __FILE__, __LINE__);
	  }
	  break;
        }

	  
      if ( metabuf == NULL )
	{
	  nEntries = FAIL;
	  sprintf(errbuf,"Cannot get the number of entries. \n");
	  H5Epush(__FILE__, "HE5_SWnentries", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(nEntries);
	}
	  


      /*
       * Check for presence of 'GROUP="' string If found then old metadata,
       * search on OBJECT string
       */
      metaflag = (strstr(metabuf, "GROUP=\"") == NULL) ? 1 : 0;
      if (metaflag == 0)
        {
	  nVal = 1;
	  strcpy(&valName[0][0], "\t\tOBJECT");
        }

      /* Begin loop through entries in metadata */
      /* -------------------------------------- */
      while (1)
        {
	  /* Search for first string */
	  /* ----------------------- */
	  strcpy(utlstr, &valName[0][0]);
	  strcat(utlstr, "=");
	  metaptrs[0] = strstr(metaptrs[0], utlstr);

	  /* If found within relevant metadata section ... */
	  /* --------------------------------------------- */
	  if (metaptrs[0] < metaptrs[1] && metaptrs[0] != NULL)
            {
	      for (i = 0; i < nVal; i++)
                {
		  /*
		   * Get all string values Don't count quotes
		   */
		  status = HE5_EHgetmetavalue(metaptrs, &valName[i][0], utlstr);
		  if ( status == FAIL )
		    {
		      nEntries = FAIL;
		      sprintf(errbuf,"Cannot get metavalue. \n");
		      H5Epush(__FILE__, "HE5_SWnentries", __LINE__, H5E_DATASET, H5E_READERROR, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      free(metabuf);
			    
		      return(nEntries);
		    }


		  *strbufsize += strlen(utlstr) - 2;
                }
	      /* Increment number of entries */
	      /* --------------------------- */
	      nEntries++;

	      /* Go to end of OBJECT */
	      /* ------------------- */
	      metaptrs[0] = strstr(metaptrs[0], "END_OBJECT");
            }
	  else
	    /* No more entries found */
	    /* --------------------- */
            {
	      break;
            }
        }
      if (metabuf != NULL) free(metabuf);


      /* Count comma separators & slashes (if mappings) */
      /* ---------------------------------------------- */
      if (nEntries > 0)
        {
	  *strbufsize += nEntries - 1;
	  *strbufsize += (nVal - 1) * nEntries;
        }
    }
  
  return(nEntries);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqswath                                                   |
|                                                                             |
|  DESCRIPTION: Returns number and names of swath structures in file          |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nSwath         long                Number of swath structures in file      |
|                                                                             |
|  INPUTS:                                                                    |
|  filename       char                HDF-EOS filename                        |
|                                                                             |
|  OUTPUTS:                                                                   |
|  swathlist      char                List of swath names (comma-separated)   |
|  strbufsize     long                Length of swathlist                     |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWinqswath(const char *filename, char *swathlist, long *strbufsize)
{
  long       nSwath   = FAIL;            /* Number of swaths in file */

  herr_t     status   = FAIL;            /* Return status variable   */

  char       errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer     */  

  CHECKPOINTER(filename);

  /* Call "HE5_EHinquire" routine */
  /* ---------------------------- */
  nSwath = HE5_EHinquire(filename,  "/HDFEOS/SWATHS", swathlist, strbufsize);
  if ( nSwath == FAIL )
    {
      sprintf(errbuf,"Cannot get information about Swath. \n");
      H5Epush(__FILE__, "HE5_SWinqswath", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }								 

 COMPLETION:
  return(nSwath);
}




/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWextend                                                     |
|                                                                             |
|  DESCRIPTION:                                                               |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  fieldname      char                fieldname                               |
|                                                                             |
|  OUTPUTS:                                                                   |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  8/23/99  A. Muslimov   Checked  for the status returned by H5Dextend().    |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_SWextend(hid_t swathID, char *fieldname, hsize_t  size[])
{
  herr_t   status   = FAIL;/* Routine return status */

  hid_t    gid      = FAIL;/* Swath group  ID       */
  hid_t    fid      = FAIL;/* HDF-EOS file ID       */
  hid_t    fieldID  = FAIL;/* fieldname dataset ID  */

  long     idx      = FAIL;/* Swath index           */


  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWextend", &fid, &gid, &idx);

  HE5_SWfieldsizeID( swathID, fieldname,  &fieldID);
 
  status = H5Dextend(fieldID, size);

  return(status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWwrrdfield                                                  |
|                                                                             |
|  DESCRIPTION: Writes/Reads fields                                           |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  fldname        char                field name                              |
|  code           char                Write/Read code (w/r)                   |
|  start          hssize_t            start array                             |
|  stride         hsize_t             stride array                            |
|  count          hsize_t             edge array                              |
|  datbuf         void                data buffer for read                    |
|                                                                             |
|  OUTPUTS:                                                                   |
|  datbuf         void                data buffer for write                   |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|                                                                             |
|  8/23/99  A. Muslimov   Added error checkings after the function calls.     |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  7/12/00  A.Muslimov    Added conversion from disk/file data type ID to     |
|                          memory data type ID before H5Dread() call.         |
|  10/5/00  A.Muslimov    Added checking for the field name (in case of pas-  |
|                          sing an alias as a "fldname").                     |
|  Nov 00   A.Muslimov    Modified a block checking if the dataset is         |
|                          appendable. Added "break" statement.               |
|  Dec 00   A.Muslimov    Modified to fix a problem with appending data to the|
|                          extendible datset.                                 |
|  Apr 03   S.Zhao        Added conversion from data type ID to memory data   |
|                         type ID before H5Dwrite() call.                     |
|  Oct 03   S.Zhao        Added to write/read a character string dataset.     |
|  Apr 04   S.Zhao        Modified for a character string dataset.            |
|  Feb 05   S.Zhao        Replaced the "count" array by the "dims" array if   |
|                         it was declared larger than the dimension size.     |
|  Sep  11  Abe Taaheri   Modified for correcting Unlimited dimension         |
|                         behavior and extension                              |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
static herr_t    
HE5_SWwrrdfield(hid_t swathID, char *fldname, char *code, const hssize_t start[], 
const hsize_t stride[], const hsize_t count[],  void *datbuf)
{    
  herr_t          status   = FAIL; /* routine return status variable     */    

  int             i;		   /* Loop index                         */
  int             startf   =  0;   /* flag (if start is NULL)            */
  int             countf   =  0;   /* flag (if counf is NULL)            */
  int             bothf    =  0;   /* flag (if start and count are NULL) */
  int             append   = FALSE;/* FLAG (if field is appendable)      */
  int             rank     = FAIL; /* Rank of dataset                    */
  int             maxrank  =  0;   /* Rank dummy variable                */
  int             nameflag = FAIL; /* Actual (1)/Alias (0) field name    */
   
  hid_t           fid      = FAIL;/* HDF-EOS file ID                     */
  hid_t           fieldID  = FAIL;/* fieldname Dataset ID                */
  hid_t           fspace   = FAIL;/* file data space ID                  */
  hid_t           mid      = FAIL;/* memory data space ID                */
  hid_t           gid      = FAIL;/* "HDFEOS" group ID                   */
  hid_t           tid      = FAIL;/* datatype ID                         */
  hid_t           mtype    = FAIL;/* Memory data type ID                 */

  long            idx      = FAIL;/* Swath index                         */
  
  hsize_t         dims[HE5_DTSETRANKMAX];   /* Field dimensions          */
  hsize_t         maxdims[HE5_DTSETRANKMAX];/* Field maximum dimensions  */
  hssize_t        *tstart =(hssize_t *)NULL;/* Not NULL "start" value    */
  hsize_t         *tcount = (hsize_t *)NULL;/* Not NULL "count" value    */
  hsize_t         *lcount = (hsize_t *)NULL;
  hsize_t         dimsize = 0;		    /* Field dimension size      */
  hsize_t         size[HE5_DTSETRANKMAX];   /* Extended dimension size   */

  hid_t           ntype[1]  = {FAIL};       /* numbertype                */

  char            *dimbuf   = (char *)NULL;  
  char            *comma    = (char *)NULL;
  char            *dimcheck = (char *)NULL;
  char            fieldname[HE5_HDFE_NAMBUFSIZE];    /* Field name buffer      */
  char            fldactualname[HE5_HDFE_NAMBUFSIZE];/* Actual field name      */     
  char            maxdimlist[HE5_HDFE_DIMBUFSIZE];   /* Maximum dimension list */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];       /* Error message buffer   */  
  H5T_class_t     classid = H5T_NO_CLASS;            /* data type class ID     */

  char            dimlist[HE5_HDFE_DIMBUFSIZE];
  char            *dimbuf1   = (char *)NULL;
  char            *dimbuf2   = (char *)NULL;
  char            *comma1    = (char *)NULL;
  char            *comma2    = (char *)NULL;
  char            *newname   = (char *)NULL;
  char            *newname1  = (char *)NULL;

  int             ibuf;                /* Loop index                        */
  char            **chardatbuf = NULL; /* string data buffer                */ 
  int             maxlen = 0;          /* max length in array of string     */
  int             strsize = 0;         /* each str length in array of str   */
  hsize_t         numattr[1];          /* number of attribute elements      */
  int             mycount = 0;         /* flag                              */
  long            strbufsize1;         /* string buffer size                */
  long            strbufsize2;         /* string buffer size                */
  long            nattr = 0;           /* number of attributes              */
  char            *attrlist1 = (char *)NULL;/* attribute list               */
  char            *attrlist2 = (char *)NULL;/* attribute list               */
  char            *attptr = (char *)NULL;   /* attribute pointer            */
  hsize_t	  dimsize_dim, dimsize_maxdim;
  int             extend_flag = 0;


  CHECKNAME(fldname);
  

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWwrrdfield", &fid, &gid, &idx);  
  if (status == FAIL) return(status);

  /* Get field info  */
  /* --------------- */
  status = HE5_SWfieldinfo(swathID, fldname, &rank, dims, ntype, NULL, NULL);
  if( status == FAIL )
    {
      sprintf(errbuf,"Cannot get information about \"%s\" field. \n", fldname);
      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  for (i=0; i<rank; i++)
    {
      if(start != NULL && start[i] > 0) /* we may want to extend a dataset */
	{
	  extend_flag = 1;
	  break;
	}
    }

    /* since in hdf5 all dimension can be appendable, the following 
    was modified so that any dimension is extedned. In HDF4 only the first
    dimension is appenable, so start[0] > 0 is valid only for HDF4 based 
    hdfeos
  if (start != NULL && start[0] > 0 && (strcmp(code,"w") == 0))
    */

    if (start != NULL && extend_flag == 1 && (strcmp(code,"w") == 0))
    {
      /* Check whether fieldname is in dataset (multi-dim field) */
      /* ------------------------------------------------------- */
      status = HE5_SWfieldinfo(swathID, fldname, &rank, dims, ntype, dimlist, maxdimlist);
      if( status == FAIL )
	{
          sprintf(errbuf,"Cannot get information about \"%s\" field. \n", fldname);
          H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          return(status);
	}

      dimbuf1 = (char *) calloc((strlen(dimlist) + 2), sizeof(char));
      if(dimbuf1 == NULL)
	{
          sprintf(errbuf,"Cannot allocate memory.\n");
          H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          return(FAIL);
	}

      memcpy(dimbuf1,dimlist, strlen(dimlist));

      dimbuf2 = (char *) calloc((strlen(maxdimlist) + 2), sizeof(char));
      if(dimbuf2 == NULL)
	{
          sprintf(errbuf,"Cannot allocate memory.\n");
          H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          free(dimbuf1);
          return(FAIL);
	}

      memcpy(dimbuf2,maxdimlist, strlen(maxdimlist));
 
      for (i = 1; i < rank + 1; i++)
	{
	  strcat(dimbuf1,",");
	  comma1 = strchr(dimbuf1,',');
	  newname = (char *) calloc(comma1 - dimbuf1 + 1, sizeof(char));
	  if(newname == NULL)
	    {
              sprintf(errbuf,"Cannot allocate memory.\n");
              H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
              HE5_EHprint(errbuf, __FILE__, __LINE__);
              free(dimbuf1);
              free(dimbuf2);
              return(FAIL);
	    }

	  memmove(newname,dimbuf1,comma1 - dimbuf1);
	  memmove(dimbuf1, comma1 + 1, strlen(comma1 + 1) + 1); 
 
	  strcat(dimbuf2,",");
	  comma2 = strchr(dimbuf2,',');
	  newname1 = (char *) calloc(comma2 - dimbuf2 + 1, sizeof(char));
	  if(newname1 == NULL)
	    {
              sprintf(errbuf,"Cannot allocate memory.\n");
              H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
              HE5_EHprint(errbuf, __FILE__, __LINE__);
              free(dimbuf1);
              free(dimbuf2);
              free(newname);
              return(FAIL);
	    }

	  memmove(newname1,dimbuf2,comma2 - dimbuf2);
	  memmove(dimbuf2, comma2 + 1, strlen(comma2 + 1) + 1); 
 
	  /* get dimsize for newname1, and dimsize for 
	     the dimension whose maxdim is newname1 */

	  dimsize_dim = HE5_SWdiminfo(swathID, newname);
	  dimsize_maxdim = HE5_SWdiminfo(swathID, newname1);

	  /* Find out if the dataset dimension is appendable */
	  /* ----------------------------------------------- */
	  if ( (dimsize_dim < dimsize_maxdim) || (dimsize_maxdim == H5S_UNLIMITED))
	    {
	      /* update dim if new dim is still <= maxdim */
	      if((start[i]+1) > dimsize_maxdim && (dimsize_maxdim != H5S_UNLIMITED))
		{
		      sprintf(errbuf, "Cannot update the dimension, new dimension size is larger than the max dimension size in the datafiled.\n");
		      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      free(dimbuf1);
		      free(dimbuf2);
		      free(newname);
		      free(newname1);
		      return(FAIL);
		}
	      else
		{
		  /*// i starts from 1, but start should be from 0.
		  // Without this fix, the updated unlimited dimension size is undefined!! */
		  status = HE5_SWupdatedim(swathID, newname, start[i-1]+1);
	      if( status == FAIL )
		{
		  sprintf(errbuf, "Cannot update the dimension.\n");
		  H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  free(dimbuf1);
		  free(dimbuf2);
		  free(newname);
		  free(newname1);
		  return(FAIL);
		} 
	    }
	    }
	  free(newname);
	  free(newname1);

	  newname = NULL;
	  newname1 = NULL;
	}

      free(dimbuf1);
      free(dimbuf2);

      dimbuf1 = NULL;
      dimbuf2 = NULL;
 
    }



  /* Call HE5_SWfldnameinfo() to get actual field name */
  /* --------------------------------------------- */
  nameflag = HE5_SWfldnameinfo(swathID, fldname, fldactualname);
  if ( nameflag == FAIL )
    {
      sprintf(errbuf, "Cannot get actual name of the field.\n");
      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
  /* Name is not alias */
  /* ----------------- */
  if (nameflag == TRUE)
    {
      strcpy(fieldname,"");
      strcpy(fieldname,fldname);
    }

  /* Name is an alias */
  /* ---------------- */
  if (nameflag == FALSE)
    {
      strcpy(fieldname,"");
      strcpy(fieldname,fldactualname);
    }


  /* Initialize dims[]/maxdims[]/size[] arrays */
  /* ----------------------------------------- */
  for (i = 0; i < HE5_DTSETRANKMAX; i++)
    {
      dims[i]    = 0;
      maxdims[i] = 0;
      size[i]    = 0;
    }
  
  /* Check whether fieldname is in dataset (multi-dim field) */
  /* ------------------------------------------------------- */
  status = HE5_SWfieldinfo(swathID, fieldname, &rank, dims, ntype, NULL, maxdimlist);
  if( status == FAIL )
    {
      sprintf(errbuf,"Cannot get information about \"%s\" field. \n", fieldname);
      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }


  /* Find out if the field is appendable */
  /* ----------------------------------- */
  dimbuf = (char *) calloc(strlen(maxdimlist) + 64, sizeof(char));
  if(dimbuf == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory.\n");
      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
  strcpy(dimbuf,maxdimlist);
  strcat(dimbuf,",");
  comma = strchr(dimbuf,',');
  
  while(comma != NULL)
    {
      dimcheck = (char *) calloc(comma - dimbuf + 1, sizeof(char));
      if(dimcheck == NULL)
	{
	  sprintf(errbuf,"Cannot allocate memory.\n");
	  H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(dimbuf);
	  return(FAIL);
	}
      memmove(dimcheck,dimbuf,comma-dimbuf);

      /* Get dimension size */
      /* ------------------ */
      dimsize = HE5_SWdiminfo(swathID, dimcheck);

      if((dimsize == H5S_UNLIMITED) || (dims[maxrank] <= dimsize))
	{
	  maxdims[maxrank] = dimsize;
	  maxrank++;
	}
      memmove(dimbuf, comma + 1, strlen(comma + 1) + 1); 
      comma = strchr(dimbuf,',');
      free(dimcheck);
    }

  free(dimbuf);
  
  for(i = 0; i < rank; i++)
    {
      if(   dims[i] == maxdims[i] )
	append = FALSE;
      else if ( (dims[i] < maxdims[i]) || (maxdims[i] == H5S_UNLIMITED))
	{
	  append = TRUE;
	  break;
	}
      else
	{
	  sprintf(errbuf,"Maximum dimension size is smaller than dimension size.\n");
	  H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
    }        
  
  /* ============================================================== */
  /* start and count are being passed as NULL from SWdefvrtregion   */
  /* which calls SWreadfield, which have NULL for start and count.  */
  /* H5Sselect_hyperslab won't take NULL values for start and count */
  /* ============================================================== */
  if(start == NULL)
    {
      tstart = (hssize_t *)calloc(rank, sizeof(hssize_t));
      for(i = 0; i < rank; i++)
	tstart[ i ] = 0;
      startf = 1;
    }
  if(count == NULL)
    {
      tcount = (hsize_t *)calloc(rank, sizeof(hsize_t));
      for(i = 0; i < rank; i++)
	tcount[ i ] = dims[ i ];
      if(startf == 1)
	bothf = 1;
      else
	countf = 1;
    }
  else
    {
      lcount =  (hsize_t *)calloc(rank, sizeof(hsize_t));
      for(i = 0; i < rank; i++)
	{
	  if(count[ i ] > dims[ i ])
	    lcount[ i ] = dims[ i ];
	  else
	    lcount[ i ] = count[ i ];
	} 
    }
  
  if (append == TRUE)
    {
      /* Get the field-related dataset ID */
      /* -------------------------------- */
      HE5_SWfieldsizeID(swathID, fieldname, &fieldID);
	  
      if(bothf == 1)
	status = H5Dextend(fieldID, tcount);
      else if(startf == 1)
	status = H5Dextend(fieldID, lcount);
      else if(countf == 1)
	status = H5Dextend(fieldID, tcount);
      else
	{
	  for(i = 0; i < rank; i++)
	    size[ i ] = start[ i ] + lcount[ i ];
		 
	  /* Extend the dataset size */
	  /* ----------------------- */
	  status = H5Dextend(fieldID, size);
	}

      if( status == FAIL)
	{
	  sprintf(errbuf,"Cannot extend the dataset. \n");
	  H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  if (start == NULL)
	    {
	      if (tstart != NULL)
		free(tstart);
	    }
	  if (count == NULL)
	    {
	      if (tcount != NULL)
		free(tcount);
	    }
	  if (lcount != NULL)
	    free(lcount);

	  return(FAIL);
	}
    }
  
  if (append == FALSE)
    {   
      /* Get the field-related dataset ID */
      /* -------------------------------- */
      HE5_SWfieldsizeID(swathID, fieldname, &fieldID);
    }
  
  /* Get the file space ID */
  /* --------------------- */
  fspace = H5Dget_space(fieldID );
  if( fspace == FAIL)
    {
      sprintf(errbuf,"Cannot get data space ID. \n");
      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATASPACE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      if (start == NULL)
	{
	  if (tstart != NULL) 
	    free(tstart);
	}
      if (count == NULL)
	{
	  if (tcount != NULL) 
	    free(tcount);
	}
      if (lcount != NULL)
	free(lcount);
	  
      return(FAIL);
    }
  
  /* Select the hyperslab */
  /* -------------------- */
  if(bothf == 1)
    status = H5Sselect_hyperslab( fspace, H5S_SELECT_SET, (const hsize_t *)tstart,stride,tcount,NULL);
  else if(startf == 1)
    status = H5Sselect_hyperslab( fspace, H5S_SELECT_SET, (const hsize_t *)tstart,stride,lcount,NULL);
  else if(countf == 1)
    status = H5Sselect_hyperslab( fspace, H5S_SELECT_SET, (const hsize_t *)start,stride,tcount,NULL);
  else
    status = H5Sselect_hyperslab( fspace, H5S_SELECT_SET, (const hsize_t *)start,stride,lcount,NULL) ;
  
  if( status == FAIL )
    {
      sprintf(errbuf,"Cannot select a hyperslab. \n");
      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      if (start == NULL)
	{
	  if (tstart != NULL) 
	    free(tstart);
	}
      if (count == NULL)
	{
	  if (tcount != NULL) 
	    free(tcount);
	}
      if (lcount != NULL)
	free(lcount);
		
      return(FAIL);
    }
  
  
  /* Define memory space */
  /* =================== */
  if(countf == 1 || bothf == 1)
    mid = H5Screate_simple(rank, tcount, NULL);
  else
    mid = H5Screate_simple(rank, lcount, NULL);
  
  if( mid == FAIL)
    {
      sprintf(errbuf,"Cannot create the data space.\n");
      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATASPACE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      if (start == NULL)
	{
	  if (tstart != NULL) 
	    free(tstart);
	}
      if (count == NULL)
	{
	  if (tcount != NULL) 
	    free(tcount);
	}
      if (lcount != NULL)
	free(lcount);
		
      return(FAIL);
    }
  
  
  /* Get the data type ID */
  /* -------------------- */
  tid = H5Dget_type(fieldID );
  if( tid == FAIL )
    {
      sprintf(errbuf,"Cannot get the data type ID.\n");
      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      if (start == NULL)
	{
	  if (tstart != NULL) 
	    free(tstart);
	}
      if (count == NULL)
	{
	  if (tcount != NULL) 
	    free(tcount);
	}
      if (lcount != NULL)
	free(lcount);
		
      return(FAIL);
    }
  
  /* Get the data type class ID */
  /* -------------------------- */
  classid = H5Tget_class(tid);
  if (classid == H5T_NO_CLASS)
    {
      sprintf(errbuf,"Cannot get the data type class ID.\n");
      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      if (start == NULL)
	{
	  if (tstart != NULL)
	    free(tstart);
	}
      if (count == NULL)
	{
	  if (tcount != NULL)
	    free(tcount);
	}
      if (lcount != NULL)
	free(lcount);
 
      return(FAIL);
    }

  /* Write/read whole data to/from the dataset */
  /* ========================================= */
  if( strcmp(code,"w") == 0)
    {
      strbufsize1 = 0;
      nattr = HE5_SWinqlocattrs(swathID, fieldname, NULL, &strbufsize1);
      if ( nattr < 0 )
	{
	  sprintf(errbuf, "Cannot retrieve the attributes. \n");
	  H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  if (start == NULL)
	    {
	      if (tstart != NULL)
		free(tstart);
	    }
	  if (count == NULL)
	    {
	      if (tcount != NULL)
		free(tcount);
	    }
	  if (lcount != NULL)
	    free(lcount);
 
	  return(FAIL);
 
	}
 
      attrlist1 = (char *) calloc(strbufsize1 + 2, sizeof(char));
      if (attrlist1 == NULL)
	{
	  sprintf(errbuf, "Cannot allocate memory for attrlist1.\n") ;
	  H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  if (start == NULL)
	    {
	      if (tstart != NULL)
		free(tstart);
	    }
	  if (count == NULL)
	    {
	      if (tcount != NULL)
		free(tcount);
	    }
	  if (lcount != NULL)
	    free(lcount);
 
	  return(FAIL);
 
	}

      nattr = HE5_SWinqlocattrs(swathID, fieldname, attrlist1, &strbufsize1);
      if ( nattr < 0 )
	{
	  sprintf(errbuf, "Cannot retrieve the attributes. \n");
	  H5Epush(__FILE__,"HE5_SWwrrdfield", __LINE__, H5E_ATTR, H5E_NOTFOUND,  errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  if (attrlist1 != NULL)
	    {
	      free(attrlist1);
	      attrlist1 = NULL;
	    }
	  if (start == NULL)
	    {
	      if (tstart != NULL)
		free(tstart);
	    }
	  if (count == NULL)
	    {
	      if (tcount != NULL)
		free(tcount);
	    }
	  if (lcount != NULL)
	    free(lcount);
 
	  return(FAIL);
 
	}

      attptr = strstr(attrlist1,"ARRAYOFSTRINGS");
      if ( (classid == H5T_STRING) && (attptr == NULL) )
	{
	  status = H5Dwrite(fieldID, tid, mid, fspace,  H5P_DEFAULT, datbuf);
	  if( status == FAIL )
	    {
	      sprintf(errbuf,"Cannot write data to the dataset.\n");
	      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      if (attrlist1 != NULL)
		{
		  free(attrlist1);
		  attrlist1 = NULL;
		}
	      if (start == NULL)
		{
		  if (tstart != NULL)
		    free(tstart);
		}
	      if (count == NULL)
		{
		  if (tcount != NULL)
		    free(tcount);
		}
	      if (lcount != NULL)
		free(lcount);
 
	      return(status);
	    }
	}

      else if ( (classid == H5T_STRING) && (attptr != NULL) )
	{
	  strbufsize2 = 0;
	  nattr = HE5_SWinqlocattrs(swathID, fieldname, NULL, &strbufsize2);
	  if ( nattr < 0 )
	    {
	      sprintf(errbuf, "Cannot retrieve the attributes. \n");
	      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      if (attrlist1 != NULL)
		{
		  free(attrlist1);
		  attrlist1 = NULL;
		}
	      if (start == NULL)
		{
		  if (tstart != NULL)
		    free(tstart);
		}
	      if (count == NULL)
		{
		  if (tcount != NULL)
		    free(tcount);
		}
	      if (lcount != NULL)
		free(lcount);
 
	      return(FAIL);

	    }

	  attrlist2 = (char *) calloc(strbufsize2 + 2, sizeof(char));
	  if (attrlist2 == NULL)
	    {
	      sprintf(errbuf, "Cannot allocate memory for attrlist2.\n") ;
	      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      if (attrlist1 != NULL)
		{
		  free(attrlist1);
		  attrlist1 = NULL;
		}
	      if (start == NULL)
		{
		  if (tstart != NULL)
		    free(tstart);
		}
	      if (count == NULL)
		{
		  if (tcount != NULL)
		    free(tcount);
		}
	      if (lcount != NULL)
		free(lcount);
 
	      return(FAIL);
 
	    }

	  nattr = HE5_SWinqlocattrs(swathID, fieldname, attrlist2, &strbufsize2);
	  if ( nattr < 0 )
	    {
	      sprintf(errbuf, "Cannot retrieve the attributes. \n");
	      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      if (attrlist1 != NULL)
		{
		  free(attrlist1);
		  attrlist1 = NULL;
		}
	      if (attrlist2 != NULL)
		{
		  free(attrlist2);
		  attrlist2 = NULL;
		}
	      if (start == NULL)
		{
		  if (tstart != NULL)
		    free(tstart);
		}
	      if (count == NULL)
		{
		  if (tcount != NULL)
		    free(tcount);
		}
	      if (lcount != NULL)
		free(lcount);
 
	      return(FAIL);
 
	    }

	  if ( (nattr == 0) || ((attptr = strstr(attrlist2,"StringLengthAttribute")) == NULL) )
	    {
	      chardatbuf = (char **)datbuf;
	      if (count == NULL) mycount = tcount[0];
	      if (count != NULL) mycount = *lcount;
	      for (ibuf = 0; ibuf < mycount; ibuf++)
		{
		  if (chardatbuf[ibuf] == NULL)
		    strsize = 0;
		  else
		    strsize = strlen(chardatbuf[ibuf]);
		  if (strsize > maxlen)
		    maxlen = strsize;

		}

	      numattr[0] = 1;
	      status = HE5_SWwritelocattr(swathID, fieldname, "StringLengthAttribute", H5T_NATIVE_INT, numattr, &maxlen);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot write attribute to the field \"%s\".",fieldname) ;
		  H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  if (attrlist1 != NULL)
		    {
		      free(attrlist1);
		      attrlist1 = NULL;
		    }
		  if (attrlist2 != NULL)
		    {
		      free(attrlist2);
		      attrlist2 = NULL;
		    }
		  if (start == NULL)
		    {
		      if (tstart != NULL)
			free(tstart);
		    }
		  if (count == NULL)
		    {
		      if (tcount != NULL)
			free(tcount);
		    }
		  if (lcount != NULL)
		    free(lcount);
 
		  return(status);
		}

	    }

	  status = H5Dwrite(fieldID, tid, mid, fspace,  H5P_DEFAULT, datbuf);
	  if( status == FAIL )
	    {
	      sprintf(errbuf,"Cannot write data to the dataset.\n");
	      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      if (attrlist1 != NULL)
		{
		  free(attrlist1);
		  attrlist1 = NULL;
		}
	      if (attrlist2 != NULL)
		{
		  free(attrlist2);
		  attrlist2 = NULL;
		}
	      if (start == NULL)
		{
		  if (tstart != NULL)
		    free(tstart);
		}
	      if (count == NULL)
		{
		  if (tcount != NULL)
		    free(tcount);
		}
	      if (lcount != NULL)
		free(lcount);
 
	      return(status);
	    }
	}
      else
	{
	  /* Get memory data type ID */
	  /* ----------------------- */
	  mtype  = HE5_EHdtype2mtype(tid);
	  if( mtype == FAIL )
	    {
	      sprintf(errbuf,"Cannot convert to memory data type.\n");
	      status = FAIL;
	      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      if (attrlist1 != NULL)
		{
		  free(attrlist1);
		  attrlist1 = NULL;
		}
	      if (start == NULL)
		{
		  if (tstart != NULL)
		    free(tstart);
		}
	      if (count == NULL)
		{
		  if (tcount != NULL)
		    free(tcount);
		}
	      if (lcount != NULL)
		free(lcount);
 
	      return(status);
	    }

	  status = H5Dwrite(fieldID, mtype, mid, fspace, H5P_DEFAULT, datbuf);
	  if( status == FAIL )
	    {
	      sprintf(errbuf,"Cannot write data to the dataset.\n");
	      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      if (attrlist1 != NULL)
		{
		  free(attrlist1);
		  attrlist1 = NULL;
		}
	      if (start == NULL)
		{
		  if (tstart != NULL) 
		    free(tstart);
		}
	      if (count == NULL)
		{
		  if (tcount != NULL) 
		    free(tcount);
		}
	      if (lcount != NULL)
		free(lcount);
			
	      return(status);
	    }
	}

      if (attrlist1 != NULL)
	{
	  free(attrlist1);
	  attrlist1 = NULL;
	}
      if (attrlist2 != NULL)
	{
	  free(attrlist2);
	  attrlist2 = NULL;
	}
		
    }
  else
    {
      if (classid == H5T_STRING)
	{
	  /* Read the data buffer */
	  /* -------------------- */
	  status = H5Dread(fieldID, tid, mid, fspace , H5P_DEFAULT, datbuf);
	  if( status == FAIL )
	    {
	      sprintf(errbuf,"Cannot read data from the dataset.\n");
	      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATASET, H5E_READERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      if (start == NULL)
		{
		  if (tstart != NULL)
		    free(tstart);
		}
	      if (count == NULL)
		{
		  if (tcount != NULL)
		    free(tcount);
		}
	      if (lcount != NULL)
		free(lcount);
 
	      return(status);
	    }
 
	}
      else
	{

	  /* Get memory data type ID */
	  /* ----------------------- */
          mtype  = HE5_EHdtype2mtype(tid);
	  if( mtype == FAIL )
	    {
	      sprintf(errbuf,"Cannot convert to memory data type.\n");
	      status = FAIL;
	      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      if (start == NULL)
		{
		  if (tstart != NULL)
		    free(tstart);
		}
	      if (count == NULL)
		{
		  if (tcount != NULL)
		    free(tcount);
		}
	      if (lcount != NULL)
		free(lcount);
		  
	      return(status);
	    }

	  /* Read the data buffer */
	  /* -------------------- */
	  status = H5Dread(fieldID, mtype, mid, fspace , H5P_DEFAULT, datbuf);
	  if( status == FAIL )
	    {
	      sprintf(errbuf,"Cannot read data from the dataset.\n");
	      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATASET, H5E_READERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      if (start == NULL)
		{
		  if (tstart != NULL) 
		    free(tstart);
		}
	      if (count == NULL)
		{
		  if (tcount != NULL) 
		    free(tcount);
		}
	      if (lcount != NULL)
		free(lcount);
			
	      return(status);
	    }
	}

    }
  
  if ( count  == NULL)
    {	
      if(tcount != NULL) free(tcount);
    }
  if( start == NULL)
    {	
      if(tstart != NULL) free(tstart);
    }
  if (lcount != NULL)
    free(lcount);
  
  /* Release data space ID */
  /* --------------------- */  
  status = H5Sclose(mid); 
  if( status == FAIL )
    {
      sprintf(errbuf,"Cannot release memory data space ID.\n");
      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATASPACE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
		
      return(status);
    }

  /* Release data space ID */
  /* --------------------- */   
  status = H5Sclose(fspace);
  if( status == FAIL )
    {
      sprintf(errbuf,"Cannot release the file data space ID.\n");
      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATASPACE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
		
      return(status);
    }

  /* Release data type ID */
  /* -------------------- */    
  status = H5Tclose(tid);
  if( status == FAIL )
    {
      sprintf(errbuf,"Cannot release the data type ID.\n");
      H5Epush(__FILE__, "HE5_SWwrrdfield", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
	  
      return(status);
    }
  
 COMPLETION:
  return(status);

}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWwritefield                                                 |
|                                                                             |
|  DESCRIPTION: Writes data to field                                          |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  fieldname      char                fieldname                               |
|  start          hssize_t            start array                             |
|  stride         hsize_t             stride array                            |
|  edge           hsize_t             edge array                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  data           void                data buffer for write                   |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|  Sep  11  Abe Taaheri   Modified for correcting Unlimited dimension         |
|                         behavior and extension                              |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_SWwritefield(hid_t swathID, char *fieldname, const hssize_t start[], const hsize_t stride[], const hsize_t edge[],  void *data)
{
  herr_t          status  = FAIL;           /* return status variable    */
  hsize_t         dims[HE5_DTSETRANKMAX];   /* Field dimensions          */
  int   	  rank     = 0;             /* Field rank                */
  int             unlimdim;
  hsize_t         maxdims[HE5_DTSETRANKMAX];/* Field maximum dimensions  */
  int             append   = FALSE;         /* FLAG (if field is appendable)*/
  int             i;                        /* Loop index                   */
  char            *errbuf = (char *)NULL;   /* error message buffer        */

  HE5_LOCK;
  CHECKNAME(fieldname);
  CHECKPOINTER(data);

  /* If a field is appendable and need to be extended, do extension here 
     before writing extended data into it 
  */

  /* get maxdims for the field */

  /* Allocate memory for error message buffer */
  /* ---------------------------------------- */
  errbuf  = (char *)calloc(HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWwritefield", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }

  status = HE5_SWflddiminfo(swathID, fieldname, &rank, dims, maxdims);
  
  /* see if we need first to extend data dimensions for unlimited 
     dimensions */
  
  for (i = 0; i < rank; i++)
    {
      if( dims[i] == maxdims[i] )
	append = FALSE;
      else if ( (dims[i] < maxdims[i]) || (maxdims[i] == H5S_UNLIMITED))
	{
	  append = TRUE;
	  break;
	}
    }
  unlimdim = i;

  if((append == TRUE) && (edge[unlimdim] > dims[unlimdim]))
    {
      hssize_t newstart[8];
      hsize_t newedge[8];
      
      for (i = 0; i < rank; i++)
	{
	  if (start != NULL)
	    {
	      newstart[i]=start[i];
	    }
	  else
	    {
	      newstart[i]= 0;
	    }

	  if (edge!= NULL)
	    {
	      newedge[i] = edge[i];
	    }
	  else
	    {
	      newedge[i]=dims[i];
	    }
	}
      newstart[unlimdim]=edge[unlimdim]-1;
      newedge[unlimdim] = 1;
      status = HE5_SWwrrdfield(swathID, fieldname, "w", newstart, stride, newedge,data);

      if (status == FAIL)
	{
	  sprintf(errbuf, "Cannot write data to the field \"%s\".",fieldname) ;
	  H5Epush(__FILE__, "HE5_SWwritefield", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(errbuf);
	  return(FAIL);
	}
      else
	{
	  
	  for (i = 0; i < rank; i++)
	    {
	      dims[i]=edge[i];
	    }
	 
	}
    }

  status = HE5_SWwrrdfield(swathID, fieldname, "w", start, stride, edge, data);
  if (status == FAIL)
    {
      sprintf(errbuf, "Cannot write data to the field \"%s\".",fieldname) ;
      H5Epush(__FILE__, "HE5_SWwritefield", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  else
    {
      status = SUCCEED;
      free(errbuf);
    }

 COMPLETION:
  HE5_UNLOCK;

  return(status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWreadfield                                                  |
|                                                                             |
|  DESCRIPTION: Reads data from field                                         |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  fieldname      char                fieldname                               |
|  start          hssize_t            start array                             |
|  stride         hsize_t             stride array                            |
|  edge           hsize_t             edge array                              |
|  buffer         void                data buffer for read                    |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_SWreadfield(hid_t  swathID, char *fieldname,const hssize_t start[], const hsize_t stride[], const hsize_t edge[],  void *data)
{
  
  herr_t   status  = FAIL;/* routine return status variable    */
  
  HE5_LOCK;
  CHECKPOINTER(fieldname);
  status = HE5_SWwrrdfield(swathID, fieldname, "r", start, stride, edge, data);
  
 COMPLETION:
  HE5_UNLOCK;
  return(status);
}





/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWfldsrch                                                    |
|                                                                             |
|  DESCRIPTION: Retrieves information about field DATASET                     |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  fldgroup        int                 Flag representing one of the groups:   |
|                                     (0) "Data Fields", (1)"Geolocation      |
|                                     Fields", and (5) "HE5_PRofile Fields".  |
|                                     (-1) FAILS.                             |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  fldname        char                field name                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  fieldID        hid_t                Field dataset ID                       |
|  rank           int                  dataset Rank                           |
|  dims           hsize_t              Dimensions of field                    |
|  typeID         hid_t                Data type ID                           |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  9/23/99  A.Muslimov    Checked for the status returned by H5Sclose().      |
|  4/18/00  A.Muslimov    Added more error handlings.                         |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  00  A.Muslimov    Modified to incorporate "PRofile Fields" group.     |
|                         Changed the coding scheme.                          |
|  Oct  00  A.Muslimov    Added the case where fieldname is an alias.         |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int   
HE5_SWfldsrch(hid_t swathID, char *fldname, hid_t *fieldID, int *rank,  hsize_t dims[], hid_t *typeID)
{
  int      fldgroup  = FAIL;       /* Field group flag  (return value)   */
  int      i;                      /* Loop index                         */
  int      nameflag  = FAIL;       /* Alias (0) /actual (1) name flag    */

  herr_t   status    = FAIL;       /* routine return status variable     */
  
  hid_t    idx       = FAIL;       /* Swath index                        */
  hid_t    idOffset  = HE5_SWIDOFFSET;/* Swath ID offset                 */
  hid_t    spaceID   = FAIL;       /* File data space ID                 */

  char     fieldname[HE5_HDFE_NAMBUFSIZE];    /* Buffer for name of a field  */ 
  char     fldactualname[HE5_HDFE_NAMBUFSIZE];/* Actual name of a field      */ 
  char     fldtype   ='n';             /* Internal group discriminating flag */
  char     name[HE5_HDFE_NAMBUFSIZE];  /* Field Name buffer                  */
  char     errbuf[HE5_HDFE_ERRBUFSIZE];/* Buffer for error message           */


  CHECKPOINTER(fldname);

  /* Compute "reduced" swath ID */
  /* -------------------------- */
  idx = swathID % idOffset;

  
  /* Call HE5_SWfldnameinfo() to get actual field name */
  /* --------------------------------------------- */
  nameflag = HE5_SWfldnameinfo(swathID, fldname, fldactualname);
  if (nameflag == FAIL)
    {
      sprintf(errbuf, "Cannot get actual name of the field.\n");
      H5Epush(__FILE__, "HE5_SWfldsrch", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  if (nameflag == FALSE)
    {
      strcpy(fieldname,"");
      strcpy(fieldname,fldactualname);
    }

  if (nameflag == TRUE)
    {
      strcpy(fieldname,"");
      strcpy(fieldname,fldname);
    }
  

  /* Loop through all geo datasets in swath */
  /* -------------------------------------- */
  for (i = 0; i < HE5_SWXSwath[idx].nGFLD; i++)
    {
      /* get dataset name */
      /* ---------------- */
      strcpy(name, HE5_SWXSwath[idx].gdataset[i].name);
      if( strcmp(fieldname, name) == 0 ) 
	{
	  fldtype ='g';
	  fldgroup = HE5_HDFE_GEOGROUP;
	  break;
	}
    } 

  /* not found in geo fields */
  /* ----------------------- */
  if( fldtype == 'n')
    {
      /* Loop through all data datasets in swath */
      /* --------------------------------------- */
      for (i = 0; i < HE5_SWXSwath[idx].nDFLD; i++)
	{
	  /* get dataset name */
	  /* ---------------- */
	  strcpy(name, HE5_SWXSwath[idx].ddataset[i].name);
	  if( strcmp(fieldname, name) == 0 )
	    {
	      fldtype ='d';
	      fldgroup   = HE5_HDFE_DATAGROUP;
	      break;
	    }
        }
    }
  

  /* not found in data fields */
  /* ------------------------ */
  if( fldtype == 'n')
    {
      /* Loop through all profile datasets in swath */
      /* ------------------------------------------ */
      for (i = 0; i < HE5_SWXSwath[idx].nPROF; i++)
	{
	  /* get dataset name */
	  /* ---------------- */
	  strcpy(name, HE5_SWXSwath[idx].pdataset[i].name);
	  if( strcmp(fieldname, name) == 0 )
	    {
	      fldtype ='p';
	      fldgroup   = HE5_HDFE_PROFGROUP;
	      break;
	    }
        }
    }


  if (fieldID != NULL)
    {

      /* Get dataset ID */
      /* ============== */
      if( fldtype =='g')
	*fieldID    = HE5_SWXSwath[idx].gdataset[i].ID;
      else if (fldtype =='d')
	*fieldID    = HE5_SWXSwath[idx].ddataset[i].ID;
      else if (fldtype =='p')
	*fieldID    = HE5_SWXSwath[idx].pdataset[i].ID;
      else
	{
	  sprintf(errbuf,"Cannot find \"%s\" field in Swath. Check the spelling.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWfldsrch", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
	  
      /* Get data space ID */
      /* ----------------- */
      spaceID  = H5Dget_space(*fieldID);
      if (spaceID == FAIL)
	{
	  sprintf(errbuf,"Cannot get the data space ID.\n");
	  H5Epush(__FILE__, "HE5_SWfldsrch", __LINE__, H5E_DATASPACE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
	  
      if (rank != NULL)
	{
	  /* Get dataset rank */
	  /* ---------------- */
	  *rank  = H5Sget_simple_extent_ndims(spaceID);
	  if (*rank == FAIL)
	    {
	      sprintf(errbuf,"Cannot get the dataset rank.\n");
	      H5Epush(__FILE__, "HE5_SWfldsrch", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(FAIL);
	    }
	}
	  
      if (typeID != NULL || dims != NULL)
	{
		  
	  /* Get data type ID */
	  /* ---------------- */
	  *typeID = H5Dget_type(*fieldID);
	  if (*typeID == FAIL)
	    {
	      sprintf(errbuf,"Cannot get the data type ID.\n");
	      H5Epush(__FILE__, "HE5_SWfldsrch", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(FAIL);
	    }

	  /* Get dimension sizes */
	  /* ------------------- */
	  status      = H5Sget_simple_extent_dims(spaceID, dims, NULL);
	  if (status == FAIL)
	    {
	      sprintf(errbuf,"Cannot get the data space dimension sizes.\n");
	      H5Epush(__FILE__, "HE5_SWfldsrch", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(FAIL);
	    }
		  
	  /* Release data type ID */
	  /* -------------------- */
	  status = H5Tclose(*typeID);
	  if (status == FAIL)
	    {
	      sprintf(errbuf,"Cannot release the data type ID.\n");
	      H5Epush(__FILE__, "HE5_SWfldsrch", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(FAIL);
	    }
	  
	  /* Release data space ID */
	  /* --------------------- */
	  status = H5Sclose(spaceID);
	  if (status == FAIL)
	    {
	      sprintf(errbuf,"Cannot release the data space ID.\n");
	      H5Epush(__FILE__, "HE5_SWfldsrch", __LINE__, H5E_DATASPACE, H5E_CLOSEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(FAIL);
	    }
		  
	}
	  
    }
  
 COMPLETION:
  return(fldgroup);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdetach                                                     |
|                                                                             |
|  DESCRIPTION: Detachs swath structure and performs housekeeping             |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  8/23/99  A. Muslimov   Checked for the statuses returned by H5Dclose()     |
|                         and H5Gclose().                                     |
|  10/28/99 A.Muslimov    Added a block 'Close previously opened ragged       |
|                         arrays'. Added a call to                            |
|                         H5Gclose(SWXSwath[sID].ra_id), and the lines, cor-  |
|                         responding to the ragged arrays in the block        |
|                         'Delete entries from External Arrays'.              |
|  Feb,2000 A.Muslimov    Fixed a bug-prone release of IDs.                   |
|  Apr,2000 A.Muslimov    Removed "Ragged Arrays" group.                      |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  00  A.Muslimov    Added "PRofile Fields" group.                       |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWdetach(hid_t swathID)
{
  herr_t         status  = FAIL;             /* Return status variable */
  long           idx     = FAIL;             /* Swath index            */
  hid_t          fid     = FAIL;             /* HDF-EOS file ID        */
  hid_t          gid     = FAIL;             /* "HDFEOS" group ID      */
  int            i, k;		 	     /* Loop indices           */
  char           errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer   */

  HE5_LOCK;

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWdetach", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
		
      /* "Detach" from previously attached "Data Fields" datasets */
      /* -------------------------------------------------------- */
      if( HE5_SWXSwath[idx].nDFLD > 0 )
	{
	  for (k = 0; k < HE5_SWXSwath[idx].nDFLD; k++)
	    {
				
	      if ( HE5_SWXSwath[idx].ddataset[k].ID > 0 )
		{    
		  status = H5Dclose(HE5_SWXSwath[idx].ddataset[k].ID);
		  if (status == FAIL)
		    {
		      sprintf(errbuf, "Cannot release the data dataset ID. \n") ;
		      H5Epush(__FILE__, "HE5_SWdetach", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
						
		      return(status);
		    }
		}
	      if(HE5_SWXSwath[idx].ddataset[k].name != NULL)
		free(HE5_SWXSwath[idx].ddataset[k].name);
				
	    }
	  if (HE5_SWXSwath[idx].ddataset != NULL)
	    free(HE5_SWXSwath[idx].ddataset);
	}


      /* "Detach" from previously attached "PRofile Fields" datasets */
      /* ----------------------------------------------------------- */
      if( HE5_SWXSwath[idx].nPROF > 0 )
	{
	  for (k = 0; k < HE5_SWXSwath[idx].nPROF; k++)
	    {
				
	      if ( HE5_SWXSwath[idx].pdataset[k].ID > 0 )
		{    
		  status = H5Dclose(HE5_SWXSwath[idx].pdataset[k].ID);
		  if (status == FAIL)
		    {
		      sprintf(errbuf, "Cannot release the profile dataset ID. \n") ;
		      H5Epush(__FILE__, "HE5_SWdetach", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
					  
		      return(status);
		    }
		}
	      if(HE5_SWXSwath[idx].pdataset[k].name != NULL)
		free(HE5_SWXSwath[idx].pdataset[k].name);
			  
	    }
	  if (HE5_SWXSwath[idx].pdataset != NULL)
	    free(HE5_SWXSwath[idx].pdataset);
	}
		

      /* "Detach" from previously attached "Geolocation Fields" datasets */
      /* --------------------------------------------------------------- */
      if( HE5_SWXSwath[idx].nGFLD > 0 )
	{
	  for (k = 0; k < HE5_SWXSwath[idx].nGFLD; k++)
	    {
	      if ( HE5_SWXSwath[idx].gdataset[k].ID > 0 )
		{    
		  status = H5Dclose(HE5_SWXSwath[idx].gdataset[k].ID);
		  if (status == FAIL)
		    {
		      sprintf(errbuf, "Cannot release the geolocation dataset ID. \n") ;
		      H5Epush(__FILE__, "HE5_SWdetach", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
						
		      return(status);
		    }
					
		}
	      if (HE5_SWXSwath[idx].gdataset[k].name != NULL)
		free(HE5_SWXSwath[idx].gdataset[k].name);   
	    }
	  if (HE5_SWXSwath[idx].gdataset != NULL)
	    free(HE5_SWXSwath[idx].gdataset);
			
	}
		
		
      /* Detach from the Swath groups */
      /* ---------------------------- */
      if ( HE5_SWXSwath[idx].geo_id > 0 )
	{
	  status = H5Gclose(HE5_SWXSwath[idx].geo_id);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot release the \"Geolocation Fields\" group ID. \n") ;
	      H5Epush(__FILE__, "HE5_SWdetach", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
				
	      return(status);
	    }
	}
		
		
      if ( HE5_SWXSwath[idx].data_id > 0 )
	{
	  status = H5Gclose(HE5_SWXSwath[idx].data_id);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot release the \"Data Fields\" group ID. \n") ;
	      H5Epush(__FILE__, "HE5_SWdetach", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
				
	      return(status);
	    }
	}
		
		
      if ( HE5_SWXSwath[idx].prof_id > 0 )
	{
	  status = H5Gclose(HE5_SWXSwath[idx].prof_id);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot release the \"Profile Fields\" group ID.") ;
	      H5Epush(__FILE__, "HE5_SWdetach", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
				
	      return(status);
	    }
	}

		
      if ( HE5_SWXSwath[idx].sw_id > 0 )
	{
	  status = H5Gclose(HE5_SWXSwath[idx].sw_id);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot release the swath group ID. \n") ;
	      H5Epush(__FILE__, "HE5_SWdetach", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
				
	      return(status);
	    }
	}
 
		
      /* Delete entries from External Arrays */
      /* ----------------------------------- */
      HE5_SWXSwath[idx].active       = 0;

      HE5_SWXSwath[idx].geo_id       = 0;
      HE5_SWXSwath[idx].data_id      = 0;
      HE5_SWXSwath[idx].prof_id      = 0;

      HE5_SWXSwath[idx].ddataset     = NULL;
      HE5_SWXSwath[idx].pdataset     = NULL;
      HE5_SWXSwath[idx].gdataset     = NULL;

      HE5_SWXSwath[idx].fid          = 0;
      HE5_SWXSwath[idx].sw_id        = 0;
      HE5_SWXSwath[idx].obj_id       = 0;

      HE5_SWXSwath[idx].nDFLD        = 0;
      HE5_SWXSwath[idx].nPROF        = 0;
      HE5_SWXSwath[idx].nGFLD        = 0;

      /* Free Region Pointers */
      /* -------------------- */
      for (k = 0; k < HE5_NSWATHREGN; k++)
	{
	  if (HE5_SWXRegion[k] != NULL && HE5_SWXRegion[k]->swathID == swathID)
	    {
	      for (i = 0; i < HE5_DTSETRANKMAX; i++)
		{
		  if (HE5_SWXRegion[k]->DimNamePtr[i] != NULL)
		    {
		      free(HE5_SWXRegion[k]->DimNamePtr[i]);
		    }
		}
				
	      free(HE5_SWXRegion[k]);
	      HE5_SWXRegion[k] = NULL;
	    }
	}		
    }

 COMPLETION:  
  HE5_UNLOCK;
  return (status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefboxregion                                               |
|                                                                             |
|  DESCRIPTION: Finds swath cross tracks within area of interest and returns  |
|               region ID                                                     |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  regionID       hid_t               Region ID                               |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  cornerlon      double   dec deg    Longitude of opposite corners of box    |
|  cornerlat      double   dec deg    Latitude of opposite corners of box     |
|  mode           int                 Search mode                             |
|                                     HDFE_MIDPOINT - Use midpoint of Xtrack  |
|                                     HDFE_ENDPOINT - Use endpoints of Xtrack |
|                                     HDFE_ANYPOINT - Use all points of Xtrack|
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Jul 98   Abe Taaheri   Fixed core dump in SWregioninfo associated with     |
|                         SWXRegion[k]->nRegions exceeding MAXNREGIONS in     |
|                         this function                                       |
|                                                                             |
|  Aug 3,99  A.Muslimov   Changed the type of lonArr[] and latArr[] from char |
|                         to float64. Changed types of fid, idx from int32_t  |
|                         to hid_t.                                           |
|  Aug 11,99 A.Muslimov   Left out a factor 8 in front of "(i * edge[1] + j)" |
|                         in  "memcpy(&lonTestVal,&lonArr[i*edge[1]+j],8);"   |
|                         and "memcpy(&latTestVal,&latArr[i*edge[1]+j],8);".  |
|                         Made similar changes in the calls to                |
|                         "memcpy(&lonTestVal,&lonArr[j],8);" and             |
|                         "memcpy(&latTestVal,&latArr[j],8);", and in all     |
|                         other calls to  memcpy().                           |
| 10/18/99     A.Muslimov Replaced memcpy() by memmove() to avoid a problem   |
|                            when arguments 1 and 2 overlap in memory.        |
| 02/08/00     A.Muslimov Added more error checkings.                         |
| 03/13/00     A.Muslimov Modified to convert non-native datatypes to native  |
|                         ones.                                               |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|  Jan  05  S. Zhao       Modified to include a region starts and stops with  |
|                         the same index on the track.                        |
|  Jan  05  S. Zhao       Returned error if regionID exceeded HE5_NSWATHREGN. |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
hid_t
HE5_SWdefboxregion(hid_t swathID, double  cornerlon[], double cornerlat[], int mode)
{

  hid_t           regionID  = FAIL;/* Region ID (return)                     */
  hid_t           fid       = FAIL;/* HDF-EOS file ID                        */
  hid_t           gid       = FAIL;/* "HDFEOS" group ID                      */
  hid_t           tid       = FAIL;/* Longitude/Latitude Datatype ID         */
  hid_t           fieldID   = FAIL;/* Longitude/Latitude Dataset ID          */
  hid_t           k;               /* Loop index                             */

  herr_t          status    = FAIL;/* routine return status variable         */
  herr_t          statLon   = FAIL;/* Status from SWfieldinfo for longitude  */
  herr_t          statLat   = FAIL;/* Status from SWfieldinfo for latitude   */
  herr_t          statCoLat = FAIL;/* Status from SWfieldinfo for            */


  int             validReg  = FAIL;                 /* validReg flag         */
  int             rank      = FAIL;                 /* Rank of dataset       */

  hid_t           nt[1]     ={FAIL};                /* number types          */

  unsigned        found     = 0;                    /* Found flag            */

  unsigned char   *flag     = (unsigned char *)NULL;/* Track flag array      */

  long            idx       = FAIL;                 /* Swath index           */
  long            bndflag   = FAIL;                 /* +/-180 boundary flag  */
  long            lonTest   = FAIL;                 /* Longitude test flag   */
  long            latTest   = FAIL;                 /* Latitude test flag    */
  long            i = 0, j  = 0;                    /* Loop indices          */

  size_t          tsize      =  0;                  /* Data type size (bytes)*/

  hssize_t        start[2]   = {FAIL, FAIL};        /* Start array (read)    */
  hssize_t        anyStart[2]= {FAIL, FAIL};        /* ANYPOINT start array  */

  hsize_t         nElem      = 0;        /* Number of elements to read       */
  hsize_t         dims[HE5_DTSETRANKMAX];/* Dims of geolocation fields       */
  hsize_t         stride[2]  = {1, 1};   /* Stride array (read)              */
  hsize_t         edge[2]    = {0, 0};	 /* Edge array (read)                */
  hsize_t         anyEdge[2] = {0, 0};	 /* ANYPOINT edge array (read)       */

  float           tempFloat  = 0.;	 /* Temporary float variable         */

  double          tempDouble = 0.;       /* Temporary double variable        */
  double          lonTestVal = 0.;       /* Longitude test value             */
  double          latTestVal = 0.;       /* Latitude test value              */

  char            *lonArr = (char *)NULL;/* Longitude data array             */
  char            *latArr = (char *)NULL;/* Latitude data array              */
  char            dimlist[HE5_HDFE_DIMBUFSIZE];/* Dimension list             */
  char            latName[16];	          /* Latitude field name             */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer        */

  HE5_LOCK;
  CHECKPOINTER(cornerlon);
  CHECKPOINTER(cornerlat);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWdefboxregion", &fid, &gid, &idx);	
	
  /* Inclusion mode must be between 0 and 2 */
  /* -------------------------------------- */
  if (mode < 0 || mode > 2)
    {
      status = FAIL;
      sprintf(errbuf, "Improper Inclusion Mode: %d.\n", mode);
      H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
	
  strcpy(dimlist,"");
	
  if (status == SUCCEED)
    {
      /* Initialize dims[] array */
      /* ----------------------- */
      for (i = 0; i < HE5_DTSETRANKMAX; i++)
	dims[i] = 0;

      /* Get "Longitude" field info */
      /* -------------------------- */
      statLon = HE5_SWfieldinfo(swathID, "Longitude", &rank, dims, nt, dimlist, NULL);
      if (statLon == FAIL)
	{
	  status = FAIL;
	  sprintf(errbuf,"\"Longitude\" field not found.\n");
	  H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	}
		
      /* Get "Latitude" field info */
      /* -------------------------- */
      statLat = HE5_SWfieldinfo(swathID, "Latitude", &rank, dims, nt, dimlist, NULL);
      if (statLat == FAIL)
	{
	  /* If not found check for "Colatitude" field info */
	  /* ---------------------------------------------- */
	  statCoLat = HE5_SWfieldinfo(swathID, "Colatitude", &rank, dims, nt,dimlist, NULL);
	  if (statCoLat == FAIL)
	    {
	      /* Neither "Latitude" nor "Colatitude" field found */
	      /* ----------------------------------------------- */
	      status = FAIL;
	      sprintf( errbuf, "Neither \"Latitude\" nor \"Colatitude\" fields found.\n");
	      H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
	  else
	    {
	      /* Latitude field is "Colatitude" */
	      /* ------------------------------ */
	      strcpy(latName, "Colatitude");
	    }
	}
      else
	{
	  /* Latitude field is "Latitude" */
	  /* ---------------------------- */
	  strcpy(latName, "Latitude");
	}
		
		
      /* Get "Latitude" or "Longitude" datatype */
      tsize = HE5_SWfieldsizeID(swathID, "Latitude", &fieldID);
      if (tsize == 0)
	{
	  status = FAIL;
	  sprintf(errbuf,"The size of a data type = 0.\n");
	  H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	}
		
		
      tid = H5Dget_type( fieldID);
      if (tid == FAIL)
	{
	  status = FAIL;
	  sprintf(errbuf,"Cannot get the dataset data type ID.\n");
	  H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	}
		
		
      if (status == SUCCEED)
	{
	  /* Search along entire "Track" dimension from beginning to end */
	  /* ----------------------------------------------------------- */
	  start[0] = 0;
	  edge[0]  = dims[0];
			
			
	  /* If 1D geolocation fields then set mode to MIDPOINT */
	  /* -------------------------------------------------- */
	  if (rank == 1)
	    mode = HE5_HDFE_MIDPOINT;
			
	  switch (mode)
	    {
	      /* If MIDPOINT search single point in middle of "CrossTrack" */
	      /* --------------------------------------------------------- */
	    case HE5_HDFE_MIDPOINT:
				
	      start[1] = HE5_EHlong2hssize( (dims[ 1 ] / 2) );
	      edge[1]  = 1;
				
	      break;
				
	      /* If ENDPOINT search 2 points at either end of "CrossTrack" */
	      /* --------------------------------------------------------- */
	    case HE5_HDFE_ENDPOINT:
				
	      start[1]  = 0;
	      stride[1] = dims[1] - 1;
	      edge[1]   = 2;
				
	      break;
				
	      /* If ANYPOINT do initial MIDPOINT search */
	      /* -------------------------------------- */
	    case HE5_HDFE_ANYPOINT:
				
	      start[1] = HE5_EHlong2hssize( (dims[1] / 2) );
	      if ( start[1] == FAIL )
		{
		  sprintf(errbuf, "Cannot convert data type. \n");
		  H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(FAIL);
		}
	      edge[1]  = 1;
				
	      break;
	    }
			
			
	  /* Compute number of elements */
	  /* -------------------------- */
	  nElem = edge[ 0 ] * edge[ 1 ];
			
			
	  /* Allocate space for longitude and latitude  */
	  /* ------------------------------------------ */
	  lonArr = (char *)calloc(nElem, sizeof(double));
	  if(lonArr == NULL)
	    {
	      H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory");
	      HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	      return(FAIL);
	    }
			
	  latArr = (char *)calloc(nElem, sizeof(double));
	  if(latArr == NULL)
	    {
	      H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory");
	      HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	      free(lonArr);
	      lonArr = NULL;
	      return(FAIL);
	    }
			
	  /* Allocate space for flag array */
	  /* ----------------------------- */
	  flag = (unsigned char *) calloc(edge[0] + 1, sizeof(unsigned char ));
	  if(flag == NULL)
	    {
	      H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory");
	      HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	      free(lonArr);
	      free(latArr);
	      lonArr = NULL;
	      latArr = NULL;
	      return(FAIL);
	    }


	  /* Read Longitude and Latitude fields */
	  /* ---------------------------------- */
	  status = HE5_SWreadfield(swathID, "Longitude", start, stride, edge, lonArr);
	  if( status == FAIL )
	    {
	      H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_FUNC, H5E_CANTINIT, "Cannot read the \"Longitude\" field.");
	      HE5_EHprint("Error: Cannot read the \"Longitude\" field, occured", __FILE__, __LINE__);
	      free(lonArr);
	      free(latArr);
	      free(flag);
	      lonArr = NULL;
	      latArr = NULL;
	      flag   = NULL;
		
	      return(FAIL);
	    }
			
	  status = HE5_SWreadfield(swathID, latName, start, stride, edge, latArr);
	  if( status == FAIL )
	    {
	      H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_FUNC, H5E_CANTINIT, "Cannot read the \"Latitude\" field.");
	      HE5_EHprint("Error: Cannot read the \"Latitude\" field, occured", __FILE__, __LINE__);
	      free(lonArr);
	      free(latArr);
	      free(flag);
	      lonArr = NULL;
	      latArr = NULL;
	      flag   = NULL;
		
	      return(FAIL);
	    }
			
			
	  /*
	   * If geolocation fields are FLOAT then cast each entry as DOUBLE
	   */
	  if ( H5Tequal( tid, H5T_NATIVE_FLOAT) || 
	       H5Tequal( tid, H5T_IEEE_F32LE) || 
	       H5Tequal( tid, H5T_IEEE_F32BE) )
	    {
	      for (i = nElem - 1; i >= 0; i--)
		{
		  memmove(&tempFloat, lonArr + sizeof(float) * i, sizeof(float));
		  tempDouble = (double)tempFloat;
		  memmove(lonArr + sizeof(double) * i, &tempDouble, sizeof(double));
		  memmove(&tempFloat, latArr + sizeof(float) * i, sizeof(float));
		  tempDouble = (double) tempFloat;
		  memmove(latArr + sizeof(double) * i, &tempDouble, sizeof(double));
		}
	    }
			
			
	  /* Set boundary flag */
	  /* ----------------- */
			
	  /*
	   * This variable is set to 1 if the region of interest crosses
	   * the +/- 180 longitude boundary
	   */
	  bndflag = (cornerlon[0] < cornerlon[1]) ? 0 : 1;
			
			
	  /* Main Search Loop */
	  /* ---------------- */
			
	  /* For each track ... */
	  /* ------------------ */
	  for (i = 0; i < edge[0]; i++)
	    {
	      /* For each value from Cross Track ... */
	      /* ----------------------------------- */
	      for (j = 0; j < edge[1]; j++)
		{
		  /* Read in single lon & lat values from data buffers */
		  /* ------------------------------------------------- */
		  memmove(&lonTestVal, &lonArr[sizeof(double) * (i * edge[1] + j)], sizeof(double));
		  memmove(&latTestVal, &latArr[sizeof(double) * (i * edge[1] + j)], sizeof(double));
					
					
		  /* If longitude value > 180 convert to -180 to 180 range */
		  /* ----------------------------------------------------- */
		  if (lonTestVal > 180)
		    lonTestVal = lonTestVal - 360;
				  
		  /* If Colatitude value convert to latitude value */
		  /* --------------------------------------------- */
		  if (statCoLat == 0)
		    latTestVal = 90 - latTestVal;
					
					
		  /* Test if lat value is within range */
		  /* --------------------------------- */
		  latTest = (latTestVal >= cornerlat[0] && latTestVal <= cornerlat[1]);
						
		  if (bndflag == 1)
		    {
		      /*
		       * If boundary flag set test whether longitude value
		       * is outside region and then flip
		       */
		      lonTest = (lonTestVal >= cornerlon[1] && lonTestVal <= cornerlon[0]);
		      lonTest = 1 - lonTest;
		    }
		  else
		    {
		      lonTest = (lonTestVal >= cornerlon[0] && lonTestVal <= cornerlon[1]);
		    }
					
					
		  /*
		   * If both longitude and latitude are within region set
		   * flag on for this track
		   */
		  if ( (lonTest + latTest) == 2 )
		    {
		      flag[i] = 1;
		      found   = 1;
		      break;
		    }
		}
            }
			
			
			
	  /* ANYPOINT search */
	  /* --------------- */
	  if ( (mode == HE5_HDFE_ANYPOINT) && (rank > 1) )
	    {
	      free(lonArr);
	      free(latArr);
	      lonArr = NULL;
	      latArr = NULL;
				
				
	      /* Allocate space for an entire single cross track */
	      /* ----------------------------------------------- */
	      lonArr = (char *) calloc(dims[1], sizeof(double));
	      if(lonArr == NULL)
		{
		  H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory"); 
		  HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
		  return(FAIL);
		}
				
	      latArr = (char *) calloc(dims[1], sizeof(double));
	      if(latArr == NULL)
		{
		  H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory"); 
		  HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
		  free(lonArr);
		  lonArr = NULL;
		  return(FAIL);
		}
				
				
	      /* Setup start and edge */
	      /* -------------------- */
	      anyStart[1] = 0;
	      anyEdge[0]  = 1;
	      anyEdge[1]  = dims[1];
				
				
	      /* For each track starting from 0 */
	      /* ------------------------------ */
	      for (i = 0; i < edge[0]; i++)
		{
					
		  /* If cross track not in region (with MIDPOINT search ... */
		  /* ------------------------------------------------------ */
		  if (flag[i] == 0)
		    {
		      /* Setup track start */
		      /* ----------------- */
		      anyStart[0] = HE5_EHlong2hssize(i);
		      if (anyStart[0] == FAIL )
			{
			  sprintf(errbuf, "Cannot convert data type. \n");
			  H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
			  HE5_EHprint(errbuf, __FILE__, __LINE__);
			  free(lonArr);
			  free(latArr);
			  lonArr = NULL;
			  latArr = NULL;

			  return(FAIL);
			}						


		      /* Read in lon and lat values for cross track */
		      /* ------------------------------------------ */
		      status = HE5_SWreadfield(swathID, "Longitude", anyStart, NULL, anyEdge, lonArr);
		      if(status == FAIL)
			{
			  H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_FUNC, H5E_CANTINIT, "Cannot read the \"Longitude\" field. \n"); 
			  HE5_EHprint("Error: Cannot read the \"Longitude\" field, occured", __FILE__, __LINE__);
			  free(lonArr);
			  free(latArr);
			  lonArr = NULL;
			  latArr = NULL;
							
			  return(FAIL);
			}
						
		      status = HE5_SWreadfield(swathID, latName, anyStart, NULL, anyEdge, latArr);
		      if(status == FAIL)
			{
			  H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_FUNC, H5E_CANTINIT, "Cannot read the \"Latitude\" field. \n"); 
			  HE5_EHprint("Error: Cannot read the \"Latitude\" field, occured", __FILE__, __LINE__);
			  free(lonArr);
			  free(latArr);
			  lonArr = NULL;
			  latArr = NULL;
							
			  return(FAIL);
			}
						
		      /*
		       * If geolocation fields are FLOAT then cast each entry as DOUBLE
		       */
		      if ( H5Tequal( tid, H5T_NATIVE_FLOAT) ||
			   H5Tequal( tid, H5T_IEEE_F32LE) ||
			   H5Tequal( tid, H5T_IEEE_F32BE) )
			{
			  for (j = dims[1] - 1; j >= 0; j--)
			    {
			      memmove(&tempFloat, lonArr + sizeof(float) * j, sizeof(float));
			      tempDouble = (double)tempFloat;
			      memmove(lonArr + sizeof(double) * j, &tempDouble, sizeof(double));
			      memmove(&tempFloat, latArr + sizeof(float) * j, sizeof(float));
			      tempDouble = (double)tempFloat;
			      memmove(latArr + sizeof(double) * j, &tempDouble, sizeof(double));
			    }
			}

		      /* For each value from Cross Track ... */
		      /* ----------------------------------- */
		      for (j = 0; j < dims[1]; j++)
			{
			  /* Read in single lon & lat values from buffers */
			  /* -------------------------------------------- */
			  memmove(&lonTestVal, &lonArr[sizeof(double) * j], sizeof(double));
			  memmove(&latTestVal, &latArr[sizeof(double) * j], sizeof(double));
							
							
			  /* If lon value > 180 convert to -180 - 180 range */
			  /* ---------------------------------------------- */
			  if (lonTestVal > 180)
			    lonTestVal = lonTestVal - 360;
						  
			  /* If Colatitude value convert to latitude value */
			  /* --------------------------------------------- */
			  if (statCoLat == 0)
			    latTestVal = 90 - latTestVal;
							
							
			  /* Test if lat value is within range */
			  /* --------------------------------- */
			  latTest = (latTestVal >= cornerlat[0] && latTestVal <= cornerlat[1]);
							
			  if (bndflag == 1)
			    {
			      /*
			       * If boundary flag set test whether
			       * longitude value is outside region and then
			       * flip
			       */
			      lonTest = (lonTestVal >= cornerlon[1] && lonTestVal <= cornerlon[0]);
			      lonTest = 1 - lonTest;
			    }
			  else
			    {
			      lonTest = (lonTestVal >= cornerlon[0] && lonTestVal <= cornerlon[1]);
			    }
							
							
			  /*
			   * If both longitude and latitude are within
			   * region set flag on for this track
			   */
							
			  if ( (lonTest + latTest) == 2 )
			    {
			      flag[i] = 1;
			      found   = 1;
			      break;
			    }
			}
		    }
		}
	    }
			
	  /* If within region setup Region Structure */
	  /* --------------------------------------- */
	  if (found == 1)
	    {
	      /* For all entries in SWXRegion array ... */
	      /* -------------------------------------- */
	      for (k = 0; k < HE5_NSWATHREGN; k++)
		{
		  /* If empty region ... */
		  /* ------------------- */
		  if (HE5_SWXRegion[k] == 0)
		    {
		      /* Allocate space for region entry */
		      /* ------------------------------- */
		      HE5_SWXRegion[k] = (struct HE5_swathRegion *)calloc(1, sizeof(struct HE5_swathRegion));
		      if(HE5_SWXRegion[k] == NULL)
			{
			  H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory"); 
			  HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
			  return(FAIL);
			}
					  
		      /* Store file and swath ID */
		      /* ----------------------- */
		      HE5_SWXRegion[k]->fid     = fid;
		      HE5_SWXRegion[k]->swathID = swathID;
					  
						
		      /* Set Start & Stop Vertical arrays to FAIL */
		      /* ---------------------------------------- */
		      for (j = 0; j < HE5_DTSETRANKMAX; j++)
			{
			  HE5_SWXRegion[k]->StartVertical[j] = FAIL;
			  HE5_SWXRegion[k]->StopVertical[j]  = FAIL;
			}
						
		      /* Set region ID */
		      /* ------------- */
		      regionID = k;
		      break;
		    }
		}
                          
	      if (k >= HE5_NSWATHREGN)
		{
		  sprintf(errbuf, "regionID exceeded HE5_NSWATHREGN.\n");
		  H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_BTREE,  H5E_BADRANGE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  if (lonArr != NULL) free(lonArr);
		  if (latArr != NULL) free(latArr);
		  if (flag   != NULL) free(flag);
		  return(FAIL);
		} 
				
	      /* Find start and stop of regions */
	      /* ------------------------------ */
				
	      /* Subtract previous flag value from current one */
	      /* --------------------------------------------- */
				
	      /*
	       * Transisition points will have flag value (+1) start or
	       * (255 = (uint8_t) -1) stop of region
	       */
	      for (i = edge[0]; i > 0; i--)
		flag[i] -= flag[i - 1];
				
				
	      for (i = 0; i <= edge[0]; i++)
		{
		  /* Start of region */
		  /* --------------- */
		  if (flag[i] == 1)
		    {
		      /* Increment (multiple) region counter */
		      /* ----------------------------------- */
		      j = ++HE5_SWXRegion[k]->nRegions;

		      if ((HE5_SWXRegion[k]->nRegions) > HE5_MAXNREGIONS)
			{
			  sprintf(errbuf, "HE5_SWXRegion[%d]->nRegions exceeded HE5_MAXNREGIONS = %d.\n", k, HE5_MAXNREGIONS);
			  H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
			  HE5_EHprint(errbuf, __FILE__, __LINE__);
			  if (lonArr != NULL) free(lonArr);
			  if (latArr != NULL) free(latArr);
			  if (flag   != NULL) free(flag);
			  return(FAIL);
			}

		      HE5_SWXRegion[k]->StartRegion[j - 1] = i;

		    }
					
		  /* End of region */
		  /* ------------- */
		  if (flag[i] == 255)
		    {
		      HE5_SWXRegion[k]->StopRegion[j - 1]  = i - 1;
		      validReg = 0;
		    }
		}
	    }
	  if (lonArr != NULL) free(lonArr);
	  if (latArr != NULL) free(latArr);
	  if (flag   != NULL) free(flag);			
	}

      status = H5Tclose(tid);
      if (status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the data type ID.\n");
	  H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
    }
  
  if(validReg != 0)
    {
      sprintf(errbuf,"Invalid region ID.\n");
      H5Epush(__FILE__, "HE5_SWdefboxregion", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      regionID = FAIL;
    }


 COMPLETION:
  HE5_UNLOCK;
  return(regionID);

}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWregionindex                                                |
|                                                                             |
|  DESCRIPTION: Finds swath cross tracks within area of interest and returns  |
|               region index and region ID                                    |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  regionID       hid_t               Region ID                               |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  cornerlon      double   dec deg    Longitude of opposite corners of box    |
|  cornerlat      double   dec deg    Latitude of opposite corners of box     |
|  mode           int                 Search mode                             |
|                                     HDFE_MIDPOINT - Use midpoint of Xtrack  |
|                                     HDFE_ENDPOINT - Use endpoints of Xtrack |
|                                     HDFE_ANYPOINT - Use all points of Xtrack|
|                                                                             |
|  OUTPUTS:                                                                   |
|  geodim         char                geolocation track dimension             |
|  idxrange       hsize_t             indices of region for along track dim.  |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
| 10/18/99     A.Muslimov Replaced memcpy() by memmove() to avoid a problem   |
|                            when arguments 1 and 2 overlap in memory.        |
| 03/13/00     A.Muslimov Modified to convert non-native datatypes to native  |
|                           ones.                                             |
| 06/21/00     A.Muslimov Casted "flag[]" to "int". Moved "l = (hsize_t)i" out|
|                           of the loop "if (mapstatus == 2){}".              |
| July 00      A.Muslimov Unmasked hdf5 data types.                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
hid_t 
HE5_SWregionindex(hid_t swathID, double cornerlon[], double cornerlat[], int  mode, char *geodim, hsize_t idxrange[])
{

  hid_t           regionID     = FAIL;         /* Region ID (return value)      */  
  hid_t           k            = 0;            /* loop index (region counter)   */
  
  herr_t          status       = FAIL;         /* status variable               */
  herr_t          mapstatus    = FAIL;         /* status variable               */
  herr_t          statLon      = FAIL;         /* status variable               */
  herr_t          statLat      = FAIL;         /* status variable               */
  herr_t          statCoLat    = FAIL;         /* status variable               */  
  
  int             validReg     = FAIL;         /* validReg  flag                */
  int             rank         = FAIL;         /* Rank of geolocation fields    */
  
  hid_t           *nt          = (hid_t *)NULL;/* number types                  */
  
  hid_t           fid          = FAIL;         /* HDF-EOS file ID               */
  hid_t           gid          = FAIL;         /* "HDFEOS" group ID             */
  hid_t           datasetid    = FAIL;         /* Dataset ID                    */
  hid_t           datatype     = FAIL;         /* Data type ID                  */
  
  unsigned char   found        =  0;           /* Found flag                    */
  unsigned char   *flag        = (unsigned char *)NULL;/* Track flag array      */
  
  long            idx          = FAIL;         /* Swath index                   */
  long            bndflag      = FAIL;         /* +/-180 boundary flag          */
  long            lonTest      = FAIL;         /* Longitude test flag           */
  long            latTest      = FAIL;         /* Latitude test flag            */
  
  hssize_t        start[2]     =  {FAIL, FAIL};/* Start array (read)            */
  hssize_t        anyStart[2]  =  {FAIL, FAIL};/* ANYPOINT start array (read)   */    
  hssize_t        i = 0, j = 0;                /* Loop indices                  */
  
  hsize_t         l            = 0;            /* loop index                    */
  hsize_t         tmpVal       = 0;            /* Start region tmp value        */
  hsize_t         dims[HE5_DTSETRANKMAX];      /* Dimension array               */
  hsize_t         nElem        = 0;            /* Number of elements to read    */
  hsize_t         stride[2]    = {1, 1};       /* Stride array (read)           */
  hsize_t         edge[2]      = {0, 0};       /* Edge array (read)             */
  hsize_t         anyEdge[2]   = {0, 0};       /* ANYPOINT edge array (read)    */
  
  float           tempFloat    = 0.;           /* Temporary float variable      */
  
  double          lonTestVal   = 0.;           /* Longitude test value          */
  double          latTestVal   = 0.;           /* Latitude test value           */
  double          tempDouble   = 0.;           /* Temporary double variable     */
  
  size_t          size         = 0;            /* Data type size (bytes)        */
  
  char            *lonArr  = (char *)NULL;     /* Longitude data array          */
  char            *latArr  = (char *)NULL;     /* Latitude data array           */
  char            dimlist[HE5_HDFE_DIMBUFSIZE];/* Dimension list (geo fields)   */
  char            latName[16];                 /* Latitude field name           */
  char            errbuf[HE5_HDFE_ERRBUFSIZE]; /* Error message buffer          */
  
  CHECKPOINTER(cornerlon);
  CHECKPOINTER(cornerlat);  
  
  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWregionindex", &fid, &gid, &idx);
  
  /* Inclusion mode must be between 0 and 2 */
  /* -------------------------------------- */
  if (mode < 0 || mode > 2)
    {
      status = FAIL;
      sprintf(errbuf, "Improper Inclusion Mode: %d.\n", mode);
      H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
  
  strcpy(dimlist,"");
  
  
  if (status == SUCCEED)
    {
      /* Initialize dims[] array */
      /* ----------------------- */
      for (l = 0; l < HE5_DTSETRANKMAX; l++)
	dims[l] = 0;

      /* Allocate memory for nt variable */
      /* ------------------------------- */
      nt = (hid_t *)calloc(1, sizeof(hid_t));
      if(nt == (hid_t *)NULL)
	{
	  sprintf(errbuf, "Cannot allocate memory.\n");
	  H5Epush(__FILE__, "HE5_SWregionindex",  __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
	  
      /* Get "Longitude" field info */
      /* -------------------------- */
      statLon = HE5_SWfieldinfo(swathID, "Longitude", &rank, dims, nt, dimlist,NULL);
      if (statLon != SUCCEED)
        {
	  status = FAIL;
	  sprintf(errbuf, "\"Longitude\" field not found.\n");
	  H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(nt);
        }

      /* Get "Latitude" field info */
      /* ------------------------- */
      statLat = HE5_SWfieldinfo(swathID, "Latitude", &rank, dims, nt, dimlist,NULL);
      if (statLat != SUCCEED)
        {
	  /* If not found check for "Colatitude" field info */
	  /* ---------------------------------------------- */
	  statCoLat = HE5_SWfieldinfo(swathID, "Colatitude", &rank, dims, nt, dimlist, NULL);
	  if (statCoLat != SUCCEED)
            {
	      /* Neither "Latitude" nor "Colatitude" field found */
	      /* ----------------------------------------------- */
	      status = FAIL;
	      sprintf(errbuf,  "Neither \"Latitude\" nor \"Colatitude\" fields found.\n");
	      H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(nt);
            }
	  else
            {
	      /* Latitude field is "Colatitude" */
	      /* ------------------------------ */
	      strcpy(latName, "Colatitude");
            }
        }
      else
        {
	  /* Latitude field is "Latitude" */
	  /* ---------------------------- */
	  strcpy(latName, "Latitude");
        }

      /* This line modifies the dimlist variable so only the along-track */
      /* dimension remains.                                              */
      /* --------------------------------------------------------------- */
      strtok(dimlist,",");
      mapstatus = HE5_SWgeomapinfo(swathID,dimlist);
      if(mapstatus == FAIL)
	{
	  status = FAIL;
	  sprintf(errbuf, "Cannot retrieve geo map information.\n");
	  H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(nt);
	}
	  
      strcpy(geodim,dimlist);

      if (status == SUCCEED)
        {
	  /* Search along entire "Track" dimension from beginning to end */
	  /* ----------------------------------------------------------- */
	  start[0] = 0;
	  edge[0]  = dims[0];


	  /* If 1D geolocation fields then set mode to MIDPOINT */
	  /* -------------------------------------------------- */
	  if (rank == 1)
            {
	      mode = HE5_HDFE_MIDPOINT;
            }


	  switch (mode)
            {
	      /* If MIDPOINT search single point in middle of "CrossTrack" */
	      /* --------------------------------------------------------- */
            case HE5_HDFE_MIDPOINT:

	      start[1] = HE5_EHhsize2hssize(dims[ 1 ]/2);
	      if ( start[1] == FAIL )
		{
		  sprintf(errbuf, "Cannot convert data type. \n");
		  H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  free(nt);
		  return(FAIL);
		}
	      edge[1]  = 1;

	      break;

	      /* If ENDPOINT search 2 points at either end of "CrossTrack" */
	      /* --------------------------------------------------------- */
            case HE5_HDFE_ENDPOINT:

	      start[1]  = 0;
	      stride[1] = dims[1] - 1;
	      edge[1]   = 2;

	      break;

	      /* If ANYPOINT do initial MIDPOINT search */
	      /* -------------------------------------- */
            case HE5_HDFE_ANYPOINT:

	      start[1] = HE5_EHhsize2hssize(dims[ 1 ]/2);
	      if ( start[1] == FAIL )
		{
		  sprintf(errbuf, "Cannot convert data type. \n");
		  H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  free(nt);
		  return(FAIL);
		}
	      edge[1]  = 1;

	      break;
            }


	  /* Compute number of elements */
	  /* -------------------------- */
	  nElem = edge[0] * edge[1];

	  /* Allocate space for longitude and latitude  */
	  /* ------------------------------------------ */
	  lonArr = (char *)calloc(nElem, sizeof(double));
	  if(lonArr == NULL)
            {
	      H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory");
	      HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	      free(nt);
	      return(FAIL);
            }

	  latArr = (char *) calloc(nElem, sizeof(double));
	  if(latArr == NULL)
            {
	      H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory");
	      HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	      free(lonArr);
	      free(nt);
	      return(FAIL);
            }


	  /* Allocate space for flag array */
	  /* ----------------------------- */
	  flag = (unsigned char *)calloc(edge[0] + 1, sizeof(unsigned char));
	  if(flag == NULL)
            {
              
	      H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory");
	      HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	      free(lonArr);
	      free(latArr);
	      free(nt);
	      return(FAIL);
            }


	  /* Read Longitude and Latitude fields */
	  /* ---------------------------------- */
	  status = HE5_SWreadfield(swathID, "Longitude",start, stride, edge, lonArr);
	  if( status  == FAIL)
            {
	      H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_DATASET, H5E_READERROR, "Cannot read the \"Longitude\" field.");
	      HE5_EHprint("Error: Cannot read the \"Longitude\" field, occured", __FILE__, __LINE__);
	      free(lonArr);
	      free(latArr);
	      free(nt);
	      free(flag);
	      return(FAIL);
            }


	  status = HE5_SWreadfield(swathID, latName, start, stride, edge, latArr);
	  if( status  == FAIL)
            {
	      H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_DATASET, H5E_READERROR, "Cannot read the \"Latitude\" field.");
	      HE5_EHprint("Error: Cannot read the \"Latitude\" field, occured", __FILE__, __LINE__);
	      free(lonArr);
	      free(latArr);
	      free(nt);
	      free(flag);
	      return(FAIL);
            }


	  /*
	   * If geolocation fields are FLOAT then cast each entry as DOUBLE 
	   */

	  datasetid = H5Dopen(HE5_SWXSwath[idx].geo_id, "Longitude");
	  if(datasetid == FAIL)
	    {
	      sprintf(errbuf, "Cannot open the dataset.\n");
	      H5Epush(__FILE__, "HE5_SWregionindex",  __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(lonArr);
	      free(latArr);
	      free(nt);
	      free(flag);
	      return(FAIL);
	    }

	  datatype  = H5Dget_type(datasetid);
	  if(datatype == FAIL)
	    {
	      sprintf(errbuf, "Cannot get the data type ID.\n");
	      H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(lonArr);
	      free(latArr);
	      free(nt);
	      free(flag);
	      return(FAIL);
	    }

	  size      = H5Tget_size(datatype);
	  if(size == 0)
	    {
	      sprintf(errbuf, "Cannot get the data type size.\n");
	      H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(lonArr);
	      free(latArr);
	      free(nt);
	      free(flag);
	      return(FAIL);
	    }

	  status    = H5Dclose(datasetid);
	  if(status == FAIL)
	    {
	      sprintf(errbuf, "Cannot close the dataset.\n");
	      H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(lonArr);
	      free(latArr);
	      free(nt);
	      free(flag);
	      return(FAIL);
	    }

	  if ( H5Tequal( datatype, H5T_NATIVE_FLOAT) ||
	       H5Tequal( datatype, H5T_IEEE_F32LE) ||
	       H5Tequal( datatype, H5T_IEEE_F32BE) )
	    {
	      for (i = nElem - 1; i >= 0; i--)
		{
		  memmove(&tempFloat, lonArr + sizeof(float) * i, sizeof(float));
		  tempDouble = (double)tempFloat;
		  memmove(lonArr + sizeof(double) * i, &tempDouble, sizeof(double));
		  memmove(&tempFloat, latArr + sizeof(float) * i, sizeof(float));
		  tempDouble = (double)tempFloat;
		  memmove(latArr + sizeof(double) * i, &tempDouble, sizeof(double));
		}
	    }


	  /* Set boundary flag */
	  /* ----------------- */

	  /*
	   * This variable is set to 1 if the region of interest crosses
	   * the +/- 180 longitude boundary
	   */
	  bndflag = (cornerlon[0] < cornerlon[1]) ? 0 : 1;


	  /* Main Search Loop */
	  /* ---------------- */

	  /* For each track ... */
	  /* ------------------ */
	  for (i = 0; i < edge[0]; i++)
	    {		 
	      /* For each value from Cross Track ... */
	      /* ----------------------------------- */
	      for (j = 0; j < edge[1]; j++)
		{
		  /* Read in single lon & lat values from data buffers */
		  /* ------------------------------------------------- */
		  memmove(&lonTestVal, &lonArr[ sizeof(double) * (i * edge[1] + j)], sizeof(double));
		  memmove(&latTestVal, &latArr[ sizeof(double) * (i * edge[1] + j)], sizeof(double));


		  /* If longitude value > 180 convert to -180 to 180 range */
		  /* ----------------------------------------------------- */
		  if (lonTestVal > 180)
		    lonTestVal = lonTestVal - 360;
				  
				  
		  /* If Colatitude value convert to latitude value */
		  /* --------------------------------------------- */
		  if (statCoLat == 0)
		    latTestVal = 90 - latTestVal;
				  

		  /* Test if lat value is within range */
		  /* --------------------------------- */
		  latTest = (latTestVal >= cornerlat[0] && latTestVal <= cornerlat[1]);

		  if (bndflag == 1)
		    {
		      /*
		       * If boundary flag set test whether longitude value
		       * is outside region and then flip
		       */
		      lonTest = (lonTestVal >= cornerlon[1] && lonTestVal <= cornerlon[0]);
		      lonTest = 1 - lonTest;
		    }
		  else
		    {
		      lonTest = (lonTestVal >= cornerlon[0] && lonTestVal <= cornerlon[1]);
		    }


		  /*
		   * If both longitude and latitude are within region set
		   * flag on for this track
		   */
		  if (lonTest + latTest == 2)
		    {
		      flag[i] = 1;
		      found   = 1;
		      break;
		    }
		}
	    }



	  /* ANYPOINT search */
	  /* --------------- */
	  if (mode == HE5_HDFE_ANYPOINT && rank > 1)
	    {
	      if (lonArr != NULL) free(lonArr);
	      if (latArr != NULL) free(latArr);

	      /* Allocate space for an entire single cross track */
	      /* ----------------------------------------------- */
	      lonArr = (char *)calloc(dims[1], sizeof(double));
	      if(lonArr == NULL)
		{
		  H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory");
		  HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
		  if (nt != NULL) free(nt);
		  if (flag != NULL) free(flag);
		  return(FAIL);
		}

	      latArr = (char *)calloc(dims[1], sizeof(double));
	      if(latArr == NULL)
		{
		  H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory");
		  HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
		  free(lonArr);
		  if (nt != NULL) free(nt);
		  if (flag != NULL) free(flag);
		  return(FAIL);
		}

	      /* Setup start and edge */
	      /* -------------------- */
	      anyStart[1] = 0;
	      anyEdge[0]  = 1;
	      anyEdge[1]  = dims[1];


	      /* For each track ... */
	      /* ------------------ */
	      for (i = 0; i < edge[0]; i++)
		{

		  /* If cross track not in region (with MIDPOINT search ... */
		  /* ------------------------------------------------------ */
		  if (flag[i] == 0)
		    {
		      /* Setup track start */
		      /* ----------------- */
		      anyStart[0] = i;

		      /* Read in lon and lat values for cross track */
		      /* ------------------------------------------ */
		      status = HE5_SWreadfield(swathID, "Longitude", anyStart, NULL, anyEdge, lonArr);
		      if( status  == FAIL )
			{
			  H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_DATASET, H5E_READERROR, "Cannot read the \"Longitude\" field. \n");
			  HE5_EHprint("Error: Cannot read the \"Longitude\" field, occured", __FILE__, __LINE__);
			  free(lonArr);
			  free(latArr);
			  if (nt != NULL) free(nt);
			  if (flag != NULL) free(flag);
			  return(FAIL);
			}


		      status = HE5_SWreadfield(swathID, latName, anyStart, NULL, anyEdge, latArr);
		      if( status == FAIL )
			{
			  H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_DATASET, H5E_READERROR, "Cannot read the \"Latitude\" field. \n");
			  HE5_EHprint("Error: Cannot read the \"Latitude\" field, occured", __FILE__, __LINE__);
			  free(lonArr);
			  free(latArr);
			  if (nt != NULL) free(nt);
			  if (flag != NULL) free(flag);
			  return(FAIL);
			}


		      /*
		       * If geolocation fields are FLOAT32 then cast each
		       *              entry as FLOAT64
		       */
		      datasetid = H5Dopen(HE5_SWXSwath[idx].geo_id, "Longitude");
		      if(datasetid == FAIL)
			{
			  sprintf(errbuf, "Cannot open the dataset.\n");
			  H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
			  HE5_EHprint(errbuf, __FILE__, __LINE__);
			  free(lonArr);
			  free(latArr);
			  if (nt != NULL) free(nt);
			  if (flag != NULL) free(flag);
			  return(FAIL);
			}

		      datatype  = H5Dget_type(datasetid);
		      if(datatype == FAIL)
			{
			  sprintf(errbuf, "Cannot get the data type ID.\n");
			  H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
			  HE5_EHprint(errbuf, __FILE__, __LINE__);
			  free(lonArr);
			  free(latArr);
			  if (nt != NULL) free(nt);
			  if (flag != NULL) free(flag);
			  return(FAIL);
			}

		      size      = H5Tget_size(datatype);
		      if(size == 0)
			{
			  sprintf(errbuf, "Cannot get the data type size.\n");
			  H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
			  HE5_EHprint(errbuf, __FILE__, __LINE__);
			  free(lonArr);
			  free(latArr);
			  if (nt != NULL) free(nt);
			  if (flag != NULL) free(flag);
			  return(FAIL);
			}

		      status    = H5Dclose(datasetid);
		      if(status == FAIL)
			{
			  sprintf(errbuf, "Cannot close the dataset.\n");
			  H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
			  HE5_EHprint(errbuf, __FILE__, __LINE__);
			  free(lonArr);
			  free(latArr);
			  if (nt != NULL) free(nt);
			  if (flag != NULL) free(flag);
			  return(FAIL);
			}

		      if ( H5Tequal( datatype, H5T_NATIVE_FLOAT) ||
			   H5Tequal( datatype, H5T_IEEE_F32LE) ||
			   H5Tequal( datatype, H5T_IEEE_F32BE) )
			{
			  for (j = dims[1] - 1; j >= 0; j--)
			    {
			      memmove(&tempFloat, lonArr + sizeof(float) * j, sizeof(float));
			      tempDouble = (double)tempFloat;
			      memmove(lonArr + sizeof(double) * j, &tempDouble, sizeof(double));
			      memmove(&tempFloat, latArr + sizeof(float) * j, sizeof(float));
			      tempDouble = (double)tempFloat;
			      memmove(latArr + sizeof(double) * j, &tempDouble, sizeof(double));
			    }
			}

		      /* For each value from Cross Track ... */
		      /* ----------------------------------- */
		      for (j = 0; j < dims[1]; j++)
			{
			  /* Read in single lon & lat values from buffers */
			  /* -------------------------------------------- */
			  memmove(&lonTestVal, &lonArr[ sizeof(double) * j ], sizeof(double));
			  memmove(&latTestVal, &latArr[ sizeof(double) * j ], sizeof(double));


			  /* If lon value > 180 convert to -180 - 180 range */
			  /* ---------------------------------------------- */
			  if (lonTestVal > 180)
			    {
			      lonTestVal = lonTestVal - 360;
			    }

			  /* If Colatitude value convert to latitude value */
			  /* --------------------------------------------- */
			  if (statCoLat == 0)
			    {
			      latTestVal = 90 - latTestVal;
			    }


			  /* Test if lat value is within range */
			  /* --------------------------------- */
			  latTest = (latTestVal >= cornerlat[0] && latTestVal <= cornerlat[1]);

			  if (bndflag == 1)
			    {
			      /*
			       * If boundary flag set test whether
			       * longitude value is outside region and then
			       * flip
			       */
			      lonTest = (lonTestVal >= cornerlon[1] && lonTestVal <= cornerlon[0]);
			      lonTest = 1 - lonTest;
			    }
			  else
			    {
			      lonTest = (lonTestVal >= cornerlon[0] && lonTestVal <= cornerlon[1]);
			    }


			  /*
			   * If both longitude and latitude are within
			   * region set flag on for this track
			   */
			  if (lonTest + latTest == 2)
			    {
			      flag[i] = 1;
			      found   = 1;
			      break;
			    }
			}
		    }
		}
	    }



	  /* If within region setup Region Structure */
	  /* --------------------------------------- */
	  if (found == 1)
	    {
	      /* For all entries in SWXRegion array ... */
	      /* -------------------------------------- */
	      for (k = 0; k < HE5_NSWATHREGN; k++)
		{
		  /*  If empty region ...  */
		  /* --------------------- */
		  if ( HE5_SWXRegion[ k ] == 0 )
		    {
		      /* Allocate space for region entry */
		      /* ------------------------------- */
		      HE5_SWXRegion[ k ] = (struct HE5_swathRegion *) calloc(1, sizeof(struct HE5_swathRegion));
		      if( HE5_SWXRegion[ k ] == NULL )
			{
			  H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory");  
			  HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
			  if(lonArr != NULL) free(lonArr);
			  if(latArr != NULL) free(latArr);
			  if(flag   != NULL) free(flag);
			  if(nt != (hid_t *)NULL) free(nt);
			  return(FAIL);
			}

		      /* Store file and swath ID */
		      /* ----------------------- */
		      HE5_SWXRegion[ k ]->fid     = fid;
		      HE5_SWXRegion[ k ]->swathID = swathID;


		      /* Set Start & Stop Vertical arrays to FAIL */
		      /* ---------------------------------------- */
		      for (j = 0; j < HE5_DTSETRANKMAX; j++)
			{
			  HE5_SWXRegion[ k ]->StartVertical[j] = FAIL;
			  HE5_SWXRegion[ k ]->StopVertical[j]  = FAIL;
			}

		      /* Set region ID */
		      /* ------------- */
		      regionID = k;
		      break;
		    }
		}


	      /* Find start and stop of regions */
	      /* ------------------------------ */

	      /* Subtract previous flag value from current one */
	      /* --------------------------------------------- */

	      /*
	       * Transisition points will have flag value (+1) start or
	       * (255 = (uint8_t) -1) stop of region
	       */
	      for ( i = edge[0]; i > 0; i-- )
		flag[ i ] -= flag[i - 1];


	      for ( i = 0; i <= edge[0]; i++ )
		{
		  /* Start of region */
		  /* --------------- */
		  if ( (int)flag[i] == 1 )
		    {
		      /* Delyth Jones Moved the increment of the region down */
		      /*  to next if statement j = ++SWXRegion[k]->nRegions; */
		      /*  using temp value, if not equal to stop region      */
		      /*  invalid region otherwise ok Delyth Jones           */

		      tmpVal = HE5_EHhssize2hsize(i + 1);
		      if ( tmpVal == 0 )
			{
			  sprintf(errbuf, "Cannot convert data type. \n");
			  H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
			  if(lonArr != NULL) free(lonArr);
			  if(latArr != NULL) free(latArr);
			  if(flag   != NULL) free(flag);
			  if(nt != (hid_t *)NULL) free(nt);
			  HE5_EHprint(errbuf, __FILE__, __LINE__);
			  return(FAIL);
			}
		    }

		  /* End of region */
		  /* ------------- */
		  if ( (int)flag[i] == 255 )
		    {
		      if( tmpVal != i )
			{
			  /* Increment (multiple) region counter */
			  /* ----------------------------------- */
			  j = ++HE5_SWXRegion[k]->nRegions;
						  
			  l = HE5_EHhssize2hsize(i);

			  if (mapstatus == 2)
			    {
			      if ((tmpVal - 1) % 2 == 1)
				tmpVal = tmpVal + 1;
							  
			      if ((l-1) % 2 == 0)
				l = l - 1;
					   
			    }
			  HE5_SWXRegion[k]->StartRegion[j - 1] = HE5_EHhsize2long( (tmpVal - 1) );
			  if ( HE5_SWXRegion[k]->StartRegion[j - 1] == FAIL )
			    {
			      sprintf(errbuf, "Cannot convert data type. \n");
			      H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
			      if(lonArr != NULL) free(lonArr);
			      if(latArr != NULL) free(latArr);
			      if(flag   != NULL) free(flag);
			      if(nt != (hid_t *)NULL )  free(nt);
			      HE5_EHprint(errbuf, __FILE__, __LINE__);

			      return(FAIL);
			    }
			  idxrange[0] = tmpVal - 1;
			  HE5_SWXRegion[k]->StopRegion[j - 1] = HE5_EHhsize2long( (l - 1) );
			  if ( HE5_SWXRegion[k]->StopRegion[j - 1] == FAIL )
			    {
			      sprintf(errbuf, "Cannot convert data type. \n");
			      H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
			      if(lonArr != NULL) free(lonArr);
			      if(latArr != NULL) free(latArr);
			      if(flag   != NULL) free(flag);
			      if(nt != (hid_t *)NULL )  free(nt);
			      HE5_EHprint(errbuf, __FILE__, __LINE__);

			      return(FAIL);
			    }
			  idxrange[1] = l - 1;
			  validReg = 0;
			}
		    }

		}

	    }

	  if(lonArr != NULL) free(lonArr);
	  if(latArr != NULL) free(latArr);
	  if(flag   != NULL) free(flag);
        }
      if(nt != (hid_t *)NULL)	free(nt);
    }

  if(validReg != 0)
    {
      H5Epush(__FILE__, "HE5_SWregionindex", __LINE__, H5E_FUNC, H5E_CANTINIT, "Invalid Region ID. \n");
      HE5_EHprint("Error: Invalid Region ID, occured", __FILE__, __LINE__);
      regionID = FAIL;
    }

 COMPLETION:  
  return(regionID);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdeftimeperiod                                              |
|                                                                             |
|  DESCRIPTION: Finds swath cross tracks observed during time period and      |
|               returns  period ID                                            |
|                                                                             |
|               region ID                                                     |
|  DESCRIPTION:                                                               |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  periodID       hid_t               Period ID                               |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  starttime      double  TAI sec     Start of time period                    |
|  stoptime       doubel  TAI sec     Stop of time period                     |
|  mode           int                 Search mode                             |
|                                     HDFE_MIDPOINT - Use midpoint of Xtrack  |
|                                     HDFE_ENDPOINT - Use endpoints of Xtrack |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|                                                                             |
|  8/23/99  A.Muslimov    Changed the datatype of fid from int32_t to hid_t.  |
| 03/13/00  A.Muslimov    Modified to convert non-native datatypes to native  |
|                         ones.                                               |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
hid_t
HE5_SWdeftimeperiod(hid_t swathID, double starttime, double stoptime, int mode)
{
  hid_t           periodID = FAIL;               /* Period ID (return)     */
  hid_t           k        = 0;			         /* Loop index             */
  hid_t           fid      = FAIL;               /* HDF-EOS file ID        */
  hid_t           gid      = FAIL;               /* "HDFEOS" group ID      */

  int             dum      = 0;			         /* Dummy (loop) variable  */
  int             rank     = FAIL;               /* Rank of a dataset      */

  herr_t          status   = FAIL;               /* status variable        */
  herr_t          statTime = FAIL;               /* status variable        */

  hid_t           *nt      = (hid_t *)NULL;      /* number types           */

  unsigned char   found    =  0;                 /* Found flag             */

  long            idx      = FAIL;               /* Swath index            */
  long            i = 0, j = 0;			         /* Loop indices           */
  
  hssize_t        start[2] = {FAIL, FAIL};       /* Start array (read)     */

  hsize_t         dims[HE5_DTSETRANKMAX];        /* Dimens. of geo fields  */
  hsize_t         stride[2] = {1, 1};            /* Stride array (read)    */
  hsize_t         edge[2]   = {0, 0};		     /* Edge array (read)      */

  double          timeTest    = 0.;		         /* Time test value        */
  double          *timeDouble = (double *)NULL;	 /* Time data array        */

  char            dimlist[HE5_HDFE_DIMBUFSIZE];	 /* Dim. list (geo flds)   */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];   /* Error message buffer   */



  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWdeftimeperiod", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Initialize dims[] array */
      /* ----------------------- */
      for (i = 0; i < HE5_DTSETRANKMAX; i++)
	dims[i] = 0;

      strcpy(dimlist,"");

      /* Get "Time" field info */
      /* --------------------- */
      nt = (hid_t *)calloc(1, sizeof(hid_t));
      if(nt == (hid_t *)NULL)
	{
	  sprintf(errbuf, "Cannot allocate memory.\n");
	  H5Epush(__FILE__, "HE5_SWdeftimeperiod", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
	  
      statTime = HE5_SWfieldinfo(swathID, "Time", &rank, dims, nt, dimlist,NULL);
      if (statTime != SUCCEED)
        {
	  status = FAIL;
	  sprintf(errbuf, "\"Time\" field not found.\n");
	  H5Epush(__FILE__, "HE5_SWdeftimeperiod", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(nt);
        }

      if (status == SUCCEED)
        {
	  /* Search along entire "Track" dimension from beginning to end */
	  /* ----------------------------------------------------------- */
	  start[0] = 0;
	  edge[0]  = dims[0];

	  /* If 1D geolocation fields then set mode to MIDPOINT */
	  /* -------------------------------------------------- */
	  if (rank == 1)
            {
	      mode = HE5_HDFE_MIDPOINT;
            }

	  switch (mode)
            {
	      /* If MIDPOINT search single point in middle of "CrossTrack" */
	      /* --------------------------------------------------------- */
            case HE5_HDFE_MIDPOINT:

	      start[1] = HE5_EHhsize2hssize(dims[ 1 ]/2);
	      if ( start[1] == FAIL )
		{
		  sprintf(errbuf, "Cannot convert data type. \n");
		  H5Epush(__FILE__, "HE5_SWdeftimeperiod", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
		  if (nt != NULL) free(nt);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(FAIL);
		}
	      edge[1]  = 1;


	      /* Allocate space for time data */
	      /* ---------------------------- */
	      timeDouble = (double *)calloc(edge[0], sizeof(double));
	      if(timeDouble == NULL)
                {
		  sprintf(errbuf, "Cannot allocate memory. \n");
		  H5Epush(__FILE__, "HE5_SWdeftimeperiod", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  if (nt != NULL) free(nt);
		    
		  return(FAIL);
                }


	      /* Read "Time" field */
	      /* ----------------- */
	      status = HE5_SWreadfield(swathID,"Time",start,NULL,edge,timeDouble);
	      break;

	      /* If ENDPOINT search 2 points at either end of "CrossTrack" */
	      /* --------------------------------------------------------- */
            case HE5_HDFE_ENDPOINT:
	      start[1]  = 0;
	      stride[1] = dims[1] - 1;
	      edge[1]   = 2;

	      /* Allocate space for time data */
	      /* ---------------------------- */
	      timeDouble = (double *)calloc(edge[0] * 2, sizeof(double));
	      if(timeDouble == (double *)NULL)
                {
		  sprintf(errbuf, "Cannot allocate memory. \n");
		  H5Epush(__FILE__, "HE5_SWdeftimeperiod", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  if (nt != NULL) free(nt);
		    
		  return(FAIL);
                }
				
	      /* Read "Time" field */
	      /* ----------------- */
	      status = HE5_SWreadfield(swathID, "Time", start, stride, edge, timeDouble);
	      break;

            }


	  /* For each track (from top) ... */
	  /* ----------------------------- */
	  for (i = 0; i < edge[0]; i++)
	    {
	      /* For each value from Cross Track ... */
	      /* ----------------------------------- */
	      for (j = 0; j < edge[1]; j++)
		{
					
		  /* Get time test value */
		  /* ------------------- */
		  timeTest = timeDouble[i * edge[1] + j];
					
		  /* If within time period ... */
		  /* ------------------------- */
		  if (timeTest >= starttime && timeTest <= stoptime)
		    {
		      /* Set found flag */
		      /* -------------- */
		      found = 1;
						
		      /* For all entries in SWXRegion array ... */
		      /* -------------------------------------- */
		      for (k = 0; k < HE5_NSWATHREGN; k++)
			{
			  /* If empty region ... */
			  /* ------------------- */
			  if (HE5_SWXRegion[k] == 0)
			    {
			      /* Allocate space for region entry */
			      /* ------------------------------- */
			      HE5_SWXRegion[k] = (struct HE5_swathRegion *) calloc(1, sizeof(struct HE5_swathRegion));
			      if(HE5_SWXRegion[k] == NULL)
				{
				  sprintf(errbuf, "Cannot allocate memory. \n");
				  H5Epush(__FILE__, "HE5_SWdeftimeperiod", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
				  HE5_EHprint(errbuf, __FILE__, __LINE__);
				  if(nt != (hid_t *)NULL) free(nt);
				  if(timeDouble != (double *)NULL) free(timeDouble);
									
				  return(FAIL);
				}
								
			      /* Store file and swath ID */
			      /* ----------------------- */
			      HE5_SWXRegion[k]->fid     = fid;
			      HE5_SWXRegion[k]->swathID = swathID;
								
								
			      /* Set number of isolated regions to 1 */
			      /* ----------------------------------- */
			      HE5_SWXRegion[k]->nRegions = 1;
								
								
			      /* Set start of region to first track found */
			      /* ---------------------------------------- */
			      HE5_SWXRegion[k]->StartRegion[0] = i;
								
								
			      /* Set Start & Stop Vertical arrays to FAIL */
			      /* ---------------------------------------- */
			      for (dum = 0; dum < HE5_DTSETRANKMAX; dum++)
				{
				  HE5_SWXRegion[k]->StartVertical[dum] = FAIL;
				  HE5_SWXRegion[k]->StopVertical[dum]  = FAIL;
				}

			      /* Set period ID */
			      /* ------------- */
			      periodID = k;
								
			      break; /* Break from "k" loop */
			    }
			}
		    }
		  if (found == 1)
		    {
		      break;	/* Break from "j" loop */
		    }
		}
	      if (found == 1)
		{
		  break;		/* Break from "i" loop */
		}
	    }
			
			
	  /* Clear found flag */
	  /* ---------------- */
	  found = 0;
			
	  /* For each track (from bottom) ... */
	  /* -------------------------------- */
	  for (i = edge[0] - 1; i >= 0; i--)
	    {
	      /* For each value from Cross Track ... */
	      /* ----------------------------------- */
	      for (j = 0; j < edge[1]; j++)
		{
		  /* Get time test value */
		  /* ------------------- */
		  timeTest = timeDouble[i * edge[1] + j];
					
		  /* If within time period ... */
		  /* ------------------------- */
		  if (timeTest >= starttime && timeTest <= stoptime)
		    {
		      /* Set found flag */
		      /* -------------- */
		      found = 1;
						
		      /* Set start of region to first track found */
		      /* ---------------------------------------- */
		      HE5_SWXRegion[k]->StopRegion[0] = i;
						
		      break;	/* Break from "j" loop */
		    }
		}
	      if (found == 1)
		{
		  break;		/* Break from "i" loop */
		}
	    }
	  if (timeDouble != (double *)NULL) free(timeDouble);
	}
		
    }

  if (nt != (hid_t *)NULL) free(nt);
    
  return (periodID);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWextractregion                                              |
|                                                                             |
|  DESCRIPTION: Retrieves data from specified region.                         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  regionID       hid_t               Region ID                               |
|  fieldname      char                Fieldname                               |
|  externalflag   int                 External geolocation fields flag        |
|                                     HDFE_INTERNAL (0)                       |
|                                     HDFE_EXTERNAL (1)                       |
|                                                                             |
|  OUTPUTS:                                                                   |
|  buffer         void                Data buffer containing subsetted region |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
| 10/18/99  A.Muslimov    Replaced memcpy() by memmove() to avoid a problem   |
|                            when arguments 1 and 2 overlap in memory.        |
| 04/19/00  A.Muslimov    Changed type of 'slen' from long to size_t.         |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Feb. 03  Terry Haran/                                                      |
|           Abe Taaheri   Forced map offset to 0 so that data is extracted    |
|                         without offset consideration. This will preserve    |
|                         original mapping between geofields and the data     |
|                         field.                                              |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWextractregion(hid_t swathID, hid_t regionID, char *fieldname, int externalflag, void *buffer)
{
  herr_t          status     = FAIL;           /* Return status variable      */
  herr_t          statMap    = FAIL;           /* status variable             */

  int             rank       = FAIL;           /* Field rank                  */
  int             dum        = FAIL;           /* Dummy (rank) variable       */
  int             i = 0, j = 0, k = 0;	       /* Loop indices                */

  hid_t           ntype[1]   = {FAIL};         /*  Field number types         */
  hid_t           dumtype[1] = {FAIL};         /*  Dummy number types         */

  unsigned char   found      =  0;             /* Found flag                  */
  unsigned char   vfound     =  0;             /* Found flag for vert.subset. */

  hid_t           fid        = FAIL;           /* HDF-EOS file ID             */
  hid_t     	  gid        = FAIL;           /* "HDFEOS" group ID           */
  hid_t           fieldID    = FAIL;           /* Field dataset ID            */

  long 	          idx        = FAIL;           /* Swath index                 */
  long            index      = FAIL;           /* Geo Dim Index               */
  long            nDim       =  0;             /* Number of dimensions        */
  long            offset     = FAIL;           /* Mapping offset              */
  long            incr       = FAIL;           /* Mapping increment           */
  long	          *idxmap    = (long *)NULL;   /* Index mapping array         */
  long            nXtrk      = 0;              /* Number of cross tracks      */

  size_t          bufOffset  = 0;              /* Output buffer offset        */
  size_t          size       = 0;              /* Size of data buffer         */
  size_t          slen[HE5_DTSETRANKMAX];      /* String length array         */
 
  hssize_t        start[HE5_DTSETRANKMAX];     /* Start array for data read   */

  hsize_t 	  idxMapElem = 0;              /* Number of idxmap elements   */
  hsize_t         dumsize    = 0;              /*  Dummy size variable        */
  hsize_t         dumdims[HE5_DTSETRANKMAX];   /* Dimensions array            */
  hsize_t         edge[HE5_DTSETRANKMAX];      /* Edge array for data read    */
  hsize_t         dims[HE5_DTSETRANKMAX];      /* Dimensions                  */

  char            dimlist[HE5_HDFE_DIMBUFSIZE];/* Dimension list              */
  char            geodim[HE5_HDFE_DIMBUFSIZE]; /* Geolocation dimension list  */
  char            tgeodim[HE5_HDFE_DIMBUFSIZE];/* Time field dimension list   */
  char            utlbuf[HE5_HDFE_DIMBUFSIZE]; /* Utility buffer              */
  char            *ptr[HE5_DTSETRANKMAX];      /* String pointer array        */
  char            errbuf[HE5_HDFE_ERRBUFSIZE]; /* error message buffer        */

  CHECKPOINTER(fieldname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWextractregion", &fid, &gid, &idx);

  /* Check for valid region ID */
  /* ------------------------- */
  if (status == SUCCEED)
    {
      if (regionID < 0 || regionID >= HE5_NSWATHREGN)
        {
	  status = FAIL;
	  sprintf(errbuf, "Invalid Region ID: %d.\n", regionID);
	  H5Epush(__FILE__, "HE5_SWextractregion", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
        }
    }

  /* Check for active region ID */
  /* -------------------------- */
  if (status == SUCCEED)
    {
      if (HE5_SWXRegion[regionID] == 0)
        {
	  status = FAIL;
	  sprintf(errbuf, "Inactive Region ID: %d.\n", regionID);
	  H5Epush(__FILE__, "HE5_SWextractregion", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
        }
    }

  /* Check that geo file and data file are same for INTERNAL subsetting */
  /* ------------------------------------------------------------------ */
  if (status == SUCCEED)
    {
      if (HE5_SWXRegion[regionID]->fid != fid && externalflag != HE5_HDFE_EXTERNAL)
        {
	  status = FAIL;
	  sprintf(errbuf, "Region is not defined for this file.\n");
	  H5Epush(__FILE__, "HE5_SWextractregion", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
        }
    }

  /* Check that geo swath and data swath are same for INTERNAL subsetting */
  /* -------------------------------------------------------------------- */
  if (status == SUCCEED)
    {
      if (HE5_SWXRegion[regionID]->swathID != swathID && externalflag != HE5_HDFE_EXTERNAL)
        {
	  status = FAIL;
	  sprintf(errbuf, "Region is not defined for this SWath.\n");
	  H5Epush(__FILE__, "HE5_SWextractregion", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
        }
    }

  /* Check for valid fieldname */
  /* ------------------------- */
  if (status == SUCCEED)
    {
      /* Initialize dims[] array */
      /* ----------------------- */
      for (i = 0; i < HE5_DTSETRANKMAX; i++)
	dims[i] = 0;

      /* Get data field info */
      /* ------------------- */
      strcpy(dimlist,"");
      status = HE5_SWfieldinfo(swathID, fieldname, &rank, dims, ntype, dimlist, NULL);
      if (status != SUCCEED)
        {
	  status = FAIL;
	  sprintf(errbuf, "Fieldname \"%s\" not found.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWextractregion", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
        }
    }

  /* No problems so proceed ... */
  /* -------------------------- */
  if (status == SUCCEED)
    {
      /* Initialize start and edge for all dimensions */
      /* -------------------------------------------- */
      for (i = 0; i < rank; i++)
        {
	  start[i] = 0;
	  edge[i]  = dims[i];
        }

      /* Vertical Subset */
      /* --------------- */
      for (j = 0; j < HE5_DTSETRANKMAX; j++)
        {
	  /* If active vertical subset ... */
	  /* ----------------------------- */
	  if (HE5_SWXRegion[regionID]->StartVertical[j] != FAIL)
            {
	      /* Find vertical dimension within dimlist */
	      /* -------------------------------------- */
	      dum = HE5_EHlong2int(HE5_EHstrwithin(HE5_SWXRegion[regionID]->DimNamePtr[j],dimlist, ',') );
	      if ( dum == FAIL )
		{
		  sprintf(errbuf, "Cannot convert data type. \n");
		  H5Epush(__FILE__, "HE5_SWextractregion", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(FAIL);
		}
	      /* If dimension found ... */
	      /* ---------------------- */
	      if (dum != FAIL)
                {
		  /* Compute start and edge for vertical dimension */
		  /* --------------------------------------------- */
		  vfound = 1;
		  start[dum] = HE5_SWXRegion[regionID]->StartVertical[j];
		  edge[dum]  = HE5_SWXRegion[regionID]->StopVertical[j] - HE5_SWXRegion[regionID]->StartVertical[j] + 1;
                }
	      else
                {
		  /* Vertical dimension not found */
		  /* ---------------------------- */
		  status = FAIL;
		  sprintf(errbuf, "Vertical Dimension Not Found: \"%s\".\n", HE5_SWXRegion[regionID]->DimNamePtr[j]);
		  H5Epush(__FILE__, "HE5_SWextractregion", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
                }
            }
        }



      /* No problems so proceed ... */
      /* -------------------------- */
      if (status == SUCCEED)
        {
	  /* If non-vertical subset regions defined ... */
	  /* ------------------------------------------ */
	  if (HE5_SWXRegion[regionID]->nRegions > 0)
            {
	      /* Initialize dumdims[] array */
	      /* -------------------------- */
	      for ( i = 0; i < HE5_DTSETRANKMAX; i++)
		dumdims[i] = 0;

	      /* Get geolocation dimension name */
	      /* ------------------------------ */
	      strcpy(geodim,"");

	      status = HE5_SWfieldinfo(HE5_SWXRegion[regionID]->swathID, "Longitude", &dum, dumdims, dumtype, geodim, NULL);

	      /* If Time field being used, check for dimensions */
	      /* ---------------------------------------------- */
	      if (HE5_timeflag == 1)
                {
		  /* code change to fix time subset bug for Landsat7 */
		  strcpy(tgeodim,"");
		  status = HE5_SWfieldinfo(HE5_SWXRegion[regionID]->swathID,"Time", &dum, dumdims, dumtype, tgeodim, NULL);

		  if (strcmp(geodim, tgeodim) != 0)
		    {
                      strcpy(geodim, tgeodim);
		    }
                }
	      HE5_timeflag = 0;

	      /* Initialize slen[] array */
	      /* ----------------------- */
	      for ( i = 0; i < HE5_DTSETRANKMAX; i++)
		slen[i] = 0;

	      /* Get "Track" (first) Dimension from geo dimlist */
	      /* ---------------------------------------------- */
	      nDim = HE5_EHparsestr(geodim, ',', ptr, slen);
	      geodim[slen[0]] = 0;

	      /* Parse Data Field Dimlist & find mapping */
	      /* --------------------------------------- */
	      nDim = HE5_EHparsestr(dimlist, ',', ptr, slen);

	      /* Loop through all dimensions and search for mapping */
	      /* -------------------------------------------------- */
	      strcpy(utlbuf,"");
	      for (i = 0; i < nDim; i++)
                {
		  memmove(utlbuf, ptr[i], slen[i]);
		  utlbuf[slen[i]] = 0;
		  statMap = HE5_SWmapinfo(swathID, geodim, utlbuf,&offset, &incr);

		  /*
		   *  Force offset to 0.
		   *  We're not changing the mapping, so we want
		   *  the original offset to apply to the subsetted data.
		   *  Otherwise, bad things happen, such as subsetting
		   *  past the end of the original data, and being unable
		   *  to read the first <offset> elements of the
		   *  original data.
		   *  The offset is only important for aligning the
		   *  data with interpolated (incr > 0) or decimated
		   *  (incr < 0) geolocation information for the data.
		   */
 
		  offset = 0;

		  /* Mapping found */
		  /* ------------- */
		  if (statMap == SUCCEED)
                    {
		      found = 1;
		      index = i;
		      break;
                    }
                }


	      /* If mapping not found check for geodim within dimlist */
	      /* ---------------------------------------------------- */
	      if (found == 0)
                {
		  index = HE5_EHstrwithin(geodim, dimlist, ',');

		  /* Geo dimension found within subset field dimlist */
		  /* ----------------------------------------------- */
		  if (index != FAIL)
                    {
		      found  = 1;
		      offset = 0;
		      incr   = 1;
                    }
                }

	      /* If mapping not found check for indexed mapping */
	      /* ---------------------------------------------- */
	      if (found == 0)
                {
		  /* Get size of geo dim & allocate space of index mapping */
		  /* ----------------------------------------------------- */
		  dumsize = HE5_SWdiminfo(swathID, geodim);
		  if(dumsize == 0)
                    {
		      H5Epush(__FILE__, "HE5_SWextractregion", __LINE__, H5E_FUNC, H5E_CANTINIT, "Cannot get the dimension size. \n"); 
		      HE5_EHprint("Error: Cannot get the dimension size, occured", __FILE__, __LINE__);
		      return(FAIL);
                    }

		  idxmap  = (long *)calloc(dumsize, sizeof(long));
		  if(idxmap == NULL)
                    {
		      H5Epush(__FILE__, "HE5_SWextractregion", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory. \n"); 
		      HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
		      return(FAIL);
                    }

		  /* Loop through all dimensions and search for mapping */
		  /* -------------------------------------------------- */
		  strcpy(utlbuf,"");
		  for (i = 0; i < nDim; i++)
                    {
		      memmove(utlbuf, ptr[i], slen[i]);
		      utlbuf[slen[i]] = 0;
		      idxMapElem = HE5_SWidxmapinfo(swathID, geodim, utlbuf, idxmap);

		      /* Mapping found */
		      /* ------------- */
		      if (idxMapElem > 0)
                        {
			  found = 1;
			  index = i;
			  break;
                        }
                    }
                }


	      /* If regular mapping found ... */
	      /* ---------------------------- */
	      if (found == 1 && idxMapElem == 0)
                {
		  for (k = 0; k < HE5_SWXRegion[regionID]->nRegions; k++)
                    {
		      if (k > 0)
                        {
			  /* Compute size in bytes of previous region */
			  /* ---------------------------------------- */
			  size = edge[0];
			  for (j = 1; j < rank; j++)
                            {
			      size *= edge[j];
                            }
			  size *= HE5_SWfieldsizeID(swathID, fieldname, &fieldID);


			  /* Compute output buffer offset */
			  /* ---------------------------- */
			  bufOffset += size;
                        }
		      else
                        {
			  /* Initialize output buffer offset */
			  /* ------------------------------- */
			  bufOffset = 0;
                        }


		      /* Compute number of cross tracks in region */
		      /* ---------------------------------------- */
		      nXtrk = HE5_SWXRegion[regionID]->StopRegion[k] - HE5_SWXRegion[regionID]->StartRegion[k] + 1;


		      /* Positive increment (geodim <= datadim) */
		      /* -------------------------------------- */
		      if (incr > 0)
                        {
			  start[index] = HE5_SWXRegion[regionID]->StartRegion[k] * incr + offset;
			  edge[index]  = nXtrk * incr;
                        }
		      else
                        {
			  /* Negative increment (geodim > datadim) */
			  /* ------------------------------------- */
			  start[index] = HE5_SWXRegion[regionID]->StartRegion[k] / (-incr) + offset;
			  edge[index]  = nXtrk / (-incr);

			  /*
			   * If Xtrk not exactly divisible by incr, round
			   * edge to next highest integer
			   */

			  if (nXtrk % (-incr) != 0)
                            {
			      edge[index]++;
                            }
                        }


		      /* Read Data into output buffer */
		      /* ---------------------------- */
		      status = HE5_SWreadfield(swathID, fieldname,start, NULL, edge,(unsigned char *) buffer + bufOffset);
                    }
                }
	      else if (found == 1 && idxMapElem > 0)
                {
		  /* Indexed Mapping */
		  /* --------------- */
		  for (k = 0; k < HE5_SWXRegion[regionID]->nRegions; k++)
                    {
		      if (k > 0)
                        {
			  /* Compute size in bytes of previous region */
			  /* ---------------------------------------- */
			  size = edge[0];
			  for (j = 1; j < rank; j++)
                            {
			      size *= edge[j];
                            }
			  size *= HE5_SWfieldsizeID(swathID,fieldname, &fieldID);

			  /* Compute output buffer offset */
			  /* ---------------------------- */
			  bufOffset += size;
                        }
		      else
                        {
			  /* Initialize output buffer offset */
			  /* ------------------------------- */
			  bufOffset = 0;
                        }

		      /* Compute start & edge from index mappings */
		      /* ---------------------------------------- */
		      start[index] = idxmap[HE5_SWXRegion[regionID]->StartRegion[k]];
		      edge[index]  = idxmap[HE5_SWXRegion[regionID]->StopRegion[k]] - idxmap[HE5_SWXRegion[regionID]->StartRegion[k]] + 1;

		      /* Read Data into output buffer */
		      /* ---------------------------- */
		      status = HE5_SWreadfield(swathID, fieldname, start, NULL, edge,(unsigned char *)buffer + bufOffset);
                    }
                }
	      else if(vfound == 1)
                {
		  /* Vertical subsetting found previously, */
		  /* read out data buffer  (xhua)          */
		  status = HE5_SWreadfield(swathID, fieldname, start, NULL, edge, (unsigned char *)buffer);
                }
	      else
                {
		  /* Mapping not found */
		  /* ----------------- */
		  status = FAIL;
		  sprintf(errbuf,"Mapping Not Defined for \"%s\" Dimension.\n", geodim);
                }
            }
	  else
            {
	      /* Read Data (Vert SS only) */
	      /* ------------------------ */
	      status = HE5_SWreadfield(swathID, fieldname, start, NULL,  edge,(unsigned char *)buffer);
            }
        }
    }
  /* Free index mappings if applicable */
  /* --------------------------------- */
  if (idxmap != NULL)  free(idxmap);

 COMPLETION:
  return (status);
}




/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWextractperiod                                              |
|                                                                             |
|  DESCRIPTION: Retrieves data from specified period.                         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  periodID       hid_t               Period ID                               |
|  fieldname      char                Fieldname                               |
|  externalflag   int                 External geolocation fields flag:       |
|                                                                             |
|                                     HDFE_INTERNAL (0)                       |
|                                     HDFE_EXTERNAL (1)                       |
|  OUTPUTS:                                                                   |
|  buffer         void                Data buffer containing subsetted region |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWextractperiod(hid_t swathID, hid_t periodID, char *fieldname, int externalflag, void *buffer)
{
  herr_t          status = FAIL;/* routine return status variable */

  HE5_timeflag           = 1;

  CHECKPOINTER(fieldname);

  /* Call SWextractregion routine */
  /* ---------------------------- */
  status = HE5_SWextractregion(swathID, periodID, fieldname, externalflag, (char *)buffer);

 COMPLETION:
  return (status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdupregion                                                  |
|                                                                             |
|  DESCRIPTION: Duplicates a region                                           |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  newregionID    hid_t               New region ID                           |
|                                                                             |
|  INPUTS:                                                                    |
|  oldregionID    hid_t               Old region ID                           |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======   ============  =================================================  |
|  July 00   A.Muslimov    Unmasked hdf5 data types.                          |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
hid_t 
HE5_SWdupregion(hid_t oldregionID)
{
  hid_t   newregionID = FAIL;/* New region ID (return) */
  hid_t   i;			     /* Loop index             */


  /* Find first empty (inactive) region */
  /* ---------------------------------- */
  for (i = 0; i < HE5_NSWATHREGN; i++)
    {
      if (HE5_SWXRegion[ i ] == 0)
        {
	  /* Allocate space for new swath region entry */
	  /* ----------------------------------------- */
	  HE5_SWXRegion[ i ] = (struct HE5_swathRegion *) calloc(1, sizeof(struct HE5_swathRegion));
	  if(HE5_SWXRegion[ i ] == NULL)
            {
	      H5Epush(__FILE__, "HE5_SWdupregion", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory. \n");
	      HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	      return(FAIL);
            }

	  /* Copy old region structure data to new region */
	  /* -------------------------------------------- */
	  *HE5_SWXRegion[ i ] = *HE5_SWXRegion[ oldregionID ];

	  /* Define new region ID */
	  /* -------------------- */
	  newregionID = i;

	  break;
        }
    }

  return (newregionID);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefvrtregion                                               |
|                                                                             |
|  DESCRIPTION: Finds elements of a monotonic field within a given range.     |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  regionID       hid_t               Region ID                               |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  regionID       hid_t               Region ID                               |
|  vertObj        char                Vertical object to subset               |
|  range          double              Vertical subsetting range               |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
| 10/18/99  A.Muslimov Replaced memcpy() by memmove() to avoid a problem      |
|                            when arguments 1 and 2 overlap in memory.        |
| 03/13/00  A.Muslimov Modified to convert non-native datatypes to            |
|                              native ones.                                   |
|                                                                             |
|  July 00   A.Muslimov   Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|  Mar  04  S.Zhao        Modified for supported field type.                  |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/


/* Macro to initialize swath region entry */
/* -------------------------------------- */

/*
 * 1) Find empty (inactive) region. 2) Allocate space for region entry. 3)
 * Store file ID and swath ID. 4) Set region ID. 5) Initialize vertical
 * subset entries to FAIL.
 */

#define HE5_SETSWTHREG						\
								\
  for (k = 0; k < HE5_NSWATHREGN; k++)				\
    {								\
      if (HE5_SWXRegion[k] == 0)				\
	{							\
	  HE5_SWXRegion[k] = (struct HE5_swathRegion *)		\
	    calloc(1, sizeof(struct HE5_swathRegion));		\
	  HE5_SWXRegion[k]->fid = fid;				\
	  HE5_SWXRegion[k]->swathID = swathID;			\
	  regionID = k;						\
	  for (j = 0; j < HE5_DTSETRANKMAX; j++)		\
	    {							\
	      HE5_SWXRegion[k]->StartVertical[j] = FAIL;	\
	      HE5_SWXRegion[k]->StopVertical[j]  = FAIL;	\
	    }							\
	  break;						\
	}							\
    }


/* Macro to fill vertical subset entry */
/* ----------------------------------- */

/*
 * 1) Find empty (inactive) vertical region. 2) Set start of vertical region.
 * 3) Allocate space for name of vertical dimension. 4) Write vertical
 * dimension name.
 */


#define HE5_FILLVERTREG						\
  for (j = 0; j < HE5_DTSETRANKMAX; j++)			\
    {								\
      if (HE5_SWXRegion[regionID]->StartVertical[j] == FAIL)	\
	{							\
	  HE5_SWXRegion[regionID]->StartVertical[j] = i;	\
	  HE5_SWXRegion[regionID]->DimNamePtr[j] =		\
            (char *)calloc( (slen + 1), sizeof(char) );		\
	  memmove(HE5_SWXRegion[regionID]->DimNamePtr[j],	\
		  dimlist, slen + 1);				\
	  break;						\
	}							\
    }


hid_t 
HE5_SWdefvrtregion(hid_t swathID, hid_t regionID, char *vertObj, double range[])
{

  hid_t           fid       = FAIL;/* HDF-EOS file ID                     */
  hid_t           gid       = FAIL;/* "HDFEOS" group ID                   */
  hid_t     	  dtype     = FAIL;/* Data type ID                        */
  hid_t           fieldID   = FAIL;/* Field related dataset ID            */
  hid_t           k         = 0;   /* Loop index                          */

  herr_t          status    = FAIL;/* routine return status variable      */

  int             vertINT   = 0;   /* Temporary INT variable              */
  int             rank      = FAIL;/* Field rank                          */
  int     	      temp      = FAIL;/* Temporary data type code            */
  int             j         = 0;   /* Loop index                          */

  hid_t           *nt       = (hid_t *)NULL;     /*  number types         */

  unsigned char   found     =  0;   /* Found flag                         */

  long            idx       = FAIL; /* Swath index                        */
  long            slen      = 0;    /* String length                      */
  long            i         = 0;    /* Loop index                         */
 
  hsize_t         dims[HE5_DTSETRANKMAX];/* Field dimensions              */

  size_t          size      = 0;     /* Size of numbertype in bytes       */

  short           vertSHT   = 0;	 /* Temporary SHORT variable          */

  float           vertFLT   = 0.;	 /* Temporary FLOAT variable          */

  double          vertDBL   = 0.;	 /* Temporary DOUBLE variable         */

  char            *vertArr = (char *)NULL;/* Ptr to vrt field data buffer */
  char            dimlist[HE5_HDFE_DIMBUFSIZE];/* Dimension list          */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer     */

  HE5_LOCK;
  CHECKPOINTER(vertObj);
  CHECKPOINTER(range);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWdefvrtregion", &fid, &gid, &idx);

  strcpy(dimlist,"");

  if (status == SUCCEED)
    {
      /* Copy first 4 characters of vertObj into dimlist */
      /* ----------------------------------------------- */
      memmove(dimlist, vertObj, 4);
      dimlist[4] = 0;

      /* If first 4 characters of vertObj = "DIM:" ... */
      /* --------------------------------------------- */

      /* Vertical Object is dimension name */
      /* --------------------------------- */
      if (strcmp(dimlist, "DIM:") == 0)
        {
	  /* Get string length of vertObj (minus "DIM:) */
	  /* ------------------------------------------ */
	  slen = strlen(vertObj) - 4;

	  /* Setup swath region entry */
	  /* ------------------------ */
	  if (regionID == FAIL)
            {
	      HE5_SETSWTHREG;
            }

	  /* Find first empty (inactive) vertical subset entry */
	  /* ------------------------------------------------- */
	  for (j = 0; j < HE5_DTSETRANKMAX; j++)
            {
	      if (HE5_SWXRegion[regionID]->StartVertical[j] == FAIL)
                {
		  /* Store start & stop of vertical region */
		  /* ------------------------------------- */
		  HE5_SWXRegion[regionID]->StartVertical[j] = (long)range[0];
		  HE5_SWXRegion[regionID]->StopVertical[j]  = (long)range[1];

		  /* Store vertical dimension name */
		  /* ----------------------------- */
		  HE5_SWXRegion[regionID]->DimNamePtr[j] = (char *)calloc( (slen + 1), sizeof(char) );
		  if(HE5_SWXRegion[regionID]->DimNamePtr[j] == NULL)
                    {
		      H5Epush(__FILE__, "HE5_SWdefvrtregion", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory. \n");
		      HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);

		      return(FAIL);
                    }
		  memmove(HE5_SWXRegion[regionID]->DimNamePtr[j], vertObj + 4, slen + 1);
		  break;
                }
            }
        }
      else
        {
	  /* Check for valid fieldname */
	  /* ------------------------- */
	  nt = (hid_t *)calloc(1, sizeof(hid_t));
	  if ( nt == (hid_t *)NULL )
	    {
	      status = FAIL;
	      sprintf( errbuf,"Cannot allocate memory for data type class ID.\n");
	      H5Epush(__FILE__, "HE5_SWdefvrtregion", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	    }
		  
	  /* Initialize dims[] array */
	  /* ----------------------- */
	  for ( j = 0; j < HE5_DTSETRANKMAX; j++)
	    dims[j] = 0;

	  /* Get field information */
	  /* --------------------- */
	  status = HE5_SWfieldinfo(swathID, vertObj, &rank, dims, nt,dimlist,NULL);
	  if (status != SUCCEED)
            {
	      status = FAIL;
	      sprintf(errbuf,"Vertical Field: \"%s\" not found.\n", vertObj);
	      H5Epush(__FILE__, "HE5_SWdefvrtregion", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      if (nt != NULL) free(nt);
            }

	  /* Get field ID and field data type */
	  /* ------------------------------- */
	  HE5_SWfieldsizeID(swathID, vertObj, &fieldID);
	  dtype = H5Dget_type( fieldID);

	  /* Check for supported field type */
	  /* ------------------------------ */
	  if (!H5Tequal(dtype, H5T_NATIVE_SHORT)  &&
	      !H5Tequal(dtype, H5T_STD_I16BE) &&
	      !H5Tequal(dtype, H5T_STD_I16LE) &&
	      !H5Tequal(dtype, H5T_NATIVE_INT)    &&
	      !H5Tequal(dtype, H5T_STD_I32BE)     &&
	      !H5Tequal(dtype, H5T_STD_I32LE)     &&
	      !H5Tequal(dtype, H5T_NATIVE_FLOAT)  &&
	      !H5Tequal(dtype, H5T_IEEE_F32BE)    &&
	      !H5Tequal(dtype, H5T_IEEE_F32LE)    &&
	      !H5Tequal(dtype, H5T_NATIVE_DOUBLE) &&
	      !H5Tequal(dtype, H5T_IEEE_F64BE)    &&
	      !H5Tequal(dtype, H5T_IEEE_F64LE))
	    {
	      status = FAIL;
	      sprintf(errbuf,"Fieldtype not supported for vertical subsetting");
	      H5Epush(__FILE__, "HE5_SWdefvrtregion", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      if (nt != NULL) free(nt);		
	    }


	  if ( H5Tequal( dtype, H5T_NATIVE_SHORT) ||
	       H5Tequal( dtype, H5T_STD_I16BE) ||
	       H5Tequal( dtype, H5T_STD_I16LE) )
	    temp = 1;
	  else if ( H5Tequal(dtype, H5T_NATIVE_INT) ||
		    H5Tequal(dtype, H5T_STD_I32BE) ||
		    H5Tequal(dtype, H5T_STD_I32LE) )
	    temp = 2;
	  else if ( H5Tequal( dtype, H5T_NATIVE_FLOAT) ||
		    H5Tequal( dtype, H5T_IEEE_F32BE) ||
		    H5Tequal( dtype, H5T_IEEE_F32LE) )
	    temp = 3;
	  else if ( H5Tequal(dtype, H5T_NATIVE_DOUBLE) ||
		    H5Tequal(dtype, H5T_IEEE_F64BE) ||
		    H5Tequal(dtype, H5T_IEEE_F64LE) )
	    temp = 4;


	  /* Check that vertical dimension is 1D */
	  /* ----------------------------------- */
	  if (status == SUCCEED)
            {
	      if (rank != 1)
                {
		  status = FAIL;
		  sprintf(errbuf, "Vertical Field: \"%s\" must be 1-dim.\n", vertObj);
		  H5Epush(__FILE__, "HE5_SWdefvrtregion", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  if (nt != NULL) free(nt);
                }
            }


	  /* If no problems then continue */
	  /* ---------------------------- */
	  if (status == SUCCEED)
            {
	      /* Get string length of vertical dimension */
	      /* --------------------------------------- */
	      slen = strlen(dimlist);

	      /* Get size in bytes of vertical field numbertype */
	      /* ---------------------------------------------- */
	      size = HE5_SWfieldsizeID(swathID,vertObj, &fieldID);

	      /* Allocate space for vertical field */
	      /* --------------------------------- */
	      vertArr = (char *)calloc(dims[0], size);
	      if(vertArr == NULL)
                {
		  H5Epush(__FILE__, "HE5_SWdefvrtregion", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory");
		  HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
                  if (nt != NULL) free(nt);
		  return(FAIL);
                }

	      /* Read vertical field */
	      /* ------------------- */
	      status = HE5_SWreadfield(swathID, vertObj, NULL, NULL, NULL, vertArr);

	      switch (temp)
                {
                case 1:

		  for (i = 0; i < dims[0]; i++)
                    {
		      /* Get single element of vertical field */
		      /* ------------------------------------ */
		      memmove(&vertINT, vertArr + i * size, size);

		      /* If within range ... */
		      /* ------------------- */
		      if (vertINT >= range[0] && vertINT <= range[1])
                        {
			  /* Set found flag */
			  /* -------------- */
			  found = 1;

			  /* Setup swath region entry */
			  /* ------------------------ */
			  if (regionID == FAIL)
                            {
			      HE5_SETSWTHREG;
                            }

			  /* Fill-in vertical region entries */
			  /* ------------------------------- */
			  HE5_FILLVERTREG;

			  break;
                        }
                    }


		  /* If found read from "bottom" of data field */
		  /* ----------------------------------------- */
		  if (found == 1)
                    {
		      for (i = dims[0] - 1; i >= 0; i--)
                        {
			  /* Get single element of vertical field */
			  /* ------------------------------------ */
			  memmove(&vertINT, vertArr + i * size, size);

			  /* If within range ... */
			  /* ------------------- */
			  if (vertINT >= range[0] && vertINT <= range[1])
                            {
			      /* Set end of vertical region */
			      /* -------------------------- */
			      HE5_SWXRegion[regionID]->StopVertical[j] = i;
			      break;
                            }
                        }
                    }
		  else
                    {
		      /* No vertical entries within region */
		      /* --------------------------------- */
		      status = FAIL;
		      sprintf(errbuf, "No vertical field entries within region.\n");
		      H5Epush(__FILE__, "HE5_SWdefvrtregion", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf); 
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      if (nt != NULL) free(nt);
			
                    }
		  break;

                case 2:

		  for (i = 0; i < dims[0]; i++)
                    {
		      /* Get single element of vertical field */
		      /* ------------------------------------ */
		      memmove(&vertSHT, vertArr + i * size, size);

		      /* If within range ... */
		      /* ------------------- */
		      if (vertSHT >= range[0]  && vertSHT <= range[1])
                        {
			  /* Set found flag */
			  /* -------------- */
			  found = 1;

			  /* Setup swath region entry */
			  /* ------------------------ */
			  if (regionID == FAIL)
			    {
			      HE5_SETSWTHREG;
			    }

			  /* Fill-in vertical region entries */
			  /* ------------------------------- */
			  HE5_FILLVERTREG;

			  break;
                        }
                    }


		  /* If found read from "bottom" of data field */
		  /* ----------------------------------------- */
		  if (found == 1)
                    {
		      for (i = dims[0] - 1; i >= 0; i--)
                        {
			  /* Get single element of vertical field */
			  /* ------------------------------------ */
			  memmove(&vertSHT, vertArr + i * size, size);

			  /* If within range ... */
			  /* ------------------- */
			  if (vertSHT >= range[0] && vertSHT <= range[1])
                            {
			      /* Set end of vertical region */
			      /* -------------------------- */
			      HE5_SWXRegion[regionID]->StopVertical[j] = i;
			      break;
                            }
                        }
                    }
		  else
                    {
		      /* No vertical entries within region */
		      /* --------------------------------- */
		      status = FAIL;
		      sprintf(errbuf, "No vertical field entries within region.\n");
		      H5Epush(__FILE__, "HE5_SWdefvrtregion", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf); 
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      if (nt != NULL) free(nt);
			
                    }
		  break;

                case 3:

		  for (i = 0; i < dims[0]; i++)
                    {
		      /* Get single element of vertical field */
		      /* ------------------------------------ */
		      memmove(&vertFLT, vertArr + i * size, size);


		      /* If within range ... */
		      /* ------------------- */
		      if (vertFLT >= range[0] && vertFLT <= range[1])
                        {
			  /* Set found flag */
			  /* -------------- */
			  found = 1;


			  /* Setup swath region entry */
			  /* ------------------------ */
			  if (regionID == FAIL)
                            {
			      HE5_SETSWTHREG;
                            }


			  /* Fill-in vertical region entries */
			  /* ------------------------------- */
			  HE5_FILLVERTREG;

			  break;
                        }
                    }


		  /* If found read from "bottom" of data field */
		  /* ----------------------------------------- */
		  if (found == 1)
                    {
		      for (i = dims[0] - 1; i >= 0; i--)
                        {
			  /* Get single element of vertical field */
			  /* ------------------------------------ */
			  memmove(&vertFLT, vertArr + i * size, size);

			  /* If within range ... */
			  /* ------------------- */
			  if (vertFLT >= range[0] && vertFLT <= range[1])
                            {
			      /* Set end of vertical region */
			      /* -------------------------- */
			      HE5_SWXRegion[regionID]->StopVertical[j] = i;
			      break;
                            }
                        }
                    }
		  else
                    {
		      /* No vertical entries within region */
		      /* --------------------------------- */
		      status = FAIL;
		      sprintf(errbuf, "No vertical field entries within region.\n");
		      H5Epush(__FILE__, "HE5_SWdefvrtregion", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf); 
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      if (nt != NULL) free(nt);
			
                    }
		  break;

                case 4:

		  for (i = 0; i < dims[0]; i++)
                    {
		      /* Get single element of vertical field */
		      /* ------------------------------------ */
		      memmove(&vertDBL, vertArr + i * size, size);


		      /* If within range ... */
		      /* ------------------- */
		      if (vertDBL >= range[0] && vertDBL <= range[1])
                        {
			  /* Set found flag */
			  /* -------------- */
			  found = 1;


			  /* Setup swath region entry */
			  /* ------------------------ */
			  if (regionID == FAIL)
                            {
			      HE5_SETSWTHREG;
                            }


			  /* Fill-in vertical region entries */
			  /* ------------------------------- */
			  HE5_FILLVERTREG;

			  break;
                        }
                    }


		  /* If found read from "bottom" of data field */
		  /* ----------------------------------------- */
		  if (found == 1)
                    {
		      for (i = dims[0] - 1; i >= 0; i--)
                        {
			  /* Get single element of vertical field */
			  /* ------------------------------------ */
			  memmove(&vertDBL, vertArr + i * size, size);

			  /* If within range ... */
			  /* ------------------- */
			  if (vertDBL >= range[0] && vertDBL <= range[1])
                            {
			      /* Set end of vertical region */
			      /* -------------------------- */
			      HE5_SWXRegion[regionID]->StopVertical[j] = i;
			      break;
                            }
                        }
                    }
		  else
                    {
		      /* No vertical entries within region */
		      /* --------------------------------- */
		      status = FAIL;
		      sprintf(errbuf, "No vertical field entries within region.\n");
		      H5Epush(__FILE__, "HE5_SWdefvrtregion", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf); 
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      if (nt != NULL) free(nt);
			
                    }
		  break;

                } /* End of switch */
	      if (vertArr != NULL) free(vertArr);
            }
        }
    }

  if(nt != (hid_t *)NULL) 
    free(nt);


 COMPLETION:
  
  if (status == FAIL)
    regionID = FAIL;

  HE5_UNLOCK;  
  return(regionID);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWsetfillvalue                                               |
|                                                                             |
|  DESCRIPTION: Sets fill value for the specified field.                      |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  fieldname      char*               field name                              |
|  fillval        void*               fill value                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  8/23/99  A.Muslimov    Checked for the status returned by                  |
|                         H5Pset_fill_value(). Changed the return status      |
|                         from intn to int   .                                |
|  11/9/99  A.Muslimov    Modified the calls to write fill value to the       |
|                         attribute which fixed a bug resulted in a wrong     |
|                         value returned by the SWgetfillvalue().             |
|  12/3/99  A.Muslimov    Fixed a bug resulted in not writing a fill value    |
|                         into the dataset.                                   |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|  Mar  04  S.Zhao        Modified for a character string dataset.            |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_SWsetfillvalue(hid_t swathID, char *fieldname, hid_t numbertype_in, void *fillval)
{
  herr_t          status       = FAIL;/* return status variable       */
  
  hid_t           fid          = FAIL;/* HDF-EOS file ID              */
  hid_t           gid          = FAIL;/* "HDFEOS" group ID            */
  
  long            idx          = FAIL;/* Swath index                  */
  
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */
  hid_t           numbertype;

  HE5_LOCK;
  CHECKPOINTER(fillval);

  /* Convert HDF-EOS5 datatype to HDF5 datatype */
  if (
      H5Tequal(numbertype_in, H5T_NATIVE_CHAR)   == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_SCHAR)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_UCHAR)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_SHORT)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_USHORT) == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_INT)    == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_UINT)   == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_LONG)   == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_ULONG)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_LLONG)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_ULLONG) == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_FLOAT)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_DOUBLE) == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_LDOUBLE)== SUCCEED ||
      H5Tequal(numbertype_in, H5T_C_S1) == SUCCEED)
    {
      numbertype = numbertype_in;
    }
  else
    {
      numbertype = HE5_EHconvdatatype((int) numbertype_in);
    }

  if(numbertype == FAIL)
    {
      sprintf(errbuf,"Cannot convert to HDF5 type data type ID for fillvalue.\n");
      H5Epush(__FILE__, "HE5_SWsetfillvalue", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }



  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWsetfillvalue", &fid, &gid, &idx);
  if(status == FAIL)
    {
      sprintf(errbuf,"Checking for valid swath ID failed.\n");
      H5Epush(__FILE__, "HE5_SWsetfillvalue", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Get current dataset creation property list */
  /* ------------------------------------------ */  
  if( HE5_SWXSwath[idx].plist == FAIL)
    {
      HE5_SWXSwath[idx].plist = H5Pcreate(H5P_DATASET_CREATE);
      if (HE5_SWXSwath[idx].plist == FAIL)
	{
	  sprintf(errbuf,"Cannot create the dataset property list.\n");
	  H5Epush(__FILE__, "HE5_SWsetfillvalue", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
    }
  
  /* Set fill value */
  /* -------------- */  
  if ((numbertype != HE5T_CHARSTRING) && (numbertype != H5T_NATIVE_CHAR) && (numbertype != H5T_C_S1))
    {
      status = H5Pset_fill_value(HE5_SWXSwath[idx].plist, numbertype, fillval);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot set fill value for \"%s\" field.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWsetfillvalue", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
    }

 
 COMPLETION: 
  HE5_UNLOCK;
  return (status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWgetfillvalue                                               |
|                                                                             |
|  DESCRIPTION: Retrieves fill value for a specified field.                   |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  fieldname      char*               field name                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  fillval        void*               fill value                              |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  8/23/99  A.Muslimov    Changed the return status from intn to int   .      |
|  11/9/99  A.Muslimov    Replaced a call to H5Pget_fill_value( plist, tid,   |
|                         fillval) by EHattr().                               |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Oct  00  A.Muslimov    Updated to allow getting of a fill value for a      |
|                         profile field. Replaced two calls by HE5_SWfldsrch. |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
| Aug 22,11 Abe Taaheri   Add code to return error if fillvalue attribute     |
|                         not found.                                          |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_SWgetfillvalue(hid_t swathID, char *fieldname, void *fillval)
{
  herr_t          status   = FAIL;/* routine return status variable   */

  hid_t           fid      = FAIL;/* HDF-EOS file ID                  */
  hid_t           gid      = FAIL;/* "HDFEOS" group ID                */
  hid_t           fieldID  = FAIL;/* field dataset ID                 */
  hid_t           tid      = FAIL;/* field dataset data type ID       */
  hid_t           plist    = FAIL;/* field dataset property list ID   */
 
  long            idx      = FAIL;/* Swath index                      */
  
  hsize_t         count[1] = { 1 };/* number of attribute elements    */
    
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */
  long            strbufsize;
  char           *attrnames = NULL;
  long            nattr = 0;           /* number of attributes              */

  HE5_LOCK;

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWgetfillvalue", &fid, &gid, &idx);
  if(status == FAIL)
    {
      sprintf(errbuf,"Checking for valid swath ID failed.\n");
      H5Epush(__FILE__, "HE5_SWgetfillvalue", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }
  
  /* Check out the field group and get field ID */
  /* ------------------------------------------ */
  HE5_SWfldsrch(swathID,fieldname,&fieldID,NULL,NULL,NULL);
  if( fieldID == FAIL )
    {
      sprintf(errbuf, "Cannot get the field ID for the \"%s\" field.\n", fieldname);
      H5Epush(__FILE__, "HE5_SWgetfillvalue", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
   
  nattr = HE5_SWinqlocattrs(swathID, fieldname, NULL, &strbufsize);
  if ( nattr < 0 )
    {
      sprintf(errbuf, "Cannot retrieve fillvalue attribute. \n");
      H5Epush(__FILE__, "HE5_SWgetfillvalue", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  attrnames = (char*)malloc(sizeof(char)*(strbufsize+1));
  if (attrnames == NULL)
    {
      sprintf(errbuf, "Cannot allocate memory for attrnames.\n") ;
      H5Epush(__FILE__, "HE5_SWgetfillvalue", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  nattr  = HE5_SWinqlocattrs(swathID, fieldname, attrnames, &strbufsize);
  if ( nattr < 0 )
    {
      sprintf(errbuf, "Cannot retrieve fillvalue attribute. \n");
      H5Epush(__FILE__, "HE5_SWgetfillvalue", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      if(attrnames != NULL)
	{
	  free(attrnames);
	  attrnames = NULL;
	}
      return(FAIL);
    }

  if(strstr(attrnames, "_FillValue")!=NULL)
    {
      /* Get the property list ID */
      /* ------------------------ */
      plist = H5Dget_create_plist(fieldID);
      if ( plist == FAIL )
	{
	  sprintf(errbuf, "Cannot get the property list ID for the \"%s\" data field.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWgetfillvalue", __LINE__, H5E_PLIST, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  if(attrnames != NULL)
	    {
	      free(attrnames);
	      attrnames = NULL;
	    }
	  return(FAIL);
	}
      
      /* Get the datatype ID */ 
      /* ------------------- */
      tid   = H5Dget_type(fieldID);
      if ( tid == FAIL )
	{
	  sprintf(errbuf, "Cannot get the data type ID for the \"%s\" data field.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWgetfillvalue", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  if(attrnames != NULL)
	    {
	      free(attrnames);
	      attrnames = NULL;
	    }
	  return(FAIL);
	}
      
      /* Read out a fill value from the attribute */
      /* ---------------------------------------- */ 
      status = HE5_EHattr(fieldID, "_FillValue", tid, count, "r", fillval); 
      if (status == FAIL )
	{
	  sprintf(errbuf, "Cannot get fill value for the  \"%s\" field.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWgetfillvalue", __LINE__, H5E_ATTR, H5E_READERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  if(attrnames != NULL)
	    {
	      free(attrnames);
	      attrnames = NULL;
	    }
	  return(status);
	}
      
      /* Release data type ID */
      /* -------------------- */
      status = H5Tclose(tid);
      if (status == FAIL )
	{
	  sprintf(errbuf, "Cannot release data type ID for the \"%s\" dataset.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWgetfillvalue", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  if(attrnames != NULL)
	    {
	      free(attrnames);
	      attrnames = NULL;
	    }
	  return(status);
	}
      
      /* Release property list ID */
      /* ------------------------ */
      status = H5Pclose(plist);
      if (status == FAIL )
	{
	  sprintf(errbuf, "Cannot release property list ID for the \"%s\" dataset.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWgetfillvalue", __LINE__, H5E_PLIST, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  if(attrnames != NULL)
	    {
	      free(attrnames);
	      attrnames = NULL;
	    }
	  return(status);
	}
    }
  else
    {
      sprintf(errbuf, "Cannot retrieve fillvalue attribute. \n");
      H5Epush(__FILE__, "HE5_SWgetfillvalue", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      if(attrnames != NULL)
	{
	  free(attrnames);
	  attrnames = NULL;
	}
      return(FAIL);
    }

 COMPLETION:
  HE5_UNLOCK;

  if(attrnames != NULL)
    {
      free(attrnames);
      attrnames = NULL;
    }
  return (status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWregioninfo                                                 |
|                                                                             |
|  DESCRIPTION: Returns size of region in bytes                               |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  regionID       hid_t               Region ID                               |
|  fieldname      char                Fieldname                               |
|                                                                             |
|  OUTPUTS:                                                                   |
|  ntype          hid_t               field number types                      |
|  rank           int                 field rank                              |
|  dims           hsize_t             dimensions of field region              |
|  size           size_t              size in bytes of field region           |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer    Description                                        |
|  ========  ============  =================================================  |
|  08/20/99  A. Muslimov   Initialized return statuses to -1.                 |
|  10/18/99  A.Muslimov    Replaced memcpy() by memmove() to avoid a problem  |
|                            when arguments 1 and 2 overlap in memory.        |
|  04/19/00  A.Muslimov    Changed type of 'slen' from long to size_t.        |
|  05/10/00  A.Muslimov    Replaced 'H5T_class_t' type by 'int' data type.    |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Apr  01  A.Muslimov    Initialized size to 0, but "Unlim" returns -1!,     |
|                          not 0.                                             |
|  Jan 03   S.Zhao        Changed the type of 'ntype' from an H5T_class_t to  |
|                         an hid_t.                                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWregioninfo(hid_t swathID, hid_t regionID, char *fieldname, hid_t *ntype, int *rank, hsize_t dims[], size_t *size)
{
  herr_t          status   = FAIL;/* routine return status variable                 */
  herr_t          statMap  = FAIL;/* Status from SWmapinfo                          */

  int             i, j, k;		  /* Loop indices                                   */
  int             dum      = FAIL;/* Dummy (rank) variable */

  hid_t           dum2[1]  ={FAIL};/* Dummy (number types) variable                 */

  unsigned char   found    =  0;  /* Found flag                                     */

  hid_t           fid      = FAIL;/* HDF-EOS file ID                                */
  hid_t           gid      = FAIL;/* "HDFEOS" group ID                              */
  hid_t           fieldID  = FAIL;/* fieldname Dataset ID                           */

  long            idx      = FAIL;/* Swath index                                    */
  long            index    = FAIL;/* Geo Dim Index                                  */
  long            nDim     =  0;  /* Number of dimensions                           */
  long            incr     =  0;  /* Mapping increment                              */
  long            offset   = FAIL;/* Mapping offset                                 */
  long            *idxmap  = (long *)NULL;/* Pointer to index mapping array         */
  long            nXtrk       =  0;            /* Number of cross tracks            */

  hsize_t         idxMapElem  =  0;            /* Number of index map elements      */
  hsize_t         dumsize     =  0;            /* Dummy size variable               */
  hsize_t         dumdims[HE5_DTSETRANKMAX];   /* Dimensions from SWfieldinfo       */

  size_t          slen[HE5_DTSETRANKMAX];      /* String length array               */

  char            dimlist[HE5_HDFE_DIMBUFSIZE];/* Dimension list                    */
  char            geodim[HE5_HDFE_DIMBUFSIZE]; /* Geolocation field dimension list  */
  char            tgeodim[HE5_HDFE_DIMBUFSIZE];/* Time Geolocation field dim. list  */
  char            utlbuf[HE5_HDFE_DIMBUFSIZE]; /* Utility buffer                    */
  char            *ptr[HE5_DTSETRANKMAX];      /* String pointer array              */
  char            *errMesg = "Vertical Dimension Not Found: \"%s\".\n";
  char            errbuf[HE5_HDFE_ERRBUFSIZE]; /* Error buffer                      */

  CHECKPOINTER(fieldname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWregioninfo", &fid, &gid, &idx);

  /* Check for valid region ID */
  /* ------------------------- */
  if (status == SUCCEED)
    {
      if (regionID < 0 || regionID >= HE5_NSWATHREGN)
        {
	  status = FAIL;
	  sprintf(errbuf, "Invalid Region id: %d.\n", regionID);
	  H5Epush(__FILE__, "HE5_SWregioninfo", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
        }
    }

  /* Check for active region ID */
  /* -------------------------- */
  if (status == SUCCEED)
    {
      if (HE5_SWXRegion[regionID] == 0)
        {
	  status = FAIL;
	  sprintf(errbuf,"Inactive Region ID: %d.\n", regionID);
	  H5Epush(__FILE__, "HE5_SWregioninfo", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
        }
    }


  /* Check for valid fieldname */
  /* ------------------------- */
  if (status == SUCCEED)
    {
      /* Get data field info */
      /* ------------------- */
      strcpy(dimlist,"");
      status = HE5_SWfieldinfo(swathID, fieldname, rank, dims, ntype, dimlist, NULL);
      if (status != SUCCEED)
        {
	  status = FAIL;
	  sprintf(errbuf,"Field \"%s\" Not Found.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWregioninfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
        }
    }


  /* No problems so proceed ... */
  /* -------------------------- */
  if (status == SUCCEED)
    {
      /* If non-vertical subset regions defined ... */
      /* ------------------------------------------ */
      if (HE5_SWXRegion[regionID]->nRegions > 0)
        {
	  /* Initialize dumdims[] array */
	  /* -------------------------- */
	  for ( i = 0; i < HE5_DTSETRANKMAX; i++)
	    dumdims[ i ] = 0;

	  /* Get geolocation dimension name */
	  /* ------------------------------ */
	  strcpy(geodim,"");

	  status = HE5_SWfieldinfo(HE5_SWXRegion[regionID]->swathID, "Longitude", &dum, dumdims, dum2, geodim,NULL);

	  /* If Time field being used, check for dimensions */
	  /* ---------------------------------------------- */
	  if (HE5_timeflag == 1)
            {
	      /* code change to fix time subset bug for Landsat7 */
	      strcpy(tgeodim,"");
	      status = HE5_SWfieldinfo(HE5_SWXRegion[regionID]->swathID, "Time", &dum, dumdims, dum2, tgeodim,NULL);

	      if (strcmp(geodim, tgeodim) != 0)
		{
                  strcpy(geodim, tgeodim);
		}
            }
		
	  HE5_timeflag = 0;

	  /* Initialize slen[] array */
	  /* ----------------------- */
	  for ( i = 0; i < HE5_DTSETRANKMAX; i++)
	    slen[ i ] = 0;

	  /* Get "Track" (first) Dimension from geo dimlist */
	  /* ---------------------------------------------- */
	  nDim = HE5_EHparsestr(geodim, ',', ptr, slen);
	  geodim[slen[0]] = 0;


	  /* Parse Data Field Dimlist & find mapping */
	  /* --------------------------------------- */
	  nDim = HE5_EHparsestr(dimlist, ',', ptr, slen);

	  /* Loop through all dimensions and search for mapping */
	  /* -------------------------------------------------- */
	  strcpy(utlbuf,"");
	  for (i = 0; i < nDim; i++)
            {
	      memmove(utlbuf, ptr[i], slen[i]);
	      utlbuf[slen[i]] = 0;
	      offset = HE5_EHint2long(dum);
	      if ( offset == FAIL )
		{
		  sprintf(errbuf, "Cannot convert data type. \n");
		  H5Epush(__FILE__, "HE5_SWregioninfo", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(FAIL);
		}

	      statMap = HE5_SWmapinfo(swathID, geodim, utlbuf, &offset, &incr);

	      /* Mapping found */
	      /* ------------- */
	      if (statMap == SUCCEED)
                {
		  found = 1;
		  index = HE5_EHint2long(i);
		  if ( index == FAIL )
		    {
		      sprintf(errbuf, "Cannot convert data type. \n");
		      H5Epush(__FILE__, "HE5_SWregioninfo", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
		      return(FAIL);
		    }
		  break;
                }
            }


	  /* If mapping not found check for geodim within dimlist */
	  /* ---------------------------------------------------- */
	  if (found == 0)
            {
	      index = HE5_EHstrwithin(geodim, dimlist, ',');

	      /* Geo dimension found within subset field dimlist */
	      /* ----------------------------------------------- */
	      if (index != FAIL)
                {
		  found = 1;
		  incr  = 1;
                }
            }



	  /* If mapping not found check for indexed mapping */
	  /* ---------------------------------------------- */
	  if (found == 0)
            {
	      /* Get size of geo dim & allocate space of index mapping */
	      /* ----------------------------------------------------- */
	      dumsize = HE5_SWdiminfo(swathID, geodim);
	      if(dumsize == 0)
                {
		  H5Epush(__FILE__, "HE5_SWregioninfo", __LINE__, H5E_FUNC, H5E_CANTINIT, "Cannot get the dimension size. \n");
		  HE5_EHprint("Error: Cannot get the dimension size, occured", __FILE__, __LINE__);
		  return(FAIL);
                }

	      idxmap = (long *) calloc(dumsize, sizeof(long));
	      if(idxmap == NULL)
                {
		  H5Epush(__FILE__, "HE5_SWregioninfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory");
		  HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
		  return(FAIL);
                }

	      /* Loop through all dimensions and search for mapping */
	      /* -------------------------------------------------- */
	      strcpy(utlbuf,"");
	      for (i = 0; i < nDim; i++)
                {
		  memmove(utlbuf, ptr[i], slen[i]);
		  utlbuf[slen[i]] = 0;

		  idxMapElem = HE5_SWidxmapinfo(swathID, geodim, utlbuf, idxmap);

		  /* Mapping found */
		  /* ------------- */
		  if (idxMapElem > 0)
                    {
		      found = 1;
		      index = i;
		      break;
                    }
                }
            }


	  /* Regular Mapping Found */
	  /* --------------------- */
	  if (found == 1 && idxMapElem == 0)
            {
	      dims[index] = 0;

	      /* Loop through all regions */
	      /* ------------------------ */
	      for (k = 0; k < HE5_SWXRegion[regionID]->nRegions; k++)
                {
		  /* Get number of cross tracks in particular region */
		  /* ----------------------------------------------- */
		  nXtrk = HE5_SWXRegion[regionID]->StopRegion[k] - HE5_SWXRegion[regionID]->StartRegion[k] + 1;

		  /* If increment is positive (geodim <= datadim) ... */
		  /* ------------------------------------------------ */
		  if (incr > 0)
                    {
		      dims[index] += nXtrk * incr;
                    }
		  else
                    {
		      /* Negative increment (geodim > datadim) */
		      /* ------------------------------------- */
		      dims[index] += nXtrk / (-incr);

		      /*
		       * If Xtrk not exactly divisible by incr, round dims
		       * to next highest integer
		       */
		      if (nXtrk % (-incr) != 0)
                        {
			  dims[index]++;
                        }
                    }
                }
            }
	  else if (found == 1 && idxMapElem > 0)
            {

	      /* Indexed Mapping */
	      /* --------------- */

	      dims[index] = 0;
	      /* Loop through all regions */
	      /* ------------------------ */
	      for (k = 0; k < HE5_SWXRegion[regionID]->nRegions; k++)
                {
		  /* Get number of cross tracks in particular region */
		  /* ----------------------------------------------- */
		  nXtrk = idxmap[HE5_SWXRegion[regionID]->StopRegion[k]] - idxmap[HE5_SWXRegion[regionID]->StartRegion[k]] + 1;

		  dims[index] += nXtrk;
                }
            }
	  else
            {
	      /* Mapping not found */
	      /* ----------------- */
	      status = FAIL;
	      sprintf( errbuf, "Mapping Not Defined for \"%s\" Dimension.\n", geodim);
	      H5Epush(__FILE__, "HE5_SWregioninfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
            }
        }

      /* Vertical Subset */
      /* --------------- */
      if (status == SUCCEED || status == FAIL)
        {
	  for (j = 0; j < HE5_DTSETRANKMAX; j++)
            {
	      /* If active vertical subset ... */
	      /* ----------------------------- */
	      if (HE5_SWXRegion[regionID]->StartVertical[j] != FAIL)
                {

		  /* Find vertical dimension within dimlist */
		  /* -------------------------------------- */
		  index = HE5_EHstrwithin(HE5_SWXRegion[regionID]->DimNamePtr[j], dimlist, ',');

		  /* If dimension found ... */
		  /* ---------------------- */
		  if (index != FAIL)
                    {
		      /* Compute dimension size */
		      /* ---------------------- */
		      dims[index] = HE5_SWXRegion[regionID]->StopVertical[j] - HE5_SWXRegion[regionID]->StartVertical[j] + 1;
                    }
		  else
                    {
		      /* Vertical dimension not found */
		      /* ---------------------------- */
		      status = FAIL;
		      *size  = 0;
		      sprintf(errbuf, errMesg, HE5_SWXRegion[regionID]->DimNamePtr[j]);
		      H5Epush(__FILE__, "HE5_SWregioninfo", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
		      HE5_EHprint(errbuf, __FILE__, __LINE__);
                    }
                }
            }



	  /* Compute size of region data buffer */
	  /* ---------------------------------- */
	  if (status == SUCCEED)
            {
	      /* Compute number of total elements */
	      /* -------------------------------- */
	      *size = dims[0];

	      for (j = 1; j < *rank; j++)
		*size *= dims[j];


	      /* Multiply by size in bytes of numbertype */
	      /* --------------------------------------- */
	      *size *= HE5_SWfieldsizeID(swathID,fieldname, &fieldID);
            }
        }
    }



  /* Free index mappings if applicable */
  /* --------------------------------- */
  if (idxmap != NULL) free(idxmap);

 COMPLETION:
  return(status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWperiodinfo                                                 |
|                                                                             |
|  DESCRIPTION: Returns size in bytes of region                               |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  periodID       hid_t               Period ID                               |
|  fieldname      char                Fieldname                               |
|                                                                             |
|  OUTPUTS:                                                                   |
|  ntype          hid_t               field number types                      |
|  rank           int                 field rank                              |
|  dims           hsize_t             dimensions of field region              |
|  size           size_t              size in bytes of field region           |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  8/23/99  A.Muslimov    Changed the return status from intn to int   .      |
|  05/10/00 A.Muslimov    Replaced 'H5T_class_t' type by 'int' data type.     |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Jan 03   S.Zhao        Changed the type of 'ntype' from an H5T_class_t to  |
|                         an hid_t.                                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWperiodinfo(hid_t swathID, hid_t periodID, char *fieldname, hid_t *ntype, int *rank, hsize_t dims[], size_t *size)
{
  herr_t   status = FAIL;/* routine return status variable */
  
  HE5_timeflag    = 1;
  
  CHECKPOINTER(fieldname);
  
  /* Call HE5_SWregioninfo */
  /* --------------------- */
  status = HE5_SWregioninfo(swathID, periodID, fieldname, ntype, rank, dims, size);
  
 COMPLETION:
  return (status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWclose                                                      |
|                                                                             |
|  DESCRIPTION: Closes HDF-EOS file                                           |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  fid            hid_t               File ID                                 |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWclose(hid_t fid)
{
  herr_t   status = FAIL;/* routine return status variable */

  /* Call HE5_EHclose to perform file close */
  /* -------------------------------------- */
  status = HE5_EHclose(fid);
  
  return (status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWupdatescene                                                |
|                                                                             |
|  DESCRIPTION: Updates the StartRegion and StopRegion values                 |
|               for a specified region. This function is for Landsat.         |
|               The start and stop values must be set to the beginning        |
|               and the end of a scene, fixed scene subsetting.               |
|                                                                             |
|                                                                             |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  regionID       hid_t               Region ID                               |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Nov 98   Xinmin Hua    Original developing                                 |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|  Jan  05  S. Zhao       Modified to exclude regions that have the same      |
|                         start and stop.                                     |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWupdatescene(hid_t swathID, hid_t regionID)
{
  herr_t          status  = FAIL;/* routine return status variable  */

  hid_t           fid     = FAIL;/* HDF-EOS file ID                 */
  hid_t           gid     = FAIL;/* "HDFEOS" group ID               */
     
  long            k;		 /* Loop index                      */
  long            idx     = FAIL;/* Swath index                     */
  long            startReg= 0;   /* Indexed start region            */
  long            stopReg = 0;   /* Indexed stop region             */

  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */
  long            index[HE5_MAXNREGIONS];/* to store indicies when stop and                                                                                 start are different */ 
  long            ind;           /* index                           */
  long            tempnRegions;  /* temp number of regions          */


  HE5_LOCK;
  
  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWupdatescene", &fid, &gid, &idx);

  /* Check for valid region ID */
  /* ------------------------- */
  if (status == SUCCEED)
    {
      if (regionID < 0 || regionID >= HE5_NSWATHREGN)
        {
	  status = FAIL;
	  sprintf(errbuf, "Invalid Region ID: %d.\n", regionID);
	  H5Epush(__FILE__, "HE5_SWupdatescene", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf); 
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
        }
    }

  /* Check for active region ID */
  /* -------------------------- */
  if (status == SUCCEED)
    {
      if (HE5_SWXRegion[regionID] == 0)
        {
	  status = FAIL;
	  sprintf(errbuf, "Inactive Region ID: %d.\n", regionID);
	  H5Epush(__FILE__, "HE5_SWupdatescene", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
        }
    }

  if (status == SUCCEED)
    {
      tempnRegions = HE5_SWXRegion[regionID]->nRegions;
      ind =0;

      for (k = 0; k < HE5_SWXRegion[regionID]->nRegions; k++)
	{
	  startReg = HE5_SWXRegion[regionID]->StartRegion[k];
	  stopReg = HE5_SWXRegion[regionID]->StopRegion[k];
	  if(startReg == stopReg)
	    {
	      /* reduce number of regions by 1, if tempnRegions is 0 issue
		 error and break from loop*/
	      tempnRegions -= 1;

	      if(tempnRegions == 0)
		{
		  /* first free allocated memory for HE5_SWXRegion[regionID]
		     in the function HE5_SWdefboxregion and make regionID
		     inactive */
		  free(HE5_SWXRegion[regionID]);
		  HE5_SWXRegion[regionID] = 0;
		  status = FAIL;
		  sprintf(errbuf, "Inactive Region ID: %d.\n", regionID);
		  H5Epush(__FILE__, "HE5_SWupdatescene", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  break;
		}
	    }
	  else
	    {
	      /* store index number of regions that have different start and stop */
	      index[ind] = k;
	      ind += 1;
	    }
	}
          
      if (status != SUCCEED)
	{
	  return (status);
	}
      else
	{
	  HE5_SWXRegion[regionID]->nRegions = tempnRegions;
	}

      /* keep starts and stops that are different in the structure  */
      for (k = 0; k < HE5_SWXRegion[regionID]->nRegions; k++)
	{
	  HE5_SWXRegion[regionID]->StartRegion[k] = 
	    HE5_SWXRegion[regionID]->StartRegion[index[k]];
	  HE5_SWXRegion[regionID]->StopRegion[k] =
	    HE5_SWXRegion[regionID]->StopRegion[index[k]];
	}
    }

  if (status == SUCCEED)
    {
      for (k = 0; k < HE5_SWXRegion[regionID]->nRegions; k++)
	{
	  startReg = HE5_SWXRegion[regionID]->StartRegion[k];
	  stopReg  = HE5_SWXRegion[regionID]->StopRegion[k];

	  if(startReg % 2 == 1) {
	    HE5_SWXRegion[regionID]->StartRegion[k] = ++startReg;
	  }
	  if(stopReg % 2 == 0) {
	    HE5_SWXRegion[regionID]->StopRegion[k] = --stopReg;
	  }
	}
    }

 COMPLETION:
  HE5_UNLOCK;
  return( status );
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWupdateidxmap                                               |
|                                                                             |
|  DESCRIPTION: Updates the map index for a specified region.                 |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nout           long                return Number of elements in output     |
|                                     index array if SUCCEED, (-1) FAIL       |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  regionID       hid_t               Region ID                               |
|  indexin        long                array of index values                   |
|                                                                             |
|  OUTPUTS:                                                                   |
|  indexout       long                array of index values                   |
|  indicies       long                array of start and stop in region       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 97   Abe Taaheri   Original Programmer                                 |
|  AUG 97   Abe Taaheri   Add support for index mapping                       |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWupdateidxmap(hid_t swathID, hid_t regionID, long indexin[], long indexout[], long indicies[])
{
  long        nout     = FAIL;/* # of elements in output array (return)  */
  long        i, k ;		  /* Loop indices                            */
  long        idx      = FAIL;/* Swath index                             */
  long        startReg =  0;  /* Indexed start region                    */
  long        stopReg  =  0;  /* Indexed stop region                     */

  herr_t      status   = FAIL;/* routine return status variable          */

  hid_t       fid      = FAIL;/* HDF-EOS file ID                         */
  hid_t       gid      = FAIL;/* "HDFEOS" group ID                       */

  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Error buffer                */

  HE5_LOCK;
  CHECKPOINTER(indexin);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWupdateidxmap", &fid, &gid, &idx);

  /* Check for valid region ID */
  /* ------------------------- */
  if (status == SUCCEED)
    {
      if (regionID < 0 || regionID >= HE5_NSWATHREGN)
        {
	  status = FAIL;
	  sprintf(errbuf,"Invalid Region id: %d.\n", regionID);
	  H5Epush(__FILE__, "HE5_SWupdateidxmap", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf); 
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
        }
    }

  /* Check for active region ID */
  /* -------------------------- */
  if (status == SUCCEED)
    {
      if (HE5_SWXRegion[regionID] == 0)
        {
	  status = FAIL;
	  sprintf(errbuf, "Inactive Region ID: %d.\n", regionID);
	  H5Epush(__FILE__, "HE5_SWupdateidxmap", __LINE__, H5E_FILE, H5E_BADRANGE, errbuf );
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
        }
    }

  if (status == SUCCEED)
    {
      /* Loop through all regions */
      /* ------------------------ */
      for (k = 0; k < HE5_SWXRegion[regionID]->nRegions; k++)
        {

	  /* fix overlap index mapping problem for Landsat7 */
	  startReg = HE5_SWXRegion[regionID]->StartRegion[ k ];
	  stopReg  = HE5_SWXRegion[regionID]->StopRegion[ k ];

	  /* If start of region is odd then increment */
	  /* ---------------------------------------- */
	  if (startReg % 2 == 1)
            {
	      startReg++;
            }

	  /* If end of region is even then decrement */
	  /* --------------------------------------- */
	  if (stopReg % 2 == 0)
            {
	      stopReg--;
            }
        }

      indicies[0] = startReg;
      indicies[1] = stopReg;

      if (indexout != NULL)
        {
	  /* get new index values */
	  for(i = startReg; i <= stopReg  ; i++)
            {
	      indexout[i - startReg] = indexin[ i ] - indexin[startReg];
            }
        }

      nout = (stopReg - startReg) + 1;
    }

 COMPLETION:
  HE5_UNLOCK;
  
  if(status == FAIL)
    return(FAIL);
  else
    return(nout);
}




/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWgeomapinfo                                                 |
|                                                                             |
|  DESCRIPTION: Returns mapping information for dimension                     |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              2 for indexed mapping, 1 for regular    |
|                                     mapping, 0 if the dimension is not      |
|                                     and (-1) FAIL                           |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  geodim         char                geolocation dimension name              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  NONE                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  7/29/99  A.Muslimov    In the call to EHmetagroup() replace gid by fid.    |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWgeomapinfo(hid_t swathID, char *geodim)
{
  herr_t         status    = FAIL;         /* Return status variable    */

  hid_t          fid       = FAIL;         /* HDF-EOS file ID           */
  hid_t          gid       = FAIL;         /* "HDFEOS" group ID         */

  long           idx       = FAIL;         /* Swath index               */

  char           *metabufr = (char *)NULL; /* Pointer to SM             */
  char           *metabufi = (char *)NULL; /* Pointer to SM             */
  char           *metaptrsr[2]={NULL,NULL};/* Pntrs to begin, end of SM */
  char           *metaptrsi[2]={NULL,NULL};/* Pntrs to begin, end of SM */
  char           utlstrr[HE5_HDFE_DIMBUFSIZE]; /* Utility string        */
  char           utlstri[HE5_HDFE_DIMBUFSIZE]; /* Utility string        */
  char           errbuf[HE5_HDFE_ERRBUFSIZE];  /* Error message buffer  */
 

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWgeomapinfo", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Get pointers to "DimensionMap" section within SM */
      metabufr = (char *)HE5_EHmetagroup(fid, HE5_SWXSwath[idx].swname, "s", "DimensionMap", metaptrsr);
      if (metabufr == NULL)
	{
	  sprintf(errbuf, "Cannot get  pointer to metabufer. \n") ;
	  H5Epush(__FILE__, "HE5_SWgeomapinfo", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  
	  return(FAIL);
	}

      /* Search for mapping - GeoDim/DataDim (surrounded by quotes) */
      sprintf(utlstrr, "%s%s%s", "\t\t\t\tGeoDimension=\"", geodim, "\"\n\t\t\t\tDataDimension=");
      metaptrsr[0] = strstr(metaptrsr[0], utlstrr);

      /* Get pointers to "IndexDimensionMap" section within SM */
      metabufi = (char *)HE5_EHmetagroup(fid, HE5_SWXSwath[idx].swname, "s", "IndexDimensionMap", metaptrsi);
      if (metabufi == NULL)
	{
	  sprintf(errbuf, "Cannot allocate memory for metabufi.") ;
	  H5Epush(__FILE__, "HE5_SWgeomapinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(metabufr);

	  return(FAIL);
	}

      /* Search for mapping - GeoDim/DataDim (surrounded by quotes) */
      sprintf(utlstri, "%s%s%s", "\t\t\t\tGeoDimension=\"", geodim, "\"\n\t\t\t\tDataDimension=");
      metaptrsi[0] = strstr(metaptrsi[0], utlstri);

      /*
      ** If regular mapping found add 1 to status
      ** If indexed mapping found add 2
      */
      if (metaptrsr[0] < metaptrsr[1] && metaptrsr[0] != NULL)
        {
	  status = status + 1;
        }

      if (metaptrsi[0] < metaptrsi[1] && metaptrsi[0] != NULL)
        {
	  status = status + 2;
        }

      free(metabufr);
      free(metabufi);
    }

  return (status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWfieldsizeID                                                |
|                                                                             |
|  DESCRIPTION:  Returns the size (in bytes) of field-related data type,      |
|                otherwise returns 0.                                         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  size           size_t  none                                                |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  fieldname      char                fieldname                               |
|                                                                             |
|  OUTPUTS:                                                                   |
|  fieldID        hid_t               field-related dataset ID                |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  8/23/99  A.Muslimov    Checked for the statuses returned by H5Tclose().    |
|  2/08/00  A.Muslimov    Added more error checkings and desciption.          |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
static size_t 
HE5_SWfieldsizeID( hid_t swathID, char *fieldname, hid_t  *fieldID)
{
  size_t         size      =  0;             /* Size of field data type  */

  herr_t         status    = FAIL;           /* Return status variable   */

  int            i;				             /* Loop index               */
  int            found     =  0;             /* Flag                     */

  hid_t          fid       = FAIL;           /* HDF-EOS file ID          */
  hid_t          gid       = FAIL;           /* "HDFEOS" group ID        */
  hid_t          dtype     = FAIL;           /* datatype ID              */

  long           idx       = FAIL;           /* Swath index              */

  char           errbuf[HE5_HDFE_ERRBUFSIZE];/* Buffer for error message */

  CHECKPOINTER(fieldname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWfieldsizeID", &fid, &gid, &idx);

  /* Loop through all geo datasets in swath */
  /* -------------------------------------- */
  for (i = 0; i < HE5_SWXSwath[idx].nGFLD; i++)
    {
      if( strcmp(fieldname, HE5_SWXSwath[idx].gdataset[i].name) == 0 )
	{
	  /* Get dataset ID */
	  /* -------------- */
	  *fieldID = HE5_SWXSwath[idx].gdataset[i].ID;
			
	  dtype    = H5Dget_type( *fieldID);
	  if (dtype == FAIL)
	    {
	      sprintf(errbuf, "Cannot get the dataset data type. \n");
	      H5Epush(__FILE__, "HE5_SWfieldsizeID", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(0);
	    }
			
	  size     = H5Tget_size(dtype);
	  if (size == 0)
	    {
	      sprintf(errbuf, "Cannot get the data type size. \n");
	      H5Epush(__FILE__, "HE5_SWfieldsizeID", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(0);
	    }

	  status   = H5Tclose(dtype);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot release the data type ID. \n");
	      H5Epush(__FILE__, "HE5_SWfieldsizeID", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(0);
	    }
	  found = 1;
	  break;
	}
		
    }

  /* not found in geo field */
  /* ---------------------- */
  if(  found == 0 )
    {
      /* Loop through all data fields in swath */
      /* ------------------------------------- */
      for (i = 0; i < HE5_SWXSwath[idx].nDFLD; i++)
	{
	  if( strcmp(fieldname, HE5_SWXSwath[idx].ddataset[i].name) == 0 )
	    {
	      /* get dataset ID */
	      /* -------------- */
	      *fieldID = HE5_SWXSwath[idx].ddataset[i].ID;
				
	      dtype    = H5Dget_type(*fieldID);
	      if (dtype == FAIL)
		{
		  sprintf(errbuf, "Cannot get the dataset data type. \n");
		  H5Epush(__FILE__, "HE5_SWfieldsizeID", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(0);
		}

	      size     = H5Tget_size(dtype);
	      if (size == 0)
		{
		  sprintf(errbuf, "Cannot get the data type size. \n");
		  H5Epush(__FILE__, "HE5_SWfieldsizeID", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(0);
		}
				
	      status   = H5Tclose(dtype);
	      if (status == FAIL)
		{
		  sprintf(errbuf, "Cannot release the data type ID. \n");
		  H5Epush(__FILE__, "HE5_SWfieldsizeID", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  return(0);
		}               
	      found = 1;
	      break;
	    }
	}
    }
  if(  found == 0 )
    {
      sprintf(errbuf, "field \"%s\" is not in Swath. \n", fieldname);
      H5Epush(__FILE__, "HE5_SWfieldsizeID", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

 COMPLETION:
  return(size);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWwritegrpattr                                               |
|                                                                             |
|  DESCRIPTION: Writes/updates attribute associated with the "Data Fields"    |
|               group in a swath.                                             |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  attrname       char                attribute name                          |
|  numtype        hid_t               attribute dataset datatype ID           |
|  count[]        hsize_t             Number of attribute elements            |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Jan 00   A.Muslimov                                                        |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWwritegrpattr(hid_t swathID, const char *attrname, hid_t numtype, hsize_t  count[], void *datbuf)
{
  herr_t     status          = FAIL;     /* Return status variable */

  hid_t      fid             = FAIL;     /* HDF-EOS file ID        */
  hid_t      gid             = FAIL;     /* "HDFEOS" group ID      */
  hid_t      DataFieldsGrpID = FAIL;     /* "Data Fields" group ID */
    
  long       idx             = FAIL;     /* Swath index            */

  char       errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer   */
  hid_t      numbertype;

  HE5_LOCK;
  CHECKNAME(attrname);
  CHECKPOINTER(count);
  CHECKPOINTER(datbuf);

  /* if numtype is HE5 numbertype, rather than H5 numbertype, then convert
     it, otherwise use numtype itself
  */
  numbertype = HE5_EHconvdatatype(numtype);
  if(numbertype == FAIL)
    {
      numbertype = numtype;
    }

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWwritegrpattr", &fid, &gid, &idx);

  if (status == SUCCEED)
    {
      /* Get "Data Fields" group ID and call HE5_EHattr to perform I/O */
      /* ------------------------------------------------------------- */
      DataFieldsGrpID = H5Gopen(HE5_SWXSwath[idx].sw_id, "Data Fields");
      if(DataFieldsGrpID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"Data Fields\" group ID. \n");
	  H5Epush(__FILE__, "HE5_SWwritegrpattr", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	} 

      status = HE5_EHattr(DataFieldsGrpID, attrname, numbertype, count,"w", datbuf);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot write Attribute \"%s\"to the \"Data Fields\" group.\n", attrname);
	  H5Epush(__FILE__, "HE5_SWwritegrpattr", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}

      status = H5Gclose(DataFieldsGrpID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"Data Fields\" group ID. \n");
	  H5Epush(__FILE__, "HE5_SWwritegrpattr", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}	
    }

 COMPLETION:
  HE5_UNLOCK;
  return (status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWreadgrpattr                                                |
|                                                                             |
|  DESCRIPTION: Reads attribute from the "Data Fields" group in a swath.      |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  attrname       char                attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Jan 00   A.Muslimov                                                        |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWreadgrpattr(hid_t swathID, const char *attrname, void * datbuf)
{
  herr_t      status          = FAIL;     /* return status variable   */
  
  hid_t       fid             = FAIL;     /* HDF-EOS file ID          */
  hid_t       gid             = FAIL;     /* "HDFEOS" group ID        */
  hid_t       ntype           = FAIL;     /* Data type ID             */
  hid_t       DataFieldsGrpID = FAIL;     /* "Data Fields" group ID   */
  
  long        idx             = FAIL;     /* Swath index              */
  
  hsize_t     count[]         = { 0 };    /* # of attribute elements  */
  
  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer     */
  

  HE5_LOCK;
  CHECKPOINTER(attrname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWreadgrpattr", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Get "Data Fields"  group ID and call HE5_EHattr to perform I/O */
      /* -------------------------------------------------------------- */
      DataFieldsGrpID = H5Gopen(HE5_SWXSwath[idx].sw_id, "Data Fields");
      if(DataFieldsGrpID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"Data Fields\" group ID.\n");
	  H5Epush(__FILE__, "HE5_SWreadgrpattr", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
        }

      status = HE5_EHattr(DataFieldsGrpID,attrname,ntype,count,"r", datbuf);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot read Attribute \"%s\" from the \"Data Fields\" group.\n", attrname);
	  H5Epush(__FILE__, "HE5_SWreadgrpattr", __LINE__, H5E_ATTR, H5E_READERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
        }

      status = H5Gclose(DataFieldsGrpID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"Data Fields\" group ID.\n");
	  H5Epush(__FILE__,  "HE5_SWreadgrpattr", __LINE__,H5E_OHDR, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
	
    }

 COMPLETION:
  HE5_UNLOCK;
  return (status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWgrpattrinfo                                                |
|                                                                             |
|  DESCRIPTION: Retrieves information about attributes in "Data Fields" group.|
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  attrname       const char*         attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  ntype          hid_t               data type ID                            |
|  count          hsize_t             Number of attribute elements            |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Jan 00   A.Muslimov                                                        |
|  May 00   A.Muslimov    Replaced 'H5T_class_t' type by 'int' data type.     |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Feb 03   S.Zhao        Changed the type of 'ntype' from an H5T_class_t to  |
|                         an hid_t.                                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWgrpattrinfo(hid_t swathID, const char *attrname, hid_t *ntype, hsize_t *count)
{
  herr_t     status          = FAIL;     /* routine return status variable */

  hid_t      fid             = FAIL;     /* HDF-EOS file ID                */
  hid_t      gid             = FAIL;     /* "HDFEOS" group ID              */
  hid_t      DataFieldsGrpID = FAIL;     /* "Data Fields" group ID         */

  long       idx             = FAIL;     /* Swath index                    */

  char       errbuf[HE5_HDFE_ERRBUFSIZE];/*  Error message buffer          */

  CHECKPOINTER(attrname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWgrpattrinfo", &fid, &gid, &idx);	
  if (status == SUCCEED)
    {
      /* Get "Data Fields"  group ID and call HE5_EHattrinfo */
      /* --------------------------------------------------- */
      DataFieldsGrpID = H5Gopen(HE5_SWXSwath[idx].sw_id, "Data Fields");
      if(DataFieldsGrpID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"Data Fields\" group ID.\n");
	  H5Epush(__FILE__, "HE5_SWgrpattrinfo", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}

      status = HE5_EHattrinfo(DataFieldsGrpID,attrname,ntype,count);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot retrieve information about Attribute \"%s\" in the \"Data Fields\" group.\n", attrname);
	  H5Epush(__FILE__, "HE5_SWgrpattrinfo", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}

      status = H5Gclose(DataFieldsGrpID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"Data Fields\" group ID.\n");
	  H5Epush(__FILE__, "HE5_SWgrpattrinfo", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}	


    }
  
 COMPLETION:
  return (status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWgrpattrinfo2                                               |
|                                                                             |
|  DESCRIPTION: Retrieves information about attributes in "Data Fields" group.|
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  attrname       const char*         attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  ntype          hid_t               data type ID                            |
|  count          hsize_t             Number of attribute elements            |
|  size           hsize_t             buf size of attribute elements          |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Jan 00   A.Muslimov                                                        |
|  May 00   A.Muslimov    Replaced 'H5T_class_t' type by 'int' data type.     |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Feb 03   S.Zhao        Changed the type of 'ntype' from an H5T_class_t to  |
|                         an hid_t.                                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWgrpattrinfo2(hid_t swathID, const char *attrname, hid_t *ntype, hsize_t *count, hsize_t *size)
{
  herr_t     status          = FAIL;     /* routine return status variable */

  hid_t      fid             = FAIL;     /* HDF-EOS file ID                */
  hid_t      gid             = FAIL;     /* "HDFEOS" group ID              */
  hid_t      DataFieldsGrpID = FAIL;     /* "Data Fields" group ID         */

  long       idx             = FAIL;     /* Swath index                    */

  char       errbuf[HE5_HDFE_ERRBUFSIZE];/*  Error message buffer          */

  CHECKPOINTER(attrname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWgrpattrinfo2", &fid, &gid, &idx);	
  if (status == SUCCEED)
    {
      /* Get "Data Fields"  group ID and call HE5_EHattrinfo */
      /* --------------------------------------------------- */
      DataFieldsGrpID = H5Gopen(HE5_SWXSwath[idx].sw_id, "Data Fields");
      if(DataFieldsGrpID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"Data Fields\" group ID.\n");
	  H5Epush(__FILE__, "HE5_SWgrpattrinfo2", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}

      status = HE5_EHattrinfo2(DataFieldsGrpID,attrname,ntype,count,size);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot retrieve information about Attribute \"%s\" in the \"Data Fields\" group.\n", attrname);
	  H5Epush(__FILE__, "HE5_SWgrpattrinfo2", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}

      status = H5Gclose(DataFieldsGrpID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"Data Fields\" group ID.\n");
	  H5Epush(__FILE__, "HE5_SWgrpattrinfo2", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}	


    }
  
 COMPLETION:
  return (status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqgrpattrs                                                |
|                                                                             |
|  DESCRIPTION:  Retrieves the number of attributes and string length of      |
|                attribute list in "Data Fields" group                        |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nattr          long                Number of attributes in "Data Fields"   |
|                                       group.                                |
|                                                                             |
|  INPUTS:                                                                    |
|  swath ID       hid_t               swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  attrnames      char                Attribute names in "Data Fields" group  |
|                                     (Comma-separated list)                  |
|  strbufsize     long                Attributes name list string length      |
|                                                                             |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Jan 00   A.Muslimov                                                        |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWinqgrpattrs(hid_t swathID, char *attrnames, long *strbufsize)
{
  long            nattr   = FAIL;             /* Number of attributes (return)  */
  long            idx     = FAIL;             /* Swath index                    */

  herr_t          status  = FAIL;             /* Return status variable         */

  hid_t           fid     = FAIL;             /* HDF-EOS file ID                */
  hid_t           gid     = FAIL;             /* "SWATHS" group ID              */
    
  char            *grpname = (char *)NULL;    /* Group name string              */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer           */



  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWinqgrpattrs", &fid, &gid, &idx);
  if(status == SUCCEED )
    {
      grpname = (char *)calloc(HE5_HDFE_NAMBUFSIZE, sizeof(char) );
      if( grpname == NULL)
        {
          H5Epush(__FILE__, "HE5_SWinqgrpattrs", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Can not allocate memory");
          HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
          return(FAIL);
        }

      strcpy(grpname,"/HDFEOS/SWATHS/");
      strcat(grpname, HE5_SWXSwath[idx].swname);
      strcat(grpname,"/Data Fields");
	
      /* search group with grpname for the number of attributes */
      /* ------------------------------------------------------ */ 
      nattr = HE5_EHattrcat(fid,  grpname, attrnames, strbufsize);
      if ( nattr < 0 )
	{
	  sprintf(errbuf, "Cannot find the attributes. \n");
	  H5Epush(__FILE__, "HE5_SWinqgrpattrs", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	}

      if (grpname != NULL) free(grpname);
    }
  
  return (nattr);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWwritegeogrpattr                                            |
|                                                                             |
|  DESCRIPTION: Writes/updates attribute associated with the "Geolocation     |
|               Fields" group in a swath.                                     |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  attrname       char                attribute name                          |
|  numtype        hid_t               attribute dataset datatype ID           |
|  count[]        hsize_t             Number of attribute elements            |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04   S.Zhao        Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_SWwritegeogrpattr(hid_t swathID, const char *attrname, hid_t numtype, hsize_t  count[], void *datbuf)
{
  herr_t     status          = FAIL;     /* Return status variable        */
 
  hid_t      fid             = FAIL;     /* HDF-EOS file ID               */
  hid_t      gid             = FAIL;     /* "HDFEOS" group ID             */
  hid_t      GeoFieldsGrpID  = FAIL;     /* "Geolocation Fields" group ID */
 
  long       idx             = FAIL;     /* Swath index                   */
 
  char       errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer          */
  hid_t      numbertype;
 
  HE5_LOCK;
  CHECKNAME(attrname);
  CHECKPOINTER(count);
  CHECKPOINTER(datbuf);
 
  /* if numtype is HE5 numbertype, rather than H5 numbertype, then convert
     it, otherwise use numtype itself
  */
  numbertype = HE5_EHconvdatatype(numtype);
  if(numbertype == FAIL)
    {
      numbertype = numtype;
    }

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWwritegeogrpattr", &fid, &gid, &idx);
 
  if (status == SUCCEED)
    {
      /* Get "Geolocation Fields" group ID and call HE5_EHattr to perform I/O */
      /* -------------------------------------------------------------------- */
      GeoFieldsGrpID = H5Gopen(HE5_SWXSwath[idx].sw_id, "Geolocation Fields");
      if(GeoFieldsGrpID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"Geolocation Fields\" group ID. \n");
	  H5Epush(__FILE__, "HE5_SWwritegeogrpattr", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
 
      status = HE5_EHattr(GeoFieldsGrpID, attrname, numbertype, count,"w", datbuf);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot write attribute \"%s\"to the \"Geolocation Fields\" group.\n", attrname);
	  H5Epush(__FILE__, "HE5_SWwritegeogrpattr", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
 
      status = H5Gclose(GeoFieldsGrpID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"Geolocation Fields\" group ID. \n");
	  H5Epush(__FILE__, "HE5_SWwritegeogrpattr", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
    }
 
 COMPLETION:
  HE5_UNLOCK;
  return (status);
}
 
 
/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWreadgeogrpattr                                             |
|                                                                             |
|  DESCRIPTION: Reads attribute from the "Geolocation Fields" group           |
|               in a swath.                                                   |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  attrname       char                attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04   S.Zhao        Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_SWreadgeogrpattr(hid_t swathID, const char *attrname, void * datbuf)
{
  herr_t      status          = FAIL;     /* return status variable          */
 
  hid_t       fid             = FAIL;     /* HDF-EOS file ID                 */
  hid_t       gid             = FAIL;     /* "HDFEOS" group ID               */
  hid_t       ntype           = FAIL;     /* Data type ID                    */
  hid_t       GeoFieldsGrpID  = FAIL;     /* "Geolocation Fields" group ID   */
 
  long        idx             = FAIL;     /* Swath index                     */
 
  hsize_t     count[]         = { 0 };    /* # of attribute elements         */
 
  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer            */
 
 
  HE5_LOCK;
  CHECKPOINTER(attrname);
 
  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWreadgeogrpattr", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Get "Geolocation Fields"  group ID and call HE5_EHattr to perform I/O */
      /* --------------------------------------------------------------------- */
      GeoFieldsGrpID = H5Gopen(HE5_SWXSwath[idx].sw_id, "Geolocation Fields");
      if(GeoFieldsGrpID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"Geolocation Fields\" group ID.\n");
	  H5Epush(__FILE__, "HE5_SWreadgeogrpattr", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
        }
 
      status = HE5_EHattr(GeoFieldsGrpID,attrname,ntype,count,"r", datbuf);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot read attribute \"%s\" from the \"Geolocation Fields\" group.\n", attrname);
	  H5Epush(__FILE__, "HE5_SWreadgeogrpattr", __LINE__, H5E_ATTR, H5E_READERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
        }
 
      status = H5Gclose(GeoFieldsGrpID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"Geolocation Fields\" group ID.\n");
	  H5Epush(__FILE__, "HE5_SWreadgeogrpattr", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
 
    }
 
 COMPLETION:
  HE5_UNLOCK;
  return (status);
}
 
 
/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWgeogrpattrinfo                                             |
|                                                                             |
|  DESCRIPTION: Retrieves information about attributes in "Geolocation Fields"|
|               group.                                                        |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  attrname       const char*         attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  ntype          hid_t               data type ID                            |
|  count          hsize_t             Number of attribute elements            |
|                                                                             |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04    S.Zhao       Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_SWgeogrpattrinfo(hid_t swathID, const char *attrname, hid_t *ntype, hsize_t *count)
{
  herr_t     status          = FAIL;     /* routine return status variable */
 
  hid_t      fid             = FAIL;     /* HDF-EOS file ID                */
  hid_t      gid             = FAIL;     /* "HDFEOS" group ID              */
  hid_t      GeoFieldsGrpID  = FAIL;     /* "Geolocation Fields" group ID  */
 
  long       idx             = FAIL;     /* Swath index                    */
 
  char       errbuf[HE5_HDFE_ERRBUFSIZE];/*  Error message buffer          */
 
  CHECKPOINTER(attrname);
 
  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWgeogrpattrinfo", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Get "Geolocation Fields"  group ID and call HE5_EHattrinfo */
      /* ---------------------------------------------------------- */
      GeoFieldsGrpID = H5Gopen(HE5_SWXSwath[idx].sw_id, "Geolocation Fields");
      if(GeoFieldsGrpID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"Geolocation Fields\" group ID.\n");
	  H5Epush(__FILE__, "HE5_SWgeogrpattrinfo", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
 
      status = HE5_EHattrinfo(GeoFieldsGrpID,attrname,ntype,count);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot retrieve information about attribute \"%s\" in the \"Geolocation Fields\" group.\n",attrname);
	  H5Epush(__FILE__, "HE5_SWgeogrpattrinfo", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
 
      status = H5Gclose(GeoFieldsGrpID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"Geolocation Fields\" group ID.\n");
	  H5Epush(__FILE__, "HE5_SWgeogrpattrinfo", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
 
    }
 
 COMPLETION:
  return (status);
}
 
  
/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWgeogrpattrinfo2                                            |
|                                                                             |
|  DESCRIPTION: Retrieves information about attributes in "Geolocation Fields"|
|               group.                                                        |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  attrname       const char*         attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  ntype          hid_t               data type ID                            |
|  count          hsize_t             Number of attribute elements            |
|  size           hsize_t             buf size of attribute elements          |
|                                                                             |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04    S.Zhao       Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_SWgeogrpattrinfo2(hid_t swathID, const char *attrname, hid_t *ntype, hsize_t *count, hsize_t *size)
{
  herr_t     status          = FAIL;     /* routine return status variable */
 
  hid_t      fid             = FAIL;     /* HDF-EOS file ID                */
  hid_t      gid             = FAIL;     /* "HDFEOS" group ID              */
  hid_t      GeoFieldsGrpID  = FAIL;     /* "Geolocation Fields" group ID  */
 
  long       idx             = FAIL;     /* Swath index                    */
 
  char       errbuf[HE5_HDFE_ERRBUFSIZE];/*  Error message buffer          */
 
  CHECKPOINTER(attrname);
 
  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWgeogrpattrinfo", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Get "Geolocation Fields"  group ID and call HE5_EHattrinfo */
      /* ---------------------------------------------------------- */
      GeoFieldsGrpID = H5Gopen(HE5_SWXSwath[idx].sw_id, "Geolocation Fields");
      if(GeoFieldsGrpID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"Geolocation Fields\" group ID.\n");
	  H5Epush(__FILE__, "HE5_SWgeogrpattrinfo2", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
 
      status = HE5_EHattrinfo2(GeoFieldsGrpID,attrname,ntype,count, size);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot retrieve information about attribute \"%s\" in the \"Geolocation Fields\" group.\n",attrname);
	  H5Epush(__FILE__, "HE5_SWgeogrpattrinfo2", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
 
      status = H5Gclose(GeoFieldsGrpID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"Geolocation Fields\" group ID.\n");
	  H5Epush(__FILE__, "HE5_SWgeogrpattrinfo2", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
 
    }
 
 COMPLETION:
  return (status);
}
 
 
/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqgeogrpattrs                                             |
|                                                                             |
|  DESCRIPTION:  Retrieves the number of attributes and string length of      |
|                attribute list in "Geolocation Fields" group.                |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nattr          long                Number of attributes in "Geolocation    |
|                                     Fields" group.                          |
|                                                                             |
|  INPUTS:                                                                    |
|  swath ID       hid_t               swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  attrnames      char                Attribute names in "Geolocation Fields" |
|                                     group (Comma-separated list)            |
|  strbufsize     long                Attributes name list string length      |
|                                                                             |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04    S.Zhao       Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long
HE5_SWinqgeogrpattrs(hid_t swathID, char *attrnames, long *strbufsize)
{
  long            nattr   = FAIL;             /* Number of attributes (return)  */
  long            idx     = FAIL;             /* Swath index                    */
 
  herr_t          status  = FAIL;             /* Return status variable         */
 
  hid_t           fid     = FAIL;             /* HDF-EOS file ID                */
  hid_t           gid     = FAIL;             /* "SWATHS" group ID              */
 
  char            *grpname = (char *)NULL;    /* Group name string              */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer           */
 
 
 
  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWinqgeogrpattrs", &fid, &gid, &idx);
  if(status == SUCCEED )
    {
      grpname = (char *)calloc(HE5_HDFE_NAMBUFSIZE, sizeof(char) );
      if( grpname == NULL)
        {
          H5Epush(__FILE__, "HE5_SWinqgeogrpattrs", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Can not allocate memory");
          HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
          return(FAIL);
        }
 
      strcpy(grpname,"/HDFEOS/SWATHS/");
      strcat(grpname, HE5_SWXSwath[idx].swname);
      strcat(grpname,"/Geolocation Fields");
 
      /* search group with grpname for the number of attributes */
      /* ------------------------------------------------------ */
      nattr = HE5_EHattrcat(fid,  grpname, attrnames, strbufsize);
      if ( nattr < 0 )
	{
	  sprintf(errbuf, "Cannot find the attributes. \n");
	  H5Epush(__FILE__, "HE5_SWinqgeogrpattrs", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	}
 
      if (grpname != NULL) free(grpname);
    }
 
  return (nattr);
}
 

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWwritelocattr                                               |
|                                                                             |
|  DESCRIPTION: Writes/updates attribute associated with a specified field in |
|                        a swath.                                             |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  fieldname      char                field name                              |
|  attrname       char                attribute name                          |
|  numtype        hid_t               attribute dataset datatype ID           |
|  count[]        hsize_t             Number of attribute elements            |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Jan 00   A.Muslimov                                                        |
|  Jul 00   A.Muslimov    Unmasked hdf5 data types.                           |
|  Nov 00   A.Muslimov    Added writing local attribute to the field of       |
|                          "Geolocation Fields" group.                        |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|  Jan 04   S.Zhao        Added writing local attribute to the field of       |
|                         "Profile Fields" group.                             |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWwritelocattr(hid_t swathID, const char *fieldname, const char *attrname, hid_t numtype, hsize_t  count[], void *datbuf)
{
  herr_t     status          =  FAIL;    /* Return status variable */

  int        fldgroup        =  FAIL;    /* Field group flag       */
  
  hid_t      fid             =  FAIL;    /* HDF-EOS file ID        */
  hid_t      gid             =  FAIL;    /* "HDFEOS" group ID      */
  hid_t      FieldGrpID      =  FAIL;    /* Field group ID         */
  hid_t      fieldID         =  FAIL;    /* Field dataset ID       */
  
  long       idx             =  FAIL;    /* Swath index            */
  
  char       *grpname = (char *)NULL;    /* Group name buffer      */    
  char       errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer   */
  hid_t      numbertype;

  HE5_LOCK;
  CHECKPOINTER(fieldname);
  CHECKNAME(attrname);
  CHECKPOINTER(count);
  CHECKPOINTER(datbuf);

  /* if numtype is HE5 numbertype, rather than H5 numbertype, then convert
     it, otherwise use numtype itself
  */
  numbertype = HE5_EHconvdatatype(numtype);
  if(numbertype == FAIL)
    {
      numbertype = numtype;
    }

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWwritelocattr", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Allocate memory for the group name buffer */
      /* ----------------------------------------- */
      grpname = (char *)calloc(64, sizeof(char) );
      if( grpname == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for the group name buffer.\n");
          H5Epush(__FILE__, "HE5_SWwritelocattr", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          return(FAIL);
        }

      /* Get the field group flag */
      /* ------------------------ */
      fldgroup = HE5_SWfldsrch(swathID,(char *)fieldname,NULL,NULL,NULL,NULL);
      if(fldgroup == FAIL)
	{
	  sprintf(errbuf,"Cannot get the group flag for \"%s\" field.\n",fieldname);
	  H5Epush(__FILE__, "HE5_SWwritelocattr", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(FAIL);
	}

      if (fldgroup == HE5_HDFE_GEOGROUP)
	strcpy(grpname,"Geolocation Fields");

      else if (fldgroup == HE5_HDFE_DATAGROUP)
	strcpy(grpname,"Data Fields");

      else if (fldgroup == HE5_HDFE_PROFGROUP)
	strcpy(grpname,"Profile Fields");


      /* Get the Field group ID */
      /* ---------------------- */
      FieldGrpID = H5Gopen(HE5_SWXSwath[idx].sw_id, grpname);
      if(FieldGrpID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"%s\" group.\n", grpname);
	  H5Epush(__FILE__, "HE5_SWwritelocattr", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(FAIL);
	}

      /* Get field ID and call HE5_EHattr to perform I/O */
      /* ----------------------------------------------- */
      fieldID = H5Dopen(FieldGrpID, fieldname);
      if(fieldID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"%s\" field dataset.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWwritelocattr", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(FAIL);
	}

      /* Call EHattr() to perform I/O */
      /* ---------------------------- */
      status = HE5_EHattr(fieldID, attrname, numbertype, count,"w", datbuf);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot write Attribute \"%s\" for the \"%s\" field.\n", attrname, fieldname);
	  H5Epush(__FILE__, "HE5_SWwritelocattr", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(status);
	}

      /* Release dataset ID */
      /* ------------------ */
      status = H5Dclose(fieldID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"%s\" field dataset ID.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWwritelocattr", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(status);
	}

      /* Release group ID */
      /* ---------------- */
      status = H5Gclose(FieldGrpID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"%s\" group ID.\n",grpname);
	  H5Epush(__FILE__, "HE5_SWwritelocattr", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(status);
	}

      free(grpname);
    }
  
 COMPLETION:
  HE5_UNLOCK;
  return (status);	
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWreadlocattr                                                |
|                                                                             |
|  DESCRIPTION: Reads attribute associated with a specified field in a swath. |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  fieldname      char                fieldname                               |
|  attrname       char                attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Jan 00   A.Muslimov    Original version.                                   |
|  Jul 00   A.Muslimov    Unmasked hdf5 data types.                           |
|  Nov 00   A.Muslimov    Added reading local attribute from "Geolocation     |
|                          Fields" group.                                     |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|  Jan 04   S.Zhao        Added reading local attribute from the field of     |
|                         "Profile Fields" group.                             |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_SWreadlocattr(hid_t swathID, const char *fieldname, const char *attrname, void * datbuf)
{
  herr_t      status          =  FAIL;    /* return status variable   */

  int         fldgroup        =  FAIL;    /* Field group flag         */

  hid_t       fid             =  FAIL;    /* HDF-EOS file ID          */
  hid_t       gid             =  FAIL;    /* "HDFEOS" group ID        */
  hid_t       ntype           =  FAIL;    /* Data type ID             */
  hid_t       FieldGrpID      =  FAIL;    /* Field group ID           */
  hid_t       fieldID         =  FAIL;    /* Field dataset ID         */
  
  long        idx             =  FAIL;    /* Swath index              */
  
  hsize_t     count[]         = { 0 };    /* number of elements       */
  
  char        *grpname = (char *)NULL;    /* Group name buffer        */
  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer     */


  HE5_LOCK;
  CHECKPOINTER(fieldname);
  CHECKPOINTER(attrname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWreadlocattr", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Allocate memory for the group name buffer */
      /* ----------------------------------------- */
      grpname = (char *)calloc(64, sizeof(char) );
      if( grpname == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for the group name buffer.\n");
          H5Epush(__FILE__, "HE5_SWreadlocattr", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          return(FAIL);
        }

      /* Get the field group flag */
      /* ------------------------ */
      fldgroup = HE5_SWfldsrch(swathID,(char *)fieldname,NULL,NULL,NULL,NULL);
      if(fldgroup == FAIL)
	{
	  sprintf(errbuf,"Cannot get the group flag for \"%s\" field. \n",fieldname);
	  H5Epush(__FILE__, "HE5_SWreadlocattr", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(FAIL);
	}

      if (fldgroup == HE5_HDFE_GEOGROUP)
	strcpy(grpname,"Geolocation Fields");

      else if (fldgroup == HE5_HDFE_DATAGROUP)
	strcpy(grpname,"Data Fields");

      else if (fldgroup == HE5_HDFE_PROFGROUP)
	strcpy(grpname,"Profile Fields");


      /* Get Field  group ID  */
      /* -------------------- */
      FieldGrpID = H5Gopen(HE5_SWXSwath[idx].sw_id, grpname);
      if(FieldGrpID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"%s\" group.\n", grpname);
	  H5Epush(__FILE__, "HE5_SWreadlocattr", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(FAIL);
	}

      /* Get field ID and call HE5_EHattr to perform I/O */
      /* ----------------------------------------------- */
      fieldID = H5Dopen(FieldGrpID, fieldname);
      if(fieldID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"%s\" field dataset.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWreadlocattr", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(FAIL);
	}
        
      /* Call EHattr() to perform I/O */
      /* ---------------------------- */
      status = HE5_EHattr(fieldID,attrname,ntype,count,"r", datbuf);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot read Attribute \"%s\" associated wth the \"%s\" field.\n", attrname,fieldname);
	  H5Epush(__FILE__, "HE5_SWreadlocattr", __LINE__, H5E_ATTR, H5E_READERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(status);
	}

      /* Release the dataset ID */
      /* ---------------------- */
      status = H5Dclose(fieldID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"%s\" field dataset ID.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWreadlocattr", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(status);
	}	

      /* Release the group ID */
      /* -------------------- */
      status = H5Gclose(FieldGrpID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"%s\" group ID.\n", grpname);
	  H5Epush(__FILE__, "HE5_SWreadlocattr", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(status);
	}
	
      free(grpname);
    }

 COMPLETION:
  HE5_UNLOCK;
  return (status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWlocattrinfo                                                |
|                                                                             |
|  DESCRIPTION: Retrievs information about attribute associated with a        |
|               specified field in the "Data Fields" / "Geolocation Fields" / |
|               "Profile Fields" group.                                       |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  fieldname      char*               field name                              |
|  attrname       const char*         attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  ntype          hid_t               data type ID                            |
|  count          hsize_t             Number of attribute elements            |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Jan 00   A.Muslimov    Original draft.                                     |
|  May 00   A.Muslimov    Replaced 'H5T_class_t' type by 'int' data type.     |
|  Jul 00   A.Muslimov    Unmasked hdf5 data types.                           |
|  Nov 00   A.Muslimov    Added retrieving info about attribute to a          |
|                          field from the "Geolocation Fields" group.         |
|  Feb 03   S.Zhao        Changed the type of 'ntype' from an H5T_class_t to  |
|                         an hid_t.                                           |
|  Jan 04   S.Zhao        Added retrieving info about attribute from a field  |
|                         in the "Profile Fields" group.                      |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_SWlocattrinfo(hid_t swathID, const char *fieldname, const char *attrname, hid_t *ntype, hsize_t *count)
{
  herr_t     status          =  FAIL;    /* Return status variable */
  
  int        fldgroup        =  FAIL;    /* Field group flag       */

  hid_t      fid             =  FAIL;    /* HDF-EOS file ID        */
  hid_t      gid             =  FAIL;    /* "HDFEOS" group ID      */
  hid_t      FieldGrpID      =  FAIL;    /* Field group ID         */
  hid_t      fieldID         =  FAIL;    /* Field dataset ID       */

  long       idx             =  FAIL;    /* Swath index            */
  
  char       *grpname  = (char *)NULL;   /* Group name buffer      */
  char       errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer   */
  
  CHECKPOINTER(fieldname);
  CHECKPOINTER(attrname); 

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */ 
  status = HE5_SWchkswid(swathID, "HE5_SWlocattrinfo", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Allocate memory for the group name buffer */
      /* ----------------------------------------- */
      grpname = (char *)calloc(64, sizeof(char) );
      if( grpname == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for the group name buffer.\n");
          H5Epush(__FILE__, "HE5_SWlocattrinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          return(FAIL);
        }

      /* Get the field group flag */
      /* ------------------------ */
      fldgroup = HE5_SWfldsrch(swathID,(char *)fieldname,NULL,NULL,NULL,NULL);
      if(fldgroup == FAIL)
	{
	  sprintf(errbuf,"Cannot get the group flag for \"%s\" field. \n",fieldname);
	  H5Epush(__FILE__, "HE5_SWlocattrinfo", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(FAIL);
	}

      if (fldgroup == HE5_HDFE_GEOGROUP)
	strcpy(grpname,"Geolocation Fields");

      else if (fldgroup == HE5_HDFE_DATAGROUP)
	strcpy(grpname,"Data Fields");

      else if (fldgroup == HE5_HDFE_PROFGROUP)
	strcpy(grpname,"Profile Fields");

      /* Get Field  group ID  */
      /* -------------------  */
      FieldGrpID = H5Gopen(HE5_SWXSwath[idx].sw_id, grpname);
      if(FieldGrpID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"%s\" group.\n", grpname);
	  H5Epush(__FILE__, "HE5_SWlocattrinfo", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(FAIL);
	}

      /* Get field ID */
      /* ------------ */
      fieldID = H5Dopen(FieldGrpID, fieldname);
      if(fieldID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"%s\" field dataset.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWlocattrinfo", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(FAIL);
	}

      /* Call EHattrinfo() to perform I/O */
      /* -------------------------------- */
      status = HE5_EHattrinfo(fieldID,attrname,ntype,count);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot retrieve information about Attribute \"%s\" in the \"%s\" group.\n", attrname, grpname);
	  H5Epush(__FILE__, "HE5_SWlocattrinfo", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(status);
	}

      /* Release dataset ID */
      /* ------------------ */
      status = H5Dclose(fieldID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"%s\" field dataset ID.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWlocattrinfo", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(status);
	}	

      /* Release group ID */
      /* ---------------- */
      status = H5Gclose(FieldGrpID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the field group ID.\n");
	  H5Epush(__FILE__, "HE5_SWlocattrinfo", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(status);
	}	
	  
      free(grpname);	  
    }

 COMPLETION:
  return (status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWlocattrinfo2                                                |
|                                                                             |
|  DESCRIPTION: Retrievs information about attribute associated with a        |
|               specified field in the "Data Fields" / "Geolocation Fields" / |
|               "Profile Fields" group.                                       |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  fieldname      char*               field name                              |
|  attrname       const char*         attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  ntype          hid_t               data type ID                            |
|  count          hsize_t             Number of attribute elements            |
|  size           hsize_t             buf size of attribute elements          |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Jan 00   A.Muslimov    Original draft.                                     |
|  May 00   A.Muslimov    Replaced 'H5T_class_t' type by 'int' data type.     |
|  Jul 00   A.Muslimov    Unmasked hdf5 data types.                           |
|  Nov 00   A.Muslimov    Added retrieving info about attribute to a          |
|                          field from the "Geolocation Fields" group.         |
|  Feb 03   S.Zhao        Changed the type of 'ntype' from an H5T_class_t to  |
|                         an hid_t.                                           |
|  Jan 04   S.Zhao        Added retrieving info about attribute from a field  |
|                         in the "Profile Fields" group.                      |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_SWlocattrinfo2(hid_t swathID, const char *fieldname, const char *attrname, hid_t *ntype, hsize_t *count, hsize_t *size)
{
  herr_t     status          =  FAIL;    /* Return status variable */
  
  int        fldgroup        =  FAIL;    /* Field group flag       */

  hid_t      fid             =  FAIL;    /* HDF-EOS file ID        */
  hid_t      gid             =  FAIL;    /* "HDFEOS" group ID      */
  hid_t      FieldGrpID      =  FAIL;    /* Field group ID         */
  hid_t      fieldID         =  FAIL;    /* Field dataset ID       */

  long       idx             =  FAIL;    /* Swath index            */
  
  char       *grpname  = (char *)NULL;   /* Group name buffer      */
  char       errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer   */
  
  CHECKPOINTER(fieldname);
  CHECKPOINTER(attrname); 

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */ 
  status = HE5_SWchkswid(swathID, "HE5_SWlocattrinfo2", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Allocate memory for the group name buffer */
      /* ----------------------------------------- */
      grpname = (char *)calloc(64, sizeof(char) );
      if( grpname == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for the group name buffer.\n");
          H5Epush(__FILE__, "HE5_SWlocattrinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          return(FAIL);
        }

      /* Get the field group flag */
      /* ------------------------ */
      fldgroup = HE5_SWfldsrch(swathID,(char *)fieldname,NULL,NULL,NULL,NULL);
      if(fldgroup == FAIL)
	{
	  sprintf(errbuf,"Cannot get the group flag for \"%s\" field. \n",fieldname);
	  H5Epush(__FILE__, "HE5_SWlocattrinfo2", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(FAIL);
	}

      if (fldgroup == HE5_HDFE_GEOGROUP)
	strcpy(grpname,"Geolocation Fields");

      else if (fldgroup == HE5_HDFE_DATAGROUP)
	strcpy(grpname,"Data Fields");

      else if (fldgroup == HE5_HDFE_PROFGROUP)
	strcpy(grpname,"Profile Fields");

      /* Get Field  group ID  */
      /* -------------------  */
      FieldGrpID = H5Gopen(HE5_SWXSwath[idx].sw_id, grpname);
      if(FieldGrpID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"%s\" group.\n", grpname);
	  H5Epush(__FILE__, "HE5_SWlocattrinfo2", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(FAIL);
	}

      /* Get field ID */
      /* ------------ */
      fieldID = H5Dopen(FieldGrpID, fieldname);
      if(fieldID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"%s\" field dataset.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWlocattrinfo2", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(FAIL);
	}

      /* Call EHattrinfo() to perform I/O */
      /* -------------------------------- */
      status = HE5_EHattrinfo2(fieldID,attrname,ntype,count,size);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot retrieve information about Attribute \"%s\" in the \"%s\" group.\n", attrname, grpname);
	  H5Epush(__FILE__, "HE5_SWlocattrinfo2", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(status);
	}

      /* Release dataset ID */
      /* ------------------ */
      status = H5Dclose(fieldID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"%s\" field dataset ID.\n", fieldname);
	  H5Epush(__FILE__, "HE5_SWlocattrinfo2", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(status);
	}	

      /* Release group ID */
      /* ---------------- */
      status = H5Gclose(FieldGrpID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the field group ID.\n");
	  H5Epush(__FILE__, "HE5_SWlocattrinfo2", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  return(status);
	}	
	  
      free(grpname);	  
    }

 COMPLETION:
  return (status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqdscaleattrs                                             |
|                                                                             |
|  DESCRIPTION:  Retrieves the number of attributes and string length of      |
|                attribute list associated with a specified dimension scale   |
|                in a swath.                                                  |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nattr          long                number of attributes (-1 if fails)      |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t   None        HDF-EOS type swath  ID                  |
|  fieldname      char                dimension scale name                    |
|  attrnames      char                attribute name(s)                       |
|                                                                             |
|  OUTPUTS:                                                                   |
|  strbufsize     long                String length of attribute (in bytes)   |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|  None                                                                       |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  June 10   Abe Taaheri  Original development.                               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWinqdscaleattrs(hid_t swathID, const char *fieldname, char *attrnames, long *strbufsize)
{
  long       nattr         =  0;  /* Number of attributes (return)  */
  long       idx           = FAIL;/* Swath index                    */    
  
  herr_t     status        = FAIL;/* routine return status variable */
  
  hid_t      fid           = FAIL;/* HDF-EOS file ID                */
  hid_t      gid           = FAIL;/* "HDFEOS" group ID              */
  
  char       *dtsname      = NULL;/* Buffer for dataset name        */
  char       errbuf[HE5_HDFE_ERRBUFSIZE];
  
  CHECKPOINTER(fieldname);
  
  /*
**********************************************************
*  Check for proper swath ID and return HDF-EOS file ID,  * 
*        "HDFEOS" group ID and Swath index                *  
**********************************************************
*/
  status = HE5_SWchkswid(swathID, "HE5_SWinqdscaleattrs", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf,"Checking for swath ID failed.\n" );
      H5Epush(__FILE__, "HE5_SWinqdscaleattrs", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  dtsname = (char *) calloc(HE5_HDFE_NAMBUFSIZE, 1);
  if( dtsname == NULL)
    {
      sprintf(errbuf, "Can not allocate memory.\n");
      H5Epush(__FILE__, "HE5_SWinqdscaleattrs", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
	
  strcpy(dtsname,"/HDFEOS/SWATHS/");
  strcat(dtsname, HE5_SWXSwath[idx].swname);
  strcat(dtsname,"/");
  strcat(dtsname,fieldname);

  nattr = HE5_EHattrcat(fid, dtsname, attrnames, strbufsize);
	
  if (dtsname != NULL) free(dtsname);
    
 COMPLETION:
  return(nattr);
	
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqlocattrs                                                |
|                                                                             |
|  DESCRIPTION:  Retrieves the number of attributes and string length of      |
|                attribute list associated with a specified field in the      |
|                "Data Fields" / "Geolocation Fields" / "Profile Fields"      |
|                group.                                                       |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nattr          long                Number of attributes in "Data Fields"   |
|                                       group.                                |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  fieldname      char                field name                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  attrnames      char                Attribute names in "Data Fields" group  |
|                                     (Comma-separated list)                  |
|  strbufsize     long                Attributes name list string length      |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Jan 00   A.Muslimov                                                        |
|  Jul 00   A.Muslimov    Unmasked hdf5 data types.                           |
|  Nov 00   A.Muslimov    Added inquiring about local attributes from         |
|                          "Geolocation Fields" group.                        |
|  Jan 04   S.Zhao        Added inquiring about local attributes from         |
|                         the "Profile Fields" group.                         |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWinqlocattrs(hid_t swathID, const char *fieldname, char *attrnames, long *strbufsize)
{
  long            nattr       = FAIL;         /* Number of attributes     */
  long            idx         = FAIL;         /* Swath index              */

  herr_t          status      = FAIL;         /* Return status variable   */

  int             fldgroup    =  FAIL;        /* Field group flag         */ 

  hid_t           fid         = FAIL;         /* HDF-EOS file ID          */
  hid_t           gid         = FAIL;         /* "SWATHS" group ID        */
    
  char            *dtsname    = (char *)NULL; /* Dataset name string      */
  char            *grpname    = (char *)NULL; /* Group name buffer        */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer     */  

  CHECKPOINTER(fieldname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWinqlocattrs", &fid, &gid, &idx);
  if(status == SUCCEED )
    {
      /* Allocate memory for the dataset name buffer */
      /* ------------------------------------------- */
      dtsname = (char *)calloc(HE5_HDFE_NAMBUFSIZE, sizeof(char) );
      if( dtsname == NULL)
        {
	  sprintf(errbuf, "Cannot allocate memory for the dataset name buffer. \n");
          H5Epush(__FILE__, "HE5_SWinqlocattrs", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          return(FAIL);
        }

      /* Allocate memory for the group name buffer */
      /* ----------------------------------------- */
      grpname = (char *)calloc(64, sizeof(char) );
      if( grpname == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for the group name buffer.\n");
          H5Epush(__FILE__, "HE5_SWinqlocattrs", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(dtsname);
          return(FAIL);
        }

      /* Get the field group flag */
      /* ------------------------ */
      fldgroup = HE5_SWfldsrch(swathID,(char *)fieldname,NULL,NULL,NULL,NULL);
      if(fldgroup == FAIL)
	{
	  sprintf(errbuf,"Cannot get the group flag for \"%s\" field.\n",fieldname);
	  H5Epush(__FILE__, "HE5_SWinqlocattrs", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	  free(dtsname);
	  return(FAIL);
	}

      if (fldgroup == HE5_HDFE_GEOGROUP)
	strcpy(grpname,"/Geolocation Fields/");

      else if (fldgroup == HE5_HDFE_DATAGROUP)
	strcpy(grpname,"/Data Fields/");

      else if (fldgroup == HE5_HDFE_PROFGROUP)
	strcpy(grpname,"/Profile Fields/");

      strcpy(dtsname,"/HDFEOS/SWATHS/");
      strcat(dtsname, HE5_SWXSwath[idx].swname);
      strcat(dtsname, grpname);
      strcat(dtsname, fieldname);
	  
      /* search group with grpname for the number of attributes */
      /* ------------------------------------------------------ */ 
      nattr = HE5_EHattrcat(fid,  dtsname, attrnames, strbufsize);
      if ( nattr < 0 )
	{
	  sprintf(errbuf, "Cannot find the attributes. \n");
	  H5Epush(__FILE__, "HE5_SWinqlocattrs", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	}

      if (dtsname != NULL) free(dtsname);
      if (grpname != NULL) free(grpname);
    }
  
 COMPLETION:
  return(nattr);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_PRdefine                                                     |
|                                                                             |
|  DESCRIPTION:  Defines "Profile" dataset within a specified Swath, under the|
|                 "Profile Fields" group.                                     |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  status         herr_t                   Return status (0) SUCCEED (-1)     |
|                                          FAIL                               |
|  INPUTS:                                                                    |
|    swathID      hid_t                    Swath ID                           |
|    profilename  const char               Profile/dataset name               |
|    dimlist      char                     Comma separated list of dimensions |
|    maxdimlist   char                     List of maximum dimensions         |
|    datatype_id  hid_t                    Base datatype ID                   |
|                                                                             |
|  OUTPUTS:                                                                   |
|    None                                                                     |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  Jun  00  A.Muslimov    Original development                                |
|  Jul  00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  00  A.Muslimov    Changed referencing the "Data Fields" to "Profile   |
|                          Fields".                                           |
|  Oct  00  A.Muslimov    Moved a block that tries to retrieve a fill value   |
|                          to HE5_PRwrite() interface.                        |
|  Dec  00  A.Muslimov    Modified to add "dimlist" and "maxdimlist" parame-  |
|                          ters and related metadata blocks.                  |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|  Feb  03  S. Zhao       Added the creation of the "Profile Fields" group.   |
|  Aug  03  S.Zhao        Added Szip compression methods.                     |
|  May  05  S.Zhao        Added HE5_EHdtype2numtype() function call.          |
|  Sep  11  Abe Taaheri   Modified for correcting Unlimited dimension         |
|                         behavior and extension, removing hardcoded name     |
|                         Unlim                                               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t 
HE5_PRdefine(hid_t swathID, const char *profilename, char *dimlist, char *maxdimlist, hid_t numbertype_in)
{ 
  herr_t        status      = FAIL;               /* Status variable (return)  */

  int           i;                                /* Loop index                */
  int           compcode    = FAIL;               /* Compression method flag   */
  int           foundAllDim = 1;                  /* "found all dims" flag     */
  int           append      = FALSE;              /* "Appendability" flag      */
  int           first       = 1;                  /* first entry flag          */
  int           rank        = 0;                  /* Profile rank              */
  int           maxrank     = 0;                  /* Max. dims rank            */

  hid_t         heos_gid    = FAIL;               /* "SWATHS" group ID         */
  hid_t         fid         = FAIL;               /* HDF-EOS file ID           */
  hid_t         gid         = FAIL;               /* "Profile Fields" group ID */
  hid_t         dataset     = FAIL;               /* Profile dataset ID        */
  hid_t         space       = FAIL;               /* Data space ID             */
  hid_t         type        = FAIL;               /* Data type ID              */
  hid_t         numtype     = FAIL;               /* Number type               */
  hid_t         datatype_id;                      /* HDF5 type Number type     */

  hsize_t       metavalue   = 0;                  /* Metadata value to insert  */
  hsize_t       dims[HE5_DTSETRANKMAX];           /* Dimension size array      */
  hsize_t       maxdims[HE5_DTSETRANKMAX];        /* Dimension size array      */
  hsize_t       dimsize     = 0;                  /* Dimension size            */

  long          idx         = FAIL;               /* Swath index               */

  H5D_layout_t  layout      = H5D_LAYOUT_ERROR;   /* Type of storage layout    */

  char          *dimbuf     = (char *)NULL;       /* Dimension buffer          */
  char          *comma      = (char *)NULL;       /* Pointer to comma          */
  char          *dimcheck   = (char *)NULL;       /* Dimension check buffer    */
  char          maxdimlstbuf[HE5_HDFE_DIMBUFSIZE];/* Max. dim. list buffer     */
  char          dimlstbuf[HE5_HDFE_DIMBUFSIZE];   /* Dim. list buffer          */
  char          compparmbuf[HE5_HDFE_DIMBUFSIZE]; /* Compression parameter     */
  char          utlbuf[HE5_HDFE_UTLBUFSIZE];      /* Utility buffer            */
  char          utlbuf2[HE5_HDFE_UTLBUFSIZE];     /* Utility buffer 2          */
  char          errbuf[HE5_HDFE_ERRBUFSIZE];      /* Error message buffer      */
  char          *HDFcomp[18] = {"HE5_HDFE_COMP_NONE", "HE5_HDFE_COMP_RLE", "HE5_HDFE_COMP_NBIT", "HE5_HDFE_COMP_SKPHUFF", "HE5_HDFE_COMP_DEFLATE", "HE5_HDFE_COMP_SZIP_CHIP", "HE5_HDFE_COMP_SZIP_K13", "HE5_HDFE_COMP_SZIP_EC", "HE5_HDFE_COMP_SZIP_NN", "HE5_HDFE_COMP_SZIP_K13orEC", "HE5_HDFE_COMP_SZIP_K13orNN", "HE5_HDFE_COMP_SHUF_DEFLATE", "HE5_HDFE_COMP_SHUF_SZIP_CHIP", "HE5_HDFE_COMP_SHUF_SZIP_K13", "HE5_HDFE_COMP_SHUF_SZIP_EC", "HE5_HDFE_COMP_SHUF_SZIP_NN", "HE5_HDFE_COMP_SHUF_SZIP_K13orEC", "HE5_HDFE_COMP_SHUF_SZIP_K13orNN"};                 /* Compression code names    */


  HE5_LOCK;
  CHECKNAME(profilename);
  CHECKPOINTER(dimlist);


  /* Convert HDF-EOS5 datatype to HDF5 datatype */
  if (
      H5Tequal(numbertype_in, H5T_NATIVE_CHAR)   == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_SCHAR)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_UCHAR)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_SHORT)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_USHORT) == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_INT)    == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_UINT)   == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_LONG)   == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_ULONG)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_LLONG)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_ULLONG) == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_FLOAT)  == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_DOUBLE) == SUCCEED ||
      H5Tequal(numbertype_in, H5T_NATIVE_LDOUBLE)== SUCCEED ||
      H5Tequal(numbertype_in, H5T_C_S1) == SUCCEED)
    {
      datatype_id = numbertype_in;
    }
  else
    {
      datatype_id = HE5_EHconvdatatype((int) numbertype_in);
    }

  if(datatype_id == FAIL)
    {
      sprintf(errbuf,"Cannot convert to HDF5 type data type ID for PR Field.\n");
      H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_PRdefine", &fid, &heos_gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for swath ID failed. \n");
      H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* initialize dims and maxdims array */
  /* --------------------------------- */
  for(i = 0; i < HE5_DTSETRANKMAX; i++)
    {
      dims[i]    = 0;
      maxdims[i] = 0;
    }
	
  /* Allocate space for dimbuf, copy dimlist into it, & append comma */
  /* --------------------------------------------------------------- */
  dimbuf = (char *) calloc(strlen(dimlist) + 64, sizeof(char));
  if(dimbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory. \n");
      HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
      return(FAIL);
    }
	
  /*
********************************************************************
*   C H E C K  T H E   C O N T E N T   O F   dimlist  S T R I N G  *   
********************************************************************
*/
  
  strcpy(dimbuf, dimlist);
  strcat(dimbuf, ",");
  
  /* Find comma */
  /* ---------- */
  comma = strchr(dimbuf, ',');
	
  /*
   * Loop through entries in dimension list to make sure they are
   *                    defined in swath
   */
  while (comma != NULL)
    {
      /* Copy dimension list entry to dimcheck */
      /* ------------------------------------- */
      dimcheck = (char *) calloc(comma - dimbuf + 1, sizeof(char));
      if(dimcheck == NULL)
	{
	  H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory. \n");
	  HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	  free(dimbuf);
	  return(FAIL);
	}
      memmove(dimcheck, dimbuf, comma - dimbuf);

      /* Get dimension size */
      /* ------------------ */
      dimsize = HE5_SWdiminfo(swathID, dimcheck);
      if (dimsize > 0)
	{
	  dims[rank] = dimsize;
	  rank++;
	}
      else
	{
	  /*
	   * If dimension list entry not found - set error return
	   * status, append name to utility buffer for error report
	   */
	  status = FAIL;
	  foundAllDim = 0;
	  if (first == 1)
	    strcpy(utlbuf, dimcheck);
	  else
	    {
	      strcat(utlbuf, ",");
	      strcat(utlbuf, dimcheck);
	    }
	  first = 0;
	}

      /*
       * Go to next dimension entry, find next comma, & free up
       * dimcheck buffer
       */
      memmove(dimbuf, comma + 1, strlen(comma + 1) + 1); 
      comma = strchr(dimbuf, ',');
      free(dimcheck);

    }
  free(dimbuf);
	
  /* If no dimensions found, report error */
  /* ------------------------------------ */
  if (foundAllDim == 0)
    {
      status = FAIL;
      sprintf(errbuf, "Dimension(s) \"%s\" not found for \"%s\" profile. \n", utlbuf, profilename);
      H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return (status); 
    }
	
	
  /*
************************************************************************
*   C H E C K  T H E   C O N T E N T   O F   maxdimlist   S T R I N G  *   
************************************************************************
*/
	
	
  /* Allocate space for dimbuf, copy maxdimlist into it, & append comma */
  /* ------------------------------------------------------------------ */
  if(maxdimlist != NULL) 
    {
      dimbuf = (char *) calloc(strlen(maxdimlist) + 64, sizeof(char));
      if(dimbuf == NULL)
	{
	  H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory. \n");
	  HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	  return(FAIL);

	}
	  
      /* Copy "maxdimlist" to "dimbuf", & append comma */
      /* --------------------------------------------- */
      strcpy(dimbuf, maxdimlist);
      strcat(dimbuf, ",");

      /* Find comma */
      /* ---------- */
      comma = strchr(dimbuf, ',');

      /*
       * Loop through entries in dimension list to make sure they are
       *                     defined in swath
       */
      while (comma != NULL)
	{
	  /* Copy dimension list entry to dimcheck */
	  /* ------------------------------------- */
	  dimcheck = (char *) calloc(comma - dimbuf + 1, sizeof(char));
	  if(dimcheck == NULL)
	    {
	      H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory. \n");
	      HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	      free(dimbuf);
	      return(FAIL);
	    }
	  memmove(dimcheck, dimbuf, comma - dimbuf);

	  /* Get dimension size */
	  /* ------------------ */
	  dimsize = HE5_SWdiminfo(swathID, dimcheck);
	  if ( (dimsize > 0) || (dimsize == H5S_UNLIMITED)  )
	    {
	      maxdims[maxrank] = dimsize;
	      maxrank++;
	    }
	  else
	    {
	      /*
	       * If dimension list entry not found - set error return
	       * status, append name to utility buffer for error report
	       */
	      status = FAIL;
	      foundAllDim = 0;
	      if (first == 1)
		strcpy(utlbuf, dimcheck);
	      else
		{
		  strcat(utlbuf, ",");
		  strcat(utlbuf, dimcheck);
		}
	      first = 0;
	    }

	  /*
	   * Go to next dimension entry, find next comma, & free up
	   * dimcheck buffer
	   */
	  memmove(dimbuf, comma + 1, strlen(comma + 1) + 1); 
	  comma = strchr(dimbuf, ',');
	  free(dimcheck);
	}

      free(dimbuf);

      /* If no dimensions found, report error */
      /* ------------------------------------ */
      if (foundAllDim == 0)
	{
	  status = FAIL;
	  sprintf(errbuf, "Dimension(s) \"%s\" not found for \"%s\" profile. \n", utlbuf, profilename);
	  H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return (status);
	}


      /* If maxrank !=rank  then report error */
      /* ------------------------------------ */
      if ( maxrank != rank )
	{
	  status = FAIL;
	  sprintf(errbuf,"Dimension rank doesn't match Maximum dimension rank. \n");
	  H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return (status);
	}
    } 
  /* "maxdimlist == NULL"  ==> maxdims[]= dims[] */
  /* ------------------------------------------- */
  else
    {
      for(i = 0; i < rank; i++ )
	maxdims[ i ] = dims[ i ];
    }

  /* Find out if the dataset dimension is appendable */
  /* ----------------------------------------------- */
  for(i = 0; i < rank; i++)
    {
      if( dims[i] == maxdims[i] )
	append = FALSE;
      else if ( (dims[i] < maxdims[i]) || (maxdims[i] == H5S_UNLIMITED))
	{
	  append = TRUE;
	  break;
	}
      else
	{
	  status = FAIL;
	  H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_ARGS, H5E_BADRANGE, "Maximum dimension size is smaller than Dimension size. \n");
	  HE5_EHprint("Error: Maximum dimension size is smaller than Dimension size, occured", __FILE__, __LINE__);
	  return(status);
	}
    }
	
  
  /* Check for valid base data type ID */
  /* --------------------------------- */
  if (H5Tequal(datatype_id, H5T_NATIVE_CHAR)    == FAIL &&
      H5Tequal(datatype_id, H5T_NATIVE_SCHAR)   == FAIL &&
      H5Tequal(datatype_id, H5T_NATIVE_UCHAR)   == FAIL &&
      H5Tequal(datatype_id, H5T_NATIVE_SHORT)   == FAIL &&
      H5Tequal(datatype_id, H5T_NATIVE_USHORT)  == FAIL &&
      H5Tequal(datatype_id, H5T_NATIVE_INT)     == FAIL &&
      H5Tequal(datatype_id, H5T_NATIVE_UINT)    == FAIL &&
      H5Tequal(datatype_id, H5T_NATIVE_LONG)    == FAIL &&
      H5Tequal(datatype_id, H5T_NATIVE_ULONG)   == FAIL &&
      H5Tequal(datatype_id, H5T_NATIVE_LLONG)   == FAIL &&
      H5Tequal(datatype_id, H5T_NATIVE_ULLONG)  == FAIL &&
      H5Tequal(datatype_id, H5T_NATIVE_FLOAT)   == FAIL &&
      H5Tequal(datatype_id, H5T_NATIVE_DOUBLE)  == FAIL &&
      H5Tequal(datatype_id, H5T_NATIVE_LDOUBLE) == FAIL
      )
    {
      H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, "Invalid (unsupported) data type. \n");
      HE5_EHprint("Error: Invalid (unsupported) data type, occured", __FILE__, __LINE__);
      return(FAIL);
    }

  /* Check if "Profile Fields" group exists */
  /* -------------------------------------- */
  if (HE5_SWXSwath[idx].prof_id != FAIL)
    {
 
      /* Get the "Profile Fields" group ID */
      /* --------------------------------- */
      gid = HE5_SWXSwath[idx].prof_id;
 
    }
  else
    {
 
      /* Create /SWATH/swathname/Profile Fields group */
      /* -------------------------------------------- */
      gid = H5Gcreate(HE5_SWXSwath[idx].sw_id, "Profile Fields", 0);
      if (gid == FAIL)
	{
	  sprintf(errbuf,"Cannot create the \"Profile Fields\" group.\n");
	  H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_OHDR, H5E_CANTCREATE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
 
      /* Setup External Arrays */
      /* --------------------- */
      HE5_SWXSwath[idx].prof_id = gid;
 
    }

		
  /* Create dataspace then create dataset */
  /*------------------------------------ */
  if( HE5_SWXSwath[idx].plist == FAIL )     
    HE5_SWXSwath[idx].plist = H5Pcreate(H5P_DATASET_CREATE);
	
  /* Get dataset layout */
  /* ------------------ */
  layout = H5Pget_layout(HE5_SWXSwath[idx].plist);
  if (layout == H5D_LAYOUT_ERROR)
    {
      status = FAIL;
      H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_ARGS, H5E_BADVALUE, "Cannot get dataset layout.\n");
      HE5_EHprint("Error: Cannot get dataset layout, occured", __FILE__, __LINE__);
      return(status);
    }
	
  if(append == FALSE)
    space = H5Screate_simple(rank, dims, NULL);
  else
    {
      if( layout == H5D_CHUNKED)
	space = H5Screate_simple(rank, dims, maxdims);
      else
	{
	  status = FAIL;
	  H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_ARGS, H5E_BADVALUE, "Appendable dataset MUST BE CHUNKED first.\n");
	  HE5_EHprint("Error: Appendable dataset MUST BE CHUNKED first, occured", __FILE__, __LINE__);
	  return(status);
	}
    }
	
  /* Create the VL data type from the base data type */
  /* ----------------------------------------------- */
  type = H5Tvlen_create(datatype_id);
  if (type == FAIL)
    {
      status = FAIL;
      sprintf(errbuf,"Cannot create the VL-data type for \"%s\" profile.\n", profilename);
      H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status); 
    }

	
  /* Create dataset */
  /* -------------- */
  dataset = H5Dcreate(gid, profilename, type, space, HE5_SWXSwath[idx].plist);
  if (dataset == FAIL)
    {
      status = FAIL;
      sprintf(errbuf,"Cannot create dataset for \"%s\" profile. \n", profilename);
      H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);   
    }
    
  /* Extend the dataset. assure that it is at least dims size */
  /* -------------------------------------------------------- */
  if( append == TRUE)
    {
      status = H5Dextend(dataset, dims);
      if (status == FAIL)
	{
	  sprintf(errbuf,"Cannot extend the dataset for \"%s\" profile.\n", profilename);
	  H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);   
	}
    }
  
  /* Store dataset IDs and dataset name */
  /* ---------------------------------- */
  if (HE5_SWXSwath[idx].nPROF > 0)
    {
      /* Allocate memory to "Profile" struct */
      /* ----------------------------------- */
      HE5_SWXSwath[idx].pdataset = (HE5_DTSinfo *)realloc((void *)HE5_SWXSwath[idx].pdataset,(HE5_SWXSwath[idx].nPROF + 1) * sizeof(HE5_DTSinfo));
	  
    }
  else
    {
      HE5_SWXSwath[idx].pdataset = (HE5_DTSinfo *)calloc(1, sizeof(HE5_DTSinfo));
      if (HE5_SWXSwath[idx].pdataset == (HE5_DTSinfo *)NULL )
	{
	  status = FAIL;
	  sprintf(errbuf,"Cannot allocate memory for \"Profile\" structure. \n");
	  H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}	  
	  
    }
  
  /* Allocate memory to name */
  /* ----------------------- */
  HE5_SWXSwath[idx].pdataset[HE5_SWXSwath[idx].nPROF].name = (char *)calloc( (strlen(profilename)+1), sizeof(char) );
  if ( HE5_SWXSwath[idx].pdataset[HE5_SWXSwath[idx].nPROF].name == (char *)NULL)
    {
      status = FAIL;
      sprintf(errbuf,"Cannot allocate memory for \"Profile\" structure. \n");
      H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(HE5_SWXSwath[idx].pdataset);
      return(status);
    }
  
  /* Load Table */
  /* ---------- */
  HE5_SWXSwath[idx].pdataset[HE5_SWXSwath[idx].nPROF].ID = dataset;
  strcpy(HE5_SWXSwath[idx].pdataset[HE5_SWXSwath[idx].nPROF].name, profilename);

  /* Increment the profile counter */
  /* ----------------------------- */
  HE5_SWXSwath[idx].nPROF++;


  /*  
******************************************************************
*                  SET   UP  METADATA  STRINGS                   *
******************************************************************
*/

  /*  Set up "DimList" string content */
  /*  ------------------------------- */
  strcpy(utlbuf,"");
  sprintf(utlbuf, "%s%s%s", profilename,":",dimlist);
    
  /* Set up "MaxdimList"  string content */
  /* ----------------------------------- */ 
  if ( maxdimlist != NULL)
    {
      status = HE5_EHmetalist(maxdimlist,maxdimlstbuf);
      if (status == FAIL)
	{
	  sprintf(errbuf, "Cannot convert the input \"%s\" list to the metadata list. \n", maxdimlist);
	  H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return (status);
	}
      sprintf(utlbuf2,"%s%s",":\n\t\t\t\tMaxdimList=", maxdimlstbuf);
      strcat(utlbuf,utlbuf2);
		 
    }
  if (maxdimlist == NULL)
    {
      status = HE5_EHmetalist(dimlist,dimlstbuf);
      if (status == FAIL)
	{
	  sprintf(errbuf, "Cannot convert the input \"%s\" list to the metadata list.\n", dimlist);
	  H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return (status);
	}
      sprintf(utlbuf2,"%s%s",":\n\t\t\t\tMaxdimList=", dimlstbuf);
      strcat(utlbuf,utlbuf2);       
		
    }

  /* Get current compression code */
  /* ---------------------------- */
  compcode = HE5_SWXSwath[idx].compcode;
    
  /* setup "CompressionType" & "CompressionParams" strings content */
  /* ------------------------------------------------------------- */
  if (compcode != HE5_HDFE_COMP_NONE)
    {
      sprintf(utlbuf2,"%s%s","\n\t\t\t\tCompressionType=", HDFcomp[compcode]);
		
      switch (compcode)
	{
	case HE5_HDFE_COMP_NBIT:

	  sprintf(compparmbuf,
		  "%s%d,%d,%d,%d%s",
		  "\n\t\t\t\tCompressionParams=(",
		  HE5_SWXSwath[idx].compparm[0],
		  HE5_SWXSwath[idx].compparm[1],
		  HE5_SWXSwath[idx].compparm[2],
		  HE5_SWXSwath[idx].compparm[3], ")");
	  strcat(utlbuf2, compparmbuf);
	  break;
			
			
	case HE5_HDFE_COMP_DEFLATE:
			
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tDeflateLevel=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;

	case HE5_HDFE_COMP_SZIP_CHIP:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;

	case HE5_HDFE_COMP_SZIP_K13:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;

	case HE5_HDFE_COMP_SZIP_EC:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;

	case HE5_HDFE_COMP_SZIP_NN:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;

	case HE5_HDFE_COMP_SZIP_K13orEC:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;

	case HE5_HDFE_COMP_SZIP_K13orNN:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;

	case HE5_HDFE_COMP_SHUF_DEFLATE:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tDeflateLevel=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;
 
	case HE5_HDFE_COMP_SHUF_SZIP_CHIP:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;
 
	case HE5_HDFE_COMP_SHUF_SZIP_K13:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;
 
	case HE5_HDFE_COMP_SHUF_SZIP_EC:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;
 
	case HE5_HDFE_COMP_SHUF_SZIP_NN:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;
 
	case HE5_HDFE_COMP_SHUF_SZIP_K13orEC:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;
 
	case HE5_HDFE_COMP_SHUF_SZIP_K13orNN:
 
	  sprintf(compparmbuf,"%s%d","\n\t\t\t\tBlockSize=", HE5_SWXSwath[idx].compparm[0]);
	  strcat(utlbuf2, compparmbuf);
	  break;

	default:
	  { 
	    sprintf(errbuf,"Compression code \"%d\" is not supported. \n", compcode);
	    H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_ARGS, H5E_UNSUPPORTED, errbuf);
	    HE5_EHprint(errbuf, __FILE__, __LINE__);
	  }
			
	  break;		    
			
			
	}
	  
      /* Concatanate compression parameters with compression code */
      /* -------------------------------------------------------- */
      strcat(utlbuf, utlbuf2);
    }
	
  /* Generate value of "DataType" metadata */
  /* ------------------------------------- */
  numtype = HE5_EHdtype2numtype(datatype_id);
  if (numtype == FAIL)
    {
      sprintf(errbuf, "Cannot get the number type ID. \n");
      H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  else if (numtype == 0)
    {
      metavalue = 0;
    }
  else
    {
      metavalue = HE5_EHhid2hsize(numtype);
      if (metavalue == 0)
	{
	  sprintf(errbuf, "Cannot convert \"hid_t\" to \"hsize_t\" data type. \n");
	  H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
    }

  /* 
******************************************************************
*   Insert metadata information to Structural Metadata section   *
******************************************************************
*/          
  status = HE5_EHinsertmeta(fid, HE5_SWXSwath[idx].swname, "s", 5L, utlbuf, &metavalue);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot insert metadata for \"%s\" profile.\n",profilename);
      H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);   
    }
	
  /* Release data type ID */
  /* -------------------- */
  status = H5Tclose(type);    
  if ( status == FAIL)
    {
      sprintf(errbuf,"Cannot release the property list ID. \n");
      H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(HE5_SWXSwath[idx].pdataset);
      free(HE5_SWXSwath[idx].pdataset[HE5_SWXSwath[idx].nPROF].name);
      return(status);
    }

  /* Release data space ID */
  /* --------------------- */
  status = H5Sclose(space);
  if ( status == FAIL)
    {
      sprintf(errbuf,"Cannot release the data space ID. \n");
      H5Epush(__FILE__, "HE5_PRdefine", __LINE__, H5E_DATASPACE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(HE5_SWXSwath[idx].pdataset);
      free(HE5_SWXSwath[idx].pdataset[HE5_SWXSwath[idx].nPROF].name);
      return(status);
    }
  

  /* Reset external array entry */
  /* -------------------------- */
  /* The reset was moved to HE5_PRwrite, to make dataset property reset
     consistent with metadata reset. Unlike swath, grid and ZA, where the
     property list is reset after definition of every field, the PR APIs
     reset property list after first dataset writing (not definition), 
     so if one defines several PR fields, all will have the same properties, 
     such as compression.
     HE5_SWXSwath[idx].compcode = HE5_HDFE_COMP_NONE;
     
     for (i = 0; i < 5; i++)       
     HE5_SWXSwath[idx].compparm[ i ] = 0; 
  */
  
 COMPLETION:  
  HE5_UNLOCK;
  return (status);    
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_PRwrite                                                      |
|                                                                             |
|  DESCRIPTION: Writes data into the "Profile" dataset within a Swath.        |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  status         herr_t                   Return status (0) SUCCEED (-1)     |
|                                          FAIL                               |
|  INPUTS:                                                                    |
|    Swath_ID     hid_t                    Swath ID                           |
|    profilename  const char               Name of Profile dataset            |
|    start        hssize_t                 start array                        |
|    stride       hsize_t                  stride array                       |
|    edge         hsize_t                  edge array                         |
|    size         size_t                   Size (in bytes) of data to write   |
|    buffer       void                     Data buffer                        |
|                                                                             |
|  OUTPUTS:                                                                   |
|    None                                                                     |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|     The "NULL" values for "start" and "edge" are not allowed.               |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  6/8/00   A.Muslimov    Original development                                |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  00  A.Muslimov    Changed referencing the "Data Fields" by "Profile   |
|                            Fields".                                         |
|  Oct 00   A.Muslimov    Added conditional release of the property list ID.  |
|  Dec 00   A.Muslimov    Enhanced to add "start", "stride", and "edge" para- |
|                            meters.                                          |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|  Apr  03  S.Zhao        Added conversion from dataset base datatype ID to   |
|                         memory base datatype ID.                            |
|  Sep  06  Abe Taaheri   Added H5Dclose to close opened dataset              |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t    
HE5_PRwrite(hid_t swathID, const char *profilename, const hssize_t start[], const hsize_t stride[], const hsize_t edge[], size_t size, void *buffer)
{  
  herr_t      status      = FAIL;         /* Status variable (return) */

  int         rank        = FAIL;         /* Rank of profile dataset  */      
  int         i;                          /* Loop index               */
  int         append      = FALSE;        /* FLAG (appendability)     */

  hid_t       heos_gid    = FAIL;         /* "SWATHS" group ID        */
  hid_t       fid         = FAIL;         /* HDF-EOS file ID          */
  hid_t       dataset     = FAIL;         /* Profile dataset ID       */
  hid_t       datatype    = FAIL;         /* Profile datatype ID      */
  hid_t       btype       = FAIL;         /* Dataset base datatype ID */
  hid_t       space       = FAIL;         /* File data space ID       */  
  hid_t       mspace      = FAIL;         /* Memory data space ID     */  
  hid_t       xfer_list   = FAIL;         /* Property list ID         */     
  hid_t       grp_id      = FAIL;         /* "Data Fields" group ID   */
  hid_t       mbtype      = FAIL;         /* "Memory" base datatype ID*/
  hid_t       mtype       = FAIL;         /* Memory data type ID      */

  H5D_fill_value_t fill_status;      /* to see if fill value is set or not */

  void        *value      = (void *)NULL; /* Temp fill value variable */

  hsize_t     count[]     = { 1 };        /* Number of attr. elements */
  hsize_t     dims[HE5_DTSETRANKMAX];     /* Array of dimension sizes */
  hsize_t     maxdims[HE5_DTSETRANKMAX];  /* Array of Max. dim. sizes */
  hsize_t     size_ext[HE5_DTSETRANKMAX]; /* Extended dimension size  */

  size_t      tsize       = 0;            /* Size of base data type   */

  long        idx         = FAIL;         /* Swath index              */

  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer     */


  HE5_LOCK;
  CHECKPOINTER(profilename);
  CHECKPOINTER(buffer);


  /* assuming that fillvalue is undefined for the field */
  fill_status = H5D_FILL_VALUE_UNDEFINED;


  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_PRwrite", &fid, &heos_gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for swath ID failed. \n");
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Initialize dims[]/maxdims[]/size_ext[] arrays */
  /* --------------------------------------------- */
  for (i = 0; i < HE5_DTSETRANKMAX; i++)
    {
      dims[i]     = 0;
      maxdims[i]  = 0;
      size_ext[i] = 0;
    }

  /* Get "Profile Fields" group ID */
  /* ----------------------------- */
  grp_id = HE5_SWXSwath[idx].prof_id;

  /* Open the dataset */
  /* ---------------- */  
  dataset = H5Dopen(grp_id, profilename);
  if (dataset == FAIL)
    {
      status = FAIL;
      sprintf(errbuf, "Cannot open the profile \"%s\". \n", profilename);
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }
    
  /* Create property list ID */
  /* ----------------------- */
  xfer_list = H5Pcreate(H5P_DATASET_XFER);  
  if (xfer_list == FAIL)
    {
      status = FAIL;
      sprintf(errbuf, "Cannot create the property list for the profile \"%s\". \n", profilename);
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Get the dataset data type ID */
  /* ---------------------------- */
  datatype = H5Dget_type(dataset);
  if (datatype == FAIL)
    {
      status = FAIL;
      sprintf(errbuf, "Cannot get the datatype ID for the profile \"%s\". \n", profilename);
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Get the data space ID */
  /* --------------------- */
  space = H5Dget_space(dataset);
  if (space == FAIL)
    {
      status = FAIL;
      sprintf(errbuf, "Cannot get the data space ID for the profile \"%s\". \n", profilename);
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_DATASPACE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Get the base data type ID */
  /* ------------------------- */
  btype = H5Tget_super(datatype);
  if( btype == FAIL)
    {
      sprintf(errbuf, "Cannot get the base data type ID. \n");
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return (FAIL);
    }

  /* Get the memory base data type ID */
  /* -------------------------------- */
  mbtype = HE5_EHdtype2mtype(btype);
  if (mbtype == FAIL)
    {
      sprintf(errbuf,"Cannot get the memory data type from the base data type.\n");
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Create data type ID */
  /* ------------------- */
  mtype  = H5Tvlen_create(mbtype);
  if (mtype == FAIL)
    {
      sprintf(errbuf,"Cannot create data type from the base data type.\n");
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }


  /* Get the size of a base data type in bytes */
  /* ----------------------------------------- */ 
  tsize = H5Tget_size(btype);
  if( tsize == 0)
    {
      sprintf(errbuf, "Cannot get the size of a base data type. \n");
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return (FAIL);
    }
    

  /* Allocate memory for a fill value */
  /* -------------------------------- */
  value = (void *)calloc(1, tsize);
  if( value == (void *)NULL)
    {
      sprintf(errbuf, "Cannot allocate memory for fill value. \n");
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
	
  /* Try to retrieve the fill value (in case it's already defined) */
  /* ------------------------------------------------------------- */ 
  H5E_BEGIN_TRY {
    status = H5Pfill_value_defined(HE5_SWXSwath[idx].plist, &fill_status );
  }
  H5E_END_TRY;
  if (fill_status == H5D_FILL_VALUE_USER_DEFINED)
    {
      H5E_BEGIN_TRY {
	status = H5Pget_fill_value(HE5_SWXSwath[idx].plist, btype, value);
      }
      H5E_END_TRY;
      
      /* Store fill value in the dataset attribute "_FillValue" */
      /* -----------------------------------------------------  */ 
      if( status != FAIL)
	{
	  status = HE5_EHattr( dataset, "_FillValue", btype, count, "w", value);
	  if( status == FAIL )
	    {
	      sprintf(errbuf, "Cannot write fill value to the attribute \"_FillValue\". \n");
	      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(value);
	      return(status);
	    }
	}
    }  
  free( value);

  /* Get the dataset rank, and dimension sizes */
  /* ----------------------------------------- */
  rank = H5Sget_simple_extent_dims(space, dims, maxdims);
  if (rank == FAIL)
    {
      sprintf(errbuf, "Cannot get the data space dimension size and maximum dimension size. \n");
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_DATASPACE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }  

  /* Find out if the dataset is extendible */
  /* ------------------------------------- */
  for(i = 0; i < rank; i++)
    {
      if(   dims[i] == maxdims[i] )
	append = FALSE;
      else if ( (dims[i] < maxdims[i]) || (maxdims[i] == H5S_UNLIMITED))
	{
	  append = TRUE;
	  break;
	}
      else
	{
	  sprintf(errbuf,"Maximum dimension size is smaller than dimension size.\n");
	  H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_ARGS, H5E_BADRANGE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
    } 
  
  /* If the dataset is APPENDIBLE, extend it */
  /* --------------------------------------- */
  if (append == TRUE)
    {
      for(i = 0; i < rank; i++)
	size_ext[ i ] = start[ i ] + edge[ i ];

      status = H5Dextend(dataset, size_ext);
      if (status == FAIL)
	{
	  sprintf(errbuf, "Cannot extend the dataset. \n");
	  H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
    }

  /* Select the hyperslab */
  /* -------------------- */
  status = H5Sselect_hyperslab( space, H5S_SELECT_SET, (const hsize_t *)start, stride, edge, NULL) ;
  if( status == FAIL )
    {
      sprintf(errbuf,"Cannot select a hyperslab. \n");
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }
	
  /* Create dataspace in memory */
  /* -------------------------- */
  mspace = H5Screate_simple(rank, edge, NULL);
  if( mspace == FAIL)
    {
      sprintf(errbuf,"Cannot create the memory data space.\n");
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_DATASPACE, H5E_CANTCREATE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }


  /* Set "write" data buffer */
  /* ----------------------- */
  status = H5Pset_buffer(xfer_list, size, NULL, NULL);
  if (status == FAIL)
    {
      sprintf(errbuf, "Cannot set data buffer for the profile \"%s\". \n", profilename);
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }  

  /* Write data to the dataset */
  /* ------------------------- */
  status = H5Dwrite(dataset, mtype, mspace, space, xfer_list, buffer);
  if (status == FAIL)
    {
      sprintf(errbuf, "Cannot write data to the profile \"%s\". \n", profilename);
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }
  
  
  /* Reclaim the write VL data. */
  /* -------------------------- */ 
  status = H5Dvlen_reclaim(datatype, space, H5P_DEFAULT, buffer);
  if (status == FAIL)
    {
      sprintf(errbuf, "Cannot reclaim the write VL data for the profile \"%s\". \n", profilename);
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }
  
  /* Release the data space ID */
  /* ------------------------- */
  status = H5Sclose(space);
  if (status == FAIL)
    {
      sprintf(errbuf, "Cannot release the file data space ID. \n");
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_DATASPACE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Release the memory data space ID */
  /* -------------------------------- */
  status = H5Sclose(mspace);
  if (status == FAIL)
    {
      sprintf(errbuf, "Cannot release the memory data space ID. \n");
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_DATASPACE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Check if the property list is "on" */
  /* ---------------------------------- */
  if ( HE5_SWXSwath[idx].plist  != FAIL )
    {
      /* Release property list ID */
      /* ------------------------ */
      status = H5Pclose(HE5_SWXSwath[idx].plist);
      if ( status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the property list ID.\n");
	  H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_PLIST, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}

      /* Reset the externally stored property list ID */
      /* -------------------------------------------- */
      HE5_SWXSwath[idx].plist   = FAIL;
	
      /* Reset external array entry */
      /* -------------------------- */
      HE5_SWXSwath[idx].compcode = HE5_HDFE_COMP_NONE;
      
      for (i = 0; i < 5; i++)       
	HE5_SWXSwath[idx].compparm[ i ] = 0;  
 
    }  


  /* Release the xfer property list ID */
  /* --------------------------------- */
  status = H5Pclose(xfer_list);
  if (status == FAIL)
    { 
      sprintf(errbuf, "Cannot release the xfer property list ID. \n");
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_PLIST, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }
  

  /* Release the data type ID */
  /* ------------------------ */
  status = H5Tclose(datatype);
  if (status == FAIL)
    { 
      sprintf(errbuf, "Cannot release the data type ID. \n");
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }
 
  /* Release dataset ID */
  /* ------------------ */
  status = H5Dclose(dataset);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot release dataset ID.\n");
      H5Epush(__FILE__, "HE5_PRwrite", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  

 COMPLETION:
  HE5_UNLOCK;
  return (status);    
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION:  HE5_PRread                                                      |
|                                                                             |
|  DESCRIPTION:  Reads data from the profile dataset.                         |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  status         herr_t                   Return status (0) SUCCEED (-1)     |
|                                          FAIL                               |
|  INPUTS:                                                                    |
|   swathID       hid_t                    Swath ID                           |
|   profilename   const char               Name of profile/dataset            |
|   start         hssize_t                 start array                        |
|   stride        hsize_t                  stride array                       |
|   edge          hsize_t                  edge array                         |
|                                                                             |
|  OUTPUTS:                                                                   |
|   buffer        void                     Data buffer                        |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  Jun 00   A.Muslimov    Original development                                |
|  Jul 00   A.Muslimov    Unmasked hdf5 data types.                           |
|  Jul 00   A.Muslimov    Added calls to H5Tget_super() and EHdtype2mtype()   |
|                          to make sure that the data type ID passed to       |
|                          H5Dread() won't cause a portability problem.       |
|  Sep 00   A.Muslimov    Updated to change "Data Fields" group by "Profile   |
|                          Fields" group.                                     |
|  Dec 00   A.Muslimov    Enhanced to add "start", "stride", and "edge" para- |
|                            meters.                                          |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|  Sep  06  Abe Taaheri   Added H5Dclose to close opened dataset              |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t     
HE5_PRread(hid_t swathID, const char *profilename, const hssize_t start[], const hsize_t stride[], const hsize_t edge[], void *buffer)
{
  herr_t      status      = FAIL;         /* Return status variable    */

  /*  int         mem_used    =  0;*/           /* "Memory allocated"        */
  int         rank        = FAIL;         /* Rank of profile dataset   */

  hid_t       heos_gid    = FAIL;         /* "SWATHS" group ID         */
  hid_t       fid         = FAIL;         /* HDF-EOS file ID           */
  hid_t       dataset     = FAIL;         /* dataset ID                */
  hid_t       plist       = FAIL;         /* Property list ID          */             
  hid_t       type        = FAIL;         /* Datatype ID               */
  hid_t       space       = FAIL;         /* File data space ID        */
  hid_t       mspace      = FAIL;         /* Memory data space ID      */
  hid_t       grp_id      = FAIL;         /* "Data Fields" group ID    */
  hid_t       btype       = FAIL;         /* Base data type ID         */
  hid_t       mbtype      = FAIL;         /* "Memory" base datatype ID */
  hid_t       mtype       = FAIL;         /* "Memory" data type ID     */

  long        idx         = FAIL;         /* Swath index               */

  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer      */
  

  HE5_LOCK;
  CHECKPOINTER(profilename);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_PRread", &fid, &heos_gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for swath ID failed. \n");
      H5Epush(__FILE__, "HE5_PRread", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }


  /* Get "Profile Fields" group ID */
  /* ----------------------------- */
  grp_id = HE5_SWXSwath[idx].prof_id;


  /* Open the Profile dataset */
  /* ------------------------ */ 
  dataset = H5Dopen(grp_id, profilename);
  if (dataset == FAIL)
    {
      status = FAIL;
      sprintf(errbuf,"Cannot open the profile dataset \"%s\". \n", profilename);
      H5Epush(__FILE__, "HE5_PRread", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Get the file data space ID */
  /* -------------------------- */
  space = H5Dget_space(dataset);
  if (space == FAIL)
    {
      status = FAIL;
      sprintf(errbuf,"Cannot get the space ID for the profile dataset \"%s\".\n", profilename);
      H5Epush(__FILE__, "HE5_PRread", __LINE__, H5E_DATASPACE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }
  
  /* Create the property list */
  /* ------------------------ */
  plist = H5Pcreate(H5P_DATASET_XFER);
  if (plist == FAIL)
    {
      status = FAIL;
      sprintf(errbuf,"Cannot create the property list. \n");
      H5Epush(__FILE__, "HE5_PRread", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }
  
  /* Set up memory manager */
  /* --------------------- */ 
  /*
    status = H5Pset_vlen_mem_manager(plist,vltypes_alloc_custom, &mem_used,vltypes_free_custom, &mem_used);
    if (status == FAIL)
    {
    sprintf(errbuf,"Cannot set up the memory manager. \n");
    H5Epush(__FILE__, "HE5_PRread", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
    HE5_EHprint(errbuf, __FILE__, __LINE__);
    return(status);
    } 
  */

  /* Get the datatype ID */
  /* ------------------- */
  type = H5Dget_type(dataset);
  if (type == FAIL)
    {
      status = FAIL;
      sprintf(errbuf,"Cannot get the data type ID.\n");
      H5Epush(__FILE__, "HE5_PRread", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Get the dataset base data type ID */
  /* --------------------------------- */
  btype = H5Tget_super(type);
  if (btype == FAIL)
    {
      status = FAIL;
      sprintf(errbuf,"Cannot get the base data type ID.\n");
      H5Epush(__FILE__, "HE5_PRread", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Get the memory base data type ID */
  /* -------------------------------- */
  mbtype = HE5_EHdtype2mtype(btype);
  if (mbtype == FAIL)
    {
      status = FAIL;
      sprintf(errbuf,"Cannot get the memory data type from the base data type.\n");
      H5Epush(__FILE__, "HE5_PRread", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Create data type ID */
  /* ------------------- */
  mtype  = H5Tvlen_create(mbtype);
  if (mtype == FAIL)
    {
      status = FAIL;
      sprintf(errbuf,"Cannot create data type from the base data type.\n");
      H5Epush(__FILE__, "HE5_PRread", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Get the dataset rank */
  /* -------------------- */
  rank = H5Sget_simple_extent_ndims(space);
  if (rank == FAIL)
    {
      status = FAIL;
      sprintf(errbuf,"Cannot get the dataset rank.\n");
      H5Epush(__FILE__, "HE5_PRread", __LINE__, H5E_DATASPACE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Select the hyperslab */
  /* -------------------- */
  status = H5Sselect_hyperslab(space, H5S_SELECT_SET, (const hsize_t *)start, stride, edge, NULL) ;
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot select the hyperslab.\n");
      H5Epush(__FILE__, "HE5_PRread", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Create the memory dataspace */
  /* --------------------------- */
  mspace = H5Screate_simple(rank, edge, NULL); 
  if (mspace == FAIL)
    {
      status = FAIL;
      sprintf(errbuf,"Cannot create the memory dataspace.\n");
      H5Epush(__FILE__, "HE5_PRread", __LINE__, H5E_DATASPACE, H5E_CANTCREATE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Read out the dataset from the disk  */
  /* ----------------------------------- */
  status = H5Dread(dataset, mtype, mspace, space, plist, buffer);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot read the data from profile dataset \"%s\".\n",profilename);
      H5Epush(__FILE__, "HE5_PRread", __LINE__, H5E_DATASET, H5E_READERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }


  /* Save the IDs for "reclaimspace" */
  /* ------------------------------- */
  profile.plist_id  = plist;
  profile.type_id   = mtype;  
  profile.space_id  = space;


  /* Release "disk" data type ID */
  /* --------------------------- */
  status = H5Tclose(type);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot release data type ID.\n");
      H5Epush(__FILE__, "HE5_PRread", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Release memory space ID */
  /* ----------------------- */
  status = H5Sclose(mspace);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot release memory space ID.\n");
      H5Epush(__FILE__, "HE5_PRread", __LINE__, H5E_DATASPACE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Release base data type ID */
  /* ------------------------- */
  status = H5Tclose(btype);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot release base data type ID.\n");
      H5Epush(__FILE__, "HE5_PRread", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

  /* Release dataset ID */
  /* ------------------ */
  status = H5Dclose(dataset);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot release dataset ID.\n");
      H5Epush(__FILE__, "HE5_PRread", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

 COMPLETION:
  HE5_UNLOCK;
  return (status);    
}

/*
  ------------------------------------------------------------ 
  |       VL datatype custom memory allocation routine       |
  ------------------------------------------------------------
*/ 
/*
  void *vltypes_alloc_custom(size_t size, void *info)
  {
  void   *ret_value = NULL;
  int    *mem_used  = (int *)info;
  size_t extra;

  extra = MAX(sizeof(void *), sizeof(int));
  if ( (ret_value = malloc(extra+size)) != NULL)
  {
  *(int *)ret_value = (int)size;
*mem_used += (int)size;
}
ret_value = ((unsigned char*)ret_value) + extra;
return(ret_value);
}
*/

/*
  ------------------------------------------------------------ 
  |       VL datatype custom memory freeing routine          |
  ------------------------------------------------------------
*/ 
/*
  void vltypes_free_custom(void *_mem, void *info)
  {
  unsigned char  *mem;
  int            *mem_used = (int *)info;
  size_t         extra;

  extra = MAX(sizeof(void *), sizeof(int));
  if (_mem != NULL)
  {
  mem = ((unsigned char *)_mem) - extra;
  *mem_used -= *(int *)mem;
  free(mem);
  } 
  }
*/

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_PRreclaimspace                                               |
|                                                                             |
|  DESCRIPTION:  Reclaims the memory used by the read buffer.                 |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  status         herr_t                   Return status (0) SUCCEED (-1)     |
|                                          FAIL                               |
|  INPUTS:                                                                    |
|   swathID       hid_t                    Swath ID                           |
|   profilename   const char               Name of profile/dataset            |
|                                                                             |
|  OUTPUTS:                                                                   |
|   buffer        void                     Data buffer                        |
|                                                                             |
|  NOTES:                                                                     |
|            After passing to H5Dvlen_reclaim the IDs may change,             |
|             so please use externally stored ID values.                      |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  6/8/00   A.Muslimov    Original development                                |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t     
HE5_PRreclaimspace(hid_t swathID, const char *profilename, void *buffer)
{
  herr_t      status      = FAIL;         /* Return status variable  */
    
  hid_t       heos_gid    = FAIL;         /* "SWATHS" group ID       */
  hid_t       fid         = FAIL;         /* HDF-EOS file ID         */
  hid_t       plist       = FAIL;         /* property list ID        */             
  hid_t       type        = FAIL;         /* datatype ID             */
  hid_t       space       = FAIL;         /* data space ID           */

  long        idx         = FAIL;         /* Swath index             */

  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer    */
  
  HE5_LOCK;
  CHECKPOINTER(buffer);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_PRreclaimspace", &fid, &heos_gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for swath ID failed. \n");
      H5Epush(__FILE__, "HE5_PRreclaimspace", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Get the stored IDs  */
  /* ------------------- */
  type    = profile.type_id;
  space   = profile.space_id;
  plist   = profile.plist_id;
  
  /* Reclaim the data space */
  /* ---------------------- */
  status = H5Dvlen_reclaim(type, space, plist, buffer);
  if (status == FAIL)
    {
      sprintf(errbuf, "Cannot reclaim the memory space. \n");
      H5Epush(__FILE__, "HE5_PRreclaimspace", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }
  
  /* Release property list ID */
  /* ------------------------ */
  status = H5Pclose(profile.plist_id);
  if (status == FAIL)
    {
      sprintf(errbuf, "Cannot release the property list ID. \n");
      H5Epush(__FILE__, "HE5_PRreclaimspace", __LINE__, H5E_PLIST, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Release the data type ID */
  /* ------------------------ */
  status = H5Tclose(profile.type_id);
  if (status == FAIL)
    { 
      sprintf(errbuf, "Cannot release the data type ID. \n");
      H5Epush(__FILE__, "HE5_PRreclaimspace", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Release the data space ID */
  /* ------------------------- */
  status = H5Sclose(profile.space_id);
  if (status == FAIL)
    {
      sprintf(errbuf, "Cannot release the data space ID. \n");
      H5Epush(__FILE__, "HE5_PRreclaimspace", __LINE__, H5E_DATASPACE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Reset IDs for next buffer */
  /* ------------------------- */
  profile.type_id   = FAIL;
  profile.space_id  = FAIL;
  profile.plist_id  = FAIL;

 COMPLETION:    
  HE5_UNLOCK;
  return (status);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION:  HE5_PRinquire                                                   |
|                                                                             |
|  DESCRIPTION:  Retrieves number of profiles in a swath                      |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  nProf          long                     Return number of profiles          |
|                                          FAIL                               |
|  INPUTS:                                                                    |
|    swathID      hid_t                    swath ID                           |
|                                                                             |
|  OUTPUTS:                                                                   |
|    profnames    char                     List of profile names              |
|    rank[]       int                      Profile/dataset rank array         |
|    classID[]    H5T_class_t              Array of profile base datatype IDs |
|                                                                             |
|  NOTES:                                                                     |
|    None                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  8/30/00  A. Muslimov   Original development                                |
|  Sep 00   A. Muslimov   Modified to change "Data Fields" onto "Profile      |
|                                Fields"                                      |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long  
HE5_PRinquire(hid_t swathID, char *profnames, int *rank, H5T_class_t *classID)
{

  long       nProf    = FAIL;            /* Number of profiles        */
  long       idx      = FAIL;            /* Swath index               */

  int        index    = FAIL;            /* Iterator index            */
  int        i;                          /* Loop index                */

  herr_t     status   = FAIL;            /* Status variable           */
   
  hid_t      gid      = FAIL;            /* "SWATHS" group ID         */
  hid_t      fid      = FAIL;            /* HDF-EOS file ID           */
  hid_t      groupID  = FAIL;            /* "Profile Fields" group ID */
  hid_t      profID   = FAIL;            /* Profile dataset ID        */
  hid_t      typeID   = FAIL;            /* Dataset type ID           */
  hid_t      spaceID  = FAIL;            /* Dataset space ID          */
  hid_t      btypeID  = FAIL;            /* Base data type ID         */

  char       errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer      */
  char       *namebuf   = (char *)NULL;  /* Buffer for the list       */
  char       *prname    = (char *)NULL;  /* Buffer for each entry     */    
  char       *comma     = (char *)NULL;  /* Pntr to comma             */  
  char       *groupname = (char *)NULL;  /* Group name string         */

  HE5_OBJINFO    profdata;

  
  /* Initialize the output data structure */
  /* ------------------------------------ */
  profdata.count   = 0;
  profdata.name    = NULL;
  profdata.strsize = 0;

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_PRinquire", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for swath ID failed. \n");
      H5Epush(__FILE__, "HE5_PRinquire", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  groupname = (char *)calloc(HE5_HDFE_NAMBUFSIZE, sizeof(char));
  if (groupname == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for \"groupname\".\n");
      H5Epush(__FILE__, "HE5_PRinquire", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }  

  strcpy(groupname,"/HDFEOS/SWATHS/");
  strcat(groupname, HE5_SWXSwath[idx].swname);
  strcat(groupname,"/Profile Fields");
  
  
  /* Get "Profile Fields" group  ID */
  /* ------------------------------ */
  groupID = HE5_SWXSwath[idx].prof_id;

  index = H5Giterate(groupID,groupname, NULL, HE5_EHobj_info, &profdata);
  if (index < 0)
    {
      sprintf(errbuf,"Iteration through the \"Profile Fields\" group failed.\n");
      H5Epush(__FILE__, "HE5_PRinquire", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(groupname);
      if(profdata.name != NULL ) free(profdata.name);
      return(FAIL);
    }

  free(groupname);

  nProf = profdata.count;
  
  if (profnames != NULL)
    strcpy(profnames,profdata.name);
    
  
  if (rank != NULL || classID != NULL)
    {
      /* Allocate memory for name buffer */
      /* ------------------------------- */
      namebuf = (char *)calloc(strlen(profdata.name)+2, sizeof(char));
      if (namebuf == NULL)
	{
	  sprintf(errbuf,"Cannot allocate memory for \"namebuf\".\n");
	  H5Epush(__FILE__, "HE5_PRinquire", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  if(profdata.name != NULL ) free(profdata.name);
	  return(FAIL);
	}
	  

      strcpy(namebuf, profdata.name);
      strcat(namebuf, ",");
 
      /* Find comma */
      /* ---------- */
      comma = strchr(namebuf, ',');
 
      i = 0;
      /* Parse the list of profiles names */
      /* -------------------------------- */
      while (comma != NULL)
	{
	  /* Copy profile list entry to prname */
	  /* --------------------------------- */
	  prname = (char *)calloc(comma - namebuf + 1, sizeof(char));
	  if (prname == NULL)
	    {
	      sprintf(errbuf,"Cannot allocate memory for \"Profile name\".\n");
	      H5Epush(__FILE__, "HE5_PRinquire", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      if(profdata.name != NULL ) free(profdata.name);
	      if (namebuf != NULL) free(namebuf);
	      return(FAIL);
	    }

	  memmove(prname, namebuf, comma - namebuf);
	  prname[comma-namebuf] = 0;
		  
	  /* Open each profile dataset */
	  /* ------------------------- */
	  profID  = H5Dopen(groupID, prname);
	  if (profID == FAIL)
	    {
	      sprintf(errbuf,"Cannot open the profile \"%s\" dataset.\n", prname);
	      H5Epush(__FILE__, "HE5_PRinquire", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      if (prname != NULL) free(prname);
	      if (namebuf != NULL) free(namebuf);
	      if (profdata.name != NULL ) free(profdata.name);
	      return(FAIL);
	    }

	  if (rank != NULL)
	    {
	      /* Get rank of the dataset */
	      /* ----------------------- */
	      spaceID = H5Dget_space(profID);
	      if (spaceID == FAIL)
		{
		  sprintf(errbuf,"Cannot get data space ID.\n");
		  H5Epush(__FILE__, "HE5_PRinquire", __LINE__, H5E_DATASPACE, H5E_NOTFOUND, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  if (prname != NULL) free(prname);
		  if (namebuf != NULL) free(namebuf);
		  if (profdata.name != NULL ) free(profdata.name);
		  return(FAIL);
		}

	      rank[i] = H5Sget_simple_extent_ndims(spaceID);
	      if (rank[i] == FAIL)
		{
		  sprintf(errbuf,"Cannot get dataset rank.\n");
		  H5Epush(__FILE__, "HE5_PRinquire", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  if (prname != NULL) free(prname);
		  if (namebuf != NULL) free(namebuf);
		  if (profdata.name != NULL ) free(profdata.name);
		  return(FAIL);
		}
			  
	      status  = H5Sclose(spaceID);
	      if (status == FAIL)
		{
		  sprintf(errbuf,"Cannot release data space ID.\n");
		  H5Epush(__FILE__, "HE5_PRinquire", __LINE__, H5E_DATASPACE, H5E_NOTFOUND, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  if (prname != NULL) free(prname);
		  if (namebuf != NULL) free(namebuf);
		  if (profdata.name != NULL ) free(profdata.name);
		  return(FAIL);
		}

	    }

	  if (classID != NULL)
	    {
	      /* Get base data type class ID */
	      /* --------------------------- */
	      typeID     = H5Dget_type(profID);
	      if (typeID == FAIL)
		{
		  sprintf(errbuf,"Cannot get data type ID.\n");
		  H5Epush(__FILE__, "HE5_PRinquire", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  if (prname != NULL) free(prname);
		  if (namebuf != NULL) free(namebuf);
		  if (profdata.name != NULL ) free(profdata.name);
		  return(FAIL);
		}
			  
	      btypeID    = H5Tget_super(typeID);
	      if (btypeID == FAIL)
		{
		  sprintf(errbuf,"Cannot get base data type ID.\n");
		  H5Epush(__FILE__, "HE5_PRinquire", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  if (prname != NULL) free(prname);
		  if (namebuf != NULL) free(namebuf);
		  if (profdata.name != NULL ) free(profdata.name);
		  return(FAIL);
		}

	      /* ------------------------------------------ */
	      /* Call "classID[i] = H5Tget_class(btypeID);" */
	      /*  to get dataset (VL) data type class ID    */
	      /* ------------------------------------------ */

	      classID[i] = H5Tget_class(btypeID);
	      if (classID[i] == H5T_NO_CLASS)
		{
		  sprintf(errbuf,"Cannot get data type class ID.\n");
		  H5Epush(__FILE__, "HE5_PRinquire", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  if (prname != NULL) free(prname);
		  if (namebuf != NULL) free(namebuf);
		  if (profdata.name != NULL ) free(profdata.name);
		  return(FAIL);
		} 
			  
	      status   = H5Tclose(typeID);
	      if (status == FAIL)
		{
		  sprintf(errbuf,"Cannot release data type ID.\n");
		  H5Epush(__FILE__, "HE5_PRinquire", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
		  HE5_EHprint(errbuf, __FILE__, __LINE__);
		  if (prname != NULL) free(prname);
		  if (namebuf != NULL) free(namebuf);
		  if (profdata.name != NULL ) free(profdata.name);
		  return(FAIL);
		}

	    }

	  /* Release dataset ID */
	  /* ------------------ */
	  status = H5Dclose(profID);
	  if (status == FAIL)
	    {
	      sprintf(errbuf,"Cannot release dataset ID.\n");
	      H5Epush(__FILE__, "HE5_PRinquire", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      if (prname != NULL) free(prname);
	      if (namebuf != NULL) free(namebuf);
	      if (profdata.name != NULL ) free(profdata.name);
	      return(FAIL);
	    }
		  

	  /* Go to next list entry, find next comma, ... */
	  /* ------------------------------------------- */ 
	  memmove(namebuf, comma + 1, strlen(comma + 1) + 1); 
	  comma = strchr(namebuf, ',');
	  if (prname != NULL) free(prname);
	  i++; 
	}
	  
      free(namebuf);	  	  
    }
  
  free(profdata.name);
  
  return(nProf);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION:   HE5_PRinfo                                                     |
|                                                                             |
|  DESCRIPTION:  Retrieves information about specified profile.               |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  status         herr_t                   Return status                      |
|                                                                             |
|  INPUTS:                                                                    |
|    swathID      hid_t                    swath ID                           |
|    profname     char                     Profile name                       |
|                                                                             |
|  OUTPUTS:                                                                   |
|    rank[]       int                      Profile/dataset rank array         |
|    dims[]       hsize_t                  dimension size array               |
|    maxdims[]    hsize_t                  max. dimension size array          |
|    ntype[]      hid_t                    Array of profile base numtype IDs  |
|    dimlist      char                     Dimension list                     |
|    maxdimlist   char                     Maximum Dimension List             |
|                                                                             |
|  NOTES:                                                                     |
|    None                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  8/30/00  A. Muslimov   Original development                                |
|  Sep  00  A. Muslimov   Modified to change the group from "Data Fields" to  |
|                          "Profile Fields".                                  |
|  Dec  00  A. Muslimov   Updated to set up "dimlist" and "maxdimlist" strings|
|                          using metadata.                                    |
|  May  03  S. Zhao       Changed the type of 'ntype' from an H5T_class_t to  |
|                         an hid_t.                                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t
HE5_PRinfo(hid_t swathID, const char *profname, int *rank, hsize_t dims[], hsize_t maxdims[], hid_t *ntype, char *dimlist, char *maxdimlist)
{
  herr_t     status   = FAIL;               /* Return status variable                 */
  herr_t     statmeta = FAIL;               /* EHgetmetavalue return status           */

  int        i        = 0;                  /* Loop index                             */

  long       idx      = FAIL;               /* Swath index                            */
  long       ndims    = 0;                  /* Number of dimensions                   */

  hid_t      groupID  = FAIL;               /* "Profile Fields" group ID              */
  hid_t      gid      = FAIL;               /* "SWATHS" group ID                      */
  hid_t      fid      = FAIL;               /* HDF-EOS file ID                        */   
  hid_t      profID   = FAIL;               /* Profile dataset ID                     */
  hid_t      typeID   = FAIL;               /* Dataset type ID                        */
  hid_t      spaceID  = FAIL;               /* Dataset space ID                       */
  hid_t      btypeID  = FAIL;               /* Base data type ID                      */
  H5T_class_t  classid = H5T_NO_CLASS;      /* data type class ID                     */

  size_t     slen[HE5_DTSETRANKMAX];        /* Length of each entry in parsed string  */

  char       *metabuf       = (char *)NULL; /* Ptr to structural metadata (SM)        */
  char       *metaptrs[2]   = {NULL,NULL};  /* Ptrs to the begining and end of SM     */
  char       utlstr[HE5_HDFE_UTLBUFSIZE];   /* Utility string                         */
  char       *ptr[HE5_DTSETRANKMAX];        /* String pointers for parsed string      */
  char       dimstr[HE5_HDFE_DIMBUFSIZE];   /* Individual dimension entry string      */
  char       maxdimstr[HE5_HDFE_DIMBUFSIZE];/* Individual max. dimension entry string */
  char       errbuf[HE5_HDFE_ERRBUFSIZE];   /* Error message buffer                   */

  CHECKPOINTER(profname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_PRinfo", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for swath ID failed. \n");
      H5Epush(__FILE__, "HE5_PRinfo", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Get "Profile Fields" group ID */
  /* ----------------------------- */
  groupID = HE5_SWXSwath[idx].prof_id;

  /* Open specified profile dataset */
  /* ------------------------------ */
  profID     = H5Dopen(groupID, profname);
  if (profID == FAIL)
    {
      sprintf(errbuf,"Cannot open \"%s\" profile.\n", profname);
      H5Epush(__FILE__, "HE5_PRinfo", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    } 

  /* Get data space ID */
  /* ----------------- */
  spaceID    = H5Dget_space(profID);
  if (spaceID == FAIL)
    {
      sprintf(errbuf,"Cannot get data space ID.\n");
      H5Epush(__FILE__, "HE5_PRinfo", __LINE__, H5E_DATASPACE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    } 

  /* Get dataset rank */
  /* ---------------- */
  *rank = H5Sget_simple_extent_dims(spaceID, dims, maxdims);
  if (*rank == FAIL)
    {
      sprintf(errbuf,"Cannot get rank of \"%s\" profile.\n", profname);
      H5Epush(__FILE__, "HE5_PRinfo", __LINE__, H5E_DATASPACE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    } 


  if (ntype != (hid_t *)NULL)
    {
      /* Get data type ID */
      /* ---------------- */
      typeID     = H5Dget_type(profID);
      if (typeID == FAIL)
	{
	  sprintf(errbuf,"Cannot get data type ID.\n");
	  H5Epush(__FILE__, "HE5_PR0info", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	} 
	  
      /* Get base data type ID */
      /* --------------------- */
      btypeID    = H5Tget_super(typeID);  
      if (btypeID == FAIL)
	{
	  sprintf(errbuf,"Cannot get base data type ID.\n");
	  H5Epush(__FILE__, "HE5_PRinfo", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	} 
	  
      /* Get data type class ID */
      /* ---------------------- */
      classid   = H5Tget_class(btypeID);
      if (classid == H5T_NO_CLASS)
	{
	  sprintf(errbuf,"Cannot get data type class ID.\n");
	  H5Epush(__FILE__, "HE5_PRinfo", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	} 

      /* Get base number type ID */
      /* ----------------------- */
      *ntype = HE5_EHdtype2numtype(btypeID);
      if (*ntype == FAIL)
	{
	  sprintf(errbuf,"Cannot get base number type ID.\n");
	  H5Epush(__FILE__, "HE5_PRinfo", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
	  
      /* Release data type ID */
      /* -------------------- */
      status     = H5Tclose(typeID);
      if (status == FAIL)
	{
	  sprintf(errbuf,"Cannot release data type ID.\n");
	  H5Epush(__FILE__, "HE5_PRinfo", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
	  
    }
  
  /* Release data space ID */
  /* --------------------- */
  status     = H5Sclose(spaceID);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot release data space ID.\n");
      H5Epush(__FILE__, "HE5_PRinfo", __LINE__, H5E_DATASPACE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    } 


  /* Release dataset ID */
  /* ------------------ */
  status = H5Dclose(profID);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot release dataset ID.\n");
      H5Epush(__FILE__, "HE5_PRinfo", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }


  /* Get pointers to "Profile Fields" section within SM */
  /* -------------------------------------------------- */
  metabuf = (char *)HE5_EHmetagroup(fid,HE5_SWXSwath[idx].swname,"s","ProfileField",metaptrs);
  if ( metabuf == NULL )
    {
      status = FAIL;
      sprintf(errbuf, "Cannot get pointer to  metabuf.\n");
      H5Epush(__FILE__, "HE5_PRinfo", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }


  sprintf(utlstr, "%s%s%s", "\"", profname, "\"\n");
  
  metaptrs[0] = strstr(metaptrs[0], utlstr);
  
  /* If profile is found in "Profile Fields" group */
  /* --------------------------------------------- */
  if (metaptrs[0] < metaptrs[1] && metaptrs[0] != NULL)
    {
      /* Get "DimList" string, trim off "(" and ")" */
      /* ------------------------------------------ */
      statmeta = HE5_EHgetmetavalue(metaptrs, "DimList", utlstr);
      if (statmeta == SUCCEED)
        {
	  memmove(utlstr, utlstr + 1, strlen(utlstr) - 2);
	  utlstr[strlen(utlstr) - 2] = 0;

	  /* Initialize slen[] array */
	  /* ----------------------- */
	  for ( i = 0; i < HE5_DTSETRANKMAX; i++)
	    slen[ i ] = 0;

	  /* Parse trimmed "DimList" string and get rank */
	  /* ------------------------------------------- */
	  ndims = HE5_EHparsestr(utlstr, ',', ptr, slen);
		  
	  /*------------------------------------------------------------------------------*/
	  /*           Metadata-based rank info (redundant)                               */
	  /*------------------------------------------------------------------------------*/ 
	  /* *rank = HE5_EHlong2int(ndims);                                               */
	  /* if (*rank == FAIL)                                                           */
	  /* {                                                                            */
	  /* sprintf(errbuf, "Cannot convert from \"long\" to \"int\" data type. \n");    */
	  /* H5Epush(__FILE__, "HE5_PRinfo", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);   */
	  /* if (metabuf != NULL) free(metabuf);                                          */
	  /* HE5_EHprint(errbuf, __FILE__, __LINE__);                                     */        
	  /* return(FAIL);                                                                */
	  /* }                                                                            */
	  /*------------------------------------------------------------------------------*/

        }
      else
        {
	  status = FAIL;
	  sprintf(errbuf, "The \"DimList\" string not found in metadata. \n");
	  H5Epush(__FILE__, "HE5_PRinfo", __LINE__, H5E_DATASET, H5E_SEEKERROR, errbuf);
	  if (metabuf != NULL) free(metabuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
        }


      /* If "DimList" IS REQUESTED ...  */
      /* -----------------------------  */
      if (dimlist != NULL) 
	{
	  strcpy(dimstr,"");
	  strcpy(dimlist,"");
			
	  /*
	   * Copy each entry in DimList and remove leading and trailing quotes.
	   * Get dimension sizes and concatenate dimension names to dimension list.
	   */
	  for (i = 0; i < ndims; i++)
	    {
	      memmove(dimstr, ptr[i] + 1, slen[i] - 2);
	      dimstr[slen[i] - 2] = 0;
	      if (i > 0)
		{
		  strcat(dimlist,",");
		}
	      strcat(dimlist, dimstr);
	    }
	}
		

      /* If "MaxdimList" IS REQUESTED  ...      */
      /* -------------------------------------- */
      if(maxdimlist != NULL)
	{
	  strcpy(utlstr,"");
	  statmeta = HE5_EHgetmetavalue(metaptrs,"MaxdimList", utlstr);
	  if (statmeta == SUCCEED)
	    {
	      memmove(utlstr, utlstr + 1, strlen(utlstr) - 2);
	      utlstr[strlen(utlstr) - 2] = 0;
	      ndims = HE5_EHparsestr(utlstr,',', ptr, slen);
	    }
	  else
	    {
	      status = FAIL;
	      sprintf(errbuf, "The \"MaxdimList\" string not found in metadata. \n");
	      H5Epush(__FILE__, "HE5_PRinfo", __LINE__, H5E_DATASET, H5E_SEEKERROR, errbuf);
	      if (metabuf != NULL) free(metabuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(status);
	    }
			
	  strcpy(maxdimstr,"");
	  strcpy(maxdimlist,"");
			
	  for (i = 0; i < ndims; i++)
	    {
	      memmove(maxdimstr, ptr[i] + 1, slen[i] - 2);
	      maxdimstr[slen[i] - 2] = 0;
	      if (maxdimlist != NULL)
		{
		  if (i > 0)
		    {
		      strcat(maxdimlist,",");
		    }
		  strcat(maxdimlist, maxdimstr);
		}
	    }
	}
	  
    }


  if (metabuf != NULL) free(metabuf);

 COMPLETION:
  return(status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_PRwritegrpattr                                               |
|                                                                             |
|  DESCRIPTION: Writes/updates attribute associated with the "Profile Fields" |
|               group in a swath.                                             |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  attrname       char                attribute name                          |
|  numtype        hid_t               attribute dataset datatype ID           |
|  count[]        hsize_t             Number of attribute elements            |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04   S.Zhao        Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_PRwritegrpattr(hid_t swathID, const char *attrname, hid_t numtype, hsize_t  count[], void *datbuf)
{
  herr_t     status          = FAIL;     /* Return status variable    */
 
  hid_t      fid             = FAIL;     /* HDF-EOS file ID           */
  hid_t      gid             = FAIL;     /* "HDFEOS" group ID         */
  hid_t      ProfFieldsGrpID = FAIL;     /* "Profile Fields" group ID */
 
  long       idx             = FAIL;     /* Swath index               */
 
  char       errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer      */
  hid_t      numbertype;
 
  HE5_LOCK;
  CHECKNAME(attrname);
  CHECKPOINTER(count);
  CHECKPOINTER(datbuf);

  /* if numtype is HE5 numbertype, rather than H5 numbertype, then convert
     it, otherwise use numtype itself
  */
  numbertype = HE5_EHconvdatatype(numtype);
  if(numbertype == FAIL)
    {
      numbertype = numtype;
    }

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_PRwritegrpattr", &fid, &gid, &idx);
 
  if (status == SUCCEED)
    {
      /* Get "Profile Fields" group ID and call HE5_EHattr to perform I/O */
      /* ---------------------------------------------------------------- */
      ProfFieldsGrpID = H5Gopen(HE5_SWXSwath[idx].sw_id, "Profile Fields");
      if(ProfFieldsGrpID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"Profile Fields\" group ID. \n");
	  H5Epush(__FILE__, "HE5_PRwritegrpattr", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
 
      status = HE5_EHattr(ProfFieldsGrpID, attrname, numbertype, count,"w", datbuf);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot write attribute \"%s\"to the \"Profile Fields\" group.\n", attrname);
	  H5Epush(__FILE__, "HE5_PRwritegrpattr", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
 
      status = H5Gclose(ProfFieldsGrpID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"Profile Fields\" group ID. \n");
	  H5Epush(__FILE__, "HE5_PRwritegrpattr", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
    }
 
 COMPLETION:
  HE5_UNLOCK;
  return (status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_PRreadgrpattr                                                |
|                                                                             |
|  DESCRIPTION: Reads attribute from the "Profile Fields" group in a swath.   |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  attrname       char                attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04   S.Zhao        Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_PRreadgrpattr(hid_t swathID, const char *attrname, void * datbuf)
{
  herr_t      status          = FAIL;     /* return status variable      */
 
  hid_t       fid             = FAIL;     /* HDF-EOS file ID             */
  hid_t       gid             = FAIL;     /* "HDFEOS" group ID           */
  hid_t       ntype           = FAIL;     /* Data type ID                */
  hid_t       ProfFieldsGrpID = FAIL;     /* "Profile Fields" group ID   */
 
  long        idx             = FAIL;     /* Swath index                 */
 
  hsize_t     count[]         = { 0 };    /* # of attribute elements     */
 
  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer        */
 
 
  HE5_LOCK;
  CHECKPOINTER(attrname);
 
  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_PRreadgrpattr", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Get "Profile Fields"  group ID and call HE5_EHattr to perform I/O */
      /* ----------------------------------------------------------------- */
      ProfFieldsGrpID = H5Gopen(HE5_SWXSwath[idx].sw_id, "Profile Fields");
      if(ProfFieldsGrpID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"Profile Fields\" group ID.\n");
	  H5Epush(__FILE__, "HE5_PRreadgrpattr", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
 
      status = HE5_EHattr(ProfFieldsGrpID,attrname,ntype,count,"r", datbuf);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot read attribute \"%s\" from the \"Profile Fields\" group.\n", attrname);
	  H5Epush(__FILE__, "HE5_PRreadgrpattr", __LINE__, H5E_ATTR, H5E_READERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
 
      status = H5Gclose(ProfFieldsGrpID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"Profile Fields\" group ID.\n");
	  H5Epush(__FILE__, "HE5_PRreadgrpattr", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
 
    }
 
 COMPLETION:
  HE5_UNLOCK;
  return (status);
}
 
 
 
/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_PRgrpattrinfo                                                |
|                                                                             |
|  DESCRIPTION: Retrieves information about attributes in "Profile Fields"    |
|               group.                                                        |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  attrname       const char*         attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  ntype          hid_t               data type ID                            |
|  count          hsize_t             Number of attribute elements            |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04   S.Zhao        Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_PRgrpattrinfo(hid_t swathID, const char *attrname, hid_t *ntype, hsize_t *count)
{
  herr_t     status          = FAIL;     /* routine return status variable    */
 
  hid_t      fid             = FAIL;     /* HDF-EOS file ID                   */
  hid_t      gid             = FAIL;     /* "HDFEOS" group ID                 */
  hid_t      ProfFieldsGrpID = FAIL;     /* "Profile Fields" group ID         */
 
  long       idx             = FAIL;     /* Swath index                       */
 
  char       errbuf[HE5_HDFE_ERRBUFSIZE];/*  Error message buffer             */
 
  CHECKPOINTER(attrname);
 
  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_PRgrpattrinfo", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Get "Profile Fields" group ID and call HE5_EHattrinfo */
      /* ----------------------------------------------------- */
      ProfFieldsGrpID = H5Gopen(HE5_SWXSwath[idx].sw_id, "Profile Fields");
      if(ProfFieldsGrpID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"Profile Fields\" group ID.\n");
	  H5Epush(__FILE__, "HE5_PRgrpattrinfo", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
 
      status = HE5_EHattrinfo(ProfFieldsGrpID,attrname,ntype,count);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot retrieve information about attribute \"%s\" in the \"Profile Fields\" group.\n", attrname);
	  H5Epush(__FILE__, "HE5_PRgrpattrinfo", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
 
      status = H5Gclose(ProfFieldsGrpID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"Profile Fields\" group ID.\n");
	  H5Epush(__FILE__, "HE5_PRgrpattrinfo", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
 
    }
 
 COMPLETION:
  return (status);
}
 
  
 
/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_PRgrpattrinfo2                                               |
|                                                                             |
|  DESCRIPTION: Retrieves information about attributes in "Profile Fields"    |
|               group.                                                        |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  attrname       const char*         attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  ntype          hid_t               data type ID                            |
|  count          hsize_t             Number of attribute elements            |
|  size           hsize_t             buf size of attribute elements          |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04   S.Zhao        Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_PRgrpattrinfo2(hid_t swathID, const char *attrname, hid_t *ntype, hsize_t *count, hsize_t *size)
{
  herr_t     status          = FAIL;     /* routine return status variable    */
 
  hid_t      fid             = FAIL;     /* HDF-EOS file ID                   */
  hid_t      gid             = FAIL;     /* "HDFEOS" group ID                 */
  hid_t      ProfFieldsGrpID = FAIL;     /* "Profile Fields" group ID         */
 
  long       idx             = FAIL;     /* Swath index                       */
 
  char       errbuf[HE5_HDFE_ERRBUFSIZE];/*  Error message buffer             */
 
  CHECKPOINTER(attrname);
 
  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_PRgrpattrinfo2", &fid, &gid, &idx);
  if (status == SUCCEED)
    {
      /* Get "Profile Fields" group ID and call HE5_EHattrinfo */
      /* ----------------------------------------------------- */
      ProfFieldsGrpID = H5Gopen(HE5_SWXSwath[idx].sw_id, "Profile Fields");
      if(ProfFieldsGrpID == FAIL)
	{
	  sprintf(errbuf,"Cannot open the \"Profile Fields\" group ID.\n");
	  H5Epush(__FILE__, "HE5_PRgrpattrinfo2", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
 
      status = HE5_EHattrinfo2(ProfFieldsGrpID,attrname,ntype,count,size);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot retrieve information about attribute \"%s\" in the \"Profile Fields\" group.\n", attrname);
	  H5Epush(__FILE__, "HE5_PRgrpattrinfo2", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
 
      status = H5Gclose(ProfFieldsGrpID);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot release the \"Profile Fields\" group ID.\n");
	  H5Epush(__FILE__, "HE5_PRgrpattrinfo2", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(status);
	}
 
    }
 
 COMPLETION:
  return (status);
}
 
 
/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_PRinqgrpattrs                                                |
|                                                                             |
|  DESCRIPTION:  Retrieves the number of attributes and string length of      |
|                attribute list in "Profile Fields" group                     |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nattr          long                Number of attributes in "Profile Fields"|
|                                     group.                                  |
|                                                                             |
|  INPUTS:                                                                    |
|  swath ID       hid_t               swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  attrnames      char                Attribute names in "Profile Fields"     |
|                                     group (Comma-separated list)            |
|  strbufsize     long                Attributes name list string length      |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04   S.Zhao        Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long
HE5_PRinqgrpattrs(hid_t swathID, char *attrnames, long *strbufsize)
{
  long            nattr   = FAIL;             /* Number of attributes (return)  */
  long            idx     = FAIL;             /* Swath index                    */
 
  herr_t          status  = FAIL;             /* Return status variable         */
 
  hid_t           fid     = FAIL;             /* HDF-EOS file ID                */
  hid_t           gid     = FAIL;             /* "SWATHS" group ID              */
 
  char            *grpname = (char *)NULL;    /* Group name string              */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer           */
 
 
 
  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_PRinqgrpattrs", &fid, &gid, &idx);
  if(status == SUCCEED )
    {
      grpname = (char *)calloc(HE5_HDFE_NAMBUFSIZE, sizeof(char) );
      if( grpname == NULL)
	{
	  sprintf(errbuf, "Cannot allocate memory. \n");
	  H5Epush(__FILE__, "HE5_PRinqgrpattrs", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
 
      strcpy(grpname,"/HDFEOS/SWATHS/");
      strcat(grpname, HE5_SWXSwath[idx].swname);
      strcat(grpname,"/Profile Fields");
 
      /* search group with grpname for the number of attributes */
      /* ------------------------------------------------------ */
      nattr = HE5_EHattrcat(fid,  grpname, attrnames, strbufsize);
      if ( nattr < 0 )
	{
	  sprintf(errbuf, "Cannot find the attributes. \n");
	  H5Epush(__FILE__, "HE5_PRinqgrpattrs", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	}
 
      if (grpname != NULL) free(grpname);
    }
 
  return (nattr);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWsetalias                                                   |
|                                                                             |
|  DESCRIPTION:  Defines alias for a specified field name                     |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  status         herr_t                   Return status                      |
|                                                                             |
|  INPUTS:                                                                    |
|    swathID      hid_t                    swath ID                           |
|    fieldname    char                     Original field name                |
|                                                                             |
|  OUTPUTS:                                                                   |
|    aliaslist    char                     List of aliases for the field name |
|                                                                             |
|  NOTES:                                                                     |
|    None                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  Sep  00  A. Muslimov   Original development                                |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t 
HE5_SWsetalias(hid_t swathID, char *fieldname, const char *aliaslist)
{
  herr_t   status     = FAIL;          /* return status variable      */

  int      fldgroup   = FAIL;          /* Field group flag            */

  hid_t    fid        = FAIL;          /* HDF-EOS file ID             */
  hid_t    gid        = FAIL;          /* "SWATHS"  group ID          */
  hid_t    groupID    = FAIL;          /* Field group ID              */

  long     idx        = FAIL;          /* Swath index                 */

  char     *buf       = NULL;          /* Pointer to temporary buffer */
  char     *comma     = NULL;          /* Pointer to comma            */
  char     *aliasname = NULL;          /* Pointer to the alias name   */
  char     errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer        */


  HE5_LOCK;
  CHECKPOINTER(fieldname);
  CHECKPOINTER(aliaslist);


  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWsetalias", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for swath ID failed. \n");
      H5Epush(__FILE__, "HE5_SWsetalias", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Find out the field group */
  /* ------------------------ */
  fldgroup = HE5_SWfldsrch(swathID,fieldname,NULL,NULL,NULL,NULL);

  if (fldgroup == HE5_HDFE_GEOGROUP)
    groupID = HE5_SWXSwath[idx].geo_id;

  else if (fldgroup == HE5_HDFE_DATAGROUP)
    groupID = HE5_SWXSwath[idx].data_id;

  else if (fldgroup == HE5_HDFE_PROFGROUP)
    groupID = HE5_SWXSwath[idx].prof_id;
  
  else
    {	  
      sprintf(errbuf, "Cannot find \"%s\" field in swath. \n", fieldname);
      H5Epush(__FILE__, "HE5_SWsetalias", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }


  /* Allocate memory for temporary buffer */
  /* ------------------------------------ */
  buf = (char *)calloc(strlen(aliaslist)+64, sizeof(char));
  if (buf == NULL)
    {
      sprintf(errbuf, "Cannot alocate memory for \"buf\". \n");
      H5Epush(__FILE__, "HE5_SWsetalias", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  

  /* Make a list like "name1,name2,name3," */
  /* ------------------------------------- */
  strcpy(buf,aliaslist);
  strcat(buf,",");

  /* Find first comma and make pointer pointing to it */
  /* ------------------------------------------------ */
  comma = strchr(buf, ',');
  while(comma != NULL)
    {
      /* Allocate memory for individual entry */
      /* ------------------------------------ */
      aliasname = (char *)calloc(comma-buf+1, sizeof(char));
      if (aliasname == NULL)
	{
	  sprintf(errbuf, "Cannot alocate memory for \"aliasname\". \n");
	  H5Epush(__FILE__, "HE5_SWsetalias", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  if (buf != NULL) free(buf);
	  return(FAIL);
	}
	  
      /* Pick up an individual entry and put it to the "aliasname" */
      /* --------------------------------------------------------- */
      memmove(aliasname,buf,comma-buf);
  
      /* Create a symbolic link for a specified object */
      /* --------------------------------------------- */
      status = H5Glink(groupID, H5G_LINK_SOFT, fieldname, aliasname);
      if (status == FAIL)
	{
	  sprintf(errbuf, "Cannot create an alias \"%s\" for \"%s\" field. \n", aliasname, fieldname);
	  H5Epush(__FILE__, "HE5_SWsetalias", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  if (aliasname != NULL) free(aliasname);
	  if (buf != NULL) free(buf);
	  return(FAIL);
	}
  
      /* Go to the next name entry */
      /* ------------------------- */
      memmove(buf, comma + 1, strlen(comma + 1) + 1); 
      comma = strchr(buf, ',');
      if (aliasname != NULL) free(aliasname);
    }
  
  if (buf != NULL) free(buf);
	  
 COMPLETION:
  HE5_UNLOCK;
  return(status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdropalias                                                  |
|                                                                             |
|  DESCRIPTION:  Removes the alias for a specified field name                 |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  status         herr_t                   Return status                      |
|                                                                             |
|  INPUTS:                                                                    |
|    swathID      hid_t                    swath ID                           |
|    aliasname    char                     alias name to remove               |
|    fldgroup     int                      Field group flag                   |
|                                                                             |
|  OUTPUTS:                                                                   |
|                                                                             |
|  NOTES:                                                                     |
|    None                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  Sep  00  A. Muslimov   Original development                                |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t 
HE5_SWdropalias(hid_t swathID, int fldgroup, const char *aliasname)
{  
  herr_t   status     = FAIL;          /* return status variable   */

  hid_t    fid        = FAIL;          /* HDF-EOS file ID          */
  hid_t    gid        = FAIL;          /* "SWATHS"  group ID       */
  hid_t    groupID    = FAIL;          /* Field group ID           */

  long     idx        = FAIL;          /* Swath index              */

  char     errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer     */


  HE5_LOCK;
  CHECKPOINTER(aliasname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWdropalias", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for swath ID failed. \n");
      H5Epush(__FILE__, "HE5_SWdropalias", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Get Group ID */
  /* ------------ */
  if (fldgroup == HE5_HDFE_GEOGROUP)
    groupID = HE5_SWXSwath[idx].geo_id;
  else if (fldgroup == HE5_HDFE_DATAGROUP)
    groupID = HE5_SWXSwath[idx].data_id;
  else if (fldgroup == HE5_HDFE_PROFGROUP)
    groupID = HE5_SWXSwath[idx].prof_id;
  else
    {	  
      sprintf(errbuf, "Invalid input group flag. \n");
      H5Epush(__FILE__, "HE5_SWdropalias", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Destroy a symbolic link */
  /* ----------------------- */
  status = H5Gunlink(groupID, aliasname);
  if (status == FAIL)
    {	  
      sprintf(errbuf, "Cannot remove alias named \"%s\". \n", aliasname);
      H5Epush(__FILE__, "HE5_SWdropalias", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

 COMPLETION:
  HE5_UNLOCK;
  return(status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqdfldalias                                               |
|                                                                             |
|  DESCRIPTION:  Retrieves the number of fields & aliases and string length of|
|                fields & aliases list in "Data Fields" group                 |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nfldalias      long                Number of fields & aliases in "Data     |
|                                     Fields" group.                          |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  fldalias       char*               Fields & aliases names in "Data Fields" |
|                                     group (Comma-separated list)            |
|  strbufsize     long*               Fields & aliases name list string length|
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Mar 03    S.Zhao       Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long
HE5_SWinqdfldalias(hid_t swathID, char *fldalias, long *strbufsize)
{
  long            nfldalias   = FAIL;         /* Number of fields & aliases (return)  */
  long            idx     = FAIL;             /* Swath index                    */
 
  herr_t          status  = FAIL;             /* Return status variable         */
 
  hid_t           fid     = FAIL;             /* HDF-EOS file ID                */
  hid_t           gid     = FAIL;             /* "SWATHS" group ID              */
 
  char            *grpname = (char *)NULL;    /* Group name string              */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer           */
 
 
  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWinqdfldalias", &fid, &gid, &idx);
  if(status == SUCCEED )
    {
      grpname = (char *)calloc(HE5_HDFE_NAMBUFSIZE, sizeof(char) );
      if( grpname == NULL)
	{
	  H5Epush(__FILE__, "HE5_SWinqdfldalias", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Can not allocate memory");
	  HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	  return(FAIL);
	}
 
      strcpy(grpname,"/HDFEOS/SWATHS/");
      strcat(grpname, HE5_SWXSwath[idx].swname);
      strcat(grpname,"/Data Fields");
 
      /* search group with grpname for the number of fields & aliases */
      /* ------------------------------------------------------------ */
      nfldalias = HE5_EHdatasetcat(fid,  grpname, fldalias, strbufsize);
      if ( nfldalias < 0 )
	{
	  sprintf(errbuf, "Cannot find the fields & aliases. \n");
	  H5Epush(__FILE__, "HE5_SWinqdfldalias", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	}
 
      if (grpname != NULL) free(grpname);
    }
  else
    {
      sprintf(errbuf, "Checking for swath ID failed. \n");
      H5Epush(__FILE__, "HE5_SWinqdfldalias", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
 
  return (nfldalias);
}
 

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqgfldalias                                               |
|                                                                             |
|  DESCRIPTION:  Retrieves the number of fields & aliases and string length of|
|                fields & aliases list in "Geolocation Fields" group          |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nfldalias      long                Number of fields & aliases in "Geo-     |
|                                     location Fields" group.                 |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  fldalias       char*               Fields & aliases names in "Geolocation  |
|                                     Fields" group (Comma-separated list)    |
|  strbufsize     long*               Fields & aliases name list string length|
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Apr 03    S.Zhao       Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long
HE5_SWinqgfldalias(hid_t swathID, char *fldalias, long *strbufsize)
{
  long            nfldalias   = FAIL;         /* Number of fields & aliases (return)  */
  long            idx     = FAIL;             /* Swath index                    */
 
  herr_t          status  = FAIL;             /* Return status variable         */
 
  hid_t           fid     = FAIL;             /* HDF-EOS file ID                */
  hid_t           gid     = FAIL;             /* "SWATHS" group ID              */
 
  char            *grpname = (char *)NULL;    /* Group name string              */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer           */
 
 
  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWinqgfldalias", &fid, &gid, &idx);
  if(status == SUCCEED )
    {
      grpname = (char *)calloc(HE5_HDFE_NAMBUFSIZE, sizeof(char) );
      if( grpname == NULL)
	{
	  H5Epush(__FILE__, "HE5_SWinqgfldalias", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Can not allocate memory");
	  HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
	  return(FAIL);
	}
 
      strcpy(grpname,"/HDFEOS/SWATHS/");
      strcat(grpname, HE5_SWXSwath[idx].swname);
      strcat(grpname,"/Geolocation Fields");
 
      /* search group with grpname for the number of fields & aliases */
      /* ------------------------------------------------------------ */
      nfldalias = HE5_EHdatasetcat(fid,  grpname, fldalias, strbufsize);
      if ( nfldalias < 0 )
	{
	  sprintf(errbuf, "Cannot find the fields & aliases. \n");
	  H5Epush(__FILE__, "HE5_SWinqgfldalias", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(grpname);
	}
 
      if (grpname != NULL) free(grpname);
    }
  else
    {
      sprintf(errbuf, "Checking for swath ID failed. \n");
      H5Epush(__FILE__, "HE5_SWinqgfldalias", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  return (nfldalias);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWaliasinfo                                                  |
|                                                                             |
|  DESCRIPTION:  Retrieves information about field aliases                    |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  status         herr_t                   Return status                      |
|                                                                             |
|  INPUTS:                                                                    |
|    swathID      hid_t                    swath ID                           |
|    aliasname    char                     alias name                         |
|    fldgroup     int                      Field group flag                   |
|                                                                             |
|  OUTPUTS:                                                                   |
|    length       int                      Buffer size                        |
|    buffer       char                     Buffer with original field name    |
|                                                                             |
|  NOTES:                                                                     |
|    None                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  Sep  00  A. Muslimov   Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t 
HE5_SWaliasinfo(hid_t swathID, int fldgroup, const char *aliasname, int *length, char *buffer)
{
  herr_t        status     = FAIL;               /* return status variable   */

  int           type       = FAIL;               /* type-value of an object  */

  size_t        size       = 0;                  /* Size of the name buffer  */

  hid_t         fid        = FAIL;               /* HDF-EOS file ID          */
  hid_t         gid        = FAIL;               /* "SWATHS"  group ID       */
  hid_t         groupID    = FAIL;               /* Field group ID           */

  long          idx        = FAIL;               /* Swath index              */

  H5G_stat_t    *statbuf   = (H5G_stat_t *)NULL; /* pointer to a structure   */

  char          errbuf[HE5_HDFE_ERRBUFSIZE];     /* Error message buffer     */

  CHECKPOINTER(aliasname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWaliasinfo", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for swath ID failed. \n");
      H5Epush(__FILE__, "HE5_SWaliasinfo", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }


  /* Get the group ID */
  /* ---------------- */
  if (fldgroup == HE5_HDFE_GEOGROUP)
    groupID = HE5_SWXSwath[idx].geo_id;
  else if (fldgroup == HE5_HDFE_DATAGROUP)
    groupID = HE5_SWXSwath[idx].data_id;
  else if (fldgroup == HE5_HDFE_PROFGROUP)
    groupID = HE5_SWXSwath[idx].prof_id;
  else
    {	  
      sprintf(errbuf, "Invalid input group flag. \n");
      H5Epush(__FILE__, "HE5_SWaliasinfo", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  if (buffer == NULL)
    {
      /* Get the string length of a "real" name  */
      /* --------------------------------------  */
      statbuf = (H5G_stat_t *)calloc(1, sizeof(H5G_stat_t));   
      if (statbuf == NULL)
	{
	  sprintf(errbuf, "Cannot allocate memory for \"statbuf\". \n");
	  H5Epush(__FILE__, "HE5_SWaliasinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}

      /* Get the Object Info */
      /* ------------------- */
      status = H5Gget_objinfo(groupID, aliasname, 0, statbuf);
      if (status == FAIL)
	{
	  sprintf(errbuf, "Cannot get information about \"%s\" alias. \n", aliasname);
	  H5Epush(__FILE__, "HE5_SWaliasinfo", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}

      /* LINK name length with a null terminator */
      /* --------------------------------------- */
      size = statbuf->linklen;

      /* Object type (dataset, link, etc) */
      /* -------------------------------- */
      type   = statbuf->type;
  
      /* Make sure that the object is a LINK */
      /* ----------------------------------- */
      if (type != H5G_LINK)
	{
	  sprintf(errbuf,"The object named \"%s\" is not a symbolic link.\n", aliasname);
	  H5Epush(__FILE__, "HE5_SWaliasinfo", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
	  
      *length = (int)size;
	  
      if ( statbuf != (H5G_stat_t *)NULL ) free(statbuf);
	  
    }
  
  if (buffer != NULL)
    {
      size = (size_t)*length;
	  
      /* Get the "real" name by an "alias" */
      /* --------------------------------- */
      status = H5Gget_linkval(groupID, aliasname, size, buffer);
      if (status == FAIL) 
	{
	  sprintf(errbuf,"Cannot get the real name for the alias named \"%s\".\n", aliasname);
	  H5Epush(__FILE__, "HE5_SWaliasinfo", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
    }
  
 COMPLETION:
  return(status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWgetaliaslist                                               |
|                                                                             |
|  DESCRIPTION:  Retrieves the number of aliases and the list of aliases in   |
|                swath                                                        |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nalias         long                number of aliases in swath              |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  fldgroup       int                 field group flag (geo or data)          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  aliaslist      char*               list of aliases (comma-separated list)  |
|  strbufsize     long*               length of aliases list                  |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Jun 05    S.Zhao       Original development                                |
|  Mar 06    Abe Taaheri  Added code to get alias strbufsize only when user   |
|                         passes aliaslist as NULL pointer                    |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long
HE5_SWgetaliaslist(hid_t swathID, int fldgroup, char *aliaslist, long *strbufsize)
{
  long            nalias  = FAIL;             /* Number of aliases (return)  */
  long            idx     = FAIL;             /* Swath index                 */

  herr_t          status  = FAIL;             /* Return status variable      */
  hid_t           fid     = FAIL;             /* HDF-EOS file ID             */
  hid_t           gid     = FAIL;             /* "SWATHS" group ID           */
  char            *fieldlist = (char *)NULL;  /* List of fields              */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer        */
  long            fldstrbuf = FAIL;           /* Buffer size for fields      */
  long            nflds   = FAIL;             /* Number of fields            */
  long            nfldalias = FAIL;           /* Number of fields & aliases  */
  char            *fldalias = (char *)NULL;   /* List of fields & aliases    */
  long            fldaliasbuf = FAIL;         /* Buffer size for fields & 
						 aliases */
  char            *buff   = (char *)NULL;     /* Pointer to temporary buffer */
  char            *comma  = (char *)NULL;     /* Pointer to comma            */
  char            *comma1 = (char *)NULL;     /* Pointer to comma            */
  char            *nameptr = (char *)NULL;    /* Pointer to each name        */
  char            *tmpbuf  = (char *)NULL;    /* Pointer to temp buffer      */
  long            nameflag = FAIL;            /* Name flag                   */

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWgetaliaslist", &fid, &gid, &idx);
  if(status == SUCCEED )
    {
      /* If aliaslist and strbufsize desired */
      /* ----------------------------------- */
      if (fldgroup == HE5_HDFE_DATAGROUP)
	{
          /* Call "HE5_SWnentries" routine to get number of Data fields */
          /* ---------------------------------------------------------- */
          nflds = HE5_SWnentries(swathID, HE5_HDFE_NENTDFLD, &fldstrbuf);
          if (nflds == FAIL)
	    {
	      sprintf(errbuf, "Cannot get the number of fields in \"Data Fields\" group. \n");
	      H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
		      H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(FAIL);
	    }
	  
          /* Allocate memory for fields list buffer */
          /* -------------------------------------- */
          fieldlist = (char *) calloc(fldstrbuf+6, sizeof(char));
          if(fieldlist == NULL)
	    {
	      sprintf(errbuf,"Cannot allocate memory.\n");
	      H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
		      H5E_RESOURCE, H5E_NOSPACE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(FAIL);
	    }
	  
          /* Call "HE5_SWinqdatafields" routine to get the list of Data 
	     fields */
          /* --------------------------------------------------------- */
          nflds = HE5_SWinqdatafields(swathID, fieldlist, NULL, NULL);
          if (nflds == FAIL)
	    {
	      sprintf(errbuf, "Cannot get the list of fields in \"Data Fields\" group. \n");
	      H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
		      H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(fieldlist);
	      return(FAIL);
	    }
	  
          /* Call "HE5_SWinqdfldalias" routine to get number of fields & 
	     aliases */
          /* --------------------------------------------------------- */
          nfldalias = HE5_SWinqdfldalias(swathID, NULL, &fldaliasbuf);
          if (nfldalias == FAIL)
	    {
	      sprintf(errbuf, "Cannot get the number of fields & aliases in \"Data Fields\" group. \n");
	      H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
		      H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(fieldlist);
	      return(FAIL);
	    }
	  
          /* Allocate memory for fields & aliases list buffer */
          /* ------------------------------------------------ */
          fldalias = (char *) calloc(fldaliasbuf+6, sizeof(char));
          if(fldalias == NULL)
	    {
	      sprintf(errbuf,"Cannot allocate memory.\n");
	      H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
		      H5E_RESOURCE, H5E_NOSPACE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(fieldlist);
	      return(FAIL);
	    }
	  
          /* Call "HE5_SWinqdfldalias" routine to get the list of fields & 
	     aliases */
          /* ----------------------------------------------------------- */
          nfldalias = HE5_SWinqdfldalias(swathID, fldalias, &fldaliasbuf);
          if (nfldalias == FAIL)
	    {
	      sprintf(errbuf, "Cannot get the list of fields & aliases in \"Data Fields\" group. \n");
	      H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
		      H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(fieldlist);
	      free(fldalias);
	      return(FAIL);
	    } 
        }
      else if (fldgroup == HE5_HDFE_GEOGROUP)
        {
          /* Call "HE5_SWnentries" routine to get number of Geolocation 
	     fields */
          /* --------------------------------------------------------- */
          nflds = HE5_SWnentries(swathID, HE5_HDFE_NENTGFLD, &fldstrbuf);
          if (nflds == FAIL)
	    {
	      sprintf(errbuf, "Cannot get the number of fields in \"Geolocation Fields\" group. \n");
	      H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
		      H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(FAIL);
	    }
	  
          /* Allocate memory for fields list buffer */
          /* -------------------------------------- */
          fieldlist = (char *) calloc(fldstrbuf+6, sizeof(char));
          if(fieldlist == NULL)
	    {
	      sprintf(errbuf,"Cannot allocate memory.\n");
	      H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
		      H5E_RESOURCE, H5E_NOSPACE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(FAIL);
	    }
	  
          /* Call "HE5_SWinqgeofields" routine to get the list of 
	     Geolocation fields */
          /* -------------------------------------------------- */
          nflds = HE5_SWinqgeofields(swathID, fieldlist, NULL, NULL);
          if (nflds == FAIL)
	    {
	      sprintf(errbuf, "Cannot get the list of fields in \"Geolocation Fields\" group. \n");
	      H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
		      H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(fieldlist);
	      return(FAIL);
	    }
	  
          /* Call "HE5_SWinqgfldalias" routine to get number of fields & 
	     aliases */
          /* --------------------------------------------------------- */
          nfldalias = HE5_SWinqgfldalias(swathID, NULL, &fldaliasbuf);
          if (nfldalias == FAIL)
	    {
	      sprintf(errbuf, "Cannot get the number of fields & aliases in \"Geolocation Fields\" group. \n");
	      H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
		      H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(fieldlist);
	      return(FAIL);
	    }
	  
          /* Allocate memory for fields & aliases list buffer */
          /* ------------------------------------------------ */
          fldalias = (char *) calloc(fldaliasbuf+6, sizeof(char));
          if(fldalias == NULL)
	    {
	      sprintf(errbuf,"Cannot allocate memory.\n");
	      H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
		      H5E_RESOURCE, H5E_NOSPACE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(fieldlist);
	      return(FAIL);
	    }
	  
          /* Call "HE5_SWinqgfldalias" routine to get the list of fields & 
	     aliases */
          /* ----------------------------------------------------------- */
          nfldalias = HE5_SWinqgfldalias(swathID, fldalias, &fldaliasbuf);
          if (nfldalias == FAIL)
	    {
	      sprintf(errbuf, "Cannot get the list of fields & aliases in \"Geolocation Fields\" group. \n");
	      H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
		      H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(fieldlist);
	      free(fldalias);
	      return(FAIL);
	    }
        }
      else
        {
          sprintf(errbuf, "Invalid input group flag. \n");
          H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
		  H5E_OHDR, H5E_NOTFOUND, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          return(FAIL);
        }
      
      *strbufsize = strlen(fldalias) - strlen(fieldlist);
      if (*strbufsize <= 0)
        {
          sprintf(errbuf, "Cannot find the aliases.\n");
          H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
		  H5E_OHDR, H5E_NOTFOUND, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          if(fieldlist != NULL) free(fieldlist);
          if(fldalias != NULL) free(fldalias);
          return(FAIL);
        }
      else
        {
          nalias = 0;
	  
          /* Allocate memory for temporary buffer */
          /* ------------------------------------ */
          buff = (char *)calloc(strlen(fldalias)+6, sizeof(char));
          if (buff == NULL)
            {
	      sprintf(errbuf, "Cannot allocate memory for \"buff\". \n");
	      H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
		      H5E_RESOURCE, H5E_NOSPACE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      if(fieldlist != NULL) free(fieldlist);
	      if(fldalias != NULL) free(fldalias);
	      return(FAIL);
            }
	  
          /* Allocate memory for aliases */
          /* --------------------------- */
          tmpbuf = (char *)calloc(*strbufsize+6, sizeof(char));
          if (tmpbuf == NULL)
            {
              sprintf(errbuf, "Cannot allocate memory for \"tmpbuf\". \n");
              H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
		      H5E_RESOURCE, H5E_NOSPACE, errbuf);
              HE5_EHprint(errbuf, __FILE__, __LINE__);
              if(fieldlist != NULL) free(fieldlist);
              if(fldalias != NULL) free(fldalias);
              if(buff != NULL) free(buff);
              return(FAIL);
            }
	  
          strcpy(buff, fldalias);
          strcat(buff, ",");
          strcat(fieldlist, ",");
	  
          /* Find first comma and make pointer pointing to it */
          /* ------------------------------------------------ */
          comma = strchr(buff, ',');
          while(comma != NULL)
            {
              /* Allocate memory for individual entry */
              /* ------------------------------------ */
              nameptr = (char *)calloc(comma-buff+6, sizeof(char));
              if (nameptr == NULL)
		{
                  sprintf(errbuf,"Cannot allocate memory for \"nameptr\". \n");
                  H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
			  H5E_RESOURCE, H5E_NOSPACE, errbuf);
                  HE5_EHprint(errbuf, __FILE__, __LINE__);
                  if(fieldlist != NULL) free(fieldlist);
                  if(fldalias != NULL) free(fldalias);
                  if(buff != NULL) free(buff);
                  if(tmpbuf != NULL) free(tmpbuf);
                  return(FAIL);
		}
	      
              /* Pick up an individual entry and put it to the "nameptr" */
              /* ------------------------------------------------------- */
              memmove(nameptr,buff,comma-buff);
              strcat(nameptr, ",");
	      
              nameflag = (strstr(fieldlist,nameptr) == NULL) ? 1 : 0;
              if (nameflag == 1)
		{
                  comma1 = strchr(tmpbuf, ',');
                  if(comma1 == NULL)
		    strcpy(tmpbuf, nameptr);
                  else
		    strcat(tmpbuf, nameptr);
		  
                  nalias++;
		}
	      
	      memmove(buff, comma + 1, strlen(comma + 1) + 1); 
              comma = strchr(buff, ',');
	      
              if (nameptr != NULL) free(nameptr);
	    }
	}

      if(aliaslist == NULL)/* just return buffersize 
			      and number of aliases */
	{
	  if(nalias > 0 )
	    {
	      if (fieldlist != NULL) free(fieldlist);
	      if (fldalias != NULL) free(fldalias);
	      if (buff != NULL) free(buff);
	      if (tmpbuf != NULL) free(tmpbuf);
	      return (nalias);
	    }
	  else
	    {
	      sprintf(errbuf, "Cannot find the aliases.\n");
	      H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
		      H5E_OHDR, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      if(fieldlist != NULL) free(fieldlist);
	      if(fldalias != NULL) free(fldalias);
	      if (buff != NULL) free(buff);
	      if (tmpbuf != NULL) free(tmpbuf);
	      return(FAIL);
	    }
	}
      else
	{
	  if(nalias > 0 )
	    {
	      strncpy(aliaslist, tmpbuf, *strbufsize-1);
	      aliaslist[*strbufsize-1] = '\0';
	    }
	  else
	    {
	      sprintf(errbuf, "Cannot find the aliases.\n");
	      H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
		      H5E_OHDR, H5E_NOTFOUND, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      if(fieldlist != NULL) free(fieldlist);
	      if(fldalias != NULL) free(fldalias);
	      if (buff != NULL) free(buff);
	      if (tmpbuf != NULL) free(tmpbuf);
	      return(FAIL);
	    }
	}
    }
  else
    {
      sprintf(errbuf, "Checking for swath ID failed. \n");
      H5Epush(__FILE__, "HE5_SWgetaliaslist", __LINE__, 
	      H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
  if (fieldlist != NULL) free(fieldlist);
  if (fldalias != NULL) free(fldalias);
  if (buff != NULL) free(buff);
  if (tmpbuf != NULL) free(tmpbuf);

  return (nalias);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWfldrename                                                  |
|                                                                             |
|  DESCRIPTION:  Changes the field name                                       |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  status         herr_t                   Return status                      |
|                                                                             |
|  INPUTS:                                                                    |
|    swathID      hid_t                    swath ID                           |
|    oldfieldname char                     Original field name                |
|                                                                             |
|  OUTPUTS:                                                                   |
|    newfieldname char                     New field name                     |
|                                                                             |
|  NOTES:                                                                     |
|    None                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  Sep  00  A. Muslimov   Original development                                |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t 
HE5_SWfldrename(hid_t swathID, char *oldfieldname, const char *newfieldname)
{
  
  herr_t   status     = FAIL;          /* Return status variable */

  int      fldgroup   = FAIL;          /* Field group flag       */
  int      k;                          /* Loop index             */

  hid_t    fid        = FAIL;          /* HDF-EOS file ID        */
  hid_t    gid        = FAIL;          /* "SWATHS"  group ID     */
  hid_t    groupID    = FAIL;          /* Field group ID         */

  long     idx        = FAIL;          /* Swath index            */

  char     errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer   */



  HE5_LOCK;
  CHECKPOINTER(oldfieldname);
  CHECKNAME(newfieldname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWfldrename", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for swath ID failed. \n");
      H5Epush(__FILE__, "HE5_SWfldrename", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Find out the field group */
  /* ------------------------ */
  fldgroup = HE5_SWfldsrch(swathID,oldfieldname,NULL,NULL,NULL,NULL);
  if (fldgroup == HE5_HDFE_GEOGROUP)
    groupID = HE5_SWXSwath[idx].geo_id;
  else if (fldgroup == HE5_HDFE_DATAGROUP)
    groupID = HE5_SWXSwath[idx].data_id;
  else if (fldgroup == HE5_HDFE_PROFGROUP)
    groupID = HE5_SWXSwath[idx].prof_id;
  else
    {	  
      sprintf(errbuf, "Error returning field group flag. \n");
      H5Epush(__FILE__, "HE5_SWfldrename", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Rename the field */
  /* ---------------- */
  status = H5Gmove(groupID, oldfieldname, newfieldname);
  if (status == FAIL)
    {	  
      sprintf(errbuf, "Cannot change the field name from \"%s\" to \"%s\". \n", oldfieldname, newfieldname);
      H5Epush(__FILE__, "HE5_SWfldrename", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
  /* Update Table */
  /* ------------ */
  if (fldgroup == HE5_HDFE_DATAGROUP)
    {
      for (k = 0; k < HE5_SWXSwath[idx].nDFLD; k++)
	{
	  if (strcmp(HE5_SWXSwath[idx].ddataset[k].name, oldfieldname) == 0 )
	    strcpy(HE5_SWXSwath[idx].ddataset[k].name, newfieldname);
	}
    }

  if (fldgroup == HE5_HDFE_GEOGROUP)
    {
      for(k = 0; k < HE5_SWXSwath[idx].nGFLD; k++)
	{
	  if (strcmp(HE5_SWXSwath[idx].gdataset[k].name, oldfieldname) == 0 )
	    strcpy(HE5_SWXSwath[idx].gdataset[k].name, newfieldname);
	}
    }

  if (fldgroup == HE5_HDFE_PROFGROUP)
    {
      for(k = 0; k < HE5_SWXSwath[idx].nPROF; k++)
	{
	  if (strcmp(HE5_SWXSwath[idx].pdataset[k].name, oldfieldname) == 0 )
	    strcpy(HE5_SWXSwath[idx].pdataset[k].name, newfieldname);
	}
    }
  
 COMPLETION:
  HE5_UNLOCK;
  return(status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWmountexternal                                              |
|                                                                             |
|  DESCRIPTION:  Mounts external data file onto "Data Fields",  "Profile      |
|                    Fields", or "Geolocation Fields" group.                  |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|    extfID       hid_t                    External file ID                   |
|                                                                             |
|  INPUTS:                                                                    |
|    swathID      hid_t                    swath ID                           |
|    fldgroup     int                      Group flag                         |
|    extfilename  char                     External File Name                 |
|                                                                             |
|  OUTPUTS:                                                                   |
|                                                                             |
|  NOTES:                                                                     |
|    None                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  Sep  00  A. Muslimov   Original development                                |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
hid_t 
HE5_SWmountexternal(hid_t swathID, int fldgroup, const char *extfilename)
{
  
  hid_t    extfID     = FAIL;           /* External file ID (return)   */
  hid_t    fid        = FAIL;           /* HDF-EOS file ID             */
  hid_t    gid        = FAIL;           /* "SWATHS"  group ID          */
  herr_t   status     = FAIL;           /* Return status variable      */

  long     idx        = FAIL;           /* Swath index                 */

  char     grpname[HE5_HDFE_NAMBUFSIZE];/* Group name buffer           */
  char     errbuf[HE5_HDFE_ERRBUFSIZE]; /* Error message buffer        */


  HE5_LOCK; 
  CHECKNAME(extfilename);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWmountexternal", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for swath ID failed. \n");
      H5Epush(__FILE__, "HE5_SWmountexternal", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  strcpy(grpname,"/HDFEOS/SWATHS/");
  strcat(grpname, HE5_SWXSwath[idx].swname);

  if (fldgroup == HE5_HDFE_DATAGROUP)
    strcat(grpname,"/Data Fields");

  if (fldgroup == HE5_HDFE_PROFGROUP)
    strcat(grpname,"/Profile Fields");

  if (fldgroup == HE5_HDFE_GEOGROUP)
    strcat(grpname,"/Geolocation Fields");


  /* Open external data file */
  /* ----------------------- */
  extfID = H5Fopen(extfilename, H5F_ACC_RDONLY, H5P_DEFAULT);
  if ( extfID == FAIL )
    {
      sprintf(errbuf, "Cannot open external file named \"%s\". \n", extfilename);
      H5Epush(__FILE__, "HE5_SWmountexternal", __LINE__, H5E_FILE, H5E_CANTOPENFILE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }



  /* Mount external file */
  /* ------------------- */
  status = H5Fmount(fid, grpname, extfID, H5P_DEFAULT);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Cannot mount external file onto \"%s\" group. \n", grpname);
      H5Epush(__FILE__, "HE5_SWmountexternal", __LINE__, H5E_FILE, H5E_MOUNT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

 COMPLETION:  
  HE5_UNLOCK;
  return(extfID);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION:     SWunmount                                                    |
|                                                                             |
|  DESCRIPTION:  Unmounts external data file from "Data Fields",  "Profile    |
|                    Fields", or "Geolocation Fields" group.                  |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  status         herr_t                   Return status                      |
|                                                                             |
|  INPUTS:                                                                    |
|    swathID      hid_t                    swath ID                           |
|    fldgroup     int                      Group flag                         |
|    fileID       hid_t                    ID of file  to be unmounted        |
|                                                                             |
|  OUTPUTS:                                                                   |
|                                                                             |
|  NOTES:                                                                     |
|    None                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  Sep  00  A. Muslimov   Original development                                |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t 
HE5_SWunmount(hid_t swathID, int fldgroup, hid_t fileID)
{
  herr_t   status     = FAIL;           /* Return status variable */

  hid_t    fid        = FAIL;           /* HDF-EOS file ID        */
  hid_t    gid        = FAIL;           /* "SWATHS"  group ID     */

  long     idx        = FAIL;           /* Swath index            */

  char     grpname[HE5_HDFE_NAMBUFSIZE];/* Group name buffer      */
  char     errbuf[HE5_HDFE_ERRBUFSIZE]; /* Error message buffer   */


  HE5_LOCK;

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWunmount", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for swath ID failed. \n");
      H5Epush(__FILE__, "HE5_SWunmount", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  strcpy(grpname,"/HDFEOS/SWATHS/");
  strcat(grpname, HE5_SWXSwath[idx].swname);

  if (fldgroup == HE5_HDFE_DATAGROUP)
    strcat(grpname,"/Data Fields");

  if (fldgroup == HE5_HDFE_PROFGROUP)
    strcat(grpname,"/Profile Fields");

  if (fldgroup == HE5_HDFE_GEOGROUP)
    strcat(grpname,"/Geolocation Fields");


  status = H5Funmount(fid, grpname);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Cannot unmount external file from \"%s\" group. \n", grpname);
      H5Epush(__FILE__, "HE5_SWunmount", __LINE__, H5E_FILE, H5E_MOUNT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  status = H5Fclose(fileID);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Cannot close external file. \n");
      H5Epush(__FILE__, "HE5_SWunmount", __LINE__, H5E_FILE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

 COMPLETION:
  HE5_UNLOCK;
  return(status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWreadexternal                                               |
|                                                                             |
|  DESCRIPTION:  Reads external dataset                                       |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  status         herr_t                   Return status                      |
|                                                                             |
|  INPUTS:                                                                    |
|    swathID      hid_t                    swath ID                           |
|    fldgroup     int                      Group flag                         |
|    fieldname    char                     Field name to read                 |
|                                                                             |
|  OUTPUTS:                                                                   |
|    buffer       void                     Output data bufer                  |
|                                                                             |
|  NOTES:                                                                     |
|    None                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  Sep  00  A. Muslimov   Original development                                |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t 
HE5_SWreadexternal(hid_t swathID, int fldgroup, const char *fieldname, void *buffer)
{
  herr_t   status     = FAIL;/* return status variable      */

  hid_t    fid        = FAIL;/* HDF-EOS file ID             */
  hid_t    gid        = FAIL;/* "SWATHS"  group ID          */
  hid_t    groupID    = FAIL;/* Group ID                    */
  hid_t    datasetID  = FAIL;/* Dataset ID                  */
  hid_t    typeID     = FAIL;/* File data type ID           */
  hid_t    mtypeID    = FAIL;/* Memory datatype ID          */

  long     idx        = FAIL;/* Swath index                 */

  char     grpname[HE5_HDFE_NAMBUFSIZE];/* Group name buffer    */
  char     errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer  */


  HE5_LOCK;
  CHECKPOINTER(fieldname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWreadexternal", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for swath ID failed. \n");
      H5Epush(__FILE__, "HE5_SWreadexternal", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  strcpy(grpname,"/HDFEOS/SWATHS/");
  strcat(grpname, HE5_SWXSwath[idx].swname);

  if (fldgroup == HE5_HDFE_DATAGROUP)
    strcat(grpname,"/Data Fields");

  if (fldgroup == HE5_HDFE_PROFGROUP)
    strcat(grpname,"/Profile Fields");

  if (fldgroup == HE5_HDFE_GEOGROUP)
    strcat(grpname,"/Geolocation Fields");


  /* Open the group containing mounted file   */
  /* ---------------------------------------- */
  groupID = H5Gopen(fid, grpname);
  if ( groupID == FAIL )
    {
      sprintf(errbuf, "Cannot open group containing mounted file. \n");
      H5Epush(__FILE__, "HE5_SWreadexternal", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Open the dataset */
  /* ---------------- */
  datasetID = H5Dopen(groupID, fieldname);
  if ( datasetID == FAIL )
    {
      sprintf(errbuf, "Cannot open mounted dataset. \n");
      H5Epush(__FILE__, "HE5_SWreadexternal", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    } 

  /* Get the data type ID */
  /* -------------------- */
  typeID = H5Dget_type(datasetID);
  if ( typeID == FAIL )
    {
      sprintf(errbuf, "Cannot get the data type ID of  mounted dataset. \n");
      H5Epush(__FILE__, "HE5_SWreadexternal", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
 
  /* Get memory data type ID */
  /* ----------------------- */
  mtypeID    = HE5_EHdtype2mtype(typeID);
  if (mtypeID == FAIL)
    {
      sprintf(errbuf, "Cannot convert to memory data type.") ;
      H5Epush(__FILE__, "HE5_SWreadexternal", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Read the mounted dataset */
  /* ------------------------ */
  status = H5Dread(datasetID, mtypeID, H5S_ALL, H5S_ALL, H5P_DEFAULT, buffer);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Cannot read mounted data.") ;
      H5Epush(__FILE__, "HE5_SWreadexternal", __LINE__, H5E_DATASET, H5E_READERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  

  /* Release data type ID */
  /* -------------------- */
  status = H5Tclose(typeID);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Cannot release data type ID.") ;
      H5Epush(__FILE__, "HE5_SWreadexternal", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
 
  /* Release dataset ID */
  /* ------------------ */
  status = H5Dclose(datasetID);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Cannot release dataset ID.") ;
      H5Epush(__FILE__, "HE5_SWreadexternal", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Release the group ID */
  /* -------------------- */
  status = H5Gclose(groupID);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Cannot release group ID.") ;
      H5Epush(__FILE__, "HE5_SWreadexternal", __LINE__, H5E_OHDR, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

 COMPLETION:
  HE5_UNLOCK;
  return(status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWsetextdata                                                 |
|                                                                             |
|  DESCRIPTION: Sets external data files.                                     |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  filelist       const char*         list of external files                  |
|  offset         off_t               array of offsets (in bytes) from the    |
|                                     beginning of the file to the location   |
|                                     in the file where the data starts       |
|  size           hsize_t             array of sizes (in bytes) reserved in   |
|                                     the file for the data.                  |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Apr 01   A.Muslimov    Original development.                               |
|  Sep  01  A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t   
HE5_SWsetextdata(hid_t swathID, const char *filelist, off_t offset[], hsize_t size[])
{
  herr_t          status       = FAIL;        /* return status variable */

  int             i;                          /* Loop index             */

  hid_t           fid          = FAIL;        /* HDF-EOS file ID        */
  hid_t           gid          = FAIL;        /* "HDFEOS" group ID      */
  
  long            idx          = FAIL;        /* Swath index            */
  
  char            *namebuf     = (char *)NULL;/* File list buffer       */
  char            *filename    = (char *)NULL;/* File name buffer       */
  char            *comma       = (char *)NULL;/* Pointer to comma       */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer   */
  

  HE5_LOCK;
  CHECKPOINTER(filelist);
  CHECKPOINTER(offset);
  CHECKPOINTER(size);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWsetextdata", &fid, &gid, &idx);
  if(status == FAIL)
    {
      sprintf(errbuf,"Checking for valid swath ID failed.\n");
      H5Epush(__FILE__, "HE5_SWsetextdata", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Get current dataset creation property list */
  /* ------------------------------------------ */  
  if( HE5_SWXSwath[idx].plist == FAIL)
    HE5_SWXSwath[idx].plist = H5Pcreate(H5P_DATASET_CREATE);


  /* Allocate space for namebuf, copy dimlist into it, & append comma */
  /* ---------------------------------------------------------------- */
  namebuf = (char *)calloc(strlen(filelist) + 64, sizeof(char));
  if(namebuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWsetextdata", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory.");
      HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
      return(FAIL);
    }
	

  /*
********************************************************************
*   C H E C K  T H E   C O N T E N T   O F  filelist  S T R I N G  *   
********************************************************************
*/

  strcpy(namebuf, filelist);
  strcat(namebuf, ",");

  /* Find comma */
  /* ---------- */
  comma = strchr(namebuf, ',');
  
  i = 0;
  
  /* Parse the list of file names */
  /* ---------------------------- */
  while (comma != NULL)
    {
      /* Allocate memory for filename buffer */
      /* ----------------------------------- */
      filename = (char *) calloc(comma - namebuf + 1, sizeof(char));
      if (filename == NULL)
	{
	  sprintf(errbuf, "Cannot allocate memory for filename. \n") ;
	  H5Epush(__FILE__, "HE5_SWsetextdata", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(namebuf);
		  
	  return(FAIL);
	}
	  
      /* Copy file list entry to filename */
      /* -------------------------------- */
      memmove(filename, namebuf, comma - namebuf);
      filename[comma-namebuf] = 0;
	  
      /* Set the property list */
      /* --------------------- */
      status = H5Pset_external(HE5_SWXSwath[idx].plist, filename, offset[i], size[i]);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot set external dataset property list.\n");
	  H5Epush(__FILE__, "HE5_SWsetextdata", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(namebuf);
	  free(filename);
	  return(status);
	}
	  
	  
      /* Go to next file  entry, find next comma, ... */
      /* ============================================ */ 
      memmove(namebuf, comma + 1, strlen(comma + 1) + 1); 
      comma = strchr(namebuf, ',');
	  
      if (filename != NULL) free(filename);
	  
      i++;
    }
  
  if (namebuf != NULL) free(namebuf);

 COMPLETION:
  HE5_UNLOCK;
  return (status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWgetextdata                                                 |
|                                                                             |
|  DESCRIPTION: Gets external data files information.                         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nfiles         int                 number of external files  SUCCEED,      |
|                                               (-1) FAIL                     |
|  INPUTS:                                                                    |
|  swathID        hid_t               swath structure ID                      |
|  fieldname      char*               External field name                     |
|                                                                             |
|  OUTPUTS:                                                                   |
|  namelength     size_t              Length of each name entry               |
|  filelist       char*               List of file names                      |
|  offset         off_t               array of offsets (in bytes) from the    |
|                                     beginning of the file to the location   |
|                                     in the file where the data starts       |
|  size           hsize_t             array of sizes (in bytes) reserved in   |
|                                     the file for the data.                  |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Apr 01   A.Muslimov    Original development.                               |
|  Sep 01   A. Muslimov   Added mutex "lock"/"unlock" calls.                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int   
HE5_SWgetextdata(hid_t swathID, char *fieldname, size_t namelength, char *filelist, off_t offset[], hsize_t size[])
{
  int             nfiles       = FAIL;        /* Number of ext. files   */
  int             i;                          /* Loop index             */

  size_t          slen         = 0;           /* String length          */

  herr_t          status       = FAIL;        /* return status variable */

  hid_t           fid          = FAIL;        /* HDF-EOS file ID        */
  hid_t           gid          = FAIL;        /* "HDFEOS" group ID      */
  hid_t           fieldID      = FAIL;        /* Data field ID          */
  hid_t           plist        = FAIL;        /* Property list ID       */

  off_t           off          = 0;           /* Offset of data segment */
 
  hsize_t         sz           = 0;           /* Size of data segment   */

  long            idx          = FAIL;        /* Swath index            */
  
  char            *filename    = (char *)NULL;/* File name buffer       */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer   */
  


  HE5_LOCK;
  CHECKPOINTER(fieldname);

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_SWgetextdata", &fid, &gid, &idx);
  if(status == FAIL)
    {
      sprintf(errbuf,"Checking for valid swath ID failed.\n");
      H5Epush(__FILE__, "HE5_SWgetextdata", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  /* Check out the field group and get field ID */
  /* ------------------------------------------ */
  HE5_SWfldsrch(swathID,fieldname,&fieldID,NULL,NULL,NULL);
  if( fieldID == FAIL )
    {
      sprintf(errbuf, "Cannot get the field ID for the \"%s\" field.\n", fieldname);
      H5Epush(__FILE__, "HE5_SWgetextdata", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
   
  /* Get the property list ID */
  /* ------------------------ */
  plist = H5Dget_create_plist(fieldID);
  if ( plist == FAIL )
    {
      sprintf(errbuf, "Cannot get the property list ID for the \"%s\" data field.\n", fieldname);
      H5Epush(__FILE__, "HE5_SWgetextdata", __LINE__, H5E_PLIST, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Get the number of external files */
  /* -------------------------------- */
  nfiles = H5Pget_external_count(plist);
  if ( nfiles < 0 )
    {
      sprintf(errbuf, "Cannot get the number of external files.\n");
      H5Epush(__FILE__, "HE5_SWgetextdata", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }


  /* Allocate memory for file name */
  /* ----------------------------- */
  filename = (char *)calloc(HE5_HDFE_NAMBUFSIZE, sizeof(char));
  if(filename == NULL)
    {
      H5Epush(__FILE__, "HE5_SWgetextdata", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory.");
      HE5_EHprint("Error: Can not allocate memory, occured", __FILE__, __LINE__);
      return(FAIL);
    }
	
  strcpy(filelist,"");
  
  /* Loop through all external files */
  /* ------------------------------- */
  for (i = 0; i < nfiles; i++)
    {
      strcpy(filename,"");

      /* Get the file name, offset, and size */
      /* ----------------------------------- */
      status = H5Pget_external(plist, i, namelength, filename, &off, &sz);
      if( status == FAIL)
	{
	  sprintf(errbuf,"Cannot get information about external file.\n");
	  H5Epush(__FILE__, "HE5_SWgetextdata", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(filename);
	  return(FAIL);
	}
	  
      offset[i] = off;
      size[i]   = sz;
	  
      strcat(filelist, filename);
	  
      /* Append comma */
      /* ------------ */
      if (nfiles > 1 && i < nfiles - 1) 
	strcat(filelist,",");
	  
    }
  
  slen = strlen(filelist);
  
  filelist[slen] = 0;

  if (filename != NULL) free(filename);


  /* Release property list ID */
  /* ------------------------ */
  status = H5Pclose(plist);
  if (status == FAIL )
    {
      sprintf(errbuf, "Cannot release property list ID.\n");
      H5Epush(__FILE__, "HE5_SWgetextdata", __LINE__, H5E_PLIST, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
 COMPLETION:
  HE5_UNLOCK;
  return (nfiles);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWindexinfo                                                  |
|                                                                             |
|  DESCRIPTION: Returns indices of a subsetted region                         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  regionID       hid_t               Region ID                               |
|  object         char*               field name                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  rank           int*                field rank                              |
|  dimlist        char*               field dimension list                    |
|  indices        hsize_t*            indices of region for along track dim.  |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  June 04   S.Zhao       Original development                                |
|  Oct 11   Abe Taaheri   Modified correcting indicies for fields with        |
|                         ranks larger than 2                                 |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t
HE5_SWindexinfo(hid_t regionID, char *object, int *rank, char *dimlist, hsize_t *indices[HE5_DTSETRANKMAX])
{
  herr_t          status = FAIL;        /* routine return status variable */
  int             j,k, fi, gi;          /* loop index                     */
 
  hid_t           *nt = (hid_t *)NULL;   /* number types          */
  hsize_t         dims[HE5_DTSETRANKMAX];/* Dimension array       */
  char            tempdimlist[HE5_HDFE_DIMBUFSIZE];/* Dimension list  */
 
  char            errbuf[HE5_HDFE_ERRBUFSIZE]; /* Error buffer    */
  long             index0, index1;
 
 
  CHECKPOINTER(object);
 
  /* Check for valid region ID */
  /* ------------------------- */
  if (regionID < 0 || regionID >= HE5_NSWATHREGN)
    {
      status = FAIL;
      sprintf(errbuf, "Invalid Region ID: %d.\n", regionID);
      H5Epush(__FILE__, "HE5_SWindexinfo", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }
 
  /* Check for active region ID */
  /* -------------------------- */
  if (HE5_SWXRegion[regionID] == 0)
    {
      status = FAIL;
      sprintf(errbuf, "Inactive Region ID: %d.\n", regionID);
      H5Epush(__FILE__, "HE5_SWindexinfo", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }
 
  /* Initialize dims[] array */
  /* ----------------------- */
  for (k = 0; k < HE5_DTSETRANKMAX; k++)
    dims[k] = 0;
 
  /* Allocate memory for nt variable */
  /* ------------------------------- */
  nt = (hid_t *)calloc(1, sizeof(hid_t));
  if(nt == (hid_t *)NULL)
    {
      sprintf(errbuf, "Cannot allocate memory.\n");
      H5Epush(__FILE__, "HE5_SWindexinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
 
  /* Get field info for given object */
  /* -------------------------- */
  status = HE5_SWfieldinfo(HE5_SWXRegion[regionID]->swathID, object, rank, dims, nt, tempdimlist, NULL);
  if (status != SUCCEED)
    {
      sprintf(errbuf, "Field \"%s\" not found.\n", object);
      H5Epush(__FILE__, "HE5_SWindexinfo", __LINE__, H5E_ARGS, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(nt);
      return(FAIL);
    }
 
  strcpy(dimlist, tempdimlist);
 
  /* Find out Field indicies corresponding to the 1st and 2nd indicies of
   * Longitude (which automatically will be the same for Latitude or
   * Colatitude) field. For 2 or multi-dimansional fields, other than 
   * Longitude, Latitude (or  Colatitude) it is important to know these
   * indicies.
   */
  status = HE5_SWllmapedidxinfo(HE5_SWXRegion[regionID]->swathID,object,&index0,&index1);
  if (status != SUCCEED)
  {
      sprintf(errbuf, "Field \"%s\" not found.\n", object);
      H5Epush(__FILE__, "HE5_SWindexinfo", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
  }

  /* index0 is field index correcponding to the 0 index of Longitude */
  /* index1 is field index correcponding to the 1 index of Longitude */

  /* Vertical Subset or regular subset */
  /* --------------------------------- */
  for (j = 0; j < *rank; j++)
    {
      if(j == index0)
	{
	  gi = 0;
	  fi = index0;
	}
      else if(j == index1)
	{
	  gi = 1;
	  fi = index1;
	}
      else
	{
	  if (j <index0)
	    {
	      gi = j + 2;
	      if(gi > 7) gi = 7;
	    }
	  else
	    {
	      gi = j;
	    }
	  fi = j;
	}

      if (HE5_SWXRegion[regionID]->StartVertical[gi] == FAIL)
        {
          if (HE5_SWXRegion[regionID]->StartRegion[gi] == 0)
            {
              indices[fi][0] = 0;
            }
          else
            {
              indices[fi][0] = HE5_EHlong2hsize(HE5_SWXRegion[regionID]->StartRegion[gi]);
            }
        }
      else
        {
          if (HE5_SWXRegion[regionID]->StartVertical[gi] == 0)
            {
              indices[fi][0] = 0;
            }
          else
            {
              indices[fi][0] = HE5_EHlong2hsize(HE5_SWXRegion[regionID]->StartVertical[gi]);
            }
        }
 
      if (HE5_SWXRegion[regionID]->StopVertical[gi] == FAIL)
        {
          if (HE5_SWXRegion[regionID]->StopRegion[gi] == 0)
            {
              indices[fi][1] = dims[fi] - 1;
            }
          else
            {
              indices[fi][1] = HE5_EHlong2hsize(HE5_SWXRegion[regionID]->StopRegion[gi]);
            }
        }
      else
        {
          if (HE5_SWXRegion[regionID]->StopVertical[gi] == 0)
            {
              indices[fi][1] = dims[fi] - 1;
            }
          else
            {
              indices[fi][1] = HE5_EHlong2hsize(HE5_SWXRegion[regionID]->StopVertical[gi]);
            }
        }
 
    }
 
  free(nt);
 
 COMPLETION:
  return (status);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWllmapedidxinfo                                             |
|                                                                             |
|  DESCRIPTION: Returns indices of a subsetted region                         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath ID                                |
|  object         char*               field name                              |
|                                                                             |
|                                                                             |
|  OUTPUTS:                                                                   |
|  indices        long                0th and 1st indices of the field        |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Oct 11   Abe Taaheri   Original development,                               |
|  Jan 12   AT            Fixed problem with preventing memcpy to use         |
|                         unacceptable pointrs for ptr and ptr2               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t
HE5_SWllmapedidxinfo(hid_t swathID, char *object, long *index0, long *index1)
{
  herr_t          status = -1;   /* routine return status variable */
  herr_t          statMap = -1;  /* Status from SWmapinfo          */
  char            dimlist[HE5_HDFE_DIMBUFSIZE];/* Dimension list   */
  char            maxdimlist[HE5_HDFE_DIMBUFSIZE];/* Dimension list*/
  int             i,j,k, iDim;   /* loop index                     */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];   /* Error buffer   */
  hid_t           nt, ntype;     /* number types                   */
  hsize_t         dims[HE5_DTSETRANKMAX];       /* Dimension array */
  int             rank;
  char            dimname0[HE5_HDFE_DIMBUFSIZE],dimname1[HE5_HDFE_DIMBUFSIZE];
  char            geodim[HE5_HDFE_DIMBUFSIZE];   /* Geolocation field dimension list */
  char            maxgeodim[HE5_HDFE_DIMBUFSIZE];/* Geolocation field max dimension list */
  char            geodimbuf[HE5_HDFE_DIMBUFSIZE];/* Geolocation field dimension list */
  long            nDim;	             /* Number of dimensions       */
  long            mDim;	             /* Number of dimensions       */
  size_t          slen[HE5_DTSETRANKMAX],slen2[HE5_DTSETRANKMAX]; /* String length array  */
  char           *ptr[HE5_DTSETRANKMAX],*ptr2[HE5_DTSETRANKMAX];  /* String pointer array */
  hsize_t         dumdims[HE5_DTSETRANKMAX];	     /* Dimensions from SWfieldinfo */
  unsigned        found = 0;         /* Found flag                  */
  char            utlbuf[HE5_HDFE_DIMBUFSIZE];    /* Utility buffer */
  long            incr;	             /* Mapping increment           */
  hsize_t         dummy;             /* Dummy variable              */
  long            dum;	             /* Dummy variable              */
  long           *idxmap = NULL;     /* Pointer to index mapping array */
  hsize_t         idxMapElem = 0;    /* Number of index map elements   */
  long            index[HE5_DTSETRANKMAX];
  long            maxrank = HE5_DTSETRANKMAX;

  /* Get data field info */
  /* ------------------- */
  status = HE5_SWfieldinfo(swathID, object, &rank,
			   dims, &ntype, dimlist, maxdimlist);
  if (status != 0)
    {
      status = -FAIL;
      sprintf(errbuf,"Cannot get information about \"%s\" field. \n", object);
      H5Epush(__FILE__, "HE5_SWllmapedidxinfo", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
    }

  status = HE5_SWfieldinfo(swathID, "Longitude", &rank, 
			   dumdims, &nt, geodim, maxgeodim);
  if (status != 0)
  {
      sprintf(errbuf, "Field \"%s\" not found.\n", "Longitude");
      H5Epush(__FILE__, "HE5_SWllmapedidxinfo", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(status);
  }

   /* Get "Track" (first) Dimension from geo dimlist */
  /* ---------------------------------------------- */
  for(iDim=0; iDim<maxrank; iDim++)
    {
      ptr[iDim] = NULL;
      ptr2[iDim] = NULL;
    }

  nDim = HE5_EHparsestr(geodim, ',', ptr, slen);

  for(iDim=0; iDim<nDim; iDim++)
    {
      index[iDim] = 0;
    }

  for(iDim=0; iDim<nDim; iDim++)
    {
      if(ptr[iDim] == NULL) break;
      else
	{
	  memcpy(geodimbuf, ptr[iDim], slen[iDim]);
	  geodimbuf[slen[iDim]] = 0;
	}

      if(strcmp(geodimbuf,"") == 0 ) break;

      /* Parse Data Field Dimlist & find mapping */
      /* --------------------------------------- */
      mDim = HE5_EHparsestr(dimlist, ',', ptr2, slen2);
      
  
      /* Loop through all dimensions and search for mapping */
      /* -------------------------------------------------- */
      for (i = 0; i < mDim; i++)
	{
	  memcpy(utlbuf, ptr2[i], slen2[i]);
	  utlbuf[slen2[i]] = 0;
	  
	  statMap = HE5_SWmapinfo(swathID, geodimbuf, utlbuf,
			      &dum, &incr);
	  
	  /* Mapping found */
	  /* ------------- */
	  if (statMap == 0)
	    {
	      found = 1;
	      index[iDim] = i;
	      break;
	    }
	}  
      
      /* If mapping not found check for geodim within dimlist */
      /* ---------------------------------------------------- */
      if (found == 0)
	{
	  index[iDim] = HE5_EHstrwithin(geodimbuf, dimlist, ',');
	  
	  /* Geo dimension found within subset field dimlist */
	  /* ----------------------------------------------- */
	  if (index[iDim] != -1)
	    {
	      found = 1;
	      incr = 1;
	    }
	}
      
      /* If mapping not found check for indexed mapping */
      /* ---------------------------------------------- */
      if (found == 0)
	{
	  /* Get size of geo dim & allocate space of index mapping */
	  /* ----------------------------------------------------- */
	  dummy = HE5_SWdiminfo(swathID, geodimbuf);
	  idxmap = (long *) calloc(dummy, sizeof(long));
	  if(idxmap == NULL)
	    {
	      sprintf(errbuf, "Failed to retrieve the size of \"%s\" dimension. \n", geodimbuf) ;
	      H5Epush(__FILE__, "HE5_SWllmapedidxinfo", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(FAIL);
	    }
	  
	  /* Loop through all dimensions and search for mapping */
	  /* -------------------------------------------------- */
	  for (i = 0; i < mDim; i++)
	    {
	      memcpy(utlbuf, ptr2[i], slen2[i]);
	      utlbuf[slen2[i]] = 0;
	      
	      idxMapElem = HE5_SWidxmapinfo(swathID, geodimbuf, utlbuf, idxmap);
	      
	      /* Mapping found */
	      /* ------------- */
	      if (idxMapElem > 0)
		{
		  found = 1;
		  index[iDim] = i;
		  break;
		}
	    }
	}
      found = 0;
    }

  *index0 = index[0];
  *index1 = index[1];;

  return(status);
}


 
 /*---------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION:    HE5_SWgetstringtype                                           |
|                                                                             |
|  DESCRIPTION: Determines type of STRING as H5T_NATIVE_CHAR or               |
|               HE5T_CHARSTRING. These are two two different                  |
|               types of Strings that HDF-EOS uses for data fieleds           |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  String datatype int                return status H5T_NATIVE_CHAR or        |
|                                     HE5T_CHARSTRING if succeed, (-1) FAIL   |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t               Swath structure ID                      |
|  fldname        char                Fieldname                               |
|  classid        H5T_class_t         Class ID                                |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
| 08/1/06  Abe Taaheri    Original programmer                                 |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWgetstringtype(hid_t swathID, char *fldname, H5T_class_t classid)
{
  char            *attrlist1 = (char *)NULL;/* attribute list               */
  long            strbufsize1;              /* string buffer size           */
  char            fldactualname[HE5_HDFE_NAMBUFSIZE];/* Actual field name   */
  char            fieldname[HE5_HDFE_NAMBUFSIZE];    /* Field name buffer   */
  char            *attptr = (char *)NULL;   /* attribute pointer            */
  herr_t	  status   = SUCCEED;       /* return status variable       */
  char		  *errbuf = (char *)NULL;   /* error message buffer         */
  int             attr = H5T_NATIVE_CHAR;   /* attribute value              */
  int             nameflag = FAIL;          /* Name flag (0-alias,1-actual) */
  long            nattr    = FAIL;          /* Number of attributes (return)*/

  HE5_LOCK;
  CHECKPOINTER(fldname);

  if(classid != H5T_STRING)/* if field is not string type, return error */
    {
      sprintf(errbuf, "Cannot get strig type for none-string field.\n");
      H5Epush(__FILE__, "HE5_SWgetstringtype", __LINE__, H5E_OHDR, 
	      H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  else
    {
      /* Call HE5_SWfldnameinfo() to get actual field name */
      /* --------------------------------------------- */
      nameflag = HE5_SWfldnameinfo(swathID, fldname, fldactualname);
      if ( nameflag == FAIL )
	{
	  sprintf(errbuf, "Cannot get actual name of the field.\n");
	  H5Epush(__FILE__, "HE5_SWgetstringtype", __LINE__, H5E_OHDR, 
		  H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}
      
      /* Name is not alias */
      /* ----------------- */
      if (nameflag == TRUE)
	{
	  strcpy(fieldname,"");
	  strcpy(fieldname,fldname);
	}
      
      /* Name is an alias */
      /* ---------------- */
      if (nameflag == FALSE)
	{
	  strcpy(fieldname,"");
	  strcpy(fieldname,fldactualname);
	}
      
      strbufsize1 = 0;
      nattr = HE5_SWinqlocattrs(swathID, fieldname, NULL, &strbufsize1);
      if ( nattr <= 0 )/* this means ARRAYOFSTRINGS attribute does not exist,
			  therefore, String datatype cannot be HE5T_CHARSTRING,
			  or H5T_C_S1 type */
	{
	  return(HE5T_NATIVE_CHAR);
	}
      
      attrlist1 = (char *) calloc(strbufsize1 + 2, sizeof(char));
      if (attrlist1 == NULL)
	{
	  sprintf(errbuf, "Cannot allocate memory for attrlist1.\n") ;
	  H5Epush(__FILE__, "HE5_SWgetstringtype", __LINE__, H5E_RESOURCE, 
		  H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);   
	}

      nattr = HE5_SWinqlocattrs(swathID, fieldname, attrlist1, &strbufsize1);
      attptr = strstr(attrlist1,"ARRAYOFSTRINGS");
      if ( (classid == H5T_STRING) && (attptr == NULL) )
	{
	  /* this means ARRAYOFSTRINGS attribute does not exist,
	     therefore, String datatype cannot be HE5T_CHARSTRING,
	     or H5T_C_S1 type 
	  */
	  return(HE5T_NATIVE_CHAR);
	}
      else if((classid == H5T_STRING) && (attptr != NULL) )
	{
	  status = HE5_SWreadlocattr(swathID, fieldname, "ARRAYOFSTRINGS", 
				     &attr);
	  if(status ==FAIL)
	    {
	      sprintf(errbuf, "Cannot read attribute from the field \"%s\".",
		      fieldname) ;
	      H5Epush(__FILE__, "HE5_SWgetstringtype", __LINE__, H5E_DATASET, 
		      H5E_READERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      return(FAIL);
	    }

	  if(attr == HE5T_CHARSTRING)
	    {
	      return(HE5T_CHARSTRING);
	    }
	  else
	    {
	      return(HE5T_NATIVE_CHAR);
	    }
	}
    }

 COMPLETION:
  HE5_UNLOCK;
  return (attr);
}


/* 
******************************************************************************
|                                                                            |
|          F  O  R  T  R  A  N  7 7      W  R  A  P  P  E  R  S              |
|                                                                            |
******************************************************************************
*/



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWopenF (FORTRAN wrapper)                                    |
|                                                                             |
|  DESCRIPTION:                                                               |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|     FileID      int     None        HDF-EOS file ID                         |
|                                                                             |
|  INPUTS:                                                                    |
|     filename    char*    None       File name string                        |
|     Flags       int      None       File access code                        |
|                                                                             |
|  OUTPUTS:                                                                   |
|     None                                                                    |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date       Programmer   Description                                       |
|  ========   ============  ================================================= |
|  Aug  00   A.Muslimov                                                       |
|  Mar  02   A.Muslimov     Added "Flags" values for core methadata.          |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int 
HE5_SWopenF(char *filename, int Flags)
{
  hid_t     fid     = FAIL;/* HDF5 file ID          */

  int       FileID  = FAIL;/* hdf-eos file ID       */
  
  uintn     flags   = 9999;/* HDF5 file access code */

  char      *errbuf = NULL;/* Error message buffer  */


  /* Allocate memory for error buffer */
  /* -------------------------------- */
  errbuf  = (char * )calloc(HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWopenF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory to error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);

      return(FAIL);
    }  

  /* Set up the file access flag */
  /* --------------------------- */
  if (Flags == HE5F_ACC_RDWR || Flags == HDF5_ACC_RDWR) flags = H5F_ACC_RDWR;
  else if (Flags == HE5F_ACC_RDONLY || Flags == HDF5_ACC_RDONLY) flags = H5F_ACC_RDONLY;
  else if (Flags == HE5F_ACC_TRUNC || Flags == HDF5_ACC_CREATE)  flags = H5F_ACC_TRUNC;
  else
    {
      sprintf(errbuf, "File access flag is not supported. \n");
      H5Epush(__FILE__, "HE5_SWopenF", __LINE__, H5E_ARGS, H5E_UNSUPPORTED, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }  
	


  /* Call HE5_EHopen to open file */
  /* ---------------------------- */
  fid = HE5_EHopen(filename, flags, H5P_DEFAULT);
  if(fid == FAIL)
    {
      sprintf(errbuf, "Cannot open the file \"%s\". Check the file name. \n", filename);
      H5Epush(__FILE__, "HE5_SWopenF", __LINE__, H5E_FILE, H5E_CANTOPENFILE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }  

  free(errbuf);

  FileID = (int)fid;
  return(FileID);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWcreateF (FORTRAN wrapper)                                  |
|                                                                             |
|  DESCRIPTION: Creates a new swath structure and returns swath ID            |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|   SwathID       int          None        Swath ID                           |
|                                                                             |
|  INPUTS:                                                                    |
|   FileID        int          None        HDF-EOS file ID                    |
|   swathname     char*        None        Swath name string                  |
|                                                                             |
|  OUTPUTS:                                                                   |
|   None                                                                      |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A. Muslimov                                                       |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int 
HE5_SWcreateF(int FileID, char *swathname)
{
  hid_t           swathID        = FAIL;/* return value of Swath ID        */
  hid_t           fid            = FAIL;/* HDF-EOS file ID                 */

  int             SwathID        = FAIL;/* int Swath ID                    */
  
  char            *errbuf =(char *)NULL;/* Buffer for error message        */

  /* Allocate memory for error buffer */
  /* -------------------------------- */
  errbuf = (char *)calloc(HE5_HDFE_DIMBUFSIZE, sizeof(char ) ) ;
  if ( errbuf == NULL )
    {
      H5Epush(__FILE__, "HE5_SWcreateF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
  

  fid = (hid_t)FileID;
  
  swathID = HE5_SWcreate(fid, swathname);
  if (swathID == FAIL)
    {
      sprintf(errbuf,"Cannot create Swath. \n");
      H5Epush(__FILE__, "HE5_SWcreateF", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
	
  SwathID = (int)swathID;	
  
  /* Deallocate memory */
  /* ----------------- */
  free(errbuf);
  
  return(SwathID);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWattachF     (FORTRAN wrapper)                              |
|                                                                             |
|  DESCRIPTION:  Attaches to an existing swath within the file.               |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  SwathID        int                 swath structure ID                      |
|                                                                             |
|  INPUTS:                                                                    |
|  FileID         int                 HDF-EOS file ID                         |
|  swathname      char                swath structure name                    |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date        Programmer    Description                                     |
|  =========   ============  ==============================================   |
|  Aug  00     A.Muslimov                                                     |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int 
HE5_SWattachF(int FileID, char *swathname)
{
  int             SwathID    = FAIL;/* int Swath ID (return)         */

  hid_t           swathID    = FAIL;/* Swath ID (return value)       */ 
  hid_t           fid        = FAIL;/* HDF-EOS file ID               */

  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */

  fid = (hid_t)FileID;

  swathID = HE5_SWattach(fid, swathname);
  if (swathID == FAIL)
    {
      sprintf(errbuf,"Cannot attach to the Swath \"%s\". \n", swathname);
      H5Epush(__FILE__, "HE5_SWattachF", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  SwathID = (int)swathID;

  return (SwathID);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdetachF  (FORTRAN wrapper)                                 |
|                                                                             |
|  DESCRIPTION: Detachs swath structure and performs housekeeping             |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int    
HE5_SWdetachF(int SwathID)
{
  int            ret     = FAIL;/* int return status              */

  hid_t          swathID = FAIL;/* HDF-EOS Swath ID               */
  herr_t         status  = FAIL;/* routine return status variable */

  char           errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer  */

  swathID = (hid_t)SwathID;

  status = HE5_SWdetach(swathID);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot detach from the Swath. \n");
      H5Epush(__FILE__, "HE5_SWdetachF", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
  ret = (int)status;	
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWcloseF    (FORTRAN wrapper)                                |
|                                                                             |
|  DESCRIPTION: Closes HDF-EOS file                                           |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  FileID         int                 File ID                                 |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int    
HE5_SWcloseF(int FileID)
{
  int      ret    = FAIL;/* int return status variable     */

  hid_t    fid    = FAIL;/* HDF-EOS file ID                */

  herr_t   status = FAIL;/* routine return status variable */

  char     errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */


  fid = (hid_t)FileID;
  status = HE5_SWclose(fid);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot close the file. \n");
      H5Epush(__FILE__, "HE5_SWcloseF", __LINE__, H5E_FILE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
  
  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefdimF                                                    |
|                                                                             |
|  DESCRIPTION: Defines numerical value of dimension (FORTRAN wrapper)        |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  dim. name      char                dimension name                          |
|  dim. size      long                dimension size                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  May 00   D.Wynne       Original Version                                    |
|  Sep 00   A.Muslimov    Updated to reflect most recent data type changes.   |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWdefdimF(int SwathID, char *dimname, long dim)
{
  int       ret       = SUCCEED;/* (int) return status variable  */ 

  hid_t     swathID   = FAIL;   /* HDF5 type swath ID            */

  herr_t	status    = SUCCEED;/* HDF5 type return status       */
 
  hsize_t	tdim      = 0;      /* temporary(dimension) variable */
  
  char		*errbuf   = (char *)NULL;/* Error message buffer     */
  
  
  errbuf = (char *)calloc(HE5_HDFE_ERRBUFSIZE, sizeof(char));
  
  tdim    = (hsize_t)dim;	
  swathID = (hid_t)SwathID;

  status = HE5_SWdefdim(swathID, dimname, tdim);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Error calling HE5_SWdefdim from FORTRAN wrapper. \n");
      H5Epush(__FILE__, "HE5_SWdefdimF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }

  free(errbuf);

  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefdimmapF                                                 |
|                                                                             |
|  DESCRIPTION: Defines mapping between geolocation and data dimensions       |
|               (FORTRAN wrapper)                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  geo dim.       char                geolocation dimension                   |
|  data dim.      char                data dimension                          |
|  offset         long                offset between dimensions               |
|  incr           long                increment between dimensions            |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  May 00   D.Wynne       Original Version                                    |
|  Sep 00   A.Muslimov    Updated to reflect most recent data type changes.   |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int 
HE5_SWdefdimmapF(int SwathID, char *geodim, char *datadim, long offset, long increment)
{
  herr_t	status     = SUCCEED;/* HDF5 type status variable   */
  
  int       ret        = SUCCEED;/* (int) return variable       */  

  hid_t     swathID    = FAIL;   /* HDF5 type swath ID          */

  hsize_t	toffset    = 0;      /* offset variable             */
  hsize_t	tincrement = 0;      /* increment variable          */
  
  char		*errbuf    = (char *)NULL;/* Error message buffer   */
  

  errbuf = (char *)calloc(HE5_HDFE_ERRBUFSIZE, sizeof(char));
  
  /* Cast variable datatype to HDF5 datatype for HDF function calls */
  /* -------------------------------------------------------------- */
  toffset    = (hsize_t)offset;	
  tincrement = (hsize_t)increment;

  swathID = (int)SwathID;
  
  status = HE5_SWdefdimmap(swathID, geodim, datadim, toffset, tincrement);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Error calling SWdefdimmap from FORTRAN wrapper. \n");
      H5Epush(__FILE__, "HE5_SWdefdimmapF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  
  free(errbuf);

  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefidxmapF                                                 |
|                                                                             |
|  DESCRIPTION: Defines index mapping between geolocation and data dimensions |
|               (FORTRAN wrapper)                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  geo dim.       char                geolocation dimension                   |
|  data dim.      char                data dimension                          |
|  index          long                array of indices                        |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov    Original Version                                    |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int 
HE5_SWdefidxmapF(int SwathID, char *geodim, char *datadim, long index[])
{
  herr_t	status     = SUCCEED;/* HDF5 type return status variable */
  
  int       ret        = SUCCEED;/* (int) return status variable     */  

  hid_t     swathID    = FAIL;   /* HDF5 type swath ID               */
  
  char		*errbuf    = (char *)NULL;/* Error message buffer        */

  errbuf = (char *)calloc(HE5_HDFE_ERRBUFSIZE, sizeof(char));
  
  swathID = (hid_t)SwathID; 
  status = HE5_SWdefidxmap(swathID, geodim, datadim, index);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Error calling SWdefidxmap from FORTRAN wrapper. \n");
      H5Epush(__FILE__, "HE5_SWdefidxmapF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  
  free(errbuf);

  ret = (int)status;
  return(ret);
}





/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefgfld                                                    |
|                                                                             |
|  DESCRIPTION: Defines geolocation field within swath structure (FORTRAN)    |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        int                 swath structure ID                      |
|  fieldname      char                fieldname                               |
|  fortdimlist    char                Dimension list (comma-separated list)   |
|                                         FORTRAN dimesion order              |
|  fortmaxdimlist char                Max Dimension list (FORTRAN order)      |
|  numbertype     int                 field type                              |
|  merge          int                 merge code                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Nov 99   Abe Taaheri   Modified for HDF5                                   |
|  May 00   D.Wynne       Updated to reflect datatypes changes throughout     |
|                         the library                                         |
|  Sep 00   A.Muslimov    Updated to reflect most recent data type changes.   |
|  Nov 00   A.Muslimov    Updated to reverse order of "fortmaxdimlist"entries.|
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWdefgfld(int swathID, char *fieldname, char *fortdimlist, char *fortmaxdimlist, int numtype, int merge)
{
  int       ret        = SUCCEED;    /* (int) return status variable   */

  herr_t    status     = SUCCEED;	 /* routine return status variable */
  
  hid_t     SwathID    = FAIL;       /* HDF5 type swath ID             */
  hid_t	    numbertype = FAIL;       /* HDF5 tyep data type  ID        */
  
  char		*dimlist   = (char *)NULL;/* Dimension list (C order)      */
  char		*maxdimlist= (char *)NULL;/* Max. dimension list (C)       */
  char		*errbuf    = (char *)NULL;/* error message buffer          */

  /* Allocate memory for error message buffers */
  /* ----------------------------------------- */
  errbuf  = (char * )calloc(HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWdefgfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }

  if(strcmp(fortmaxdimlist,"") == 0)
    fortmaxdimlist = NULL;


  /* Convert data type ID */
  /* -------------------- */
  numbertype = HE5_EHconvdatatype(numtype);
  if(numbertype == FAIL)
    {
      sprintf(errbuf,"Cannot convert \"int\" data type ID to HDF5 data type ID.\n");
      H5Epush(__FILE__, "HE5_SWdefgfld", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }


  /* Allocate space for C order dimension list */
  /* ----------------------------------------- */
  dimlist = (char *)calloc(strlen(fortdimlist) + 1, sizeof(char));
  if(dimlist == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for dimlist.\n");
      H5Epush(__FILE__, "HE5_SWdefgfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  
  /* Reverse entries in dimension list (FORTRAN -> C) */
  /* ------------------------------------------------ */
  status = HE5_EHrevflds(fortdimlist, dimlist);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot reverse entries in dimension list.\n");
      H5Epush(__FILE__, "HE5_SWdefgfld", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(dimlist);
      return(FAIL);
    }

  if (fortmaxdimlist != NULL)
    {
      /* Allocate space for C order maximum dimension list */
      /* ------------------------------------------------- */
      maxdimlist = (char *)calloc(strlen(fortmaxdimlist) + 1, sizeof(char));
      if(maxdimlist == NULL)
	{
	  sprintf(errbuf,"Cannot allocate memory for maxdimlist.\n");
	  H5Epush(__FILE__, "HE5_SWdefgfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(dimlist);
	  free(errbuf);
	  return(FAIL);
	}

      /* Reverse entries in maximum dimension list (FORTRAN -> C) */
      /* -------------------------------------------------------- */
      status = HE5_EHrevflds(fortmaxdimlist, maxdimlist);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot reverse entries in maximum dimension list.\n");
	  H5Epush(__FILE__, "HE5_SWdefgfld", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(errbuf);
	  free(dimlist);
	  free(maxdimlist);
	  return(FAIL);
	}
	  
    }
  else 
    {
      maxdimlist = NULL;
    }


  SwathID = (hid_t)swathID;
    
  
  /* Call Define Field routine */
  /* ------------------------- */
  status = HE5_SWdefinefield(SwathID, "Geolocation Fields", fieldname, dimlist, maxdimlist, numbertype, merge);
  if(status == FAIL)
    {
      sprintf(errbuf,"Error calling HE5_SWdefinefield() from FORTRAN wrapper.\n");
      H5Epush(__FILE__, "HE5_SWdefgfld", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(dimlist);
      if (maxdimlist !=NULL) 
	free(maxdimlist);
	  
      return(FAIL);
    }  

  free(dimlist);
  if (maxdimlist !=NULL) 
    free(maxdimlist);
  
  free(errbuf);

  ret = (int)status;
  return (ret);
}
 
/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefdfld                                                    |
|                                                                             |
|                                                                             |
|  DESCRIPTION: Defines data field within swath structure (FORTRAN)           |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t              return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        int                 swath structure ID                      |
|  fieldname      char                fieldname                               |
|  fortdimlist    char                Dimension list (comma-separated list)   |
|                                         FORTRAN dimesion order              |
|  fortmaxdimlist char                Max Dimension list (FORTRAN order)      |
|  numbertype     int                 field type                              |
|  merge          int                 merge code                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Sep 00   A.Muslimov    Updated to reflect most recent data type changes.   |
|  Nov 00   A.Muslimov    Updated to reverse order of "fortmaxdimlist"entries.|
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWdefdfld(int swathID, char *fieldname, char *fortdimlist, char *fortmaxdimlist, int numtype, int merge)
 
{
  int       ret        = SUCCEED;/* (int) return status variable   */  

  herr_t	status     = SUCCEED;/* routine return status variable */

  hid_t     SwathID    = FAIL;   /* HDF5 type swath ID             */
  hid_t	    numbertype = FAIL;   /* HDF5 type data type ID         */
  
  char		*dimlist   = (char *)NULL;/* Dimension list (C order)  */
  char		*maxdimlist= (char *)NULL;/* Max. dimension list (C)   */
  char		*errbuf    = (char *)NULL;/* error message buffer      */

  SwathID = (hid_t)swathID;

  numbertype = HE5_EHconvdatatype(numtype);
  if(numbertype == FAIL)
    {
      H5Epush(__FILE__, "HE5_SWdefdfld", __LINE__, H5E_DATATYPE, H5E_BADVALUE, "Cannot convert datatype for FORTRAN wrapper.");
      HE5_EHprint("Error: Cannot convert datatype for FORTRAN wrapper, occured", __FILE__, __LINE__);
      return(FAIL);
    }
  
  if(strcmp(fortmaxdimlist,"") == 0)
    fortmaxdimlist = NULL;
  
  
  /* Allocate memory for error message buffers */
  /* ----------------------------------------- */
  errbuf  = (char * )calloc(HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWdefdfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
  
  /* Allocate space for C order dimension list */
  /* ----------------------------------------- */
  dimlist = (char *)calloc(strlen(fortdimlist) + 1, sizeof(char));
  if(dimlist == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for dimlist.\n");
      H5Epush(__FILE__, "HE5_SWdefdfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  
  /* Reverse entries in dimension list (FORTRAN -> C) */
  /* ------------------------------------------------ */
  status = HE5_EHrevflds(fortdimlist, dimlist);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot reverse entries in dimension list.\n");
      H5Epush(__FILE__, "HE5_SWdefdfld", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(dimlist);
      return(FAIL);
    }

  if (fortmaxdimlist != NULL)
    {
      /* Allocate space for C order max. dim. list */
      /* ----------------------------------------- */
      maxdimlist = (char *)calloc(strlen(fortmaxdimlist) + 1, sizeof(char));
      if(maxdimlist == NULL)
	{
	  sprintf(errbuf,"Cannot allocate memory for maxdimlist.\n");
	  H5Epush(__FILE__, "HE5_SWdefdfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(dimlist);
	  free(errbuf);
	  return(FAIL);
	}


      /* Reverse entries in dimension list (FORTRAN -> C) */
      /* ------------------------------------------------ */
      status = HE5_EHrevflds(fortmaxdimlist, maxdimlist);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot reverse entries in maximum dimension list.\n");
	  H5Epush(__FILE__, "HE5_SWdefdfld", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(errbuf);
	  free(dimlist);
	  free(maxdimlist);
	  return(FAIL);
	}
    }
  else
    {
      maxdimlist = NULL;
    }
	  
  
  /* Call Define Field routine */
  /* ------------------------- */
  status = HE5_SWdefinefield(SwathID, "Data Fields", fieldname, dimlist, maxdimlist, numbertype, merge);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot define \"%s\" field.\n", fieldname);
      H5Epush(__FILE__, "HE5_SWdefdfld", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(dimlist);
      if (maxdimlist!=NULL) 
	free(maxdimlist);
	  
      return(FAIL);
    }
  
  free(dimlist);
  if (maxdimlist != NULL) 
    free(maxdimlist);
  
  free(errbuf);

  ret = (int)status;
  return (ret);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefcompF      (FORTRAN wrapper)                            |
|                                                                             |
|  DESCRIPTION: Defines compression type and parameters                       |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int     None        return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|  compcode       int                 compression code                        |
|  compparm       int                 compression parameters                  |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:   Before calling this function, storage must be CHUNKED             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int   
HE5_SWdefcompF(int SwathID, int compcode,  int *compparm)
{
  int             ret      = FAIL; /* routine return status variable   */

  herr_t          status   = FAIL; /* routine return status variable   */

  hid_t           swathID  = FAIL; /* HDF5 type  Swath ID              */

  char            errbuf[HE5_HDFE_ERRBUFSIZE]; /* Error message buffer     */

  swathID = (hid_t)SwathID;

  status = HE5_SWdefcomp(swathID, compcode, compparm);
  if(status == FAIL)
    {
      sprintf(errbuf,"Error calling SWdefcomp() from FORTRAN wrapper.\n");
      H5Epush(__FILE__, "HE5_SWdefcompF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

  ret = (int)status;
  return(ret);

}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefchunkF                                                  |
|                                                                             |
|  DESCRIPTION: FORTRAN wrapper for SWdefchunk                                |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  ndims          int                 rank of a dataset                       |
|  *dim           long                pointer to the array containing sizes   |
|                                     of each dimension of a chunk            |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date         Programmer    Description                                    |
|  =========   ============  ==============================================   |
|  8/13/99     A.Muslimov    Changed the return type of SWdefchunk from intn  |
|                            to herr_t. Checked the statuses for H5P... calls.|
|  May 00      D.Wynne       Updated to reflect datatype changes in Library   |
|  Aug 00      A.Muslimov    Updated to reflect data type changes.            |
|  Jan 01      A.Muslimov    Added proper FORTRAN to C dimension order        |
|                             conversion.                                     |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWdefchunkF(int SwathID, int ndims, long *dim)
{
  int		ret       = FAIL;           /* return status        */
  int		j = 0;                      /* Loop index           */

  herr_t	status    = FAIL;           /* return status        */

  hid_t     swathID   = FAIL;           /* HDF5 type swath ID   */

  hsize_t	*tempdims = (hsize_t *)NULL;/* Temporary variable   */
  
  char		*errbuf   = (char *)NULL;   /* error message buffer */

  /* Allocate memory for error message buffer */
  errbuf  = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWdefchunkF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
  
  /* Allocate space for C order dimension list */
  /* ----------------------------------------- */
  tempdims = (hsize_t *)calloc(ndims, sizeof(hsize_t));
  if(tempdims == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for tempdims.\n");
      H5Epush(__FILE__, "HE5_SWdefchunkF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  
  
  /* Change from FORTRAN to C dimension order */
  /* ---------------------------------------- */
  for (j = 0; j < ndims; j++)
    tempdims[j] = (hsize_t)dim[ndims - 1 - j];


  swathID = (hid_t)SwathID;

  status = HE5_SWdefchunk(swathID, ndims, tempdims);
  if(status == FAIL)
    {
      sprintf(errbuf,"Error calling SWdefchunk() from FORTRAN wrapper.\n");
      H5Epush(__FILE__, "HE5_SWdefchunkF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(tempdims);
      return(FAIL);
    }

  
  free(tempdims);
  free(errbuf);
  
  ret = (int)status;
  return(ret);
 
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWcompinfoF  (FORTRAN wrapper)                               |
|                                                                             |
|  DESCRIPTION:                                                               |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int     None        Return status  (0) SUCCEED, (-1) FAIL   |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int     None        Swath Object ID                         |
|  compcode       int                                                         |
|  compparm       int                                                         |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int 
HE5_SWcompinfoF(int SwathID, char *fieldname, int *compcode, int compparm[])
{
  int             ret      = FAIL;        /* Return status variable       */

  herr_t          status   = FAIL;        /* Return status variable       */

  hid_t           swathID  = FAIL;        /* HDF5 type Swath ID           */

  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer     */


  swathID = (hid_t)SwathID;

  status = HE5_SWcompinfo(swathID, fieldname, compcode, compparm);
  if (status == FAIL)
    {
      sprintf(errbuf , "Compression information for \"%s\" not found.\n", fieldname);
      H5Epush(__FILE__, "HE5_SWcompinfoF", __LINE__, H5E_BTREE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWwrcharfld                                                  |
|                                                                             |
|  DESCRIPTION: Writes data to a character string field (FORTRAN wrapper      |
|               around SWwritefield)                                          |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  fieldname      char                fieldname                               |
|  elemlen        int                 each element length in array of string  |
|  numelem        int                 number of elements in declared buffer   |
|                                     array                                   |
|  fortstart      long                start array                             |
|  fortstride     long                stride array                            |
|  fortedge       long                edge array                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  data           void                data buffer for write                   |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04   S.Zhao        For an array of character string dataset.           |
|  Jun 04   S.Zhao        Added one more argument (numelem).                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWwrcharfld(int SwathID, char *fieldname, int elemlen, int numelem, long fortstart[], long fortstride[], long fortedge[], void *data)
{
  int             ret      = SUCCEED;       /* int return status variable     */
  int             i;                        /* Loop index                     */
  int             rank     = 0;             /* Field rank                     */
 
  herr_t          status   = SUCCEED;       /* routine return status variable */
 
  hid_t           ntype[1] = {FAIL};        /* Field numbertypes              */
 
  hid_t           swathID  = FAIL;          /* HDF-EOS swath ID               */
 
  hssize_t        *start  = (hssize_t *)NULL;/* Pointer to start array (C order)  */
 
  hsize_t         dims[HE5_DTSETRANKMAX];    /* Field dimensions                  */
  hsize_t         *stride = (hsize_t *)NULL; /* Pointer to stride array (C order) */
  hsize_t         *edge   = (hsize_t *)NULL; /* Pointer to edge array (C order)   */
 
  char            *errbuf = (char *)NULL;    /* error message buffer              */
  char            **strdatabuf = NULL;       /* string data buffer                */
  int             nelem = 0;                 /* number of elements in array of str*/
  int             strsize = 0;               /* each str length in array of str   */
  char            *blankPtr = (char *)NULL;  /* pointer to blank character        */
  char            *tmpString = (char *)NULL; /* pointer to temp string            */
  int             attr = 0;                  /* attribute value                   */
  hsize_t         count[1];                  /* number of attribute elements      */
 
 
  /* Allocate memory for error message buffer */
  /* ---------------------------------------- */
  errbuf  = (char *)calloc(HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWwrcharfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
 
  swathID = (hid_t)SwathID;
 
  /* Initialize dims[] array */
  /* ----------------------- */
  for ( i = 0; i < HE5_DTSETRANKMAX; i++)
    dims[ i ] = 0;
 
  /* Get field info  */
  /* --------------- */
  status = HE5_SWfieldinfo(swathID, fieldname, &rank, dims, ntype, NULL, NULL);
  if (status != FAIL)
    {
      start = (hssize_t *)calloc(rank, sizeof(hssize_t));
      if(start == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for start.\n");
	  H5Epush(__FILE__, "HE5_SWwrcharfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(errbuf);
	  return(FAIL);
        }
 
      stride = (hsize_t *)calloc(rank, sizeof(hsize_t));
      if(stride == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for stride.\n");
	  H5Epush(__FILE__, "HE5_SWwrcharfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(errbuf);
	  return(FAIL);
        }
 
      edge = (hsize_t *)calloc(rank, sizeof(hsize_t));
      if(edge == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for edge.\n");
	  H5Epush(__FILE__, "HE5_SWwrcharfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  free(errbuf);
	  return(FAIL);
        }
 
      /* Reverse order of dimensions (FORTRAN -> C) */
      /* ------------------------------------------ */
      for (i = 0; i < rank; i++)
        {
	  start[i]  = (hssize_t)fortstart[rank - 1 - i];
	  stride[i] = (hsize_t)fortstride[rank - 1 - i];
	  edge[i]   = (hsize_t)fortedge[rank - 1 - i];
        }
 
      strsize = elemlen;
      nelem = dims[0];

      tmpString = (char *)calloc(1,strsize+1);
      if(tmpString == NULL)
	{
	  sprintf(errbuf,"Cannot allocate memory for tmpString.\n");
	  H5Epush(__FILE__, "HE5_SWwrcharfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  free(edge);
	  free(errbuf);
	  return(FAIL);
	}
 
      strdatabuf = (char **)malloc(nelem*sizeof(char *));
      for (i = 0; i<nelem; i++)
	{
	  strdatabuf[i] = NULL;
	  strdatabuf[i] = (char *)malloc((strsize+1)*sizeof(char));
	  strncpy(strdatabuf[i],(char *)data+(strsize*i), strsize);
	  strdatabuf[i][strsize] = '\0';
	  strcpy(tmpString,strdatabuf[i]);
 
	  /* Find the first non blank character from the end */
	  /* ----------------------------------------------- */
	  blankPtr = tmpString + strsize -1;
	  while (*blankPtr == ' ')
	    {
	      blankPtr--;
	    }
 
	  /* Turn it into a C string */
	  /* ----------------------- */
	  blankPtr++;
	  *blankPtr = '\0';
 
	  strcpy(strdatabuf[i], tmpString);
	} 
 
      free(tmpString);

      count[0] = 1;
      attr = strsize;
      status = HE5_SWwritelocattr(swathID, fieldname, "StringLengthAttribute", H5T_NATIVE_INT, count, &attr);
      if (status == FAIL)
	{
	  sprintf(errbuf, "Cannot write attribute to the field \"%s\".",fieldname) ;
	  H5Epush(__FILE__, "HE5_SWwrcharfld", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  free(edge);
	  free(errbuf);
	  if (strdatabuf != NULL)
	    {
	      for (i = 0; i<nelem; i++)
		{
		  if (strdatabuf[i] != NULL)
		    {
		      free (strdatabuf[i]);
		      strdatabuf[i] = NULL;
		    }
		}
	      free (strdatabuf);
	      strdatabuf = NULL;
	    }
	  return(FAIL);
	}
 
      status = HE5_SWwrrdfield(swathID, fieldname, "w", start, stride, edge, strdatabuf);
      if (status == FAIL)
	{
	  sprintf(errbuf, "Cannot write data to the field \"%s\".",fieldname) ;
	  H5Epush(__FILE__, "HE5_SWwrcharfld", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  free(edge);
	  free(errbuf);
	  if (strdatabuf != NULL)
	    {
	      for (i = 0; i<nelem; i++)
		{
		  if (strdatabuf[i] != NULL)
		    {
		      free (strdatabuf[i]);
		      strdatabuf[i] = NULL;
		    }
		}
	      free (strdatabuf);
	      strdatabuf = NULL;
	    }

	  return(FAIL);
	}
 
      free(start);
      free(stride);
      free(edge);
      free(errbuf);
      if (strdatabuf != NULL)
	{
	  for (i = 0; i<nelem; i++)
	    {
	      if (strdatabuf[i] != NULL)
		{
		  free (strdatabuf[i]);
		  strdatabuf[i] = NULL;
		}
	    }
	  free (strdatabuf);
	  strdatabuf = NULL;
	}

    }
  else
    {
      sprintf(errbuf, "Error calling HE5_SWfieldinfo() from FORTRAN wrapper. \n") ;
      H5Epush(__FILE__, "HE5_SWwrcharfld", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      status = FAIL;
 
      free(errbuf);
    }
 
  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWwrfld                                                      |
|                                                                             |
|  DESCRIPTION: Writes data to field (FORTRAN wrapper around SWwritefield)    |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  fieldname      char                fieldname                               |
|  fortstart      long                start array                             |
|  fortstride     long                stride array                            |
|  fortedge       long                edge array                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  data           void                data buffer for write                   |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Nov 99   Abe Taaheri   Modified for HDF5                                   |
|  Aug 00   A.Muslimov    Modified to conform to HDF5 data types.             |
|  Feb 05   S.Zhao        Replaced the "myedge" array by the "dims" array if  |
|                         it was larger than the dimension size.              |
|  Sep 11   Abe Taaheri   Modified for correcting Unlimited dimension         |
|                         behavior and extension                              |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWwrfld(int SwathID, char *fieldname, long fortstart[], long fortstride[],
 long fortedge[], void *data)
{
  int             ret      = SUCCEED;       /* int return status variable     */
  int             i;                        /* Loop index                     */
  int   	  rank     = 0;             /* Field rank                     */

  herr_t          status   = SUCCEED;       /* routine return status variable */

  hid_t   	  ntype[1] = {FAIL};        /* Field numbertypes              */
 
  hid_t           swathID  = FAIL;          /* HDF-EOS swath ID               */
    
  hssize_t        *start  = (hssize_t *)NULL;/* Pointer to start array (C order)  */

  hsize_t         dims[HE5_DTSETRANKMAX];    /* Field dimensions                  */
  hsize_t         *stride = (hsize_t *)NULL; /* Pointer to stride array (C order) */
  hsize_t         *edge   = (hsize_t *)NULL; /* Pointer to edge array (C order)   */
  
  char            *errbuf = (char *)NULL;    /* error message buffer              */
  hsize_t         *myedge = (hsize_t *)NULL;
  int             unlimdim;
  hsize_t         maxdims[HE5_DTSETRANKMAX];/* Field maximum dimensions     */
  int             append   = FALSE;         /* FLAG (if field is appendable)*/

  /* Allocate memory for error message buffer */
  /* ---------------------------------------- */
  errbuf  = (char *)calloc(HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWwrfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
  
  swathID = (hid_t)SwathID;

  /* Initialize dims[] , maxdims[] array */
  /* ----------------------- */
  for ( i = 0; i < HE5_DTSETRANKMAX; i++)
    {
      dims[ i ] = 0;
      maxdims[ i ] = 0;
    }

  /* Get field info  */
  /* --------------- */
  status = HE5_SWfieldinfo(swathID, fieldname, &rank, dims, ntype, NULL, NULL);
  if (status != FAIL)
    {
      start = (hssize_t *)calloc(rank, sizeof(hssize_t));
      if(start == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for start.\n");
	  H5Epush(__FILE__, "HE5_SWwrfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(errbuf);
	  return(FAIL);
        }

      stride = (hsize_t *)calloc(rank, sizeof(hsize_t));
      if(stride == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for stride.\n");
	  H5Epush(__FILE__, "HE5_SWwrfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(errbuf);
	  return(FAIL);
        }

      edge = (hsize_t *)calloc(rank, sizeof(hsize_t));
      if(edge == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for edge.\n");
	  H5Epush(__FILE__, "HE5_SWwrfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  free(errbuf);
	  return(FAIL);
        }

      /* Reverse order of dimensions (FORTRAN -> C) */
      /* ------------------------------------------ */
      for (i = 0; i < rank; i++)
        {
	  start[i]  = (hssize_t)fortstart[rank - 1 - i];
	  stride[i] = (hsize_t)fortstride[rank - 1 - i];
	  edge[i]   = (hsize_t)fortedge[rank - 1 - i];
        }

      myedge = (hsize_t *)calloc(rank, sizeof(hsize_t));
      if(myedge == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for edge.\n");
	  H5Epush(__FILE__, "HE5_SWwrfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  free(edge);
	  free(errbuf);
	  return(FAIL);
        }
 
      /* get maxdims for the field */
      status = HE5_SWflddiminfo(swathID, fieldname, &rank, dims, maxdims);

      /* see if we need first to extend data dimensions for unlimited 
	 dimensions */

      for (i = 0; i < rank; i++)
        {
	  if( dims[i] == maxdims[i] )
	    append = FALSE;
	  else if ( (dims[i] < maxdims[i]) || (maxdims[i] == H5S_UNLIMITED))
	    {
	      append = TRUE;
	      break;
	    }
	}
      unlimdim = i;

      if(append == FALSE)
	{
      for (i = 0; i < rank; i++)
        {
	  if(edge[i] > dims[i])
	    myedge[i] = dims[i];
	  else
	    myedge[i] = edge[i];
        }
	}
      else
	{
	  for (i = 0; i < rank; i++)
	    {
	      myedge[i] = edge[i];
	    }
	}

      if((append == TRUE) && (edge[unlimdim] > dims[unlimdim]))
	{
	  hssize_t newstart[8];
	  hsize_t newedge[8];

	  for (i = 0; i < rank; i++)
	    {
	      newstart[i]=start[i];
	      newedge[i] = edge[i];
	    }
	  newstart[unlimdim]=edge[unlimdim]-1;
	  newedge[unlimdim] = 1;
	  status = HE5_SWwrrdfield(swathID, fieldname, "w", newstart, stride, newedge,data);
	  if (status == FAIL)
	    {
	      sprintf(errbuf, "Cannot write data to the field \"%s\".",fieldname) ;
	      H5Epush(__FILE__, "HE5_SWwrfld", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(start);
	      free(stride);
	      free(edge);
	      free(myedge);
	      free(errbuf);
	      return(FAIL);
	    }
	  else
	    {
	      for (i = 0; i < rank; i++)
		{
		  dims[i]=edge[i];
		}
	    }
	}

      status = HE5_SWwrrdfield(swathID, fieldname, "w", start, stride, myedge,data);
      if (status == FAIL)
        {
	  sprintf(errbuf, "Cannot write data to the field \"%s\".",fieldname) ;
	  H5Epush(__FILE__, "HE5_SWwrfld", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  free(edge);
	  free(myedge);
	  free(errbuf);
	  return(FAIL);
        }

      free(start);
      free(stride);
      free(edge);
      free(myedge);
      free(errbuf);

    }
  else
    {
      sprintf(errbuf, "Error calling HE5_SWfieldinfo() from FORTRAN wrapper. \n") ;
      H5Epush(__FILE__, "HE5_SWwrfld", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      status = FAIL;
 
      free(errbuf);
    }
 
  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWwrattr                                                     |
|                                                                             |
|  DESCRIPTION: FORTRAN wrapper for Writes/updates attribute in a swath.      |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  attrname       char*               attribute name                          |
|  numtype        int                 attribute HDF numbertype                |
|  fortcount[]    long                Number of attribute elements            |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Oct 99   Abe Taaheri   Modified data types                                 |
|  Aug 00   A.Muslimov    Modified to conform to HDF5 data types              |
|  Nov 02   S.Zhao        Modified to get the size of a string attribute.     |
|  Mar 04   S.Zhao        Modified for a character string attribute.          |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWwrattr(int SwathID, char *attrname, int numtype, long fortcount[], void * datbuf)
{
  int       ret     = FAIL;/* int return status variable                 */
  int       rank    = 1;   /* Note: It is assumed that fortcout has just */
  /* one element to agree with EHattr function  */
  int		i;             /* Loop index                                 */

  hid_t     swathID    = FAIL;/* HDF-EOS Swath ID                        */
  hid_t     numbertype = FAIL;/* HDF5 data type ID                       */ 

  herr_t	status     = FAIL;/* routine return status variable          */
  
  hsize_t	*count     = (hsize_t *)NULL;/* Pointer to count array (C order)*/
    
  char      *errbuf = (char *)NULL;   /* error message buffer            */
  char      *tempbuf = (char *)NULL;  /* temp buffer */
  
  numbertype = HE5_EHconvdatatype(numtype);
  if(numbertype == FAIL)
    {
      H5Epush(__FILE__, "HE5_SWwrattr", __LINE__, H5E_DATATYPE, H5E_BADVALUE, "Error calling HE5_EHconvdatatype() from FORTRAN wrapper.");
      HE5_EHprint("Error: Error calling HE5_EHconvdatatype() from FORTRAN wrapper, occured", __FILE__, __LINE__);
      return(FAIL);
    }
  
  /* Allocate memory for error message buffer */
  /* ---------------------------------------- */
  errbuf  = (char *)calloc(HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWwrattr", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }

  /* Allocate memory for "count" array */
  /* --------------------------------- */
  count = (hsize_t *)calloc(rank, sizeof(hsize_t));
  if( count == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for count.\n");
      H5Epush(__FILE__, "HE5_SWwrattr", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }

  /* Reverse order of dimensions (FORTRAN -> C) */
  /* ------------------------------------------ */
  for (i = 0; i < rank; i++)
    {
      count[i] = (hsize_t)fortcount[rank - 1 - i];
    }
  
  swathID = (hid_t)SwathID;

  if ((numbertype == HE5T_CHARSTRING) || (numbertype == H5T_NATIVE_CHAR) || (numbertype == H5T_C_S1))
    {
      if (strlen((char *)datbuf) < count[0])
	{
	  sprintf(errbuf,"Size of databuf is less than the number of attribute elements.\n");
	  H5Epush(__FILE__, "HE5_SWwrattr", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(count);
	  free(errbuf);
	  return(FAIL);
	}
 
      /* Allocate memory for temp buffer */
      /* ------------------------------- */
      tempbuf = (char * )calloc((count[0]+1), sizeof(char));
      if(tempbuf == NULL)
	{
	  sprintf(errbuf,"Cannot allocate memory for temp buffer.\n"); 
	  H5Epush(__FILE__, "HE5_SWwrattr", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(count);
	  free(errbuf);
	  return(FAIL);
	}

      strncpy(tempbuf, (char *)datbuf, count[0]);
      tempbuf[count[0]] = '\0';
 
      /* Call SWwriteattr() */
      /* ------------------ */
      status = HE5_SWwriteattr(swathID, attrname, numbertype, count, tempbuf);
      if( status == FAIL)
	{
          sprintf(errbuf,"Cannot write data to the attribute \"%s\".\n", attrname);
          H5Epush(__FILE__, "HE5_SWwrattr", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          free(count);
          free(errbuf);
          free(tempbuf);
          return(FAIL);
	}
 
      free(count);
      free(errbuf);
      free(tempbuf);
    }
  else
    {
      /* Call SWwriteattr() */
      /* ------------------ */
      status = HE5_SWwriteattr(swathID, attrname, numbertype, count, datbuf);
      if( status == FAIL)
	{
	  sprintf(errbuf,"Cannot write data to the attribute \"%s\".\n", attrname);
	  H5Epush(__FILE__, "HE5_SWwrattr", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(count);
	  free(errbuf);
          return(FAIL);
	}
      free(count);
      free(errbuf);
    }

  ret = (int)status;
  return(ret);
}
 
/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWsetfill  (FORTRAN wrapper)                                 |
|                                                                             |
|  DESCRIPTION: Sets fill value for the specified field.                      |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  fieldname      char*               field name                              |
|  fillval        void*               fill value                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWsetfill(int SwathID, char *fieldname, int numtype, void *fillval)
{
  int          ret        = FAIL;/* int return status variable  */ 

  herr_t       status     = FAIL;/* return status variable      */
 
  hid_t        numbertype = FAIL;/* HDF5 data tyope ID          */
  hid_t        swathID    = FAIL;/* HDF5 Swath ID               */

  char         errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer  */

  numbertype = HE5_EHconvdatatype(numtype);
  if(numbertype == FAIL)
    {
      sprintf(errbuf,"Cannot convert to HDF5 type data type ID from FORTRAN wrapper.\n");
      H5Epush(__FILE__, "HE5_SWsetfill", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  swathID = (hid_t)SwathID;
  status = HE5_SWsetfillvalue(swathID, fieldname, numbertype, fillval);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot set fill value for the field \"%s\".\n", fieldname);
      H5Epush(__FILE__, "HE5_SWsetfill", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

  ret = (int)status;
  return(ret);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWgetfill   (FORTRAN wrapper)                                |
|                                                                             |
|  DESCRIPTION: Retrieves fill value for a specified field.                   |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|  fieldname      char*               field name                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  fillval        void*               fill value                              |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int   
HE5_SWgetfill(int SwathID, char *fieldname, void *fillval)
{
  int             ret      = FAIL;/* routine return status variable   */

  herr_t          status   = FAIL;/* routine return status variable   */

  hid_t           swathID  = FAIL;/* HDF5 type swath ID               */
    
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */

  swathID = (hid_t)SwathID;

  status = HE5_SWgetfillvalue(swathID, fieldname, fillval);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot get fill value for the field \"%s\".\n", fieldname);
      H5Epush(__FILE__, "HE5_SWgetfill", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

  ret = (int)status;
  return (ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWrdfld                                                      |
|                                                                             |
|  DESCRIPTION: Reads data from field (FORTRAN wrapper around SWreadfield)    |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  fieldname      char                fieldname                               |
|  fortstart      long                start array                             |
|  fortstride     long                stride array                            |
|  fortedge       long                edge array                              |
|  buffer         void                data buffer for read                    |
|                                                                             |
|                                                                             |
|  OUTPUTS:                                                                   |
|     None                                                                    |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Nov 99   Abe Taaheri   Modified for HDF5                                   |
|  May 00   D.Wynne       Updated to reflect data type changes                |
|  Aug 00   A.Muslimov    Updated to conform to HDF5 data types               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWrdfld(int SwathID, char *fieldname, long fortstart[], long fortstride[], long fortedge[], void *buffer)
 
{
  int              ret      = SUCCEED;       /* routine return status variable */
  int              i        = 0;             /* Loop index                     */
  int              rank     = 0;             /* Field rank                     */
 
  hid_t            ntype[1] = {FAIL};        /* Field number types             */
 
  hid_t            swathID  = FAIL;          /* Swath HDF5 type  ID            */
 
  herr_t           status   = SUCCEED;       /* routine return status variable */
 
  hssize_t         *start  = (hssize_t *)NULL;/* Pointer to start array (C order)  */
  hsize_t          dims[HE5_DTSETRANKMAX];    /* Field dimensions                  */
  hsize_t          *stride = (hsize_t *)NULL; /* Pointer to stride array (C order) */
  hsize_t          *edge   = (hsize_t *)NULL; /* Pointer to edge array (C order)   */
 
  char             *errbuf = (char *)NULL;    /* error message buffer              */
 
 
  /* Allocate memory for error message buffers */
  /* ----------------------------------------- */
  errbuf  = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWrdfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
 
  swathID = (hid_t)SwathID;
 
  /* Initialize dims[] array */
  /* ----------------------- */
  for ( i = 0; i < HE5_DTSETRANKMAX; i++)
    dims[ i ] = 0;
 
  /* Get field info */
  /* -------------- */
  status = HE5_SWfieldinfo(swathID, fieldname, &rank, dims, ntype, NULL,NULL);
  if (status != FAIL)
    {
      start =  (hssize_t *)calloc(rank, sizeof(hssize_t));
      if(start == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for start.\n");
	  H5Epush(__FILE__, "HE5_SWrdfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(errbuf);
	  return(FAIL);
        }
      stride = (hsize_t *)calloc(rank, sizeof(hsize_t));
      if(stride == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for stride.\n");
	  H5Epush(__FILE__, "HE5_SWrdfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(errbuf);
	  return(FAIL);
        }
      edge = (hsize_t *)calloc(rank, sizeof(hsize_t));
      if(edge == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for edge.\n");
	  H5Epush(__FILE__, "HE5_SWrdfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  free(errbuf);
	  return(FAIL);
        }
 
      /* Reverse order of dimensions (FORTRAN -> C) */
      /* ------------------------------------------ */
      for (i = 0; i < rank; i++)
        {
	  start[i]  = (hssize_t)fortstart[rank - 1 - i];
	  stride[i] = (hsize_t)fortstride[rank - 1 - i];
	  edge[i]   = (hsize_t)fortedge[rank - 1 - i];
        }
 
      /* Read data from the field */
      /* ------------------------ */
      status = HE5_SWwrrdfield(swathID, fieldname, "r", start, stride, edge, buffer);
      if (status == FAIL)
        {
	  sprintf(errbuf, "Cannot read data from the \"%s\" field.",fieldname) ;
	  H5Epush(__FILE__, "HE5_SWrdfld", __LINE__, H5E_DATASET, H5E_READERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  free(edge);
	  free(errbuf);
	  return(FAIL);
        }
 
      free(start);
      free(stride);
      free(edge);
      free(errbuf);
 
    }
  else
    {
      sprintf(errbuf, "Fieldname \"%s\" does not exist.",fieldname) ;
      H5Epush(__FILE__, "HE5_SWrdfld", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      status = FAIL;
    }
 
 
  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWrdcharfld                                                  |
|                                                                             |
|  DESCRIPTION: Reads data from a character string field (FORTRAN wrapper     |
|               around SWreadfield)                                           |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  fieldname      char                fieldname                               |
|  elemlen        int                 each element length in array of string  |
|  numelem        int                 number of elements in declared buffer   |
|                                     array                                   |
|  fortstart      long                start array                             |
|  fortstride     long                stride array                            |
|  fortedge       long                edge array                              |
|  buffer         void                data buffer for read                    |
|                                                                             |
|  OUTPUTS:                                                                   |
|     None                                                                    |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Apr 04   S.Zhao        For an array of character string dataset.           |
|  Jun 04   S.Zhao        Added two more arguments (elemlen and numelem).     |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWrdcharfld(int SwathID, char *fieldname, int elemlen, int numelem, long fortstart[], long fortstride[], long fortedge[], void *buffer)
 
{
  int		   ret      = SUCCEED;       /* routine return status variable */
  int		   i        = 0;	     /* Loop index                     */
  int		   rank     = 0;             /* Field rank                     */

  hid_t            ntype[1] = {FAIL};        /* Field number types             */

  hid_t            swathID  = FAIL;          /* Swath HDF5 type  ID            */

  herr_t	   status   = SUCCEED;       /* routine return status variable */
    
  hssize_t	   *start  = (hssize_t *)NULL;/* Pointer to start array (C order)  */
  hsize_t	   dims[HE5_DTSETRANKMAX];    /* Field dimensions                  */
  hsize_t	   *stride = (hsize_t *)NULL; /* Pointer to stride array (C order) */
  hsize_t	   *edge   = (hsize_t *)NULL; /* Pointer to edge array (C order)   */
  
  char		   *errbuf = (char *)NULL;    /* error message buffer              */
  char             **strdatabuf = NULL;       /* string data buffer                */
  int              stlen = 0;                 /* whole string array length         */ 
  int              nelem = 0;                 /* number of elements in array of str*/
  int              strsize = 0;               /* each str length in array of str   */
  int              attr = 0;                  /* attribute value                   */
  int              j = 0;                     /* Loop index                        */

  int              num_elem_passed_out;
  int              numread;


  /* Allocate memory for error message buffers */
  /* ----------------------------------------- */
  errbuf  = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWrdcharfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
  
  swathID = (hid_t)SwathID;
  
  /* Initialize dims[] array */
  /* ----------------------- */
  for ( i = 0; i < HE5_DTSETRANKMAX; i++)
    dims[ i ] = 0;

  /* Get field info */
  /* -------------- */
  status = HE5_SWfieldinfo(swathID, fieldname, &rank, dims, ntype, NULL,NULL);  
  if (status != FAIL)
    {
      start =  (hssize_t *)calloc(rank, sizeof(hssize_t));
      if(start == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for start.\n");
	  H5Epush(__FILE__, "HE5_SWrdcharfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(errbuf);
	  return(FAIL);
        }
      stride = (hsize_t *)calloc(rank, sizeof(hsize_t));
      if(stride == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for stride.\n");
	  H5Epush(__FILE__, "HE5_SWrdcharfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(errbuf);
	  return(FAIL);
        }
      edge = (hsize_t *)calloc(rank, sizeof(hsize_t));
      if(edge == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for edge.\n");
	  H5Epush(__FILE__, "HE5_SWrdcharfld", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  free(errbuf);
	  return(FAIL);
        }
 
      /* Reverse order of dimensions (FORTRAN -> C) */
      /* ------------------------------------------ */
      for (i = 0; i < rank; i++)
        {
	  start[i]  = (hssize_t)fortstart[rank - 1 - i];
	  stride[i] = (hsize_t)fortstride[rank - 1 - i];
	  edge[i]   = (hsize_t)fortedge[rank - 1 - i];
        }

      status = HE5_SWreadlocattr(swathID, fieldname, "StringLengthAttribute", &attr);
      if (status == FAIL)
	{
	  sprintf(errbuf, "Cannot read attribute from the field \"%s\".",fieldname) ;
	  H5Epush(__FILE__, "HE5_SWrdcharfld", __LINE__, H5E_DATASET, H5E_READERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  free(edge);
	  free(errbuf);
	  return(FAIL);
	}

      if(elemlen < attr )
	{
	  sprintf(errbuf, "Element length passed in is not correct. Should be same as in declration");
	  H5Epush(__FILE__, "HE5_SWrdcharfld", __LINE__, H5E_DATASET, H5E_READERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  free(edge);
	  free(errbuf);
	  return(FAIL);
	}

      strsize = attr;
      stlen = dims[0] * strsize;
      nelem = stlen / strsize;
      strdatabuf = (char **)malloc(nelem*sizeof(char *));
      for (i = 0; i<nelem; i++)
	{
	  strdatabuf[i] = NULL;
	  strdatabuf[i] = (char *)malloc((strsize+1)*sizeof(char));
	} 

      /* Read data from the field */
      /* ------------------------ */           
      status = HE5_SWwrrdfield(swathID, fieldname, "r", start, stride, edge, strdatabuf);
      if (status == FAIL)
	{
	  sprintf(errbuf, "Cannot read data from the \"%s\" field.",fieldname) ;
	  H5Epush(__FILE__, "HE5_SWrdcharfld", __LINE__, H5E_DATASET, H5E_READERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  free(edge);
	  free(errbuf);
	  if (strdatabuf != NULL)
	    {
	      for (i = 0; i<nelem; i++)
		{
		  if (strdatabuf[i] != NULL)
		    {
		      free (strdatabuf[i]);
		      strdatabuf[i] = NULL;
		    }
		}
	      free (strdatabuf);
	      strdatabuf = NULL;
	    }                                 
	  return(FAIL);
	}
      if(numelem == 0)
	{
	  sprintf(errbuf, "Number of elements passed in cannot be zero.") ;
	  H5Epush(__FILE__, "HE5_SWrdcharfld", __LINE__, H5E_DATASET, H5E_READERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  free(edge);
	  free(errbuf);
	  if (strdatabuf != NULL)
	    {
	      for (i = 0; i<nelem; i++)
		{
		  if (strdatabuf[i] != NULL)
		    {
		      free (strdatabuf[i]);
		      strdatabuf[i] = NULL;
		    }
		}
	      free (strdatabuf);
	      strdatabuf = NULL;
	    }                                 
	  return(FAIL);
	}

      if(edge != NULL)
	{
	  numread = edge[0];
	}
      else
	{
	  numread = (dims[0] - start[0])/stride[0];
	}

      if(numread <= 0)
	{
	  sprintf(errbuf, "Number of elements passed in cannot be zero.") ;
	  H5Epush(__FILE__, "HE5_SWrdcharfld", __LINE__, H5E_DATASET, H5E_READERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  free(edge);
	  free(errbuf);
	  if (strdatabuf != NULL)
	    {
	      for (i = 0; i<nelem; i++)
		{
		  if (strdatabuf[i] != NULL)
		    {
		      free (strdatabuf[i]);
		      strdatabuf[i] = NULL;
		    }
		}
	      free (strdatabuf);
	      strdatabuf = NULL;
	    }                                 
	  return(FAIL);
	}
      if(numread <=  numelem)
	{
	  num_elem_passed_out = numread;
	}
      else
	{
	  num_elem_passed_out = numelem;
	}

      stlen = strlen(strdatabuf[0]);
      strcpy((char *)buffer,strdatabuf[0]);
      for (j = stlen; j < elemlen; j++)
	{
	  strcat((char *)buffer," ");
	}

      for (i = 1; i < num_elem_passed_out; i++)
	{
	  strcat((char *)buffer,strdatabuf[i]);
	  stlen = strlen(strdatabuf[i]);
	  for (j = stlen; j < elemlen; j++)
	    {
	      strcat((char *)buffer," ");
	    }
	}

      free(start);
      free(stride);
      free(edge);
      free(errbuf);
      if (strdatabuf != NULL)
	{
	  for (i = 0; i<nelem; i++)
	    {
	      if (strdatabuf[i] != NULL)
		{
		  free (strdatabuf[i]);
		  strdatabuf[i] = NULL;
		}
	    }
	  free (strdatabuf);
	  strdatabuf = NULL;
	}

    }
  else
    {
      sprintf(errbuf, "Fieldname \"%s\" does not exist.",fieldname) ;
      H5Epush(__FILE__, "HE5_SWrdcharfld", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      status = FAIL;
    }
  

  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWrdattr  (FORTRAN wrapper)                                  |
|                                                                             |
|  DESCRIPTION: Reads attribute from a swath.                                 |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|  attrname       char                attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int    
HE5_SWrdattr(int SwathID, char *attrname, void *datbuf)
{
  int         ret     = FAIL;/* routine return status variable    */

  herr_t      status  = FAIL;/* routine return status variable    */

  hid_t       swathID = FAIL;/* HDF-EOS swath ID                  */

  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */

  swathID = (hid_t)SwathID;

  /* Read the attribute buffer */
  /* ------------------------- */
  status = HE5_SWreadattr(swathID, attrname, datbuf);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Cannot read the attribute value. \n");
      H5Epush(__FILE__, "HE5_SWrdattr", __LINE__, H5E_ATTR, H5E_READERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
  
  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWrdgattr     (FORTRAN wrapper)                              |
|                                                                             |
|  DESCRIPTION: Reads attribute from the "Data Fields" group in a swath.      |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  attrname       char                attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int    
HE5_SWrdgattr(int SwathID, char *attrname, void *datbuf)
{
  int         ret             = FAIL;   /* (int) return status      */

  herr_t      status          = FAIL;   /* return status variable   */
  
  hid_t       swathID         = FAIL;   /* HDF5 type Swath ID       */
  
  char        errbuf[HE5_HDFE_ERRBUFSIZE];  /* Error message buffer */
  
  swathID = (hid_t)SwathID;

  status = HE5_SWreadgrpattr(swathID,attrname,datbuf);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot read Attribute \"%s\" from the \"Data Fields\" group.\n", attrname);
      H5Epush(__FILE__, "HE5_SWrdgattr", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWrdgeogattr     (FORTRAN wrapper)                           |
|                                                                             |
|  DESCRIPTION: Reads attribute from the "Geolocation Fields" group           |
|               in a swath.                                                   |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  attrname       char                attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04    S.Zhao       Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int   
HE5_SWrdgeogattr(int SwathID, char *attrname, void *datbuf)
{
  int         ret             = FAIL;   /* (int) return status      */
 
  herr_t      status          = FAIL;   /* return status variable   */
 
  hid_t       swathID         = FAIL;   /* HDF5 type Swath ID       */
 
  char        errbuf[HE5_HDFE_ERRBUFSIZE];  /* Error message buffer */
 
  swathID = (hid_t)SwathID;
 
  status = HE5_SWreadgeogrpattr(swathID,attrname,datbuf);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot read attribute \"%s\" from the \"Geolocation Fields\" group.\n", attrname);
      H5Epush(__FILE__, "HE5_SWrdgeogattr", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
 
  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWwrlattr                                                    |
|                                                                             |
|  DESCRIPTION: FORTRAN wrapper to Write/update local attribute in a swath.   |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  fieldname      char*               field with local attribute              |
|  attrname       char*               local attribute name                    |
|  numtype        int                 local attribute HDF numbertype          |
|  fortcount[]    long                Number of local attribute elements      |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Apr 00   D.Wynne       Original Programmer                                 |
|  Aug 00   A.Muslimov    Modified to conform to HDF5 data types.             |
|  Nov 02   S.Zhao        Modified to get the size of a string attribute.     |
|  Mar 04   S.Zhao        Modified for a character string attribute.          |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWwrlattr(int SwathID, char *fieldname, char *attrname, int numtype, long fortcount[], void *datbuf)
{
  int		   ret  = FAIL;             /* routine return status variable             */
  int 	       rank = 1;                /* Note: It is assumed that fortcout has just */
  /* one element to agree with EHattr function  */
  int		   i = 0;

  herr_t	   status = FAIL;           /* routine return status variable             */
  
  hsize_t	   *count = (hsize_t *)NULL;/* Pointer to count array (C order)           */
 
  hid_t        swathID    = FAIL;       /* Swath HDF5 type ID                         */   
  hid_t        numbertype = FAIL;       /* HDF5 dta type ID                           */
  
  char         *errbuf = (char *)NULL;  /* error message buffer                       */
  char         *tempbuf = (char *)NULL; /* temp buffer                                */


  /* Get HDF5 type data type ID */
  /* -------------------------- */
  numbertype = HE5_EHconvdatatype(numtype);
  if(numbertype == FAIL)
    {
      sprintf(errbuf,"Cannot convert to HDF5 data type ID.\n");
      H5Epush(__FILE__, "HE5_SWwrlattr", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
  /* Allocate memory for error message buffers */
  errbuf  = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWwrlattr", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
  
  count = (hsize_t *)calloc(rank, sizeof(hsize_t));
  if( count == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for count.\n");
      H5Epush(__FILE__, "HE5_SWwrlattr", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }

  
  /* Reverse order of dimensions (FORTRAN -> C) */
  /* ------------------------------------------ */
  for (i = 0; i < rank; i++)
    {
      count[i] = (hsize_t)fortcount[rank - 1 - i];
    }
  
  swathID = (hid_t)SwathID;

  if ((numbertype == HE5T_CHARSTRING) || (numbertype == H5T_NATIVE_CHAR) || (numbertype == H5T_C_S1))
    {
      if (strlen((char *)datbuf) < count[0])
	{
	  sprintf(errbuf,"Size of databuf is less than the number of local attribute elements.\n");
	  H5Epush(__FILE__, "HE5_SWwrlattr", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(count);
	  free(errbuf);
	  return(FAIL);
	}

      /* Allocate memory for temp buffer */
      /* ------------------------------- */
      tempbuf = (char * )calloc((count[0]+1), sizeof(char));
      if(tempbuf == NULL)
	{
	  sprintf(errbuf,"Cannot allocate memory for temp buffer.\n");
	  H5Epush(__FILE__, "HE5_SWwrlattr", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(count);
	  free(errbuf);
	  return(FAIL);
	}

      strncpy(tempbuf, (char *)datbuf, count[0]);
      tempbuf[count[0]] = '\0';

      /* Write local attribute buffer */
      /* ---------------------------- */
      status = HE5_SWwritelocattr(swathID, fieldname, attrname, numbertype, count, tempbuf);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot write local attribute value.\n");
	  H5Epush(__FILE__, "HE5_SWwrlattr", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(count);
	  free(errbuf);
          free(tempbuf);
          return(FAIL);
	} 
      free(count);
      free(errbuf);
      free(tempbuf);
    }
  else
    {
      /* Write local attribute buffer */
      /* ---------------------------- */
      status = HE5_SWwritelocattr(swathID, fieldname, attrname, numbertype, count, datbuf);
      if(status == FAIL)
	{
          sprintf(errbuf,"Cannot write local attribute value.\n");
          H5Epush(__FILE__, "HE5_SWwrlattr", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          free(count);
          free(errbuf);
          return(FAIL);
	}
      free(count);
      free(errbuf);
    }

  ret = (int)status;
  return(ret);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWrdlattr    (FORTRAN  wrapper)                              |
|                                                                             |
|  DESCRIPTION: Reads attribute associated with a specified field in a swath. |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  fieldname      char                fieldname                               |
|  attrname       char                attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int    
HE5_SWrdlattr(int SwathID, char *fieldname, char *attrname, void *datbuf)
{
  int         ret             =  FAIL;/* return status variable   */

  herr_t      status          =  FAIL;/* return status variable   */

  hid_t       swathID         =  FAIL;/* HDF5 type Swath  ID      */
  
  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */

  swathID = (hid_t)SwathID;

  status = HE5_SWreadlocattr(swathID,fieldname, attrname, datbuf);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot read Attribute \"%s\" associated wth the \"%s\" field.\n", attrname,fieldname);
      H5Epush(__FILE__, "HE5_SWrdlattr", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

  ret  = (int)status;
  return(ret);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqmapsF    (FORTRAN wrapper)                              |
|                                                                             |
|  DESCRIPTION: Returns dimension mappings and offsets and increments         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nMap           long                Number of dimension mappings            |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  dimmaps        char                dimension mappings (comma-separated)    |
|  offset         long                array of offsets                        |
|  increment      long                array of increments                     |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWinqmapsF(int SwathID, char *dimmaps, long offset[], long increment[])
{
  long           nMap      = FAIL;/* Number of mappings                */

  hid_t          swathID   = FAIL;/* HDF-EOS swath ID                  */

  char           errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer   */

  swathID = (hid_t)SwathID;

  /* Call HE5_SWinqmaps */
  /* ------------------ */
  nMap = HE5_SWinqmaps(swathID, dimmaps, offset, increment);
  if(nMap == FAIL)
    {
      sprintf(errbuf,"Error calling SWinqmaps() from FORTRAN wrapper.\n");
      H5Epush(__FILE__, "HE5_SWinqmapsF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

  return(nMap);
}


 
/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqimapsF                                                  |
|                                                                             |
|  DESCRIPTION: Returns indexed mappings and index sizes                      |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nMap           long                Number of indexed dimension mappings    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  idxmaps        char                indexed dimension mappings              |
|                                     (comma-separated)                       |
|  idxsizes       long                Number of elements in each mapping      |
|                                                                             |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  May 00   D.Wynne       Original Version                                    |
|  Aug 00   A.Muslimov    Modified to conform to HDF5 data type               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long
HE5_SWinqimapsF(int SwathID, char *idxmaps, long idxsizes[])
{
  int		i          = 0;   /* Loop index                       */         
  
  hid_t     swathID    = FAIL;/* HDF5 type swath ID               */

  long		nmaps      = FAIL;/* Number of index maps             */
  long		strbufsize = 0;   /* Buffer size for length of string */
  
  hsize_t	*tidxsizes = (hsize_t *)NULL;/* Size of mapping       */

  char      errbuf[HE5_HDFE_ERRBUFSIZE]; /* Error message buffer  */

  swathID = (hid_t)SwathID;

  /* Get the number of index maps */
  /* ---------------------------- */
  nmaps = HE5_SWnentries(swathID, 2, &strbufsize);
  if(nmaps == FAIL)
    {
      sprintf(errbuf,"Error calling SWnentries() from FORTRAN wrapper.\n");
      H5Epush(__FILE__, "HE5_SWinqimapsF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
  /* Allocate space for index sizes */
  /* ------------------------------ */
  tidxsizes = (hsize_t *)calloc(nmaps, sizeof(hsize_t));
  if(tidxsizes == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for tidxsizes.\n");
      H5Epush(__FILE__, "HE5_SWinqimapsF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  
  /* Retrieve the list of maps and the sizes */
  /* --------------------------------------- */
  nmaps = HE5_SWinqidxmaps(swathID, idxmaps, tidxsizes);
  if(nmaps == FAIL)
    {
      sprintf(errbuf,"Error calling SWinqidxmaps() from FORTRAN wrapper.\n");
      H5Epush(__FILE__, "HE5_SWinqimapsF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(tidxsizes);
      return(FAIL);
    }


  /* Convert data type  */
  /* ------------------ */
  for(i = 0; i < nmaps; i++)
    idxsizes[i] = (long)tidxsizes[i];
  

  free(tidxsizes);
  
  return(nmaps);
}
 
/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqdimsF                                                   |
|                                                                             |
|  DESCRIPTION: Returns dimension names and values defined in swath structure |
|               (FORTRAN Wrapper)                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nDim           long                Number of defined dimensions            |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  dimnames       char                Dimension names (comma-separated)       |
|  dims           long                Dimension values                        |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  May 00   D.Wynne       Original Version                                    |
|  Aug 00   A.Muslimov    Modified to conform to HDF5 data type               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long
HE5_SWinqdimsF(int SwathID, char *dimnames, long dims[])
{
  int		i          = 0;   /* Loop index                    */
  
  hid_t     swathID    = FAIL;/* HDF5 type swath ID            */ 
 
  long		nDim       = FAIL;/* (return) number of dimensions */
  long		strbufsize = 0;   /* String size variable          */
  
  hsize_t	*tdims     = (hsize_t *)NULL;/* Dimension variable */

  char      errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */


  swathID = (hid_t)SwathID;  
  
  nDim = HE5_SWnentries(swathID, 0, &strbufsize);
  if(nDim == FAIL)
    {
      sprintf(errbuf,"Error calling SWnentries() from FORTRAN wrapper.\n");
      H5Epush(__FILE__, "HE5_SWinqdimsF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
  tdims = (hsize_t *)calloc(nDim, sizeof(hsize_t));
  if(tdims == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for tdims.\n");
      H5Epush(__FILE__, "HE5_SWinqdimsF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
 

  nDim = HE5_SWinqdims(swathID, dimnames, tdims);
  if(nDim == FAIL)
    {
      sprintf(errbuf,"Error calling HE5_SWinqdims() from FORTRAN wrapper.\n");
      H5Epush(__FILE__, "HE5_SWinqdimsF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(tdims);
      return(FAIL);
    }
  
  
  /* Convert data type */
  /* ----------------- */
  for(i = 0; i < nDim; i++)
    dims[i] = (long)tdims[i];
  

  free(tdims);
  
  return (nDim); 
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqgflds    (FORTRAN wrapper)                              |
|                                                                             |
|  DESCRIPTION: Inquires about geo fields in swath                            |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nflds          long                Number of geo fields in swath           |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  fieldlist      char                Field names (comma-separated)           |
|  rank           int                 Array of ranks                          |
|  ntype          int                 number types                            |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWinqgflds(int SwathID, char *fieldlist, int rank[], int ntype[])
{
  long            nflds   = FAIL;              /* Number of Geo  fields */
  long            i;                           /* Loop index            */

  hid_t           swathID = FAIL;              /* HDF5 data type ID     */

  hid_t           *dtype = (hid_t *)NULL;      /* Data type             */

  char            errbuf[HE5_HDFE_ERRBUFSIZE]; /* Error message buffer  */

  swathID = (hid_t)SwathID;

  /* Call "HE5_SWinqgeofields" routine to get number of fields */
  /* ----------------------------------------------------- */
  nflds = HE5_SWinqgeofields(swathID, fieldlist, NULL, NULL);
  if (nflds == FAIL)
    {
      sprintf(errbuf, "Cannot get information about fields in \"Geolocation Fields\" group. \n");
      H5Epush(__FILE__, "HE5_SWinqgflds", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  dtype = (hid_t *)calloc(nflds,sizeof(hid_t));
  if (dtype == NULL)
    {
      sprintf(errbuf, "Cannot allocate memory. \n");
      H5Epush(__FILE__, "HE5_SWinqgflds", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  nflds = HE5_SWinqgeofields(swathID, fieldlist, rank, dtype);
  if (nflds == FAIL)
    {
      sprintf(errbuf, "Cannot get information about fields in \"Geolocation Fields\" group. \n");
      H5Epush(__FILE__, "HE5_SWinqgflds", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(dtype);
      return(FAIL);
    }

  for (i = 0; i < nflds; i++)
    ntype[i] = (int)dtype[i];
  
  free(dtype);
  return (nflds);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqdflds      (FORTRAN wrapper)                            |
|                                                                             |
|  DESCRIPTION: Inquires about data fields in swath                           |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nflds          long                Number of data fields in swath          |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  fieldlist      char                Field names (comma-separated)           |
|  rank           int                 Array of ranks                          |
|  ntype          int                 number types                            |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWinqdflds(int SwathID, char *fieldlist, int rank[], int ntype[])
{
  long            nflds   = FAIL;               /* Number of Data fields  */
  long            i;                            /* Looop index            */
  
  hid_t           swathID = FAIL;               /* HDF5 type swath ID     */

  hid_t           *dtype  = (hid_t *)NULL;      /* Data type              */

  char            errbuf[HE5_HDFE_ERRBUFSIZE];      /* Error message buffer   */


  swathID = (hid_t)SwathID;

  /* Call "HE5_SWinqdatafields" routine to get number of fields */
  /* ------------------------------------------------------ */
  nflds = HE5_SWinqdatafields(swathID, fieldlist, NULL, NULL);
  if (nflds == FAIL)
    {
      sprintf(errbuf, "Cannot get the number of fields in \"Data Fields\" group. \n");
      H5Epush(__FILE__, "HE5_SWinqdflds", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  dtype = (hid_t *)calloc(nflds, sizeof(hid_t));
  if (dtype == NULL)
    {
      sprintf(errbuf, "Cannot allocate memory. \n");
      H5Epush(__FILE__, "HE5_SWinqdflds", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }


  nflds = HE5_SWinqdatafields(swathID, fieldlist, rank, dtype);
  if (nflds == FAIL)
    {
      sprintf(errbuf, "Cannot get the number of fields in \"Data Fields\" group. \n");
      H5Epush(__FILE__, "HE5_SWinqdflds", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(dtype);
      return(FAIL);
    }

  for (i = 0; i < nflds; i++)
    ntype[i] = (int)dtype[i];


  free(dtype);
  return(nflds);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdiminfoF                                                   |
|                                                                             |
|  DESCRIPTION: FORTRAN wrapper for SWdiminfo to Retrieve size of specified   |
|               dimension.                                                    |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  size           long    None        Size of dimension                       |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int     None        swath structure ID                      |
|  dimname        char*   None        Dimension name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  9/21/99  A.Muslimov    In the call to EHmetagroup() replaced the argument  |
|                         gid by fid.                                         |
|  Oct 99   Abe Taaheri   Added to convert hsize_t to integer                 |
|  Aug 00   A.Muslimov    Modified to conform to HDF5 data type               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long
HE5_SWdiminfoF(int SwathID, char *dimname)
{
  long        size    = 0;                 /* dimension size  (return) */

  hid_t       swathID = FAIL;              /* HDF5 data type ID        */  

  hsize_t     tsize   = 0;                 /* size variable            */
  
  char        errbuf[HE5_HDFE_ERRBUFSIZE]; /* Error message buffer     */

  swathID = (hid_t)SwathID;

  tsize = HE5_SWdiminfo(swathID, dimname);
  if (tsize == 0)
    {
      sprintf(errbuf, "Error calling SWdiminfo() from FORTRAN wrapper. \n");
      H5Epush(__FILE__, "HE5_SWdiminfoF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
  size = (long)tsize;
  
  return(size);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWmapinfoF   (FORTRAN wrapper)                               |
|                                                                             |
|  DESCRIPTION: Returns dimension mapping information                         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  geodim         char                geolocation dimension name              |
|  datadim        char                data dimension name                     |
|                                                                             |
|  OUTPUTS:                                                                   |
|  offset         long                mapping offset                          |
|  increment      long                mapping increment                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int 
HE5_SWmapinfoF(int SwathID, char *geodim, char *datadim, long *offset, long *increment)
{
  int            ret      = FAIL;	/* routine return status variable */
   
  herr_t         status   = FAIL;	/* routine return status variable */

  hid_t          swathID  = FAIL;	/* HDF-EOS swath ID               */

  char           errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer  */

  /* Initialize return values */
  /* ------------------------ */
  *offset    = FAIL;
  *increment = FAIL;

  swathID = (hid_t)SwathID;

  status = HE5_SWmapinfo(swathID, geodim, datadim, offset, increment);
  if (status == FAIL)
    {
      sprintf(errbuf, "Cannot get mapping information.") ;
      H5Epush(__FILE__, "HE5_SWmapinfoF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  ret = (int)status;
  return(ret);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWgmapinfo   (FORTRAN wrapper)                               |
|                                                                             |
|  DESCRIPTION: Returns mapping information for dimension                     |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 2 for indexed mapping, 1 for regular    |
|                                     mapping, 0 if the dimension is not      |
|                                     and (-1) FAIL                           |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|  geodim         char                geolocation dimension name              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  NONE                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int    
HE5_SWgmapinfo(int SwathID, char *geodim)
{
  int            ret       = FAIL;           /* Return status variable    */

  herr_t         status    = FAIL;           /* Return status variable    */

  hid_t          swathID   = FAIL;           /* HDF5 type swath ID        */

  char           errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer      */
 
  swathID = (hid_t)SwathID;

  status = HE5_SWgeomapinfo(swathID, geodim);
  if (status == FAIL)
    {
      sprintf(errbuf, "Cannot get geolocation mapping information.") ;
      H5Epush(__FILE__, "HE5_SWgmapinfo", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  ret = (int)status;
  return(ret);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWfldinfoF                                                   |
|                                                                             |
|  DESCRIPTION: FORTRAN wrapper arount SWfieldinfo                            |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure id                      |
|  fieldname      char                name of field                           |
|                                                                             |
|  OUTPUTS:                                                                   |
|  rank           long                rank of field (# of dims)               |
|  dims           long                field dimensions                        |
|  ntype          int                 field number type                       |
|  fortdimlist    char                field dimension list (FORTRAN order)    |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Nov 99   Abe Taaheri   Modified for HDF5                                   |
|  Aug 00   A.Muslimov    Updated to conform to the HDF5 data types.          |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWfldinfoF(int SwathID, char *fieldname, int *rank, long dims[], int *ntype, char *fortdimlist, char *fortmaxdimlist)
{
  int		   ret      = SUCCEED;    /* routine return status variable */
  int		   j        = 0;          /* Loop Index                     */

  herr_t	   status   = SUCCEED;    /* routine return status variable */

  hid_t            swathID  = FAIL;       /* HDF5 type data type ID         */   
  
  hid_t            dtype[1] = {FAIL}; /* Data type                      */

  hsize_t	   tempdims[HE5_DTSETRANKMAX];/* Dimension sizes array      */       
  hsize_t 	   swap     = 0;              /* Temporary dimension size   */

  char		   *errbuf  = (char *)NULL;   /* error message buffer       */
 
  /* Dimension lists in C order */
  /* -------------------------- */
  char		   *dimlist    = (char *)NULL;
  char		   *maxdimlist = (char *)NULL;

  
  /* Allocate memory for error message buffers */
  /* ----------------------------------------- */
  errbuf  = (char *)calloc(HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWfldinfoF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
  
  /* Allocate space for C order dimension list */
  /* ----------------------------------------- */
  maxdimlist = (char *)calloc(HE5_HDFE_UTLBUFSIZE, sizeof(char));
  dimlist    = (char *)calloc(HE5_HDFE_UTLBUFSIZE, sizeof(char));
  if(dimlist == NULL || maxdimlist == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for input list.\n");
      H5Epush(__FILE__, "HE5_SWfldinfoF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  
  swathID = (hid_t)SwathID;

  /* Initialize tempdims[] array */
  /* --------------------------- */
  for ( j = 0; j < HE5_DTSETRANKMAX; j++)
    tempdims[ j ] = 0;

  /* Get field info */
  /* -------------- */
  status = HE5_SWfieldinfo(swathID, fieldname, rank, tempdims, dtype, dimlist, maxdimlist);
  if (status == SUCCEED)
    {
      for (j = 0; j < *rank / 2; j++)
        {
	  swap = tempdims[*rank - 1 - j];
	  tempdims[*rank - 1 - j] = tempdims[j];
	  tempdims[j] = swap;
        }
      /* change the datatype */
      /* ------------------- */
      for (j = 0; j < *rank; j++)
	dims[j] = (long)tempdims[j];

      /* Reverse order of dimensions entries in dimension list */
      /* ----------------------------------------------------- */
      if(fortdimlist != (char *)NULL)
	{
	  status = HE5_EHrevflds(dimlist, fortdimlist);
	  if(status == FAIL)
	    {
	      sprintf(errbuf,"Cannot reverse entries in dimension list.\n");
	      H5Epush(__FILE__, "HE5_SWfldinfoF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(errbuf);
	      free(dimlist);
	      free(maxdimlist);
	      return(FAIL);
	    }
	}
      if(fortmaxdimlist != (char *)NULL)
	{
	  status = HE5_EHrevflds(maxdimlist, fortmaxdimlist);
	  if(status == FAIL)
	    {
	      sprintf(errbuf,"Cannot reverse entries in maximum dimension list.\n");
	      H5Epush(__FILE__, "HE5_SWfldinfoF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(errbuf);
	      free(dimlist);
	      free(maxdimlist);
	      return(FAIL);
	    }
		  
	}
    }

  *ntype = (int)dtype[0];

  free(maxdimlist);
  free(dimlist);
  free(errbuf);

  ret = (int)status;
  return(ret); 
}
  
 
/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWchunkinfoF                                                 |
|                                                                             |
|  DESCRIPTION: FORTRAN wrapper for SWchunkinfo                               |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  fieldname      char*               name of field                           |
|                                                                             |
|  OUTPUTS:                                                                   |
|  ndims          int*                rank of a dataset                       |
|  dims           long                the array containing sizes              |
|                                     of each dimension of a chunk            |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date         Programmer    Description                                    |
|   =========    ============  ============================================   |
|   Dec 03       S.Zhao        Original development                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWchunkinfoF(int SwathID, char *fieldname, int *ndims, long dims[])
{
  int           ret       = FAIL;           /* return status        */
  int           j         = 0;              /* Loop index           */
 
  herr_t        status    = FAIL;           /* return status        */
 
  hid_t         swathID   = FAIL;           /* HDF5 type swath ID   */
 
  hsize_t       tempdims[HE5_DTSETRANKMAX]; /* Temporary dimension sizes array */
  hsize_t       swap      = 0;              /* Temporary dimension size   */
 
  char          *errbuf   = (char *)NULL;   /* error message buffer */
 
  /* Allocate memory for error message buffer */
  errbuf  = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWchunkinfoF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
 
  /* Initialize tempdims[] array */
  /* --------------------------- */
  for ( j = 0; j < HE5_DTSETRANKMAX; j++)
    tempdims[ j ] = 0; 
 
  swathID = (hid_t)SwathID;
 
  status = HE5_SWchunkinfo(swathID, fieldname, ndims, tempdims);
  if(status == FAIL)
    {
      sprintf(errbuf,"Error calling SWchunkinfo() from FORTRAN wrapper.\n");
      H5Epush(__FILE__, "HE5_SWchunkinfoF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }

  for (j = 0; j < *ndims / 2; j++)
    {
      swap = tempdims[*ndims - 1 - j];
      tempdims[*ndims - 1 - j] = tempdims[j];
      tempdims[j] = swap;
    }

  for (j = 0; j < *ndims; j++)
    dims[j] = (long)tempdims[j];
 
  free(errbuf);
 
  ret = (int)status;
  return(ret);
 
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWidxmapinfoF                                                |
|                                                                             |
|  DESCRIPTION: Returns indexed mapping information                           |
|               (FORTRAN Wrapper)                                             |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  size           long                Number of index values (sz of geo dim)  |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure id                      |
|  geodim         char                geolocation dimension name              |
|  datadim        char                data dimension name                     |
|                                                                             |
|  OUTPUTS:                                                                   |
|  index          long                array of index values                   |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  May 00   D.Wynne       Original Version                                    |
|  Aug 00   A.Muslimov    Updated to conform to HDF5 data types               |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long
HE5_SWidxmapinfoF(int SwathID, char *geodim, char *datadim, long index[])
{
  long        size    = FAIL;         /* routine return status variable */

  hid_t       swathID = FAIL;         /* HDF5 type swath ID             */

  hsize_t     gsize   = 0;            /* Temporary size variable        */
  
  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer       */

  swathID = (hid_t)SwathID;

  gsize = HE5_SWidxmapinfo(swathID, geodim, datadim, index);
  if (gsize == 0)
    {
      sprintf(errbuf, "Error calling SWidxmapinfo() from FORTRAN wrapper. \n");
      H5Epush(__FILE__, "HE5_SWidxmapinfoF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

  size = (long)gsize;

  return(size);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWwrgattr                                                    |
|                                                                             |
|  DESCRIPTION: FORTRAN wrapper to Write/update group attribute in a swath.   |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  attrname       char*               group attribute name                    |
|  numtype        int                 group attribute HDF numbertype          |
|  fortcount[]    long                Number of group attribute elements      |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                   It is assumed that fortcout has just one element to agree |
|                   with EHattr() call.                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Apr 00   D.Wynne       Original Programmer                                 |
|  Aug 00   A.Muslimov    Updated to reflect most recent data type changes.   |
|  Nov 02   S.Zhao        Modified to get the size of a string attribute.     |
|  Mar 04   S.Zhao        Modified for a character string attribute.          |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWwrgattr(int SwathID, char *attrname, int numtype, long fortcount[], void *datbuf)
{
  int          ret    = FAIL;            /* (int) return status variable      */
  int		   rank   = 1;               /* Rank variable                     */
  int		   i;                        /* Loop index                        */

  herr_t	   status     = FAIL;        /* routine return status variable    */
  
  hid_t        swathID    = FAIL;        /* HDF5 type Swath ID                */
  hid_t        numbertype = FAIL;        /* HDF5 data type ID                 */
             
  hsize_t      *count  = (hsize_t *)NULL;/* Pointer to count array (C order)  */
  
  char         *errbuf = (char *)NULL;   /* error message buffer              */
  char         *tempbuf = (char *)NULL;  /* temp buffer                       */
  
  /* Allocate memory for error message buffers */
  /* ----------------------------------------- */
  errbuf  = (char *)calloc(HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWwrgattr", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }

  /* Get HDF5 data type ID */
  /* --------------------- */
  numbertype = HE5_EHconvdatatype(numtype);
  if(numbertype == FAIL)
    {
      sprintf(errbuf,"Cannot convert to HDF5 type data type ID.\n");
      H5Epush(__FILE__, "HE5_SWwrgattr", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }


  count = (hsize_t *)calloc(rank, sizeof(hsize_t));
  if( count == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for count.\n");
      H5Epush(__FILE__, "HE5_SWwrgattr", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }

  /* Reverse order of dimensions (FORTRAN -> C) */
  /* ------------------------------------------ */
  for (i = 0; i < rank; i++)
    count[i] = (hsize_t)fortcount[rank - 1 - i];
  
  
  swathID = (hid_t)SwathID;

  if ((numbertype == HE5T_CHARSTRING) || (numbertype == H5T_NATIVE_CHAR) || (numbertype == H5T_C_S1))
    {
      if (strlen((char *)datbuf) < count[0])
	{
	  sprintf(errbuf,"Size of databuf is less than the number of group attribute elements.\n");
	  H5Epush(__FILE__, "HE5_SWwrgattr", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(count);
	  free(errbuf);
	  return(FAIL);
	}

      /* Allocate memory for temp buffer */
      /* ------------------------------- */
      tempbuf = (char * )calloc((count[0]+1), sizeof(char));
      if(tempbuf == NULL)
	{
	  sprintf(errbuf,"Cannot allocate memory for temp buffer.\n");
	  H5Epush(__FILE__, "HE5_SWwrgattr", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(count);
	  free(errbuf);
	  return(FAIL);
	}

      strncpy(tempbuf, (char *)datbuf, count[0]);
      tempbuf[count[0]] = '\0';
 
      status = HE5_SWwritegrpattr(swathID, attrname, numbertype, count, tempbuf);
      if(status == FAIL)
	{
          sprintf(errbuf,"Cannot write group attribute value.\n");
          H5Epush(__FILE__, "HE5_SWwrgattr", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          free(errbuf);
          free(count);
          free(tempbuf);
          return(FAIL);
	}
      free(count);
      free(errbuf);
      free(tempbuf);
    }
  else
    {
      status = HE5_SWwritegrpattr(swathID, attrname, numbertype, count, datbuf);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot write group attribute value.\n");
	  H5Epush(__FILE__, "HE5_SWwrgattr", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(errbuf);
	  free(count);
	  return(FAIL);
	}
      free(count);
      free(errbuf);
    }

  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWwrgeogattr                                                 |
|                                                                             |
|  DESCRIPTION: FORTRAN wrapper to write/update the "Geolocation Fields" group|
|               attribute in a swath.                                         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  attrname       char*               group attribute name                    |
|  numtype        int                 group attribute HDF numbertype          |
|  fortcount[]    long                Number of group attribute elements      |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                   It is assumed that fortcout has just one element to agree |
|                   with EHattr() call.                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04   S.Zhao        Original development                                |
|  Mar 04   S.Zhao        Modified for a character string attribute.          |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWwrgeogattr(int SwathID, char *attrname, int numtype, long fortcount[], void *datbuf)
{
  int          ret    = FAIL;            /* (int) return status variable      */
  int          rank   = 1;               /* Rank variable                     */
  int          i;                        /* Loop index                        */
 
  herr_t       status     = FAIL;        /* routine return status variable    */
 
  hid_t        swathID    = FAIL;        /* HDF5 type Swath ID                */
  hid_t        numbertype = FAIL;        /* HDF5 data type ID                 */
 
  hsize_t      *count  = (hsize_t *)NULL;/* Pointer to count array (C order)  */
 
  char         *errbuf = (char *)NULL;   /* error message buffer              */
  char         *tempbuf = (char *)NULL;  /* temp buffer                       */
 
  /* Allocate memory for error message buffers */
  /* ----------------------------------------- */
  errbuf  = (char *)calloc(HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWwrgeogattr", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
 
  /* Get HDF5 data type ID */
  /* --------------------- */
  numbertype = HE5_EHconvdatatype(numtype);
  if(numbertype == FAIL)
    {
      sprintf(errbuf,"Cannot convert to HDF5 type data type ID.\n");
      H5Epush(__FILE__, "HE5_SWwrgeogattr", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
 
  count = (hsize_t *)calloc(rank, sizeof(hsize_t));
  if( count == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for count.\n");
      H5Epush(__FILE__, "HE5_SWwrgeogattr", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
 
  /* Reverse order of dimensions (FORTRAN -> C) */
  /* ------------------------------------------ */
  for (i = 0; i < rank; i++)
    count[i] = (hsize_t)fortcount[rank - 1 - i];
 
 
  swathID = (hid_t)SwathID;
 
  if ((numbertype == HE5T_CHARSTRING) || (numbertype == H5T_NATIVE_CHAR) || (numbertype == H5T_C_S1))
    {
      if (strlen((char *)datbuf) < count[0])
	{
	  sprintf(errbuf,"Size of databuf is less than the number of group attribute elements.\n");
	  H5Epush(__FILE__, "HE5_SWwrgeogattr", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(count);
	  free(errbuf);
	  return(FAIL);
	}
 
      /* Allocate memory for temp buffer */
      /* ------------------------------- */
      tempbuf = (char * )calloc((count[0]+1), sizeof(char));
      if(tempbuf == NULL)
	{
	  sprintf(errbuf,"Cannot allocate memory for temp buffer.\n");
	  H5Epush(__FILE__, "HE5_SWwrgeogattr", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(count);
	  free(errbuf);
	  return(FAIL);
	}
 
      strncpy(tempbuf, (char *)datbuf, count[0]);
      tempbuf[count[0]] = '\0';
 
      status = HE5_SWwritegeogrpattr(swathID, attrname, numbertype, count, tempbuf);
      if(status == FAIL)
	{
          sprintf(errbuf,"Cannot write group attribute value.\n");
          H5Epush(__FILE__, "HE5_SWwrgeogattr", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          free(errbuf);
          free(count);
          free(tempbuf);
          return(FAIL);
	}
      free(count);
      free(errbuf);
      free(tempbuf);
    }
  else
    {
      status = HE5_SWwritegeogrpattr(swathID, attrname, numbertype, count, datbuf);
      if(status == FAIL)
	{
          sprintf(errbuf,"Cannot write group attribute value.\n");
          H5Epush(__FILE__, "HE5_SWwrgeogattr", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          free(errbuf);
          free(count);
          return(FAIL);
	}
      free(count);
      free(errbuf);
    }
 
  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWatinfo                                                     |
|                                                                             |
|  DESCRIPTION:  FORTRAN wrapper for SWattrinfo                               |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  attrname       char*               attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  numbertype     int                 attribute HDF numbertype                |
|  fortcount      long                Number of attribute elements            |
|                                                                             |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  9/28/99  A.Muslimov    Changed the type of return value from intn          |
|                         to herr_t.                                          |
|  Oct 99   Abe Taaheri   Added for HDF5                                      |
|  May 00   D.Wynne       Updated to reflect datatype changes                 |
|  Aug 00   A.Muslimov    Updated to reflect yet another datatype changes     |
|                                                                             |
|                                                                             |
|  END_PROLOG                                                                 |
|                                                                             |
-----------------------------------------------------------------------------*/
int
HE5_SWatinfo(int SwathID, char *attrname, int *numbertype, long *fortcount)
{
  int          ret      = FAIL;               /* (int) return status variable  */ 

  herr_t       status   = FAIL;	              /* return status variable        */

  hid_t        *ntype   = (hid_t *)NULL;      /* Data type class ID            */

  hid_t        swathID  = FAIL;               /* HDF5 type Swath ID            */

  hsize_t      *count   = (hsize_t *)NULL;    /* Pointer to count (C order)    */
  
  char         *errbuf  = (char *)NULL;       /* error message buffer          */
  
  /* Allocate memory for error message buffers */
  errbuf  = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWatinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
  
  count = (hsize_t *) calloc(1, sizeof(hsize_t));
  if( count == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for count.\n");
      H5Epush(__FILE__, "HE5_SWatinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  
  ntype = (hid_t *) calloc(1, sizeof(hid_t));
  if(ntype == (hid_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for ntype.\n");
      H5Epush(__FILE__, "HE5_SWatinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      return(FAIL);
    }


  swathID = (hid_t)SwathID;

  status = HE5_SWattrinfo(swathID, attrname, ntype, count);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot get information about attribute \"%s\".\n", attrname);
      H5Epush(__FILE__, "HE5_SWatinfo", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      free(ntype);
      return(FAIL);
    }  

  
  *fortcount  = (long)(*count);
  *numbertype = (int)(*ntype);

  free(errbuf);
  free(count);
  free(ntype);

  ret = (int)status;
  return(ret);
}
 


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWatinfo2                                                    |
|                                                                             |
|  DESCRIPTION:  FORTRAN wrapper for SWattrinfo2                              |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  attrname       char*               attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  numbertype     int                 attribute HDF numbertype                |
|  fortcount      long                Number of attribute elements            |
|  fortsize       long                buf size of attribute elements          |
|                                                                             |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  9/28/99  A.Muslimov    Changed the type of return value from intn          |
|                         to herr_t.                                          |
|  Oct 99   Abe Taaheri   Added for HDF5                                      |
|  May 00   D.Wynne       Updated to reflect datatype changes                 |
|  Aug 00   A.Muslimov    Updated to reflect yet another datatype changes     |
|                                                                             |
|                                                                             |
|  END_PROLOG                                                                 |
|                                                                             |
-----------------------------------------------------------------------------*/
int
HE5_SWatinfo2(int SwathID, char *attrname, int *numbertype, long *fortcount, long *fortsize)
{
  int          ret      = FAIL;               /* (int) return status variable  */ 

  herr_t       status   = FAIL;	              /* return status variable        */

  hid_t        *ntype   = (hid_t *)NULL;      /* Data type class ID            */

  hid_t        swathID  = FAIL;               /* HDF5 type Swath ID            */

  hsize_t      *count   = (hsize_t *)NULL;    /* Pointer to count (C order)    */
  hsize_t      *size    = (hsize_t *)NULL;    /* Pointer to size  (C order)    */
  
  char         *errbuf  = (char *)NULL;       /* error message buffer          */
  
  /* Allocate memory for error message buffers */
  errbuf  = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
  
  count = (hsize_t *) calloc(1, sizeof(hsize_t));
  if( count == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for count.\n");
      H5Epush(__FILE__, "HE5_SWatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  
  ntype = (hid_t *) calloc(1, sizeof(hid_t));
  if(ntype == (hid_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for ntype.\n");
      H5Epush(__FILE__, "HE5_SWatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      return(FAIL);
    }

  size = (hsize_t *) calloc(1, sizeof(hsize_t));
  if( size == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for size.\n");
      H5Epush(__FILE__, "HE5_SWatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  

  swathID = (hid_t)SwathID;

  status = HE5_SWattrinfo2(swathID, attrname, ntype, count, size);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot get information about attribute \"%s\".\n", attrname);
      H5Epush(__FILE__, "HE5_SWatinfo2", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      free(ntype);
      return(FAIL);
    }  

  
  *fortcount  = (long)(*count);
  *fortsize   = (long)(*size);
  *numbertype = (int)(*ntype);

  free(errbuf);
  free(count);
  free(size);
  free(ntype);

  ret = (int)status;
  return(ret);
}
 

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWgatinfo                                                    |
|                                                                             |
|  DESCRIPTION:  FORTRAN wrapper for SWgrpattrinfo                            |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  attrname       char*               attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  numbertype     int                 attribute HDF numbertype                |
|  fortcount      long                Number of attribute elements            |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  9/28/99  A.Muslimov    Changed the type of return value from intn          |
|                         to herr_t.                                          |
|  Oct 99   Abe Taaheri   Added for HDF5                                      |
|  May 00   D.Wynne       Updated to reflect datatype changes                 |
|  Aug 00   A.Muslimov    Updated to reflect yet another datatype changes     |
|                                                                             |
|  END_PROLOG                                                                 |
|                                                                             |
-----------------------------------------------------------------------------*/
int
HE5_SWgatinfo(int SwathID, char *attrname, int *numbertype, long *fortcount)
{
  int	      ret     = FAIL;	        /* (int) return status variable   */

  herr_t      status  = FAIL;           /* routine return status variable */

  hid_t       *ntype  = (hid_t *)NULL;  /* Data type class ID         */

  hid_t       swathID = FAIL;           /* HDF5 type Swath ID             */

  hsize_t     *count  = (hsize_t *)NULL;/* Pointer to count  (C order)    */
  
  char        *errbuf = (char *)NULL;   /* error message buffer           */
  
  /* Allocate memory for error message buffers */
  errbuf  = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWgatinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
  
  count = (hsize_t *)calloc(1, sizeof(hsize_t));
  if( count == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for count.\n");
      H5Epush(__FILE__, "HE5_SWgatinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  
  ntype = (hid_t *)calloc(1, sizeof(hid_t));
  if( ntype == (hid_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for ntype.\n");
      H5Epush(__FILE__, "HE5_SWgatinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      return(FAIL);
    }


  swathID = (hid_t)SwathID;

  status = HE5_SWgrpattrinfo(swathID, attrname, ntype, count);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot get information about group attribute.\n");
      H5Epush(__FILE__, "HE5_SWgatinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      free(ntype);
      return(FAIL);
    }
  
  *fortcount  = (long)(*count);
  *numbertype = (int)(*ntype);

  free(errbuf);
  free(count);
  free(ntype);
  
  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWgatinfo2                                                   |
|                                                                             |
|  DESCRIPTION:  FORTRAN wrapper for SWgrpattrinfo2                           |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  attrname       char*               attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  numbertype     int                 attribute HDF numbertype                |
|  fortcount      long                Number of attribute elements            |
|  fortsize       long                buf size of attribute elements          |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  9/28/99  A.Muslimov    Changed the type of return value from intn          |
|                         to herr_t.                                          |
|  Oct 99   Abe Taaheri   Added for HDF5                                      |
|  May 00   D.Wynne       Updated to reflect datatype changes                 |
|  Aug 00   A.Muslimov    Updated to reflect yet another datatype changes     |
|                                                                             |
|  END_PROLOG                                                                 |
|                                                                             |
-----------------------------------------------------------------------------*/
int
HE5_SWgatinfo2(int SwathID, char *attrname, int *numbertype, long *fortcount, long *fortsize)
{
  int	      ret     = FAIL;	        /* (int) return status variable   */

  herr_t      status  = FAIL;           /* routine return status variable */

  hid_t       *ntype  = (hid_t *)NULL;  /* Data type class ID         */

  hid_t       swathID = FAIL;           /* HDF5 type Swath ID             */

  hsize_t     *count  = (hsize_t *)NULL;/* Pointer to count  (C order)    */
  hsize_t     *size   = (hsize_t *)NULL;/* Pointer to size   (C order)    */
  
  char        *errbuf = (char *)NULL;   /* error message buffer           */
  
  /* Allocate memory for error message buffers */
  errbuf  = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWgatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
  
  count = (hsize_t *)calloc(1, sizeof(hsize_t));
  if( count == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for count.\n");
      H5Epush(__FILE__, "HE5_SWgatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  
  ntype = (hid_t *)calloc(1, sizeof(hid_t));
  if( ntype == (hid_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for ntype.\n");
      H5Epush(__FILE__, "HE5_SWgatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      return(FAIL);
    }

  size = (hsize_t *)calloc(1, sizeof(hsize_t));
  if( size == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for size.\n");
      H5Epush(__FILE__, "HE5_SWgatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }

  swathID = (hid_t)SwathID;

  status = HE5_SWgrpattrinfo2(swathID, attrname, ntype, count, size);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot get information about group attribute.\n");
      H5Epush(__FILE__, "HE5_SWgatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      free(ntype);
      return(FAIL);
    }
  
  *fortcount  = (long)(*count);
  *fortsize   = (long)(*size);
  *numbertype = (int)(*ntype);

  free(errbuf);
  free(count);
  free(size);
  free(ntype);
  
  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWgeogatinfo                                                 |
|                                                                             |
|  DESCRIPTION:  FORTRAN wrapper for SWgeogrpattrinfo                         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  attrname       char*               attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  numbertype     int                 attribute HDF numbertype                |
|  fortcount      long                Number of attribute elements            |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04    S.Zhao       Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
|                                                                             |
-----------------------------------------------------------------------------*/
int
HE5_SWgeogatinfo(int SwathID, char *attrname, int *numbertype, long *fortcount)
{
  int         ret     = FAIL;           /* (int) return status variable   */
 
  herr_t      status  = FAIL;           /* routine return status variable */
 
  hid_t       *ntype  = (hid_t *)NULL;  /* Data type class ID             */
 
  hid_t       swathID = FAIL;           /* HDF5 type Swath ID             */
 
  hsize_t     *count  = (hsize_t *)NULL;/* Pointer to count  (C order)    */
 
  char        *errbuf = (char *)NULL;   /* error message buffer           */
 
  /* Allocate memory for error message buffers */
  errbuf  = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWgeogatinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
 
  count = (hsize_t *)calloc(1, sizeof(hsize_t));
  if( count == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for count.\n");
      H5Epush(__FILE__, "HE5_SWgeogatinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
 
  ntype = (hid_t *)calloc(1, sizeof(hid_t));
  if( ntype == (hid_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for ntype.\n");
      H5Epush(__FILE__, "HE5_SWgeogatinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      return(FAIL);
    }
 
 
  swathID = (hid_t)SwathID;
 
  status = HE5_SWgeogrpattrinfo(swathID, attrname, ntype, count);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot get information about group attribute.\n");
      H5Epush(__FILE__, "HE5_SWgeogatinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      free(ntype);
      return(FAIL);
    }
 
  *fortcount  = (long)(*count);
  *numbertype = (int)(*ntype);
 
  free(errbuf);
  free(count);
  free(ntype);
 
  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWgeogatinfo2                                                |
|                                                                             |
|  DESCRIPTION:  FORTRAN wrapper for SWgeogrpattrinfo2                        |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  attrname       char*               attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  numbertype     int                 attribute HDF numbertype                |
|  fortcount      long                Number of attribute elements            |
|  fortsize       long                buf size of attribute elements          |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04    S.Zhao       Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
|                                                                             |
-----------------------------------------------------------------------------*/
int
HE5_SWgeogatinfo2(int SwathID, char *attrname, int *numbertype, long *fortcount, long *fortsize)
{
  int         ret     = FAIL;           /* (int) return status variable   */
 
  herr_t      status  = FAIL;           /* routine return status variable */
 
  hid_t       *ntype  = (hid_t *)NULL;  /* Data type class ID             */
 
  hid_t       swathID = FAIL;           /* HDF5 type Swath ID             */
 
  hsize_t     *count  = (hsize_t *)NULL;/* Pointer to count  (C order)    */
  hsize_t     *size   = (hsize_t *)NULL;/* Pointer to size   (C order)    */
 
  char        *errbuf = (char *)NULL;   /* error message buffer           */
 
  /* Allocate memory for error message buffers */
  errbuf  = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWgeogatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
 
  count = (hsize_t *)calloc(1, sizeof(hsize_t));
  if( count == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for count.\n");
      H5Epush(__FILE__, "HE5_SWgeogatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
 
  ntype = (hid_t *)calloc(1, sizeof(hid_t));
  if( ntype == (hid_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for ntype.\n");
      H5Epush(__FILE__, "HE5_SWgeogatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      return(FAIL);
    }
 
  size = (hsize_t *)calloc(1, sizeof(hsize_t));
  if( size == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for size.\n");
      H5Epush(__FILE__, "HE5_SWgeogatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
 
 
  swathID = (hid_t)SwathID;
 
  status = HE5_SWgeogrpattrinfo2(swathID, attrname, ntype, count, size);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot get information about group attribute.\n");
      H5Epush(__FILE__, "HE5_SWgeogatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      free(ntype);
      return(FAIL);
    }
 
  *fortcount  = (long)(*count);
  *fortsize   = (long)(*size);
  *numbertype = (int)(*ntype);
 
  free(errbuf);
  free(count);
  free(size);
  free(ntype);
 
  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqgattrs (FORTRAN wrapper)                                |
|                                                                             |
|  DESCRIPTION:  Retrieves the number of attributes and string length of      |
|                attribute list in "Data Fields" group                        |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nattr          long                Number of attributes in "Data Fields"   |
|                                       group.                                |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  attrnames      char                Attribute names in "Data Fields" group  |
|                                     (Comma-separated list)                  |
|  strbufsize     long                Attributes name list string length      |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWinqgattrs(int SwathID, char *attrnames, long *strbufsize)
{
  long            nattr   = FAIL;         /* Number of attributes (return)  */

  hid_t           swathID = FAIL;         /* HDF5 type swath ID             */

  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer       */

  swathID = (hid_t)SwathID;
  
  nattr = HE5_SWinqgrpattrs(swathID, attrnames, strbufsize);
  if ( nattr < 0 )
    {
      sprintf(errbuf, "Cannot retrieve the attributes. \n");
      H5Epush(__FILE__, "HE5_SWinqgattrs", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
  
  return(nattr);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqgeogattrs (FORTRAN wrapper)                             |
|                                                                             |
|  DESCRIPTION:  Retrieves the number of attributes and string length of      |
|                attribute list in "Geolocation Fields" group.                |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nattr          long                Number of attributes in "Geolocation    |
|                                     Fields" group                           |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  attrnames      char                Attribute names in "Geolocation Fields" |
|                                     group (Comma-separated list)            |
|  strbufsize     long                Attributes name list string length      |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04    S.Zhao       Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long
HE5_SWinqgeogattrs(int SwathID, char *attrnames, long *strbufsize)
{
  long            nattr   = FAIL;         /* Number of attributes (return)  */
 
  hid_t           swathID = FAIL;         /* HDF5 type swath ID             */
 
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer       */
 
  swathID = (hid_t)SwathID;
 
  nattr = HE5_SWinqgeogrpattrs(swathID, attrnames, strbufsize);
  if ( nattr < 0 )
    {
      sprintf(errbuf, "Cannot retrieve the attributes. \n");
      H5Epush(__FILE__, "HE5_SWinqgeogattrs", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
 
  return(nattr);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqattrsF     (FORTRAN wrapper)                            |
|                                                                             |
|  DESCRIPTION:                                                               |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nattr          long                Number of attributes in swath struct    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  attrnames      char                Attribute names in swath struct         |
|                                     (Comma-separated list)                  |
|  strbufsize     long                Attributes name list string length      |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWinqattrsF(int SwathID, char *attrnames, long *strbufsize)
{
  long            nattr    = FAIL;  /* Number of attributes (return)  */

  hid_t           swathID  = FAIL;  /* HDF5 type swath ID             */

  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */


  swathID = (hid_t)SwathID;

  nattr = HE5_SWinqattrs(swathID, attrnames, strbufsize);
  if ( nattr < 0 )
    {
      sprintf(errbuf, "Cannot retrieve the attributes. \n");
      H5Epush(__FILE__, "HE5_SWinqattrsF", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
  
  return(nattr);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWlatinfo                                                    |
|                                                                             |
|  DESCRIPTION:  FORTRAN wrapper for SWlocattrinfo                            |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  fieldname      char*               field name name                         |
|                                                                             |
|  OUTPUTS:                                                                   |
|  attrname       char*               attribute name                          |
|  numbertype     int                 attribute HDF numbertype                |
|  fortcount      long                Number of attribute elements            |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  9/28/99  A.Muslimov    Changed the type of return value from intn          |
|                         to herr_t.                                          |
|  Oct 99   Abe Taaheri   Added for HDF5                                      |
|  May 00   D.Wynne       Updated to reflect datatype changes                 |
|  Aug 00   A.Muslimov    Updated to reflect yet another datatype changes     |
|                                                                             |
|                                                                             |
|  END_PROLOG                                                                 |
|                                                                             |
-----------------------------------------------------------------------------*/
int
HE5_SWlatinfo(int SwathID, char *fieldname, char *attrname, int *numbertype, long *fortcount)
{
  int	   	  ret     = FAIL;	        /* (int) return status variable   */

  herr_t   	  status  = FAIL;           /* routine return status variable */

  hid_t       *ntype  = (hid_t *)NULL;  /* Data type class ID         */

  hid_t       swathID = FAIL;           /* HDF5 type Swath ID             */

  hsize_t     *count  = (hsize_t *)NULL;/* Pointer to count  (C order)    */
  
  char        *errbuf = (char *)NULL;   /* error message buffer           */

  /* Allocate memory for error message buffers */
  errbuf  = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWlatinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
  
  count = (hsize_t *)calloc(1, sizeof(hsize_t));
  if( count == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for count.\n");
      H5Epush(__FILE__, "HE5_SWlatinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  
  ntype = (hid_t *)calloc(1, sizeof(hid_t));
  if( ntype == (hid_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for ntype.\n");
      H5Epush(__FILE__, "HE5_SWlatinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      return(FAIL);
    }

  swathID = (hid_t)SwathID;
  
  status = HE5_SWlocattrinfo(swathID, fieldname, attrname, ntype, count);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot get information about local attribute.\n");
      H5Epush(__FILE__, "HE5_SWlatinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      free(ntype);
      return(FAIL);
    }
  
  *fortcount  = (long)(*count);
  *numbertype = (int)(*ntype);
  
  free(errbuf);
  free(count);
  free(ntype);
  

  ret = (int)status;
  return(ret);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWlatinfo2                                                   |
|                                                                             |
|  DESCRIPTION:  FORTRAN wrapper for SWlocattrinfo2                           |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  fieldname      char*               field name name                         |
|                                                                             |
|  OUTPUTS:                                                                   |
|  attrname       char*               attribute name                          |
|  numbertype     int                 attribute HDF numbertype                |
|  fortcount      long                Number of attribute elements            |
|  fortsize       long                buf size of attribute elements          |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  9/28/99  A.Muslimov    Changed the type of return value from intn          |
|                         to herr_t.                                          |
|  Oct 99   Abe Taaheri   Added for HDF5                                      |
|  May 00   D.Wynne       Updated to reflect datatype changes                 |
|  Aug 00   A.Muslimov    Updated to reflect yet another datatype changes     |
|                                                                             |
|                                                                             |
|  END_PROLOG                                                                 |
|                                                                             |
-----------------------------------------------------------------------------*/
int
HE5_SWlatinfo2(int SwathID, char *fieldname, char *attrname, int *numbertype, long *fortcount, long *fortsize)
{
  int	   	  ret     = FAIL;	        /* (int) return status variable   */

  herr_t   	  status  = FAIL;           /* routine return status variable */

  hid_t       *ntype  = (hid_t *)NULL;  /* Data type class ID         */

  hid_t       swathID = FAIL;           /* HDF5 type Swath ID             */

  hsize_t     *count  = (hsize_t *)NULL;/* Pointer to count  (C order)    */

  hsize_t     *size   = (hsize_t *)NULL;/* Pointer to size   (C order)    */
  
  char        *errbuf = (char *)NULL;   /* error message buffer           */

  /* Allocate memory for error message buffers */
  errbuf  = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWlatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
  
  count = (hsize_t *)calloc(1, sizeof(hsize_t));
  if( count == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for count.\n");
      H5Epush(__FILE__, "HE5_SWlatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  
  ntype = (hid_t *)calloc(1, sizeof(hid_t));
  if( ntype == (hid_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for ntype.\n");
      H5Epush(__FILE__, "HE5_SWlatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      return(FAIL);
    }
  
  size = (hsize_t *)calloc(1, sizeof(hsize_t));
  if( size == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for size.\n");
      H5Epush(__FILE__, "HE5_SWlatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  
  swathID = (hid_t)SwathID;
  
  status = HE5_SWlocattrinfo2(swathID, fieldname, attrname, ntype, count, size);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot get information about local attribute.\n");
      H5Epush(__FILE__, "HE5_SWlatinfo2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      free(ntype);
      return(FAIL);
    }
  
  *fortcount  = (long)(*count); 
  *fortsize   = (long)(*size);
  *numbertype = (int)(*ntype);
  
  free(errbuf);
  free(count);
  free(size);
  free(ntype);
  

  ret = (int)status;
  return(ret);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqlattrs     (FORTRAN wrapper)                            |
|                                                                             |
|  DESCRIPTION:  Retrieves the number of attributes and string length of      |
|                attribute list associated with a specified field in the      |
|                "Data Fields" group.                                         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nattr          long                Number of attributes in "Data Fields"   |
|                                       group.                                |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  fieldname      char                field name                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  attrnames      char                Attribute names in "Data Fields" group  |
|                                     (Comma-separated list)                  |
|  strbufsize     long                Attributes name list string length      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWinqlattrs(int SwathID, char *fieldname, char *attrnames, long *strbufsize)
{
  long            nattr       = FAIL;     /* Number of attributes   */

  hid_t           swathID     = FAIL;     /* HDF5 type swath ID     */
    
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer   */  

  swathID = (hid_t)SwathID;

  nattr = HE5_SWinqlocattrs(swathID, fieldname, attrnames, strbufsize);
  if ( nattr < 0 )
    {
      sprintf(errbuf, "Cannot retrieve the attributes. \n");
      H5Epush(__FILE__, "HE5_SWinqlattrs", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
 
  return (nattr);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWidtype                                                     |
|                                                                             |
|  DESCRIPTION: Inquires about geo/data fields in swath                       |
|               (FORTRAN Wrapper)                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                  return status (0) SUCCEED, (-1) FAIL   |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID      int                                                           |
|  fieldname    char *                                                        |
|  attrname     char *                                                        |
|  fieldgroup   int                                                           |
|                                                                             |
|  OUTPUTS:                                                                   |
|  Type         int                                                           |
|  Class        int                                                           |
|  Order        int                                                           |
|  size         long                                                          |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Oct 99   D.Wynne       Original Programmer                                 |
|  Dec 99   A.Muslimov    Changed the status data type from hid_t to int   .  |
|  Feb 00   A.Muslimov    Added error checking after the function calls.      |
|  Mar 00   A.Muslimov    Updated to include Group/Local Attributes options.  |
|  May 00   A.Muslimov    Replaced 'H5T_class_t' type by 'int' data type.     |
|  Aug 00   A.Muslimov    Updated to reflect most recent data type changes.   |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int   
HE5_SWidtype(int SwathID, char *fieldname, char *attrname, int fieldgroup, int *Type, int *Class, int *Order, long *size)
{
  int		   ret      = FAIL;               /* (int) status variable  */

  herr_t	   status   = FAIL;               /* return status variable */
  
  size_t	   *tsize   = (size_t *)NULL;     /* data size variable     */ 

  hid_t        *typeID  = (hid_t *)NULL;      /* HDF5 Data type ID      */
  hid_t        swathID  = FAIL;               /* HDF5 type swath ID     */
 
  H5T_class_t  *classID = (H5T_class_t *)NULL;/*  Data type class ID    */
  H5T_order_t  *order   = (H5T_order_t *)NULL;/* Byte order of datatype */

  char         *errbuf  = (char *)NULL;       /* error message buffer   */

  
  /* Allocate memory for error message buffers */
  errbuf  = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWidtype", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
  
  typeID = (hid_t *)calloc(1, sizeof(hid_t));
  if(typeID == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for typeID.\n");
      H5Epush(__FILE__, "HE5_SWidtype", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }

  tsize = (size_t *)calloc(1, sizeof(size_t));
  if(tsize == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for tsize.\n");
      H5Epush(__FILE__, "HE5_SWidtype", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(typeID);
      return(FAIL);
    }

  classID = (H5T_class_t *)calloc(1, sizeof(H5T_class_t));
  if(classID == (H5T_class_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for classID.\n");
      H5Epush(__FILE__, "HE5_SWidtype", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(typeID);
      free(tsize);
      return(FAIL);
    }

  order = (H5T_order_t *)calloc(1, sizeof(H5T_order_t));
  if(order == (H5T_order_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for order.\n");
      H5Epush(__FILE__, "HE5_SWidtype", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(typeID);
      free(tsize);
      free(classID);
      return(FAIL);
    }


  swathID = (hid_t)SwathID;

  /* Get data type information */
  /* ------------------------- */
  status = HE5_SWinqdatatype(swathID, fieldname, attrname, fieldgroup, typeID, classID, order, tsize);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot get information about data type.\n");
      H5Epush(__FILE__, "HE5_SWidtype", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(typeID);
      free(tsize);
      free(classID);
      free(order);
      return(FAIL);
    }
  

  *Type   = (int)(*typeID);
  *Class  = (int)(*classID);
  *Order  = (int)(*order);
  *size   = (long)(*tsize);
  

  free(errbuf);
  free(typeID);
  free(classID);
  free(order);
  free(tsize);


  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefboxreg     (FORTRAN wrapper)                            |
|                                                                             |
|  DESCRIPTION: Finds swath cross tracks within area of interest and returns  |
|               region ID                                                     |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  RegionID       int                 Region ID                               |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|  cornerlon      double   dec deg    Longitude of opposite corners of box    |
|  cornerlat      double   dec deg    Latitude of opposite corners of box     |
|  mode           int                 Search mode                             |
|                                     HDFE_MIDPOINT - Use midpoint of Xtrack  |
|                                     HDFE_ENDPOINT - Use endpoints of Xtrack |
|                                     HDFE_ANYPOINT - Use all points of Xtrack|
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWdefboxreg(int SwathID, double  cornerlon[], double cornerlat[], int mode)
{
  int             RegionID = FAIL;/* Region ID (return)                     */

  hid_t           swathID  = FAIL;/* HDF5 type swath ID                     */
  hid_t           regionID = FAIL;/* HDF5 type region ID                    */

  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error buffer string        */

  swathID = (hid_t)SwathID;

  regionID = HE5_SWdefboxregion(swathID, cornerlon, cornerlat, mode);
  if (regionID == FAIL)
    {
      sprintf(errbuf,"Cannot define box region.\n");
      H5Epush(__FILE__, "HE5_SWdefboxreg", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
  RegionID = (int)regionID;
  return(RegionID);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefvrtreg                                                  |
|                                                                             |
|  DESCRIPTION: FORTRAN wrapper arount HE5_SWdefvrtregion                     |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  RegionID       int                 Region ID                               |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|  RegionID       int                 Region ID                               |
|  vertObj        char                Vertical object to subset               |
|  range          double              Vertical subsetting range               |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Nov 99   Abe Taaheri   Modified for HDF5                                   |
|  Aug 00   A.Muslimov    Updated to reflect data type changes.               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWdefvrtreg(int SwathID, int RegionID, char *vertObj, double fortrange[])
{
  hid_t     swathID   =  FAIL;      /* HDF5 type swath ID     */
  hid_t     regionID  =  FAIL;      /* HDF5 type region ID    */

  double	range[2]  = {0.,0.};    /* range (C) array        */

  char 	    utlbuf[16];                 /* Utility buffer         */
  char      errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer   */
  
  /* Copy first four character of vertObj to utlbuf */
  /* ---------------------------------------------- */
  memcpy(utlbuf, vertObj, 4);
  utlbuf[4] = 0;
  
  /* If subsetting on dimension elements convert FORTRAN indices to C */
  /* ---------------------------------------------------------------- */
  if (strcmp(utlbuf, "DIM:") == 0)
    {
      range[0] = fortrange[0] - 1;
      range[1] = fortrange[1] - 1;
    }
  else
    {
      range[0] = fortrange[0];
      range[1] = fortrange[1];
    }
  
  swathID  = (hid_t)SwathID;
  regionID = (hid_t)RegionID;

  /* Call HE5_SWdefvrtregion */
  /* ------------------- */
  regionID = HE5_SWdefvrtregion(swathID, regionID, vertObj, range);
  if (regionID == FAIL)
    {
      sprintf(errbuf,"Cannot define vertical region.\n");
      H5Epush(__FILE__, "HE5_SWdefvrtreg", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }  

  
  RegionID = (int)regionID;
  return(RegionID);
}
      

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWreginfo                                                    |
|                                                                             |
|  DESCRIPTION: FORTRAN wrapper around SWregioninfo                           |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|  RegionID       int                 Region ID                               |
|  fieldname      char                Fieldname                               |
|                                                                             |
|                                                                             |
|  OUTPUTS:                                                                   |
|  nunmbertype    int                 field number type                       |
|  rank           int                 field rank                              |
|  dims           long                dimensions of field region              |
|                                     (FORTRAN order)                         |
|  size           long                size in bytes of field region           |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Nov 99   Abe Taaheri   Modified for HDF5                                   |
|  Aug 00   A.Muslimov    Updated to reflect data type changes.               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWreginfo(int SwathID, int RegionID, char *fieldname, int *numbertype, int *rank, long dims[], long *size)
{
  int          ret      = FAIL;/* (int) Return status variable   */
  int		   j        = 0;   /* Loop index                     */

  hid_t        swathID  = FAIL;/* HDF5 type swath ID             */
  hid_t        regionID = FAIL;/* HDF5 type region ID            */

  herr_t	   status   = FAIL;/* routine return status variable */
  
  hid_t       *ntype = (hid_t *)NULL;/* number types  */
  size_t	  *tsize = (size_t *)NULL;
  
  hsize_t     swap   = 0;             /* Temporary swap variable */
  hsize_t     tempdims[HE5_DTSETRANKMAX];
  
  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Error buffer string */

  swathID  = (hid_t)SwathID;
  regionID = (hid_t)RegionID;

  tsize = (size_t *)calloc(1, sizeof(size_t));
  if (tsize == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for tsize.\n");
      H5Epush(__FILE__, "HE5_SWreginfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    } 

  ntype = (hid_t *)calloc(1, sizeof(hid_t));
  if (ntype == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for ntype.\n");
      H5Epush(__FILE__, "HE5_SWreginfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(tsize);
      return(FAIL);
    } 
  
  /* Initialize tempdims[] array */
  /* --------------------------- */
  for (j = 0; j < HE5_DTSETRANKMAX; j++)
    tempdims[ j ] = 0;

  /* Call SWregioninfo */
  /* ----------------- */
  status = HE5_SWregioninfo(swathID, regionID, fieldname, ntype, rank, tempdims, tsize);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot get information about region.\n");
      H5Epush(__FILE__, "HE5_SWreginfo", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(tsize);
      free(ntype);
      return(FAIL);
    }  
  
  /* Change dimensions to FORTRAN order */
  /* ---------------------------------- */
  for (j = 0; j < *rank / 2; j++)
    {
      swap = tempdims[*rank - 1 - j];
      tempdims[*rank - 1 - j] = tempdims[j];
      tempdims[j] = swap;
    }

  /* cast dimension sizes */
  /* -------------------- */
  for (j = 0; j < *rank; j++)
    dims[j] = (long)tempdims[j];
  

  *size       = (long)(*tsize);
  *numbertype = (int)(*ntype);

  free(tsize);
  free(ntype);

  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWextreg    (FORTRAN wrapper)                                |
|                                                                             |
|  DESCRIPTION: Retrieves data from specified region.                         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|  RegionID       int                 Region ID                               |
|  fieldname      char                Fieldname                               |
|  externalflag   int                 External geolocation fields flag        |
|                                     HDFE_INTERNAL (0)                       |
|                                     HDFE_EXTERNAL (1)                       |
|                                                                             |
|  OUTPUTS:                                                                   |
|  buffer         void                Data buffer containing subsetted region |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov    Updated to reflect data type changes.               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int    
HE5_SWextreg(int SwathID, int RegionID, char *fieldname, int externalflag, void *buffer)
{
  int          ret      = FAIL;  /* routine return status variable */

  hid_t        swathID  = FAIL;  /* HDF5 type swath ID             */
  hid_t        regionID = FAIL;  /* HDF5 type region ID            */

  herr_t	   status   = FAIL;  /* routine return status variable */

  char         errbuf[HE5_HDFE_ERRBUFSIZE];/* error message buffer */

  swathID  = (hid_t)SwathID;
  regionID = (hid_t)RegionID;

  status = HE5_SWextractregion(swathID, regionID, fieldname, externalflag, buffer);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot extract region data.\n");
      H5Epush(__FILE__, "HE5_SWextreg", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }  

  ret = (int)status;
  return(ret);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdeftmeper    (FORTRAN wrapper)                             |
|                                                                             |
|  DESCRIPTION: Finds swath cross tracks observed during time period and      |
|               returns  period ID                                            |
|                                                                             |
|                                                                             |
|  DESCRIPTION:                                                               |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  PeriodID       int                 Period ID                               |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|  starttime      double  TAI sec     Start of time period                    |
|  stoptime       doubel  TAI sec     Stop of time period                     |
|  mode           int                 Search mode                             |
|                                     HDFE_MIDPOINT - Use midpoint of Xtrack  |
|                                     HDFE_ENDPOINT - Use endpoints of Xtrack |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov    Updated to reflect data type changes.               |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWdeftmeper(int SwathID, double starttime, double stoptime, int mode)
{
  int             PeriodID = FAIL;            /* Period ID (return)   */

  hid_t           periodID = FAIL;            /* HDF5 type Period ID  */
  hid_t           swathID  = FAIL;            /* HDF5 type swath ID   */

  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer */


  swathID = (hid_t)SwathID;

  periodID = HE5_SWdeftimeperiod(swathID, starttime, stoptime, mode);
  if (periodID == FAIL)
    {
      sprintf(errbuf,"Cannot define time period.\n");
      H5Epush(__FILE__, "HE5_SWdeftmeper", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }   
    
  PeriodID = (int)periodID;
  return(PeriodID);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWperinfo                                                    |
|                                                                             |
|  DESCRIPTION: FORTRAN wrapper around SWperiodinfo                           |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|  PeriodID       int                 Period ID                               |
|  fieldname      char                Fieldname                               |
|                                                                             |
|                                                                             |
|  OUTPUTS:                                                                   |
|  nunmbertype    int                 field number type                       |
|  rank           int                 field rank                              |
|  dims           long                dimensions of field region              |
|                                     (FORTRAN order)                         |
|  size           long                size in bytes of field region           |
|                                                                             |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Nov 99   Abe Taaheri   Modified for HDF5                                   |
|  Aug 00   A.Muslimov    Updated to reflect data type changes.               |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWperinfo(int SwathID, int PeriodID, char *fieldname, int *numbertype,int *rank, long dims[], long *size)
{
  int		       ret      = SUCCEED;/* routine return status variable  */
  int		       j = 0;             /* Loop index                      */

  hid_t            swathID  = FAIL;   /* HDF5 type swath ID              */
  hid_t            periodID = FAIL;   /* HDF5 type period ID             */

  hid_t                *ntype   = (hid_t *)NULL;/* number types          */

  herr_t	       status   = SUCCEED;/* routine return status variable  */
  
  size_t	       *tsize   = (size_t *)NULL;
  
  hsize_t          swap     = 0;            /* Temporary swap variable    */
  hsize_t          tempdims[HE5_DTSETRANKMAX];
  
  char             errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer    */

  HE5_timeflag = 1;

  swathID  = (hid_t)SwathID;
  periodID = (hid_t)PeriodID;

  tsize = (size_t *)calloc(1, sizeof(size_t));
  if (tsize == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for tsize.\n");
      H5Epush(__FILE__, "HE5_SWperinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    } 

  ntype = (hid_t *)calloc(1, sizeof(hid_t));
  if (ntype == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for ntype.\n");
      H5Epush(__FILE__, "HE5_SWperinfo", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(tsize);
      return(FAIL);
    } 

  /* Initialize tempdims[] array */
  /* --------------------------- */
  for (j = 0; j < HE5_DTSETRANKMAX; j++)
    tempdims[ j ] = 0;

  /* Call SWregioninfo */
  /* ----------------- */
  status = HE5_SWregioninfo(swathID, periodID, fieldname, ntype, rank, tempdims, tsize);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot get information about region.\n");
      H5Epush(__FILE__, "HE5_SWperinfo", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(tsize);
      free(ntype);
      return(FAIL);
    }  
  
  /* Change dimensions to FORTRAN order */
  /* ---------------------------------- */
  for (j = 0; j < *rank / 2; j++)
    {
      swap = tempdims[*rank - 1 - j];
      tempdims[*rank - 1 - j] = tempdims[j];
      tempdims[j] = swap;
    }

  for (j = 0; j < *rank; j++)
    dims[j] = (long)tempdims[j];
 
 
  *size       = (long)(*tsize);
  *numbertype = (int)(*ntype);

  free(tsize);
  free(ntype);

  ret = (int)status;
  return(ret);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdupreg     (FORTRAN wrapper)                               |
|                                                                             |
|  DESCRIPTION: Duplicates a region                                           |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  NewregionID    int                 New region ID                           |
|                                                                             |
|  INPUTS:                                                                    |
|  OldregionID    int                 Old region ID                           |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======   ============  =================================================  |
|  Aug  00   A.Muslimov                                                       |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int 
HE5_SWdupreg(int OldregionID)
{
  int     NewregionID = FAIL;/* New region ID (return) */

  hid_t   newregionID = FAIL;/* New region ID          */
  hid_t   oldregionID = FAIL;/* Old region ID          */


  oldregionID = (hid_t)OldregionID;

  newregionID = HE5_SWdupregion(oldregionID);
  if(newregionID == FAIL)
    {
      H5Epush(__FILE__, "HE5_SWdupreg", __LINE__, H5E_FUNC, H5E_CANTINIT, "Cannot duplicate region.");
      HE5_EHprint("Error: Cannot duplicate region, occured", __FILE__, __LINE__);
      return(FAIL);
    }

  NewregionID = (int)newregionID;
  return(NewregionID);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWupscene     (FORTRAN wrapper)                              |
|                                                                             |
|  DESCRIPTION: Updates the StartRegion and StopRegion values                 |
|               for a specified region. This function is for Landsat.         |
|               The start and stop values must be set to the beginning        |
|               and the end of a scene, fixed scene subsetting.               |
|                                                                             |
|                                                                             |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|  RegionID       int                 Region ID                               |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int    
HE5_SWupscene(int SwathID, int RegionID)
{
  int             ret      = FAIL;/* routine return status variable  */

  herr_t          status   = FAIL;/* routine return status variable  */

  hid_t           swathID  = FAIL;/* HDF5 type swath ID              */
  hid_t           regionID = FAIL;/* HDF5 type region ID             */

  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer   */


  swathID  = (hid_t)SwathID;
  regionID = (hid_t)RegionID;
  
  status = HE5_SWupdatescene(swathID, regionID);
  if (status == FAIL)
    {
      sprintf(errbuf, "Cannot update scene.\n");
      H5Epush(__FILE__, "HE5_SWupscene", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
  
  ret = (int)status;
  return(ret);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWregidx                                                     |
|                                                                             |
|  DESCRIPTION: Finds swath cross tracks within area of interest and returns  |
|               region index and region ID (FORTRAN Wrapper)                  |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  RegionID       int                 Region ID                               |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|  cornerlon      double  dec deg     Longitude of opposite corners of box    |
|  cornerlat      double  dec deg     Latitude of opposite corners of box     |
|  mode           int                 Search mode                             |
|                                     HDFE_MIDPOINT - Use midpoint of Xtrack  |
|                                     HDFE_ENDPOINT - Use endpoints of Xtrack |
|                                     HDFE_ANYPOINT - Use all points of Xtrack|
|                                                                             |
|  OUTPUTS:                                                                   |
|  geodim         char                geolocation track dimension             |
|  idxrange       long                indices of region for along track dim.  |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  May 00   D.Wynne       Original Programmer                                 |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWregidx(int SwathID, double cornerlon[], double cornerlat[], int mode, char *geodim, long idxrange[])
{
  int		i          = 0;              /* Loop index           */
  int		RegionID   = SUCCEED;        /* Region ID            */

  hid_t     swathID    = FAIL;           /* HDF5 type swath ID   */
  hid_t     regionID   = FAIL;           /* HDF5 type region ID  */

  hsize_t	range[2]   = {0, 0};         /* Index range array    */
  
  char      errbuf[HE5_HDFE_ERRBUFSIZE]; /* Error message buffer */

  swathID = (hid_t)SwathID;

  regionID = HE5_SWregionindex(swathID, cornerlon, cornerlat, mode, geodim, range);
  if (regionID == FAIL)
    {
      sprintf(errbuf, "Cannot get the region indices.\n");
      H5Epush(__FILE__, "HE5_SWregidx", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
  
  for(i = 0; i < 2; i++)
    idxrange[i] = HE5_EHhsize2long(range[i]);

  
  RegionID = (int)regionID;
  return(RegionID);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWextper   (FORTRAN wrapper)                                 |
|                                                                             |
|  DESCRIPTION: Retrieves data from specified period.                         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|  PeriodID       int                 Period ID                               |
|  fieldname      char                Fieldname                               |
|  externalflag   int                 External geolocation fields flag:       |
|                                                                             |
|                                     HDFE_INTERNAL (0)                       |
|                                     HDFE_EXTERNAL (1)                       |
|  OUTPUTS:                                                                   |
|  buffer         void                Data buffer containing subsetted region |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  Aug 00  A.Muslimov                                                         |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int    
HE5_SWextper(int SwathID, int PeriodID, char *fieldname, int externalflag, void *buffer)
{
  int             ret      = FAIL;        /* return status variable  */

  herr_t          status   = FAIL;        /* return status variable  */

  hid_t           swathID  = FAIL;        /* HDF5 type swath ID      */
  hid_t           periodID = FAIL;        /* HDF5 type period ID     */

  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer    */


  HE5_timeflag = 1;
  swathID  = (hid_t)SwathID;
  periodID = (hid_t)PeriodID;

  /* Call SWextractregion routine */
  /* ---------------------------- */
  status = HE5_SWextractregion(swathID, periodID, fieldname, externalflag, (char *)buffer);
  if (status == FAIL)
    {
      sprintf(errbuf, "Cannot extract the period.\n");
      H5Epush(__FILE__, "HE5_SWextper", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }


  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWupimap     (FORTRAN wrapper)                               |
|                                                                             |
|  DESCRIPTION: Updates the map index for a specified region.                 |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nout           long                return Number of elements in output     |
|                                     index array if SUCCEED, (-1) FAIL       |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|  RegionID       int                 Region ID                               |
|  indexin        long                array of index values                   |
|                                                                             |
|  OUTPUTS:                                                                   |
|  indexout       long                array of index values                   |
|  indicies       long                array of start and stop in region       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWupimap(int SwathID, int RegionID, long indexin[], long indexout[], long indicies[])
{
  long        nout     = FAIL;/* # of elements in output array (return)  */

  hid_t       regionID = FAIL;/* HDF5 type region  ID                    */
  hid_t       swathID  = FAIL;/* HDF5 type swath ID                      */

  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Error buffer                    */

  swathID  = (hid_t)SwathID;
  regionID = (hid_t)RegionID;

  nout = HE5_SWupdateidxmap(swathID, regionID, indexin, indexout, indicies);
  if (nout == FAIL)
    {
      sprintf(errbuf, "Failed to update index mapping.\n");
      H5Epush(__FILE__, "HE5_SWupimap", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf );
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
  
  return(nout);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqswathF   (FORTRAN wrapper)                              |
|                                                                             |
|  DESCRIPTION: Returns number and names of swath structures in file          |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nSwath         long                Number of swath structures in file      |
|                                                                             |
|  INPUTS:                                                                    |
|  filename       char                HDF-EOS filename                        |
|                                                                             |
|  OUTPUTS:                                                                   |
|  swathlist      char                List of swath names (comma-separated)   |
|  strbufsize     long                Length of swathlist                     |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  July 00  A.Muslimov    Unmasked hdf5 data types.                           |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWinqswathF(char *filename, char *swathlist, long *strbufsize)
{
  long       nSwath     = FAIL;/* Number of swath structures in file */

  char       errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer     */  

  nSwath = HE5_SWinqswath(filename, swathlist, strbufsize);
  if ( nSwath < 0 )
    {
      sprintf(errbuf,"Cannot get information about Swath.");
      H5Epush(__FILE__, "HE5_SWinqswathF", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }								 

  return(nSwath);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWnentriesF    (FORTRAN wrapper)                             |
|                                                                             |
|  DESCRIPTION: Returns number of entries and string buffer size              |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nEntries       long                Number of entries                       |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|  entrycode      int                 Entry code                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  strbufsize     long                Length of comma-separated list          |
|                                     (Does not include null-terminator       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Aug 00   A.Muslimov                                                        |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWnentriesF(int SwathID, int entrycode, long *strbufsize)
{
  long            nEntries   = FAIL;       /* Number of entries         */

  hid_t           swathID    = FAIL;       /* HDF5 type swath ID        */

  char            errbuf[HE5_HDFE_ERRBUFSIZE]; /* Buffer for error message  */
  

  swathID = (hid_t)SwathID;

  nEntries = HE5_SWnentries(swathID, entrycode, strbufsize);
  if (nEntries < 0)
    {
      sprintf(errbuf,"Failed to get number of entries in a swath.");       
      H5Epush(__FILE__, "HE5_SWnentriesF", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

  return(nEntries);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION:     HE5_PRdefineF     (FORTRAN wrapper)                          |
|                                                                             |
|  DESCRIPTION:  Defines "Profile" dataset within a specified Swath, under the|
|                 "Data Fields" group.                                        |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  ret            int                      Return status (0) SUCCEED (-1)     |
|                                          FAIL                               |
|  INPUTS:                                                                    |
|  SwathID        int                      Swath ID                           |
|  profilename    char                     Profile/dataset name               |
|  fortdimlist    char                     Dim. list (comma-separated list)   |
|                                          FORTRAN dimesion order             |
|  fortmaxdimlist char                     Max Dim. list (FORTRAN order)      |
|                                          profile/dataset                    |
|  ntype          int                      Base datatype ID                   |
|                                                                             |
|  OUTPUTS:                                                                   |
|    None                                                                     |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  Aug 00   A.Muslimov    Original development.                               |
|  Dec 00   A.Muslimov    Updated to add "fortdimlist" and "fortmaxdimlist"   |
|                          inputs.                                            |
|  May 01   C.Praderas    Continued development.                              |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int  
HE5_PRdefineF(int SwathID, char *profilename, char *fortdimlist, char *fortmaxdimlist, int ntype)
{ 
  int         ret         = FAIL;/* return status variable      */

  herr_t      status      = FAIL;/* return status variable      */

  hid_t       swathID     = FAIL;/* HDF5 type swath ID          */
  hid_t       dtypeID     = FAIL;/* HDF5 type data type ID      */

  char	      *dimlist    = (char *)NULL; /* Dimension list (C order)  */
  char	      *maxdimlist = (char *)NULL; /* Max. dimension list (C)   */
  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer      */

  swathID = (hid_t)SwathID;
  dtypeID = HE5_EHconvdatatype(ntype);   
  if(dtypeID == FAIL)
    {
      H5Epush(__FILE__, "HE5_PRdefineF", __LINE__, H5E_DATATYPE, H5E_BADVALUE, "Cannot convert datatype for FORTRAN wrapper.");
      HE5_EHprint("Error: Cannot convert datatype for FORTRAN wrapper, occured", __FILE__, __LINE__);
      return(FAIL);
    }

  if(strcmp(fortmaxdimlist,"") == 0)
    fortmaxdimlist = NULL;

  /* Allocate space for C order dimension list */
  /* ----------------------------------------- */
  dimlist = (char *)calloc(strlen(fortdimlist) + 1, sizeof(char));
  if(dimlist == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for dimlist.\n");
      H5Epush(__FILE__, "HE5_PRdefineF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
  /* Reverse entries in dimension list (FORTRAN -> C) */
  /* ------------------------------------------------ */
  status = HE5_EHrevflds(fortdimlist, dimlist);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot reverse entries in dimension list.\n");
      H5Epush(__FILE__, "HE5_PRdefineF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(dimlist);
      return(FAIL);
    }

  if (fortmaxdimlist != NULL)
    {
      /* Allocate space for C order max. dim. list */
      /* ----------------------------------------- */
      maxdimlist = (char *)calloc(strlen(fortmaxdimlist) + 1, sizeof(char));
      if(maxdimlist == NULL)
	{
	  sprintf(errbuf,"Cannot allocate memory for maxdimlist.\n");
	  H5Epush(__FILE__, "HE5_PRdefineF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(dimlist);
	  return(FAIL);
	}


      /* Reverse entries in dimension list (FORTRAN -> C) */
      /* ------------------------------------------------ */
      status = HE5_EHrevflds(fortmaxdimlist, maxdimlist);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot reverse entries in maximum dimension list.\n");
	  H5Epush(__FILE__, "HE5_PRdefineF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(dimlist);
	  free(maxdimlist);
	  return(FAIL);
	}
    }
  else
    {
      maxdimlist = NULL;
    }
	  
  /* Define specified profile */
  /* ------------------------ */
  status = HE5_PRdefine(swathID, profilename, dimlist, maxdimlist, dtypeID);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot define \"%s\" profile.\n", profilename);
      H5Epush(__FILE__, "HE5_PRdefineF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(dimlist);
      if (maxdimlist!=NULL) 
	free(maxdimlist);

      return(FAIL); 
    }

  free(dimlist);
  if (maxdimlist != NULL) 
    free(maxdimlist);
  
  ret = (int)status;
  return (ret);    
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION:    HE5_PRwriteF    (FORTRAN  wrapper)                            |
|                                                                             |
|  DESCRIPTION: Writes data into the "Profile" dataset within a Swath.        |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  ret            int                      Return status (0) SUCCEED (-1)     |
|                                          FAIL                               |
|  INPUTS:                                                                    |
|    Swath_ID     int                      Swath ID                           |
|    profilename  char                     Name of Profile dataset            |
|    fortstart    long                     start array                        |
|    fortstride   long                     stride array                       |
|    fortedge     long                     edge array                         |
|                                                                             |
|    buffer       void                     Data buffer                        |
|                                                                             |
|  OUTPUTS:                                                                   |
|    None                                                                     |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  Aug 00   A.Muslimov    Original development                                |
|  Dec 00   A.Muslimov    Updated to add "start", "stride", and "edge"        |
|                           parameters.                                       |
|  May 01   C.Praderas    Continued development.                              |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int    
HE5_PRwriteF(int SwathID, char *profilename, long fortstart[], long fortstride[], long fortedge[], long size,  long len[], void *buffer)
{  
  int         ret     = FAIL;             /* return status variable        */
  int		  rank    = 0;                /* Profile rank                  */
  int         i;                          /* Loop index                    */
  int         nelmnts = 0;                /* Number of elements in Profile */
                                          /*  field                        */
  long        begin_offset = 0;           /* Used in storing  to VL buffer */
  long        end_offset   = 0;           /*           "  "                */
  long        length       = 0;           /*           "  "                */
  long        idx          = FAIL;        /* Swath index                   */

  herr_t      status  = FAIL;             /* return status variable        */
  
  hid_t       groupID  = FAIL;            /* "Profile Fields" group ID     */
  hid_t       gid      = FAIL;            /* "SWATHS" group ID             */
  hid_t       fid      = FAIL;            /* HDF-EOS file ID               */   
  hid_t       profID   = FAIL;            /* Profile dataset ID            */
  hid_t       typeID   = FAIL;            /* Dataset type ID               */
  hid_t       btypeID  = FAIL;            /* Base data type ID             */
  hid_t       swathID  = FAIL;            /* HDF5 type swath ID            */

  hssize_t    *start  = (hssize_t *)NULL; /* Ptr to start array (C order)  */
  hsize_t     dims[HE5_DTSETRANKMAX];     /* Profile dimensions            */
  hsize_t     maxdims[HE5_DTSETRANKMAX];  /* Profile maximum dimensions    */
  hsize_t     *stride = (hsize_t *)NULL;  /* Ptr to stride array (C order) */
  hsize_t     *edge   = (hsize_t *)NULL;  /* Ptr to edge array (C order)   */

  size_t      dsize      = 0;             /* Data size variable            */
  size_t      btype_size = 0;             /* Size of base datatype         */

  char        *buffer_char=NULL;
  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer          */

  hvl_t       *profile_buffer;            /*Data buffer for the profile    */

  
  dsize   = (size_t)size;  
  swathID = (hid_t)SwathID;

  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_PRinfo", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for swath ID failed. \n");
      H5Epush(__FILE__, "HE5_PRwriteF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Get "Profile Fields" group ID */
  /* ----------------------------- */
  groupID = HE5_SWXSwath[idx].prof_id;
  
  /* Open specified profile dataset */
  /* ------------------------------ */
  profID     = H5Dopen(groupID, profilename);
  if (profID == FAIL)
    {
      sprintf(errbuf,"Cannot open \"%s\" profile.\n", profilename);
      H5Epush(__FILE__, "HE5_PRwriteF", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    } 
  
  /* Get data type ID */
  /* ---------------- */
  typeID     = H5Dget_type(profID);
  if (typeID == FAIL)
    {
      sprintf(errbuf,"Cannot get data type ID.\n");
      H5Epush(__FILE__, "HE5_PRwriteF", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    } 

	  
  /* Get base data type ID */
  /* --------------------- */
  btypeID    = H5Tget_super(typeID);  
  if (btypeID == FAIL)
    {
      sprintf(errbuf,"Cannot get base data type ID.\n");
      H5Epush(__FILE__, "HE5_PRwriteF", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    } 
	  
  /* Get size of base data type */
  /* -------------------------- */
  btype_size   = H5Tget_size(btypeID);
  if (btype_size == FAIL)
    {
      sprintf(errbuf,"Cannot get size of base data type.\n");
      H5Epush(__FILE__, "HE5_PRwriteF", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    } 

  /* Release data type ID */
  /* -------------------- */
  status     = H5Tclose(typeID);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot release data type ID.\n");
      H5Epush(__FILE__, "HE5_PRwriteF", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
	  
  /* Release dataset ID */
  /* ------------------ */
  status = H5Dclose(profID);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot release dataset ID.\n");
      H5Epush(__FILE__, "HE5_PRwriteF", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Initialize dims[]/maxdims[] arrays */
  /* ---------------------------------- */
  for ( i = 0; i < HE5_DTSETRANKMAX; i++)
    {
      dims[ i ]    = 0;
      maxdims[ i ] = 0;
    }
  
  /* Get profile rank  */
  /* ----------------- */
  status = HE5_PRinfo(swathID, profilename, &rank, dims, maxdims, NULL, NULL, NULL);
  if (status != FAIL)
    {
      start = (hssize_t *)calloc(rank, sizeof(hssize_t));
      if(start == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for start.\n");
	  H5Epush(__FILE__, "HE5_PRwriteF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
        }
	  
      stride = (hsize_t *)calloc(rank, sizeof(hsize_t));
      if(stride == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for stride.\n");
	  H5Epush(__FILE__, "HE5_PRwriteF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  return(FAIL);
        }

      edge = (hsize_t *)calloc(rank, sizeof(hsize_t));
      if(edge == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for edge.\n");
	  H5Epush(__FILE__, "HE5_PRwriteF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  return(FAIL);
        }
 
      /* Reverse order of dimensions (FORTRAN -> C) */
      /* ------------------------------------------ */
      for (i = 0; i < rank; i++)
        {
	  start[i]  = (hssize_t)fortstart[rank - 1 - i];
	  stride[i] = (hsize_t)fortstride[rank - 1 - i];
	  edge[i]   = (hsize_t)fortedge[rank - 1 - i];
        }
	  
      /* Determine number of elements in Profile Field */
      /* --------------------------------------------- */
      nelmnts = 0;
      for (i = 0; i < rank; i++)  
	{
	  nelmnts = (int)fortedge[i] + nelmnts;      
	}

      buffer_char  = (char *)calloc(size*btype_size,1);
      if(buffer_char == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for buffer_char.\n");
	  H5Epush(__FILE__, "HE5_PRwriteF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  free(edge);
	  return(FAIL);
        }
	  
      memmove(buffer_char, buffer, size*btype_size); 
	  
      profile_buffer = (hvl_t *)calloc(nelmnts, sizeof(hvl_t));
      if(profile_buffer == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for profile_buffer.\n");
	  H5Epush(__FILE__, "HE5_PRwriteF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  free(edge);
	  free(buffer_char);
	  return(FAIL);
        }
	  
      begin_offset = 0;
      end_offset   = -1;
      for (i = 0; i < nelmnts; i++)
	{
	  profile_buffer[i].p = malloc(len[i]*((long)btype_size));
		  
	  begin_offset        = end_offset + 1;
	  end_offset          = begin_offset + len[i]*((long)btype_size) - 1;
	  length              = end_offset - begin_offset + 1;
		  
	  memmove(profile_buffer[i].p, &buffer_char[begin_offset], length); 
		  
	  profile_buffer[i].len  = (size_t)len[i]; 
		  
	}
	  
      free(buffer_char);
	  
	  
      /* Write data buffer to the profile dataset  */
      /* ----------------------------------------- */
      status = HE5_PRwrite(swathID, profilename, start, stride, edge, dsize, profile_buffer);
      if ( status == FAIL )
	{
	  sprintf(errbuf, "Cannot write data to \"%s\" profile. \n", profilename);
	  H5Epush(__FILE__, "HE5_PRwriteF", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  free(edge);
	  free(profile_buffer);	
	  return(FAIL);
	}
	  
      free(start);
      free(stride);
      free(edge);
      free(profile_buffer);	
    }
  else
    {
      sprintf(errbuf, "Error calling HE5_PRinfo() from FORTRAN wrapper. \n") ;
      H5Epush(__FILE__, "HE5_PRwriteF", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      status = FAIL;
    }


  ret = (int)status;
  return(ret);    
}
/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION:  HE5_PRreadF (FORTRAN wrapper)                                   |
|                                                                             |
|  DESCRIPTION:  Reads data from the profile dataset.                         |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  ret            int                      Return status (0) SUCCEED (-1)     |
|                                          FAIL                               |
|  INPUTS:                                                                    |
|   SwathID       int                      Swath ID                           |
|   profilename   char                     Name of profile/dataset            |
|   fortstart     long                     start array                        |
|   fortstride    long                     stride array                       |
|   fortedge      long                     edge array                         |
|   len           long                     lengths of each element in the     |
|                                           profile field                     |
|                                                                             |
|  OUTPUTS:                                                                   |
|   buffer_output void                      Data buffer                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  Aug 00   A.Muslimov    Original development                                |
|  Dec 00   A.Muslimov    Updated to add "start", "stride", and "edge"        |
|                           parameters.                                       |
|  May 01   C.Praderas    Continued development.                              |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int     
HE5_PRreadF(int SwathID, char *profilename, long fortstart[], long fortstride[], long fortedge[],long len[], void *buffer_output)
{
  int         ret         = FAIL;            /* Status variable       */
  int         rank        = FAIL;            /* Rank of dataset       */
  int         i;                             /* Loop index            */        

  long        num_prof_elmnts  = 0;       /* number of elements in profile */
  long        profile_datasize = 0;       /* Size (in bytes) of Prof Field */
  long        begin_offset     = 0;       /* Used in storing  to VL buffer */
  long        end_offset       = 0;       /*           "  "                */
  long        length           = 0;       /*           "  "                */

  long        idx              = FAIL;    /* Swath index                   */

  herr_t      status   = FAIL;            /* Status variable               */

  hid_t       swathID  = FAIL;            /* HDF5-type swath ID            */
  hid_t       groupID  = FAIL;            /* "Profile Fields" group ID     */
  hid_t       gid      = FAIL;            /* "SWATHS" group ID             */
  hid_t       fid      = FAIL;            /* HDF-EOS file ID               */   
  hid_t       profID   = FAIL;            /* Profile dataset ID            */
  hid_t       typeID   = FAIL;            /* Dataset type ID               */
  hid_t       btypeID  = FAIL;            /* Base data type ID             */

  hssize_t	  *start      = (hssize_t *)NULL;/* Start array (C order)      */
  hsize_t	  *stride     = (hsize_t *)NULL; /* Stride array (C order)     */
  hsize_t	  *edge       = (hsize_t *)NULL; /* Edge array (C order)       */
  hsize_t     dims[HE5_DTSETRANKMAX];        /* Profile dimensions         */
  hsize_t     maxdims[HE5_DTSETRANKMAX];     /* Profile max.dims           */ 

  size_t      btype_size  = 0;               /* Size of base datatype      */
  size_t      vltype_size = 0;               /* Size of variable length    */

  char        errbuf[HE5_HDFE_ERRBUFSIZE];   /* Error message buffer       */
  char        *buffer_char=NULL;

  hvl_t       *buffer;        /*  Buffer to read outt data from profile  */
  
  swathID = (hid_t)SwathID;


  /* Get HDF-EOS file ID, "HDFEOS" group ID and Swath index */
  /* ------------------------------------------------------ */
  status = HE5_SWchkswid(swathID, "HE5_PRinfo", &fid, &gid, &idx);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Checking for swath ID failed. \n");
      H5Epush(__FILE__, "HE5_PRreadF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
  /* Get "Profile Fields" group ID */
  /* ----------------------------- */
  groupID = HE5_SWXSwath[idx].prof_id;
  
  /* Open specified profile dataset */
  /* ------------------------------ */
  profID     = H5Dopen(groupID, profilename);
  if (profID == FAIL)
    {
      sprintf(errbuf,"Cannot open \"%s\" profile.\n", profilename);
      H5Epush(__FILE__, "HE5_PRreadF", __LINE__, H5E_DATASET, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    } 

  /* Get data type ID */
  /* ---------------- */
  typeID     = H5Dget_type(profID);
  if (typeID == FAIL)
    {
      sprintf(errbuf,"Cannot get data type ID.\n");
      H5Epush(__FILE__, "HE5_PRreadF", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    } 
  
  /* Get size of variable length data type (Profile field) */
  /* ----------------------------------------------------- */
  vltype_size   = H5Tget_size(typeID);
  if (vltype_size == FAIL)
    {
      sprintf(errbuf,"Cannot get size of variable length data type.\n");
      H5Epush(__FILE__, "HE5_PRreadF", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    } 
	  
  /* Get base data type ID */
  /* --------------------- */
  btypeID    = H5Tget_super(typeID);  
  if (btypeID == FAIL)
    {
      sprintf(errbuf,"Cannot get base data type ID.\n");
      H5Epush(__FILE__, "HE5_PRreadF", __LINE__, H5E_DATATYPE, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    } 
  
  /* Get size of base data type */
  /* -------------------------- */
  btype_size   = H5Tget_size(btypeID);
  if (btype_size == FAIL)
    {
      sprintf(errbuf,"Cannot get size of base data type.\n");
      H5Epush(__FILE__, "HE5_PRreadF", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    } 

  /* Release data type ID */
  /* -------------------- */
  status     = H5Tclose(typeID);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot release data type ID.\n");
      H5Epush(__FILE__, "HE5_PRreadF", __LINE__, H5E_DATATYPE, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
	  
  /* Release dataset ID */
  /* ------------------ */
  status = H5Dclose(profID);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot release dataset ID.\n");
      H5Epush(__FILE__, "HE5_PRreadF", __LINE__, H5E_DATASET, H5E_CLOSEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  

  /* Initialize dims[]/maxdims[] arrays */
  /* ---------------------------------- */
  for ( i = 0; i < HE5_DTSETRANKMAX; i++)
    {
      dims[ i ]    = 0;
      maxdims[ i ] = 0;
    }
  

  /* Get profile rank  */
  /* ----------------- */
  status = HE5_PRinfo(swathID, profilename, &rank, dims, maxdims, NULL, NULL, NULL);
  if (status != FAIL)
    {
      start = (hssize_t *)calloc(rank, sizeof(hssize_t));
      if(start == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for start.\n");
	  H5Epush(__FILE__, "HE5_PRreadF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
        }
	  
      stride = (hsize_t *)calloc(rank, sizeof(hsize_t));
      if(stride == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for stride.\n");
	  H5Epush(__FILE__, "HE5_PRreadF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  return(FAIL);
        }

      edge = (hsize_t *)calloc(rank, sizeof(hsize_t));
      if(edge == NULL)
        {
	  sprintf(errbuf,"Cannot allocate memory for edge.\n");
	  H5Epush(__FILE__, "HE5_PRreadF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(start);
	  free(stride);
	  return(FAIL);
        }
 
      /* Reverse order of dimensions (FORTRAN -> C) */
      /* ------------------------------------------ */
      for (i = 0; i < rank; i++)
        {
	  start[i]  = (hssize_t)fortstart[rank - 1 - i];
	  stride[i] = (hsize_t)fortstride[rank - 1 - i];
	  edge[i]   = (hsize_t)fortedge[rank - 1 - i];
        }

      /* Allocate space for buffer */
      /* ------------------------- */
      buffer = (hvl_t *) calloc(fortedge[0],sizeof(hvl_t));
      if ( buffer == NULL )
	{
	  H5Epush(__FILE__, "HE5_PRreadF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for read buffer.\n");
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return(FAIL);
	}

      /* Read the data from profile dataset  */
      /* ----------------------------------- */
      status = HE5_PRread(swathID, profilename, start, stride, edge, buffer);
      if ( status == FAIL )
	{
	  sprintf(errbuf, "Cannot read data from \"%s\" profile. \n", profilename);
	  H5Epush(__FILE__, "HE5_PRreadF", __LINE__, H5E_DATASET, H5E_READERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
          free(buffer);
	  return(FAIL);
	}
	  
      free(start);
      free(stride);
      free(edge);
	  
    }
  else
    {
      sprintf(errbuf, "Error calling HE5_PRinfo() from FORTRAN wrapper. \n") ;
      H5Epush(__FILE__, "HE5_PRreadF", __LINE__, H5E_ARGS, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      status = FAIL;
    }
  

  /* Calculate the number of elements in the profile field */
  /* ----------------------------------------------------- */
  for( i=0; i<rank; i++ )
    {
      num_prof_elmnts = num_prof_elmnts + (long)dims[i];
    }
  
  profile_datasize = 0;
  for( i = 0; i < num_prof_elmnts; i++ )
    {
      profile_datasize = profile_datasize + ((long) buffer[i].len)*((long)btype_size);  
      len[i] = (long) buffer[i].len;  
    }
  
  /* Allocate space */
  /* -------------- */
  buffer_char = (char *) calloc(profile_datasize,sizeof(unsigned char)); 
  if(buffer_char == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for buffer_char.\n");
      H5Epush(__FILE__, "HE5_PRreadF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(buffer);
      return(FAIL);
    }
  
  begin_offset = 0;
  end_offset   = -1;
  
  for( i = 0; i < num_prof_elmnts; i++ )
    {
      begin_offset        = end_offset + 1;
      end_offset          = begin_offset + len[i]*((long)btype_size) - 1;
      length              = end_offset - begin_offset + 1;
	  
      memmove(&buffer_char[begin_offset],buffer[i].p,length);
    }
  
  memmove(buffer_output,buffer_char,profile_datasize);
  
  status = HE5_PRreclaimspace(swathID, profilename, buffer);
  if (status == FAIL)
    {
      sprintf(errbuf, "Cannot reclaim the memory space. \n");
      H5Epush(__FILE__, "HE5_PRreadF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(buffer);
      free(buffer_char);
      return(FAIL);
    }

  /* Release memory */
  /* -------------- */
  free(buffer);    
  free(buffer_char);
  
  ret  = (int)status;
  return(ret);    
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_PRinquireF   (FORTRAN wrapper)                               |
|                                                                             |
|  DESCRIPTION:  Retrieves number of profiles in a swath                      |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  nProf          long                     Return number of profiles          |
|                                          FAIL                               |
|  INPUTS:                                                                    |
|    SwathID      int                      swath ID                           |
|                                                                             |
|  OUTPUTS:                                                                   |
|    profnames    char                     List of profile names              |
|    rank[]       int                      Profile/dataset rank array         |
|    ntype[]      int                      Array of profile base datatype IDs |
|                                                                             |
|  NOTES:                                                                     |
|    None                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  8/30/00  A. Muslimov   Original development                                |
|  Sep 00   A. Muslimov   Modified to change "Data Fields" onto "PRofile      |
|                                Fields"                                      |
|  May 01   C.Praderas    Continued development.                              |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long  
HE5_PRinquireF(int SwathID, char *profnames, int *rank, int *ntype)
{

  long         nProf    = FAIL;               /* Number of profiles   */

  int          i;                             /* Loop index           */

  H5T_class_t  *dtype   = (H5T_class_t *)NULL;/* Data type class ID   */   

  hid_t        swathID  = FAIL;               /* Swath group ID       */

  char         errbuf[HE5_HDFE_ERRBUFSIZE];   /* Error message buffer */


  swathID = (hid_t)SwathID;

  nProf = HE5_PRinquire(swathID, profnames, NULL, NULL);
  if (nProf == FAIL)
    {
      sprintf(errbuf, "Error calling HE5_PRinquire() from FORTRAN wrapper. \n");
      H5Epush(__FILE__, "HE5_PRinquireF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  dtype = (H5T_class_t *)calloc(nProf, sizeof(H5T_class_t));
  if (dtype == NULL)
    {
      sprintf(errbuf, "Cannot allocate memory for dtype. \n");
      H5Epush(__FILE__, "HE5_PRinquireF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }


  nProf = HE5_PRinquire(swathID, profnames, rank, dtype);
  if (nProf == FAIL)
    {
      sprintf(errbuf, "Error calling HE5_PRinquire() from FORTRAN wrapper. \n");
      H5Epush(__FILE__, "HE5_PRinquireF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
  for ( i = 0; i < nProf; i++)
    ntype[i] = (int)dtype[i];

  free(dtype);
  return(nProf);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_PRinfoF  (FORTRAN wrapper)                                   |
|                                                                             |
|  DESCRIPTION:  Retrieves information about specified profile.               |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  ret            int                      Return status                      |
|                                                                             |
|  INPUTS:                                                                    |
|    SwathID      int                      swath ID                           |
|    profname     char                     Profile name                       |
|                                                                             |
|  OUTPUTS:                                                                   |
|    rank[]       int                      Profile/dataset rank array         |
|    dims[]       long                     dimension size array               |
|    maxdims[]    long                     max. dimension size array          |
|    ntype        int                      Pointer to base datatype ID        |
|    fortdimlist      char                 Dimension list                     |
|    fortmaxdimlist   char                 Maximum Dimension List             |
|                                                                             |
|  NOTES:                                                                     |
|    None                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  8/30/00  A. Muslimov   Original development                                |
|  Sep  00  A. Muslimov   Modified to change the group from "Data Fields" to  |
|                          "HE5_PRofile Fields".                              |
|  May 01   C.Praderas    Continued development.                              |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int      
HE5_PRinfoF(int SwathID, char *profname, int *rank, long dims[], long maxdims[], int *ntype, char *fortdimlist, char *fortmaxdimlist)
{
  int           ret      = FAIL;    /* Return status variable       */
  int           j;                  /* Loop index                   */
        
  herr_t        status   = FAIL;    /* Return status variable       */

  hid_t         swathID  = FAIL;    /* Swath group ID               */
 
  hid_t         dtype[1] = {FAIL};  /* Data type ID                 */

  hsize_t	    tempdims[HE5_DTSETRANKMAX];   /* Dimension sizes array    */
  hsize_t	    tempmaxdims[HE5_DTSETRANKMAX];/* Max.Dim. sizes array     */
  hsize_t 	    swap     = 0;                 /* Temporary dimension size */

  /* Dimension lists in C order */
  /* -------------------------- */
  char		    *dimlist    = (char *)NULL;
  char		    *maxdimlist = (char *)NULL;

  char          errbuf[HE5_HDFE_ERRBUFSIZE];  /* Error message buffer   */

  swathID = (hid_t)SwathID;

  /* Allocate space for C order dimension list */
  /* ----------------------------------------- */
  maxdimlist = (char *)calloc(HE5_HDFE_UTLBUFSIZE, sizeof(char));
  dimlist    = (char *)calloc(HE5_HDFE_UTLBUFSIZE, sizeof(char));
  if(dimlist == NULL || maxdimlist == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for input list.\n");
      H5Epush(__FILE__, "HE5_PRinfoF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Initialize tempdims[]/tempmaxdims[] arrays */
  /* ------------------------------------------ */
  for ( j = 0; j < HE5_DTSETRANKMAX; j++)
    {
      tempdims[ j ]    = 0;
      tempmaxdims[ j ] = 0;
    }


  /* Get profile info */
  /* ---------------- */
  status = HE5_PRinfo(swathID, profname, rank, tempdims, tempmaxdims, dtype, dimlist, maxdimlist);
  if (status == SUCCEED)
    {
      for (j = 0; j < *rank / 2; j++)
        {
	  swap = tempdims[*rank - 1 - j];
	  tempdims[*rank - 1 - j] = tempdims[j];
	  tempdims[j] = swap;

	  swap = tempmaxdims[*rank - 1 - j];
	  tempmaxdims[*rank - 1 - j] = tempmaxdims[j];
	  tempmaxdims[j] = swap;
        }

      /* change the datatype */
      /* ------------------- */
      for (j = 0; j < *rank; j++)
	{
	  dims[j]    = (long)tempdims[j];
	  maxdims[j] = (long)tempmaxdims[j];
	}
	  
      /* Reverse order of dimensions entries in dimension list */
      /* ----------------------------------------------------- */
      if(fortdimlist != (char *)NULL)
	{
	  status = HE5_EHrevflds(dimlist, fortdimlist);
	  if(status == FAIL)
	    {
	      sprintf(errbuf,"Cannot reverse entries in dimension list.\n");
	      H5Epush(__FILE__, "HE5_PRinfoF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(dimlist);
	      free(maxdimlist);
	      return(FAIL);
	    }
	}
      if(fortmaxdimlist != (char *)NULL)
	{
	  status = HE5_EHrevflds(maxdimlist, fortmaxdimlist);
	  if(status == FAIL)
	    {
	      sprintf(errbuf,"Cannot reverse entries in maximum dimension list.\n");
	      H5Epush(__FILE__, "HE5_PRinfoF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	      HE5_EHprint(errbuf, __FILE__, __LINE__);
	      free(dimlist);
	      free(maxdimlist);
	      return(FAIL);
	    }
		  
	}
    }
  
  *ntype = (int)dtype[0];

  free(maxdimlist);
  free(dimlist);

  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_PRwrgattrF                                                   |
|                                                                             |
|  DESCRIPTION: FORTRAN wrapper to write/update "Profile Fields" group        |
|               attribute in a swath.                                         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  attrname       char*               group attribute name                    |
|  numtype        int                 group attribute HDF numbertype          |
|  fortcount[]    long                Number of group attribute elements      |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                   It is assumed that fortcout has just one element to agree |
|                   with EHattr() call.                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04   S.Zhao        Original development                                |
|  Mar 04   S.Zhao        Modified for a character string attribute.          |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_PRwrgattrF(int SwathID, char *attrname, int numtype, long fortcount[], void *datbuf)
{
  int              ret    = FAIL;            /* (int) return status variable      */
  int              rank   = 1;               /* Rank variable                     */
  int              i;                        /* Loop index                        */
 
  herr_t           status     = FAIL;        /* routine return status variable    */
 
  hid_t            swathID    = FAIL;        /* HDF5 type Swath ID                */
  hid_t            numbertype = FAIL;        /* HDF5 data type ID                 */
 
  hsize_t          *count  = (hsize_t *)NULL;/* Pointer to count array (C order)  */
 
  char             *errbuf = (char *)NULL;   /* error message buffer              */
  char             *tempbuf = (char *)NULL;  /* temp buffer                       */
 
  /* Allocate memory for error message buffers */
  /* ----------------------------------------- */
  errbuf  = (char *)calloc(HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_PRwrgattrF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
 
  /* Get HDF5 data type ID */
  /* --------------------- */
  numbertype = HE5_EHconvdatatype(numtype);
  if(numbertype == FAIL)
    {
      sprintf(errbuf,"Cannot convert to HDF5 type data type ID.\n");
      H5Epush(__FILE__, "HE5_PRwrgattrF", __LINE__, H5E_DATATYPE, H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
 
  count = (hsize_t *)calloc(rank, sizeof(hsize_t));
  if( count == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for count.\n");
      H5Epush(__FILE__, "HE5_PRwrgattrF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
 
  /* Reverse order of dimensions (FORTRAN -> C) */
  /* ------------------------------------------ */
  for (i = 0; i < rank; i++)
    count[i] = (hsize_t)fortcount[rank - 1 - i];
 
 
  swathID = (hid_t)SwathID;
 
  if ((numbertype == HE5T_CHARSTRING) || (numbertype == H5T_NATIVE_CHAR) || (numbertype == H5T_C_S1))
    {
      if (strlen((char *)datbuf) < count[0])
	{
	  sprintf(errbuf,"Size of databuf is less than the number of group attribute elements.\n");
	  H5Epush(__FILE__, "HE5_PRwrgattrF", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(count);
	  free(errbuf);
	  return(FAIL);
	}
 
      /* Allocate memory for temp buffer */
      /* ------------------------------- */
      tempbuf = (char * )calloc((count[0]+1), sizeof(char));
      if(tempbuf == NULL)
	{
	  sprintf(errbuf,"Cannot allocate memory for temp buffer.\n");
	  H5Epush(__FILE__, "HE5_PRwrgattrF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(count);
	  free(errbuf);
	  return(FAIL);
	}
 
      strncpy(tempbuf, (char *)datbuf, count[0]);
      tempbuf[count[0]] = '\0';
 
      status = HE5_PRwritegrpattr(swathID, attrname, numbertype, count, tempbuf);
      if(status == FAIL)
	{
          sprintf(errbuf,"Cannot write group attribute value.\n");
          H5Epush(__FILE__, "HE5_PRwrgattrF", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          free(errbuf);
          free(count);
          free(tempbuf);
          return(FAIL);
	}
      free(count);
      free(errbuf);
      free(tempbuf);
    }
  else
    {
      status = HE5_PRwritegrpattr(swathID, attrname, numbertype, count, datbuf);
      if(status == FAIL)
	{
          sprintf(errbuf,"Cannot write group attribute value.\n");
          H5Epush(__FILE__, "HE5_PRwrgattrF", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
          HE5_EHprint(errbuf, __FILE__, __LINE__);
          free(errbuf);
          free(count);
          return(FAIL);
	}
      free(count);
      free(errbuf);
    }
 
  ret = (int)status;
  return(ret);
}
 
 
/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_PRrdgattrF    (FORTRAN wrapper)                              |
|                                                                             |
|  DESCRIPTION: Reads attribute from the "Profile Fields" group in a swath.   |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  attrname       char                attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04   S.Zhao        Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int   
HE5_PRrdgattrF(int SwathID, char *attrname, void *datbuf)
{
  int         ret             = FAIL;   /* (int) return status      */
 
  herr_t      status          = FAIL;   /* return status variable   */
 
  hid_t       swathID         = FAIL;   /* HDF5 type Swath ID       */
 
  char        errbuf[HE5_HDFE_ERRBUFSIZE];  /* Error message buffer */
 
  swathID = (hid_t)SwathID;
 
  status = HE5_PRreadgrpattr(swathID,attrname,datbuf);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot read attribute \"%s\" from the \"Profile Fields\" group.\n", attrname);
      H5Epush(__FILE__, "HE5_PRrdgattrF", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
 
  ret = (int)status;
  return(ret);
}
 
 
/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_PRgattrinfoF                                                 |
|                                                                             |
|  DESCRIPTION:  FORTRAN wrapper for PRgrpattrinfo                            |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  attrname       char*               attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  numbertype     int                 attribute HDF numbertype                |
|  fortcount      long                Number of attribute elements            |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04   S.Zhao        Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
|                                                                             |
-----------------------------------------------------------------------------*/
int
HE5_PRgattrinfoF(int SwathID, char *attrname, int *numbertype, long *fortcount)
{
  int             ret     = FAIL;           /* (int) return status variable   */
 
  herr_t          status  = FAIL;           /* routine return status variable */
 
  hid_t           *ntype  = (hid_t *)NULL;  /* Data type class ID             */
 
  hid_t           swathID = FAIL;           /* HDF5 type Swath ID             */
 
  hsize_t         *count  = (hsize_t *)NULL;/* Pointer to count  (C order)    */
 
  char            *errbuf = (char *)NULL;   /* error message buffer           */
 
  /* Allocate memory for error message buffers */
  errbuf  = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_PRgattrinfoF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
 
  count = (hsize_t *)calloc(1, sizeof(hsize_t));
  if( count == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for count.\n");
      H5Epush(__FILE__, "HE5_PRgattrinfoF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
 
  ntype = (hid_t *)calloc(1, sizeof(hid_t));
  if( ntype == (hid_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for ntype.\n");
      H5Epush(__FILE__, "HE5_PRgattrinfoF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      return(FAIL);
    }
 
  swathID = (hid_t)SwathID;
 
  status = HE5_PRgrpattrinfo(swathID, attrname, ntype, count);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot get information about group attribute.\n");
      H5Epush(__FILE__, "HE5_PRgattrinfoF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      free(ntype);
      return(FAIL);
    }
 
  *fortcount  = (long)(*count);
  *numbertype = (int)(*ntype);
 
  free(errbuf);
  free(count);
  free(ntype);
 
  ret = (int)status;
  return(ret);
}
 
 
 
/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_PRgattrinfoF2                                                |
|                                                                             |
|  DESCRIPTION:  FORTRAN wrapper for PRgrpattrinfo2                           |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  attrname       char*               attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  numbertype     int                 attribute HDF numbertype                |
|  fortcount      long                Number of attribute elements            |
|  fortsize       long                buf size of attribute elements          |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04   S.Zhao        Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
|                                                                             |
-----------------------------------------------------------------------------*/
int
HE5_PRgattrinfoF2(int SwathID, char *attrname, int *numbertype, long *fortcount, long *fortsize)
{
  int             ret     = FAIL;           /* (int) return status variable   */
 
  herr_t          status  = FAIL;           /* routine return status variable */
 
  hid_t           *ntype  = (hid_t *)NULL;  /* Data type class ID             */
 
  hid_t           swathID = FAIL;           /* HDF5 type Swath ID             */
 
  hsize_t         *count  = (hsize_t *)NULL;/* Pointer to count  (C order)    */
 
  hsize_t         *size   = (hsize_t *)NULL;/* Pointer to size   (C order)    */
 
  char            *errbuf = (char *)NULL;   /* error message buffer           */
 
  /* Allocate memory for error message buffers */
  errbuf  = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_PRgattrinfoF2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }
 
  count = (hsize_t *)calloc(1, sizeof(hsize_t));
  if( count == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for count.\n");
      H5Epush(__FILE__, "HE5_PRgattrinfoF2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
 
  ntype = (hid_t *)calloc(1, sizeof(hid_t));
  if( ntype == (hid_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for ntype.\n");
      H5Epush(__FILE__, "HE5_PRgattrinfoF2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      return(FAIL);
    }
  
  size = (hsize_t *)calloc(1, sizeof(hsize_t));
  if( size == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for size.\n");
      H5Epush(__FILE__, "HE5_PRgattrinfoF2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
 
  swathID = (hid_t)SwathID;
 
  status = HE5_PRgrpattrinfo2(swathID, attrname, ntype, count, size);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot get information about group attribute.\n");
      H5Epush(__FILE__, "HE5_PRgattrinfoF2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(count);
      free(ntype);
      return(FAIL);
    }
 
  *fortcount  = (long)(*count);
  *fortsize   = (long)(*size);
  *numbertype = (int)(*ntype);
 
  free(errbuf);
  free(count);
  free(size);
  free(ntype);
 
  ret = (int)status;
  return(ret);
}
 

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_PRinqgattrsF (FORTRAN wrapper)                               |
|                                                                             |
|  DESCRIPTION:  Retrieves the number of attributes and string length of      |
|                attribute list in "Profile Fields" group                     |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nattr          long                Number of attributes in "Profile Fields"|
|                                     group.                                  |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  attrnames      char                Attribute names in "Profile Fields"     |
|                                     group (Comma-separated list)            |
|  strbufsize     long                Attributes name list string length      |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Feb 04   S.Zhao        Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long
HE5_PRinqgattrsF(int SwathID, char *attrnames, long *strbufsize)
{
  long            nattr   = FAIL;         /* Number of attributes (return)  */
 
  hid_t           swathID = FAIL;         /* HDF5 type swath ID             */
 
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer       */
 
  swathID = (hid_t)SwathID;
 
  nattr = HE5_PRinqgrpattrs(swathID, attrnames, strbufsize);
  if ( nattr < 0 )
    {
      sprintf(errbuf, "Cannot retrieve the attributes. \n");
      H5Epush(__FILE__, "HE5_PRinqgattrsF", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
 
  return(nattr);
}
 

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWsetaliasF    (FORTRAN wrapper)                             |
|                                                                             |
|  DESCRIPTION:  Defines alias for a specified field name                     |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  ret            int                      Return status                      |
|                                                                             |
|  INPUTS:                                                                    |
|   SwathID       int                      swath ID                           |
|   fieldname     char                     Original field name                |
|                                                                             |
|  OUTPUTS:                                                                   |
|   fortaliaslist char                     Comma separated list of aliases for|
|                                            the field name                   |
|  NOTES:                                                                     |
|    None                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  Oct  00  A. Muslimov   Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int    
HE5_SWsetaliasF(int SwathID, char *fieldname, char *fortaliaslist)
{
  int      ret        = FAIL;/* (int)Return status variable */

  herr_t   status     = FAIL;/* return status variable      */

  hid_t    swathID    = FAIL;/* HDF5 type swath ID          */

  char     *aliaslist = NULL;/* C-order list of aliases     */
  char     errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer  */

  swathID = (hid_t)SwathID;

  /* Allocate space for C order alias list */
  /* ------------------------------------- */
  aliaslist = (char *)calloc(strlen(fortaliaslist) + 1, sizeof(char));
  if(aliaslist == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for aliaslist.\n");
      H5Epush(__FILE__, "HE5_SWsetaliasF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
  
  /* Reverse entries in alias list (FORTRAN -> C) */
  /* -------------------------------------------- */
  status = HE5_EHrevflds(fortaliaslist, aliaslist);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot reverse entries in alias list.\n");
      H5Epush(__FILE__, "HE5_SWsetaliasF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(aliaslist);
      return(FAIL);
    }



  /* Call SWsetalias() */
  /* ----------------- */
  status = HE5_SWsetalias(swathID, fieldname, aliaslist);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Error calling SWsetalias() from FORTRAN wrapper. \n");
      H5Epush(__FILE__, "HE5_SWsetaliasF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(aliaslist);
      return(FAIL);
    }

  free(aliaslist);

  ret = (int)status;
  return(ret);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdropaliasF    (FORTRAN wrapper)                            |
|                                                                             |
|  DESCRIPTION:  Removes the alias for a specified field name                 |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  ret            int                      Return status                      |
|                                                                             |
|  INPUTS:                                                                    |
|    SwathID      int                      swath ID                           |
|    aliasname    char                     alias name to remove               |
|    fldgroup     int                      Field group flag                   |
|                                                                             |
|  OUTPUTS:                                                                   |
|                                                                             |
|  NOTES:                                                                     |
|    None                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  Oct  00  A. Muslimov   Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int    
HE5_SWdropaliasF(int SwathID, int fldgroup, char *aliasname)
{  
  int      ret        = FAIL;/* (int)Return status variable */

  herr_t   status     = FAIL;/* return status variable      */

  hid_t    swathID    = FAIL;/* HDF5 type Swath ID          */

  char     errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer  */

  swathID = (hid_t)SwathID;
  
  status = HE5_SWdropalias(swathID, fldgroup, aliasname);
  if(status == FAIL)
    {
      sprintf(errbuf,"Error calling SWdropalias() from FORTRAN wrapper.\n");
      H5Epush(__FILE__, "HE5_SWdropaliasF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  ret = (int)status;

  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqdfldaliasF (FORTRAN wrapper)                            |
|                                                                             |
|  DESCRIPTION:  Retrieves the number of fields & aliases and string length of|
|                fields & aliases list in "Data Fields" group                 |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nfldalias      long                Number of fields & aliases in "Data     |
|                                     Fields"  group.                         |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  fldalias       char*               Fields & aliases names in "Data Fields" |
|                                     group (Comma-separated list)            |
|  strbufsize     long*               Fields & aliases name list string length|
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Mar 03    S.Zhao       Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long
HE5_SWinqdfldaliasF(int SwathID, char *fldalias, long *strbufsize)
{
  long            nfldalias   = FAIL;     /* Number of fields & aliases (return)  */
 
  hid_t           swathID = FAIL;         /* HDF5 type swath ID             */
 
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer       */
 
  swathID = (hid_t)SwathID;
 
  nfldalias = HE5_SWinqdfldalias(swathID, fldalias, strbufsize);
  if ( nfldalias < 0 )
    {
      sprintf(errbuf, "Cannot retrieve the fields & aliases. \n");
      H5Epush(__FILE__, "HE5_SWinqdfldaliasF", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
 
  return(nfldalias);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqgfldaliasF (FORTRAN wrapper)                            |
|                                                                             |
|  DESCRIPTION:  Retrieves the number of fields & aliases and string length of|
|                fields & aliases list in "Geolocation Fields" group          |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nfldalias      long                Number of fields & aliases in "Geo-     |
|                                     location Fields"  group.                |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|                                                                             |
|  OUTPUTS:                                                                   |
|  fldalias       char*               Fields & aliases names in "Geolocation  |
|                                     Fields" group (Comma-separated list)    |
|  strbufsize     long*               Fields & aliases name list string length|
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Apr 03    S.Zhao       Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long
HE5_SWinqgfldaliasF(int SwathID, char *fldalias, long *strbufsize)
{
  long            nfldalias   = FAIL;     /* Number of fields & aliases (return)  */
 
  hid_t           swathID = FAIL;         /* HDF5 type swath ID             */
 
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer       */
 
  swathID = (hid_t)SwathID;
 
  nfldalias = HE5_SWinqgfldalias(swathID, fldalias, strbufsize);
  if ( nfldalias < 0 )
    {
      sprintf(errbuf, "Cannot retrieve the fields & aliases. \n");
      H5Epush(__FILE__, "HE5_SWinqgfldaliasF", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
 
  return(nfldalias);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWaliasinfoF    (FORTRAN wrapper)                            |
|                                                                             |
|  DESCRIPTION:  Retrieves information about field aliases                    |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  ret            int                      Return status                      |
|                                                                             |
|  INPUTS:                                                                    |
|    SwathID      int                      swath ID                           |
|    aliasname    char                     alias name                         |
|    fldgroup     int                      Field group flag                   |
|                                                                             |
|  OUTPUTS:                                                                   |
|    length       int                      Buffer size                        |
|    buffer       char                     Buffer with original field name    |
|                                                                             |
|  NOTES:                                                                     |
|    None                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  Oct  00  A. Muslimov   Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int    
HE5_SWaliasinfoF(int SwathID, int fldgroup, char *aliasname, int *length, char *buffer)
{
  int           ret        = FAIL;/* (int) return status variable          */
      
  herr_t        status     = FAIL;/* return status variable                */

  hid_t         swathID    = FAIL;/* HDF5 type swath ID                    */

  char          errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer        */

  swathID = (hid_t)SwathID;

  status = HE5_SWaliasinfo(swathID, fldgroup, aliasname, length, buffer);
  if(status == FAIL)
    {
      sprintf(errbuf,"Error calling SWaliasinfo() from FORTRAN wrapper.\n");
      H5Epush(__FILE__, "HE5_SWaliasinfoF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  ret = (int)status;

  return(ret);  

}
/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWfldrenameF   (FORTRAN wrapper)                             |
|                                                                             |
|  DESCRIPTION:  Changes the field name                                       |
|                                                                             |
|                                                                             |
|  Return Value    Type        Units       Description                        |
|  ============   ===========  =========   =================================  |
|  ret            int                      Return status                      |
|                                                                             |
|  INPUTS:                                                                    |
|    SwathID      int                      swath ID                           |
|    oldfieldname char                     Original field name                |
|                                                                             |
|  OUTPUTS:                                                                   |
|    newfieldname char                     New field name                     |
|                                                                             |
|  NOTES:                                                                     |
|    None                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  =======  ============  =================================================   |
|  Oct  00  A. Muslimov   Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int    
HE5_SWfldrenameF(int SwathID, char *oldfieldname, char *newfieldname)
{
  int      ret        = FAIL;/* (int)Return status variable */

  herr_t   status     = FAIL;/* return status variable      */

  hid_t    swathID    = FAIL;/* HDF5 type swath ID          */

  char     errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer  */

  swathID = (hid_t)SwathID;
  
  status = HE5_SWfldrename(swathID, oldfieldname, newfieldname);
  if(status == FAIL)
    {
      sprintf(errbuf,"Error calling SWfldrename() from FORTRAN wrapper.\n");
      H5Epush(__FILE__, "HE5_SWfldrenameF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  ret = (int)status;

  return(ret);  
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefcomchunkF    (FORTRAN wrapper)                          |
|                                                                             |
|  DESCRIPTION: Defines compression type and parameters and sets chunking     |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int     None        return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 Swath structure ID                      |
|  compcode       int                 compression code                        |
|  compparm       int                 compression parameters                  |
|  rank           int                 rank of a dataset                       |
|  *dim           long                pointer to the array containing sizes   |
|                                     of each dimension of a chunk            |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
| 
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Oct 00   A.Muslimov    Original version.                                   |
|  Jan 01   A.Muslimov    Added proper FORTRAN to C dimension order conversion|
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int   
HE5_SWdefcomchunkF(int SwathID, int compcode, int *compparm, int rank, long *dim)
{
  int		ret       = FAIL;           /* return status        */
  int		j         = 0;              /* Loop index           */

  herr_t	status    = FAIL;           /* return status        */

  hsize_t	*tempdims = (hsize_t *)NULL;/* Temporary variable   */

  hid_t     swathID   = FAIL;           /* HDF5 type swath ID   */
  
  char		*errbuf   = (char *)NULL;   /* error message buffer */
    
  /* Allocate memory for error message buffer */
  /* ---------------------------------------- */
  errbuf  = (char * )calloc( HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWdefcomchunkF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }

  /* Allocate space for C order dimension list */
  /* ----------------------------------------- */
  tempdims = (hsize_t *)calloc(rank, sizeof(hsize_t));
  if(tempdims == (hsize_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for tempdims.\n");
      H5Epush(__FILE__, "HE5_SWdefcomchunkF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }
  
  /* Change from FORTRAN to C dimension order */
  /* ---------------------------------------- */
  for (j = 0; j < rank; j++)
    tempdims[j] = (hsize_t)dim[ rank - 1 - j ];

  swathID = (hid_t)SwathID;

  /* Call HE5_SWdefcomchunk() */
  /* ------------------------ */
  status = HE5_SWdefcomchunk(swathID, compcode, compparm, rank, tempdims);
  if (status == FAIL)
    {
      sprintf(errbuf, "Error calling HE5_SWdefcomchunk from FORTRAN wrapper.\n");
      H5Epush(__FILE__, "HE5_SWdefcomchunkF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(tempdims);
      return(FAIL);
    }

  free(tempdims);
  free(errbuf);
    
  ret = (int)status;
  return(ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWsetextdataF      (FORTRAN wrapper)                         |
|                                                                             |
|  DESCRIPTION: Sets external data files.                                     |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  ret            int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  fortfilelist   char*               list of external files (FORTRAN order)  |
|  offset         long                array of offsets (in bytes) from the    |
|                                     beginning of the file to the location   |
|                                     in the file where the data starts       |
|  size           long                array of sizes (in bytes) reserved in   |
|                                     the file for the data.                  |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Apr 01   A.Muslimov    Original development.                               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int   
HE5_SWsetextdataF(int SwathID, char *fortfilelist, long offset[], long size[])
{
  int             ret          = FAIL;           /* return status variable */

  herr_t          status       = FAIL;           /* Return status variable */
  hid_t           swathID      = FAIL;           /* Swath HDF5 type ID     */
  
  off_t           *off         = (off_t *)NULL;  /* Array of data offsets  */
  
  long            nentries     = 0;              /* Number of list entries */
  long            i;                             /* Loop index             */
  
  hsize_t         *sz          = (hsize_t *)NULL;/* Array of data sizes    */

  char            *filelist    = (char *)NULL;   /* Files list (C order)   */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];   /* Error message buffer   */
  
  /* Allocate space for C order file list */
  /* ------------------------------------ */
  filelist = (char *)calloc(HE5_HDFE_UTLBUFSIZE, sizeof(char));
  if(filelist == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for input list.\n");
      H5Epush(__FILE__, "HE5_SWsetextdataF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Reverse entries in input list */
  /* ----------------------------- */
  status = HE5_EHrevflds(fortfilelist, filelist);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot reverse entries in file list.\n");
      H5Epush(__FILE__, "HE5_SWsetextdataF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(filelist);
      return(FAIL);
    }


  /* Parse the list of entries to get number of files */
  /* ------------------------------------------------ */
  nentries = HE5_EHparsestr(filelist, ',', NULL, NULL);
  if(nentries <= 0)
    {
      sprintf(errbuf,"Cannot parse the input list/input list is empty.\n");
      H5Epush(__FILE__, "HE5_SWsetextdataF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(filelist);
      return(FAIL);
    }
  

  /* Allocate space for offset array */
  /* ------------------------------- */
  off = (off_t *)calloc(nentries, sizeof(off_t));
  if(off == (off_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for input offset array.\n");
      H5Epush(__FILE__, "HE5_SWsetextdataF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(filelist);
      return(FAIL);
    }

  /* Allocate space for size array */
  /* ----------------------------- */
  sz = (hsize_t *)calloc(nentries, sizeof(hsize_t));
  if(sz == (hsize_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for input size array.\n");
      H5Epush(__FILE__, "HE5_SWsetextdataF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(filelist);
      free(off);
      return(FAIL);
    }

  /* Copy the elements of input arrays */
  /* --------------------------------- */
  for (i = 0; i < nentries; i++)
    {
      off[ nentries - 1 - i ] = (off_t)offset[ i ]; 
      sz[  nentries - 1 - i ]  = (hsize_t)size[ i ];
    }


  swathID = (hid_t)SwathID;

  /* Call the C function */
  /* ------------------- */
  status = HE5_SWsetextdata(swathID, filelist, off, sz);
  if (status == FAIL)
    {
      sprintf(errbuf, "Error calling HE5_SWsetextdata from FORTRAN wrapper.\n");
      H5Epush(__FILE__, "HE5_SWsetextdataF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(filelist);
      free(off);
      free(sz);
      return(FAIL);
    }

  if (filelist != NULL) free(filelist);
  if (off != NULL) free(off);
  if (sz != NULL) free(sz);
  
  ret = (int)status;
  return(ret);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWgetextdataF       (FORTRAN wrapper)                        |
|                                                                             |
|  DESCRIPTION: Gets external data files information.                         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nfiles         int                 number of external files  SUCCEED,      |
|                                               (-1) FAIL                     |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  fieldname      char*               External field name                     |
|                                                                             |
|  OUTPUTS:                                                                   |
|  namelength     long                Length of each name entry               |
|  fortfilelist   char*               List of file names (FORTRAN order)      |
|  offset         long                array of offsets (in bytes) from the    |
|                                     beginning of the file to the location   |
|                                     in the file where the data starts       |
|  size           long                array of sizes (in bytes) reserved in   |
|                                     the file for the data.                  |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Apr 01   A.Muslimov    Original development.                               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int   
HE5_SWgetextdataF(int SwathID, char *fieldname, long namelength, char *fortfilelist, long offset[], long size[])
{
  int             nfiles       = FAIL;           /* number of files (return) */
  int             i;                             /* Loop index               */

  herr_t          status       = FAIL;           /* Return status variable   */
  hid_t           swathID      = FAIL;           /* Swath HDF5 type ID       */
  
  off_t           *off         = (off_t *)NULL;  /* Array of data offsets    */

  hsize_t         *sz          = (hsize_t *)NULL;/* Array of sizes           */

  size_t          nmlen        = 0;              /* Each entry string length */ 

  char            *filelist    = (char *)NULL;   /* Files list (C order)     */
  char            errbuf[HE5_HDFE_ERRBUFSIZE];   /* Error message buffer     */
  
  /* Allocate space for C order output file list */
  /* ------------------------------------------- */
  filelist = (char *)calloc(HE5_HDFE_UTLBUFSIZE, sizeof(char));
  if(filelist == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for output list.\n");
      H5Epush(__FILE__, "HE5_SWgetextdataF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Allocate space for offset array */
  /* ------------------------------- */
  off = (off_t *)calloc(HE5_FLDNUMBERMAX , sizeof(off_t));
  if(off == (off_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for input offset array.\n");
      H5Epush(__FILE__, "HE5_SWgetextdataF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(filelist);
      return(FAIL);
    }

  /* Allocate space for size array */
  /* ----------------------------- */
  sz = (hsize_t *)calloc(HE5_FLDNUMBERMAX, sizeof(hsize_t));
  if(sz == (hsize_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for input size array.\n");
      H5Epush(__FILE__, "HE5_SWgetextdataF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(filelist);
      free(off);
      return(FAIL);
    }
  
  swathID = (hid_t)SwathID;

  nmlen = (size_t)namelength;

  /* Call the C function */
  /* ------------------- */
  nfiles = HE5_SWgetextdata(swathID, fieldname, nmlen, filelist, off, sz);
  if (nfiles == FAIL)
    {
      sprintf(errbuf, "Error calling HE5_SWgetextdata from FORTRAN wrapper.\n");
      H5Epush(__FILE__, "HE5_SWgetextdataF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(filelist);
      free(off);
      free(sz);
      return(FAIL);
    }

  /* Reverse entries in output list */
  /* ----------------------------- */
  status = HE5_EHrevflds(filelist, fortfilelist);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot reverse entries in output file list.\n");
      H5Epush(__FILE__, "HE5_SWgetextdataF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(filelist);
      free(off);
      free(sz);
      return(FAIL);
    }
  
  /* Populate the output arrays */
  /* -------------------------- */
  for (i = 0; i < nfiles; i++)
    {
      offset[ nfiles - 1 - i ] = (long)off[ i ];
      size[ nfiles - 1 - i ]   = (long)sz[ i ];
    }

  if (filelist != NULL) free(filelist);
  if (off != NULL) free(off);
  if (sz != NULL) free(sz);

  
  return(nfiles);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWindexinfoF                                                 |
|                                                                             |
|  DESCRIPTION: FORTRAN wrapper around SWindexinfo                            |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  RegionID       int                 Region ID                               |
|  object         char*               field name                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  rank           int*                field rank                              |
|  fortdimlist    char*               field dimension list                    |
|  fortindices    long*               indices of region for along track dim.  |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  June 04   S.Zhao       Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWindexinfoF(int RegionID, char *object, int *rank, char *fortdimlist, long *fortindices)
{
  int       ret        = FAIL; /* (int) Return status variable   */
  int       i, j;                        /* Loop index           */
 
  hid_t     regionID   = FAIL;           /* HDF5 type region ID  */
  herr_t    status     = FAIL; /* routine return status variable */
 
  char      errbuf[HE5_HDFE_ERRBUFSIZE]; /* Error message buffer */
  hsize_t   *indices[HE5_DTSETRANKMAX];
  hsize_t   swap       = 0;              /* Temporary dimension size   */
 
  /* Dimension lists in C order */
  /* -------------------------- */
  char      *dimlist   = (char *)NULL;
 
 
  /* Allocate space for C order dimension list */
  /* ----------------------------------------- */
  dimlist = (char *)calloc(HE5_HDFE_UTLBUFSIZE, sizeof(char));
  if(dimlist == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for input list.\n");
      H5Epush(__FILE__, "HE5_SWindexinfoF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }
 
  for (i = 0; i < HE5_DTSETRANKMAX; i++)
    {
      indices[i] = (hsize_t *)malloc(2*sizeof(hsize_t));
    }
 
  regionID = (hid_t)RegionID;
 
  /* Call SWindexinfo */
  /* ---------------- */
  status = HE5_SWindexinfo(regionID, object, rank, dimlist, indices);
  if (status == FAIL)
    {
      sprintf(errbuf,"Cannot get information about indices.\n");
      H5Epush(__FILE__, "HE5_SWindexinfoF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(dimlist);
      for (i = 0; i < HE5_DTSETRANKMAX; i++)
	{
	  free(indices[i]);
	  indices[i] = NULL;
	}
      return(FAIL);
    }
 
  /* Reverse order of dimensions entries in dimension list */
  /* ----------------------------------------------------- */
  if(fortdimlist != (char *)NULL)
    {
      status = HE5_EHrevflds(dimlist, fortdimlist);
      if(status == FAIL)
	{
	  sprintf(errbuf,"Cannot reverse entries in dimension list.\n");
	  H5Epush(__FILE__, "HE5_SWindexinfoF", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  free(dimlist);
	  for (i = 0; i < HE5_DTSETRANKMAX; i++)
	    {
	      free(indices[i]);
	      indices[i] = NULL;
	    }
	  return(FAIL);
	}
    }
 
  for (j = 0; j < *rank / 2; j++)
    {
      for (i = 0; i < 2; i++)
	{
	  swap = indices[*rank - 1 - j][i];
	  indices[*rank - 1 - j][i] = indices[j][i];
	  indices[j][i] = swap;
	}
    }
 
  for (j = 0; j < *rank; j++)
    {
      for (i = 0; i < 2; i++)
	{
	  fortindices[j*2+i] = (long)indices[j][i];
	}
    }
 
  for (i = 0; i < HE5_DTSETRANKMAX; i++)
    {
      free(indices[i]);
      indices[i] = NULL;
    }
 
  free(dimlist);
  dimlist = NULL;
 
  ret = (int)status;
  return(ret);
}
 

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWwrdmeta                                                    |
|                                                                             |
|  DESCRIPTION: Defines structural metadata for pre-existing data             |
|               field within swath structure (FORTRAN)                        |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  fieldname      char                fieldname                               |
|  fortdimlist    char                Dimension list (comma-separated list)   |
|                                         FORTRAN dimesion order              |
|  mvalue         int                 field type                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Jun 05    S. Zhao      Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWwrdmeta(int SwathID, char *fieldname, char *fortdimlist, int mvalue)
{
  int       ret        = FAIL;   /* (int) return status variable   */
  herr_t    status     = FAIL;   /* routine return status variable */

  hid_t     swathID    = FAIL;   /* HDF5 type swath ID             */
  hid_t     numbertype = FAIL;   /* HDF5 type data type ID         */

  char      *dimlist = (char *)NULL;   /* Dimension list (C order) */
  char      *errbuf  = (char *)NULL;   /* error message buffer     */
    

  swathID = (hid_t)SwathID;
    
  numbertype = HE5_EHconvdatatype(mvalue);
  if(numbertype == FAIL)
    {
      H5Epush(__FILE__, "HE5_SWwrdmeta", __LINE__, H5E_DATATYPE, H5E_BADVALUE, "Cannot convert datatype for FORTRAN wrapper.");
      HE5_EHprint("Error: Cannot convert datatype for FORTRAN wrapper, occured", __FILE__, __LINE__);
      return(FAIL);
    }

  /* Allocate memory for error message buffers */
  /* ----------------------------------------- */
  errbuf  = (char * )calloc(HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWwrdmeta", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }

  /* Allocate space for C order dimension list */
  /* ----------------------------------------- */
  dimlist = (char *) calloc(strlen(fortdimlist) + 1, sizeof(char));
  if(dimlist == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for dimlist.\n");
      H5Epush(__FILE__, "HE5_SWwrdmeta", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }

  /* Reverse entries in dimension list (FORTRAN -> C) */
  /* ------------------------------------------------ */
  status = HE5_EHrevflds(fortdimlist, dimlist);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot reverse entries in dimension list.\n");
      H5Epush(__FILE__, "HE5_SWwrdmeta", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(dimlist);
      return(FAIL);
    }

  /* Call Write Metadata routine */
  /* --------------------------- */
  status = HE5_SWwritedatameta(swathID, fieldname, dimlist, numbertype);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot write \"%s\" field metadata.\n", fieldname);
      H5Epush(__FILE__, "HE5_SWwrdmeta", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(dimlist);
      return(FAIL);
    }

  free(dimlist);
  free(errbuf);

  ret = (int)status;
  return (ret);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWwrgmeta                                                    |
|                                                                             |
|  DESCRIPTION: Defines structural metadata for pre-existing geolocation      |
|               field within swath structure (FORTRAN)                        |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  fieldname      char                fieldname                               |
|  fortdimlist    char                Dimension list (comma-separated list)   |
|                                         FORTRAN dimesion order              |
|  mvalue         int                 field type                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Jun 05    S. Zhao      Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWwrgmeta(int SwathID, char *fieldname, char *fortdimlist, int mvalue)
{
  int       ret        = FAIL;   /* (int) return status variable   */
  herr_t    status     = FAIL;   /* routine return status variable */

  hid_t     swathID    = FAIL;   /* HDF5 type swath ID             */
  hid_t     numbertype = FAIL;   /* HDF5 type data type ID         */

  char      *dimlist = (char *)NULL;   /* Dimension list (C order) */
  char      *errbuf  = (char *)NULL;   /* error message buffer     */


  swathID = (hid_t)SwathID;

  numbertype = HE5_EHconvdatatype(mvalue);
  if(numbertype == FAIL)
    {
      H5Epush(__FILE__, "HE5_SWwrgmeta", __LINE__, H5E_DATATYPE, H5E_BADVALUE, "Cannot convert datatype for FORTRAN wrapper.");
      HE5_EHprint("Error: Cannot convert datatype for FORTRAN wrapper, occured", __FILE__, __LINE__);
      return(FAIL);
    }

  /* Allocate memory for error message buffers */
  /* ----------------------------------------- */
  errbuf  = (char * )calloc(HE5_HDFE_ERRBUFSIZE, sizeof(char));
  if(errbuf == NULL)
    {
      H5Epush(__FILE__, "HE5_SWwrgmeta", __LINE__, H5E_RESOURCE, H5E_NOSPACE, "Cannot allocate memory for error buffer.");
      HE5_EHprint("Error: Cannot allocate memory for error buffer, occured", __FILE__, __LINE__);
      return(FAIL);
    }

  /* Allocate space for C order dimension list */
  /* ----------------------------------------- */
  dimlist = (char *) calloc(strlen(fortdimlist) + 1, sizeof(char));
  if(dimlist == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for dimlist.\n");
      H5Epush(__FILE__, "HE5_SWwrgmeta", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      return(FAIL);
    }

  /* Reverse entries in dimension list (FORTRAN -> C) */
  /* ------------------------------------------------ */
  status = HE5_EHrevflds(fortdimlist, dimlist);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot reverse entries in dimension list.\n");
      H5Epush(__FILE__, "HE5_SWwrgmeta", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(dimlist);
      return(FAIL);
    }

  /* Call Write Metadata routine */
  /* --------------------------- */
  status = HE5_SWwritegeometa(swathID, fieldname, dimlist, numbertype);
  if(status == FAIL)
    {
      sprintf(errbuf,"Cannot write \"%s\" field metadata.\n", fieldname);
      H5Epush(__FILE__, "HE5_SWwrgmeta", __LINE__, H5E_FUNC, H5E_CANTINIT, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(errbuf);
      free(dimlist);
      return(FAIL);
    }

  free(dimlist);
  free(errbuf);

  ret = (int)status;
  return (ret);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWgetaliaslistF (FORTRAN wrapper)                            |
|                                                                             |
|  DESCRIPTION:  Retrieves the number of aliases and aliases list in swath    |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nalias         long                number of aliases                       |
|                                                                             |
|  INPUTS:                                                                    |
|  SwathID        int                 swath structure ID                      |
|  fldgroup       int                 field group flag (geo or data)          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  aliaslist      char*               list of aliases (comma-separated list)  |
|  strbufsize     long*               length of aliases list                  |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Jul 05    S.Zhao       Original development                                |
|  Dec 05    T.Roegner    NCR 44092 - Added CYGWIN capability                 |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long
HE5_SWgetaliaslistF(int SwathID, int fldgroup, char *aliaslist, long *strbufsize)
{
  long   nalias  = FAIL;         /* Number of aliases (return)     */
  hid_t  swathID = FAIL;         /* HDF5 type swath ID             */
  char   errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer       */


  swathID = (hid_t)SwathID;

  nalias = HE5_SWgetaliaslist(swathID, fldgroup, aliaslist, strbufsize);
  if (nalias < 0)
    {
      sprintf(errbuf, "Cannot retrieve the aliases. \n");
      H5Epush(__FILE__, "HE5_SWgetaliaslistF", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

  return(nalias);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWsetdimscale2F (FORTRAN wrapper for HE5_SWsetdimscale2)     |
|                                                                             |
|  DESCRIPTION: Defines a dimension scale for a fields dimension in a SW      |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swID           int                 SW structure ID                         |
|  fieldname      char                field name                              |
|  dimname        char                dim name                                |
|  dimscalename   char                dim scale name                          |
|  dim            long                Dimemsion value                         |
|  numbertype_in  int                 dim scale data type such as DFNT_INT32, |
|                                     DFNT_FLOAT64, DFNT_FLOAT32, etc.        |
|  data           void                data buffer for write                   |
|                                                                             |
|                                                                             |
|  OUTPUTS:                                                                   |
|                None                                                         |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  March 17 Abe Taaheri  Original Programmer                                  |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWsetdimscale2F(int SwathID, char *fieldname, char *dimname, char *dimscalename,
		  long dim, int numbertype_in, void * data)
{
  herr_t          status;
  hid_t           swID;
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer       */


  swID = (hid_t)SwathID;

  status = HE5_SWsetdimscale2(swID, fieldname, dimname, dimscalename,
			     (hsize_t) dim, (hid_t) numbertype_in, data);

  if (status < 0)
    {
      sprintf(errbuf, "Cannot set dimension scale %s for field %s. \n", dimname, fieldname);
      H5Epush(__FILE__, "HE5_SWsetdimscale2F", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

  return((int)status);

}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWsetdimscaleF (FORTRAN wrapper)                             |
|                                                                             |
|  DESCRIPTION: Defines a dimension scale for a fields dimension in a SW      |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swID           int                 SW structure ID                         |
|  fieldname      char                field name                              |
|  dimname        char                dim name                                |
|  dim            long                Dimemsion value                         |
|  numbertype_in  int                 dim scale data type such as DFNT_INT32, |
|                                     DFNT_FLOAT64, DFNT_FLOAT32, etc.        |
|  data           void                data buffer for write                   |
|                                                                             |
|                                                                             |
|  OUTPUTS:                                                                   |
|                None                                                         |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  May 10    Abe Taaheri  Original Programmer                                 |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWsetdimscaleF(int SwathID, char *fieldname, char *dimname,
		  long dim, int numbertype_in, void * data)
{
  herr_t          status;
  hid_t           swID;
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer       */


  swID = (hid_t)SwathID;

  status = HE5_SWsetdimscale(swID, fieldname, dimname,
			     (hsize_t) dim, (hid_t) numbertype_in, data);

  if (status < 0)
    {
      sprintf(errbuf, "Cannot set dimension scale %s for field %s. \n", dimname, fieldname);
      H5Epush(__FILE__, "HE5_SWsetdimscaleF", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

  return((int)status);

}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefdimscale2F (FORTRAN wrapper forHE5_SWdefdimscale2 )     |
|                                                                             |
|  DESCRIPTION: Defines dimension scale for a dimension for all fields in a   |
|               Swath                                                         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swID           int                 SW structure ID                         |
|  dimname        char                dim name                                |
|  dimscalename   char                dim scale name                          |
|  dim            long                Dimemsion value                         |
|  numbertype_in  int                 dim scale data type such as DFNT_INT32, |
|                                     DFNT_FLOAT64, DFNT_FLOAT32, etc.        |
|  data           void                data buffer for write                   |
|                                                                             |
|                                                                             |
|  OUTPUTS:                                                                   |
|                None                                                         |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  March 17  Abe Taaheri  Original Programmer                                 |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWdefdimscale2F(int SwathID, char *dimname, char *dimscalename,
		  long dim, int numbertype_in, void * data)
{
  herr_t          status;
  hid_t           swID;
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer       */


  swID = (hid_t)SwathID;

  status = HE5_SWdefdimscale2(swID, dimname, dimscalename,
			     (hsize_t) dim, (hid_t) numbertype_in, data);

  if (status < 0)
    {
      sprintf(errbuf, "Cannot set dimension scale %s for all fields in swath. \n", dimname);
      H5Epush(__FILE__, "HE5_SWdefdimscale2F", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

  return((int)status);

}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdefdimscaleF (FORTRAN wrapper)                             |
|                                                                             |
|  DESCRIPTION: Defines dimension scale for a dimension for all fields in a   |
|               Swath                                                         |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swID           int                 SW structure ID                         |
|  dimname        char                dim name                                |
|  dim            long                Dimemsion value                         |
|  numbertype_in  int                 dim scale data type such as DFNT_INT32, |
|                                     DFNT_FLOAT64, DFNT_FLOAT32, etc.        |
|  data           void                data buffer for write                   |
|                                                                             |
|                                                                             |
|  OUTPUTS:                                                                   |
|                None                                                         |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Jan 14    Abe Taaheri  Original Programmer                                 |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWdefdimscaleF(int SwathID, char *dimname,
		  long dim, int numbertype_in, void * data)
{
  herr_t          status;
  hid_t           swID;
  char            errbuf[HE5_HDFE_ERRBUFSIZE];/* Error message buffer       */


  swID = (hid_t)SwathID;

  status = HE5_SWdefdimscale(swID, dimname,
			     (hsize_t) dim, (hid_t) numbertype_in, data);

  if (status < 0)
    {
      sprintf(errbuf, "Cannot set dimension scale %s for all fields in swath. \n", dimname);
      H5Epush(__FILE__, "HE5_SWdefdimscaleF", __LINE__, H5E_DATASET, H5E_WRITEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

  return((int)status);

}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWgetdimscaleF  (FORTRAN wrapper)                            |
|                                                                             |
|  DESCRIPTION: Get dimension scale for a dimension of a field in a SW        |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         int                 return databuffsize  SUCCEED, (-1) FAIL |
|                                                                             |
|  INPUTS:                                                                    |
|  swID           int                 SWATH structure ID                      |
|  fieldname      char                field name                              |
|  dimname        char                dim name                                |
|                                                                             |
|                                                                             |
|  OUTPUTS:                                                                   |
|  dimsize        long                dimension size                          |
|  ntype          int                 number type                             |
|  databuff       void                data buffer for read                    |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  May 10    Abe Taaheri  Original Programmer                                 |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long
HE5_SWgetdimscaleF(int SwathID, char *fieldname, char *dimname, long *dimsize,
		   int *ntype, void * databuff)
{
  hsize_t         databuffsize =(hsize_t)FAIL; /* Size of buffer            */
  hid_t           swID         = FAIL;         /* HDF5 type swath ID        */
  char            errbuf[HE5_HDFE_ERRBUFSIZE]; /* Buffer for error message  */
  hsize_t         ds;
  hid_t           numtype;

  swID = (hid_t)SwathID;

  databuffsize = HE5_SWgetdimscale(swID, fieldname, dimname, &ds, &numtype,
				   databuff);
  *dimsize = (long) ds;
  *ntype = (int) numtype;

  if ( databuffsize < 0 )
    {
      sprintf(errbuf,"Cannot get dimension scale %s for field %s. \n", dimname, fieldname);
      H5Epush(__FILE__, "HE5_SWgetdimscaleF", __LINE__, H5E_OHDR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
						 
  return((long)databuffsize);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWreaddscaleattrF (FORTRAN wrapper)                          |
|                                                                             |
|  DESCRIPTION: Reads attribute associated with a dimension scale field       |
|               from a SW.                                                    |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swID           int     None        HDF-EOS type SWATH  ID                  |
|  fieldname      char                field name                              |
|  attrname       char                attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Jun 10   Abe Taaheri   Original development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int
HE5_SWreaddscaleattrF(int SwathID, char *fieldname, char *attrname, void *datbuf)
{
  herr_t          status         = FAIL;       /* return status             */
  hid_t           swID           = FAIL;       /* HDF5 type swath ID        */
  char            errbuf[HE5_HDFE_ERRBUFSIZE]; /* Buffer for error message  */
  

  swID = (hid_t)SwathID;

  status = HE5_SWreaddscaleattr(swID, fieldname, attrname, datbuf);
  if ( status < 0 )
    {
      sprintf(errbuf,"Cannot read attribute %s for dimension scale %s. \n", attrname, fieldname);
      H5Epush(__FILE__, "HE5_SWreaddscaleattrF", __LINE__, H5E_IO, H5E_SEEKERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
						 
  return((int)status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION:  HE5_SWwritedscaleattrF (FORTRAN wrapper)                        |
|                                                                             |
|  DESCRIPTION: Writes/updates attribute associated with a dimension scale    |
|               field in a SW.                                                |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swID           int                 SWATH structure ID                      |
|  fieldname      char*               dimension scale SDS name                |
|  attrname       char*               attribute name                          |
|  numtype        int                 attribute datatype ID                   |
|  count[]        long                Number of attribute elements            |
|  datbuf         void                I/O buffer                              |
|                                                                             |
|  OUTPUTS:                                                                   |
|  None                                                                       |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  May 10   Abe Taaheri   Original development.                               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int    
HE5_SWwritedscaleattrF(int SwathID, char *fieldname, char *attrname, int numtype, long count[], void *datbuf)
{
  herr_t          status         = FAIL;       /* return status             */
  hid_t           swID           = FAIL;       /* HDF5 type swath ID        */
  char            errbuf[HE5_HDFE_ERRBUFSIZE]; /* Buffer for error message  */
  hsize_t         fort_count[HE5_FLDNUMBERMAX];

  swID = (hid_t)SwathID;

  fort_count[0] = (hsize_t)count[0];
  status = HE5_SWwritedscaleattr(swID, fieldname, attrname, (hid_t)numtype, fort_count, datbuf);

  if ( status < 0 )
    {
      sprintf(errbuf,"Cannot write attribute %s for dimension scale %s. \n", attrname, fieldname);
      H5Epush(__FILE__, "HE5_SWwritedscaleattrF", __LINE__, H5E_ATTR, H5E_WRITEERROR, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }
						 
  return((int)status);
}



/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdscaleattrinfoF (FORTRAN wrapper)                          |
|                                                                             |
|  DESCRIPTION: Retrieves information about dimension scale attribute         |
|               (attribute associated with a specified dimension scale field) |
|                in a SW.                                                     |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swID           int       None      HDF-EOS type SWATH  ID                  |
|  fieldname      char*               field name                              |
|  attrname       char*               attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  ntype          int                 attribute data type ID                  |
|  fortcount      long                Number of attribute elements            |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  May 10   Abe Taaheri   Original Development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int 
HE5_SWdscaleattrinfoF(int SwathID, char *fieldname, char *attrname, int *ntype, long *fortcount)
{
  herr_t          status         = FAIL;       /* return status             */
  hid_t           swID           = FAIL;       /* HDF5 type swath ID        */
  char            errbuf[HE5_HDFE_ERRBUFSIZE]; /* Buffer for error message  */
  hsize_t         *count = (hsize_t *)NULL;    /* C-order count array       */
  hid_t           *dtype  = (hid_t *)NULL;     /* Data type class ID        */

  swID = (hid_t)SwathID;

  dtype = (hid_t *)calloc(1, sizeof(hid_t));
  if(dtype == (hid_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for \"dtype\".\n");
      H5Epush(__FILE__, "HE5_SWdscaleattrinfoF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  count = (hsize_t *)calloc(1, sizeof(hsize_t));
  if(count == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for \"count\".\n");
      H5Epush(__FILE__, "HE5_SWdscaleattrinfoF", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(dtype);
      return(FAIL);
    }

  count[0] = 0;

  status = HE5_SWdscaleattrinfo(swID, fieldname, attrname, dtype, count);
  if ( status == FAIL)
    {
      sprintf(errbuf, "Cannot retrieve attribute info for the %s dimension scale. \n", fieldname);
      H5Epush(__FILE__, "HE5_SWdscaleattrinfoF", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(count);
      free(dtype);
      return(FAIL);
    }
  
  *fortcount = (long)(*count);
  *ntype     = (int)(*dtype);

  free(count);
  free(dtype);
  return((int)status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWdscaleattrinfoF2 (FORTRAN wrapper)                         |
|                                                                             |
|  DESCRIPTION: Retrieves information about dimension scale attribute         |
|               (attribute associated with a specified dimension scale field) |
|                in a SW.                                                     |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         int                 return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swID           int       None      HDF-EOS type SWATH  ID                  |
|  fieldname      char*               field name                              |
|  attrname       char*               attribute name                          |
|                                                                             |
|  OUTPUTS:                                                                   |
|  ntype          int                 attribute data type ID                  |
|  fortcount      long                Number of attribute elements            |
|  fortsize       long                buf size of attribute elements          |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  May 10   Abe Taaheri   Original Development                                |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
int 
HE5_SWdscaleattrinfoF2(int SwathID, char *fieldname, char *attrname, int *ntype, long *fortcount, long *fortsize)
{
  herr_t          status         = FAIL;       /* return status             */
  hid_t           swID           = FAIL;       /* HDF5 type swath ID        */
  char            errbuf[HE5_HDFE_ERRBUFSIZE]; /* Buffer for error message  */
  hsize_t         *count = (hsize_t *)NULL;    /* C-order count array       */
  hsize_t         *size  = (hsize_t *)NULL;    /* buf size of array element */
  hid_t           *dtype  = (hid_t *)NULL;     /* Data type class ID        */

  swID = (hid_t)SwathID;

  dtype = (hid_t *)calloc(1, sizeof(hid_t));
  if(dtype == (hid_t *)NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for \"dtype\".\n");
      H5Epush(__FILE__, "HE5_SWdscaleattrinfoF2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  count = (hsize_t *)calloc(1, sizeof(hsize_t));
  if(count == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for \"count\".\n");
      H5Epush(__FILE__, "HE5_SWdscaleattrinfoF2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(dtype);
      return(FAIL);
    }
 size = (hsize_t *)calloc(1, sizeof(hsize_t));
  if(size == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for \"size\".\n");
      H5Epush(__FILE__, "HE5_SWdscaleattrinfoF2", __LINE__, H5E_RESOURCE, H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(dtype);
      return(FAIL);
    }

  count[0] = 0;

  status = HE5_SWdscaleattrinfo2(swID, fieldname, attrname, dtype, count, size);
  if ( status == FAIL)
    {
      sprintf(errbuf, "Cannot retrieve attribute info for the %s dimension scale. \n", fieldname);
      H5Epush(__FILE__, "HE5_SWdscaleattrinfoF2", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      free(count);
      free(dtype);
      return(FAIL);
    }
  
  *fortcount = (long)(*count);  
  *fortsize  = (long)(*size);
  *ntype     = (int)(*dtype);

  free(count);
  free(size);
  free(dtype);
  return((int)status);
}


/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWinqdscaleattrsF (FORTRAN wrapper)                          |
|                                                                             |
|  DESCRIPTION:  Retrieves the number of attributes and string length of      |
|                attribute list associated with a specified dimension scale   |
|                in a SW.                                                     |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  nattr          long                number of attributes (-1 if fails)      |
|                                                                             |
|  INPUTS:                                                                    |
|  swID           int     None        HDF-EOS type SWATH  ID                  |
|  fieldname      char                dimension scale name                    |
|  attrnames      char                attribute name(s)                       |
|                                                                             |
|  OUTPUTS:                                                                   |
|  strbufsize     long                String length of attribute (in bytes)   |
|                                                                             |
|  NOTES:                                                                     |
|                                                                             |
|  None                                                                       |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  June 10   Abe Taaheri  Original development.                               |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
long 
HE5_SWinqdscaleattrsF(int SwathID, char *fieldname, char *attrnames, long *strbufsize)
{
  long            status         = FAIL;       /* return status             */
  hid_t           swID           = FAIL;       /* HDF5 type swath ID        */
  char            errbuf[HE5_HDFE_ERRBUFSIZE]; /* Buffer for error message  */
  

  swID = (hid_t)SwathID;

  status = HE5_SWinqdscaleattrs(swID, fieldname, attrnames, strbufsize);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Cannot find the attribute %s for dimension scale %s. \n",attrnames,fieldname);
      H5Epush(__FILE__, "HE5_SWinqdscaleattrsF", __LINE__, H5E_ATTR, H5E_NOTFOUND, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
    }

  return (status);
}

/*----------------------------------------------------------------------------|
|  BEGIN_PROLOG                                                               |
|                                                                             |
|  FUNCTION: HE5_SWflddiminfo                                                 |
|                                                                             |
|  DESCRIPTION:  This functions returns dims and maxdims                      |
|                                                                             |
|                                                                             |
|  Return Value    Type     Units     Description                             |
|  ============   ======  =========   =====================================   |
|  status         herr_t  None        return status (0) SUCCEED, (-1) FAIL    |
|                                                                             |
|  INPUTS:                                                                    |
|  swathID        hid_t   None        HDF-EOS type swath  ID                  |
|  fieldname      char*               fieldname                               |
|                                                                             |
|  OUTPUTS:                                                                   |
|  rank           int                 field rank                              |
|  dims           hsize_t             dimensions of field                     |
|  maxdims        hsize_t             max dimensions of field                 |
|  NOTES:                                                                     |
|                                                                             |
|                                                                             |
|   Date     Programmer   Description                                         |
|  ======   ============  =================================================   |
|  Sep 11   Abe Taaheri   Added support for unlimited dimension adjustment    |
|                                                                             |
|  END_PROLOG                                                                 |
-----------------------------------------------------------------------------*/
herr_t
HE5_SWflddiminfo(hid_t SwathID, char *fieldname, int *rank,  hsize_t dims[], hsize_t maxdims[])
{
  herr_t      status         = FAIL;      /* return status             */
  hid_t       swID           = FAIL;      /* HDF5 type swath ID        */
  char        errbuf[HE5_HDFE_ERRBUFSIZE];/* Buffer for error message  */
  hid_t       ntype[1] = {FAIL};          /* Field numbertypes         */
  char	      *dimlist    = (char *)NULL; /* Dimension list in C order */
  char	      *maxdimlist = (char *)NULL; /* max Dimension list in C order */
  char        *dimbuf   = (char *)NULL;   /* Dimension buffer          */
  char        *comma    = (char *)NULL;   /* Pointer to comma          */
  char        *dimcheck = (char *)NULL;   /* Dimension check buffer    */
  hsize_t     dimsize   = 0;              /* Dimension size            */
  int         maxrank     = 0;            /* max dim  rank             */
  int         i           = 0;            /* Loop index                */
  int         foundAllDim = 1;            /* found all dimensions flag */
  int         first       = 1;            /* first entry flag          */
  char        utlbuf[HE5_HDFE_UTLBUFSIZE];/* Utility buffer            */

  swID = (hid_t)SwathID;

  /* Allocate space for C order dimension list */
  /* ----------------------------------------- */
  maxdimlist = (char *)calloc(HE5_HDFE_UTLBUFSIZE, sizeof(char));
  dimlist    = (char *)calloc(HE5_HDFE_UTLBUFSIZE, sizeof(char));
  if(dimlist == NULL || maxdimlist == NULL)
    {
      sprintf(errbuf,"Cannot allocate memory for input list.\n");
      H5Epush(__FILE__, "HE5_SWflddiminfo", __LINE__, H5E_RESOURCE, 
	      H5E_NOSPACE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Get field info  */
  /* --------------- */
  status = HE5_SWfieldinfo(swID, fieldname, rank, dims, ntype, 
			   dimlist, maxdimlist);
  if ( status == FAIL )
    {
      sprintf(errbuf, "Error calling HE5_SWfieldinfo. \n") ;
      H5Epush(__FILE__, "HE5_SWflddiminfo", __LINE__, H5E_ARGS, 
	      H5E_BADVALUE, errbuf);
      HE5_EHprint(errbuf, __FILE__, __LINE__);
      return(FAIL);
    }

  /* Allocate space for dimbuf, copy maxdimlist into it, & append comma */
  /* ------------------------------------------------------------------ */
  if(maxdimlist != NULL)
    {
      dimbuf = (char *) calloc(strlen(maxdimlist) + 64, sizeof(char));
      if(dimbuf == NULL)
	{
	  H5Epush(__FILE__, "HE5_SWflddiminfo", __LINE__, H5E_RESOURCE, 
		  H5E_NOSPACE, "Cannot allocate memory. \n");
	  HE5_EHprint("Error: Can not allocate memory, occured", 
		      __FILE__, __LINE__);
	  return(FAIL);

	}
	  
      /* Copy "maxdimlist" to "dimbuf", & append comma */
      /* --------------------------------------------- */
      strcpy(dimbuf, maxdimlist);
      strcat(dimbuf, ",");

      /* Find comma */
      /* ---------- */
      comma = strchr(dimbuf, ',');

      /*
       * Loop through entries in dimension list to make sure they are
       *                     defined in swath
       */
      while (comma != NULL)
	{
	  /* Copy dimension list entry to dimcheck */
	  /* ------------------------------------- */
	  dimcheck = (char *) calloc(comma - dimbuf + 1, sizeof(char));
	  if(dimcheck == NULL)
	    {
	      H5Epush(__FILE__, "HE5_SWflddiminfo", __LINE__, H5E_RESOURCE, 
		      H5E_NOSPACE, "Cannot allocate memory. \n");
	      HE5_EHprint("Error: Can not allocate memory, occured", 
			  __FILE__, __LINE__);
	      free(dimbuf);
	      free(dimlist);
	      free(maxdimlist);
	      return(FAIL);
	    }
	  memmove(dimcheck, dimbuf, comma - dimbuf);

	  /* Get dimension size */
	  /* ------------------ */
	  dimsize = HE5_SWdiminfo(swID, dimcheck);
	  if ( (dimsize > 0) || (dimsize == H5S_UNLIMITED) )
	    {
	      maxdims[maxrank] = dimsize;
	      maxrank++;
	    }
	  else
	    {
	      /*
	       * If dimension list entry not found - set error return
	       * status, append name to utility buffer for error report
	       */
	      status = FAIL;
	      foundAllDim = 0;
	      if (first == 1)
		strcpy(utlbuf, dimcheck);
	      else
		{
		  strcat(utlbuf, ",");
		  strcat(utlbuf, dimcheck);
		}
	      first = 0;
	    }

	  /*
	   * Go to next dimension entry, find next comma, & free up
	   * dimcheck buffer
	   */
	  memmove(dimbuf, comma + 1, strlen(comma + 1) + 1); 
	  comma = strchr(dimbuf, ',');
	  free(dimcheck);
	}

      free(dimbuf);
      free(dimlist);
      free(maxdimlist);

      /* If no dimensions found, report error */
      /* ------------------------------------ */
      if (foundAllDim == 0)
	{
	  status = FAIL;
	  sprintf(errbuf, "Dimension(s) \"%s\" not found for \"%s\" field. \n",
		  utlbuf, fieldname);
	  H5Epush(__FILE__, "HE5_SWflddiminfo", __LINE__, H5E_BTREE, 
		  H5E_NOTFOUND, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return (status);
	}


      /* If maxrank !=rank  then report error */
      /* ------------------------------------ */
      if ( maxrank != *rank )
	{
	  status = FAIL;
	  sprintf(errbuf,"Dimension rank doesn't match Max dimension rank.\n");
	  H5Epush(__FILE__, "HE5_SWflddiminfo", __LINE__, H5E_ARGS,
		  H5E_BADVALUE, errbuf);
	  HE5_EHprint(errbuf, __FILE__, __LINE__);
	  return (status);
	}
    } 
  /* "maxlist == NULL"  ==> maxdims[]= dims[] */
  /* ---------------------------------------- */
  else
    {
      for(i = 0; i < *rank; i++ )
	maxdims[ i ] = dims[ i ];
    }

  return (status);
}

#ifndef _cplusplus

/* HDF types used in FORTRAN bindings */
 
#if defined(DEC_ALPHA) || defined(IRIX) || defined(UNICOS) || defined(LINUX64) || defined(IA64) || defined(MACINTOSH) || defined(MACINTEL) || defined(IBM6000) || defined(CYGWIN)
 
#define INT32  INT
#define INT32V INTV
#define PINT32 PINT
 
#else
 
#define INT32  LONG
#define INT32V LONGV
#define PINT32 PLONG
 
#endif


/* File/Swath access routines */

FCALLSCFUN2(INT, HE5_SWopenF, HE5_SWOPEN, he5_swopen, STRING, INT)
FCALLSCFUN2(INT, HE5_SWcreateF, HE5_SWCREATE, he5_swcreate, INT, STRING)
FCALLSCFUN2(INT, HE5_SWattachF, HE5_SWATTACH, he5_swattach, INT, STRING)
FCALLSCFUN1(INT, HE5_SWdetachF, HE5_SWDETACH, he5_swdetach, INT)
FCALLSCFUN1(INT, HE5_SWcloseF, HE5_SWCLOSE, he5_swclose, INT)

/* Definition routines */

FCALLSCFUN3(INT, HE5_SWdefdimF, HE5_SWDEFDIM, he5_swdefdim, INT, STRING, LONG)
FCALLSCFUN5(INT, HE5_SWdefdimmapF, HE5_SWDEFMAP, he5_swdefmap, INT, STRING, STRING, LONG, LONG)
FCALLSCFUN4(INT, HE5_SWdefidxmapF, HE5_SWDEFIMAP, he5_swdefimap, INT, STRING, STRING, LONGV)
FCALLSCFUN6(INT, HE5_SWdefgfld, HE5_SWDEFGFLD, he5_swdefgfld, INT, STRING, STRING, STRING, INT, INT)
FCALLSCFUN6(INT, HE5_SWdefdfld, HE5_SWDEFDFLD, he5_swdefdfld, INT, STRING, STRING, STRING, INT, INT)
FCALLSCFUN3(INT, HE5_SWdefcompF, HE5_SWDEFCOMP, he5_swdefcomp, INT, INT, PINT)
FCALLSCFUN3(INT, HE5_SWdefchunkF, HE5_SWDEFCHUNK, he5_swdefchunk, INT, INT, PLONG)
FCALLSCFUN5(INT, HE5_SWdefcomchunkF, HE5_SWDEFCOMCH, he5_swdefcomch, INT, INT, PINT, INT, PLONG)
FCALLSCFUN5(LONG, HE5_SWupimap, HE5_SWUPIMAP, he5_swupimap, INT, INT, LONGV, LONGV, LONGV)
FCALLSCFUN3(INT, HE5_SWfldrenameF, HE5_SWFLDRNM, he5_swfldrnm, INT, STRING, STRING)

/* I/O routines */

FCALLSCFUN6(INT, HE5_SWwrfld, HE5_SWWRFLD, he5_swwrfld, INT, STRING, LONGV, LONGV, LONGV, PVOID)
FCALLSCFUN8(INT, HE5_SWwrcharfld, HE5_SWWRCHARFLD, he5_swwrcharfld, INT, STRING, INT, INT, LONGV, LONGV, LONGV, PVOID)
FCALLSCFUN6(INT, HE5_SWrdfld, HE5_SWRDFLD, he5_swrdfld, INT, STRING, LONGV, LONGV, LONGV, PVOID)
FCALLSCFUN8(INT, HE5_SWrdcharfld, HE5_SWRDCHARFLD, he5_swrdcharfld, INT, STRING, INT, INT, LONGV, LONGV, LONGV, PVOID)
FCALLSCFUN5(INT, HE5_SWwrattr, HE5_SWWRATTR, he5_swwrattr,INT,STRING,INT,LONGV,PVOID)
FCALLSCFUN5(INT, HE5_SWwrgattr, HE5_SWWRGATTR, he5_swwrgattr, INT, STRING, INT, LONGV,PVOID)
FCALLSCFUN5(INT, HE5_SWwrgeogattr, HE5_SWWRGEOGATTR, he5_swwrgeogattr, INT, STRING, INT, LONGV,PVOID)
FCALLSCFUN6(INT, HE5_SWwrlattr, HE5_SWWRLATTR, he5_swwrlattr, INT, STRING,STRING,INT,LONGV,PVOID)
FCALLSCFUN3(INT, HE5_SWrdattr, HE5_SWRDATTR, he5_swrdattr, INT, STRING, PVOID)
FCALLSCFUN3(INT, HE5_SWrdgattr, HE5_SWRDGATTR, he5_swrdgattr,INT,STRING,PVOID)
FCALLSCFUN3(INT, HE5_SWrdgeogattr, HE5_SWRDGEOGATTR, he5_swrdgeogattr,INT,STRING,PVOID)
FCALLSCFUN4(INT, HE5_SWrdlattr, HE5_SWRDLATTR, he5_swrdlattr,INT,STRING,STRING,PVOID)
FCALLSCFUN4(INT, HE5_SWsetfill, HE5_SWSETFILL, he5_swsetfill, INT, STRING, INT, PVOID)
FCALLSCFUN3(INT, HE5_SWgetfill, HE5_SWGETFILL, he5_swgetfill, INT, STRING, PVOID)
FCALLSCFUN3(INT, HE5_SWsetaliasF, HE5_SWSETALIAS, he5_swsetalias, INT, STRING, STRING)
FCALLSCFUN3(INT, HE5_SWdropaliasF, HE5_SWDRPALIAS, he5_swdrpalias, INT, INT, STRING)
FCALLSCFUN4(INT, HE5_SWwrdmeta, HE5_SWWRDMETA, he5_swwrdmeta, INT, STRING, STRING, INT)
FCALLSCFUN4(INT, HE5_SWwrgmeta, HE5_SWWRGMETA, he5_swwrgmeta, INT, STRING, STRING, INT)


/* Inquiry routines */

FCALLSCFUN3(LONG, HE5_SWinqswathF, HE5_SWINQSWATH, he5_swinqswath, STRING, PSTRING,PLONG)
FCALLSCFUN3(LONG, HE5_SWnentriesF, HE5_SWNENTRIES, he5_swnentries,INT,INT,PLONG)
FCALLSCFUN2(LONG, HE5_SWdiminfoF, HE5_SWNDIMINFO, he5_swdiminfo, INT, STRING)
FCALLSCFUN5(INT, HE5_SWmapinfoF, HE5_SWNMAPINFO, he5_swmapinfo,INT,STRING,STRING,PLONG,PLONG)
FCALLSCFUN2(INT, HE5_SWgmapinfo, HE5_SWGMAPINFO, he5_swgmapinfo,INT,STRING)
FCALLSCFUN7(INT, HE5_SWfldinfoF, HE5_SWFLDINFO, he5_swfldinfo,INT,STRING,PINT,LONGV,PINT,PSTRING,PSTRING)
FCALLSCFUN4(LONG, HE5_SWidxmapinfoF, HE5_SWIMAPINFO, he5_swimapinfo,INT,STRING,STRING,LONGV)
FCALLSCFUN4(LONG, HE5_SWinqmapsF, HE5_SWINQMAPS, he5_swinqmaps,INT,PSTRING,LONGV,LONGV)
FCALLSCFUN3(LONG, HE5_SWinqimapsF, HE5_SWINQIMAPS, he5_swinqimaps,INT,PSTRING,LONGV)
FCALLSCFUN3(LONG, HE5_SWinqdimsF, HE5_SWINQDIMS, he5_swinqdims,INT,PSTRING,LONGV)
FCALLSCFUN4(LONG, HE5_SWinqgflds, HE5_SWINQGFLDS, he5_swinqgflds, INT,PSTRING, INTV, INTV)
FCALLSCFUN4(LONG, HE5_SWinqdflds, HE5_SWINQDFLDS, he5_swinqdflds, INT,PSTRING, INTV, INTV)
FCALLSCFUN4(INT, HE5_SWatinfo, HE5_SWATTRINFO, he5_swattrinfo, INT, STRING, PINT, PLONG)
FCALLSCFUN4(INT, HE5_SWgatinfo, HE5_SWGATTRINFO, he5_swgattrinfo, INT, STRING, PINT, PLONG)
FCALLSCFUN4(INT, HE5_SWgeogatinfo, HE5_SWGEOGATTRINFO, he5_swgeogattrinfo, INT, STRING, PINT, PLONG)
FCALLSCFUN5(INT, HE5_SWlatinfo, HE5_SWLATTRINFO, he5_swlattrinfo, INT, STRING, STRING, PINT, PLONG)
FCALLSCFUN5(INT, HE5_SWatinfo2, HE5_SWATTRINFO2, he5_swattrinfo2, INT, STRING, PINT, PLONG, PLONG)
FCALLSCFUN5(INT, HE5_SWgatinfo2, HE5_SWGATTRINFO2, he5_swgattrinfo2, INT, STRING, PINT, PLONG, PLONG)
FCALLSCFUN5(INT, HE5_SWgeogatinfo2, HE5_SWGEOGATTRINFO2, he5_swgeogattrinfo2, INT, STRING, PINT, PLONG, PLONG)
FCALLSCFUN6(INT, HE5_SWlatinfo2, HE5_SWLATTRINFO2, he5_swlattrinfo2, INT, STRING, STRING, PINT, PLONG, PLONG)
FCALLSCFUN4(INT, HE5_SWcompinfoF, HE5_SWCOMPINFO, he5_swcompinfo, INT, STRING,PINT, INTV)
FCALLSCFUN3(LONG, HE5_SWinqattrsF, HE5_SWINQATTRS, he5_swinqattrs,INT,PSTRING,PLONG)
FCALLSCFUN4(LONG, HE5_SWinqlattrs, HE5_SWINQLATTRS, he5_swinqlattrs,INT,STRING,PSTRING,PLONG)
FCALLSCFUN3(LONG, HE5_SWinqgattrs, HE5_SWINQGATTRS, he5_swinqgattrs,INT,PSTRING,PLONG)
FCALLSCFUN3(LONG, HE5_SWinqgeogattrs, HE5_SWINQGEOGATTRS, he5_swinqgeogattrs,INT,PSTRING,PLONG)
FCALLSCFUN7(INT, HE5_SWreginfo, HE5_SWREGINFO, he5_swreginfo,INT,INT,STRING,PINT,PINT,LONGV,PLONG)
FCALLSCFUN7(INT, HE5_SWperinfo, HE5_SWPERINFO, he5_swperinfo,INT,INT,STRING,PINT,PINT,LONGV,PLONG)
FCALLSCFUN8(INT, HE5_SWidtype, HE5_SWIDTYPEF, he5_swidtype, INT,STRING,STRING,INT,PINT,PINT,PINT,PLONG)
FCALLSCFUN5(INT, HE5_SWaliasinfoF, HE5_SWALIASINFO, he5_swaliasinfo, INT, INT, STRING, PINT, STRING)
FCALLSCFUN3(LONG, HE5_SWinqdfldaliasF, HE5_SWINQDFLDALIAS, he5_swinqdfldalias,INT,PSTRING,PLONG)
FCALLSCFUN3(LONG, HE5_SWinqgfldaliasF, HE5_SWINQGFLDALIAS, he5_swinqgfldalias,INT,PSTRING,PLONG)
FCALLSCFUN4(INT, HE5_SWchunkinfoF, HE5_SWCHUNKINFO, he5_swchunkinfo,INT,STRING,PINT,LONGV)
FCALLSCFUN4(LONG, HE5_SWgetaliaslistF, HE5_SWGETALIASLIST, he5_swgetaliaslist,INT,INT,PSTRING,PLONG)


/* Subsetting routines */

FCALLSCFUN4(INT, HE5_SWdefboxreg, HE5_SWDEFBOXREG, he5_swdefboxreg, INT, DOUBLEV, DOUBLEV, INT)
FCALLSCFUN4(INT, HE5_SWdefvrtreg, HE5_SWDEFVRTREG, he5_swdefvrtreg,INT,INT,STRING,DOUBLEV)
FCALLSCFUN5(INT, HE5_SWextreg, HE5_SWEXTREG, he5_swextreg, INT, INT, STRING, INT, PVOID)
FCALLSCFUN4(INT, HE5_SWdeftmeper, HE5_SWDEFTMEPER, he5_swdeftmeper,INT,DOUBLE,DOUBLE,INT)
FCALLSCFUN1(INT, HE5_SWdupreg, HE5_SWDUPREG, he5_swdupreg, INT)
FCALLSCFUN2(INT, HE5_SWupscene, HE5_SWUPSCENE, he5_swupscene,INT, INT)
FCALLSCFUN6(INT, HE5_SWregidx, HE5_SWREGIDX, he5_swregidx,INT,DOUBLEV,DOUBLEV,INT,PSTRING,LONGV)
FCALLSCFUN5(INT, HE5_SWextper, HE5_SWEXTPER, he5_swextper,INT,INT,STRING,INT,PVOID)
FCALLSCFUN5(INT, HE5_SWindexinfoF, HE5_SWINDEXINFOF, he5_swindexinfof,INT,STRING,PINT,PSTRING,PLONG)


/* PROFILE INTERFACE */

FCALLSCFUN5(INT, HE5_PRdefineF, HE5_PRDEFINE, he5_prdefine, INT, STRING, STRING, STRING, INT)
FCALLSCFUN8(INT, HE5_PRwriteF, HE5_PRWRITE, he5_prwrite, INT, STRING, LONGV, LONGV, LONGV, LONG, LONGV, PVOID)
FCALLSCFUN7(INT, HE5_PRreadF, HE5_PRREAD, he5_prread, INT, STRING, LONGV, LONGV, LONGV, LONGV, PVOID)
FCALLSCFUN4(LONG, HE5_PRinquireF, HE5_PRINQIRE, he5_prinquire, INT, STRING, PINT, PINT)
FCALLSCFUN8(INT, HE5_PRinfoF, HE5_PRINFO, he5_prinfo,INT,STRING,PINT,LONGV,LONGV,PINT,PSTRING,PSTRING)
FCALLSCFUN5(INT, HE5_PRwrgattrF, HE5_PRWRGATTR, he5_prwrgattr, INT, STRING, INT, LONGV,PVOID)
FCALLSCFUN3(INT, HE5_PRrdgattrF, HE5_PRRDGATTR, he5_prrdgattr,INT,STRING,PVOID)
FCALLSCFUN4(INT, HE5_PRgattrinfoF, HE5_PRGATTRINFO, he5_prgattrinfo, INT, STRING, PINT, PLONG)
FCALLSCFUN5(INT, HE5_PRgattrinfoF2, HE5_PRGATTRINFO2, he5_prgattrinfo2, INT, STRING, PINT, PLONG, PLONG)
FCALLSCFUN3(LONG, HE5_PRinqgattrsF, HE5_PRINQGATTRS, he5_prinqgattrs,INT,PSTRING,PLONG)

FCALLSCFUN5(INT, HE5_SWdefdimscaleF, HE5_SWDEFDIMSCALE, he5_swdefdimscale,INT,STRING,LONG,INT,PVOID)
FCALLSCFUN6(INT, HE5_SWdefdimscale2F, HE5_SWDEFDIMSCALE2, he5_swdefdimscale2,INT,STRING,STRING,LONG,INT,PVOID)
FCALLSCFUN6(INT, HE5_SWsetdimscaleF, HE5_SWSETDIMSCALE, he5_swsetdimscale,INT,STRING,STRING,LONG,INT,PVOID)
FCALLSCFUN7(INT, HE5_SWsetdimscale2F, HE5_SWSETDIMSCALE2, he5_swsetdimscale2,INT,STRING,STRING,STRING,LONG,INT,PVOID)
FCALLSCFUN6(LONG, HE5_SWgetdimscaleF, HE5_SWGETDIMSCALE, he5_swgetdimscale,INT,STRING,STRING,PLONG,PINT,PVOID)
FCALLSCFUN4(INT, HE5_SWreaddscaleattrF,HE5_SWREADDSCALEATTR, he5_swreaddscaleattr,INT,STRING,STRING,PVOID)
FCALLSCFUN6(INT, HE5_SWwritedscaleattrF, HE5_SWWRITEDSCALEATTR, he5_swwritedscaleattr,INT,STRING,STRING,INT,LONGV,PVOID)
FCALLSCFUN5(INT, HE5_SWdscaleattrinfoF, HE5_SWDSCALEATTRINFO, he5_swdscaleattrinfo,INT,STRING,STRING,PINT,PLONG)
FCALLSCFUN6(INT, HE5_SWdscaleattrinfoF2, HE5_SWDSCALEATTRINFO2, he5_swdscaleattrinfo2,INT,STRING,STRING,PINT,PLONG,PLONG)
FCALLSCFUN4(INT, HE5_SWinqdscaleattrsF, HE5_SWINQDSCALATTRS, he5_swinqdscaleattrs,INT,STRING,STRING,PLONG)

/* EXTERNAL DATA FILE INTERFACE */

FCALLSCFUN4(INT, HE5_SWsetextdataF, HE5_SWSETXDAT, he5_swsetxdat,INT,STRING,LONGV,LONGV)
FCALLSCFUN6(INT, HE5_SWgetextdataF, HE5_SWGETXDAT, he5_swgetxdat,INT,STRING,LONG,PSTRING,LONGV,LONGV)

#endif







