Пример #1
0
void ast_context_add_switch2(struct ast_context *con, const char *value, const char *data, int eval, const char *registrar)
{
	if(!no_comp)
		printf("Executed ast_context_add_switch2(con, value=%s, data=%s, eval=%d, registrar=%s);\n", value, data, eval, registrar);
	if( dump_extensions ) {
		struct namelist *x;
		x = create_name((char*)value);
		strncpy(x->name2,data,100);
		if( eval ) {

			ADD_LAST(con->switches,x);

		} else {

			ADD_LAST(con->eswitches,x);
		}
	}
}
Пример #2
0
static InternetAddress*
lbabl_get_internet_address(LDAP *dir, LDAPMessage * e)
{
    InternetAddress *ia;
    BerElement *ber = NULL;
    char *attr;
    struct berval **vals;
    int i;
    gchar *email = NULL, *sn = NULL, *cn = NULL, *first = NULL;

    for (attr = ldap_first_attribute(dir, e, &ber);
	 attr != NULL; 
         attr = ldap_next_attribute(dir, e, ber)) {
	/*
	 * For each attribute, get the attribute name and values.
	 */
	if ((vals = ldap_get_values_len(dir, e, attr)) != NULL) {
	    for (i = 0; vals[i] != NULL; i++) {
		if ((g_ascii_strcasecmp(attr, "sn") == 0) && (!sn))
		    sn = g_strndup(vals[i]->bv_val, vals[i]->bv_len);
		if ((g_ascii_strcasecmp(attr, "cn") == 0) && (!cn))
		    cn = g_strndup(vals[i]->bv_val, vals[i]->bv_len);
		if ((g_ascii_strcasecmp(attr, "givenName") == 0) && (!first))
		    first = g_strndup(vals[i]->bv_val, vals[i]->bv_len);
		if ((g_ascii_strcasecmp(attr, "mail") == 0) && (!email))
		    email = g_strndup(vals[i]->bv_val, vals[i]->bv_len);
	    }
	    ldap_value_free_len(vals);
	}
        ldap_memfree(attr);
    }
    /*
     * Record will have e-mail (searched)
     */
    if(email == NULL) email = g_strdup("none");
    g_return_val_if_fail(email != NULL, NULL);

    if(!cn)
        cn = create_name(first, sn);
    ia = internet_address_mailbox_new(cn, email);
    g_free(email); g_free(sn); g_free(cn); g_free(first);

    return ia;
}
Пример #3
0
/* Function 'readSubset' returning a subset of image. The data type of the
   output image is float, regardless what the input data type is. It errors
   on complex data. The function expects to have the memory for the returning 
   image array already allocated. 
*/
void readSubset(char *fileName, int width, int height, int posX, int posY, 
		float *subset)
{
  FILE *fp;
  char dataFileName[255];
  int ii, kk;
  float *buffer;
  meta_parameters *meta = meta_read(fileName);
  int lines = meta->general->line_count;
  int samples = meta->general->sample_count;

  /* Check whether input parameters are feasible */
  assert (width > 0);
  assert (height > 0);
  assert (width < lines);
  assert (height < samples);
  assert (posX > 0);
  assert (posY > 0);
  assert ((posX+width) < samples);
  assert ((posY+height) < lines);
  if (meta->general->data_type > 5)
    printErr("   ERROR: 'readSubset' does not work on complex data!\n");

  /* Allocate memory for buffers */
  buffer = (float *) MALLOC(height*samples*sizeof(float));

  /* Open image file */
  create_name(dataFileName, fileName, ".img");
  fp = FOPEN(dataFileName, "rb");

  /* Read the appropriate data chunk */
  get_float_lines(fp, meta, posY, height, buffer);

  /* Fill in the subset buffer */
  for (ii=0; ii<height; ii++) 
    for (kk=0; kk<width; kk++) 
      subset[ii*width+kk] = buffer[ii*samples+posX+kk];

  /* Clean up */
  FCLOSE(fp);
  FREE(buffer);
  meta_free(meta);
}
Пример #4
0
/* ---------------------------------------------------------------------
 * daemon(): Public
 *    Become a daemon: go into the background, reset our process group,
 *    and clobber the current directory and stdin, stdout, stderr.
 *    Ideas for what needs to be done more or less stolen from BSD sources.
 *    Exits on failure, and complains vigorously!
 *
 */
void 
daemon(const char *progname, const char *logdir)
{
   int	len, retval, fd, errfd;
   char	path[PATH_LEN];	

   if ((retval=fork()) < 0)			/* Go into the background */
      fatal(progname, "daemon(): fork() failed");
   else if (retval)
      exit(0);

   if ((int) setsid() < 0)			/* Reset the process group */
      fatal(progname, "daemon(): setsid() failed");

   strcpy(path, logdir);

   if (chdir(path) < 0)				/* Clobber current directory */
      if (chdir("/") < 0)
         fatal(progname, "daemon(): chdir() failed");

   /* create a unique log file name */
   sprintf(path+strlen(path), "/%s", create_name(logdir, progname, "log"));

   if ((fd = open("/dev/null", O_RDWR, 0)) == -1)  /* Clobber stdin,stdout.. */
      fatal(progname, "daemon(): open() failed for /dev/null");

   if ((errfd = open(path, O_CREAT|O_APPEND|O_WRONLY, 0644)) == -1) {
      fprintf(stderr, "daemon(): open() failed for errorfile %s\n", path);
      fatal(progname, "daemon(): open() failed for errorfile");
   }

   if (dup2(fd, 0) < 0 || dup2(errfd, 1) < 0)
      fatal(progname, "daemon(): dup2() failed");

   /* Not much we can do if this dup2 fails - oh well, gotta ignore it */
   (void) dup2(errfd, 2);

   if ((fd > 2 && close(fd) < 0) || (errfd > 2 && close(errfd) < 0))
      fatal(progname, "daemon(): close() failed");

   return;

} /* daemon() */
Пример #5
0
int device_store(struct audio_device *dev, gboolean is_default)
{
	char value[64];
	char filename[PATH_MAX + 1];
	char src_addr[18], dst_addr[18];
	int offset = 0;

	if (!dev->path)
		return -EINVAL;

	ba2str(&dev->dst, dst_addr);
	ba2str(&dev->store, src_addr);

	create_name(filename, PATH_MAX, STORAGEDIR, src_addr, "audio");
	create_file(filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

	if (is_default)
		textfile_put(filename, "default", dst_addr);
	if (dev->headset) {
		snprintf(value, 64, "headset ");
		offset += strlen("headset ");
	}
	if (dev->gateway) {
		snprintf(value + offset, 64 - offset, "gateway ");
		offset += strlen("gateway ");
	}
	if (dev->sink) {
		snprintf(value + offset, 64 - offset, "sink ");
		offset += strlen("sink ");
	}
	if (dev->source) {
		snprintf(value + offset, 64 - offset, "source ");
		offset += strlen("source ");
	}
	if (dev->control) {
		snprintf(value + offset, 64 - offset, "control ");
		offset += strlen("control ");
	}
	if (dev->target)
		snprintf(value + offset, 64 - offset, "target");

	return textfile_put(filename, dst_addr, value);
}
Пример #6
0
int read_pairable_timeout(const char *src, int *timeout)
{
	char filename[PATH_MAX + 1], *str;

	create_name(filename, PATH_MAX, STORAGEDIR, src, "config");

	str = textfile_get(filename, "pairto");
	if (!str)
		return -ENOENT;

	if (sscanf(str, "%d", timeout) != 1) {
		free(str);
		return -ENOENT;
	}

	free(str);

	return 0;
}
Пример #7
0
static
FRESULT follow_path (	/* FR_OK(0): successful, !=0: error code */
	DIR *dj,			/* Directory object to return last directory and found object */
	const char *path	/* Full-path string to find a file or directory */
)
{
	FRESULT res;
	BYTE *dir;


	while (*path == ' ') path++;		/* Skip leading spaces */
	if (*path == '/') path++;			/* Strip heading separator */
	dj->sclust = 0;						/* Set start directory (always root dir) */

	if ((BYTE)*path <= ' ') {			/* Null path means the root directory */
		res = dir_rewind(dj);
		FatFs->buf[0] = 0;

	} else {							/* Follow path */
		for (;;) {
			res = create_name(dj, &path);	/* Get a segment */
			if (res != FR_OK) break;
			res = dir_find(dj);				/* Find it */
			if (res != FR_OK) {				/* Could not find the object */
				if (res == FR_NO_FILE && !*(dj->fn+11))
					res = FR_NO_PATH;
				break;
			}
			if (*(dj->fn+11)) break;		/* Last segment match. Function completed. */
			dir = FatFs->buf;				/* There is next segment. Follow the sub directory */
			if (!(dir[DIR_Attr] & AM_DIR)) { /* Cannot follow because it is a file */
				res = FR_NO_PATH; break;
			}
			dj->sclust =
#if _FS_FAT32
				((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | 
#endif
				LD_WORD(dir+DIR_FstClusLO);
		}
	}

	return res;
}
Пример #8
0
char* create_unique_name(struct name_list *l)
{
	char *name = NULL;

	do {
		free(name);
		name = create_name(l);
	} while (st_lookup_exact(&l->taken, name));

	/*
	 * The data pointer in the string tree merely needs to evaluate to true,
	 * because it will never be dereferenced. Using the name string itself
	 * is fine, even though it might not be a valid pointer in the future.
	 */
	if (st_add_string(&l->taken, name, name)) {
		free(name);
		return NULL;
	}

	return name;
}
Пример #9
0
static int
t1_delete(char *name, dns_rbt_t *rbt, isc_mem_t *mctx,
	  isc_result_t *dns_result)
{
	int		nprobs;
	dns_name_t	*dns_name;

	nprobs = 0;
	if (name && dns_result) {
		if (create_name(name, mctx, &dns_name) == 0) {
			*dns_result = dns_rbt_deletename(rbt, dns_name,
							 ISC_FALSE);
			delete_name(dns_name, mctx);
		} else {
			++nprobs;
		}
	} else {
		++nprobs;
	}
	return(nprobs);
}
Пример #10
0
static void register_connections_stored(const char *adapter)
{
	char filename[PATH_MAX + 1];
	char *pattern;
	struct stat st;
	GSList *list;
	bdaddr_t src;
	bdaddr_t default_src;
	int dev_id;

	create_name(filename, PATH_MAX, STORAGEDIR, adapter, "network");

	str2ba(adapter, &src);

	if (stat(filename, &st) < 0)
		return;

	if (!(st.st_mode & __S_IFREG))
		return;

	textfile_foreach(filename, parse_stored_connection, &src);

	/* Check default connection for current default adapter */
	bacpy(&default_src, BDADDR_ANY);
	dev_id = hci_get_route(&default_src);
	if (dev_id < 0 || hci_devba(dev_id, &default_src) < 0)
		return;

	if (bacmp(&default_src, &src) != 0)
		return;

	pattern = textfile_get(filename, "default");
	if (!pattern)
		return;

	list = find_connection_pattern(connection, pattern);
	if (!list)
		return;
	default_index = g_slist_position(connection_paths, list);
}
Пример #11
0
void print_params(const char *in,struct ARDOP_PARAMS *a,const char *sourceProgram)
{
 FILE *fp; char out[1024];

 create_name(out,in,".in");
 fp = FOPEN(out,"w");

 fprintf(fp,"ARDOP2.5 SAR Processing Parameter File (%s)\n",sourceProgram);
 fprintf(fp,"%i \t\t\t\t\t! Debug Flag                 \n", a->iflag);
 fprintf(fp,"%i \t\t\t\t\t! First line (from 0)        \n", a->ifirstline);
 fprintf(fp,"%i \t\t\t\t\t! Number of patches          \n", a->npatches);
 fprintf(fp,"%i \t\t\t\t\t! i,q byte samples to skip   \n", a->ifirst);
 fprintf(fp,"%i \t\t\t\t\t! Output lines per patch     \n", a->na_valid);
 fprintf(fp,"%i \t\t\t\t\t! Deskew flag            \n", a->deskew);
 fprintf(fp,"%i %i \t\t\t\t\t! 1st range sample, num samples \n",a->isave,a->nla);
 fprintf(fp,"%.8f %.10f %.10f\t\t\t! Dopp quad coefs(Hz/prf)\n",
         a->fd,a->fdd,a->fddd);
 fprintf(fp,"%9.1f \t\t\t\t! Earth Radius              \n",a->re);
 fprintf(fp,"%8.3f \t\t\t\t! Body fixed S/C velocity(m/s)\n",a->vel);
 fprintf(fp,"%8.3f \t\t\t\t! Spacecraft Height         \n",a->ht);
 fprintf(fp,"%8.3f \t\t\t\t! Range of first sample     \n",a->r00);
 fprintf(fp,"%8.3f \t\t\t\t! Pulse Repitition Freq.    \n",a->prf);
 fprintf(fp,"%f \t\t\t\t! Single look az. res.         \n", a->azres );
 fprintf(fp,"%i \t\t\t\t\t! Number of azimuth looks     \n", a->nlooks);
 fprintf(fp,"%E \t\t\t\t! Range sampling frequency (Hz) \n", a->fs);
 fprintf(fp,"%E \t\t\t\t! Chirp Slope (Hz/s)            \n", a->slope);
 fprintf(fp,"%E \t\t\t\t! Pulse Length (s)              \n", a->pulsedur);
 fprintf(fp,"%3.1f \t\t\t\t\t! Chirp extension         \n", a->nextend);
 fprintf(fp,"%f \t\t\t\t! Radar wavelength             \n", a->wavl);
 fprintf(fp,"%f \t\t\t\t! Range spectrum weight        \n", a->rhww);
 fprintf(fp,"%f %f \t\t\t! Bandwidth fractional trunc.\n", a->pctbw,a->pctbwaz);
 fprintf(fp,"%f %f %f %f     ! First patch slope,inter range,az\n",
     a->sloper, a->interr, a->slopea, a->intera);
 fprintf(fp,"%g %g %g %g     ! Delta per patch slope,inter range,az\n",
     a->dsloper, a->dinterr, a->dslopea, a->dintera);

 FCLOSE(fp);
 return;
}
Пример #12
0
static
FRESULT follow_path (	/* FR_OK(0): successful, !=0: error code */
	DIR *dj,			/* Directory object to return last directory and found object */
	BYTE *dir,			/* 32-byte working buffer */
	const char *path	/* Full-path string to find a file or directory */
)
{
	FRESULT res;


	while (*path == ' ') path++;		/* Skip leading spaces */
	if (*path == '/') path++;			/* Strip heading separator */
	dj->sclust = 0;						/* Set start directory (always root dir) */

	if ((BYTE)*path <= ' ') {			/* Null path means the root directory */
		res = dir_rewind(dj);
		dir[0] = 0;

	} else {							/* Follow path */
		for (;;) {
			res = create_name(dj, &path);	/* Get a segment */
			if (res != FR_OK) break;
			res = dir_find(dj, dir);		/* Find it */
			if (res != FR_OK) {				/* Could not find the object */
				if (res == FR_NO_FILE && !*(dj->fn+11))
					res = FR_NO_PATH;
				break;
			}
			if (*(dj->fn+11)) break;		/* Last segment match. Function completed. */
			if (!(dir[DIR_Attr] & AM_DIR)) { /* Cannot follow because it is a file */
				res = FR_NO_PATH; break;
			}
			dj->sclust = LD_CLUST(dir);
		}
	}

	return res;
}
Пример #13
0
int proxy_store(bdaddr_t *src, const char *uuid, const char *tty,
		const char *name, uint8_t ch, int opts, struct termios *ti)
{
	char filename[PATH_MAX + 1], key[32], src_addr[18], *value;
	unsigned int i;
	int pos, size, err;
	uint8_t *pti;

	ba2str(src, src_addr);

	create_name(filename, PATH_MAX, STORAGEDIR, src_addr, "proxy");
	create_file(filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

	if (!name)
		name = "Port Proxy Entity";

	size = MAX_LEN_UUID_STR + 16 + strlen(name) + sizeof(struct termios) * 2;
	value = g_malloc0(size);

	snprintf(key, 32, "%s", tty);

	/* tty uuid 00 0x0000 name:termios */
	pos = snprintf(value, size, "%s %d 0x%04X %s:", uuid, ch, opts, name);

	if (!ti)
		goto done;

	for (i = 0, pti = (uint8_t *) ti; i < sizeof(struct termios); i++, pti++)
		sprintf(value + pos + (i * 2), "%2.2X", *pti);

done:
	err = textfile_put(filename, key, value);
	g_free(value);

	return err;
}
Пример #14
0
 result_type operator()(ScalarType const & /*scal*/) const {
   mapped_host_scalar * p = new mapped_host_scalar(utils::type_to_string<ScalarType>::value());
   p->name_ = create_name(current_arg_, memory_, NULL);
   return container_ptr_type(p);
 }
Пример #15
0
static void detect_pipe_max (void)
{
  int read_fd;
  int write_fd;
  
  /* can be anything! */
  char *character = "a";
  char *pipe = NULL;
  
  gboolean available = TRUE;
  int w = 0;
  long wrote = 0;
  
  pipe = create_name ();
  if (pipe == NULL)
    {
      g_warning ("can't create test pipe name");
      return;
    }
 
  if (mkfifo (pipe, 0600) < 0)
    {
      g_warning ("unable to create test pipe...");
      g_free (pipe);
      
      return;
    }
 
  /* open both end of the pipe */
  read_fd = open (pipe, O_RDONLY | O_NONBLOCK);
  if (read_fd < 0)
    {
      cpio_removeFile (pipe);
      g_free (pipe);
      
      return;
    }
    
  write_fd = open (pipe, O_WRONLY | O_NONBLOCK);
  if (write_fd < 0)
    {
      cpio_closeFile (write_fd);
      cpio_removeFile (pipe);
      g_free (pipe);
      
      return;
    }

  while (available)
    {
      w = 0;
          
      cpio_write (write_fd, character, 1, &w);
      if (w < 0)
        available = FALSE;
      else
        wrote += w;
    }
    
  GST_DETECTED_PIPE_CAPACITY = wrote;
    
  cpio_closeFile (write_fd);    
  cpio_closeFile (read_fd);
  cpio_removeFile (pipe);
      
  g_free (pipe);  
}
Пример #16
0
int sr2gr_pixsiz(const char *infile, const char *outfile, float grPixSize)
{
	int    in_np,  in_nl;               /* input number of pixels,lines  */
	int    out_np, out_nl;              /* output number of pixels,lines */
	int    ii,line,band;
	float  oldX,oldY;
	float  sr2gr[MAX_IMG_SIZE];
	float  ml2gr[MAX_IMG_SIZE];
	int    a_lower[MAX_IMG_SIZE];
	int    lower[MAX_IMG_SIZE], upper[MAX_IMG_SIZE];
	float  a_ufrac[MAX_IMG_SIZE], a_lfrac[MAX_IMG_SIZE];
	float  ufrac[MAX_IMG_SIZE], lfrac[MAX_IMG_SIZE];
	float *ibuf1,*ibuf2,*obuf;
	char   infile_name[512],inmeta_name[512];
	char   outfile_name[512],outmeta_name[512];
	FILE  *fpi, *fpo;
	meta_parameters *in_meta;
	meta_parameters *out_meta;

        create_name (infile_name, infile, ".img");
        create_name (outfile_name, outfile, ".img");

        create_name (inmeta_name, infile, ".meta");
        create_name (outmeta_name, outfile, ".meta");

	in_meta  = meta_read(inmeta_name);
	out_meta = meta_copy(in_meta);
	in_nl = in_meta->general->line_count;
	in_np = in_meta->general->sample_count;
	
	if (in_meta->sar->image_type != 'S')
	{
            asfPrintError("sr2gr only works with slant range images!\n");
	}

      	oldX = in_meta->general->x_pixel_size * in_meta->sar->sample_increment;
	oldY = in_meta->general->y_pixel_size * in_meta->sar->line_increment;

        /* If user didn't specify a pixel size, make the pixels square & leave
           the y pixel size unchanged */
        if (grPixSize < 0)
            grPixSize = oldY;

	/*Update metadata for new pixel size*/
	out_meta->sar->time_shift  += ((in_meta->general->start_line)
				* in_meta->sar->azimuth_time_per_pixel);
	out_meta->sar->slant_shift -= ((in_meta->general->start_sample)
				* in_meta->general->x_pixel_size);
	out_meta->general->start_line   = 0.0;
	out_meta->general->start_sample = 0.0;
	out_meta->sar->azimuth_time_per_pixel *= grPixSize
					/ in_meta->general->y_pixel_size;
	out_meta->sar->line_increment   = 1.0;
        out_meta->sar->sample_increment = 1.0;
        if (out_meta->transform)
          out_meta->transform->target_pixel_size = grPixSize;	
	/*Create ground/slant and azimuth conversion vectors*/
	out_meta->sar->image_type       = 'G'; 
	out_meta->general->x_pixel_size = grPixSize;
	out_meta->general->y_pixel_size = grPixSize;
	sr2gr_vec(out_meta,oldX,grPixSize,sr2gr);
	ml_vec(oldY,grPixSize,ml2gr);

	out_np = MAX_IMG_SIZE;
	out_nl = MAX_IMG_SIZE;
	for (ii=MAX_IMG_SIZE-1; ii>0; ii--)
		if ((int)sr2gr[ii] > in_np)
			out_np = ii;
	for (ii=MAX_IMG_SIZE-1; ii>0; ii--)
		if ((int)ml2gr[ii] > in_nl)
			out_nl = ii;
	
	out_meta->general->line_count   = out_nl;
        out_meta->general->line_scaling *= (double)in_nl/(double)out_nl;
        out_meta->general->sample_scaling = 1;
	out_meta->general->sample_count = out_np;
	if (out_meta->projection) {
		out_meta->projection->perX = grPixSize;
		out_meta->projection->perY = grPixSize;
	}

	meta_write(out_meta,outmeta_name);
	
	fpi = fopenImage(infile_name,"rb");
	fpo = fopenImage(outfile_name,"wb");
	
	for (ii=0; ii<MAX_IMG_SIZE; ii++)
	{
		lower[ii] = (int) sr2gr[ii];
		upper[ii] = lower[ii] + 1;
		ufrac[ii] = sr2gr[ii] - (float) lower[ii];
		lfrac[ii] = 1.0 - ufrac[ii]; 
		
		a_lower[ii] = (int) ml2gr[ii];
		a_ufrac[ii] = ml2gr[ii] - (float) a_lower[ii];
		a_lfrac[ii] = 1.0 - a_ufrac[ii]; 
	}

	ibuf1 = (float *) MALLOC ((in_np+FUDGE_FACTOR)*sizeof(float));
	ibuf2 = (float *) MALLOC ((in_np+FUDGE_FACTOR)*sizeof(float));
	obuf = (float *) MALLOC (out_np*sizeof(float));

	/* Initialize input arrays to 0 */
	for (ii=0;ii<in_np+FUDGE_FACTOR;ii++) {
		ibuf1[ii]=ibuf2[ii]=0.0;
	}

        /* Get the band info */
        int bc = in_meta->general->band_count;
        char **band_name = extract_band_names(in_meta->general->bands, bc);

	/* Work dat magic! */
        for (band=0; band<bc; ++band) {
          asfPrintStatus("Working on band: %s\n", band_name[band]);
          for (line=0; line<out_nl; line++)
          {
            if (a_lower[line]+1 < in_nl)
            {
              get_band_float_line(fpi,in_meta,band,a_lower[line],  ibuf1);
              get_band_float_line(fpi,in_meta,band,a_lower[line]+1,ibuf2);
            }
            
            for (ii=0; ii<out_np; ii++)
            {
              int val00,val01,val10,val11,tmp1,tmp2;
              val00 = ibuf1[lower[ii]];
              val01 = ibuf1[upper[ii]];
              val10 = ibuf2[lower[ii]];
              val11 = ibuf2[upper[ii]];
              
              tmp1 = val00*lfrac[ii] + val01*ufrac[ii];
              tmp2 = val10*lfrac[ii] + val11*ufrac[ii];
              
              obuf[ii] = tmp1*a_lfrac[line] + tmp2*a_ufrac[line];
            }
            put_band_float_line(fpo,out_meta,band,line,obuf);
            asfLineMeter(line, out_nl);
          }
        }
        for (band=0; band<bc; ++band)
          FREE(band_name[band]);
        FREE(band_name);
        meta_free(in_meta);
        meta_free(out_meta);
	FCLOSE(fpi);
	FCLOSE(fpo);
	
        return TRUE;
}
Пример #17
0
void read_params(const char *pfile,struct ARDOP_PARAMS *gbla)
{
  char versionStr[255];
  float version=1.0;
  char buf[512];
  FILE *fp;

/*Open Parameter file.*/
  create_name(buf,pfile,".in");
  fp = FOPEN(buf,"r");

/*Determine file version.*/
  FILL(buf,255,fp); sscanf(buf,"%s", versionStr);
  if (0==strncmp("ARDOP",versionStr,5))
  {
    sscanf(versionStr,"ARDOP%f",&version);
/*      if (!quietflag) printf("   Parsing ARDOP input file, version %.2f\n",version);*/
  }
  else if (0==strncmp("AISP",versionStr,4))    // handle old-style .in files
  {
    sscanf(versionStr,"AISP%f", &version);
/*      if (!quietflag) printf("   Parsing ARDOP input file, version %.2f\n",version);*/
  }

  FILL(buf,255,fp);

/*Read in parameters.*/
  if (version<2.2)
  {/*File has encoded input and output names*/
      sscanf(buf,"%s",gbla->in1);
      FILL(buf,255,fp); sscanf(buf,"%s\n", gbla->out);
      FILL(buf,255,fp);
  }
  sscanf(buf,"%i\n", &gbla->iflag);

  if (version<2.0)
  {
    FILL(buf,255,fp); sscanf(buf,"%i\n", &gbla->nbytes);
    FILL(buf,255,fp); sscanf(buf,"%i\n", &gbla->ngood);
  }

  FILL(buf,255,fp); sscanf(buf,"%i\n", &gbla->ifirstline);
  FILL(buf,255,fp); sscanf(buf,"%i\n", &gbla->npatches);
  FILL(buf,255,fp); sscanf(buf,"%i\n", &gbla->ifirst);
  FILL(buf,255,fp); sscanf(buf,"%i\n", &gbla->na_valid);
  FILL(buf,255,fp); sscanf(buf,"%i\n", &gbla->deskew);

  if (version<2.0)
  {
    FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->caltone);
  }

  FILL(buf,255,fp); sscanf(buf,"%i %i\n", &gbla->isave,&gbla->nla);
  FILL(buf,255,fp); sscanf(buf,"%f %f %f\n", &gbla->fd,&gbla->fdd,&gbla->fddd);
  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->re);
  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->vel);
  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->ht);
  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->r00);
  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->prf);

  if (version<2.0)
  {
    FILL(buf,255,fp); sscanf(buf,"%f %f\n", &gbla->xmi,&gbla->xmq);
    FILL(buf,255,fp); sscanf(buf,"%s\n", gbla->iqflip);
  }

  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->azres);
  FILL(buf,255,fp); sscanf(buf,"%i\n", &gbla->nlooks);
  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->fs);
  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->slope);
  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->pulsedur);
  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->nextend);

  FILL(buf,255,fp);
  if (strstr(buf,"Secondary")!=NULL) /*Skip over secondary range migration section.*/
    { FILL(buf,255,fp); }
  sscanf(buf,"%f\n", &gbla->wavl);

  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->rhww);
  FILL(buf,255,fp); sscanf(buf,"%f %f\n", &gbla->pctbw,&gbla->pctbwaz);
  FILL(buf,255,fp); sscanf(buf,"%f %f %f %f\n",
     &gbla->sloper, &gbla->interr, &gbla->slopea, &gbla->intera);
  FILL(buf,255,fp); sscanf(buf,"%g %g %g %g\n",
     &gbla->dsloper, &gbla->dinterr, &gbla->dslopea, &gbla->dintera);

  FCLOSE(fp);
  return;
}
Пример #18
0
int
main(int argc, char *argv[])
{
  int seedX=-1,seedY=-1; 
  char szWrap[MAXNAME], szUnwrap[MAXNAME];
  meta_parameters *meta;

  logflag=0;

  while (currArg < (argc-2)) {
    char *key = argv[currArg++];
    if (strmatch(key,"-log")) {
      CHECK_ARG(1);
      strcpy(logFile,GET_ARG(1));
      fLog = FOPEN(logFile, "a");
      logflag = 1;
    }
    else if (strmatch(key,"-x")) {
      CHECK_ARG(1);
      sscanf(GET_ARG(1), "%d", &seedX);
    }
    else if (strmatch(key,"-y")) {
      CHECK_ARG(1);
      sscanf(GET_ARG(1), "%d", &seedY);
    }
    else {
      printf("\n   ***Invalid option: %s\n", argv[currArg-1]);
      usage(argv[0]);
    }
  }
  create_name(szWrap, argv[currArg++], ".img");
  create_name(szUnwrap, argv[currArg], ".img");

  printf("%s\n",date_time_stamp());
  printf("Program: escher\n\n");
  if (logflag) {
    StartWatchLog(fLog);
    printLog("Program: escher\n\n");
  }

  meta = meta_read(szWrap);
  wid = meta->general->sample_count;
  len = meta->general->line_count;
  if ((seedX==-1)&&(seedY==-1))
  {
  	seedX=wid/2;
  	seedY=len/2;
  }
  
  meta_write(meta, szUnwrap);
  

  size = wid*len;
  mask  = (Uchar *)calloc(size, sizeof(Uchar));
  im    = (Uchar *)calloc(size, sizeof(Uchar));
  phase = (float *)MALLOC(sizeof(float)*size);
  /*coh   = (float *)MALLOC(sizeof(float)*size);*/

  /* perform steps*/
  printf("\n   begin unwrapping phase...\n");
  loadWrappedPhase(szWrap);
  groundBorder();
  makeMask();
  
  doStats("   after makeMask():");

  installCordon("cordon");
  cutMask();

  doStats("   after cutMask():");

#if DO_DEBUG_CHECKS
  saveMask((char *)mask, "test");

  verifyCuts();                                           
#endif

  checkSeed(&seedX, &seedY);

  integratePhase(seedX, seedY);

  doStats("   after integratePhase():");

  finishUwp();

  saveMask(mask, szUnwrap);

  saveUwp(szUnwrap);
  
  /* clean up & save*/
  free(mask);
  free(im);
  free(phase);
  return(0);
}
Пример #19
0
int
main(int argc, char **argv) {
	char *command, *arg, buffer[1024];
	const char *whitespace;
	dns_name_t *name, *foundname;
	dns_fixedname_t fixedname;
	dns_rbt_t *rbt = NULL;
	int length, ch;
	isc_boolean_t show_final_mem = ISC_FALSE;
	isc_result_t result;
	void *data;

	progname = strrchr(*argv, '/');
	if (progname != NULL)
		progname++;
	else
		progname = *argv;

	while ((ch = isc_commandline_parse(argc, argv, "m")) != -1) {
		switch (ch) {
		case 'm':
			show_final_mem = ISC_TRUE;
			break;
		}
	}

	argc -= isc_commandline_index;
	argv += isc_commandline_index;
	POST(argv);

	if (argc > 1) {
		printf("Usage: %s [-m]\n", progname);
		exit(1);
	}

	setbuf(stdout, NULL);

	/*
	 * So isc_mem_stats() can report any allocation leaks.
	 */
	isc_mem_debugging = ISC_MEM_DEBUGRECORD;

	result = isc_mem_create(0, 0, &mctx);
	if (result != ISC_R_SUCCESS) {
		printf("isc_mem_create: %s: exiting\n",
		       dns_result_totext(result));
		exit(1);
	}

	result = dns_rbt_create(mctx, delete_name, NULL, &rbt);
	if (result != ISC_R_SUCCESS) {
		printf("dns_rbt_create: %s: exiting\n",
		       dns_result_totext(result));
		exit(1);
	}

	whitespace = " \t";

	while (fgets(buffer, sizeof(buffer), stdin) != NULL) {
		length = strlen(buffer);

		if (buffer[length - 1] != '\n') {
			printf("line to long (%lu max), ignored\n",
			       (unsigned long)sizeof(buffer) - 2);
			continue;
		}

		buffer[length - 1] = '\0';

		command = buffer + strspn(buffer, whitespace);

		if (*command == '#')
			continue;

		arg = strpbrk(command, whitespace);
		if (arg != NULL) {
			*arg++ = '\0';
			arg += strspn(arg, whitespace);
		}

		length = strlen(command);
		if (*command != '\0') {
			if (CMDCHECK("add")) {
				name = create_name(arg);
				if (name != NULL) {
					printf("adding name %s\n", arg);
					result = dns_rbt_addname(rbt,
								 name, name);
					PRINTERR(result);
				}

			} else if (CMDCHECK("delete")) {
				name = create_name(arg);
				if (name != NULL) {
					printf("deleting name %s\n", arg);
					result = dns_rbt_deletename(rbt, name,
								    ISC_FALSE);
					PRINTERR(result);
					delete_name(name, NULL);
				}

			} else if (CMDCHECK("nuke")) {
				name = create_name(arg);
				if (name != NULL) {
					printf("nuking name %s "
					       "and its descendants\n", arg);
					result = dns_rbt_deletename(rbt, name,
								    ISC_TRUE);
					PRINTERR(result);
					delete_name(name, NULL);
				}

			} else if (CMDCHECK("search")) {
				name = create_name(arg);
				if (name != NULL) {
					printf("searching for name %s ... ",
					       arg);

					dns_fixedname_init(&fixedname);
					foundname =
						dns_fixedname_name(&fixedname);
					data = NULL;

					result = dns_rbt_findname(rbt, name, 0,
								  foundname,
								  &data);
					switch (result) {
					case ISC_R_SUCCESS:
						printf("found exact: ");
						print_name(data);
						putchar('\n');
						break;
					case DNS_R_PARTIALMATCH:
						printf("found parent: ");
						print_name(data);
						printf("\n\t(foundname: ");
						print_name(foundname);
						printf(")\n");
						break;
					case ISC_R_NOTFOUND:
						printf("NOT FOUND!\n");
						break;
					case ISC_R_NOMEMORY:
						printf("OUT OF MEMORY!\n");
						break;
					default:
						printf("UNEXPECTED RESULT\n");
					}

					delete_name(name, NULL);
				}

			} else if (CMDCHECK("check")) {
				/*
				 * Or "chain".  I know, I know.  Lame name.
				 * I was having a hard time thinking of a
				 * name (especially one that did not have
				 * a conflicting first letter with another
				 * command) that would differentiate this
				 * from the search command.
				 *
				 * But it is just a test program, eh?
				 */
				name = create_name(arg);
				if (name != NULL) {
					detail(rbt, name);

					delete_name(name, NULL);
				}

			} else if (CMDCHECK("forward")) {
				iterate(rbt, ISC_TRUE);

			} else if (CMDCHECK("backward")) {
				iterate(rbt, ISC_FALSE);

			} else if (CMDCHECK("print")) {
				if (arg == NULL || *arg == '\0')
					dns_rbt_printall(rbt, NULL);
				else
					printf("usage: print\n");

			} else if (CMDCHECK("quit")) {
				if (arg == NULL || *arg == '\0')
					break;
				else
					printf("usage: quit\n");
			} else {
				printf("a(dd) NAME, d(elete) NAME, "
				       "s(earch) NAME, p(rint), or q(uit)\n");

			}
		}

	}

	dns_rbt_destroy(&rbt);

	if (show_final_mem)
		isc_mem_stats(mctx, stderr);

	return (0);
}
Пример #20
0
int main(int argc,char **argv)
{
  int lines,samps,start_line;   /* Number of image lines and samples          */
  int x,y,ii;                   /* Counters and the filter frequency indicies */
  char *inName, *outName;       /* Input filename                             */
  char metaName[256];           /* Name of meta file                          */
  complexFloat *inBuf;          /* Input/Output Image Buffers                 */
  complexFloat *fftBuf;         /* FFT Buffer for the image                   */
  float *ampBuf,*phsBuf;        /* Amplitude and Phase Buffers                */
  float df, freq[FFT_LEN], f_s; /* Frequency Vector                           */
  FILE *inF,*outF1;             /* Input and Output file pointers             */
  meta_parameters *meta;        /* Meta-file data pointer                     */

/* Usage is shown if the user doesn't give correct number of arguments */
  if(argc!=4) { usage(argv[0]); }

  StartWatch();

/* Get the filename and filter start and end frequencies from the command line */ 
  inName  = argv[1];
  outName = argv[2];
  start_line = atoi(argv[3]);
  create_name(metaName, inName, ".meta");

/* Get the PRF and number of samples from the meta-file */
  meta = meta_read(metaName);
  lines = FFT_LEN;
  samps = meta->general->sample_count;
  f_s   = 1/(meta->sar->azimuth_time_per_pixel);
  printf("Sampling Frequency is %f\n",f_s);

/* Compute the FFT length based on the number of lines. Must be a power of 2 */
  printf("FFT Length is %d\n",FFT_LEN);
  cfft1d(FFT_LEN,NULL,0);

/* Allocate the memory for all the buffers */
  inBuf  = (complexFloat *)MALLOC(sizeof(complexFloat)*samps*FFT_LEN);
  fftBuf = (complexFloat *)MALLOC(sizeof(complexFloat)*FFT_LEN);
  ampBuf = (float *)MALLOC(sizeof(float)*FFT_LEN);
  phsBuf = (float *)MALLOC(sizeof(float)*FFT_LEN);

  df = f_s/FFT_LEN;
  for(ii=0; ii<FFT_LEN; ii++)   freq[ii] = df*ii;

/* Open the Complex Image File */
  if((inF=FOPEN(inName,"rb"))==NULL) {	
    printf("Complex Image file %s could not be opened\n",inName);
    exit(EXIT_FAILURE);
  }

/* Zero out all the arrays and begin processing data */
  for(ii=0; ii<FFT_LEN; ii++) {
    ampBuf[ii]=0;
    phsBuf[ii]=0;
  }

/* Read in the data chunk */
  printf("Reading Data Starting at Line %d\n",start_line);
  get_complexFloat_lines(inF, meta, start_line, FFT_LEN, inBuf);

/* Process the each column, take the average at the end */
  printf("Performing the FFT\n");
  for(x=0; x<samps; x++) {
    if(x%500 == 0)  printf("Processing Column %d\n",x);

    for(y=0; y<FFT_LEN; y++) {
      fftBuf[y].real=0;
      fftBuf[y].imag=0;
    }

    for(y=0; y<lines; y++) {
      fftBuf[y].real=inBuf[y*samps+x].real;
      fftBuf[y].imag=inBuf[y*samps+x].imag;
    }

    cfft1d(FFT_LEN,fftBuf,-1);

    for (ii=0; ii<FFT_LEN; ii++) {
      ampBuf[ii] += sqrt(fftBuf[ii].real*fftBuf[ii].real
                         + fftBuf[ii].imag*fftBuf[ii].imag);	
      if(fftBuf[ii].imag!=0.0 || fftBuf[ii].real!=0.0)
        phsBuf[ii] += atan2(fftBuf[ii].imag, fftBuf[ii].real);
    }
  }
  printf("Finished the FFT\n");

/* Open and write output file */
  strcat(outName,".spectra"); 
  if((outF1=FOPEN(outName,"w"))==NULL) {
    printf("Unable to write output %s\n",outName);
    exit(EXIT_FAILURE);
  }
  for (ii=0; ii<FFT_LEN; ii++) {
    ampBuf[ii] /= samps;
    phsBuf[ii] /= samps;
    fprintf(outF1,"%f %f %f\n",freq[ii],ampBuf[ii],phsBuf[ii]);
  }

/* Close up & leave */
  meta_free(meta);
  FCLOSE(outF1);
  StopWatch();
  return 0;
}
Пример #21
0
/* Main program */
int main(int argc, char *argv[])
{
  FILE *fpLook=NULL, *fpIncid=NULL, *fpRange=NULL, *fpIn=NULL, *fpMask=NULL;
  meta_parameters *meta;
  stateVector stVec;
  int ii, kk, ll;
  char inFile[255], metaFile[255], dataFile[255], outLook[255], outIncid[255];
  char outRange[255], outBase[255], outFile[255], *maskFile=NULL; 
  char cmd[255], *bufMask=NULL;
  float *bufImage=NULL, *bufLook=NULL, *bufIncid=NULL, *bufRange=NULL;
  double latitude, longitude, time, doppler, earth_radius=0, satellite_height, range;
  double look_angle, incidence_angle, height;
  double line, sample, re=6378144.0, rp=6356754.9, px, py;
  double firstLook=0.0, firstIncid=0.0, firstRange=0.0;
  flag_indices_t flags[NUM_FLAGS];

  /* Set all flags to 'not set' */
  for (ii=0; ii<NUM_FLAGS; ii++) {
    flags[ii] = FLAG_NOT_SET;
  }
  
/**********************BEGIN COMMAND LINE PARSING STUFF**********************/
  /* Check to see if any options were provided */
  if (checkForOption("-help", argc, argv) != -1) /* Most important */
    help_page();
  flags[f_LOOK] = checkForOption("-look", argc, argv);
  flags[f_INCIDENCE] = checkForOption("-incidence", argc, argv);
  flags[f_RANGE] = checkForOption("-range", argc, argv);
  flags[f_LINE] = checkForOption("-line", argc, argv);
  flags[f_SAMPLE] = checkForOption("-sample", argc, argv);
  flags[f_MIN] = checkForOption("-min", argc, argv);
  flags[f_MAX] = checkForOption("-max", argc, argv);
  flags[f_BINS] = checkForOption("-bins", argc, argv);
  flags[f_INTERVAL] = checkForOption("-interval", argc, argv);

  /* Make sure to set log & quiet flags (for use in our libraries) */
  logflag = (flags[f_LOG]!=FLAG_NOT_SET) ? TRUE : FALSE;
  quietflag = (flags[f_QUIET]!=FLAG_NOT_SET) ? TRUE : FALSE;

  { /* We need to make sure the user specified the proper number of arguments */
    int needed_args = 4;/*command & in_base & out_base */
    if (flags[f_MIN] != FLAG_NOT_SET) needed_args += 2; /* option & value */
    if (flags[f_MAX] != FLAG_NOT_SET) needed_args += 2; /* option & value */
    if (flags[f_BINS] != FLAG_NOT_SET) needed_args += 2; /* option & value */
    if (flags[f_INTERVAL] != FLAG_NOT_SET) needed_args += 2; /* option & value */

    /*Make sure we have enough arguments*/
    if (argc != needed_args)
      usage();/*This exits with a failure*/
  }

  /* We must be close to good enough at this point...start filling in fields 
     as needed */
  if (flags[f_MIN] != FLAG_NOT_SET)
    min = atof(argv[flags[f_MIN] + 1]);
  if (flags[f_MAX] != FLAG_NOT_SET)
    max = atof(argv[flags[f_MAX] + 1]);
  if (flags[f_BINS] != FLAG_NOT_SET)
    bins = atoi(argv[flags[f_BINS] + 1]);
  if (flags[f_INTERVAL] != FLAG_NOT_SET)
    interval = atof(argv[flags[f_INTERVAL] + 1]);

  if (flags[f_QUIET] == FLAG_NOT_SET)
    /* display splash screen if not quiet */
    print_splash_screen(argc, argv);
  if (flags[f_LOG] != FLAG_NOT_SET)
    strcpy(logFile, argv[flags[f_LOG] + 1]);
  else
    /* default behavior: log to tmp<pid>.log */
    sprintf(logFile, "tmp%i.log", (int)getpid());
  fLog = FOPEN(logFile, "a");

  /* Fetch required arguments */
  strcpy(inFile,argv[argc - 2]);
  strcpy(outBase,argv[argc - 1]);
/***********************END COMMAND LINE PARSING STUFF***********************/

  create_name(metaFile, inFile, ".meta");
  create_name(dataFile, inFile, ".img");
  
  /* Read metadata */
  meta = meta_read(inFile);
  lines = meta->general->line_count;
  samples = meta->general->sample_count;

  /* Set some values */
  doppler = 0.0;

  /* Determine what kind of image it is */
  if (meta->sar->image_type=='P') {
    if (meta->projection->type==SCANSAR_PROJECTION)
      printf("   Detected ScanSAR ");
  }
  else if (meta->sar->image_type=='S')
    printf("   Detected slant range ");
  else if (meta->sar->image_type=='G')
    printf("   Detected ground range ");
/*
  switch (meta->general->image_data_type) 
    {
    case AMPLITUDE_IMAGE: 
      printf("amplitude image ...\n");
      break;
    case SIGMA_IMAGE:
      printf("sigma image ...\n");
      break;
    case GAMMA_IMAGE:
      printf("gamma image ...\n");
      break;
    case BETA_IMAGE:
      printf("beta image ...\n");
      break;
    case RAW_IMAGE:
    case COMPLEX_IMAGE:
    case PHASE_IMAGE:
    case POWER_IMAGE:
    case COHERENCE_IMAGE:
    case GEOREFERENCED_IMAGE:
    case GEOCODED_IMAGE:
    case POLARIMETRIC_IMAGE:
    case LUT_IMAGE:
    case ELEVATION:
    case DEM:
    case IMAGE:
    case MASK:
      break;
    }
*/
  /* Create a mask file for background fill - required only for ScanSAR */
  if (meta->sar->image_type=='P') {
    if (meta->projection->type==SCANSAR_PROJECTION) {
      fpIn = fopenImage(inFile, "rb");
      bufImage = (float *) MALLOC(samples * sizeof(float));
      printf("   Generating mask file ...\n");
      maskFile = (char *) MALLOC(255*sizeof(char));
      sprintf(maskFile, "tmp%i.mask", (int)getpid());
      fpMask = fopenImage(maskFile, "wb");
      bufMask = (unsigned char *) MALLOC(samples * sizeof(char));
      for (ii=0; ii<lines; ii++) {
	get_float_line(fpIn, meta, ii, bufImage);
	for (kk=0; kk<samples; kk++) {
	  if (bufImage[kk]>0.0)
	    bufMask[kk] = 1;
	  else
	    bufMask[kk] = 0;
	}      
	ASF_FWRITE(bufMask, sizeof(char), samples, fpMask);
      }
      FCLOSE(fpMask);
      FREE(bufMask);
      FCLOSE(fpIn);
      FREE(bufImage);
    }
  }

  /* Create grid for least square approach */
  printf("   Initialization ...\n");
  if (flags[f_LOOK] != FLAG_NOT_SET) {
    sprintf(outLook, "tmp%i.look", (int)getpid());
    fpLook = FOPEN(outLook, "w");
  }
  if (flags[f_INCIDENCE] != FLAG_NOT_SET) {
    sprintf(outIncid, "tmp%i.incid", (int)getpid());
    fpIncid = FOPEN(outIncid, "w");
  }
  if (flags[f_RANGE] != FLAG_NOT_SET) {
    sprintf(outRange, "tmp%i.range", (int)getpid());
    fpRange = FOPEN(outRange, "w");
  }

  if (flags[f_LOOK] != FLAG_NOT_SET || flags[f_INCIDENCE] != FLAG_NOT_SET ||
      flags[f_RANGE] != FLAG_NOT_SET) {
    for (ll=0; ll<=RES_X; ll++)
      for (kk=0; kk<=RES_Y; kk++) {
	line = ll * lines / RES_Y;
	sample = kk * samples / RES_X;
	
	if (meta->sar->image_type=='P') {
	  px = meta->projection->startX + meta->projection->perX * sample;
	  py = meta->projection->startY + meta->projection->perY * line;
	  proj_to_latlon(meta->projection, px, py, 0.0,
		     &latitude, &longitude, &height);
	  latLon2timeSlant(meta, latitude, longitude, &time, &range, &doppler);
	}
	else
	  time = meta_get_time(meta, line, sample);
	
	stVec = meta_get_stVec(meta, time);
	if (meta->sar->image_type=='P') {
	  if (meta->projection->type==SCANSAR_PROJECTION) 
	    earth_radius = meta->projection->param.atct.rlocal;
	  else
	    asfPrintError("Unable to determine earth radius.\n");
	}
	else
	  earth_radius = my_get_earth_radius(time, stVec, re, rp);
	satellite_height = my_get_satellite_height(time, stVec);
	range = my_get_slant_range(meta, earth_radius, satellite_height, line, sample);
	look_angle = my_get_look_angle(earth_radius, satellite_height, range);
	incidence_angle = my_get_incidence_angle(earth_radius, satellite_height, range);
	
	if (ll==0 && kk==0) {
	  firstLook = look_angle * R2D;
	  firstIncid = incidence_angle * R2D;
	  firstRange = range;
	}
	
	if (flags[f_LOOK] != FLAG_NOT_SET)
	  fprintf(fpLook, "%.18f %.12f %.12f\n", (float)look_angle*R2D, 
		  line, sample);
	if (flags[f_INCIDENCE] != FLAG_NOT_SET)
	  fprintf(fpIncid, "%.18f %.12f %.12f\n", (float)incidence_angle*R2D, 
		  line, sample);
	if (flags[f_RANGE] != FLAG_NOT_SET) 
	  fprintf(fpRange, "%.18f %.12f %.12f\n", (float)range, line, sample);
      }
  }
  
  /* Close files for now */
  if (flags[f_LOOK] != FLAG_NOT_SET) {
    FCLOSE(fpLook);
    FREE(bufLook);
  }
  if (flags[f_INCIDENCE] != FLAG_NOT_SET) {
    FCLOSE(fpIncid);
    FREE(bufIncid);
  }
  if (flags[f_RANGE] != FLAG_NOT_SET) {
    FCLOSE(fpRange);
    FREE(bufRange);
  }
  
  /* Calculate plots */
  if (flags[f_LOOK] != FLAG_NOT_SET) {
    create_name(outFile, outBase, "_look.plot");
    calculate_plot("Look angle", outLook, dataFile, maskFile, outFile, 
		   meta, firstLook);
  }
  if (flags[f_INCIDENCE] != FLAG_NOT_SET) {
    create_name(outFile, outBase, "_incid.plot");
    calculate_plot("Incidence angle", outIncid, dataFile, maskFile, outFile, 
		   meta, firstIncid);
  }
  if (flags[f_RANGE] != FLAG_NOT_SET) {
    create_name(outFile, outBase, "_range.plot");
    calculate_plot("Range", outRange, dataFile, maskFile, outFile, 
		   meta, firstRange);
  }
  if (flags[f_LINE] != FLAG_NOT_SET) {
    create_name(outFile, outBase, "_line.plot");
    calculate_plot("Line", NULL, dataFile, maskFile, outFile, 
		   meta, 0.0);
  }
  if (flags[f_SAMPLE] != FLAG_NOT_SET) {
    create_name(outFile, outBase, "_sample.plot");
    calculate_plot("Sample", NULL, dataFile, maskFile, outFile, 
		   meta, 0.0);
  }
  
  /* Clean up */
  sprintf(cmd, "rm -rf tmp*");
  system(cmd);
  
  exit(0);
}
Пример #22
0
/* libbalsa_address_book_ldap_get_address:
 * loads a single address from connection specified by LDAPMessage.
 */
static LibBalsaAddress* 
libbalsa_address_book_ldap_get_address(LibBalsaAddressBook * ab,
				       LDAPMessage * e)
{
    LibBalsaAddressBookLdap *ldap_ab;
    gchar *email = NULL, *cn = NULL, *org = NULL, *uid = NULL;
    gchar *first = NULL, *last = NULL;
    LibBalsaAddress *address = NULL;
    char *attr;
    struct berval **vals;
    BerElement *ber = NULL;
    int i;

    ldap_ab = LIBBALSA_ADDRESS_BOOK_LDAP(ab);

    for (attr = ldap_first_attribute(ldap_ab->directory, e, &ber);
	 attr != NULL; attr=ldap_next_attribute(ldap_ab->directory, e, ber)) {
	/*
	 * For each attribute, get the attribute name and values.
	 */
	if ((vals=ldap_get_values_len(ldap_ab->directory, e, attr)) != NULL) {
	    for (i = 0; vals[i] != NULL; i++) {
		if ((g_ascii_strcasecmp(attr, "sn") == 0) && (!last))
		    last = g_strndup(vals[i]->bv_val, vals[i]->bv_len);
		if ((g_ascii_strcasecmp(attr, "cn") == 0) && (!cn))
		    cn = g_strndup(vals[i]->bv_val, vals[i]->bv_len);
		if ((g_ascii_strcasecmp(attr, "givenName") == 0) && (!first))
		    first = g_strndup(vals[i]->bv_val, vals[i]->bv_len);
		if ((g_ascii_strcasecmp(attr, "o") == 0) && (!org))
		    org = g_strndup(vals[i]->bv_val, vals[i]->bv_len);
		if ((g_ascii_strcasecmp(attr, "uid") == 0) && (!uid))
		    uid = g_strndup(vals[i]->bv_val, vals[i]->bv_len);
		if ((g_ascii_strcasecmp(attr, "mail") == 0) && (!email))
		    email = g_strndup(vals[i]->bv_val, vals[i]->bv_len);
	    }
	    ldap_value_free_len(vals);
	}
        ldap_memfree(attr);
    }
    /*
     * Record will have e-mail (searched)
     */
    if(email == NULL) email = g_strdup("none");
    g_return_val_if_fail(email != NULL, NULL);

    address = libbalsa_address_new();
    if (cn)
	address->full_name = cn;
    else {
	address->full_name = create_name(first, last);
        if(!address->full_name)
            address->full_name = g_strdup(_("No-Name"));
    }
    address->first_name = first;
    address->last_name = last;
    address->nick_name = uid;
    address->organization = org;
    address->address_list = g_list_prepend(address->address_list, email);

    return address;
}
Пример #23
0
 result_type operator()(scalar<ScalarType> const & scal) const {
   mapped_scalar * p = new mapped_scalar(utils::type_to_string<ScalarType>::value());
   p->name_ = create_name(current_arg_, memory_, (void*)&scal);
   return container_ptr_type(p);
 }
Пример #24
0
static int serve_client_in(CLIENT *client, int sock, const char *dir, 
    const char *hostname)
{
    FILE *fp = NULL;

    FILESTATS fstats;

    char in_dir[PATH_LEN+1];
    char path[PATH_LEN+1];

    int buflen;
    int cur_ptr = 0;
    int file_recvcnt = 0;
    int moredata = TRUE;
    int workbuflen = 0;

    unsigned char *workbuf = NULL;

/*-------------------------------------------------------------------------+
 |  Create and validate the incoming file directory.
 +------------------------------------------------------------------------*/

    errno = 0;

    sprintf(in_dir, "%s/%s/%s", dir, client->hostname, CHOUSESYS_INLOC);

    if ( !directory_validate(in_dir) )
    {
        fprintf(stderr, "%s: %s: error: invalid input directory: %s\n",
            timestamp(), ProgName, in_dir); 
        return 1;
    }

/*-------------------------------------------------------------------------+
 |  Allocate space for working with the input data as it is received. This
 |  buffer must be dynamically allocated to be the combined size of the
 |  socket input data buffer and the end-of-data buffer. This size of
 |  work buffer will allow enough input data to be read to scan for the
 |  end-of-data marker even if it spans multiple socket retrievals.
 +------------------------------------------------------------------------*/

    workbuf = (unsigned char *) malloc (CH_MSG_SIZE + client->eod.hex_buflen);
    if ( workbuf == NULL )
    {
        fprintf(stderr, "%s: %s: error: could not allocate work buffer: %s\n",
            timestamp(), ProgName, strerror(errno)); 
        return 1;
    }

/*-------------------------------------------------------------------------+
 |  Process data in the work buffer until there isn't enough data left to
 |  match the end-of-data marker. Add data to the work buffer from the
 |  input socket connection when needed.
 +------------------------------------------------------------------------*/

    while ( moredata || workbuflen >= client->eod.hex_buflen)
    {
        if ( workbuflen < client->eod.hex_buflen)
        {
            if (cur_ptr > 0)
               memmove(workbuf,&workbuf[cur_ptr],workbuflen);

            if ( get_socket_data(sock,hostname,&workbuf[workbuflen],
                 &buflen,&moredata) != 0)
               break;

            workbuflen = workbuflen + buflen;
            cur_ptr = 0;
        }

/*-------------------------------------------------------------------------+
 |      There is enough data in the work buffer to process. Prepare an
 |      output file if there isn't one connected yet.
 +------------------------------------------------------------------------*/

        else
        {
            if ( fp == NULL)
            {
                memset(&fstats, 0, sizeof(fstats));

                sprintf(path, "%s/%s", in_dir, 
                    create_name(in_dir, client->hostname, "data"));

                if ( (fstats.name = (char *)strrchr(path, '/')) == NULL )
                    fstats.name = path; /* no path in path */
                else
                    fstats.name++; /* skip leading '/' */

                if ( (fp = fopen(path, "w+")) == NULL )
                {
                    fprintf(stderr, "%s: %s: error: ");
                    fprintf(stderr, "open \"%s\" failed: %s\n",
                        fstats.name, strerror(ferror(fp))); 
                    if (workbuf != NULL)
                       free(workbuf);
                    return 1;
                }
#ifdef DEBUG
                if ( Debug > 2 )
                {
                    PRINT_DBGLOC;
                    fprintf(stderr, "Created/Opened file \"%s\"\n", basename(path));
                }
#endif
            }

/*-------------------------------------------------------------------------+
 |          Check the current position in the work buffer for the
 |          end-of-data marker. If found, switch to the next file.
 |          Otherwise copy the character at the current position into the
 |          current file.
 +------------------------------------------------------------------------*/

            if ( memcmp(workbuf+cur_ptr, client->eod.hex_buf, 
                client->eod.hex_buflen) == 0 )
            {
                fflush(fp);
                fclose(fp);
                fp = NULL;

                file_recvcnt++;
                fprintf(stderr, "%s: %s: info: ", timestamp(), ProgName);
                fprintf(stderr, "receive succeeded from %s - ", hostname);
                fprintf(stderr, "file \"%s (%d bytes)\" saved\n",
                    fstats.name, fstats.filesize);

                memset(&fstats, 0, sizeof(fstats));

                sprintf(path, "%s/%s", in_dir, 
                    create_name(in_dir, client->hostname, "data"));

                if ( (fstats.name = (char *)strrchr(path, '/')) == NULL )
                    fstats.name = path; /* no path in path */
                else
                    fstats.name++; /* skip leading '/' */

                if ( (fp = fopen(path, "w+")) == NULL )
                {
                    fprintf(stderr, "%s: %s: error: ");
                    fprintf(stderr, "open \"%s\" failed: %s\n",
                        fstats.name, strerror(ferror(fp))); 
                    if (workbuf != NULL)
                       free(workbuf);
                    return 1;
                }
#ifdef DEBUG
                if ( Debug > 2 )
                {
                    PRINT_DBGLOC;
                    fprintf(stderr, "Created/Opened file \"%s\"\n", basename(path));
                }
#endif
                cur_ptr = cur_ptr + client->eod.hex_buflen;
                workbuflen = workbuflen - client->eod.hex_buflen;
            }
            else
            {
                fstats.socksize++;
                if ( fputc(workbuf[cur_ptr], fp) == EOF )
                {
                    fprintf(stderr, "%s: %s: error: ");
                    fprintf(stderr, "write \"%s\" failed: %s\n",
                        fstats.name, strerror(ferror(fp))); 
                    break;
                }
                fstats.filesize++;
                cur_ptr++;
                workbuflen--;
            }
        }
    }

/*-------------------------------------------------------------------------+
 |  Close connections for the last file processed. The last file should be
 |  empty. The socket data stream should end with the end-of-data marker
 |  which causes the last data to be written to the previous file. An
 |  empty next file is created because we don't really know when the end
 |  of the data will occur. If any data was written to the last file, then
 |  an error in transmission occurred.
 +------------------------------------------------------------------------*/

    if (fp != NULL)
    {
        fflush(fp);
        fclose(fp);
        fp = NULL;

        if ( fstats.filesize == 0 )
        {
            unlink(path);
        }
        else
        {
            file_recvcnt++;
            fprintf(stderr, "%s: %s: info: ", timestamp(), ProgName);
            fprintf(stderr, "Error, extra data received from %s - ", hostname);
            fprintf(stderr, "file \"%s (%d bytes)\" saved\n",
                fstats.name, fstats.filesize);
        }
    }

/*-------------------------------------------------------------------------+
 |  Log final statistics for this pass.
 +------------------------------------------------------------------------*/

    fprintf(stderr, "%s: %s: info: completed %s: %d files received\n",
        timestamp(), ProgName, hostname, file_recvcnt);

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

    return 0;

} /* serve_client_in() */
Пример #25
0
int main(int argc, char *argv[])
{
	char *baseFile;
	meta_parameters *meta;
	baseline base;
	int   wid, len,		/* Width and Length of input scene    */
		ss, sl;		/* Offsets of input scene in original */
	int x,y;
	double xScale,yScale;
	float percent=5.0;
	
	FILE  *fin, *fout;
	char  szInPhase[255], szInAmp[255], szOutPhase[255], szOutAmp[255];
	float *data;
	double *sflat,*cflat;
	double derampDirection=1.0;/*1.0=forward deramping.  -1.0=backward deramping.*/
	logflag=0;

/* process command line args */
	currArg=1; /* from cla.h in asf.h */
	/* optional args */
	while (currArg < (argc-3)) {
		char *key = argv[currArg++];
		if (strmatch(key,"-log")) {
			CHECK_ARG(1);
			strcpy(logFile,GET_ARG(1));
			fLog = FOPEN(logFile, "a");
			logflag=1;
		}
		else if (strmatch(key,"-backward")) {
			derampDirection = -1.0;
		}
		else {printf("**Invalid option: %s\n",argv[currArg-1]); usage(argv[0]);}
	}
	if ((argc-currArg) < 3) {printf("Insufficient arguments.\n"); usage(argv[0]);}
	/* required args */
	create_name(szInAmp, argv[currArg], "_amp.img");
	create_name(szInPhase, argv[currArg], "_phase.img");
	baseFile = argv[currArg+1];

	asfSplashScreen(argc, argv);
	
	/* Get input scene size and windowing info, check validity */
	meta = meta_read(szInPhase);

	wid = meta->general->sample_count;
	len = meta->general->line_count;
	ss = meta->general->start_sample - 1;
	sl = meta->general->start_line - 1;
	xScale = meta->sar->sample_increment;
	yScale = meta->sar->line_increment;
	
	create_name(szOutAmp,argv[currArg+2],"_amp.img");
	meta_write(meta, szOutAmp);
	create_name(szOutPhase,argv[currArg+2],"_phase.img");
	meta_write(meta, szOutPhase);

	/*Link over ".amp" file, if it exists.*/
	if (fileExists(szInAmp)&&!fileExists(szOutAmp))
	{
		char command[1024];
		sprintf(command,"ln -s %s %s\n", szInAmp, szOutAmp);
		system(command);
	}
	
	/* buffer mallocs, read data file */
	data = (float *)MALLOC(sizeof(float)*wid);
	sflat = (double *)MALLOC(sizeof(double)*wid);
	cflat = (double *)MALLOC(sizeof(double)*wid);
	fin = fopenImage(szInPhase,"rb");
	fout = fopenImage(szOutPhase,"wb");
	
	/* read in CEOS parameters & convert to meters */
	base=read_baseline(baseFile);
	
	/* calculate slant ranges and look angles - Ian's thesis eqn 3.10 */
	for (x = 0; x < wid; x++) {
		double flat=meta_flat(meta,0.0,x*xScale+ss);
		sflat[x]=sin(flat);
		cflat[x]=cos(flat);
	}
	/* Deramp 'data' array */
	
/*	printf("\n  starting in-place deramp of input data \n\n");*/
	for (y = 0; y < len; y++)
	{
		double Bn_y,Bp_y;
		double twok=derampDirection*2.0*meta_get_k(meta);
		meta_interp_baseline(meta,base,y*(int)yScale+sl,&Bn_y,&Bp_y);
		/* read in the next row of data */
		get_float_line(fin, meta, y, data);
		
		/* calculate flat-earth range phase term & remove it */ 
		for (x = 0; x < wid; x++)
		{
			double d=data[x];
			if (d!=0.0) /*Ignore points which didn't phase unwrap.*/
				d -= twok*(Bp_y*cflat[x]-Bn_y*sflat[x]);
			/*Was: d-=ceos_flat_phase(ceos,base,x,y);*/
			data[x]=d;
		}
		
		/* write out this row of data */
		put_float_line(fout, meta, y, data);
		if (y*100/len==percent) {
		  printf("   Completed %3.0f percent\n", percent);
		  percent+=5.0;
		}
	}
/*	printf("\nDone with deramp\n\n");*/
	
	/* save and scram */
	FCLOSE(fin); FCLOSE(fout);
	FREE(data); FREE(sflat);FREE(cflat);

	printf("   Completed 100 percent\n\n");
	if (logflag) {
	  sprintf(logbuf, "   Wrote %lld bytes of data\n\n", (long long)(len*wid*4));
	  printLog(logbuf);
	}

	return 0;
}
Пример #26
0
lasErr c_putddr(const char *hname,struct DDR *ddr)
{
    int   access;                   /* file access type                      */
    int   action;                   /* file close action                     */
    int   clen;                     /* length of char part of record         */
    int   dlen;                     /* length of data part of record         */
    FILE *fd;                       /* file descriptor                       */
    char  d_temp[DDSTCT][DDSYLN];   /* temporary for squeezed strings        */
    char *junk_temp,hostddr[1024];
    unsigned char *dbuf;            /* pointer to area where data is stuffed */
    int ii;                         /* Index for corresponding metadata      */

    /* Ensure that required parameters were specified.
    --------------------------------------------------*/
    if ((ddr->nl < 1) || (ddr->nl > MAXNL)) {
      c_errmsg("Invalid number of lines specified","putddr-badnl",NON_FATAL);
      return(E_FAIL);
    }
    if ((ddr->ns < 1) || (ddr->ns > MAXNS)) {
      c_errmsg("Invalid number of samples specified","putddr-badns",NON_FATAL);
      return(E_FAIL);
    }
    if ((ddr->nbands < 1) || (ddr->nbands > MAXBND)) {
      c_errmsg("Invalid number of bands specified","putddr-badbnds",NON_FATAL);
      return(E_FAIL);
    }
    if ((ddr->dtype < 1) || (ddr->dtype > 20)) {
      c_errmsg("Invalid data type specified","putddr-bdtype",NON_FATAL);
      return(E_FAIL);
    }

    strcpy(ddr->system,"ieee-std");

    c_lsmknm(hname,".ddr",hostddr);

    access = 1;                          /* open DDR file for write access   */
    c_lsopen(&fd,hostddr,&access);

    /*  Place the string portion of the DDR into a temporary buffer
    ---------------------------------------------------------------*/
    junk_temp = (char *)&ddr->spare;
    strncpy(junk_temp,ddr->system,4);
    strcpy(d_temp[0],squeeze(ddr->system,DDSYLN));
    strcpy(d_temp[1],squeeze(ddr->proj_units,DDPULN));
    strcpy(d_temp[2],squeeze(ddr->last_used_date,DDLDLN));
    strcpy(d_temp[3],squeeze(ddr->last_used_time,DDLTLN));

    clen = DDSTCT * DDSYLN - 1;                /* set up and output record 1 */
    dlen = DISIZE * 4;
    dbuf = (unsigned char *) MALLOC(dlen);
    int2byteArr((int *)ddr,dbuf,DISIZE);
    c_lswrit(&fd,"DDRINT",&clen,&dlen,d_temp[0],dbuf,"I4");
    free(dbuf);

    /* Set up and output record 2
       There is no character part to this record 
    --------------------------------------------*/
    clen = 0;				  
    dlen = DDSIZE * 8;

    // convert all floating point values to proper endian-ness
    for (ii=0; ii<15; ++ii)
      big64(ddr->proj_coef[ii]);
    for (ii=0; ii<2; ++ii) {
      big64(ddr->upleft[ii]);
      big64(ddr->loleft[ii]);
      big64(ddr->upright[ii]);
      big64(ddr->loright[ii]);
    }
    big64(ddr->pdist_y);
    big64(ddr->pdist_x);
    big64(ddr->line_inc);
    big64(ddr->sample_inc);

    dbuf = (unsigned char *) &(ddr->proj_coef[0]);
    c_lswrit(&fd,"DDRDUB",&clen,&dlen,d_temp[0],dbuf,"R8");

    action = 0;                                 /* close associated DDR file */
    c_lsclos(&fd,hostddr,&action);

    {/*Create/write correct number of BDRs*/
	    int bandNo;
	    for (bandNo=1;bandNo<=ddr->nbands;bandNo++)
	    {
		    struct BDDR bdr;
		    int_c_intbdr(&bdr);
		    bdr.bandno=bandNo;
		    int_c_putbdr(hname,&bdr);
	    }
    }

    /* Find corresponding meta structure to fill necessary values to
    ----------------------------------------------------------------*/
    ii = get_meta_ddr_struct_index(hname);
    if ((ii>-1) && (ii<NUM_META_DDR_STRUCTS)) {
        if (meta_ddr_structs[ii].ddr != ddr) {
/*            printf("\n"
                   "Warning: Bad programming in the asf_meta library.\n"
                   "         Something that should not have happened in c_putddr() did.\n"
                   "         Please contact Patrick Denny ([email protected]).\n");*/
        }
        if (meta_ddr_structs[ii].ddr == ddr) {
            meta_parameters *mds_meta;
            struct DDR *mds_ddr  = meta_ddr_structs[ii].ddr;
            int open_flag = 0;
            char meta_name[512];

            create_name(meta_name, meta_ddr_structs[ii].base_name, ".meta");

            /* Get the meta structure if its never been gotten (meta=NULL)
             * or its been free'd (meta->general==NULL) */
            if (meta_ddr_structs[ii].meta==NULL
	       || meta_ddr_structs[ii].meta->general==NULL) {
	        if (fileExists(meta_name)) {
                    mds_meta = meta_read(meta_name);
                    open_flag = 1;
		}
		else /* No meta struct/file */ {
		    return(E_SUCC);
		}
            }
            else
                {mds_meta = meta_ddr_structs[ii].meta;}

            /* Fill the meta structure with updated values */
            mds_meta->general->line_count     = mds_ddr->nl;
            mds_meta->general->sample_count   = mds_ddr->ns;
            mds_meta->general->start_line     = mds_ddr->master_line - 1;
            mds_meta->general->start_sample   = mds_ddr->master_sample - 1;
            mds_meta->sar->line_increment     = mds_ddr->line_inc;
            mds_meta->sar->sample_increment   = mds_ddr->sample_inc;
            if (mds_meta->sar->image_type=='P')
                    {strcpy(mds_meta->projection->units, mds_ddr->proj_units);}
            switch ( mds_ddr->dtype ) {
              case 0: /* DTYPE_BYTE */
              case DTYPE_BYTE:  mds_meta->general->data_type = ASF_BYTE;  break;
              case DTYPE_SHORT: mds_meta->general->data_type = INTEGER16; break;
              case DTYPE_LONG:  mds_meta->general->data_type = INTEGER32; break;
              case DTYPE_FLOAT: mds_meta->general->data_type = REAL32;    break;
              case DTYPE_DOUBLE:mds_meta->general->data_type = REAL64;    break;
              case DTYPE_COMPLEX:
                           mds_meta->general->data_type = COMPLEX_REAL32; break;
              default:
	            printf("WARNING: c_putddr: Unrecognized meta/DDR data type (%d).\n",
		           mds_ddr->dtype);
                    break;
            }
 	    if (open_flag) {
                meta_write(mds_meta, meta_ddr_structs[ii].base_name);
                meta_free(mds_meta);
            }
        }
    }
    return(E_SUCC);
}
Пример #27
0
int main(int argc,char *argv[])
{
  char  infile1[256], infile2[256], infile3[256];  // Input file name                         
  char  outfile[256];         			   // Output file name
  char tmpPath[1024];
  browse_type_t mode = NOTYPE;
  int   i,j;
  int   sample_count;
  double scale;
  extern int currArg;
  strcpy(tmpPath, "");

  // Parse command line
  if ((argc-currArg)<1) {
    printf("Insufficient arguments.\n"); 
    usage("");
  }

  while (currArg < (argc-2)) {
    char *key = argv[currArg++];
    if (strmatches(key, "-sentinel", "--sentinel", NULL)) {
      CHECK_ARG(1);
      scale = atof(GET_ARG(1));
      mode = SENTINEL_DUAL;
    }
    else if (strmatches(key, "-tmpDir", "--tmpDir", NULL)) {
      CHECK_ARG(1);
      strcpy(tmpPath, GET_ARG(1));
    }
    else if (strmatches(key, "-log", "--log", NULL)) {
      CHECK_ARG(1);
      strcpy(logFile,GET_ARG(1));
      fLog = FOPEN(logFile, "a");
      logflag = TRUE;
    }
    else if (strmatches(key, "-quiet", "--quiet", "-q", NULL))
      quietflag = TRUE;
    else {
      --currArg;
      break;
    }
  }
  if ((argc-currArg) < 2) {
    printf("Insufficient arguments.\n");
    usage(argv[0]);
  }
  if (mode == NOTYPE && argc == 4)
    mode = PALSAR_FBD;
  else if (mode == NOTYPE && argc == 5) 
    mode = PALSAR_PLR;

  if (!quietflag) 
    asfSplashScreen(argc, argv);

  if (mode == PALSAR_FBD) {
  
    asfPrintStatus("Creating colorized browse image from PALSAR FBD data\n");
    create_name(infile1,argv[1],".img");
    create_name(infile2,argv[2],".img");
    create_name(outfile,argv[3],".img");

    meta_parameters *meta1 = meta_read(infile1);
    meta_parameters *meta2 = meta_read(infile2);

    if (meta1->general->line_count != meta2->general->line_count ||
        meta1->general->sample_count != meta2->general->sample_count)
      {
        asfPrintError("Images must be the same size!!!\n");
        exit(1);
      }    
    strcpy(meta1->general->bands,"HH");
    strcpy(meta2->general->bands,"HV");

    int pixel_count = meta1->general->line_count*meta1->general->sample_count;
    float *buf1 = MALLOC(pixel_count * sizeof(float));
    float *buf2 = MALLOC(pixel_count * sizeof(float));
    float *buf3 = MALLOC(pixel_count * sizeof(float));
    unsigned char *cbuf1, *cbuf2, *cbuf3;
    FILE *fp1 = FOPEN(infile1, "r");
    FILE *fp2 = FOPEN(infile2, "r");
    FILE *ofp = FOPEN(outfile, "w");
    char ofile1[256];
    char ofile2[256];

    strcpy(ofile1,argv[1]);
    strcat(ofile1,"_DB.img");
    strcpy(ofile2,argv[2]);
    strcat(ofile2,"_DB.img");
 
    printf("Creating output DB files %s and %s\n",ofile1,ofile2);
    FILE *ofp1 = FOPEN(ofile1, "w");
    FILE *ofp2 = FOPEN(ofile2, "w");

    get_float_lines(fp1,meta1,0,meta1->general->line_count, buf1);
    get_float_lines(fp2,meta2,0,meta2->general->line_count, buf2);

    /* Convert data from sigma0 to dB */
    sample_count = 0;
    for (i=0; i<meta1->general->line_count; ++i) {
      for (j=0; j<meta1->general->sample_count; ++j) {
        if (meta_is_valid_double(buf1[sample_count])) {
          if (buf1[sample_count] != 0)
            buf1[sample_count] = 10.0 * log10f(buf1[sample_count]);
          if (buf2[sample_count] != 0)
            buf2[sample_count] = 10.0 * log10f(buf2[sample_count]);
        }
  	sample_count++;
      }
    }
    put_float_lines(ofp1, meta1, 0,meta1->general->line_count,buf1);
    put_float_lines(ofp2, meta2, 0,meta1->general->line_count,buf2);

    meta_write(meta1, ofile1);
    meta_write(meta2, ofile2);

    fclose(fp1);
    fclose(fp2);
    fclose(ofp1);
    fclose(ofp2);

    /* Scale the data to a byte range using given min/max values */
    cbuf1 = my_floats_to_bytes(buf1,(long long) pixel_count, 0.0,MINMAX,-30.0,-1.0); 
    cbuf2 = my_floats_to_bytes(buf2,(long long) pixel_count, 0.0,MINMAX,-30.0,-10.0); 
   
    /* 
    cbuf1 = my_floats_to_bytes(buf1,(long long) pixel_count, 0.0,MINMAX,-31.0,7.1); 
    cbuf2 = my_floats_to_bytes(buf2,(long long) pixel_count, 0.0,MINMAX,-31.0,7.1);
    */

    strcpy(ofile1,argv[1]);
    strcat(ofile1,"_byte.img");
    strcpy(ofile2,argv[2]);
    strcat(ofile2,"_byte.img");
 
    printf("Creating output byte files %s and %s\n",ofile1,ofile2);
    ofp1 = FOPEN(ofile1, "w");
    ofp2 = FOPEN(ofile2, "w");

    meta1->general->data_type=REAL32;
    meta2->general->data_type=REAL32;

    sample_count = 0;
    for (i=0; i<meta1->general->line_count; ++i) {
      for (j=0; j<meta1->general->sample_count; ++j) {
          buf1[sample_count] = (float) cbuf1[sample_count];
          buf2[sample_count] = (float) cbuf2[sample_count];
  	  sample_count++;
      }
    }

    put_float_lines(ofp1,meta1,0,meta1->general->line_count,buf1); 
    put_float_lines(ofp2,meta2,0,meta2->general->line_count,buf2); 

    meta_write(meta1, ofile1);
    meta_write(meta2, ofile2);

    fclose(ofp1);
    fclose(ofp2);

    /* Create the third band for the color image */
    sample_count = 0;
    for (i=0; i<meta1->general->line_count; ++i) {
      for (j=0; j<meta1->general->sample_count; ++j) {
 	 if (buf2[sample_count] != 0) {
           /*
           buf3[sample_count] = (buf1[sample_count] / buf2[sample_count]); 
           */

           buf3[sample_count] = (buf1[sample_count] - buf2[sample_count]);
           if (buf3[sample_count] < 1) buf3[sample_count] = 1;
           else if (buf3[sample_count] > 255) buf3[sample_count] = 255;
         } else buf3[sample_count] = 0;
         sample_count++;
       }
    }

    cbuf3 = my_floats_to_bytes(buf3,(long long) pixel_count, 0.0,SIGMA ,-25.0,-10.0); 
    sample_count = 0;
    for (i=0; i<meta1->general->line_count; ++i) {
      for (j=0; j<meta1->general->sample_count; ++j) {
          buf3[sample_count] = (float) cbuf3[sample_count];
  	  sample_count++;
      }
    }

    /* Finally, create the 3 banded image we were looking for */
    strcpy(meta1->general->bands,"HH,HV,DIV");
    meta1->general->band_count=3;
    put_band_float_lines(ofp,meta1,0,0,meta1->general->line_count,buf1);
    put_band_float_lines(ofp,meta1,1,0,meta1->general->line_count,buf2);
    put_band_float_lines(ofp,meta1,2,0,meta1->general->line_count,buf3);

    meta_write(meta1,outfile);

  } 
  else if (mode == PALSAR_PLR) {
  
    /* Mode 1 - Create Color Browse from 3 bands using 3sigma stretch */
    asfPrintStatus("Creating colorized browse image from PALSAR PLR data\n");
    create_name(infile1,argv[1],".img");
    create_name(infile2,argv[2],".img");
    create_name(infile3,argv[3],".img");
    create_name(outfile,argv[4],".img");

    meta_parameters *meta1 = meta_read(infile1);
    meta_parameters *meta2 = meta_read(infile2);
    meta_parameters *meta3 = meta_read(infile3);

    if (meta1->general->line_count != meta2->general->line_count ||
        meta1->general->sample_count != meta2->general->sample_count)
      {
        asfPrintError("Images must be the same size!!!\n");
        exit(1);
      }

    if (meta3->general->line_count != meta2->general->line_count ||
        meta3->general->sample_count != meta2->general->sample_count)
      {
        asfPrintError("Images must be the same size!!!\n");
        exit(1);
      }

    int pixel_count = meta1->general->line_count*meta1->general->sample_count;
    float *buf1 = MALLOC(pixel_count * sizeof(float));
    float *buf2 = MALLOC(pixel_count * sizeof(float));
    float *buf3 = MALLOC(pixel_count * sizeof(float));
    float *buf4 = MALLOC(pixel_count * sizeof(float));
    unsigned char *cbuf1, *cbuf2, *cbuf3, *cbuf4;
    FILE *fp1 = FOPEN(infile1, "r");
    FILE *fp2 = FOPEN(infile2, "r");
    FILE *fp3 = FOPEN(infile3, "r");
    FILE *ofp = FOPEN(outfile, "w");

    get_float_lines(fp1,meta1,0,meta1->general->line_count, buf1);
    get_float_lines(fp2,meta2,0,meta2->general->line_count, buf2);
    get_float_lines(fp3,meta3,0,meta3->general->line_count, buf3);

    /* Convert data from sigma0 to dB */
    sample_count = 0;
    for (i=0; i<meta1->general->line_count; ++i) {
      for (j=0; j<meta1->general->sample_count; ++j) {
        if (meta_is_valid_double(buf1[sample_count])) {
          if (buf1[sample_count] != 0)
            buf1[sample_count] = 10.0 * log10f(buf1[sample_count]);
          if (buf2[sample_count] != 0)
            buf2[sample_count] = 10.0 * log10f(buf2[sample_count]);
          if (buf3[sample_count] != 0)
            buf3[sample_count] = 10.0 * log10f(buf3[sample_count]);
        }
  	sample_count++;
      }
    }
    /* Scale the data to a byte range using 3-sigma stretch values */
    cbuf1 = my_floats_to_bytes(buf1,(long long) pixel_count, 0.0,SIGMA3,-30.0,-1.0);
    cbuf2 = my_floats_to_bytes(buf2,(long long) pixel_count, 0.0,SIGMA3,-30.0,-10.0);
    cbuf3 = my_floats_to_bytes(buf3,(long long) pixel_count, 0.0,SIGMA3,-30.0,-10.0);

    meta1->general->data_type=REAL32;
    //meta2->general->data_type=ASF_BYTE;
    //meta3->general->data_type=ASF_BYTE;

    sample_count = 0;
    for (i=0; i<meta1->general->line_count; ++i) {
      for (j=0; j<meta1->general->sample_count; ++j) {
          buf1[sample_count] = (float) cbuf1[sample_count];
          buf2[sample_count] = (float) cbuf2[sample_count];
          buf3[sample_count] = (float) cbuf3[sample_count];
          sample_count++;
      }
    }
 
    /* Finally, create the 3 banded image we were looking for */
    strcpy(meta1->general->bands,"HH,HV,VV");
    meta1->general->band_count=3;
    put_band_float_lines(ofp,meta1,0,0,meta1->general->line_count,buf1);
    put_band_float_lines(ofp,meta1,1,0,meta1->general->line_count,buf2);
    put_band_float_lines(ofp,meta1,2,0,meta1->general->line_count,buf3);

    meta_write(meta1,outfile);
  }
  else if (mode == SENTINEL_DUAL) {
  
    asfPrintStatus("Creating colorized browse image from Sentinel dual-pol "
      "data\n");
    if (strlen(tmpPath) > 0) {
      create_name(infile1,argv[5],".img");
      create_name(infile2,argv[6],".img");
      create_name(outfile,argv[7],".tif");
    }
    else {
      create_name(infile1,argv[3],".img");
      create_name(infile2,argv[4],".img");
      create_name(outfile,argv[5],".tif");
    }

    // Create temporary directory
    char tmpDir[1024];
    if (strlen(tmpPath) > 0)
      sprintf(tmpDir, "%s%cbrowse-", tmpPath, DIR_SEPARATOR);
    else
      strcpy(tmpDir, "browse-");
    strcat(tmpDir, time_stamp_dir());
    create_clean_dir(tmpDir);
    asfPrintStatus("Temp dir is: %s\n", tmpDir);
  
    // Calculate ratio image
    char tmpRatio[512], tmpRed[512], tmpGreen[512], tmpBlue[512], tmpIn[512];
    char *inFiles[2]; 
    inFiles[0] = (char *) MALLOC(sizeof(char)*255);
    inFiles[1] = (char *) MALLOC(sizeof(char)*255);
    strcpy(inFiles[0], infile1);
    strcpy(inFiles[1], infile2);
    sprintf(tmpRatio, "%s%cdiv.img", tmpDir, DIR_SEPARATOR);
    raster_calc(tmpRatio, "a/b", 2, inFiles);
    
    // Resample all three bands and scale to byte
    meta_parameters *metaIn = meta_read(tmpRatio);
    double scaleFactor = 1.0/(scale/metaIn->general->x_pixel_size);
    meta_free(metaIn);
    sprintf(tmpIn, "%s%cred.img", tmpDir, DIR_SEPARATOR);
    resample(infile1, tmpIn, scaleFactor, scaleFactor);
    sprintf(tmpRed, "%s%cred_byte.img", tmpDir, DIR_SEPARATOR);
    floats_to_bytes_from_file(tmpIn, tmpRed, NULL, -40.0, SIGMA);
    sprintf(tmpIn, "%s%cgreen.img", tmpDir, DIR_SEPARATOR);
    resample(infile2, tmpIn, scaleFactor, scaleFactor);
    sprintf(tmpGreen, "%s%cgreen_byte.img", tmpDir, DIR_SEPARATOR);
    floats_to_bytes_from_file(tmpIn, tmpGreen, NULL, -40.0, SIGMA);
    sprintf(tmpIn, "%s%cblue.img", tmpDir, DIR_SEPARATOR);
    resample(tmpRatio, tmpIn, scaleFactor, scaleFactor);    
    sprintf(tmpBlue, "%s%cblue_byte.img", tmpDir, DIR_SEPARATOR);
    floats_to_bytes_from_file(tmpIn, tmpBlue, NULL, -40.0, SIGMA);

    // Layer stack the bands
    char tmpBrowse[512];
    sprintf(tmpBrowse, "%s%cbrowse.img", tmpDir, DIR_SEPARATOR);
    FILE *fpOut = FOPEN(tmpBrowse, "w");    
    meta_parameters *metaOut = meta_read(tmpRed);
    metaOut->general->band_count = 3;
    metaIn = meta_read(tmpRed);
    int line_count = metaIn->general->line_count;
    int sample_count = metaIn->general->sample_count;
    
    float *buf = (float *) MALLOC(sizeof(float)*line_count*sample_count);
    FILE *fpIn = FOPEN(tmpBlue, "r");
    get_float_lines(fpIn, metaIn, 0, line_count, buf);
    put_band_float_lines(fpOut, metaOut, 0, 0, line_count, buf);
    FCLOSE(fpIn);
    fpIn = FOPEN(tmpGreen, "r");
    get_float_lines(fpIn, metaIn, 0, line_count, buf);
    put_band_float_lines(fpOut, metaOut, 1, 0, line_count, buf);
    FCLOSE(fpIn);
    fpIn = FOPEN(tmpRed, "r");
    get_float_lines(fpIn, metaIn, 0, line_count, buf);
    put_band_float_lines(fpOut, metaOut, 2, 0, line_count, buf);
    FCLOSE(fpIn);
    FCLOSE(fpOut);
    FREE(buf);

    strcpy(metaOut->general->bands, "red,green,blue");
    meta_write(metaOut, tmpBrowse);
    
    // Export to GeoTIFF
    char *band_names[3] = { "blue", "green", "red" };
    asf_export_bands(GEOTIFF, NONE, TRUE, FALSE, FALSE, FALSE, FALSE, 
      tmpBrowse, outfile, band_names, NULL, NULL);

    // Clean up
    asfPrintStatus("Removing temporary directory: %s\n", tmpDir);
    remove_dir(tmpDir);
    meta_free(metaIn);
    meta_free(metaOut);
  }
  else
    asfPrintError("Mode is not defined!\n");

  asfPrintStatus("Done.\n");
  exit(EXIT_SUCCESS);
}
Пример #28
0
int main(int argc, char **argv)
{
  char meta_name[255];
  char esri_name[255];
  meta_parameters *meta=NULL;
  esri_header *esri=NULL;
  FILE *fp;
  char line[255]="", key[25]="", value[25]="";
  extern int currArg; /* from cla.h in asf.h... initialized to 1 */
  logflag = 0;

  /* Parse command line args */
  while (currArg < (argc-2))
    {
      char *key=argv[currArg++];
      if (strmatch(key,"-log")) {
	sprintf(logFile, "%s", argv[currArg]);
	logflag = 1;
      }
      else {
	printf("\n   ***Invalid option:  %s\n\n",
	       argv[currArg-1]);
	usage(argv[0]);
      }
    }
  if ((argc-currArg) < 2) {
    printf("Insufficient arguments.\n"); 
    usage(argv[0]);
  }

  create_name(esri_name, argv[currArg], ".hdr");
  create_name(meta_name, argv[currArg+1], ".meta");

  asfSplashScreen(argc, argv);
  
  /* Allocate memory for ESRI header structure */
  esri = (esri_header *)MALLOC(sizeof(esri_header));

  /* Read .hdr and fill meta structures */ 
  fp = FOPEN(esri_name, "r");
  while (NULL != fgets(line, 255, fp)) {
    sscanf(line, "%s %s", key, value);
    if (strncmp(key, "NROWS", 5)==0) esri->nrows = atoi(value);
    else if (strncmp(key, "NCOLS", 5)==0) esri->ncols = atoi(value);
    else if (strncmp(key, "NBITS", 5)==0) {
      esri->nbits = atoi(value);
      if (esri->nbits < 8) {
        sprintf(errbuf, "\n   ERROR: metadata do not support data less than 8 bit\n\n");
        printErr(errbuf);
      }
    } 
    else if (strncmp(key, "NBANDS", 6)==0)
      esri->nbands = atoi(value);
    else if (strncmp(key, "BYTEORDER", 9)==0) esri->byteorder = value[0];
    else if (strncmp(key, "LAYOUT", 6)==0) {
      sprintf(esri->layout, "%s", value);
      if (strncmp(uc(esri->layout), "BSQ", 3)!=0) {
        sprintf(errbuf, "\n   ERROR: metadata do not support data other than BSQ format\n\n");
        printErr(errbuf);
      }
    }
    else if (strncmp(key, "SKIPBYTES", 9)==0) {
      esri->skipbytes = atoi(value);
      if (esri->skipbytes > 0) {
        sprintf(errbuf, "\n   ERROR: metadata only support generic binary data\n\n");
        printErr(errbuf);
      }
    }
    else if (strncmp(key, "ULXMAP", 6)==0) esri->ulxmap = atof(value);
    else if (strncmp(key, "ULYMAP", 6)==0) esri->ulymap = atof(value);
    else if (strncmp(key, "XDIM", 4)==0) esri->xdim = atof(value);
    else if (strncmp(key, "YDIM", 4)==0) esri->ydim = atof(value);
    /* bandrowbytes, totalrowbytes, bandgapdata and nodata currently not used */
  }
  FCLOSE(fp);

  /* Fill metadata structure with valid data */
  meta = esri2meta(esri);
  
  /* Write metadata file */
  meta_write(meta, meta_name);

  /* Clean and report */
  meta_free(meta);
  asfPrintStatus("   Converted ESRI header (%s) to metadata file (%s)\n\n",
		 esri_name, meta_name);
  
  return 0;
}
Пример #29
0
static int
test_rbt_gen(char *filename, char *command, char *testname,
	     isc_result_t exp_result)
{
	int		rval;
	int		result;
	dns_rbt_t	*rbt;
	isc_result_t	isc_result;
	isc_result_t	dns_result;
	isc_mem_t	*mctx;
	isc_entropy_t	*ectx;
	dns_name_t	*dns_name;

	result = T_UNRESOLVED;

	if (strcmp(command, "create") != 0)
		t_info("testing using name %s\n", testname);

	mctx = NULL;
	ectx = NULL;

	isc_result = isc_mem_create(0, 0, &mctx);
	if (isc_result != ISC_R_SUCCESS) {
		t_info("isc_mem_create: %s: exiting\n",
		       dns_result_totext(isc_result));
		return(T_UNRESOLVED);
	}

	isc_result = isc_entropy_create(mctx, &ectx);
	if (isc_result != ISC_R_SUCCESS) {
		t_info("isc_entropy_create: %s: exiting\n",
		       dns_result_totext(isc_result));
		isc_mem_destroy(&mctx);
		return(T_UNRESOLVED);
	}

	isc_result = isc_hash_create(mctx, ectx, DNS_NAME_MAXWIRE);
	if (isc_result != ISC_R_SUCCESS) {
		t_info("isc_hash_create: %s: exiting\n",
		       dns_result_totext(isc_result));
		isc_entropy_detach(&ectx);
		isc_mem_destroy(&mctx);
		return(T_UNRESOLVED);
	}

	rbt = NULL;
	if (rbt_init(filename, &rbt, mctx) != 0) {
		if (strcmp(command, "create") == 0)
			result = T_FAIL;
		isc_hash_destroy();
		isc_entropy_detach(&ectx);
		isc_mem_destroy(&mctx);
		return(result);
	}

	/*
	 * Now try the database command.
	 */
	if (strcmp(command, "create") == 0) {
		result = T_PASS;
	} else if (strcmp(command, "add") == 0) {
		if (create_name(testname, mctx, &dns_name) == 0) {
			dns_result = dns_rbt_addname(rbt, dns_name, dns_name);

			if (dns_result != ISC_R_SUCCESS)
				delete_name(dns_name, mctx);

			if (dns_result == exp_result) {
				if (dns_result == ISC_R_SUCCESS) {
					rval = t1_search(testname, rbt, mctx,
							 &dns_result);
					if (rval == 0) {
					     if (dns_result == ISC_R_SUCCESS) {
						     result = T_PASS;
					     } else {
						     result = T_FAIL;
					     }
					} else {
						t_info("t1_search failed\n");
						result = T_UNRESOLVED;
					}
				} else {
					result = T_PASS;
				}
			} else {
				t_info("dns_rbt_addname returned %s, "
				       "expected %s\n",
				       dns_result_totext(dns_result),
				       dns_result_totext(exp_result));
				result = T_FAIL;
			}
		} else {
			t_info("create_name failed\n");
			result = T_UNRESOLVED;
		}
	} else if ((strcmp(command, "delete") == 0) ||
		   (strcmp(command, "nuke") == 0)) {
		rval = t1_delete(testname, rbt, mctx, &dns_result);
		if (rval == 0) {
			if (dns_result == exp_result) {
				rval = t1_search(testname, rbt, mctx,
						 &dns_result);
				if (rval == 0) {
					if (dns_result == ISC_R_SUCCESS) {
						t_info("dns_rbt_deletename "
						       "didn't delete "
						       "the name");
						result = T_FAIL;
					} else {
						result = T_PASS;
					}
				}
			} else {
				t_info("delete returned %s, expected %s\n",
					dns_result_totext(dns_result),
					dns_result_totext(exp_result));
				result = T_FAIL;
			}
		}
	} else if (strcmp(command, "search") == 0) {
		rval = t1_search(testname, rbt, mctx, &dns_result);
		if (rval == 0) {
			if (dns_result == exp_result) {
				result = T_PASS;
			} else {
				t_info("find returned %s, expected %s\n",
					dns_result_totext(dns_result),
					dns_result_totext(exp_result));
				result = T_FAIL;
			}
		}
	}

	dns_rbt_destroy(&rbt);
	isc_hash_destroy();
	isc_entropy_detach(&ectx);
	isc_mem_destroy(&mctx);
	return(result);
}
Пример #30
0
int main(int argc, char **argv)
{
  double min, max;             /* Minimum & maximum sample values       */
  double sum_of_samples=0.0;   /* Sum of all samples accounted for      */
  double sum_of_squared_samples=0.0; /* Sum of all squared samples accounted for*/
  double trim_fraction;        /* Fraction used to trim the histogram   */
  int ii;                      /* Loop index                            */
  long samples_counted=0;      /* Number of all samples accounted for   */
  float *data_line;           /* Buffer for a line of samples          */
  long line, sample;            /* Line and sample indices               */
  long num_lines, num_samples;  /* Number of lines and samples           */
  int percent_complete=0;      /* Percent of data sweep completed       */
  int overmeta_flag=FALSE;     /* If TRUE write over current .meta file */
  int overstat_flag=FALSE;     /* If TRUE write over current .stat file */
  int nometa_flag=FALSE;       /* If TRUE do not write .meta file       */
  int nostat_flag=FALSE;       /* If TRUE do not write .stat file       */
  int mask_flag=FALSE;         /* TRUE if user specifies a mask value   */
  int trim_flag=FALSE;         /* If TRUE trim histogram                */
  double mask=NAN;             /* Value to ignore while caculating stats*/
  char meta_name[261];         /* Meta file name                        */
  meta_parameters *meta;       /* SAR meta data structure               */
  char sar_name[256];          /* SAR file name WITH extention          */
  FILE *sar_file;              /* SAR data file pointer to take stats on*/
  stat_parameters *stats;      /* Statistics structure                  */
  char stat_name[261];         /* Stats file name                       */
  extern int currArg;          /* Pre-initialized to 1                  */

  /* We initialize these to a magic number for checking. */
  long start_line = -1;         /* Window starting line.                 */
  long start_sample = -1;       /* Window starting sample.               */
  long window_height = -1;      /* Window height in lines.               */
  long window_width = -1;       /* Window width in samples.              */

/* parse command line */
  handle_license_and_version_args(argc, argv, "stats");
  logflag=quietflag=FALSE;
  while (currArg < (argc-1)) {
    char *key = argv[currArg++];
    if (strmatch(key,"-quiet")) {
      quietflag=TRUE;
    }
    else if (strmatch(key,"-log")) {
      CHECK_ARG(1);
      strcpy(logFile,GET_ARG(1));
      fLog = FOPEN(logFile, "a");
      logflag=TRUE;
    }
    else if (strmatch(key,"-mask")) {
      CHECK_ARG(1);
      mask = atof(GET_ARG(1));
      mask_flag=TRUE;
    }
    else if (strmatch(key,"-overmeta")) {
      overmeta_flag=TRUE;
    }
    else if (strmatch(key,"-overstat")) {
      overstat_flag=TRUE;
    }
    else if (strmatch(key,"-nometa")) {
      nometa_flag=TRUE;
    }
    else if (strmatch(key,"-nostat")) {
      nostat_flag=TRUE;
    }
    else if (strmatch(key,"-startline")) {
      CHECK_ARG(1);
      nometa_flag=TRUE; /* Implied.  */
      start_line = atol(GET_ARG(1));
      if ( start_line < 0 ) {
        printf("error: -startline argument must be greater than or equal to zero\n");
        usage(argv[0]);
      }
    }
    else if (strmatch(key,"-startsample")) {
      CHECK_ARG(1);
      nometa_flag=TRUE; /* Implied.  */
      start_sample = atol(GET_ARG(1));
      if ( start_sample < 0 ) {
        printf("error: -startsample argument must be greater than or equal to zero\n");
        usage(argv[0]);
      }
    }
    else if (strmatch(key,"-width")) {
      CHECK_ARG(1);
      nometa_flag=TRUE; /* Implied.  */
      window_width = atol(GET_ARG(1));
      if ( window_width < 0 ) {
        printf("error: -width argument must be greater than or equal to zero\n");
        usage(argv[0]);
      }
    }
    else if (strmatch(key,"-height")) {
      CHECK_ARG(1);
      nometa_flag=TRUE; /* Implied.  */
      window_height = atol(GET_ARG(1));
      if ( window_height < 0 ) {
        printf("error: -height argument must be greater than or equal to zero\n");
        usage(argv[0]);
      }
    }
    else if (strmatch(key,"-trim")) {
      CHECK_ARG(1);
      trim_flag=TRUE; /* Implied.  */
      trim_fraction = atof(GET_ARG(1));
    }
    else {printf( "\n**Invalid option:  %s\n",argv[currArg-1]); usage(argv[0]);}
  }

  if ((argc-currArg)<1) {printf("Insufficient arguments.\n"); usage(argv[0]);}
  strcpy (sar_name, argv[currArg]);
  char *ext = findExt(sar_name);
  if (ext == NULL || strcmp("IMG", uc(ext)) != 0) {
    strcpy(sar_name, appendExt(sar_name, ".img"));
  }
  create_name(meta_name, sar_name, ".meta");
  create_name(stat_name, sar_name, ".stat");

  printf("\nProgram: stats\n\n");
  if (logflag) {
    fprintf(fLog, "\nProgram: stats\n\n");
  }
  printf("\nCalculating statistics for %s\n\n", sar_name);
  if (logflag) {
    fprintf(fLog,"\nCalculating statistics for %s\n\n", sar_name);
  }
  meta = meta_read(meta_name);
  num_lines = meta->general->line_count;
  num_samples = meta->general->sample_count;

  if ( start_line == -1 ) start_line = 0;
  if ( start_line > num_lines ) {
    printf("error: -startline argument is larger than index of last line in image\n");
    exit(EXIT_FAILURE);
  }
  if ( start_sample == -1 ) start_sample = 0;
  if ( start_sample > num_samples ) {
    printf("error: -startsample argument is larger than index of last sample in image\n");
    exit(EXIT_FAILURE);
  }
  if ( window_height == -1 ) window_height = num_lines;
  if ( start_line + window_height > num_lines ) {
    printf("warning: window specified with -startline, -height options doesn't fit in image\n");
  }
  if ( window_width == -1 ) window_width = num_samples;
  if ( start_sample + window_width > num_samples ) {
    printf("warning: window specified with -startsample, -width options doesn't fit in image\n");
  }

/* Make sure we don't over write any files that we don't want to */
  if (meta->stats && !overmeta_flag && !nometa_flag) {
    printf(" ** The meta file already has a populated statistics structure.\n"
           " ** If you want to run this program and replace that structure,\n"
           " ** then use the -overmeta option to do so. If you want to run\n"
           " ** this program, but don't want to replace the structure, use\n"
           " ** the -nometa option.\n");
    if (logflag) {
      fprintf(fLog,
      " ** The meta file already has a populated statistics structure.\n"
      " ** If you want to run this program and replace that structure,\n"
      " ** then use the -overmeta option to do so. If you want to run\n"
      " ** this program, but don't want to replace the structure, use\n"
      " ** the -nometa option.\n");
    }
    exit(EXIT_FAILURE);
  }
  if (fileExists(stat_name) && !overstat_flag && !nostat_flag) {
    printf(" ** The file, %s, already exists. If you want to\n"
           " ** overwrite it, then use the -overstat option to do so.\n"
           " ** If you want to run the progam but don't want to write\n"
           " ** over the current file, then use the -nostat option.\n",
           stat_name);
    if (logflag) {
      fprintf(fLog,
      " ** The file, %s, already exists. If you want to\n"
      " ** overwrite it, then use the -overstat option to do so.\n"
      " ** If you want to run the progam but don't want to write\n"
      " ** over the current file, then use the -nostat option.\n",
      stat_name);
    }
    exit(EXIT_FAILURE);
  }

/* Let user know the window in which the stats will be taken */
  if ((start_line!=0) || (start_sample!=0)
      || (window_height!=num_lines) || (window_width!=num_samples)) {
        if (!quietflag) {
      printf("Taking statistics on a window with upper left corner (%ld,%ld)\n"
      "  and lower right corner (%ld,%ld)\n",
      start_sample, start_line,
      window_width+start_sample, window_height+start_line);
    }
    if (logflag && !quietflag) {
      fprintf(fLog,
        "Taking statistics on a window with upper left corner (%ld,%ld)\n"
      "  and lower right corner (%ld,%ld)\n",
      start_sample, start_line,
      window_width+start_sample, window_height+start_line);
    }

  }

/* Allocate line buffer */
  data_line = (float *)MALLOC(sizeof(float)*num_samples);
  if (meta->stats) FREE(meta->stats);
  if (meta->general->band_count <= 0) {
    printf(" ** Band count in the existing data is missing or less than zero.\nDefaulting to one band.\n");
    if (logflag) {
      fprintf(fLog, " ** Band count in the existing data is missing or less than zero.\nDefaulting to one band.\n");
    }
    meta->general->band_count = 1;
  }
  meta->stats = meta_statistics_init(meta->general->band_count);
  if (!meta->stats) {
    printf(" ** Cannot allocate memory for statistics data structures.\n");
    if (logflag) {
      fprintf(fLog, " ** Cannot allocate memory for statistics data structures.\n");
    }
    exit(EXIT_FAILURE);
  }
  stats = (stat_parameters *)MALLOC(sizeof(stat_parameters) * meta->stats->band_count);
  if (!stats) {
    printf(" ** Cannot allocate memory for statistics data structures.\n");
    if (logflag) {
      fprintf(fLog, " ** Cannot allocate memory for statistics data structures.\n");
    }
    exit(EXIT_FAILURE);
  }

  int  band;
  long band_offset;
  for (band = 0; band < meta->stats->band_count; band++) {
    /* Find min, max, and mean values */
    if (!quietflag) printf("\n");
    if (logflag && !quietflag) fprintf(fLog,"\n");
    min = 100000000;
    max = -100000000;
    sum_of_samples=0.0;
    sum_of_squared_samples=0.0;
    percent_complete=0;
    band_offset = band * meta->general->line_count;
    sar_file = FOPEN(sar_name, "r");
    for (line=start_line+band_offset; line<start_line+window_height+band_offset; line++) {
      if (!quietflag) asfPercentMeter((float)(line-start_line-band_offset)/(float)(window_height-start_line));
      get_float_line(sar_file, meta, line, data_line);
      for (sample=start_sample; sample<start_sample+window_width; sample++) {
        if ( mask_flag && FLOAT_EQUIVALENT(data_line[sample],mask) )
          continue;
        if (data_line[sample] < min) min=data_line[sample];
        if (data_line[sample] > max) max=data_line[sample];
        sum_of_samples += data_line[sample];
        sum_of_squared_samples += SQR(data_line[sample]);
        samples_counted++;
      }
    }
    if (!quietflag) asfPercentMeter(1.0);
//    if (!quietflag) printf("\rFirst data sweep: 100%% complete.\n");
    FCLOSE(sar_file);

    stats[band].min = min;
    stats[band].max = max;
    stats[band].upper_left_line = start_line;
    stats[band].upper_left_samp = start_sample;
    stats[band].lower_right_line = start_line + window_height;
    stats[band].lower_right_samp = start_sample + window_width;
    stats[band].mask = mask;

    stats[band] = calc_hist(stats[band], sar_name, band, meta, sum_of_samples,
                      samples_counted, mask_flag);


  /* Remove outliers and trim the histogram by resetting the minimum and
    and maximum */
    if (trim_flag) {
      register int sum=0, num_pixels, minDex=0, maxDex=255;
      double overshoot, width;

      num_pixels = (int)(samples_counted*trim_fraction);
      minDex = 0;
      while (sum < num_pixels)
        sum += stats[band].histogram[minDex++];
      if (minDex-1>=0)
        overshoot = (double)(num_pixels-sum)/stats[band].histogram[minDex-1];
      else
        overshoot = 0;
      stats[band].min = (minDex-overshoot-stats[band].offset)/stats[band].slope;

      sum=0;
      while (sum < num_pixels)
        sum += stats[band].histogram[maxDex--];
      if (maxDex+1<256)
        overshoot = (double)(num_pixels-sum)/stats[band].histogram[maxDex+1];
      else
        overshoot = 0;
      stats[band].max = (maxDex+1+overshoot-stats[band].offset)/stats[band].slope;

      /* Widening the range for better visual effect */
      width = (stats[band].max-stats[band].min)*(1/(1.0-2*trim_fraction)-1);
      stats[band].min -= width/2;
      stats[band].max += width/2;

      /* Couple useful corrections borrowed from SARview */
      if ((stats[band].max-stats[band].min) < 0.01*(max-min)) {
        stats[band].max = max;
        stats[band].min = min;
      }
      if (min == 0.0)
        stats[band].min=0.0;
      if (stats[band].min == stats[band].max)
        stats[band].max = stats[band].min + MICRON;

      stats[band].slope = 255.0/(stats[band].max-stats[band].min);
      stats[band].offset = -stats[band].slope*stats[band].min;

      stats[band] = calc_hist(stats[band], sar_name, band, meta, sum_of_samples,
                        samples_counted, mask_flag);
    }
  }
  if(data_line)FREE(data_line);

  /* Populate meta->stats structure */
  char **band_names = NULL;
  if (meta_is_valid_string(meta->general->bands) &&
      strlen(meta->general->bands)               &&
      meta->general->band_count > 0)
  {
    band_names = extract_band_names(meta->general->bands, meta->general->band_count);
  }
  else {
    if (meta->general->band_count <= 0) meta->general->band_count = 1;
    band_names = (char **) MALLOC (meta->general->band_count * sizeof(char *));
    int i;
    for (i=0; i<meta->general->band_count; i++) {
      band_names[i] = (char *) MALLOC (64 * sizeof(char));
      sprintf(band_names[i], "%02d", i);
    }
  }
  int band_no;
  for (band_no = 0; band_no < meta->stats->band_count; band_no++) {
    strcpy(meta->stats->band_stats[band_no].band_id, band_names[band_no]);
    meta->stats->band_stats[band_no].min = stats[band_no].min;
    meta->stats->band_stats[band_no].max = stats[band_no].max;
    meta->stats->band_stats[band_no].mean = stats[band_no].mean;
    meta->stats->band_stats[band_no].rmse = stats[band_no].rmse;
    meta->stats->band_stats[band_no].std_deviation = stats[band_no].std_deviation;
    meta->stats->band_stats[band_no].mask = stats[band_no].mask;
  }
  if (band_names) {
    int i;
    for (i=0; i<meta->general->band_count; i++) {
      if (band_names[i]) FREE (band_names[i]);
    }
    FREE(band_names);
  }

/* Print findings to the screen (and log file if applicable)*/
  if (!quietflag) {
    printf("\n");
    printf("Statistics found:\n");
    if (mask_flag)
      { printf("Used mask %-16.11g\n",mask); }
    printf("Number of bands: %d\n", meta->stats->band_count);
    for (band=0; band<meta->stats->band_count; band++) {
      printf("\n\nBand name = \"%s\"\n", meta->stats->band_stats[band].band_id);
      printf("Minimum = %-16.11g\n",stats[band].min);
      printf("Maximum = %-16.11g\n",stats[band].max);
      printf("Mean = %-16.11g\n",stats[band].mean);
      printf("Root mean squared error = %-16.11g\n",
            stats[band].rmse);
      printf("Standard deviation = %-16.11g\n",
            stats[band].std_deviation);
      printf("\n");
      printf("Data fit to [0..255] using equation:  byte = %g * sample + %g\n",
            stats[band].slope, stats[band].offset);
                  if (trim_flag)
                    printf("Trimming fraction = %.3g\n", trim_fraction);
      printf("\n");
      printf("Histogram:\n");
      for (ii=0; ii<256; ii++) {
        if (ii%8 == 0) {
          printf("%s%3i-%3i:",
            (ii==0) ? "" : "\n",
            ii, ii+7);
        }
        printf(" %8i", stats[band].histogram[ii]);
      }
      printf("\n");
    }
  }
  if (logflag && !quietflag) {
    fprintf(fLog,"Statistics found:\n");
    if (mask_flag)
      { fprintf(fLog,"Used mask %-16.11g\n",mask); }
    fprintf(fLog,"Number of bands: %d\n", meta->stats->band_count);
    for (band=0; band<meta->stats->band_count; band++) {
      fprintf(fLog,"\n\nBand name = \"%s\"\n", meta->stats->band_stats[band].band_id);
      fprintf(fLog,"Minimum = %-16.11g\n",stats[band].min);
      fprintf(fLog,"Maximum = %-16.11g\n",stats[band].max);
      fprintf(fLog,"Mean = %-16.11g\n",stats[band].mean);
      fprintf(fLog,"Root mean squared error = %-16.11g\n",
             stats[band].rmse);
      fprintf(fLog,"Standard deviation = %-16.11g\n",
             stats[band].std_deviation);
      fprintf(fLog,"\n");
      fprintf(fLog,"Data fit to [0..255] using equation:  byte = %g * sample + %g\n",
             stats[band].slope, stats[band].offset);
      if (trim_flag)
        fprintf(fLog,"Trimming fraction = %.3g\n", trim_fraction);
      fprintf(fLog,"\n");
      fprintf(fLog,"Histogram:\n");
      for (ii=0; ii<256; ii++) {
        if (ii%8 == 0) {
          fprintf(fLog,"%s%3i-%3i:",
                 (ii==0) ? "" : "\n",
                 ii, ii+7);
        }
        fprintf(fLog," %8i", stats[band].histogram[ii]);
      }
      fprintf(fLog,"\n");
    }
  }

/* Write out .meta and .stat files */
  if (!nometa_flag) meta_write(meta, meta_name);
  if (!nostat_flag) stat_write(stats, stat_name, meta->stats->band_count);

/* Free the metadata structure */
  meta_free(meta);

/* Report */
  if (!quietflag) {
    printf("\n");
    printf("Statistics taken on image file %s.\n",sar_name);
    if (!nometa_flag)
      printf("Statistics written to the stats block in %s.\n",
        meta_name);
    if (!nostat_flag)
      printf("Statistics plus histogram written to %s.\n",
        stat_name);
    printf("\n");
  }
  if (logflag && !quietflag) {
    fprintf(fLog,"\n");
    fprintf(fLog,"Statistics taken on image file '%s'\n",sar_name);
    if (!nometa_flag)
      fprintf(fLog,"Statistics written to the stats block in %s\n",
        meta_name);
    if (!nostat_flag)
      fprintf(fLog,"Statistics plus histogram written to %s\n",
        stat_name);
    fprintf(fLog,"\n");
  }

  if (fLog) FCLOSE(fLog);
  return 0;
}