コード例 #1
0
ファイル: hash.c プロジェクト: vocho/qnxpkgsrcmirror
/* ARGSUSED */
DB *
__hash_open(const char *file, int flags, mode_t mode, const HASHINFO *info,
    int dflags)
{
	HTAB *hashp;
	struct stat statbuf;
	DB *dbp;
	int bpages, new_table, nsegs, save_errno;
	ssize_t hdrsize;

	if ((flags & O_ACCMODE) == O_WRONLY) {
		errno = EINVAL;
		return (NULL);
	}

	if (!(hashp = calloc(1, sizeof(HTAB))))
		return (NULL);
	hashp->fp = -1;

	/*
	 * Even if user wants write only, we need to be able to read
	 * the actual file, so we need to open it read/write. But, the
	 * field in the hashp structure needs to be accurate so that
	 * we can check accesses.
	 */
	hashp->flags = flags;

	new_table = 0;
	if (!file || (flags & O_TRUNC) ||
	    (stat(file, &statbuf) && (errno == ENOENT))) {
		if (errno == ENOENT)
			errno = 0; /* Just in case someone looks at errno */
		new_table = 1;
	}
	if (file) {
		if ((hashp->fp = open(file, flags, mode)) == -1)
			RETURN_ERROR(errno, error0);
		if (fcntl(hashp->fp, F_SETFD, FD_CLOEXEC) == -1)
			RETURN_ERROR(errno, error1);
		if (fstat(hashp->fp, &statbuf) == -1)
			RETURN_ERROR(errno, error1);
		new_table |= statbuf.st_size == 0;
	}
	if (new_table) {
		if (!(hashp = init_hash(hashp, file, info)))
			RETURN_ERROR(errno, error1);
	} else {
		/* Table already exists */
		if (info && info->hash)
			hashp->hash = info->hash;
		else
			hashp->hash = __default_hash;

		hdrsize = read(hashp->fp, &hashp->hdr, sizeof(HASHHDR));
#if BYTE_ORDER == LITTLE_ENDIAN
		swap_header(hashp);
#endif
		if (hdrsize == -1)
			RETURN_ERROR(errno, error1);
		if (hdrsize != sizeof(HASHHDR))
			RETURN_ERROR(EFTYPE, error1);
		/* Verify file type, versions and hash function */
		if (hashp->MAGIC != HASHMAGIC)
			RETURN_ERROR(EFTYPE, error1);
#define	OLDHASHVERSION	1
		if (hashp->VERSION != HASHVERSION &&
		    hashp->VERSION != OLDHASHVERSION)
			RETURN_ERROR(EFTYPE, error1);
		if (hashp->hash(CHARKEY, sizeof(CHARKEY)) != hashp->H_CHARKEY)
			RETURN_ERROR(EFTYPE, error1);
		/*
		 * Figure out how many segments we need.  Max_Bucket is the
		 * maximum bucket number, so the number of buckets is
		 * max_bucket + 1.
		 */
		nsegs = (hashp->MAX_BUCKET + 1 + hashp->SGSIZE - 1) /
			 hashp->SGSIZE;
		hashp->nsegs = 0;
		if (alloc_segs(hashp, nsegs))
			/*
			 * If alloc_segs fails, table will have been destroyed
			 * and errno will have been set.
			 */
			return (NULL);
		/* Read in bitmaps */
		bpages = (hashp->SPARES[hashp->OVFL_POINT] +
		    (unsigned int)(hashp->BSIZE << BYTE_SHIFT) - 1) >>
		    (hashp->BSHIFT + BYTE_SHIFT);

		hashp->nmaps = bpages;
		(void)memset(&hashp->mapp[0], 0, bpages * sizeof(uint32_t *));
	}

	/* Initialize Buffer Manager */
	if (info && info->cachesize)
		__buf_init(hashp, info->cachesize);
	else
		__buf_init(hashp, DEF_BUFSIZE);

	hashp->new_file = new_table;
	hashp->save_file = file && (hashp->flags & O_RDWR);
	hashp->cbucket = -1;
	if (!(dbp = malloc(sizeof(DB)))) {
		save_errno = errno;
		hdestroy(hashp);
		errno = save_errno;
		return (NULL);
	}
	dbp->internal = hashp;
	dbp->close = hash_close;
	dbp->del = hash_delete;
	dbp->fd = hash_fd;
	dbp->get = hash_get;
	dbp->put = hash_put;
	dbp->seq = hash_seq;
	dbp->sync = hash_sync;
	dbp->type = DB_HASH;

#ifdef DEBUG
	(void)fprintf(stderr,
"%s\n%s%p\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%x\n%s%x\n%s%d\n%s%d\n",
	    "init_htab:",
	    "TABLE POINTER   ", hashp,
	    "BUCKET SIZE     ", hashp->BSIZE,
	    "BUCKET SHIFT    ", hashp->BSHIFT,
	    "DIRECTORY SIZE  ", hashp->DSIZE,
	    "SEGMENT SIZE    ", hashp->SGSIZE,
	    "SEGMENT SHIFT   ", hashp->SSHIFT,
	    "FILL FACTOR     ", hashp->FFACTOR,
	    "MAX BUCKET      ", hashp->MAX_BUCKET,
	    "OVFL POINT	     ", hashp->OVFL_POINT,
	    "LAST FREED      ", hashp->LAST_FREED,
	    "HIGH MASK       ", hashp->HIGH_MASK,
	    "LOW  MASK       ", hashp->LOW_MASK,
	    "NSEGS           ", hashp->nsegs,
	    "NKEYS           ", hashp->NKEYS);
#endif
#ifdef HASH_STATISTICS
	hash_overflows = hash_accesses = hash_collisions = hash_expansions = 0;
#endif
	return (dbp);

error1:
	if (hashp != NULL)
		(void)close(hashp->fp);

error0:
	free(hashp);
	errno = save_errno;
	return (NULL);
}
コード例 #2
0
static jdwpTransportError JNICALL
socketTransport_attach(jdwpTransportEnv* env, const char* addressString, jlong attachTimeout,
		       jlong handshakeTimeout)
{
    struct sockaddr_in sa;
    int err;

    if (addressString == NULL || addressString[0] == '\0') {
	RETURN_ERROR(JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT, "address is missing");
    }
     
    err = parseAddress(addressString, &sa, 0x7f000001);
    if (err != JDWPTRANSPORT_ERROR_NONE) {
        return err;
    }

    socketFD = dbgsysSocket(AF_INET, SOCK_STREAM, 0);
    if (socketFD < 0) {
	RETURN_IO_ERROR("unable to create socket");
    }

    err = setOptions(socketFD);
    if (err) {
        return err;
    }

    /* 
     * To do a timed connect we make the socket non-blocking
     * and poll with a timeout;
     */
    if (attachTimeout > 0) {
        dbgsysConfigureBlocking(socketFD, JNI_FALSE);
    }

    err = dbgsysConnect(socketFD, (struct sockaddr *)&sa, sizeof(sa));
    if (err == DBG_EINPROGRESS && attachTimeout > 0) {
	err = dbgsysFinishConnect(socketFD, (long)attachTimeout);

	if (err == DBG_ETIMEOUT) {
	    dbgsysConfigureBlocking(socketFD, JNI_TRUE);
	    RETURN_ERROR(JDWPTRANSPORT_ERROR_TIMEOUT, "connect timed out");
	}
    }

    if (err < 0) {
	RETURN_IO_ERROR("connect failed");
    }

    if (attachTimeout > 0) {
	dbgsysConfigureBlocking(socketFD, JNI_TRUE); 
    }

    err = handshake(socketFD, handshakeTimeout);
    if (err) {
	dbgsysSocketClose(socketFD);
	socketFD = -1;
 	return err;
    }

    return JDWPTRANSPORT_ERROR_NONE;
}
コード例 #3
0
ファイル: PackageFile.cpp プロジェクト: luciang/haiku
	virtual status_t WriteData(const void* buffer, size_t size)
	{
		RETURN_ERROR(write_to_io_request(fRequest, buffer, size));
	}
コード例 #4
0
ファイル: fm_sp.c プロジェクト: 2trill2spill/freebsd
t_Error FM_VSP_Init(t_Handle h_FmVsp)
{

    t_FmVspEntry                *p_FmVspEntry = (t_FmVspEntry *)h_FmVsp;
    struct fm_storage_profile_params   fm_vsp_params;
    uint8_t                     orderedArray[FM_PORT_MAX_NUM_OF_EXT_POOLS];
    uint16_t                    sizesArray[BM_MAX_NUM_OF_POOLS];
    t_Error                     err;
    uint16_t                    absoluteProfileId = 0;
    int                         i = 0;

    SANITY_CHECK_RETURN_ERROR(p_FmVspEntry, E_INVALID_HANDLE);
    SANITY_CHECK_RETURN_ERROR(p_FmVspEntry->p_FmVspEntryDriverParams,E_INVALID_HANDLE);

    CHECK_INIT_PARAMETERS(p_FmVspEntry, CheckParams);

    memset(&orderedArray, 0, sizeof(uint8_t) * FM_PORT_MAX_NUM_OF_EXT_POOLS);
    memset(&sizesArray, 0, sizeof(uint16_t) * BM_MAX_NUM_OF_POOLS);

    err = FmSpBuildBufferStructure(&p_FmVspEntry->intContext,
                                   &p_FmVspEntry->p_FmVspEntryDriverParams->bufferPrefixContent,
                                   &p_FmVspEntry->bufMargins,
                                   &p_FmVspEntry->bufferOffsets,
                                   &p_FmVspEntry->internalBufferOffset);
    if (err != E_OK)
        RETURN_ERROR(MAJOR, err, NO_MSG);


    err = CheckParamsGeneratedInternally(p_FmVspEntry);
    if (err != E_OK)
        RETURN_ERROR(MAJOR, err, NO_MSG);


     p_FmVspEntry->p_FmSpRegsBase =
        (struct fm_pcd_storage_profile_regs *)FmGetVSPBaseAddr(p_FmVspEntry->h_Fm);
    if (!p_FmVspEntry->p_FmSpRegsBase)
        RETURN_ERROR(MAJOR, E_INVALID_VALUE, ("impossible to initialize SpRegsBase"));

    /* order external buffer pools in ascending order of buffer pools sizes */
    FmSpSetBufPoolsInAscOrderOfBufSizes(&(p_FmVspEntry->p_FmVspEntryDriverParams)->extBufPools,
                                        orderedArray,
                                        sizesArray);

    p_FmVspEntry->extBufPools.numOfPoolsUsed =
        p_FmVspEntry->p_FmVspEntryDriverParams->extBufPools.numOfPoolsUsed;
    for (i = 0; i < p_FmVspEntry->extBufPools.numOfPoolsUsed; i++)
    {
       p_FmVspEntry->extBufPools.extBufPool[i].id = orderedArray[i];
       p_FmVspEntry->extBufPools.extBufPool[i].size = sizesArray[orderedArray[i]];
    }

    /* on user responsibility to fill it according requirement */
    memset(&fm_vsp_params, 0, sizeof(struct fm_storage_profile_params));
    fm_vsp_params.dma_swap_data              = p_FmVspEntry->p_FmVspEntryDriverParams->dmaSwapData;
    fm_vsp_params.int_context_cache_attr     = p_FmVspEntry->p_FmVspEntryDriverParams->dmaIntContextCacheAttr;
    fm_vsp_params.header_cache_attr          = p_FmVspEntry->p_FmVspEntryDriverParams->dmaHeaderCacheAttr;
    fm_vsp_params.scatter_gather_cache_attr  = p_FmVspEntry->p_FmVspEntryDriverParams->dmaScatterGatherCacheAttr;
    fm_vsp_params.dma_write_optimize         = p_FmVspEntry->p_FmVspEntryDriverParams->dmaWriteOptimize;
    fm_vsp_params.liodn_offset               = p_FmVspEntry->p_FmVspEntryDriverParams->liodnOffset;
    fm_vsp_params.no_scather_gather          = p_FmVspEntry->p_FmVspEntryDriverParams->noScatherGather;

    if (p_FmVspEntry->p_FmVspEntryDriverParams->p_BufPoolDepletion)
    {
        fm_vsp_params.buf_pool_depletion.buf_pool_depletion_enabled = TRUE;
        fm_vsp_params.buf_pool_depletion.pools_grp_mode_enable = p_FmVspEntry->p_FmVspEntryDriverParams->p_BufPoolDepletion->poolsGrpModeEnable;
        fm_vsp_params.buf_pool_depletion.num_pools = p_FmVspEntry->p_FmVspEntryDriverParams->p_BufPoolDepletion->numOfPools;
        fm_vsp_params.buf_pool_depletion.pools_to_consider = p_FmVspEntry->p_FmVspEntryDriverParams->p_BufPoolDepletion->poolsToConsider;
        fm_vsp_params.buf_pool_depletion.single_pool_mode_enable = p_FmVspEntry->p_FmVspEntryDriverParams->p_BufPoolDepletion->singlePoolModeEnable;
        fm_vsp_params.buf_pool_depletion.pools_to_consider_for_single_mode = p_FmVspEntry->p_FmVspEntryDriverParams->p_BufPoolDepletion->poolsToConsiderForSingleMode;
        fm_vsp_params.buf_pool_depletion.has_pfc_priorities = TRUE;
        fm_vsp_params.buf_pool_depletion.pfc_priorities_en = p_FmVspEntry->p_FmVspEntryDriverParams->p_BufPoolDepletion->pfcPrioritiesEn;
    }
    else
        fm_vsp_params.buf_pool_depletion.buf_pool_depletion_enabled = FALSE;
 
    if (p_FmVspEntry->p_FmVspEntryDriverParams->p_BackupBmPools)
    {
        fm_vsp_params.backup_pools.num_backup_pools = p_FmVspEntry->p_FmVspEntryDriverParams->p_BackupBmPools->numOfBackupPools;
        fm_vsp_params.backup_pools.pool_ids = p_FmVspEntry->p_FmVspEntryDriverParams->p_BackupBmPools->poolIds;
    }
    else
        fm_vsp_params.backup_pools.num_backup_pools = 0;

    fm_vsp_params.fm_ext_pools.num_pools_used = p_FmVspEntry->extBufPools.numOfPoolsUsed;
    fm_vsp_params.fm_ext_pools.ext_buf_pool = (struct fman_ext_pool_params*)&p_FmVspEntry->extBufPools.extBufPool;
    fm_vsp_params.buf_margins = (struct fman_sp_buf_margins*)&p_FmVspEntry->bufMargins;
    fm_vsp_params.int_context = (struct fman_sp_int_context_data_copy*)&p_FmVspEntry->intContext;

    /* no check on err - it was checked earlier */
    FmVSPGetAbsoluteProfileId(p_FmVspEntry->h_Fm,
                              p_FmVspEntry->portType,
                              p_FmVspEntry->portId,
                              p_FmVspEntry->relativeProfileId,
                              &absoluteProfileId);

    ASSERT_COND(p_FmVspEntry->p_FmSpRegsBase);
    ASSERT_COND(fm_vsp_params.int_context);
    ASSERT_COND(fm_vsp_params.buf_margins);
    ASSERT_COND((absoluteProfileId <= FM_VSP_MAX_NUM_OF_ENTRIES));

    /* Set all registers related to VSP */
    fman_vsp_init(p_FmVspEntry->p_FmSpRegsBase, absoluteProfileId, &fm_vsp_params,FM_PORT_MAX_NUM_OF_EXT_POOLS, BM_MAX_NUM_OF_POOLS, FM_MAX_NUM_OF_PFC_PRIORITIES);

    p_FmVspEntry->absoluteSpId = absoluteProfileId;

    if (p_FmVspEntry->p_FmVspEntryDriverParams)
        XX_Free(p_FmVspEntry->p_FmVspEntryDriverParams);
    p_FmVspEntry->p_FmVspEntryDriverParams = NULL;

    return E_OK;
}
コード例 #5
0
ファイル: myhdf.c プロジェクト: Jwely/ledaps
bool PutAttrDouble(int32 sds_id, Myhdf_attr_t *attr, double *val)
/* 
!C******************************************************************************

!Description: 'PutAttrDouble' writes an attribute from a parameter of type
 'double' to a HDF file.
 
!Input Parameters:
 sds_id         SDS id
 attr           Attribute data structure; the following fields are used:
                   name, type, nval

!Output Parameters:
 val            An array of values from the HDF attribute (converted from
                  type 'double' to the native type
 (returns)      Status:
                  'true' = okay
		      'false' = error writing the attribute information

!Team Unique Header:

 ! Design Notes:
   1. The values in the attribute are converted from the stored type to 
      'double' type.
   2. The HDF file is assumed to be open for SD (Science Data) access.
   3. If the attribute has more than 'MYHDF_MAX_NATTR_VAL' values, an error
      status is returned.
   4. Error messages are handled with the 'RETURN_ERROR' macro.
!END****************************************************************************
*/
{
  char8 val_char8[MYHDF_MAX_NATTR_VAL];
  int8 val_int8[MYHDF_MAX_NATTR_VAL];
  uint8 val_uint8[MYHDF_MAX_NATTR_VAL];
  int16 val_int16[MYHDF_MAX_NATTR_VAL];
  uint16 val_uint16[MYHDF_MAX_NATTR_VAL];
  int32 val_int32[MYHDF_MAX_NATTR_VAL];
  uint32 val_uint32[MYHDF_MAX_NATTR_VAL];
  float32 val_float32[MYHDF_MAX_NATTR_VAL];
  float64 val_float64[MYHDF_MAX_NATTR_VAL];
  int i;
  void *buf;

  if (attr->nval <= 0  ||  attr->nval > MYHDF_MAX_NATTR_VAL) 
    RETURN_ERROR("invalid number of values", "PutAttrDouble", false);

  switch (attr->type) {
    case DFNT_CHAR8:
      for (i = 0; i < attr->nval; i++) {
        if (     val[i] >= ((double)MYHDF_CHAR8H)) val_char8[i] = MYHDF_CHAR8H;
        else if (val[i] <= ((double)MYHDF_CHAR8L)) val_char8[i] = MYHDF_CHAR8L;
        else if (val[i] >= 0.0) val_char8[i] = (char8)(val[i] + 0.5);
        else                    val_char8[i] = -((char8)(-val[i] + 0.5));
      }
      buf = (void *)val_char8;
      break;

    case DFNT_INT8:
      for (i = 0; i < attr->nval; i++) {
        if (     val[i] >= ((double)MYHDF_INT8H)) val_int8[i] = MYHDF_INT8H;
        else if (val[i] <= ((double)MYHDF_INT8L)) val_int8[i] = MYHDF_INT8L;
        else if (val[i] >= 0.0) val_int8[i] =   (int8)( val[i] + 0.5);
        else                    val_int8[i] = -((int8)(-val[i] + 0.5));
      }
      buf = (void *)val_int8;
      break;

    case DFNT_UINT8:
      for (i = 0; i < attr->nval; i++) {
        if (     val[i] >= ((double)MYHDF_UINT8H)) val_uint8[i] = MYHDF_UINT8H;
        else if (val[i] <= ((double)MYHDF_UINT8L)) val_uint8[i] = MYHDF_UINT8L;
        else if (val[i] >= 0.0) val_uint8[i] =   (uint8)( val[i] + 0.5);
        else                    val_uint8[i] = -((uint8)(-val[i] + 0.5));
      }
      buf = (void *)val_uint8;
      break;

    case DFNT_INT16:
      for (i = 0; i < attr->nval; i++) {
        if (     val[i] >= ((double)MYHDF_INT16H)) val_int16[i] = MYHDF_INT16H;
        else if (val[i] <= ((double)MYHDF_INT16L)) val_int16[i] = MYHDF_INT16L;
        else if (val[i] >= 0.0) val_int16[i] =   (int16)( val[i] + 0.5);
        else                    val_int16[i] = -((int16)(-val[i] + 0.5));
      }
      buf = (void *)val_int16;
      break;

    case DFNT_UINT16:
      for (i = 0; i < attr->nval; i++) {
        if (     val[i] >= ((double)MYHDF_UINT16H)) val_uint16[i] = MYHDF_UINT16H;
        else if (val[i] <= ((double)MYHDF_UINT16L)) val_uint16[i] = MYHDF_UINT16L;
        else if (val[i] >= 0.0) val_uint16[i] =   (uint16)( val[i] + 0.5);
        else                    val_uint16[i] = -((uint16)(-val[i] + 0.5));
      }
      buf = (void *)val_uint16;
      break;

    case DFNT_INT32:
      for (i = 0; i < attr->nval; i++) {
        if (     val[i] >= ((double)MYHDF_INT32H)) val_int32[i] = MYHDF_INT32H;
        else if (val[i] <= ((double)MYHDF_INT32L)) val_int32[i] = MYHDF_INT32L;
        else if (val[i] >= 0.0) val_int32[i] =   (int32)( val[i] + 0.5);
        else                    val_int32[i] = -((int32)(-val[i] + 0.5));
      }
      buf = (void *)val_int32;
      break;

    case DFNT_UINT32:
      for (i = 0; i < attr->nval; i++) {
        if (     val[i] >= ((double)MYHDF_UINT32H)) val_uint32[i] = MYHDF_UINT32H;
        else if (val[i] <= ((double)MYHDF_UINT32L)) val_uint32[i] = MYHDF_UINT32L;
        else if (val[i] >= 0.0) val_uint32[i] =   (uint32)( val[i] + 0.5);
        else                    val_uint32[i] = -((uint32)(-val[i] + 0.5));
      }
      buf = (void *)val_uint32;
      break;

    case DFNT_FLOAT32:
      for (i = 0; i < attr->nval; i++) {
        if (     val[i] >=  ((double)MYHDF_FLOAT32H)) val_float32[i] =  MYHDF_FLOAT32H;
        else if (val[i] <= -((double)MYHDF_FLOAT32H)) val_float32[i] = -MYHDF_FLOAT32H;
        else val_float32[i] = (float32)val[i];
      }
      buf = (void *)val_float32;
      break;

    case DFNT_FLOAT64:
      if (sizeof(float64) == sizeof(double))
        buf = (void *)val;
      else {
        for (i = 0; i < attr->nval; i++)
          val_float64[i] = val[i];
        buf = (void *)val_float64;
      }
      break;

    default: 
      RETURN_ERROR("unimplmented type", "PutAttrDouble", false);
  }

  if (SDsetattr(sds_id, attr->name, attr->type, attr->nval, buf) == HDF_ERROR)
    RETURN_ERROR("setting attribute", "PutAttrDouble", false);

  return true;
}
コード例 #6
0
int read_envi_header
(
    char *data_type,       /* I: input data type        */
    char *scene_name,      /* I: scene name             */
    Input_meta_t *meta     /* O: saved header file info */
)
{
    char  buffer[MAX_STR_LEN] = "\0"; /* for retrieving fields        */
    char  *label = NULL;              /* for retrieving string tokens */
    char  *tokenptr = NULL;           /* for retrieving string tokens */
    char  *tokenptr2 = NULL;          /* for retrieving string tokens */
    char  *seperator = "=";           /* for retrieving string tokens */
    char  *seperator2 = ",";          /* for retrieving string tokens */
    FILE *in;                         /* file ptr to input hdr file   */
    int ib;                           /* loop index                   */
    char map_info[10][MAX_STR_LEN];   /* projection information fields*/
    char FUNC_NAME[] = "read_envi_header"; /* function name           */
    char filename[MAX_STR_LEN];       /* scene name                   */
    int len;                          /* for strlen                   */
    char short_scene[MAX_STR_LEN];    /* char string for text manipulation */
    char directory[MAX_STR_LEN];      /* for constucting path/file names */
    char tmpstr[MAX_STR_LEN];         /* char string for text manipulation */
    char scene_list_name[MAX_STR_LEN];/* char string for text manipulation */
    int landsat_number;               /* mission number defines file name */


    /******************************************************************/
    /*                                                                */
    /* Determine the file name.                                       */
    /*                                                                */
    /******************************************************************/

    if (strcmp(data_type, "tifs") == 0)
    {
        len = strlen(scene_name);
        landsat_number = atoi(sub_string(scene_name,(len-19),1));
        if (landsat_number == 8)
            sprintf(filename, "%s_sr_band2.hdr", scene_name);
        else
            sprintf(filename, "%s_sr_band1.hdr", scene_name);
    }
    else if (strcmp(data_type, "bip") == 0)
    {
        len = strlen(scene_name);
        strncpy(short_scene, scene_name, len-5);
        split_directory_scenename(scene_name, directory, scene_list_name);
        if (strncmp(short_scene, ".", 1) == 0)
        {
            strncpy(tmpstr, short_scene + 2, len - 2);
            sprintf(filename, "%s/%s_MTLstack.hdr", tmpstr, scene_list_name);
        }
        else
            sprintf(filename, "%s/%s_MTLstack.hdr", short_scene, scene_list_name);
    }

    in=fopen(filename, "r");
    if (in == NULL)
    {
        RETURN_ERROR ("opening header file", FUNC_NAME, FAILURE);
    }

    /* process line by line */
    while(fgets(buffer, MAX_STR_LEN, in) != NULL) 
    {

        char *s;
        s = strchr(buffer, '=');
        if (s != NULL)
        {
            /* get string token */
            tokenptr = strtok(buffer, seperator);
            label=trimwhitespace(tokenptr);

            if (strcmp(label,"lines") == 0)
            {
                tokenptr = trimwhitespace(strtok(NULL, seperator));
                meta->lines = atoi(tokenptr);
            }

            if (strcmp(label,"data type") == 0)
            {
                tokenptr = trimwhitespace(strtok(NULL, seperator));
                meta->data_type = atoi(tokenptr);
            }

            if (strcmp(label,"byte order") == 0)
            {
                tokenptr = trimwhitespace(strtok(NULL, seperator));
                meta->byte_order = atoi(tokenptr);
            }

            if (strcmp(label,"samples") == 0)
            {
                tokenptr = trimwhitespace(strtok(NULL, seperator));
                meta->samples = atoi(tokenptr);
            }

            if (strcmp(label,"interleave") == 0)
            {
                tokenptr = trimwhitespace(strtok(NULL, seperator));
                strcpy(meta->interleave, tokenptr);
            }

            if (strcmp(label,"UPPER_LEFT_CORNER") == 0)
            {
                tokenptr = trimwhitespace(strtok(NULL, seperator));
            }

            if (strcmp(label,"map info") == 0)
            {
                tokenptr = trimwhitespace(strtok(NULL, seperator));
            }

            if (strcmp(label,"map info") == 0)
            {
                tokenptr2 = strtok(tokenptr, seperator2);
                ib = 0;
                while(tokenptr2 != NULL)
                {
                    strcpy(map_info[ib], tokenptr2);
                    if (ib == 3)
                        meta->upper_left_x = atoi(map_info[ib]);
                    if (ib == 4)
                        meta->upper_left_y = atoi(map_info[ib]);
                    if (ib == 5)
                        meta->pixel_size = atoi(map_info[ib]);
                    if(ib == 7)
                        meta->utm_zone = atoi(map_info[ib]);
                    tokenptr2 = strtok(NULL, seperator2);
                    ib++;
                }
            }
        }
    }
    fclose(in);

    return (SUCCESS);
}
コード例 #7
0
ファイル: fm_sp.c プロジェクト: 2trill2spill/freebsd
t_Error FmSpCheckBufPoolsParams(t_FmExtPools            *p_FmExtPools,
                                t_FmBackupBmPools       *p_FmBackupBmPools,
                                t_FmBufPoolDepletion    *p_FmBufPoolDepletion)
{

    int         i = 0, j = 0;
    bool        found;
    uint8_t     count = 0;

    if (p_FmExtPools)
    {
        if (p_FmExtPools->numOfPoolsUsed > FM_PORT_MAX_NUM_OF_EXT_POOLS)
                RETURN_ERROR(MAJOR, E_INVALID_VALUE, ("numOfPoolsUsed can't be larger than %d", FM_PORT_MAX_NUM_OF_EXT_POOLS));

        for (i=0;i<p_FmExtPools->numOfPoolsUsed;i++)
        {
            if (p_FmExtPools->extBufPool[i].id >= BM_MAX_NUM_OF_POOLS)
                RETURN_ERROR(MAJOR, E_INVALID_VALUE, ("extBufPools.extBufPool[%d].id can't be larger than %d", i, BM_MAX_NUM_OF_POOLS));
            if (!p_FmExtPools->extBufPool[i].size)
                RETURN_ERROR(MAJOR, E_INVALID_VALUE, ("extBufPools.extBufPool[%d].size is 0", i));
        }
    }
    if (!p_FmExtPools && (p_FmBackupBmPools || p_FmBufPoolDepletion))
          RETURN_ERROR(MAJOR, E_INVALID_VALUE, ("backupBmPools ot bufPoolDepletion can not be defined without external pools"));

    /* backup BM pools indication is valid only for some chip derivatives
       (limited by the config routine) */
    if (p_FmBackupBmPools)
    {
        if (p_FmBackupBmPools->numOfBackupPools >= p_FmExtPools->numOfPoolsUsed)
            RETURN_ERROR(MAJOR, E_INVALID_VALUE, ("p_BackupBmPools must be smaller than extBufPools.numOfPoolsUsed"));
        found = FALSE;
        for (i = 0;i<p_FmBackupBmPools->numOfBackupPools;i++)
        {

            for (j=0;j<p_FmExtPools->numOfPoolsUsed;j++)
            {
                if (p_FmBackupBmPools->poolIds[i] == p_FmExtPools->extBufPool[j].id)
                {
                    found = TRUE;
                    break;
                }
            }
            if (!found)
                RETURN_ERROR(MAJOR, E_INVALID_VALUE, ("All p_BackupBmPools.poolIds must be included in extBufPools.extBufPool[n].id"));
            else
                found = FALSE;
        }
    }

    /* up to extBufPools.numOfPoolsUsed pools may be defined */
    if (p_FmBufPoolDepletion && p_FmBufPoolDepletion->poolsGrpModeEnable)
    {
        if ((p_FmBufPoolDepletion->numOfPools > p_FmExtPools->numOfPoolsUsed))
            RETURN_ERROR(MAJOR, E_INVALID_VALUE, ("bufPoolDepletion.numOfPools can't be larger than %d and can't be larger than numOfPoolsUsed", FM_PORT_MAX_NUM_OF_EXT_POOLS));

        if (!p_FmBufPoolDepletion->numOfPools)
          RETURN_ERROR(MAJOR, E_INVALID_VALUE, ("bufPoolDepletion.numOfPoolsToConsider can not be 0 when poolsGrpModeEnable=TRUE"));

        found = FALSE;
        count = 0;
        /* for each pool that is in poolsToConsider, check if it is defined
           in extBufPool */
        for (i=0;i<BM_MAX_NUM_OF_POOLS;i++)
        {
            if (p_FmBufPoolDepletion->poolsToConsider[i])
            {
                for (j=0;j<p_FmExtPools->numOfPoolsUsed;j++)
                 {
                    if (i == p_FmExtPools->extBufPool[j].id)
                    {
                        found = TRUE;
                        count++;
                        break;
                    }
                 }
                if (!found)
                    RETURN_ERROR(MAJOR, E_INVALID_STATE, ("Pools selected for depletion are not used."));
                else
                    found = FALSE;
            }
        }
        /* check that the number of pools that we have checked is equal to the number announced by the user */
        if (count != p_FmBufPoolDepletion->numOfPools)
            RETURN_ERROR(MAJOR, E_INVALID_VALUE, ("bufPoolDepletion.numOfPools is larger than the number of pools defined."));
    }

    if (p_FmBufPoolDepletion && p_FmBufPoolDepletion->singlePoolModeEnable)
    {
        /* calculate vector for number of pools depletion */
        found = FALSE;
        count = 0;
        for (i=0;i<BM_MAX_NUM_OF_POOLS;i++)
        {
            if (p_FmBufPoolDepletion->poolsToConsiderForSingleMode[i])
            {
                for (j=0;j<p_FmExtPools->numOfPoolsUsed;j++)
                {
                    if (i == p_FmExtPools->extBufPool[j].id)
                    {
                        found = TRUE;
                        count++;
                        break;
                    }
                }
                if (!found)
                    RETURN_ERROR(MAJOR, E_INVALID_STATE, ("Pools selected for depletion are not used."));
                else
                    found = FALSE;
            }
        }
        if (!count)
            RETURN_ERROR(MAJOR, E_INVALID_VALUE, ("No pools defined for single buffer mode pool depletion."));
    }

    return E_OK;
}
コード例 #8
0
ファイル: FspsWrapperPeim.c プロジェクト: agileinsider/edk2
/**
This function is called after PEI core discover memory and finish migration.

@param[in] PeiServices    Pointer to PEI Services Table.
@param[in] NotifyDesc     Pointer to the descriptor for the Notification event that
caused this function to execute.
@param[in] Ppi            Pointer to the PPI data associated with this function.

@retval EFI_STATUS        Always return EFI_SUCCESS
**/
EFI_STATUS
EFIAPI
PeiMemoryDiscoveredNotify (
  IN EFI_PEI_SERVICES          **PeiServices,
  IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDesc,
  IN VOID                      *Ppi
  )
{
  FSP_INFO_HEADER           *FspsHeaderPtr;
  UINT64                    TimeStampCounterStart;
  EFI_STATUS                Status;
  VOID                      *FspHobListPtr;
  EFI_HOB_GUID_TYPE         *GuidHob;
  FSPS_UPD_COMMON           *FspsUpdDataPtr;
  UINTN                     *SourceData;

  
  DEBUG ((DEBUG_INFO, "PeiMemoryDiscoveredNotify enter\n"));
  
  //
  // Copy default FSP-S UPD data from Flash
  //
  FspsHeaderPtr = (FSP_INFO_HEADER *)FspFindFspHeader (PcdGet32 (PcdFspsBaseAddress));
  FspsUpdDataPtr = (FSPS_UPD_COMMON *)AllocateZeroPool ((UINTN)FspsHeaderPtr->CfgRegionSize);
  ASSERT (FspsUpdDataPtr != NULL);
  SourceData = (UINTN *)((UINTN)FspsHeaderPtr->ImageBase + (UINTN)FspsHeaderPtr->CfgRegionOffset);
  CopyMem (FspsUpdDataPtr, SourceData, (UINTN)FspsHeaderPtr->CfgRegionSize);

  UpdateFspsUpdData ((VOID *)FspsUpdDataPtr);

  TimeStampCounterStart = AsmReadTsc ();
  PERF_START_EX(&gFspApiPerformanceGuid, "EventRec", NULL, 0, 0x9000);
  Status = CallFspSiliconInit ((VOID *)FspsUpdDataPtr);
  PERF_END_EX(&gFspApiPerformanceGuid, "EventRec", NULL, 0, 0x907F);
  DEBUG ((DEBUG_INFO, "Total time spent executing FspSiliconInitApi: %d millisecond\n", DivU64x32 (GetTimeInNanoSecond (AsmReadTsc () - TimeStampCounterStart), 1000000)));
  if (EFI_ERROR(Status)) {
    DEBUG ((DEBUG_ERROR, "ERROR - Failed to execute FspSiliconInitApi(), Status = %r\n", Status));
  }
  DEBUG((DEBUG_INFO, "FspSiliconInit status: 0x%x\n", Status));
  ASSERT_EFI_ERROR (Status);

  Status = TestFspSiliconInitApiOutput ((VOID *)NULL);
  if (RETURN_ERROR (Status)) {
    DEBUG ((DEBUG_ERROR, "ERROR - TestFspSiliconInitApiOutput () fail, Status = %r\n", Status));
  }

  //
  // Now FspHobList complete, process it
  //
  GuidHob = GetFirstGuidHob (&gFspHobGuid);
  ASSERT (GuidHob != NULL);
  FspHobListPtr = *(VOID **)GET_GUID_HOB_DATA (GuidHob);
  DEBUG ((DEBUG_INFO, "FspHobListPtr - 0x%x\n", FspHobListPtr));
  PostFspsHobProcess (FspHobListPtr);

  //
  // Install FspSiliconInitDonePpi so that any other driver can consume this info.
  //
  Status = PeiServicesInstallPpi (&mPeiFspSiliconInitDonePpi);
  ASSERT_EFI_ERROR(Status);

  return Status;
}
コード例 #9
0
ファイル: cJuryModule.cpp プロジェクト: acobus/OptiCar
tResult cJuryModule::OnDataUpdate(const tString& strName, const tVoid* pData, const tSize& szSize)
{
    // called from the connection lib on new data

    // check data size
    RETURN_IF_POINTER_NULL(pData);
    if (szSize <= 0)
    {
        RETURN_ERROR(ERR_INVALID_ARG);
    }

    // check the name of the data
    if (strName == CONLIB_IN_PORT_NAME_DRIVER_STRUCT)
    {     
        // data from driver
        const tDriverStruct* sDriverData = (const tDriverStruct*) pData;
        
        //update the gui
        emit SetDriverState(sDriverData->i8StateID, sDriverData->i16ManeuverEntry);


        //update the timeline
        if (m_i16LastDriverEntryId < sDriverData->i16ManeuverEntry || m_i16LastDriverEntryId == -1 || sDriverData->i8StateID == -1 || sDriverData->i8StateID == 2)
        {
            // set the first time manually
            if (m_oLastReceiveTimestamp.isNull())
            {
                m_oLastReceiveTimestamp = QTime::currentTime();
                m_i16LastDriverEntryId = sDriverData->i16ManeuverEntry;
            }

            // calc the time diff
            tTimeStamp timeDiff = (m_oLastReceiveTimestamp.msecsTo(QTime::currentTime()));  //time in milliseconds
            QString Message;
            switch (stateCar(sDriverData->i8StateID))
            {
            case stateCar_READY:
                Message = "from " + QString::number(m_i16LastDriverEntryId) + " to " + QString::number(sDriverData->i16ManeuverEntry) + ": " + QString::number(timeDiff) + " msec: Ready";
                break;
            case stateCar_RUNNING:
                Message = "from " + QString::number(m_i16LastDriverEntryId) + " to " + QString::number(sDriverData->i16ManeuverEntry) + ": " + QString::number(timeDiff) + " msec: OK";
                break;
            case stateCar_COMPLETE:
                Message = "from " + QString::number(m_i16LastDriverEntryId) + " to " + QString::number(sDriverData->i16ManeuverEntry) + ": " + QString::number(timeDiff) + " msec: Complete";
                break;
            case stateCar_ERROR:
                Message = "from " + QString::number(m_i16LastDriverEntryId) + " to " + QString::number(sDriverData->i16ManeuverEntry) + ": " + QString::number(timeDiff) + " msec: Error";
                break;
            case stateCar_STARTUP:
                break;
            }
            // set the last time
            m_oLastReceiveTimestamp = QTime::currentTime();             
            m_i16LastDriverEntryId = sDriverData->i16ManeuverEntry;
            //update the ui
            SetLogText(Message);
        }

    }
    else if (strName == CONLIB_IN_PORT_NAME_JURY_STRUCT_LOOPBACK)
    {
        // data from jury loopback
        const tJuryStruct* sJuryLoopbackData = (const tJuryStruct*) pData;

        QString strText = QString("Loopback Jury: Received jury struct loopback with action ");
        switch(juryActions(sJuryLoopbackData->i8ActionID))
        {
        case action_GETREADY:
            strText += "GETREADY ";
            break;
        case action_START:
            strText += "START ";
            break;
        case action_STOP:
            strText += "STOP ";
            break;
        default:
            strText += "UNKNOWN ";
            break;
        }

        strText += QString(" and maneuver ") + QString::number(sJuryLoopbackData->i16ManeuverEntry);

        // write text to log (just for checking the connection)
        SetLogText(strText);
        //QMetaObject::invokeMethod(this, "OnAppendText", Qt::AutoConnection, Q_ARG(QString, strText));
    }
    else if (strName == CONLIB_IN_PORT_NAME_EMERGENCY_STOP_LOOPBACK)
    {
        // data from emergency loopback
        const tJuryEmergencyStop* sJuryLoopbackData = (const tJuryEmergencyStop*) pData;

        QString strText = QString("Loopback Emergency: Received emergency loopback with "); 
        strText += (sJuryLoopbackData->bEmergencyStop == true) ? QString("true") : QString("false");
        
        // write text to log (just for checking the connection)
        SetLogText(strText);
        //QMetaObject::invokeMethod(this, "OnAppendText", Qt::AutoConnection, Q_ARG(QString, strText));
    }
    else if (strName == CONLIB_IN_PORT_NAME_MANEUVER_LIST)
    {
        // data from maneuverlist loopback
        const tInt32* i32DataSize = (const tInt32*) pData;
        const tChar* pcString = (const tChar*) ((tChar*)pData + sizeof(tInt32));
        tString strManeuver(pcString);
        QString strText = QString("Loopback ManeuverList received"); 

        // check the data content
        if(*i32DataSize != (m_strManeuverList.size() + sizeof(char)))
        {
            strText += QString(" size does not match"); 
        }
        if(strManeuver != m_strManeuverList)
        {
            strText += QString(" content does not match"); 
        }
        
        strText += "!!!";

        // write text to log (just for checking the connection)
        SetLogText(strText);
        //QMetaObject::invokeMethod(this, "OnAppendText", Qt::AutoConnection, Q_ARG(QString, strText));
    }
    RETURN_NOERROR;

}
コード例 #10
0
ファイル: misc.c プロジェクト: NGenetzky/espa-cloud-masking
/******************************************************************************
MODULE:  get_args

PURPOSE:  Gets the command-line arguments and validates that the required
arguments were specified.

RETURN VALUE:
Type = int
Value           Description
-----           -----------
FAILURE         Error getting the command-line arguments or a command-line
                argument and associated value were not specified
SUCCESS         No errors encountered

HISTORY:
Date        Programmer       Reason
--------    ---------------  -------------------------------------
1/2/2013    Gail Schmidt     Original Development
3/15/2013   Song Guo         Changed to support Fmask
9/13/2013   Song Guo         Changed to use RETURN_ERROR
2/19/2014   Gail Schmidt     Modified to utilize the ESPA internal raw binary
                             file format

NOTES:
  1. Memory is allocated for the input and output files.  All of these should
     be character pointers set to NULL on input.  The caller is responsible
     for freeing the allocated memory upon successful return.
******************************************************************************/
int get_args
(
    int argc,              /* I: number of cmd-line args */
    char *argv[],          /* I: string of cmd-line args */
    char **xml_infile,     /* O: address of input XML filename */
    float *cloud_prob,     /* O: cloud_probability input */
    int *cldpix,           /* O: cloud_pixel buffer used for image dilate */
    int *sdpix,            /* O: shadow_pixel buffer used for image dilate */
    int *max_cloud_pixels, /* O: Max cloud pixel number to divide cloud */
    bool * verbose         /* O: verbose flag */
)
{
    int c;                         /* current argument index */
    int option_index;              /* index for the command-line option */
    static int verbose_flag = 0;   /* verbose flag */
    static int cldpix_default = 3; /* Default buffer for cloud pixel dilate */
    static int sdpix_default = 3;  /* Default buffer for shadow pixel dilate */
    static int max_pixel_default = 0; /* Default maxium cloud pixel number for
                                         cloud division, 0 means no division */
    static float cloud_prob_default = 22.5; /* Default cloud probability */
    char errmsg[MAX_STR_LEN];               /* error message */
    char FUNC_NAME[] = "get_args";          /* function name */
    static struct option long_options[] = {
        {"verbose", no_argument, &verbose_flag, 1},
        {"xml", required_argument, 0, 'i'},
        {"prob", required_argument, 0, 'p'},
        {"cldpix", required_argument, 0, 'c'},
        {"sdpix", required_argument, 0, 's'},
        {"max_cloud_pixels", required_argument, 0, 'x'},
        {"help", no_argument, 0, 'h'},
        {0, 0, 0, 0}
    };

    /* Assign the default values */
    *cloud_prob = cloud_prob_default;
    *cldpix = cldpix_default;
    *sdpix = sdpix_default;
    *max_cloud_pixels = max_pixel_default;

    /* Loop through all the cmd-line options */
    opterr = 0; /* turn off getopt_long error msgs as we'll print our own */
    while (1)
    {
        /* optstring in call to getopt_long is empty since we will only
           support the long options */
        c = getopt_long (argc, argv, "", long_options, &option_index);
        if (c == -1)
        {
            /* Out of cmd-line options */
            break;
        }

        switch (c)
        {
        case 0:
            /* If this option set a flag, do nothing else now. */
            if (long_options[option_index].flag != 0)
                break;

        case 'h':              /* help */
            usage ();
            return FAILURE;
            break;

        case 'i':              /* xml infile */
            *xml_infile = strdup (optarg);
            break;

        case 'p':              /* cloud probability value */
            *cloud_prob = atof (optarg);
            break;

        case 'c':              /* cloud pixel value for image dilation */
            *cldpix = atoi (optarg);
            break;

        case 's':              /* snow pixel value for image dilation */
            *sdpix = atoi (optarg);
            break;

        case 'x':              /* maxium cloud pixel number for cloud division,
                                   0 means no division */
            *max_cloud_pixels = atoi (optarg);
            break;

        case '?':
        default:
            sprintf (errmsg, "Unknown option %s", argv[optind - 1]);
            usage ();
            RETURN_ERROR (errmsg, FUNC_NAME, FAILURE);
            break;
        }
    }

    /* Make sure the infile was specified */
    if (*xml_infile == NULL)
    {
        sprintf (errmsg, "XML input file is a required argument");
        usage ();
        RETURN_ERROR (errmsg, FUNC_NAME, FAILURE);
    }

    /* Make sure this is some positive value */
    if (*max_cloud_pixels < 0)
    {
        sprintf (errmsg, "max_cloud_pixels must be >= 0");
        RETURN_ERROR (errmsg, FUNC_NAME, FAILURE);
    }

    /* Check the verbose flag */
    if (verbose_flag)
        *verbose = true;
    else
        *verbose = false;

    if (*verbose)
    {
        printf ("XML_input_file = %s\n", *xml_infile);
        printf ("cloud_probability = %f\n", *cloud_prob);
        printf ("cloud_pixel_buffer = %d\n", *cldpix);
        printf ("shadow_pixel_buffer = %d\n", *sdpix);
        printf ("max_cloud_pixels = %d\n", *max_cloud_pixels);
    }

    return SUCCESS;
}
コード例 #11
0
/*****************************************************************************
MODULE:  potential_cloud_shadow_snow_mask

PURPOSE: Identify the cloud pixels, snow pixels, water pixels, clear land
         pixels, and potential shadow pixels

RETURN: SUCCESS
        FAILURE

HISTORY:
Date        Programmer       Reason
--------    ---------------  -------------------------------------
3/15/2013   Song Guo         Original Development

NOTES:
1. Thermal buffer is expected to be in degrees Celsius with a factor applied
   of 100.  Many values which compare to the thermal buffer in this code are
   hardcoded and assume degrees celsius * 100.
*****************************************************************************/
int potential_cloud_shadow_snow_mask
(
    Input_t * input,            /*I: input structure */
    float cloud_prob_threshold, /*I: cloud probability threshold */
    float *clear_ptm,           /*O: percent of clear-sky pixels */
    float *t_templ,             /*O: percentile of low background temp */
    float *t_temph,             /*O: percentile of high background temp */
    unsigned char *pixel_mask,  /*I/O: pixel mask */
    unsigned char *conf_mask,   /*I/O: confidence mask */
    bool verbose                /*I: value to indicate if intermediate
                                     messages should be printed */
)
{
    char errstr[MAX_STR_LEN];   /* error string */
    int nrows = input->size.l;  /* number of rows */
    int ncols = input->size.s;  /* number of columns */
    int ib = 0;                 /* band index */
    int row = 0;                /* row index */
    int col = 0;                /* column index */
    int image_data_counter = 0;        /* mask counter */
    int clear_pixel_counter = 0;       /* clear sky pixel counter */
    int clear_land_pixel_counter = 0;  /* clear land pixel counter */
    int clear_water_pixel_counter = 0; /* clear water pixel counter */
    float ndvi, ndsi;           /* NDVI and NDSI values */
    int16 *f_temp = NULL;       /* clear land temperature */
    int16 *f_wtemp = NULL;      /* clear water temperature */
    float visi_mean;            /* mean of visible bands */
    float whiteness = 0.0;      /* whiteness value */
    float hot;                  /* hot value for hot test */
    float land_ptm;             /* clear land pixel percentage */
    float water_ptm;            /* clear water pixel percentage */
    unsigned char land_bit;     /* Which clear bit to test all or just land */
    unsigned char water_bit;    /* Which clear bit to test all or just water */
    float l_pt;                 /* low percentile threshold */
    float h_pt;                 /* high percentile threshold */
    float t_wtemp;              /* high percentile water temperature */
    float *wfinal_prob = NULL;  /* final water pixel probabilty value */
    float *final_prob = NULL;   /* final land pixel probability value */
    float wtemp_prob;           /* water temperature probability value */
    int t_bright;               /* brightness test value for water */
    float brightness_prob;      /* brightness probability value */
    int t_buffer;               /* temperature test buffer */
    float temp_l;               /* difference of low/high tempearture
                                   percentiles */
    float temp_prob;            /* temperature probability */
    float vari_prob;            /* probability from NDVI, NDSI, and whiteness */
    float max_value;            /* maximum value */
    float *prob = NULL;         /* probability value */
    float *wprob = NULL;        /* probability value */
    float clr_mask = 0.0;       /* clear sky pixel threshold */
    float wclr_mask = 0.0;      /* water pixel threshold */
    int data_size;              /* Data size for memory allocation */
    int16 *nir = NULL;          /* near infrared band data */
    int16 *swir1 = NULL;        /* short wavelength infrared band data */
    int16 *nir_data = NULL;          /* Data to be filled */
    int16 *swir1_data = NULL;        /* Data to be filled */
    int16 *filled_nir_data = NULL;   /* Filled result */
    int16 *filled_swir1_data = NULL; /* Filled result */
    float nir_boundary;         /* NIR boundary value / background value */
    float swir1_boundary;       /* SWIR1 boundary value / background value */
    int16 shadow_prob;          /* shadow probability */
    int status;                 /* return value */
    int satu_bv;                /* sum of saturated bands 1, 2, 3 value */

    int pixel_index;
    int pixel_count;

    pixel_count = nrows * ncols;

    /* Dynamic memory allocation */
    unsigned char *clear_mask = NULL;

    clear_mask = calloc (pixel_count, sizeof (unsigned char));
    if (clear_mask == NULL)
    {
        RETURN_ERROR ("Allocating mask memory", "pcloud", FAILURE);
    }

    if (verbose)
        printf ("The first pass\n");

    /* Loop through each line in the image */
    for (row = 0; row < nrows; row++)
    {
        if (verbose)
        {
            /* Print status on every 1000 lines */
            if (!(row % 1000))
            {
                printf ("Processing line %d\r", row);
                fflush (stdout);
            }
        }

        /* For each of the image bands */
        for (ib = 0; ib < input->nband; ib++)
        {
            /* Read each input reflective band -- data is read into
               input->buf[ib] */
            if (!GetInputLine (input, ib, row))
            {
                sprintf (errstr, "Reading input image data for line %d, "
                         "band %d", row, ib);
                RETURN_ERROR (errstr, "pcloud", FAILURE);
            }
        }

        /* For the thermal band */
        /* Read the input thermal band -- data is read into input->therm_buf */
        if (!GetInputThermLine (input, row))
        {
            sprintf (errstr, "Reading input thermal data for line %d", row);
            RETURN_ERROR (errstr, "pcloud", FAILURE);
        }

        for (col = 0; col < ncols; col++)
        {
            pixel_index = row * ncols + col;

            int ib;
            for (ib = 0; ib < BI_REFL_BAND_COUNT; ib++)
            {
                if (input->buf[ib][col] == input->meta.satu_value_ref[ib])
                    input->buf[ib][col] = input->meta.satu_value_max[ib];
            }
            if (input->therm_buf[col] == input->meta.therm_satu_value_ref)
                input->therm_buf[col] = input->meta.therm_satu_value_max;

            /* process non-fill pixels only
               Due to a problem with the input LPGS data, the thermal band
               may have values less than FILL_PIXEL after scaling so exclude
               those as well */
            if (input->therm_buf[col] <= FILL_PIXEL
                || input->buf[BI_BLUE][col] == FILL_PIXEL
                || input->buf[BI_GREEN][col] == FILL_PIXEL
                || input->buf[BI_RED][col] == FILL_PIXEL
                || input->buf[BI_NIR][col] == FILL_PIXEL
                || input->buf[BI_SWIR_1][col] == FILL_PIXEL
                || input->buf[BI_SWIR_2][col] == FILL_PIXEL)
            {
                pixel_mask[pixel_index] = CF_FILL_BIT;
                clear_mask[pixel_index] = CF_CLEAR_FILL_BIT;
                continue;
            }
            image_data_counter++;

            if ((input->buf[BI_RED][col] + input->buf[BI_NIR][col]) != 0)
            {
                ndvi = (float) (input->buf[BI_NIR][col]
                                - input->buf[BI_RED][col])
                       / (float) (input->buf[BI_NIR][col]
                                  + input->buf[BI_RED][col]);
            }
            else
                ndvi = 0.01;

            if ((input->buf[BI_GREEN][col] + input->buf[BI_SWIR_1][col]) != 0)
            {
                ndsi = (float) (input->buf[BI_GREEN][col]
                                - input->buf[BI_SWIR_1][col])
                       / (float) (input->buf[BI_GREEN][col]
                                  + input->buf[BI_SWIR_1][col]);
            }
            else
                ndsi = 0.01;

            /* Basic cloud test, equation 1 */
            if (((ndsi - 0.8) < MINSIGMA)
                && ((ndvi - 0.8) < MINSIGMA)
                && (input->buf[BI_SWIR_2][col] > 300)
                && (input->therm_buf[col] < 2700))
            {
                pixel_mask[pixel_index] |= CF_CLOUD_BIT;
            }
            else
                pixel_mask[pixel_index] &= ~CF_CLOUD_BIT;

            /* It takes every snow pixel including snow pixels under thin
               or icy clouds, equation 20 */
            if (((ndsi - 0.15) > MINSIGMA)
                && (input->therm_buf[col] < 1000)
                && (input->buf[BI_NIR][col] > 1100)
                && (input->buf[BI_GREEN][col] > 1000))
            {
                pixel_mask[pixel_index] |= CF_SNOW_BIT;
            }
            else
                pixel_mask[pixel_index] &= ~CF_SNOW_BIT;

            /* Zhe's water test (works over thin cloud), equation 5 */
            if ((((ndvi - 0.01) < MINSIGMA)
                  && (input->buf[BI_NIR][col] < 1100))
                || (((ndvi - 0.1) < MINSIGMA)
                    && (ndvi > MINSIGMA)
                    && (input->buf[BI_NIR][col] < 500)))
            {
                pixel_mask[pixel_index] |= CF_WATER_BIT;
            }
            else
                pixel_mask[pixel_index] &= ~CF_WATER_BIT;

            /* visible bands flatness (sum(abs)/mean < 0.6 => bright and dark
               cloud), equation 2 */
            if (pixel_mask[pixel_index] & CF_CLOUD_BIT)
            {
                visi_mean = (float) (input->buf[BI_BLUE][col]
                                     + input->buf[BI_GREEN][col]
                                     + input->buf[BI_RED][col]) / 3.0;
                if (visi_mean != 0)
                {
                    whiteness =
                        ((fabs ((float) input->buf[BI_BLUE][col] - visi_mean)
                          + fabs ((float) input->buf[BI_GREEN][col] - visi_mean)
                          + fabs ((float) input->buf[BI_RED][col]
                                  - visi_mean))) / visi_mean;
                }
                else
                {
                    /* Just put a large value to remove them from cloud pixel
                       identification */
                    whiteness = 100.0;
                }
            }

            /* Update cloud_mask,  if one visible band is saturated,
               whiteness = 0, due to data type conversion, pixel value
               difference of 1 is possible */
            if ((input->buf[BI_BLUE][col]
                 >= (input->meta.satu_value_max[BI_BLUE] - 1))
                ||
                (input->buf[BI_GREEN][col]
                 >= (input->meta.satu_value_max[BI_GREEN] - 1))
                ||
                (input->buf[BI_RED][col]
                 >= (input->meta.satu_value_max[BI_RED] - 1)))
            {
                whiteness = 0.0;
                satu_bv = 1;
            }
            else
            {
                satu_bv = 0;
            }

            if ((pixel_mask[pixel_index] & CF_CLOUD_BIT) &&
                (whiteness - 0.7) < MINSIGMA)
            {
                pixel_mask[pixel_index] |= CF_CLOUD_BIT;
            }
            else
                pixel_mask[pixel_index] &= ~CF_CLOUD_BIT;

            /* Haze test, equation 3 */
            hot = (float) input->buf[BI_BLUE][col]
                  - 0.5 * (float) input->buf[BI_RED][col]
                  - 800.0;
            if ((pixel_mask[pixel_index] & CF_CLOUD_BIT)
                && (hot > MINSIGMA || satu_bv == 1))
                pixel_mask[pixel_index] |= CF_CLOUD_BIT;
            else
                pixel_mask[pixel_index] &= ~CF_CLOUD_BIT;

            /* Ratio 4/5 > 0.75 test, equation 4 */
            if ((pixel_mask[pixel_index] & CF_CLOUD_BIT) &&
                input->buf[BI_SWIR_1][col] != 0)
            {
                if ((float) input->buf[BI_NIR][col] /
                    (float) input->buf[BI_SWIR_1][col] - 0.75 > MINSIGMA)
                    pixel_mask[pixel_index] |= CF_CLOUD_BIT;
                else
                    pixel_mask[pixel_index] &= ~CF_CLOUD_BIT;
            }
            else
                pixel_mask[pixel_index] &= ~CF_CLOUD_BIT;

            /* Build counters for clear, clear land, and clear water */
            if (pixel_mask[pixel_index] & CF_CLOUD_BIT)
            {
                /* It is cloud so make sure none of the bits are set */
                clear_mask[pixel_index] = CF_CLEAR_NONE;
            }
            else
            {
                clear_mask[pixel_index] = CF_CLEAR_BIT;
                clear_pixel_counter++;

                if (pixel_mask[pixel_index] & CF_WATER_BIT)
                {
                    /* Add the clear water bit */
                    clear_mask[pixel_index] |= CF_CLEAR_WATER_BIT;
                    clear_water_pixel_counter++;
                }
                else
                {
                    /* Add the clear land bit */
                    clear_mask[pixel_index] |= CF_CLEAR_LAND_BIT;
                    clear_land_pixel_counter++;
                }
            }
        }
    }
    printf ("\n");

    *clear_ptm = 100.0 * ((float) clear_pixel_counter
                          / (float) image_data_counter);
    land_ptm = 100.0 * ((float) clear_land_pixel_counter
                        / (float) image_data_counter);
    water_ptm = 100.0 * ((float) clear_water_pixel_counter
                         / (float) image_data_counter);

    if (verbose)
    {
        printf ("(clear_pixels, clear_land_pixels, clear_water_pixels,"
                " image_data_counter) = (%d, %d, %d, %d)\n",
                clear_pixel_counter, clear_land_pixel_counter,
                clear_water_pixel_counter, image_data_counter);
        printf ("(clear_ptm, land_ptm, water_ptm) = (%f, %f, %f)\n",
                *clear_ptm, land_ptm, water_ptm);
    }

    if ((*clear_ptm - 0.1) <= MINSIGMA)
    {
        /* No thermal test is needed, all clouds */
        *t_templ = -1.0;
        *t_temph = -1.0;
        for (pixel_index = 0; pixel_index < pixel_count; pixel_index++)
        {
            /* All cloud */
            if (!(pixel_mask[pixel_index] & CF_CLOUD_BIT))
                pixel_mask[pixel_index] |= CF_SHADOW_BIT;
            else
                pixel_mask[pixel_index] &= ~CF_SHADOW_BIT;
        }
    }
    else
    {
        f_temp = calloc (pixel_count, sizeof (int16));
        f_wtemp = calloc (pixel_count, sizeof (int16));
        if (f_temp == NULL || f_wtemp == NULL)
        {
            sprintf (errstr, "Allocating temp memory");
            RETURN_ERROR (errstr, "pcloud", FAILURE);
        }

        if (verbose)
            printf ("The second pass\n");

        /* Determine which bit to test for land */
        if ((land_ptm - 0.1) >= MINSIGMA)
        {
            /* use clear land only */
            land_bit = CF_CLEAR_LAND_BIT;
        }
        else
        {
            /* not enough clear land so use all clear pixels */
            land_bit = CF_CLEAR_BIT;
        }

        /* Determine which bit to test for water */
        if ((water_ptm - 0.1) >= MINSIGMA)
        {
            /* use clear water only */
            water_bit = CF_CLEAR_WATER_BIT;
        }
        else
        {
            /* not enough clear water so use all clear pixels */
            water_bit = CF_CLEAR_BIT;
        }

        int16 f_temp_max = SHRT_MIN;
        int16 f_temp_min = SHRT_MAX;
        int16 f_wtemp_max = SHRT_MIN;
        int16 f_wtemp_min = SHRT_MAX;
        int land_count = 0;
        int water_count = 0;
        /* Loop through each line in the image */
        for (row = 0; row < nrows; row++)
        {
            if (verbose)
            {
                /* Print status on every 1000 lines */
                if (!(row % 1000))
                {
                    printf ("Processing line %d\r", row);
                    fflush (stdout);
                }
            }

            /* For the thermal band, read the input thermal band  */
            if (!GetInputThermLine (input, row))
            {
                sprintf (errstr, "Reading input thermal data for line %d",
                         row);
                RETURN_ERROR (errstr, "pcloud", FAILURE);
            }

            for (col = 0; col < ncols; col++)
            {
                pixel_index = row * ncols + col;

                if (clear_mask[pixel_index] & CF_CLEAR_FILL_BIT)
                    continue;

                if (input->therm_buf[col] == input->meta.therm_satu_value_ref)
                    input->therm_buf[col] = input->meta.therm_satu_value_max;

                /* get clear land temperature */
                if (clear_mask[pixel_index] & land_bit)
                {
                    f_temp[land_count] = input->therm_buf[col];
                    if (f_temp_max < f_temp[land_count])
                        f_temp_max = f_temp[land_count];
                    if (f_temp_min > f_temp[land_count])
                        f_temp_min = f_temp[land_count];
                    land_count++;
                }

                /* get clear water temperature */
                if (clear_mask[pixel_index] & water_bit)
                {
                    f_wtemp[water_count] = input->therm_buf[col];
                    if (f_wtemp_max < f_wtemp[water_count])
                        f_wtemp_max = f_wtemp[water_count];
                    if (f_wtemp_min > f_wtemp[water_count])
                        f_wtemp_min = f_wtemp[water_count];
                    water_count++;
                }
            }
        }
        printf ("\n");

        /* Set maximum and minimum values to zero if no clear land/water
           pixels */
        if (f_temp_min == SHRT_MAX)
            f_temp_min = 0;
        if (f_temp_max == SHRT_MIN)
            f_temp_max = 0;
        if (f_wtemp_min == SHRT_MAX)
            f_wtemp_min = 0;
        if (f_wtemp_max == SHRT_MIN)
            f_wtemp_max = 0;

        /* Tempearture for snow test */
        l_pt = 0.175;
        h_pt = 1.0 - l_pt;

        /* 0.175 percentile background temperature (low) */
        status = prctile (f_temp, land_count, f_temp_min, f_temp_max,
                          100.0 * l_pt, t_templ);
        if (status != SUCCESS)
        {
            sprintf (errstr, "Error calling prctile routine");
            RETURN_ERROR (errstr, "pcloud", FAILURE);
        }

        /* 0.825 percentile background temperature (high) */
        status = prctile (f_temp, land_count, f_temp_min, f_temp_max,
                          100.0 * h_pt, t_temph);
        if (status != SUCCESS)
        {
            sprintf (errstr, "Error calling prctile routine");
            RETURN_ERROR (errstr, "pcloud", FAILURE);
        }

        status = prctile (f_wtemp, water_count, f_wtemp_min, f_wtemp_max,
                          100.0 * h_pt, &t_wtemp);
        if (status != SUCCESS)
        {
            sprintf (errstr, "Error calling prctile routine");
            RETURN_ERROR (errstr, "pcloud", FAILURE);
        }

        /* Temperature test */
        t_buffer = 4 * 100;
        *t_templ -= (float) t_buffer;
        *t_temph += (float) t_buffer;
        temp_l = *t_temph - *t_templ;

        /* Release f_temp memory */
        free (f_wtemp);
        f_wtemp = NULL;
        free (f_temp);
        f_temp = NULL;

        wfinal_prob = calloc (pixel_count, sizeof (float));
        final_prob = calloc (pixel_count, sizeof (float));
        if (wfinal_prob == NULL || final_prob == NULL)
        {
            sprintf (errstr, "Allocating prob memory");
            RETURN_ERROR (errstr, "pcloud", FAILURE);
        }

        if (verbose)
            printf ("The third pass\n");

        /* Loop through each line in the image */
        for (row = 0; row < nrows; row++)
        {
            if (verbose)
            {
                /* Print status on every 1000 lines */
                if (!(row % 1000))
                {
                    printf ("Processing line %d\r", row);
                    fflush (stdout);
                }
            }

            /* For each of the image bands */
            for (ib = 0; ib < input->nband; ib++)
            {
                /* Read each input reflective band -- data is read into
                   input->buf[ib] */
                if (!GetInputLine (input, ib, row))
                {
                    sprintf (errstr, "Reading input image data for line %d, "
                             "band %d", row, ib);
                    RETURN_ERROR (errstr, "pcloud", FAILURE);
                }
            }

            /* For the thermal band, data is read into input->therm_buf */
            if (!GetInputThermLine (input, row))
            {
                sprintf (errstr, "Reading input thermal data for line %d",
                         row);
                RETURN_ERROR (errstr, "pcloud", FAILURE);
            }

            /* Loop through each sample in the image */
            for (col = 0; col < ncols; col++)
            {
                pixel_index = row * ncols + col;

                if (pixel_mask[pixel_index] & CF_FILL_BIT)
                    continue;

                for (ib = 0; ib < BI_REFL_BAND_COUNT - 1; ib++)
                {
                    if (input->buf[ib][col] == input->meta.satu_value_ref[ib])
                        input->buf[ib][col] = input->meta.satu_value_max[ib];
                }
                if (input->therm_buf[col] == input->meta.therm_satu_value_ref)
                    input->therm_buf[col] = input->meta.therm_satu_value_max;

                if (pixel_mask[pixel_index] & CF_WATER_BIT)
                {
                    /* Get cloud prob over water */
                    /* Temperature test over water */
                    wtemp_prob = (t_wtemp - (float) input->therm_buf[col]) /
                        400.0;
                    if (wtemp_prob < MINSIGMA)
                        wtemp_prob = 0.0;

                    /* Brightness test (over water) */
                    t_bright = 1100;
                    brightness_prob = (float) input->buf[BI_SWIR_1][col] /
                        (float) t_bright;
                    if ((brightness_prob - 1.0) > MINSIGMA)
                        brightness_prob = 1.0;
                    if (brightness_prob < MINSIGMA)
                        brightness_prob = 0.0;

                    /*Final prob mask (water), cloud over water probability */
                    wfinal_prob[pixel_index] =
                        100.0 * wtemp_prob * brightness_prob;
                    final_prob[pixel_index] = 0.0;
                }
                else
                {
                    temp_prob =
                        (*t_temph - (float) input->therm_buf[col]) / temp_l;
                    /* Temperature can have prob > 1 */
                    if (temp_prob < MINSIGMA)
                        temp_prob = 0.0;

                    if ((input->buf[BI_RED][col] + input->buf[BI_NIR][col]) != 0)
                    {
                        ndvi = (float) (input->buf[BI_NIR][col]
                                        - input->buf[BI_RED][col])
                               / (float) (input->buf[BI_NIR][col]
                                          + input->buf[BI_RED][col]);
                    }
                    else
                        ndvi = 0.01;

                    if ((input->buf[BI_GREEN][col]
                         + input->buf[BI_SWIR_1][col]) != 0)
                    {
                        ndsi = (float) (input->buf[BI_GREEN][col]
                                        - input->buf[BI_SWIR_1][col])
                               / (float) (input->buf[BI_GREEN][col]
                                          + input->buf[BI_SWIR_1][col]);
                    }
                    else
                        ndsi = 0.01;

                    /* NDVI and NDSI should not be negative */
                    if (ndsi < MINSIGMA)
                        ndsi = 0.0;
                    if (ndvi < MINSIGMA)
                        ndvi = 0.0;

                    visi_mean = (input->buf[BI_BLUE][col]
                                 + input->buf[BI_GREEN][col]
                                 + input->buf[BI_RED][col]) / 3.0;
                    if (visi_mean != 0)
                    {
                        whiteness =
                            ((fabs ((float) input->buf[BI_BLUE][col]
                                    - visi_mean)
                              + fabs ((float) input->buf[BI_GREEN][col]
                                      - visi_mean)
                              + fabs ((float) input->buf[BI_RED][col]
                                      - visi_mean))) / visi_mean;
                    }
                    else
                        whiteness = 0.0;

                    /* If one visible band is saturated, whiteness = 0 */
                    if ((input->buf[BI_BLUE][col]
                         >= (input->meta.satu_value_max[BI_BLUE] - 1))
                        ||
                        (input->buf[BI_GREEN][col]
                         >= (input->meta.satu_value_max[BI_GREEN] - 1))
                        ||
                        (input->buf[BI_RED][col]
                         >= (input->meta.satu_value_max[BI_RED] - 1)))
                    {
                        whiteness = 0.0;
                    }

                    /* Vari_prob=1-max(max(abs(NDSI),abs(NDVI)),whiteness); */
                    if ((ndsi - ndvi) > MINSIGMA)
                        max_value = ndsi;
                    else
                        max_value = ndvi;
                    if ((whiteness - max_value) > MINSIGMA)
                        max_value = whiteness;
                    vari_prob = 1.0 - max_value;

                    /*Final prob mask (land) */
                    final_prob[pixel_index] = 100.0 * (temp_prob * vari_prob);
                    wfinal_prob[pixel_index] = 0.0;
                }
            }
        }
        printf ("\n");

        /* Allocate memory for prob */
        prob = malloc (pixel_count * sizeof (float));
        if (prob == NULL)
        {
            sprintf (errstr, "Allocating prob memory");
            RETURN_ERROR (errstr, "pcloud", FAILURE);
        }

        float prob_max = 0.0;
        float prob_min = 0.0;
        land_count = 0;
        for (pixel_index = 0; pixel_index < pixel_count; pixel_index++)
        {
            if (clear_mask[pixel_index] & CF_CLEAR_FILL_BIT)
                continue;

            if (clear_mask[pixel_index] & land_bit)
            {
                prob[land_count] = final_prob[pixel_index];

                if ((prob[land_count] - prob_max) > MINSIGMA)
                    prob_max = prob[land_count];

                if ((prob_min - prob[land_count]) > MINSIGMA)
                    prob_min = prob[land_count];

                land_count++;
            }
        }

        /* Dynamic threshold for land */
        status = prctile2 (prob, land_count, prob_min, prob_max,
                           100.0 * h_pt, &clr_mask);
        if (status != SUCCESS)
        {
            sprintf (errstr, "Error calling prctile2 routine");
            RETURN_ERROR (errstr, "pcloud", FAILURE);
        }
        clr_mask += cloud_prob_threshold;

        /* Release memory for prob */
        free (prob);
        prob = NULL;

        /* Allocate memory for wprob */
        wprob = malloc (pixel_count * sizeof (float));
        if (wprob == NULL)
        {
            sprintf (errstr, "Allocating wprob memory");
            RETURN_ERROR (errstr, "pcloud", FAILURE);
        }

        float wprob_max = 0.0;
        float wprob_min = 0.0;
        water_count = 0;
        for (pixel_index = 0; pixel_index < pixel_count; pixel_index++)
        {
            if (clear_mask[pixel_index] & CF_CLEAR_FILL_BIT)
                continue;

            if (clear_mask[pixel_index] & water_bit)
            {
                wprob[water_count] = wfinal_prob[pixel_index];

                if ((wprob[water_count] - wprob_max) > MINSIGMA)
                    wprob_max = wprob[water_count];

                if ((wprob_min - wprob[water_count]) > MINSIGMA)
                    wprob_min = wprob[water_count];

                water_count++;
            }
        }

        /* Dynamic threshold for water */
        status = prctile2 (wprob, water_count, wprob_min, wprob_max,
                           100.0 * h_pt, &wclr_mask);
        if (status != SUCCESS)
        {
            sprintf (errstr, "Error calling prctile2 routine");
            RETURN_ERROR (errstr, "pcloud", FAILURE);
        }
        wclr_mask += cloud_prob_threshold;

        /* Release memory for wprob */
        free (wprob);
        wprob = NULL;

        if (verbose)
        {
            printf ("pcloud probability threshold (land) = %.2f\n", clr_mask);
            printf ("pcloud probability threshold (water) = %.2f\n",
                    wclr_mask);

            printf ("The fourth pass\n");
        }

        /* Loop through each line in the image */
        for (row = 0; row < nrows; row++)
        {
            if (verbose)
            {
                /* Print status on every 1000 lines */
                if (!(row % 1000))
                {
                    printf ("Processing line %d\r", row);
                    fflush (stdout);
                }
            }

            /* For the thermal band, data is read into input->therm_buf */
            if (!GetInputThermLine (input, row))
            {
                sprintf (errstr, "Reading input thermal data for line %d",
                         row);
                RETURN_ERROR (errstr, "pcloud", FAILURE);
            }

            for (col = 0; col < ncols; col++)
            {
                pixel_index = row * ncols + col;

                if (pixel_mask[pixel_index] & CF_FILL_BIT)
                    continue;

                if (input->therm_buf[col] == input->meta.therm_satu_value_ref)
                {
                    input->therm_buf[col] = input->meta.therm_satu_value_max;
                }

                if (((pixel_mask[pixel_index] & CF_CLOUD_BIT)
                     &&
                     (final_prob[pixel_index] > clr_mask)
                     &&
                     (!(pixel_mask[pixel_index] & CF_WATER_BIT)))
                    ||
                    ((pixel_mask[pixel_index] & CF_CLOUD_BIT)
                     &&
                     (wfinal_prob[pixel_index] > wclr_mask)
                     &&
                     (pixel_mask[pixel_index] & CF_WATER_BIT))
                    ||
                    (input->therm_buf[col] < *t_templ + t_buffer - 3500))
                {
                    /* This test indicates a high confidence */
                    conf_mask[pixel_index] = CLOUD_CONFIDENCE_HIGH;

                    /* Original code was only this if test and setting the
                       cloud bit or not */
                    pixel_mask[pixel_index] |= CF_CLOUD_BIT;
                }
                else if (((pixel_mask[pixel_index] & CF_CLOUD_BIT)
                          &&
                          (final_prob[pixel_index] > clr_mask-10.0)
                          &&
                          (!(pixel_mask[pixel_index] & CF_WATER_BIT)))
                         ||
                         ((pixel_mask[pixel_index] & CF_CLOUD_BIT)
                          &&
                          (wfinal_prob[pixel_index] > wclr_mask-10.0)
                          &&
                          (pixel_mask[pixel_index] & CF_WATER_BIT)))
                {
                    /* This test indicates a medium confidence */
                    conf_mask[pixel_index] = CLOUD_CONFIDENCE_MED;

                    /* Don't set the cloud bit per the original code */
                    pixel_mask[pixel_index] &= ~CF_CLOUD_BIT;
                }
                else
                {
                    /* All remaining are a low confidence */
                    conf_mask[pixel_index] = CLOUD_CONFIDENCE_LOW;

                    /* Don't set the cloud bit per the original code */
                    pixel_mask[pixel_index] &= ~CF_CLOUD_BIT;
                }
            }
        }
        printf ("\n");

        /* Free the memory */
        free (wfinal_prob);
        wfinal_prob = NULL;
        free (final_prob);
        final_prob = NULL;

        /* Band NIR & SWIR1 flood fill section */
        data_size = input->size.l * input->size.s;
        nir = calloc (data_size, sizeof (int16));
        swir1 = calloc (data_size, sizeof (int16));
        if (nir == NULL || swir1 == NULL)
        {
            sprintf (errstr, "Allocating nir and swir1 memory");
            RETURN_ERROR (errstr, "pcloud", FAILURE);
        }

        if (verbose)
            printf ("The fifth pass\n");

        nir_data = calloc (data_size, sizeof (int16));
        swir1_data = calloc (data_size, sizeof (int16));
        filled_nir_data = calloc (data_size, sizeof (int16));
        filled_swir1_data = calloc (data_size, sizeof (int16));
        if (nir_data == NULL || swir1_data == NULL ||
            filled_nir_data == NULL || filled_swir1_data == NULL)
        {
            sprintf (errstr, "Allocating nir and swir1 memory");
            RETURN_ERROR (errstr, "pcloud", FAILURE);
        }

        int16 nir_max = 0;
        int16 nir_min = 0;
        int16 swir1_max = 0;
        int16 swir1_min = 0;
        int nir_count = 0;
        int swir1_count = 0;
        /* Loop through each line in the image */
        for (row = 0; row < nrows; row++)
        {
            if (verbose)
            {
                /* Print status on every 1000 lines */
                if (!(row % 1000))
                {
                    printf ("Processing line %d\r", row);
                    fflush (stdout);
                }
            }

            /* For each of the image bands */
            for (ib = 0; ib < input->nband; ib++)
            {
                /* Read each input reflective band -- data is read into
                   input->buf[ib] */
                if (!GetInputLine (input, ib, row))
                {
                    sprintf (errstr, "Reading input image data for line %d, "
                             "band %d", row, ib);
                    RETURN_ERROR (errstr, "pcloud", FAILURE);
                }
            }

            for (col = 0; col < ncols; col++)
            {
                pixel_index = row * ncols + col;

                if (clear_mask[pixel_index] & CF_CLEAR_FILL_BIT)
                    continue;

                if (input->buf[BI_NIR][col]
                    == input->meta.satu_value_ref[BI_NIR])
                {
                    input->buf[BI_NIR][col] =
                        input->meta.satu_value_max[BI_NIR];
                }
                if (input->buf[BI_SWIR_1][col]
                    == input->meta.satu_value_ref[BI_SWIR_1])
                {
                    input->buf[BI_SWIR_1][col] =
                        input->meta.satu_value_max[BI_SWIR_1];
                }

                if (clear_mask[pixel_index] & land_bit)
                {
                    nir[nir_count] = input->buf[BI_NIR][col];
                    if (nir[nir_count] > nir_max)
                        nir_max = nir[nir_count];
                    if (nir[nir_count] < nir_min)
                        nir_min = nir[nir_count];
                    nir_count++;

                    swir1[swir1_count] = input->buf[BI_SWIR_1][col];
                    if (swir1[swir1_count] > swir1_max)
                        swir1_max = swir1[swir1_count];
                    if (swir1[swir1_count] < swir1_min)
                        swir1_min = swir1[swir1_count];
                    swir1_count++;
                }
            }

            /* NIR */
            memcpy(&nir_data[row * input->size.s], &input->buf[BI_NIR][0],
                   input->size.s * sizeof (int16));
            /* SWIR1 */
            memcpy(&swir1_data[row * input->size.s], &input->buf[BI_SWIR_1][0],
                   input->size.s * sizeof (int16));
        }
        printf ("\n");

        /* Estimating background (land) Band NIR Ref */
        status = prctile (nir, nir_count, nir_min, nir_max,
                          100.0 * l_pt, &nir_boundary);
        if (status != SUCCESS)
        {
            sprintf (errstr, "Calling prctile function\n");
            RETURN_ERROR (errstr, "pcloud", FAILURE);
        }
        status = prctile (swir1, swir1_count, swir1_min, swir1_max,
                          100.0 * l_pt, &swir1_boundary);
        if (status != SUCCESS)
        {
            sprintf (errstr, "Calling prctile function\n");
            RETURN_ERROR (errstr, "pcloud", FAILURE);
        }

        /* Release the memory */
        free (nir);
        free (swir1);
        nir = NULL;
        swir1 = NULL;

        /* Call the fill minima routine to do image fill */
/* Perform them in parallel if threading is enabled */
#ifdef _OPENMP
#pragma omp parallel sections
#endif
{
    {
        if (fill_local_minima_in_image("NIR Band", nir_data,
                                       input->size.l, input->size.s,
                                       nir_boundary, filled_nir_data)
            != SUCCESS)
        {
            printf ("Error Running fill_local_minima_in_image on NIR band");
            status = ERROR;
        }
    }

#ifdef _OPENMP
    #pragma omp section
#endif
    {
        if (fill_local_minima_in_image("SWIR1 Band", swir1_data,
                                       input->size.l, input->size.s,
                                       swir1_boundary, filled_swir1_data)
            != SUCCESS)
        {
            printf ("Error Running fill_local_minima_in_image on SWIR1 band");
            status = ERROR;
        }
    }
}

        /* Release the memory */
        free(nir_data);
        free(swir1_data);
        nir_data = NULL;
        swir1_data = NULL;

        if (status == ERROR)
        {
            free(filled_nir_data);
            free(filled_swir1_data);
            sprintf (errstr, "Running fill_local_minima_in_image");
            RETURN_ERROR (errstr, "pcloud", FAILURE);
        }

        if (verbose)
            printf ("The sixth pass\n");

        int16 new_nir;
        int16 new_swir1;
        for (row = 0; row < nrows; row++)
        {
            if (verbose)
            {
                /* Print status on every 1000 lines */
                if (!(row % 1000))
                {
                    printf ("Processing line %d\r", row);
                    fflush (stdout);
                }
            }

            /* For each of the image bands */
            for (ib = 0; ib < input->nband; ib++)
            {
                /* Read each input reflective band -- data is read into
                   input->buf[ib] */
                if (!GetInputLine (input, ib, row))
                {
                    sprintf (errstr, "Reading input image data for line %d, "
                             "band %d", row, ib);
                    RETURN_ERROR (errstr, "pcloud", FAILURE);
                }
            }

            /* For the thermal band, data is read into input->therm_buf */
            if (!GetInputThermLine (input, row))
            {
                sprintf (errstr, "Reading input thermal data for line %d",
                         row);
                RETURN_ERROR (errstr, "pcloud", FAILURE);
            }

            for (col = 0; col < ncols; col++)
            {
                pixel_index = row * ncols + col;

                if (input->buf[BI_NIR][col]
                    == input->meta.satu_value_ref[BI_NIR])
                {
                    input->buf[BI_NIR][col] =
                        input->meta.satu_value_max[BI_NIR];
                }
                if (input->buf[BI_SWIR_1][col]
                    == input->meta.satu_value_ref[BI_SWIR_1])
                {
                    input->buf[BI_SWIR_1][col] =
                        input->meta.satu_value_max[BI_SWIR_1];
                }

                if (pixel_mask[pixel_index] & CF_FILL_BIT)
                {
                    conf_mask[pixel_index] = CF_FILL_PIXEL;
                    continue;
                }

                new_nir = filled_nir_data[pixel_index] -
                          input->buf[BI_NIR][col];
                new_swir1 = filled_swir1_data[pixel_index] -
                            input->buf[BI_SWIR_1][col];

                if (new_nir < new_swir1)
                    shadow_prob = new_nir;
                else
                    shadow_prob = new_swir1;

                if (shadow_prob > 200)
                    pixel_mask[pixel_index] |= CF_SHADOW_BIT;
                else
                    pixel_mask[pixel_index] &= ~CF_SHADOW_BIT;

                /* refine Water mask (no confusion water/cloud) */
                if ((pixel_mask[pixel_index] & CF_WATER_BIT) &&
                    (pixel_mask[pixel_index] & CF_CLOUD_BIT))
                {
                    pixel_mask[pixel_index] &= ~CF_WATER_BIT;
                }
            }
        }
        printf ("\n");

        /* Release the memory */
        free(nir_data);
        nir_data = NULL;
        free(swir1_data);
        swir1_data = NULL;
        free(filled_nir_data);
        filled_nir_data = NULL;
        free(filled_swir1_data);
        filled_swir1_data = NULL;
    }

    free (clear_mask);
    clear_mask = NULL;

    return SUCCESS;
}
コード例 #12
0
ファイル: misc.c プロジェクト: NGenetzky/espa-cloud-masking
/******************************************************************************
MODULE:  prctile2

PURPOSE:  Calculate Percentile of a floating point array

RETURN: SUCCESS
        FAILURE

HISTORY:
Date        Programmer       Reason
--------    ---------------  -------------------------------------
3/15/2013   Song Guo         Original Development
Nov/2014    Ron Dilley       Speed improvements by removing divisions

NOTES: 
******************************************************************************/
int prctile2
(
    float *array, /*I: input data pointer */
    int nums,     /*I: number of input data array */
    float min,    /*I: minimum value in the input data array */
    float max,    /*I: maximum value in the input data array  */
    float prct,   /*I: percentage threshold */
    float *result /*O: percentile calculated */
)
{
    int *interval;            /* array to store data in an interval */
    int i, j;                 /* loop variables */
    int start, end;           /* start/end variables */
    int loops;                /* data range of input data */
    float inv_nums_100;       /* inverse of the nums value * 100 */
    int sum;

    /* Just return 0 if no input value */
    if (nums == 0)
    {
        *result = 0.0;
        return SUCCESS;
    }
    else
    {
        *result = max;
    }

    start = (int) rint (min);
    end = (int) rint (max);

    loops = end - start + 2;

    interval = calloc (loops, sizeof (int));
    if (interval == NULL)
    {
        RETURN_ERROR ("Invalid memory allocation", "prctile2", FAILURE);
    }

    for (i = 0; i < nums; i++)
    {
        interval[(int) rint (array[i]) - start]++;
    }

    inv_nums_100 = (1.0/((float) nums)) * 100.0;
    sum = 0;
    for (j = 0; j < loops; j++)
    {
        sum += interval[j];
        if (((float) sum * inv_nums_100) >= prct)
        {
            *result = (float) (start + j);
            break;
        }
        else
        {
            continue;
        }
    }
    free (interval);

    return SUCCESS;
}
コード例 #13
0
static jdwpTransportError JNICALL
socketTransport_readPacket(jdwpTransportEnv* env, jdwpPacket* packet) {
    jint length, data_len;
    jint n;

    /* packet can't be null */
    if (packet == NULL) {
	RETURN_ERROR(JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT, "packet is null");
    }

    /* read the length field */
    n = recv_fully(socketFD, (char *)&length, sizeof(jint));

    /* check for EOF */
    if (n == 0) {
	packet->type.cmd.len = 0;
	return JDWPTRANSPORT_ERROR_NONE;
    }
    if (n != sizeof(jint)) {
	RETURN_RECV_ERROR(n);
    }

    length = (jint)dbgsysNetworkToHostLong(length);
    packet->type.cmd.len = length;


    n = recv_fully(socketFD,(char *)&(packet->type.cmd.id),sizeof(jint));
    if (n < (int)sizeof(jint)) {
	RETURN_RECV_ERROR(n);
    }

    packet->type.cmd.id = (jint)dbgsysNetworkToHostLong(packet->type.cmd.id);

    n = recv_fully(socketFD,(char *)&(packet->type.cmd.flags),sizeof(jbyte));
    if (n < (int)sizeof(jbyte)) {
	RETURN_RECV_ERROR(n);
    }

    if (packet->type.cmd.flags & JDWPTRANSPORT_FLAGS_REPLY) {
        n = recv_fully(socketFD,(char *)&(packet->type.reply.errorCode),sizeof(jbyte));
	if (n < (int)sizeof(jshort)) {
	    RETURN_RECV_ERROR(n);
	}

        /* FIXME - should the error be converted to host order?? */


    } else {
        n = recv_fully(socketFD,(char *)&(packet->type.cmd.cmdSet),sizeof(jbyte));
	if (n < (int)sizeof(jbyte)) {
	    RETURN_RECV_ERROR(n);
	}
    
        n = recv_fully(socketFD,(char *)&(packet->type.cmd.cmd),sizeof(jbyte));
        if (n < (int)sizeof(jbyte)) {
	    RETURN_RECV_ERROR(n);
	}
    }

    data_len = length - ((sizeof(jint) * 2) + (sizeof(jbyte) * 3));

    if (data_len < 0) {
	setLastError(0, "Badly formed packet received - invalid length");
	return JDWPTRANSPORT_ERROR_IO_ERROR;
    } else if (data_len == 0) {
        packet->type.cmd.data = NULL;
    } else {
        packet->type.cmd.data= (*callback->alloc)(data_len);

        if (packet->type.cmd.data == NULL) {
            RETURN_ERROR(JDWPTRANSPORT_ERROR_OUT_OF_MEMORY, "out of memory");
	}

        n = recv_fully(socketFD,(char *)packet->type.cmd.data, data_len);
	if (n < data_len) {
            (*callback->free)(packet->type.cmd.data);
	    RETURN_RECV_ERROR(n);
        }
    }

    return JDWPTRANSPORT_ERROR_NONE;
}
コード例 #14
0
static jdwpTransportError JNICALL
socketTransport_writePacket(jdwpTransportEnv* env, const jdwpPacket *packet)
{
    jint len, data_len, id;
    /* 
     * room for header and up to MAX_DATA_SIZE data bytes
     */
    char header[HEADER_SIZE + MAX_DATA_SIZE];
    jbyte *data;

    /* packet can't be null */
    if (packet == NULL) {
	RETURN_ERROR(JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT, "packet is NULL");
    }

    len = packet->type.cmd.len;		/* includes header */
    data_len = len - HEADER_SIZE;

    /* bad packet */
    if (data_len < 0) {
	RETURN_ERROR(JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT, "invalid length");
    }

    /* prepare the header for transmission */
    len = (jint)dbgsysHostToNetworkLong(len);
    id = (jint)dbgsysHostToNetworkLong(packet->type.cmd.id);

    memcpy(header + 0, &len, 4);
    memcpy(header + 4, &id, 4);
    header[8] = packet->type.cmd.flags;
    if (packet->type.cmd.flags & JDWPTRANSPORT_FLAGS_REPLY) {
	jshort errorCode =
            dbgsysHostToNetworkShort(packet->type.reply.errorCode);
        memcpy(header + 9, &errorCode, 2);
    } else {
        header[9] = packet->type.cmd.cmdSet;
        header[10] = packet->type.cmd.cmd;
    }

    data = packet->type.cmd.data;
    /* Do one send for short packets, two for longer ones */
    if (data_len <= MAX_DATA_SIZE) {
        memcpy(header + HEADER_SIZE, data, data_len);
        if (dbgsysSend(socketFD, (char *)&header, HEADER_SIZE + data_len, 0) != 
            HEADER_SIZE + data_len) {
            RETURN_IO_ERROR("send failed");
        }
    } else {
        memcpy(header + HEADER_SIZE, data, MAX_DATA_SIZE);
        if (dbgsysSend(socketFD, (char *)&header, HEADER_SIZE + MAX_DATA_SIZE, 0) != 
            HEADER_SIZE + MAX_DATA_SIZE) {
            RETURN_IO_ERROR("send failed");
        }
        /* Send the remaining data bytes right out of the data area. */
        if (dbgsysSend(socketFD, (char *)data + MAX_DATA_SIZE, 
                       data_len - MAX_DATA_SIZE, 0) != data_len - MAX_DATA_SIZE) {
            RETURN_IO_ERROR("send failed");
        }
    }

    return JDWPTRANSPORT_ERROR_NONE;
}
コード例 #15
0
ファイル: hash.c プロジェクト: SecareLupus/Drood
extern DB *
__hash_open(const char *file, int flags, int mode, const HASHINFO *info, int dflags)
{
	HTAB *hashp=NULL;
	struct stat statbuf;
	DB *dbp;
	int bpages, hdrsize, new_table, nsegs, save_errno;

	if ((flags & O_ACCMODE) == O_WRONLY) {
		errno = EINVAL;
		return NULL;
	}

	/* zero the statbuffer so that
	 * we can check it for a non-zero
	 * date to see if stat succeeded
	 */
	memset(&statbuf, 0, sizeof(struct stat));

	if (!(hashp = (HTAB *)calloc(1, sizeof(HTAB)))) {
		errno = ENOMEM;
		return NULL;
	}
	hashp->fp = NO_FILE;
	if(file)
		hashp->filename = strdup(file);

	/*
	 * Even if user wants write only, we need to be able to read
	 * the actual file, so we need to open it read/write. But, the
	 * field in the hashp structure needs to be accurate so that
	 * we can check accesses.
	 */
	hashp->flags = flags;

	new_table = 0;
	if (!file || (flags & O_TRUNC) 	|| (stat(file, &statbuf)  && (errno == ENOENT))) 
	{
		if (errno == ENOENT)
			errno = 0; /* Just in case someone looks at errno */
		new_table = 1;
	}
	else if(statbuf.st_mtime && statbuf.st_size == 0)
	{
		/* check for a zero length file and delete it
	 	 * if it exists
	 	 */
		new_table = 1;
	}
	hashp->file_size = statbuf.st_size;

	if (file) {				 
#if defined(_WIN32) || defined(_WINDOWS) || defined (macintosh)  || defined(XP_OS2)
		if ((hashp->fp = DBFILE_OPEN(file, flags | O_BINARY, mode)) == -1)
			RETURN_ERROR(errno, error1);
#else
		if ((hashp->fp = open(file, flags, mode)) == -1)
			RETURN_ERROR(errno, error1);
		(void)fcntl(hashp->fp, F_SETFD, 1);
#endif
	}
	if (new_table) {
		if (!init_hash(hashp, file, (HASHINFO *)info))
			RETURN_ERROR(errno, error1);
	} else {
		/* Table already exists */
		if (info && info->hash)
			hashp->hash = info->hash;
		else
			hashp->hash = __default_hash;

		hdrsize = read(hashp->fp, (char *)&hashp->hdr, sizeof(HASHHDR));
		if (hdrsize == -1)
			RETURN_ERROR(errno, error1);
		if (hdrsize != sizeof(HASHHDR))
			RETURN_ERROR(EFTYPE, error1);
#if BYTE_ORDER == LITTLE_ENDIAN
		swap_header(hashp);
#endif
		/* Verify file type, versions and hash function */
		if (hashp->MAGIC != HASHMAGIC)
			RETURN_ERROR(EFTYPE, error1);
#define	OLDHASHVERSION	1
		if (hashp->VERSION != HASHVERSION &&
		    hashp->VERSION != OLDHASHVERSION)
			RETURN_ERROR(EFTYPE, error1);
		if (hashp->hash(CHARKEY, sizeof(CHARKEY)) != hashp->H_CHARKEY)
			RETURN_ERROR(EFTYPE, error1);
		if (hashp->NKEYS < 0) /* Old bad database. */
			RETURN_ERROR(EFTYPE, error1);

		/*
		 * Figure out how many segments we need.  Max_Bucket is the
		 * maximum bucket number, so the number of buckets is
		 * max_bucket + 1.
		 */
		nsegs = (hashp->MAX_BUCKET + 1 + hashp->SGSIZE - 1) /
			 hashp->SGSIZE;
		hashp->nsegs = 0;
		if (alloc_segs(hashp, nsegs))
			/* If alloc_segs fails, errno will have been set.  */
			RETURN_ERROR(errno, error1);
		/* Read in bitmaps */
		bpages = (hashp->SPARES[hashp->OVFL_POINT] +
		    (hashp->BSIZE << BYTE_SHIFT) - 1) >>
		    (hashp->BSHIFT + BYTE_SHIFT);

		hashp->nmaps = bpages;
		(void)memset(&hashp->mapp[0], 0, bpages * sizeof(uint32 *));
	}

	/* Initialize Buffer Manager */
	if (info && info->cachesize)
		__buf_init(hashp, (int32) info->cachesize);
	else
		__buf_init(hashp, DEF_BUFSIZE);

	hashp->new_file = new_table;
#ifdef macintosh
	hashp->save_file = file && !(hashp->flags & O_RDONLY);
#else
	hashp->save_file = file && (hashp->flags & O_RDWR);
#endif
	hashp->cbucket = -1;
	if (!(dbp = (DB *)malloc(sizeof(DB)))) {
		RETURN_ERROR(ENOMEM, error1);
	}
	dbp->internal = hashp;
	dbp->close = hash_close;
	dbp->del = hash_delete;
	dbp->fd = hash_fd;
	dbp->get = hash_get;
	dbp->put = hash_put;
	dbp->seq = hash_seq;
	dbp->sync = hash_sync;
	dbp->type = DB_HASH;

#ifdef HASH_STATISTICS
	hash_overflows = hash_accesses = hash_collisions = hash_expansions = 0;
#endif
	return (dbp);

error1:
	hdestroy(hashp);
	errno = save_errno;
	return (NULL);
}
コード例 #16
0
ファイル: cJuryModule.cpp プロジェクト: acobus/OptiCar
tResult cJuryModule::LoadManeuverList()
{
    // load the maneuver list
    // clear old list
    m_strManeuverList.clear();
    // use QDom for parsing
    QDomDocument oDoc("maneuver_list");
    QFile oFile(m_strManeuverFile);

    // open file
    if(!oFile.open(QIODevice::ReadOnly))
    {
        RETURN_ERROR(ERR_FILE_NOT_FOUND);
    }
    if (!oDoc.setContent(&oFile))
    {
        oFile.close();
        RETURN_ERROR(ERR_INVALID_FILE);
    }

    // get the root element
    QDomElement oRoot = oDoc.documentElement();

    // get all sectors from DOM
    QDomNodeList lstSectors = oRoot.elementsByTagName("AADC-Sector");

    // iterate over all sectors
    for (int nIdxSectors = 0; nIdxSectors < lstSectors.size(); ++nIdxSectors)
    {
        // get the ids and maneuver from sector
        QDomNode oNodeSector = lstSectors.item(nIdxSectors);
        QDomElement oElementSector = oNodeSector.toElement();
        QString strIdSector = oElementSector.attribute("id");
        tSector sSector;
        sSector.id = strIdSector.toInt();
        QDomNodeList lstManeuver = oElementSector.elementsByTagName("AADC-Maneuver");
        // iterate over all maneuver
        for (int nIdxManeuver = 0; nIdxManeuver < lstManeuver.size(); ++nIdxManeuver)
        {
            // get the id and the action
            QDomNode oNodeManeuver = lstManeuver.item(nIdxManeuver);
            QDomElement oElementManeuver = oNodeManeuver.toElement();
            QString strIdManeuver = oElementManeuver.attribute("id");
            tAADC_Maneuver sManeuver;
            sManeuver.nId = strIdManeuver.toInt();
            sManeuver.action = oElementManeuver.attribute("action").toStdString();
            // fill the internal maneuver list
            sSector.lstManeuvers.push_back(sManeuver);
        }

        // fill the internal sector list
        m_lstSections.push_back(sSector);
    }
   
    // check sector list
    if (m_lstSections.size() > 0)
    {
        SetLogText("Jury Module: Loaded Maneuver file successfully.");
    }
    else
    {
        SetLogText("Jury Module: no valid Maneuver Data found!");
    }

    // fill the combo boxes
    FillComboBoxes();
    // get the xml string for transmission
    m_strManeuverList = oDoc.toString().toStdString();
    // set the controls (enable/disable)
    SetControlState();
    
    RETURN_NOERROR;
}
コード例 #17
0
ファイル: SerializeVariablesLib.c プロジェクト: B-Rich/edk2
/**
  Adds a variable to the variable serialization instance

  @param[in] Handle - Handle for a variable serialization instance
  @param[in] VariableName - Refer to RuntimeServices GetVariable
  @param[in] VendorGuid - Refer to RuntimeServices GetVariable
  @param[in] Attributes - Refer to RuntimeServices GetVariable
  @param[in] DataSize - Refer to RuntimeServices GetVariable
  @param[in] Data - Refer to RuntimeServices GetVariable

  @retval      RETURN_SUCCESS - All variables were set successfully
  @retval      RETURN_OUT_OF_RESOURCES - There we not enough resources to
                 add the variable
  @retval      RETURN_INVALID_PARAMETER - Handle was not a valid
                 variable serialization instance or
                 VariableName, VariableGuid or Data are NULL.

**/
RETURN_STATUS
EFIAPI
SerializeVariablesAddVariable (
  IN EFI_HANDLE                   Handle,
  IN CHAR16                       *VariableName,
  IN EFI_GUID                     *VendorGuid,
  IN UINT32                       Attributes,
  IN UINTN                        DataSize,
  IN VOID                         *Data
  )
{
  RETURN_STATUS  Status;
  SV_INSTANCE    *Instance;
  UINT32         SerializedNameSize;
  UINT32         SerializedDataSize;
  UINTN          SerializedSize;

  Instance = SV_FROM_HANDLE (Handle);

  if ((Instance->Signature != SV_SIGNATURE) ||
      (VariableName == NULL) || (VendorGuid == NULL) || (Data == NULL)) {
  }

  SerializedNameSize = (UINT32) StrSize (VariableName);

  SerializedSize =
    sizeof (SerializedNameSize) +
    SerializedNameSize +
    sizeof (*VendorGuid) +
    sizeof (Attributes) +
    sizeof (SerializedDataSize) +
    DataSize;

  Status = EnsureExtraBufferSpace (
             Instance,
             SerializedSize
             );
  if (RETURN_ERROR (Status)) {
    return Status;
  }

  //
  // Add name size (UINT32)
  //
  AppendToBuffer (Instance, (VOID*) &SerializedNameSize, sizeof (SerializedNameSize));

  //
  // Add variable unicode name string
  //
  AppendToBuffer (Instance, (VOID*) VariableName, SerializedNameSize);

  //
  // Add variable GUID
  //
  AppendToBuffer (Instance, (VOID*) VendorGuid, sizeof (*VendorGuid));

  //
  // Add variable attributes
  //
  AppendToBuffer (Instance, (VOID*) &Attributes, sizeof (Attributes));

  //
  // Add variable data size (UINT32)
  //
  SerializedDataSize = (UINT32) DataSize;
  AppendToBuffer (Instance, (VOID*) &SerializedDataSize, sizeof (SerializedDataSize));

  //
  // Add variable data
  //
  AppendToBuffer (Instance, Data, DataSize);

  return RETURN_SUCCESS;
}
コード例 #18
0
EGLAPI EGLBoolean EGLAPIENTRY eglChooseConfig(EGLDisplay display, const EGLint *attrib_list,
               EGLConfig *configs, EGLint config_size,
               EGLint *num_config) {
    VALIDATE_DISPLAY(display);
    if(!num_config) {
         RETURN_ERROR(EGL_FALSE,EGL_BAD_PARAMETER);
    }

        //selection defaults
        // NOTE: Some variables below are commented out to reduce compiler warnings.
        // TODO(digit): Look if these variables are really needed or not, and if so
        // fix the code to do it properly.
        EGLint      surface_type       = EGL_WINDOW_BIT;
        EGLint      renderable_type    = EGL_OPENGL_ES_BIT;
        //EGLBoolean  bind_to_tex_rgb    = EGL_DONT_CARE;
        //EGLBoolean  bind_to_tex_rgba   = EGL_DONT_CARE;
        EGLenum     caveat             = EGL_DONT_CARE;
        EGLint      config_id          = EGL_DONT_CARE;
        EGLBoolean  native_renderable  = EGL_DONT_CARE;
        EGLint      native_visual_type = EGL_DONT_CARE;
        //EGLint      max_swap_interval  = EGL_DONT_CARE;
        //EGLint      min_swap_interval  = EGL_DONT_CARE;
        EGLint      trans_red_val      = EGL_DONT_CARE;
        EGLint      trans_green_val    = EGL_DONT_CARE;
        EGLint      trans_blue_val     = EGL_DONT_CARE;
        EGLenum     transparent_type   = EGL_NONE;
        //EGLint      buffer_size        = 0;
        EGLint      red_size           = 0;
        EGLint      green_size         = 0;
        EGLint      blue_size          = 0;
        EGLint      alpha_size         = 0;
        EGLint      depth_size         = 0;
        EGLint      frame_buffer_level = 0;
        //EGLint      sample_buffers_num = 0;
        EGLint      samples_per_pixel  = 0;
        EGLint      stencil_size       = 0;

    if(!EglValidate::noAttribs(attrib_list)) { //there are attribs
        int i = 0 ;
        bool hasConfigId = false;
        while(attrib_list[i] != EGL_NONE && !hasConfigId) {
            switch(attrib_list[i]) {
            case EGL_MAX_PBUFFER_WIDTH:
            case EGL_MAX_PBUFFER_HEIGHT:
            case EGL_MAX_PBUFFER_PIXELS:
            case EGL_NATIVE_VISUAL_ID:
                break; //we dont care from those selection crateria
            case EGL_LEVEL:
                if(attrib_list[i+1] == EGL_DONT_CARE) {
                    RETURN_ERROR(EGL_FALSE,EGL_BAD_ATTRIBUTE);
                }
                frame_buffer_level = attrib_list[i+1];
                break;
            case EGL_BUFFER_SIZE:
                if(attrib_list[i+1] < 0) {
                    RETURN_ERROR(EGL_FALSE,EGL_BAD_ATTRIBUTE);
                }
                //buffer_size = attrib_list[i+1];
                break;
            case EGL_RED_SIZE:
                if(attrib_list[i+1] < 0) {
                     RETURN_ERROR(EGL_FALSE,EGL_BAD_ATTRIBUTE);
                }
                red_size = attrib_list[i+1];
                break;
            case EGL_GREEN_SIZE:
                if(attrib_list[i+1] < 0) {
                    RETURN_ERROR(EGL_FALSE,EGL_BAD_ATTRIBUTE);
                }
                green_size = attrib_list[i+1];
                break;
            case EGL_BLUE_SIZE:
                if(attrib_list[i+1] < 0) {
                    RETURN_ERROR(EGL_FALSE,EGL_BAD_ATTRIBUTE);
                }
                blue_size = attrib_list[i+1];
                break;
            case EGL_ALPHA_SIZE:
                if(attrib_list[i+1] < 0) {
                    RETURN_ERROR(EGL_FALSE,EGL_BAD_ATTRIBUTE);
                }
                alpha_size = attrib_list[i+1];
                break;
            case EGL_BIND_TO_TEXTURE_RGB:
                //bind_to_tex_rgb = attrib_list[i+1];
                break;
            case EGL_BIND_TO_TEXTURE_RGBA:
                //bind_to_tex_rgba = attrib_list[i+1];
                break;
            case EGL_CONFIG_CAVEAT:
                if(attrib_list[i+1] != EGL_NONE && attrib_list[i+1] != EGL_SLOW_CONFIG && attrib_list[i+1] != EGL_NON_CONFORMANT_CONFIG) {
                    RETURN_ERROR(EGL_FALSE,EGL_BAD_ATTRIBUTE);
                }
                caveat = attrib_list[i+1];
                break;
            case EGL_CONFIG_ID:
                if(attrib_list[i+1] < 0) {
                    RETURN_ERROR(EGL_FALSE,EGL_BAD_ATTRIBUTE);
                }
                config_id = attrib_list[i+1];
                hasConfigId = true;
                break;
            case EGL_DEPTH_SIZE:
                if(attrib_list[i+1] < 0) {
                    RETURN_ERROR(EGL_FALSE,EGL_BAD_ATTRIBUTE);
                }
                depth_size = attrib_list[i+1];
                break;
            case EGL_MAX_SWAP_INTERVAL:
                if(attrib_list[i+1] < 0) {
                    RETURN_ERROR(EGL_FALSE,EGL_BAD_ATTRIBUTE);
                }
                //max_swap_interval = attrib_list[i+1];
                break;
            case EGL_MIN_SWAP_INTERVAL:
                if(attrib_list[i+1] < 0) {
                    RETURN_ERROR(EGL_FALSE,EGL_BAD_ATTRIBUTE);
                }
                //min_swap_interval = attrib_list[i+1];
                break;
            case EGL_NATIVE_RENDERABLE:
                native_renderable = attrib_list[i+1];
                break;
            case EGL_RENDERABLE_TYPE:
                renderable_type = attrib_list[i+1];
                break;
            case EGL_NATIVE_VISUAL_TYPE:
                native_visual_type = attrib_list[i+1];
                break;
                if(attrib_list[i+1] < 0 || attrib_list[i+1] > 1 ) {
                    RETURN_ERROR(EGL_FALSE,EGL_BAD_ATTRIBUTE);
                }
            case EGL_SAMPLE_BUFFERS:
                //sample_buffers_num = attrib_list[i+1];
                break;
                if(attrib_list[i+1] < 0) {
                    RETURN_ERROR(EGL_FALSE,EGL_BAD_ATTRIBUTE);
                }
            case EGL_SAMPLES:
                if(attrib_list[i+1] < 0) {
                    RETURN_ERROR(EGL_FALSE,EGL_BAD_ATTRIBUTE);
                }
                samples_per_pixel = attrib_list[i+1];
                break;
            case EGL_STENCIL_SIZE:
                if(attrib_list[i+1] < 0) {
                    RETURN_ERROR(EGL_FALSE,EGL_BAD_ATTRIBUTE);
                }
                stencil_size = attrib_list[i+1];
                break;
            case EGL_SURFACE_TYPE:
                surface_type = attrib_list[i+1];
                break;
            case EGL_TRANSPARENT_TYPE:
                if(attrib_list[i+1] != EGL_NONE && attrib_list[i+1] != EGL_TRANSPARENT_RGB ) {
                    RETURN_ERROR(EGL_FALSE,EGL_BAD_ATTRIBUTE);
                }
                transparent_type = attrib_list[i+1];
                break;
            case EGL_TRANSPARENT_RED_VALUE:
                trans_red_val = attrib_list[i+1];
                break;
            case EGL_TRANSPARENT_GREEN_VALUE:
                trans_green_val = attrib_list[i+1];
                break;
            case EGL_TRANSPARENT_BLUE_VALUE:
                trans_blue_val = attrib_list[i+1];
                break;
            default:
                RETURN_ERROR(EGL_FALSE,EGL_BAD_ATTRIBUTE);
            }
            i+=2;
        }
        if(hasConfigId) {
            EglConfig* pConfig = dpy->getConfig(config_id);
            if(pConfig) {
                if(configs) {
                    configs[0]  = static_cast<EGLConfig>(pConfig);
                }
                *num_config = 1;
                return EGL_TRUE;
            } else {
                RETURN_ERROR(EGL_FALSE,EGL_BAD_ATTRIBUTE);
            }
        }
    }
    EglConfig dummy(red_size,green_size,blue_size,alpha_size,caveat,config_id,depth_size,
                    frame_buffer_level,0,0,0,native_renderable,renderable_type,0,native_visual_type,
                    samples_per_pixel,stencil_size,surface_type,transparent_type,
                    trans_red_val,trans_green_val,trans_blue_val,NULL);

    *num_config = dpy->chooseConfigs(dummy,configs,config_size);


    return EGL_TRUE;
}
コード例 #19
0
int read_cfmask
(
    int  curr_scene_num, /* I:   current num. in list of scenes to read       */
    char *data_type,     /* I:   type of flies, tifs or single BIP            */
    char **scene_list,   /* I:   current scene name in list of sceneIDs       */
    int  row,            /* I:   the row (Y) location within img/grid         */
    int  col,            /* I:   the col (X) location within img/grid         */
    int  num_samples,    /* I:   number of image samples (X width)            */
    FILE ***fp_tifs,     /* I/O: file ptr array for tif band file names       */
    FILE **fp_bip,       /* I/O: file pointer array for BIP file names        */
    unsigned char *fmask_buf,/* O:   pointer to cfmask band values            */
                         /* I/O: Worldwide Reference System path and row for  */
                         /* I/O: the current swath, this group of variables   */
                         /* I/O: is for filtering out swath overlap, and      */
    int *prev_wrs_path,  /* I/O: using the first of two scenes in a swath,    */
    int *prev_wrs_row,   /* I/O: , because it is recommended to use the meta  */
    int *prev_year,      /* I/O: data from the first for things like sun      */
    int *prev_jday,      /* I/O: angle, etc. However, always removing a       */
    unsigned char *prev_fmask_buf,/* I/O: redundant x/y location specified    */
    int *valid_scene_count,/* I/O: x/y is not always valid for gridded data,  */
    int *swath_overlap_count,/* I/O: it may/may not be in swap overlap area.  */
    char **valid_scene_list,/* I/O: 2-D array for list of filtered            */
    int *clear_sum,      /* I/O: Total number of clear cfmask pixels          */
    int *water_sum,      /* I/O: counter for cfmask water pixels.             */
    int *shadow_sum,     /* I/O: counter for cfmask shadow pixels.            */
    int *sn_sum,         /* I/O: Total number of snow cfmask pixels           */
    int *cloud_sum,      /* I/O: counter for cfmask cloud pixels.             */
    int *fill_sum,       /* I/O: counter for cfmask fill pixels.              */
    int *all_sum,        /* I/O: Total of all cfmask pixels                   */
    unsigned char *updated_fmask_buf, /* I/O: new entry in valid fmask values */
    int *updated_sdate_array, /* I/O: new buf of valid date values            */
    int *sdate,          /* I:   Original array of julian date values         */
    int *valid_num_scenes/* I/O: number of valid scenes after reading cfmask  */
)

{

    int len;             /* for strlen call                             */
    int landsat_number;  /* mission number for determining file names   */
    char scene_name[MAX_STR_LEN]; /* current scene id name              */
    char filename[MAX_STR_LEN];   /* temp for constructing file name    */
    int wrs_path;        /* Worldwide Reference System path             */
    int wrs_row = 0;     /* WRS row                                     */
    int year;            /* Year of acquisition date of current scene   */
    int jday;            /* Julian day since 0 of current scene date    */
    bool debug = 1;      /* for debug printing                          */
    int status;          /* for return status of function calls         */
    char short_scene[MAX_STR_LEN]; /* for parsing file names            */
    char directory[MAX_STR_LEN]; /* for parsing file names              */
    char tmpstr[MAX_STR_LEN]; /* for parsing file names                 */
    char errmsg[MAX_STR_LEN]; /* for printing errors before log/quit    */
    char FUNC_NAME[] = "read_cfmask"; /* for printing errors messages   */
    int int_buf;         /* for reading cfmask value then type cast     */

    if (strcmp(data_type, "tifs") == 0)
    {

        /**************************************************************/
        /*                                                            */
        /* Determine the cfmask file name to read.                    */
        /*                                                            */
        /**************************************************************/
    
        len = strlen(scene_list[curr_scene_num]);
        landsat_number = atoi(sub_string(scene_list[curr_scene_num],(len-19),1));
        wrs_path = atoi(sub_string(scene_list[curr_scene_num],(len-18),3));
        wrs_row =  atoi(sub_string(scene_list[curr_scene_num],(len-15),3));
        year = atoi(sub_string(scene_list[curr_scene_num],(len-12),4));
        jday = atoi(sub_string(scene_list[curr_scene_num],(len- 8),3));
        sprintf(filename, "%s_cfmask.img", scene_list[curr_scene_num]);
    
        /**************************************************************/
        /*                                                            */
        /* Open the cfmask file, fseek and read.                      */
        /* if the path, year, and jdate of adjacent sorted scenes are */
        /* the same, and the rows are different by 1, and both fmask  */
        /* values are NOT fill, then this is a case of swath (pixel)  */
        /* overlap, so use the lesser row number of the two, and      */
        /* throw away the grerater row of the two, and update the     */
        /* valid scene list accordingly.   If only one of the two     */
        /* fmask values are FILL, then we are not in an area of swath */
        /* overlap, and the later check for fill will elinimate the   */
        /* uneccesary scene pixels.                                   */
        /*                                                            */
        /**************************************************************/
    
        fp_tifs[CFMASK_BAND][curr_scene_num] = open_raw_binary(filename,"rb");
        if (fp_tifs[CFMASK_BAND][curr_scene_num] == NULL)
            printf("error open %d scene, %d bands files\n", curr_scene_num, CFMASK_BAND+1);
    
        fseek(fp_tifs[CFMASK_BAND][curr_scene_num], (row * num_samples + col)*sizeof(unsigned char), 
            SEEK_SET);
    
        if (read_raw_binary(fp_tifs[CFMASK_BAND][curr_scene_num], 1, 1,
            sizeof(unsigned char), &fmask_buf[curr_scene_num]) != 0)
            printf("error reading %d scene, %d bands\n", curr_scene_num, CFMASK_BAND+1);

        close_raw_binary(fp_tifs[CFMASK_BAND][curr_scene_num]);
    }

    else if (strcmp(data_type, "bip") == 0)

    {

        len = strlen(scene_list[curr_scene_num]);
        strncpy(short_scene, scene_list[curr_scene_num], len-5);
        split_directory_scenename(scene_list[curr_scene_num], directory, scene_name);
        if (strncmp(short_scene, ".", 1) == 0)
        {
            strncpy(tmpstr, short_scene + 2, len - 2);
            sprintf(filename, "%s/%s_MTLstack", tmpstr, scene_name);
        }
        else
            sprintf(filename, "%s/%s_MTLstack", short_scene, scene_name);
        fp_bip[curr_scene_num] = open_raw_binary(filename,"rb");
        if (fp_bip[curr_scene_num] == NULL)
        {
            sprintf(errmsg, "Opening %d scene files\n", curr_scene_num);
            RETURN_ERROR (errmsg, FUNC_NAME, ERROR);
        }
        fseek(fp_bip[curr_scene_num], ((row - 1)* num_samples + col - 1) *
              TOTAL_BANDS * sizeof(short int) + (TOTAL_IMAGE_BANDS * sizeof(short int)), SEEK_SET);

        if (read_raw_binary(fp_bip[curr_scene_num], 1, 1,
                sizeof(short int), &int_buf) != 0)
        {
            sprintf(errmsg, "error reading %d scene, %d bands\n",curr_scene_num, CFMASK_BAND+1);
            RETURN_ERROR(errmsg, FUNC_NAME, FAILURE);
        }

        fmask_buf[curr_scene_num] = (unsigned char)int_buf;

        close_raw_binary(fp_bip[curr_scene_num]);

    }

    /******************************************************************/
    /*                                                                */
    /* Check for swath overlap pixels.  If consecutive temporal       */
    /* are in the same path, and in adjacent rows, are not fill, and  */
    /* have the same acquisition date, then they are essentially the  */
    /* same pixel, so use the first, because the metadata such as     */
    /* sun angle, etc. are more closely associated with the first.    */
    /*                                                                */
    /******************************************************************/

    if ((wrs_path == *prev_wrs_path) && (wrs_row == (*prev_wrs_row - 1)) &&
        (year == *prev_year) && (jday == *prev_jday) &&
        (fmask_buf[curr_scene_num] != CFMASK_FILL) && (*prev_fmask_buf != CFMASK_FILL))

    {
        (*swath_overlap_count)++;
        strcpy(valid_scene_list[(*valid_scene_count) - 1], scene_list[curr_scene_num]);
        if (debug)
        {
            printf("i = %d swath overlap %s\n", curr_scene_num, scene_list[curr_scene_num -1]);
        }
    }

    else

    {
        strcpy(valid_scene_list[*valid_scene_count], scene_list[curr_scene_num]);

        /**************************************************************/
        /*                                                            */
        /* Call the function with the case statement for totalling    */
        /* cfmask values, because it is used for all input type       */
        /* options, and we put it in a function so we did not have to */
        /* make multiple updates if something changed.                */
        /*                                                            */
        /**************************************************************/

        status = assign_cfmask_values (fmask_buf[curr_scene_num], clear_sum,
                                       water_sum, shadow_sum, sn_sum,
                                       cloud_sum, fill_sum, all_sum);
        if (status != SUCCESS)
        {
            RETURN_ERROR ("Calling assign_cfmask_values", 
                          "read_cfmask", FAILURE);
        }

        /**************************************************************/
        /*                                                            */
        /* After succesfully reading the cfmask data, update the list */
        /* of valid julian dates.                                     */
        /*                                                            */
        /**************************************************************/

        if (fmask_buf[curr_scene_num] < CFMASK_FILL)
        {
            updated_fmask_buf[*valid_scene_count] = fmask_buf[curr_scene_num];
            updated_sdate_array[*valid_scene_count] = sdate[curr_scene_num];
            (*valid_scene_count)++;
            (*valid_num_scenes)++;
        }
    }

    *prev_wrs_path = wrs_path;
    *prev_wrs_row  = wrs_row;
    *prev_year = year;
    *prev_jday = jday;
    *prev_fmask_buf = fmask_buf[curr_scene_num];

    return(SUCCESS);

}
コード例 #20
0
EGLAPI EGLBoolean EGLAPIENTRY eglMakeCurrent(EGLDisplay display,
                                             EGLSurface draw,
                                             EGLSurface read,
                                             EGLContext context) {
    VALIDATE_DISPLAY(display);

    bool releaseContext = EglValidate::releaseContext(context, read, draw);
    if(!releaseContext && EglValidate::badContextMatch(context, read, draw)) {
        RETURN_ERROR(EGL_FALSE, EGL_BAD_MATCH);
    }

    ThreadInfo* thread = getThreadInfo();
    ContextPtr prevCtx = thread->eglContext;

    if(releaseContext) { //releasing current context
       if(prevCtx.Ptr()) {
           g_eglInfo->getIface(prevCtx->version())->flush();
           if(!dpy->nativeType()->makeCurrent(NULL,NULL,NULL)) {
               RETURN_ERROR(EGL_FALSE,EGL_BAD_ACCESS);
           }
           thread->updateInfo(ContextPtr(NULL),dpy,NULL,ShareGroupPtr(NULL),dpy->getManager(prevCtx->version()));
       }
    } else { //assining new context
        VALIDATE_CONTEXT(context);
        VALIDATE_SURFACE(draw,newDrawSrfc);
        VALIDATE_SURFACE(read,newReadSrfc);

        EglSurface* newDrawPtr = newDrawSrfc.Ptr();
        EglSurface* newReadPtr = newReadSrfc.Ptr();
        ContextPtr  newCtx     = ctx;

        if (newCtx.Ptr() && prevCtx.Ptr()) {
            if (newCtx.Ptr() == prevCtx.Ptr()) {
                if (newDrawPtr == prevCtx->draw().Ptr() &&
                    newReadPtr == prevCtx->read().Ptr()) {
                    // nothing to do
                    return EGL_TRUE;
                }
            }
            else {
                // Make sure previous context is detached from surfaces
                releaseContext = true;
            }
        }

        //surfaces compatibility check
        if(!((*ctx->getConfig()).compatibleWith((*newDrawPtr->getConfig()))) ||
           !((*ctx->getConfig()).compatibleWith((*newReadPtr->getConfig())))) {
            RETURN_ERROR(EGL_FALSE,EGL_BAD_MATCH);
        }

         EglOS::Display* nativeDisplay = dpy->nativeType();
         EglOS::Surface* nativeRead = newReadPtr->native();
         EglOS::Surface* nativeDraw = newDrawPtr->native();
        //checking native window validity
        if(newReadPtr->type() == EglSurface::WINDOW &&
                !nativeDisplay->isValidNativeWin(nativeRead)) {
            RETURN_ERROR(EGL_FALSE,EGL_BAD_NATIVE_WINDOW);
        }
        if(newDrawPtr->type() == EglSurface::WINDOW &&
                !nativeDisplay->isValidNativeWin(nativeDraw)) {
            RETURN_ERROR(EGL_FALSE,EGL_BAD_NATIVE_WINDOW);
        }

        if(prevCtx.Ptr()) {
            g_eglInfo->getIface(prevCtx->version())->flush();
        }
        if (!dpy->nativeType()->makeCurrent(
                newReadPtr->native(),
                newDrawPtr->native(),
                newCtx->nativeType())) {
               RETURN_ERROR(EGL_FALSE,EGL_BAD_ACCESS);
        }
        //TODO: handle the following errors
        // EGL_BAD_CURRENT_SURFACE , EGL_CONTEXT_LOST  , EGL_BAD_ACCESS

        thread->updateInfo(newCtx,dpy,newCtx->getGlesContext(),newCtx->getShareGroup(),dpy->getManager(newCtx->version()));
        newCtx->setSurfaces(newReadSrfc,newDrawSrfc);
        g_eglInfo->getIface(newCtx->version())->initContext(newCtx->getGlesContext(),newCtx->getShareGroup());

        // Initialize the GLES extension function table used in
        // eglGetProcAddress for the context's GLES version if not
        // yet initialized. We initialize it here to make sure we call the
        // GLES getProcAddress after when a context is bound.
        g_eglInfo->initClientExtFuncTable(newCtx->version());
    }

    // release previous context surface binding
    if(prevCtx.Ptr() && releaseContext) {
        prevCtx->setSurfaces(SurfacePtr(NULL),SurfacePtr(NULL));
    }

    return EGL_TRUE;
}
コード例 #21
0
ファイル: fm_sp.c プロジェクト: 2trill2spill/freebsd
t_Error FmSpBuildBufferStructure(t_FmSpIntContextDataCopy   *p_FmSpIntContextDataCopy,
                                 t_FmBufferPrefixContent     *p_BufferPrefixContent,
                                 t_FmSpBufMargins            *p_FmSpBufMargins,
                                 t_FmSpBufferOffsets         *p_FmSpBufferOffsets,
                                 uint8_t                     *internalBufferOffset)
{
    uint32_t                        tmp;

    SANITY_CHECK_RETURN_ERROR(p_FmSpIntContextDataCopy,  E_INVALID_VALUE);
    ASSERT_COND(p_FmSpIntContextDataCopy);
    ASSERT_COND(p_BufferPrefixContent);
    ASSERT_COND(p_FmSpBufMargins);
    ASSERT_COND(p_FmSpBufferOffsets);

    /* Align start of internal context data to 16 byte */
    p_FmSpIntContextDataCopy->extBufOffset =
        (uint16_t)((p_BufferPrefixContent->privDataSize & (OFFSET_UNITS-1)) ?
            ((p_BufferPrefixContent->privDataSize + OFFSET_UNITS) & ~(uint16_t)(OFFSET_UNITS-1)) :
             p_BufferPrefixContent->privDataSize);

    /* Translate margin and intContext params to FM parameters */
    /* Initialize with illegal value. Later we'll set legal values. */
    p_FmSpBufferOffsets->prsResultOffset = (uint32_t)ILLEGAL_BASE;
    p_FmSpBufferOffsets->timeStampOffset = (uint32_t)ILLEGAL_BASE;
    p_FmSpBufferOffsets->hashResultOffset= (uint32_t)ILLEGAL_BASE;
    p_FmSpBufferOffsets->pcdInfoOffset   = (uint32_t)ILLEGAL_BASE;

    /* Internally the driver supports 4 options
       1. prsResult/timestamp/hashResult selection (in fact 8 options, but for simplicity we'll
          relate to it as 1).
       2. All IC context (from AD) not including debug.*/

    /* This 'if' covers option 2. We copy from beginning of context. */
    if (p_BufferPrefixContent->passAllOtherPCDInfo)
    {
        p_FmSpIntContextDataCopy->size = 128; /* must be aligned to 16 */
        /* Start copying data after 16 bytes (FD) from the beginning of the internal context */
        p_FmSpIntContextDataCopy->intContextOffset = 16;

        if (p_BufferPrefixContent->passAllOtherPCDInfo)
            p_FmSpBufferOffsets->pcdInfoOffset = p_FmSpIntContextDataCopy->extBufOffset;
        if (p_BufferPrefixContent->passPrsResult)
            p_FmSpBufferOffsets->prsResultOffset =
                (uint32_t)(p_FmSpIntContextDataCopy->extBufOffset + 16);
        if (p_BufferPrefixContent->passTimeStamp)
            p_FmSpBufferOffsets->timeStampOffset =
                (uint32_t)(p_FmSpIntContextDataCopy->extBufOffset + 48);
        if (p_BufferPrefixContent->passHashResult)
            p_FmSpBufferOffsets->hashResultOffset =
                (uint32_t)(p_FmSpIntContextDataCopy->extBufOffset + 56);
    }
    else
    {
        /* This case covers the options under 1 */
        /* Copy size must be in 16-byte granularity. */
        p_FmSpIntContextDataCopy->size =
            (uint16_t)((p_BufferPrefixContent->passPrsResult ? 32 : 0) +
                      ((p_BufferPrefixContent->passTimeStamp ||
                      p_BufferPrefixContent->passHashResult) ? 16 : 0));

        /* Align start of internal context data to 16 byte */
        p_FmSpIntContextDataCopy->intContextOffset =
            (uint8_t)(p_BufferPrefixContent->passPrsResult ? 32 :
                      ((p_BufferPrefixContent->passTimeStamp  ||
                       p_BufferPrefixContent->passHashResult) ? 64 : 0));

        if (p_BufferPrefixContent->passPrsResult)
            p_FmSpBufferOffsets->prsResultOffset = p_FmSpIntContextDataCopy->extBufOffset;
        if (p_BufferPrefixContent->passTimeStamp)
            p_FmSpBufferOffsets->timeStampOffset =  p_BufferPrefixContent->passPrsResult ?
                                        (p_FmSpIntContextDataCopy->extBufOffset + sizeof(t_FmPrsResult)) :
                                        p_FmSpIntContextDataCopy->extBufOffset;
        if (p_BufferPrefixContent->passHashResult)
            /* If PR is not requested, whether TS is requested or not, IC will be copied from TS */
            p_FmSpBufferOffsets->hashResultOffset = p_BufferPrefixContent->passPrsResult ?
                                          (p_FmSpIntContextDataCopy->extBufOffset + sizeof(t_FmPrsResult) + 8) :
                                          p_FmSpIntContextDataCopy->extBufOffset + 8;
    }

    if (p_FmSpIntContextDataCopy->size)
        p_FmSpBufMargins->startMargins =
            (uint16_t)(p_FmSpIntContextDataCopy->extBufOffset +
                       p_FmSpIntContextDataCopy->size);
    else
        /* No Internal Context passing, STartMargin is immediately after privateInfo */
        p_FmSpBufMargins->startMargins = p_BufferPrefixContent->privDataSize;

    /* save extra space for manip in both external and internal buffers */
    if (p_BufferPrefixContent->manipExtraSpace)
    {
        uint8_t extraSpace;
#ifdef FM_CAPWAP_SUPPORT
        if ((p_BufferPrefixContent->manipExtraSpace + CAPWAP_FRAG_EXTRA_SPACE) >= 256)
            RETURN_ERROR(MAJOR, E_INVALID_VALUE,
                         ("p_BufferPrefixContent->manipExtraSpace should be less than %d",
                          256-CAPWAP_FRAG_EXTRA_SPACE));
        extraSpace = (uint8_t)(p_BufferPrefixContent->manipExtraSpace + CAPWAP_FRAG_EXTRA_SPACE);
#else
        extraSpace = p_BufferPrefixContent->manipExtraSpace;
#endif /* FM_CAPWAP_SUPPORT */
        p_FmSpBufferOffsets->manipOffset = p_FmSpBufMargins->startMargins;
        p_FmSpBufMargins->startMargins += extraSpace;
        *internalBufferOffset = extraSpace;
    }

    /* align data start */
    tmp = (uint32_t)(p_FmSpBufMargins->startMargins % p_BufferPrefixContent->dataAlign);
    if (tmp)
        p_FmSpBufMargins->startMargins += (p_BufferPrefixContent->dataAlign-tmp);
    p_FmSpBufferOffsets->dataOffset = p_FmSpBufMargins->startMargins;

    return E_OK;
}
コード例 #22
0
ファイル: daConsole.c プロジェクト: AshleyDeSimone/edk2
/* Write a NULL terminated WCS to the EFI console.

  @param[in,out]  BufferSize  Number of bytes in Buffer.  Set to zero if
                              the string couldn't be displayed.
  @param[in]      Buffer      The WCS string to be displayed

  @return   The number of characters written.
*/
static
ssize_t
EFIAPI
da_ConWrite(
  IN  struct __filedes     *filp,
  IN  off_t                *Position,
  IN  size_t                BufferSize,
  IN  const void           *Buffer
  )
{
  EFI_STATUS                          Status;
  EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL    *Proto;
  ConInstance                        *Stream;
  ssize_t                             NumChar;
  //XYoffset                            CursorPos;

  Stream = BASE_CR(filp->f_ops, ConInstance, Abstraction);
  // Quick check to see if Stream looks reasonable
  if(Stream->Cookie != CON_COOKIE) {    // Cookie == 'IoAb'
    EFIerrno = RETURN_INVALID_PARAMETER;
    return -1;    // Looks like a bad This pointer
  }
  if(Stream->InstanceNum == STDIN_FILENO) {
    // Write is not valid for stdin
    EFIerrno = RETURN_UNSUPPORTED;
    return -1;
  }
  // Everything is OK to do the write.
  Proto = (EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *)Stream->Dev;

  // Convert string from MBCS to WCS and translate \n to \r\n.
  NumChar = WideTtyCvt(gMD->UString, (const char *)Buffer, BufferSize);
  //if(NumChar > 0) {
  //  BufferSize = (size_t)(NumChar * sizeof(CHAR16));
  //}
  BufferSize = NumChar;

  //if( Position != NULL) {
  //  CursorPos.Offset = (UINT64)*Position;

  //  Status = Proto->SetCursorPosition(Proto,
  //                                    (INTN)CursorPos.XYpos.Column,
  //                                    (INTN)CursorPos.XYpos.Row);
  //  if(RETURN_ERROR(Status)) {
  //    return -1;
  //  }
  //}

  // Send the Unicode buffer to the console
  Status = Proto->OutputString( Proto, gMD->UString);
  // Depending on status, update BufferSize and return
  if(RETURN_ERROR(Status)) {
    BufferSize = 0;    // We don't really know how many characters made it out
  }
  else {
    //BufferSize = NumChar;
    Stream->NumWritten += NumChar;
  }
  EFIerrno = Status;
  return BufferSize;
}
コード例 #23
0
ファイル: myhdf.c プロジェクト: Jwely/ledaps
bool GetAttrDouble(int32 sds_id, Myhdf_attr_t *attr, double *val)
/* 
!C******************************************************************************

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

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

!Team Unique Header:

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

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

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

  return true;
}
コード例 #24
0
/*****************************************************************************
  NAME:  GetXMLInput

  PURPOSE:  Find the files needed by this application in the XML file and open
            them.

  RETURN VALUE:  Type = int
      Value    Description
      -------  ---------------------------------------------------------------
      SUCCESS  No errors were encountered.
      ERROR    An error was encountered.
*****************************************************************************/
int
GetXMLInput
(
    Espa_internal_meta_t *metadata, /* I: input metadata */
    bool use_toa_flag,              /* I: use TOA or SR data */
    char *dem_filename,             /* I: the name of the DEM file */
    Input_Data_t *input_data        /* O: updated with information from XML */
)
{
    int index;
    char msg[256];

    char product_name[30];
    char blue_band_name[30];
    char green_band_name[30];
    char red_band_name[30];
    char nir_band_name[30];
    char swir1_band_name[30];
    char swir2_band_name[30];

    /* Figure out the band names and product name to use */
    if ((strcmp (metadata->global.satellite, "LANDSAT_4") == 0)
        || (strcmp (metadata->global.satellite, "LANDSAT_5") == 0)
        || (strcmp (metadata->global.satellite, "LANDSAT_7") == 0))
    {
        if (use_toa_flag)
        {
            snprintf (product_name, sizeof (product_name), "toa_refl");

            snprintf (blue_band_name, sizeof (blue_band_name), "toa_band1");
            snprintf (green_band_name, sizeof (green_band_name), "toa_band2");
            snprintf (red_band_name, sizeof (red_band_name), "toa_band3");
            snprintf (nir_band_name, sizeof (nir_band_name), "toa_band4");
            snprintf (swir1_band_name, sizeof (swir1_band_name), "toa_band5");
            snprintf (swir2_band_name, sizeof (swir2_band_name), "toa_band7");
        }
        else
        {
            snprintf (product_name, sizeof (product_name), "sr_refl");

            snprintf (blue_band_name, sizeof (blue_band_name), "sr_band1");
            snprintf (green_band_name, sizeof (green_band_name), "sr_band2");
            snprintf (red_band_name, sizeof (red_band_name), "sr_band3");
            snprintf (nir_band_name, sizeof (nir_band_name), "sr_band4");
            snprintf (swir1_band_name, sizeof (swir1_band_name), "sr_band5");
            snprintf (swir2_band_name, sizeof (swir2_band_name), "sr_band7");
        }
    }
    else if (strcmp (metadata->global.satellite, "LANDSAT_8") == 0)
    {
        if (use_toa_flag)
        {
            snprintf (product_name, sizeof (product_name), "toa_refl");

            snprintf (blue_band_name, sizeof (blue_band_name), "toa_band2");
            snprintf (green_band_name, sizeof (green_band_name), "toa_band3");
            snprintf (red_band_name, sizeof (red_band_name), "toa_band4");
            snprintf (nir_band_name, sizeof (nir_band_name), "toa_band5");
            snprintf (swir1_band_name, sizeof (swir1_band_name), "toa_band6");
            snprintf (swir2_band_name, sizeof (swir2_band_name), "toa_band7");
        }
        else
        {
            snprintf (product_name, sizeof (product_name), "sr_refl");

            snprintf (blue_band_name, sizeof (blue_band_name), "sr_band2");
            snprintf (green_band_name, sizeof (green_band_name), "sr_band3");
            snprintf (red_band_name, sizeof (red_band_name), "sr_band4");
            snprintf (nir_band_name, sizeof (nir_band_name), "sr_band5");
            snprintf (swir1_band_name, sizeof (swir1_band_name), "sr_band6");
            snprintf (swir2_band_name, sizeof (swir2_band_name), "sr_band7");
        }
    }
    else
    {
        RETURN_ERROR ("Error invalid satellite", MODULE_NAME, ERROR);
    }

    /* Scan the metadata searching for the bands to open */
    for (index = 0; index < metadata->nbands; index++)
    {
        /* Only look at the ones with the product name we are looking for */
        if (strcmp (metadata->band[index].product, product_name) == 0)
        {
            if (strcmp (metadata->band[index].name, blue_band_name) == 0)
            {
                open_band (metadata->band[index].file_name, input_data,
                           I_BAND_BLUE);

                if (metadata->band[index].data_type != ESPA_INT16)
                {
                    snprintf (msg, sizeof (msg),
                              "%s incompatable data type expecting INT16",
                              blue_band_name);
                    RETURN_ERROR(msg, MODULE_NAME, ERROR);
                }

                /* Always use this one for the lines and samples since
                   they will be the same for us, along with the pixel
                   size values */
                input_data->lines = metadata->band[index].nlines;
                input_data->samples = metadata->band[index].nsamps;
                input_data->x_pixel_size =
                    metadata->band[index].pixel_size[0];
                input_data->y_pixel_size =
                    metadata->band[index].pixel_size[1];

                /* Grab the scale factor for this band */
                input_data->scale_factor[I_BAND_BLUE] =
                    metadata->band[index].scale_factor;

                /* Grab the fill value for this band */
                input_data->fill_value[I_BAND_BLUE] =
                    metadata->band[index].fill_value;
            }
            else if (strcmp (metadata->band[index].name, green_band_name) == 0)
            {
                open_band (metadata->band[index].file_name, input_data,
                           I_BAND_GREEN);

                if (metadata->band[index].data_type != ESPA_INT16)
                {
                    snprintf (msg, sizeof (msg),
                              "%s incompatable data type expecting INT16",
                              green_band_name);
                    RETURN_ERROR(msg, MODULE_NAME, ERROR);
                }

                /* Grab the scale factor for this band */
                input_data->scale_factor[I_BAND_GREEN] =
                    metadata->band[index].scale_factor;

                /* Grab the fill value for this band */
                input_data->fill_value[I_BAND_GREEN] =
                    metadata->band[index].fill_value;
            }
            else if (strcmp (metadata->band[index].name, red_band_name) == 0)
            {
                open_band (metadata->band[index].file_name, input_data,
                           I_BAND_RED);

                if (metadata->band[index].data_type != ESPA_INT16)
                {
                    snprintf (msg, sizeof (msg),
                              "%s incompatable data type expecting INT16",
                              red_band_name);
                    RETURN_ERROR(msg, MODULE_NAME, ERROR);
                }

                /* Grab the scale factor for this band */
                input_data->scale_factor[I_BAND_RED] =
                    metadata->band[index].scale_factor;

                /* Grab the fill value for this band */
                input_data->fill_value[I_BAND_RED] =
                    metadata->band[index].fill_value;
            }
            else if (strcmp (metadata->band[index].name, nir_band_name) == 0)
            {
                open_band (metadata->band[index].file_name, input_data,
                           I_BAND_NIR);

                if (metadata->band[index].data_type != ESPA_INT16)
                {
                    snprintf (msg, sizeof (msg),
                              "%s incompatable data type expecting INT16",
                              nir_band_name);
                    RETURN_ERROR(msg, MODULE_NAME, ERROR);
                }

                /* Grab the scale factor for this band */
                input_data->scale_factor[I_BAND_NIR] =
                    metadata->band[index].scale_factor;

                /* Grab the fill value for this band */
                input_data->fill_value[I_BAND_NIR] =
                    metadata->band[index].fill_value;
            }
            else if (strcmp (metadata->band[index].name, swir1_band_name) == 0)
            {
                open_band (metadata->band[index].file_name, input_data,
                           I_BAND_SWIR1);

                if (metadata->band[index].data_type != ESPA_INT16)
                {
                    snprintf (msg, sizeof (msg),
                              "%s incompatable data type expecting INT16",
                              swir1_band_name);
                    RETURN_ERROR(msg, MODULE_NAME, ERROR);
                }

                /* Grab the scale factor for this band */
                input_data->scale_factor[I_BAND_SWIR1] =
                    metadata->band[index].scale_factor;

                /* Grab the fill value for this band */
                input_data->fill_value[I_BAND_SWIR1] =
                    metadata->band[index].fill_value;
            }
            else if (strcmp (metadata->band[index].name, swir2_band_name) == 0)
            {
                open_band (metadata->band[index].file_name, input_data,
                           I_BAND_SWIR2);

                if (metadata->band[index].data_type != ESPA_INT16)
                {
                    snprintf (msg, sizeof (msg),
                              "%s incompatable data type expecting INT16",
                              swir2_band_name);
                    RETURN_ERROR(msg, MODULE_NAME, ERROR);
                }

                /* Grab the scale factor for this band */
                input_data->scale_factor[I_BAND_SWIR2] =
                    metadata->band[index].scale_factor;

                /* Grab the fill value for this band */
                input_data->fill_value[I_BAND_SWIR2] =
                    metadata->band[index].fill_value;
            }
        }

        /* Search for the CFMASK band */
        if (!strcmp (metadata->band[index].product, "cfmask"))
        {
            if (!strcmp (metadata->band[index].name, "cfmask"))
            {
                open_band (metadata->band[index].file_name, input_data,
                           I_BAND_CFMASK);

                if (metadata->band[index].data_type != ESPA_UINT8)
                {
                    RETURN_ERROR("cfmask incompatable data type expecting"
                                 " UINT8", MODULE_NAME, ERROR);
                }

                /* Default to a no-op since CFMASK doesn't have a scale
                   factor */
                input_data->scale_factor[I_BAND_CFMASK] = 1.0;

                /* Grab the fill value for this band */
                input_data->fill_value[I_BAND_CFMASK] =
                    metadata->band[index].fill_value;
            }
        }
    }

    /* Add the DEM band to the list */
    open_band (dem_filename, input_data, I_BAND_DEM);
    /* Default to a no-op since DEM doesn't have a scale factor */
    input_data->scale_factor[I_BAND_DEM] = 1.0;
    /* Default so the variable is initialized
       The DEM should not have values this negative */
    input_data->fill_value[I_BAND_DEM] = -9999;

    /* Verify all the bands have something (all are required for DSWE) */
    for (index = 0; index < MAX_INPUT_BANDS; index++)
    {
        if (input_data->band_fd[index] == NULL ||
            input_data->band_name[index] == NULL)
        {
            ERROR_MESSAGE ("Error opening required input data", MODULE_NAME);

            close_input (input_data);
            return ERROR;
        }
    }

    return SUCCESS;
}
コード例 #25
0
ファイル: myhdf.c プロジェクト: Jwely/ledaps
bool GetAttrString(int32 sds_id, Myhdf_attr_t *attr, char *string)
/* 
!C******************************************************************************

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

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

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

!Team Unique Header:

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

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

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

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

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

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

  return true;
}
コード例 #26
0
static jdwpTransportError JNICALL
socketTransport_accept(jdwpTransportEnv* env, jlong acceptTimeout, jlong handshakeTimeout) 
{
    int socketLen, err;
    struct sockaddr_in socket;
    jlong startTime = (jlong)0;

    /*
     * Use a default handshake timeout if not specified - this avoids an indefinite
     * hang in cases where something other than a debugger connects to our port.
     */
    if (handshakeTimeout == 0) {
	handshakeTimeout = 2000;
    }
   
    do {
	/*
	 * If there is an accept timeout then we put the socket in non-blocking
	 * mode and poll for a connection.
	 */
        if (acceptTimeout > 0) {
	    int rv;
	    dbgsysConfigureBlocking(serverSocketFD, JNI_FALSE);
            startTime = dbgsysCurrentTimeMillis();
	    rv = dbgsysPoll(serverSocketFD, JNI_TRUE, JNI_FALSE, (long)acceptTimeout);
	    if (rv <= 0) {
	        /* set the last error here as could be overridden by configureBlocking */
	        if (rv == 0) {
	            setLastError(JDWPTRANSPORT_ERROR_IO_ERROR, "poll failed");
	        }
		/* restore blocking state */
	        dbgsysConfigureBlocking(serverSocketFD, JNI_TRUE);
	        if (rv == 0) {
	            RETURN_ERROR(JDWPTRANSPORT_ERROR_TIMEOUT, "timed out waiting for connection");
	        } else {		
		    return JDWPTRANSPORT_ERROR_IO_ERROR;
		}
	    }
	}   

	/*
	 * Accept the connection
	 */
	memset((void *)&socket,0,sizeof(struct sockaddr_in));
        socketLen = sizeof(socket);
        socketFD = dbgsysAccept(serverSocketFD,
                                (struct sockaddr *)&socket,
                                &socketLen);
        /* set the last error here as could be overridden by configureBlocking */
        if (socketFD < 0) {
	    setLastError(JDWPTRANSPORT_ERROR_IO_ERROR, "accept failed");
        }
	/* 
	 * Restore the blocking state - note that the accepted socket may be in 
	 * blocking or non-blocking mode (platform dependent). However as there
	 * is a handshake timeout set then it will go into non-blocking mode
	 * anyway for the handshake.
	 */
        if (acceptTimeout > 0) {
	    dbgsysConfigureBlocking(serverSocketFD, JNI_TRUE);
        }
        if (socketFD < 0) {
            return JDWPTRANSPORT_ERROR_IO_ERROR;
        }

	/* handshake with the debugger */
        err = handshake(socketFD, handshakeTimeout);

	/* 
	 * If the handshake fails then close the connection. If there if an accept
	 * timeout then we must adjust the timeout for the next poll.
	 */
        if (err) {
	    fprintf(stderr, "Debugger failed to attach: %s\n", getLastError());
	    dbgsysSocketClose(socketFD);        
	    socketFD = -1;
	    if (acceptTimeout > 0) {
                long endTime = dbgsysCurrentTimeMillis();
		acceptTimeout -= (endTime - startTime);
		if (acceptTimeout <= 0) {
                    setLastError(JDWPTRANSPORT_ERROR_IO_ERROR, 
			"timeout waiting for debugger to connect");
                    return JDWPTRANSPORT_ERROR_IO_ERROR;
		}
	    }
	} 
    } while (socketFD < 0);

    return JDWPTRANSPORT_ERROR_NONE;
}