Пример #1
0
/*--------------------------------------------------------------------*/
int mbr_dem_hsurivax(int verbose, void *mbio_ptr, int *error) {
	char *function_name = "mbr_dem_hsurivax";
	int status = MB_SUCCESS;
	struct mb_io_struct *mb_io_ptr;

	/* print input debug statements */
	if (verbose >= 2) {
		fprintf(stderr, "\ndbg2  MBIO function <%s> called\n", function_name);
		fprintf(stderr, "dbg2  Revision id: %s\n", rcs_id);
		fprintf(stderr, "dbg2  Input arguments:\n");
		fprintf(stderr, "dbg2       verbose:    %d\n", verbose);
		fprintf(stderr, "dbg2       mbio_ptr:   %p\n", (void *)mbio_ptr);
	}

	/* get pointer to mbio descriptor */
	mb_io_ptr = (struct mb_io_struct *)mbio_ptr;

	/* deallocate memory for data descriptor */
	status = mb_freed(verbose, __FILE__, __LINE__, (void **)&mb_io_ptr->raw_data, error);
	status = mb_freed(verbose, __FILE__, __LINE__, (void **)&mb_io_ptr->store_data, error);

	/* print output debug statements */
	if (verbose >= 2) {
		fprintf(stderr, "\ndbg2  MBIO function <%s> completed\n", function_name);
		fprintf(stderr, "dbg2  Return values:\n");
		fprintf(stderr, "dbg2       error:      %d\n", *error);
		fprintf(stderr, "dbg2  Return status:\n");
		fprintf(stderr, "dbg2       status:  %d\n", status);
	}

	/* return status */
	return (status);
}
Пример #2
0
/*------------------------------------------------------------------------------*/
int mbview_freevectorarrays(int verbose,
			double	**veclon,
			double	**veclat,
			double	**vecz,
			double	**vecdata,
			int *error)
{
	/* local variables */
	char	*function_name = "mbview_freevectorarrays";
	int	status = MB_SUCCESS;

	/* print starting debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  MBIO function <%s> called\n",
			function_name);
		fprintf(stderr,"dbg2  MB-system Version %s\n",MB_VERSION);
		fprintf(stderr,"dbg2  Input arguments:\n");
		fprintf(stderr,"dbg2       verbose:                   %d\n", verbose);
		fprintf(stderr,"dbg2       veclon:                    %lu\n", (size_t)*veclon);
		fprintf(stderr,"dbg2       veclat:                    %lu\n", (size_t)*veclat);
		fprintf(stderr,"dbg2       vecz:                      %lu\n", (size_t)*vecz);
		fprintf(stderr,"dbg2       vecdata:                   %lu\n", (size_t)*vecdata);
		}

	/* free the arrays using mb_free */
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)veclon,error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)veclat,error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)vecz,error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)vecdata,error);

	/* print output debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  MBIO function <%s> completed\n",
			function_name);
		fprintf(stderr,"dbg2  Return values:\n");
		fprintf(stderr,"dbg2       veclon:                    %lu\n", (size_t)*veclon);
		fprintf(stderr,"dbg2       veclat:                    %lu\n", (size_t)*veclat);
		fprintf(stderr,"dbg2       vecz:                      %lu\n", (size_t)*vecz);
		fprintf(stderr,"dbg2       vecdata:                   %lu\n", (size_t)*vecdata);
		fprintf(stderr,"dbg2       error:                     %d\n", *error);
		fprintf(stderr,"dbg2  Return status:\n");
		fprintf(stderr,"dbg2       status:                    %d\n", status);
		}

	/* return */
	return(status);
}
Пример #3
0
/*--------------------------------------------------------------------*/
int mbr_dem_em12darw(int verbose, void *mbio_ptr, int *error) {
	char *function_name = "mbr_dem_em12darw";
	int status = MB_SUCCESS;
	struct mb_io_struct *mb_io_ptr;
	struct mbsys_simrad_struct *store;

	/* print input debug statements */
	if (verbose >= 2) {
		fprintf(stderr, "\ndbg2  MBIO function <%s> called\n", function_name);
		fprintf(stderr, "dbg2  Input arguments:\n");
		fprintf(stderr, "dbg2       verbose:    %d\n", verbose);
		fprintf(stderr, "dbg2       mbio_ptr:   %p\n", (void *)mbio_ptr);
	}

	/* get pointers to mbio descriptor and data structures */
	mb_io_ptr = (struct mb_io_struct *)mbio_ptr;
	store = (struct mbsys_simrad_struct *)mb_io_ptr->store_data;

	/* deallocate memory for data descriptor */
	status = mb_freed(verbose, __FILE__, __LINE__, (void **)&mb_io_ptr->raw_data, error);
	status = mbsys_simrad_deall(verbose, mbio_ptr, &mb_io_ptr->store_data, error);

	/* print output debug statements */
	if (verbose >= 2) {
		fprintf(stderr, "\ndbg2  MBIO function <%s> completed\n", function_name);
		fprintf(stderr, "dbg2  Return values:\n");
		fprintf(stderr, "dbg2       error:      %d\n", *error);
		fprintf(stderr, "dbg2  Return status:\n");
		fprintf(stderr, "dbg2       status:  %d\n", status);
	}

	return (status);
}
Пример #4
0
/*----------------------------------------------------------------------*/
static int remove_rejected_samps(int verbose, swpls_sxpping *ping, int *error) {
	char *function_name = "remove_rejected_samps";
	int status = MB_SUCCESS;
	swpls_point *points;
	int valid, i;

	if (verbose >= 2) {
		fprintf(stderr, "\ndbg2  function <%s> called\n", function_name);
		fprintf(stderr, "dbg2  Revision id: %s\n", rcs_id);
		fprintf(stderr, "dbg2  Input arguments:\n");
		fprintf(stderr, "dbg2       verbose:     %d\n", verbose);
		fprintf(stderr, "dbg2       ping:        %p\n", (void *)ping);
	}

	/* count the number of valid samples */
	valid = 0;
	for (i = 0; i < ping->nosampsfile; i++) {
		if (ping->points[i].status != SWPLS_POINT_REJECTED) {
			valid++;
		}
	}

	/* create a temporary array to hold the valid samples */
	status = mb_mallocd(verbose, __FILE__, __LINE__, valid * sizeof(swpls_point), (void **)&points, error);
	if (status != MB_SUCCESS) {
		char message[MAX_ERROR_STRING] = {0};
		sprintf(message, "Failure to allocate memory for temporary array (%lu bytes)", valid * sizeof(swpls_point));
		error_exit(verbose, *error, "mb_mallocd", message);
	}

	/* copy the valid samples to the temporary array */
	valid = 0;
	for (i = 0; i < ping->nosampsfile; i++) {
		if (ping->points[i].status != SWPLS_POINT_REJECTED) {
			points[valid++] = ping->points[i];
		}
	}

	/* copy the valid samples to the front of the ping->points array and adjust
	   the sample count. This effectively truncates the ping on write. */
	for (i = 0; i < valid; i++) {
		ping->points[i] = points[i];
	}
	ping->nosampsfile = valid;

	/* free memory for the temporary points array */
	status = mb_freed(verbose, __FILE__, __LINE__, (void **)&points, error);

	if (verbose >= 2) {
		fprintf(stderr, "\ndbg2  function <%s> completed\n", function_name);
		fprintf(stderr, "dbg2  Return values:\n");
		fprintf(stderr, "dbg2       error:      %d\n", *error);
		fprintf(stderr, "dbg2  Return status:\n");
		fprintf(stderr, "dbg2       status:     %d\n", status);
	}

	return (status);
} /* remove_rejected_samps */
Пример #5
0
/*--------------------------------------------------------------------*/
int mbsys_stereopair_deall(int verbose, void *mbio_ptr, void **store_ptr,
			int *error)
{
	char	*function_name = "mbsys_stereopair_deall";
	int	status = MB_SUCCESS;
	struct mbsys_stereopair_struct *store;

	/* print input debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  MBIO function <%s> called\n",function_name);
		fprintf(stderr,"dbg2  Revision id: %s\n",version_id);
		fprintf(stderr,"dbg2  Input arguments:\n");
		fprintf(stderr,"dbg2       verbose:    %d\n",verbose);
		fprintf(stderr,"dbg2       mbio_ptr:   %p\n",(void *)mbio_ptr);
		fprintf(stderr,"dbg2       store_ptr:  %p\n",(void *)*store_ptr);
		}

	/* get data structure pointer */
	store = (struct mbsys_stereopair_struct *) *store_ptr;
	
	/* deallocate any arrays or structures contained within the store data structure */
	if (store->num_soundings_alloc > 0 && store->soundings != NULL)
		status = mb_freed(verbose,__FILE__,__LINE__,(void **)(&store->soundings),error);

	/* deallocate memory for data structure */
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)store_ptr,error);

	/* print output debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  MBIO function <%s> completed\n",function_name);
		fprintf(stderr,"dbg2  Return values:\n");
		fprintf(stderr,"dbg2       error:      %d\n",*error);
		fprintf(stderr,"dbg2  Return status:\n");
		fprintf(stderr,"dbg2       status:     %d\n",status);
		}

	/* return status */
	return(status);
}
Пример #6
0
/*--------------------------------------------------------------------*/
int mb_topogrid_deall(int verbose, void **topogrid_ptr, int *error)
{
	char	*function_name = "mb_topogrid_deall";
	int	status = MB_SUCCESS;
	struct mb_topogrid_struct *topogrid;

	/* print input debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  MBIO function <%s> called\n", function_name);
		fprintf(stderr,"dbg2  Revision id: %s\n",rcs_id);
		fprintf(stderr,"dbg2  Input arguments:\n");
		fprintf(stderr,"dbg2       verbose:                   %d\n", verbose);
		fprintf(stderr,"dbg2       topogrid_ptr:              %p\n", topogrid_ptr);
		fprintf(stderr,"dbg2       topogrid:                  %p\n", *topogrid_ptr);
		}

	/* deallocate the topogrid structure */
	topogrid = (struct mb_topogrid_struct *) *topogrid_ptr;
	if (topogrid->data != NULL)
		status = mb_freed(verbose, __FILE__, __LINE__, (void **)&(topogrid->data), error);
	status = mb_freed(verbose,__FILE__, __LINE__, (void **)topogrid_ptr,error);

	/* print output debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  MB7K2SS function <%s> completed\n",
			function_name);
		fprintf(stderr,"dbg2  Return values:\n");
		fprintf(stderr,"dbg2       error:                     %d\n",*error);
		fprintf(stderr,"dbg2  Return status:\n");
		fprintf(stderr,"dbg2       status:                    %d\n",status);
		}

	/* return status */
	return(status);
}
Пример #7
0
/*--------------------------------------------------------------------*/
int mbr_dem_swplssxp(int verbose, void *mbio_ptr, int *error) {
	char *function_name = "mbr_dem_swplssxp";
	int status = MB_SUCCESS;
	struct mb_io_struct *mb_io_ptr;
	char **bufferptr;
	char *buffer;
	int *bufferalloc;

	/* print input debug statements */
	if (verbose >= 2) {
		fprintf(stderr, "\ndbg2  MBIO function <%s> called\n", function_name);
		fprintf(stderr, "dbg2  Revision id: %s\n", rcs_id);
		fprintf(stderr, "dbg2  Input arguments:\n");
		fprintf(stderr, "dbg2       verbose:    %d\n", verbose);
		fprintf(stderr, "dbg2       mbio_ptr:   %p\n", mbio_ptr);
	}

	/* get pointers to mbio descriptor */
	mb_io_ptr = (struct mb_io_struct *)mbio_ptr;

	/* deallocate memory for data descriptor */
	status = mbsys_swathplus_deall(verbose, mbio_ptr, &mb_io_ptr->store_data, error);

	/* deallocate memory for reading/writing buffer */
	bufferptr = (char **)&mb_io_ptr->saveptr1;
	buffer = (char *)*bufferptr;
	bufferalloc = (int *)&mb_io_ptr->save6;
	status = mb_freed(verbose, __FILE__, __LINE__, (void **)bufferptr, error);
	*bufferalloc = 0;

	/* print output debug statements */
	if (verbose >= 2) {
		fprintf(stderr, "\ndbg2  MBIO function <%s> completed\n", function_name);
		fprintf(stderr, "dbg2  Return values:\n");
		fprintf(stderr, "dbg2       error:   %d\n", *error);
		fprintf(stderr, "dbg2  Return status:\n");
		fprintf(stderr, "dbg2       status:  %d\n", status);
	}

	/* return status */
	return (status);
} /* mbr_dem_swplssxp */
Пример #8
0
/*--------------------------------------------------------------------*/
int mbr_dem_gsfgenmb(int verbose, void *mbio_ptr, int *error) {
	char *function_name = "mbr_dem_gsfgenmb";
	int status = MB_SUCCESS;
	struct mb_io_struct *mb_io_ptr;
	struct mbf_gsfgenmb_struct *data;
	gsfRecords *records;

	/* print input debug statements */
	if (verbose >= 2) {
		fprintf(stderr, "\ndbg2  MBIO function <%s> called\n", function_name);
		fprintf(stderr, "dbg2  Input arguments:\n");
		fprintf(stderr, "dbg2       verbose:    %d\n", verbose);
		fprintf(stderr, "dbg2       mbio_ptr:   %p\n", (void *)mbio_ptr);
	}

	/* get pointer to mbio descriptor */
	mb_io_ptr = (struct mb_io_struct *)mbio_ptr;
	data = (struct mbf_gsfgenmb_struct *)mb_io_ptr->raw_data;
	records = &(data->records);

	/* deallocate memory for data descriptor */
	/*gsfFree(records);*/
	status = mb_freed(verbose, __FILE__, __LINE__, (void **)&mb_io_ptr->raw_data, error);
	status = mbsys_gsf_deall(verbose, mbio_ptr, &mb_io_ptr->store_data, error);

	/* print output debug statements */
	if (verbose >= 2) {
		fprintf(stderr, "\ndbg2  MBIO function <%s> completed\n", function_name);
		fprintf(stderr, "dbg2  Return values:\n");
		fprintf(stderr, "dbg2       error:      %d\n", *error);
		fprintf(stderr, "dbg2  Return status:\n");
		fprintf(stderr, "dbg2       status:  %d\n", status);
	}

	return (status);
}
Пример #9
0
int main (int argc, char **argv)
{
	extern char *optarg;
	int	errflg = 0;
	int	c;
	int	help = 0;
	int	flag = 0;

	/* MBIO status variables */
	int	status = MB_SUCCESS;
	int	verbose = 0;
	int	error = MB_ERROR_NO_ERROR;
	char	*message;

	/* MBIO read control parameters */
	int	format;
	int	pings;
	int	lonflip;
	double	bounds[4];
	int	btime_i[7];
	int	etime_i[7];
	double	btime_d;
	double	etime_d;
	double	speedmin;
	double	timegap;
	int	beams_bath;
	int	beams_amp;
	int	pixels_ss;
	void	*mbio_ptr = NULL;

	/* mbrollbias control variables */
	int	iformat;
	int	jformat;
	char	ifile[MB_PATH_MAXLINE];
	char	jfile[MB_PATH_MAXLINE];
	int	xdim, ydim;

	/* mbio read values */
	int	rpings;
	int	kind;
	int	time_i[7];
	double	time_d;
	double	navlon;
	double	navlat;
	double	speed;
	double	heading;
	double	distance;
	double	altitude;
	double	sonardepth;
	char	*beamflag = NULL;
	double	*bath = NULL;
	double	*bathlon = NULL;
	double	*bathlat = NULL;
	double	*amp = NULL;
	double	*ss = NULL;
	double	*sslon = NULL;
	double	*sslat = NULL;
	char	comment[MB_COMMENT_MAXLINE];

	/* grid variables */
	double	deglontokm, deglattokm;
	double	mtodeglon, mtodeglat;
	double	dx, dy;
	int	*icount = NULL;
	int	*jcount = NULL;
	struct bathptr	*idata = NULL;
	struct bathptr	*jdata = NULL;
	struct bath	*zone = NULL;
	int	ndatafile;
	double	iaa, ibb, icc, ihh;
	double	jaa, jbb, jcc, jhh;
	double	hx, hy, dd;
	double	isine, icosine, jsine, jcosine;
	double	roll_bias;

	/* matrix parameters */
	int	nmatrix = 3;
	double	matrix[3][3];
	double	vector[3];
	double	xx[3];

	/* output stream for basic stuff (stdout if verbose <= 1,
		stderr if verbose > 1) */
	FILE	*outfp;

	/* other variables */
	int	i, j, k;
	int	ii, jj, kk;
	int	ib, ix, iy, indx;

	/* get current default values */
	status = mb_defaults(verbose,&format,&pings,&lonflip,bounds,
		btime_i,etime_i,&speedmin,&timegap);

	/* set default input and output */
	strcpy (ifile, "\0");
	strcpy (jfile, "\0");

	/* initialize some values */
	pings = 1;
	iformat = format;
	jformat = format;
	btime_i[0] = 1962;
	btime_i[1] = 2;
	btime_i[2] = 21;
	btime_i[3] = 10;
	btime_i[4] = 30;
	btime_i[5] = 0;
	btime_i[6] = 0;
	etime_i[0] = 2062;
	etime_i[1] = 2;
	etime_i[2] = 21;
	etime_i[3] = 10;
	etime_i[4] = 30;
	etime_i[5] = 0;
	etime_i[6] = 0;
	speedmin = 0.0;
	timegap = 1000000000.0;
	bounds[0] = 0.0;
	bounds[1] = 0.0;
	bounds[2] = 0.0;
	bounds[3] = 0.0;
	xdim = 5;
	ydim = 5;

	/* process argument list */
	while ((c = getopt(argc, argv, "VvHhL:l:R:r:F:f:I:i:J:j:D:d:")) != -1)
	  switch (c)
		{
		case 'H':
		case 'h':
			help++;
			break;
		case 'V':
		case 'v':
			verbose++;
			break;
		case 'L':
		case 'l':
			sscanf (optarg,"%d", &lonflip);
			flag++;
			break;
		case 'R':
		case 'r':
			mb_get_bounds(optarg, bounds);
			flag++;
			break;
		case 'F':
		case 'f':
			sscanf (optarg,"%d/%d", &iformat,&jformat);
			flag++;
			break;
		case 'I':
		case 'i':
			sscanf (optarg,"%s", ifile);
			flag++;
			break;
		case 'J':
		case 'j':
			sscanf (optarg,"%s", jfile);
			flag++;
			break;
		case 'D':
		case 'd':
			sscanf (optarg,"%d/%d", &xdim, &ydim);
			flag++;
			break;
		case '?':
			errflg++;
		}

	/* set output stream */
	if (verbose <= 1)
		outfp = stdout;
	else
		outfp = stderr;

	/* if error flagged then print it and exit */
	if (errflg)
		{
		fprintf(outfp,"usage: %s\n", usage_message);
		fprintf(outfp,"\nProgram <%s> Terminated\n",
			program_name);
		error = MB_ERROR_BAD_USAGE;
		exit(error);
		}

	/* print starting message */
	if (verbose == 1 || help)
		{
		fprintf(outfp,"\nProgram %s\n",program_name);
		fprintf(outfp,"Version %s\n",rcs_id);
		fprintf(outfp,"MB-system Version %s\n",MB_VERSION);
		}

	/* print starting debug statements */
	if (verbose >= 2)
		{
		fprintf(outfp,"\ndbg2  Program <%s>\n",program_name);
		fprintf(outfp,"dbg2  Version %s\n",rcs_id);
		fprintf(outfp,"dbg2  MB-system Version %s\n",MB_VERSION);
		fprintf(outfp,"dbg2  Control Parameters:\n");
		fprintf(outfp,"dbg2       verbose:          %d\n",verbose);
		fprintf(outfp,"dbg2       help:             %d\n",help);
		fprintf(outfp,"dbg2       pings:            %d\n",pings);
		fprintf(outfp,"dbg2       lonflip:          %d\n",lonflip);
		fprintf(outfp,"dbg2       btime_i[0]:       %d\n",btime_i[0]);
		fprintf(outfp,"dbg2       btime_i[1]:       %d\n",btime_i[1]);
		fprintf(outfp,"dbg2       btime_i[2]:       %d\n",btime_i[2]);
		fprintf(outfp,"dbg2       btime_i[3]:       %d\n",btime_i[3]);
		fprintf(outfp,"dbg2       btime_i[4]:       %d\n",btime_i[4]);
		fprintf(outfp,"dbg2       btime_i[5]:       %d\n",btime_i[5]);
		fprintf(outfp,"dbg2       btime_i[6]:       %d\n",btime_i[6]);
		fprintf(outfp,"dbg2       etime_i[0]:       %d\n",etime_i[0]);
		fprintf(outfp,"dbg2       etime_i[1]:       %d\n",etime_i[1]);
		fprintf(outfp,"dbg2       etime_i[2]:       %d\n",etime_i[2]);
		fprintf(outfp,"dbg2       etime_i[3]:       %d\n",etime_i[3]);
		fprintf(outfp,"dbg2       etime_i[4]:       %d\n",etime_i[4]);
		fprintf(outfp,"dbg2       etime_i[5]:       %d\n",etime_i[5]);
		fprintf(outfp,"dbg2       etime_i[6]:       %d\n",etime_i[6]);
		fprintf(outfp,"dbg2       speedmin:         %f\n",speedmin);
		fprintf(outfp,"dbg2       timegap:          %f\n",timegap);
		fprintf(outfp,"dbg2       input file 1:     %s\n",ifile);
		fprintf(outfp,"dbg2       input file 2:     %s\n",jfile);
		fprintf(outfp,"dbg2       file 1 format:    %d\n",iformat);
		fprintf(outfp,"dbg2       file 2 format:    %d\n",jformat);
		fprintf(outfp,"dbg2       grid x dimension: %d\n",xdim);
		fprintf(outfp,"dbg2       grid y dimension: %d\n",ydim);
		fprintf(outfp,"dbg2       grid bounds[0]:   %f\n",bounds[0]);
		fprintf(outfp,"dbg2       grid bounds[1]:   %f\n",bounds[1]);
		fprintf(outfp,"dbg2       grid bounds[2]:   %f\n",bounds[2]);
		fprintf(outfp,"dbg2       grid bounds[3]:   %f\n",bounds[3]);
		}

	/* if help desired then print it and exit */
	if (help)
		{
		fprintf(outfp,"\n%s\n",help_message);
		fprintf(outfp,"\nusage: %s\n", usage_message);
		exit(error);
		}

	/* get format if required */
	if (format == 0)
		mb_get_format(verbose,ifile,NULL,&format,&error);

	/* if bounds not specified then quit */
	if (bounds[0] >= bounds[1] || bounds[2] >= bounds[3]
		|| bounds[2] <= -90.0 || bounds[3] >= 90.0)
		{
		fprintf(outfp,"\nGrid bounds not properly specified:\n\t%f %f %f %f\n",bounds[0],bounds[1],bounds[2],bounds[3]);
		fprintf(outfp,"\nProgram <%s> Terminated\n",
			program_name);
		error = MB_ERROR_BAD_PARAMETER;
		exit(error);
		}

	/* calculate grid properties and other values */
	mb_coor_scale(verbose,0.5*(bounds[2]+bounds[3]),&mtodeglon,&mtodeglat);
	deglontokm = 0.001/mtodeglon;
	deglattokm = 0.001/mtodeglat;
	dx = (bounds[1] - bounds[0])/(xdim);
	dy = (bounds[3] - bounds[2])/(ydim);

	/* output info */
	if (verbose >= 0)
		{
		fprintf(outfp,"\nMBROLLBIAS Parameters:\n");
		fprintf(outfp,"Input file 1:     %s\n",ifile);
		fprintf(outfp,"Input file 2:     %s\n",jfile);
		fprintf(outfp,"Region grid bounds:\n");
		fprintf(outfp,"  Longitude: %9.4f %9.4f\n",bounds[0],bounds[1]);
		fprintf(outfp,"  Latitude:  %9.4f %9.4f\n",bounds[2],bounds[3]);
		fprintf(outfp,"Region grid dimensions: %d %d\n",xdim,ydim);
		fprintf(outfp,"Longitude interval: %f degrees or %f km\n",
			dx,dx*deglontokm);
		fprintf(outfp,"Latitude interval:  %f degrees or %f km\n",
			dy,dy*deglattokm);
		fprintf(outfp,"Longitude flipping:   %d\n",lonflip);
		fprintf(outfp,"\n");
		}

	/* allocate memory for counting arrays */
	status = mb_mallocd(verbose,__FILE__,__LINE__,xdim*ydim*sizeof(int),(void **)&icount,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,xdim*ydim*sizeof(int),(void **)&jcount,&error);

	/* if error initializing memory then quit */
	if (error != MB_ERROR_NO_ERROR)
		{
		mb_error(verbose,error,&message);
		fprintf(outfp,"\nMBIO Error allocating data arrays:\n%s\n",
			message);
		fprintf(outfp,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* initialize arrays */
	for (i=0;i<xdim*ydim;i++)
		{
		icount[i] = 0;
		jcount[i] = 0;
		}

	/* count data in first swath file */

	/* initialize the first swath file */
	ndatafile = 0;
	if ((status = mb_read_init(
		verbose,ifile,iformat,pings,lonflip,bounds,
		btime_i,etime_i,speedmin,timegap,
		&mbio_ptr,&btime_d,&etime_d,
		&beams_bath,&beams_amp,&pixels_ss,&error)) != MB_SUCCESS)
		{
		mb_error(verbose,error,&message);
		fprintf(outfp,"\nMBIO Error returned from function <mb_read_init>:\n%s\n",message);
		fprintf(outfp,"\nMultibeam File <%s> not initialized for reading\n",ifile);
		fprintf(outfp,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* allocate memory for reading data arrays */
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(char),(void **)&beamflag,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(double),(void **)&bath,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(double),(void **)&bathlon,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(double),(void **)&bathlat,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_amp*sizeof(double),(void **)&amp,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,pixels_ss*sizeof(double),(void **)&ss,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,pixels_ss*sizeof(double),(void **)&sslon,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,pixels_ss*sizeof(double),(void **)&sslat,&error);

	/* if error initializing memory then quit */
	if (error != MB_ERROR_NO_ERROR)
		{
		mb_error(verbose,error,&message);
		fprintf(outfp,"\nMBIO Error allocating data arrays:\n%s\n",
			message);
		fprintf(outfp,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* loop over reading */
	while (error <= MB_ERROR_NO_ERROR)
		{
		status = mb_read(verbose,mbio_ptr,&kind,
			&rpings,time_i,&time_d,
			&navlon,&navlat,
			&speed,&heading,
			&distance,&altitude,&sonardepth,
			&beams_bath,&beams_amp,&pixels_ss,
			beamflag,bath,amp,bathlon,bathlat,
			ss,sslon,sslat,
			comment,&error);

		/* time gaps are not a problem here */
		if (error == MB_ERROR_TIME_GAP)
			{
			error = MB_ERROR_NO_ERROR;
			status = MB_SUCCESS;
			}

		/* print debug statements */
		if (verbose >= 2)
			{
			fprintf(stderr,"\ndbg2  Ping read in program <%s>\n",program_name);
			fprintf(stderr,"dbg2       kind:           %d\n",kind);
			fprintf(stderr,"dbg2       beams_bath:     %d\n",beams_bath);
			fprintf(stderr,"dbg2       beams_amp:      %d\n",beams_amp);
			fprintf(stderr,"dbg2       pixels_ss:      %d\n",pixels_ss);
			fprintf(stderr,"dbg2       error:          %d\n",error);
			fprintf(stderr,"dbg2       status:         %d\n",status);
			}

		if (error == MB_ERROR_NO_ERROR)
			{
			for (ib=0;ib<beams_bath;ib++)
				if (mb_beam_ok(beamflag[ib]))
				{
				ix = (bathlon[ib] - bounds[0])/dx;
				iy = (bathlat[ib] - bounds[2])/dy;
				if (ix >= 0 && ix < xdim
					&& iy >= 0 && iy < ydim)
					{
					indx = ix + iy*xdim;
					icount[indx]++;
					ndatafile++;
					}
				}
			}
		}
	status = mb_close(verbose,&mbio_ptr,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&beamflag,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&bath,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&bathlon,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&bathlat,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&amp,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&ss,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&sslon,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&sslat,&error);
	status = MB_SUCCESS;
	error = MB_ERROR_NO_ERROR;
	if (verbose >= 2)
		fprintf(outfp,"\n");
	fprintf(outfp,"%d depth points counted in %s\n",
			ndatafile,ifile);

	/* count data in second swath file */

	/* initialize the second swath file */
	ndatafile = 0;
	if ((status = mb_read_init(
		verbose,jfile,jformat,pings,lonflip,bounds,
		btime_i,etime_i,speedmin,timegap,
		&mbio_ptr,&btime_d,&etime_d,
		&beams_bath,&beams_amp,&pixels_ss,&error)) != MB_SUCCESS)
		{
		mb_error(verbose,error,&message);
		fprintf(outfp,"\nMBIO Error returned from function <mb_read_init>:\n%s\n",message);
		fprintf(outfp,"\nMultibeam File <%s> not initialized for reading\n",jfile);
		fprintf(outfp,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* allocate memory for reading data arrays */
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(char),(void **)&beamflag,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(double),(void **)&bath,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(double),(void **)&bathlon,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(double),(void **)&bathlat,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_amp*sizeof(double),(void **)&amp,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,pixels_ss*sizeof(double),(void **)&ss,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,pixels_ss*sizeof(double),(void **)&sslon,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,pixels_ss*sizeof(double),(void **)&sslat,&error);

	/* if error initializing memory then quit */
	if (error != MB_ERROR_NO_ERROR)
		{
		mb_error(verbose,error,&message);
		fprintf(outfp,"\nMBIO Error allocating data arrays:\n%s\n",
			message);
		fprintf(outfp,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* loop over reading */
	while (error <= MB_ERROR_NO_ERROR)
		{
		status = mb_read(verbose,mbio_ptr,&kind,
			&rpings,time_i,&time_d,
			&navlon,&navlat,
			&speed,&heading,
			&distance,&altitude,&sonardepth,
			&beams_bath,&beams_amp,&pixels_ss,
			beamflag,bath,amp,bathlon,bathlat,
			ss,sslon,sslat,
			comment,&error);

		/* time gaps are not a problem here */
		if (error == MB_ERROR_TIME_GAP)
			{
			error = MB_ERROR_NO_ERROR;
			status = MB_SUCCESS;
			}

		/* print debug statements */
		if (verbose >= 2)
			{
			fprintf(stderr,"\ndbg2  Ping read in program <%s>\n",program_name);
			fprintf(stderr,"dbg2       kind:           %d\n",kind);
			fprintf(stderr,"dbg2       beams_bath:     %d\n",beams_bath);
			fprintf(stderr,"dbg2       beams_amp:      %d\n",beams_amp);
			fprintf(stderr,"dbg2       pixels_ss:      %d\n",pixels_ss);
			fprintf(stderr,"dbg2       error:          %d\n",error);
			fprintf(stderr,"dbg2       status:         %d\n",status);
			}

		if (error == MB_ERROR_NO_ERROR)
			{
			for (ib=0;ib<beams_bath;ib++)
				if (mb_beam_ok(beamflag[ib]))
				{
				ix = (bathlon[ib] - bounds[0])/dx;
				iy = (bathlat[ib] - bounds[2])/dy;
				if (ix >= 0 && ix < xdim
					&& iy >= 0 && iy < ydim)
					{
					indx = ix + iy*xdim;
					jcount[indx]++;
					ndatafile++;
					}
				}
			}
		}
	status = mb_close(verbose,&mbio_ptr,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&beamflag,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&bath,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&bathlon,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&bathlat,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&amp,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&ss,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&sslon,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&sslat,&error);
	status = MB_SUCCESS;
	error = MB_ERROR_NO_ERROR;
	if (verbose >= 2)
		fprintf(outfp,"\n");
	fprintf(outfp,"%d depth points counted in %s\n",
			ndatafile,jfile);

	/* allocate space for data */
	status = mb_mallocd(verbose,__FILE__,__LINE__,xdim*ydim*sizeof(struct bathptr),
			(void **)&idata,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,xdim*ydim*sizeof(struct bathptr),
			(void **)&jdata,&error);
	for (i=0;i<xdim;i++)
		for (j=0;j<ydim;j++)
			{
			k = i*ydim + j;
			idata[k].ptr = NULL;
			jdata[k].ptr = NULL;
			if (icount[k] > 0)
				{
				status = mb_mallocd(verbose,__FILE__,__LINE__,
					icount[k]*sizeof(struct bath),
					(void **)&(idata[k].ptr),&error);
				icount[k] = 0;
				}
			if (jcount[k] > 0)
				{
				status = mb_mallocd(verbose,__FILE__,__LINE__,
					jcount[k]*sizeof(struct bath),
					(void **)&(jdata[k].ptr),&error);
				jcount[k] = 0;
				}
			}

	/* if error initializing memory then quit */
	if (error != MB_ERROR_NO_ERROR)
		{
		mb_error(verbose,error,&message);
		fprintf(outfp,"\nMBIO Error allocating data arrays:\n%s\n",
			message);
		fprintf(outfp,"Try using ping averaging to reduce the number of data.\n");
		fprintf(outfp,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* read data in first swath file */

	/* initialize the first swath file */
	ndatafile = 0;
	if ((status = mb_read_init(
		verbose,ifile,iformat,pings,lonflip,bounds,
		btime_i,etime_i,speedmin,timegap,
		&mbio_ptr,&btime_d,&etime_d,
		&beams_bath,&beams_amp,&pixels_ss,&error)) != MB_SUCCESS)
		{
		mb_error(verbose,error,&message);
		fprintf(outfp,"\nMBIO Error returned from function <mb_read_init>:\n%s\n",message);
		fprintf(outfp,"\nMultibeam File <%s> not initialized for reading\n",ifile);
		fprintf(outfp,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* allocate memory for reading data arrays */
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(double),(void **)&beamflag,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(double),(void **)&bath,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(double),(void **)&bathlon,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(double),(void **)&bathlat,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_amp*sizeof(double),(void **)&amp,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,pixels_ss*sizeof(double),(void **)&ss,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,pixels_ss*sizeof(double),(void **)&sslon,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,pixels_ss*sizeof(double),(void **)&sslat,&error);

	/* if error initializing memory then quit */
	if (error != MB_ERROR_NO_ERROR)
		{
		mb_error(verbose,error,&message);
		fprintf(outfp,"\nMBIO Error allocating data arrays:\n%s\n",
			message);
		fprintf(outfp,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* loop over reading */
	while (error <= MB_ERROR_NO_ERROR)
		{
		status = mb_read(verbose,mbio_ptr,&kind,
			&rpings,time_i,&time_d,
			&navlon,&navlat,
			&speed,&heading,
			&distance,&altitude,&sonardepth,
			&beams_bath,&beams_amp,&pixels_ss,
			beamflag,bath,amp,bathlon,bathlat,
			ss,sslon,sslat,
			comment,&error);

		/* time gaps are not a problem here */
		if (error == MB_ERROR_TIME_GAP)
			{
			error = MB_ERROR_NO_ERROR;
			status = MB_SUCCESS;
			}

		/* print debug statements */
		if (verbose >= 2)
			{
			fprintf(stderr,"\ndbg2  Ping read in program <%s>\n",program_name);
			fprintf(stderr,"dbg2       kind:           %d\n",kind);
			fprintf(stderr,"dbg2       beams_bath:     %d\n",beams_bath);
			fprintf(stderr,"dbg2       beams_amp:      %d\n",beams_amp);
			fprintf(stderr,"dbg2       pixels_ss:      %d\n",pixels_ss);
			fprintf(stderr,"dbg2       error:          %d\n",error);
			fprintf(stderr,"dbg2       status:         %d\n",status);
			}

		if (error == MB_ERROR_NO_ERROR)
			{
			for (ib=0;ib<beams_bath;ib++)
				if (mb_beam_ok(beamflag[ib]))
				{
				ix = (bathlon[ib] - bounds[0])/dx;
				iy = (bathlat[ib] - bounds[2])/dy;
				if (ix >= 0 && ix < xdim
					&& iy >= 0 && iy < ydim)
					{
					indx = ix + iy*xdim;
					zone = idata[indx].ptr;
					zone[icount[indx]].x =
						deglontokm*
						(bathlon[ib] - bounds[0]);
					zone[icount[indx]].y =
						deglattokm*
						(bathlat[ib] - bounds[2]);
					zone[icount[indx]].d = 0.001*bath[ib];
					zone[icount[indx]].h = heading;
					icount[indx]++;
					ndatafile++;
					}
				}
			}
		}
	status = mb_close(verbose,&mbio_ptr,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&beamflag,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&bath,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&bathlon,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&bathlat,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&amp,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&ss,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&sslon,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&sslat,&error);
	status = MB_SUCCESS;
	error = MB_ERROR_NO_ERROR;
	if (verbose >= 2)
		fprintf(outfp,"\n");
	fprintf(outfp,"%d depth points read from %s\n",
			ndatafile,ifile);

	/* read data in second swath file */

	/* initialize the second swath file */
	ndatafile = 0;
	if ((status = mb_read_init(
		verbose,jfile,jformat,pings,lonflip,bounds,
		btime_i,etime_i,speedmin,timegap,
		&mbio_ptr,&btime_d,&etime_d,
		&beams_bath,&beams_amp,&pixels_ss,&error)) != MB_SUCCESS)
		{
		mb_error(verbose,error,&message);
		fprintf(outfp,"\nMBIO Error returned from function <mb_read_init>:\n%s\n",message);
		fprintf(outfp,"\nMultibeam File <%s> not initialized for reading\n",jfile);
		fprintf(outfp,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* allocate memory for reading data arrays */
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(char),(void **)&beamflag,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(double),(void **)&bath,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(double),(void **)&bathlon,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(double),(void **)&bathlat,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_amp*sizeof(double),(void **)&amp,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,pixels_ss*sizeof(double),(void **)&ss,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,pixels_ss*sizeof(double),(void **)&sslon,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,pixels_ss*sizeof(double),(void **)&sslat,&error);

	/* if error initializing memory then quit */
	if (error != MB_ERROR_NO_ERROR)
		{
		mb_error(verbose,error,&message);
		fprintf(outfp,"\nMBIO Error allocating data arrays:\n%s\n",
			message);
		fprintf(outfp,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* loop over reading */
	while (error <= MB_ERROR_NO_ERROR)
		{
		status = mb_read(verbose,mbio_ptr,&kind,
			&rpings,time_i,&time_d,
			&navlon,&navlat,
			&speed,&heading,
			&distance,&altitude,&sonardepth,
			&beams_bath,&beams_amp,&pixels_ss,
			beamflag,bath,amp,bathlon,bathlat,
			ss,sslon,sslat,
			comment,&error);

		/* time gaps are not a problem here */
		if (error == MB_ERROR_TIME_GAP)
			{
			error = MB_ERROR_NO_ERROR;
			status = MB_SUCCESS;
			}

		/* print debug statements */
		if (verbose >= 2)
			{
			fprintf(stderr,"\ndbg2  Ping read in program <%s>\n",program_name);
			fprintf(stderr,"dbg2       kind:           %d\n",kind);
			fprintf(stderr,"dbg2       beams_bath:     %d\n",beams_bath);
			fprintf(stderr,"dbg2       beams_amp:      %d\n",beams_amp);
			fprintf(stderr,"dbg2       pixels_ss:      %d\n",pixels_ss);
			fprintf(stderr,"dbg2       error:          %d\n",error);
			fprintf(stderr,"dbg2       status:         %d\n",status);
			}

		if (error == MB_ERROR_NO_ERROR)
			{
			for (ib=0;ib<beams_bath;ib++)
				if (mb_beam_ok(beamflag[ib]))
				{
				ix = (bathlon[ib] - bounds[0])/dx;
				iy = (bathlat[ib] - bounds[2])/dy;
				if (ix >= 0 && ix < xdim
					&& iy >= 0 && iy < ydim)
					{
					indx = ix + iy*xdim;
					zone = jdata[indx].ptr;
					zone[jcount[indx]].x =
						deglontokm*
						(bathlon[ib] - bounds[0]);
					zone[jcount[indx]].y =
						deglattokm*
						(bathlat[ib] - bounds[2]);
					zone[jcount[indx]].d = 0.001*bath[ib];
					zone[jcount[indx]].h = heading;
					jcount[indx]++;
					ndatafile++;
					}
				}
			}
		}
	status = mb_close(verbose,&mbio_ptr,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&beamflag,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&bath,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&bathlon,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&bathlat,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&amp,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&ss,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&sslon,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&sslat,&error);
	status = MB_SUCCESS;
	error = MB_ERROR_NO_ERROR;
	if (verbose >= 2)
		fprintf(outfp,"\n");
	fprintf(outfp,"%d depth points read from %s\n",
			ndatafile,jfile);

	/* loop over regions */
	for (i=0;i<xdim;i++)
	  for (j=0;j<ydim;j++)
		{
		/* set index */
		indx = i + j*xdim;

		/* print out id info */
		fprintf(outfp,"\nRegion %d (%d %d) bounds:\n",j+i*ydim,i,j);
		fprintf(outfp,"    Longitude: %9.4f %9.4f\n",
			bounds[0]+dx*i,bounds[0]+dx*(i+1));
		fprintf(outfp,"    Latitude:  %9.4f %9.4f\n",
			bounds[2]+dy*j,bounds[2]+dy*(j+1));

		/* get the best fitting planes */
		if (icount[indx] >= MINIMUM_NUMBER_DATA
			&& jcount[indx] >= MINIMUM_NUMBER_DATA)
			{
			/* use data from first data file */
			zone = idata[indx].ptr;

			/* zero the arrays */
			ihh = 0.0;
			hx = 0.0;
			hy = 0.0;
			for (ii=0;ii<nmatrix;ii++)
			  {
			  vector[ii] = 0.0;
			  for (jj=0;jj<nmatrix;jj++)
				matrix[ii][jj] = 0.0;
			  }

			/* construct normal equations */
			for (kk=0;kk<icount[indx];kk++)
			  {
			  ihh += zone[kk].h;
			  hx += sin(DTR * zone[kk].h);
			  hy += cos(DTR * zone[kk].h);
			  xx[0] = 1.0;
			  xx[1] = zone[kk].x;
			  xx[2] = zone[kk].y;
			  for (ii=0;ii<nmatrix;ii++)
			    {
			    vector[ii] += zone[kk].d * xx[ii];
			    for (jj=0;jj<nmatrix;jj++)
				{
				matrix[ii][jj] += xx[ii] * xx[jj];
				}
			    }
			  }

			/* solve the normal equations */
			gauss((double *)matrix,vector,nmatrix,nmatrix,1.0e-08,&error,1);

			/* get the solution */
			iaa = vector[0];
			ibb = vector[1];
			icc = vector[2];
			hx = hx/icount[indx];
			hy = hy/icount[indx];
			dd = sqrt(hx * hx + hy * hy);
			if (dd > 0.0)
				ihh = RTD * atan2((hx/dd), (hy/dd));
			else
				ihh = ihh/icount[indx];
			if (ihh > 360.0)
				ihh = ihh - 360.0;
			else if (ihh < 0.0)
				ihh = ihh + 360.0;

			/* use data from second data file */
			zone = jdata[indx].ptr;

			/* zero the arrays */
			jhh = 0.0;
			hx = 0.0;
			hy = 0.0;
			for (ii=0;ii<nmatrix;ii++)
			  {
			  vector[ii] = 0.0;
			  for (jj=0;jj<nmatrix;jj++)
				matrix[ii][jj] = 0.0;
			  }

			/* construct normal equations */
			for (kk=0;kk<jcount[indx];kk++)
			  {
			  jhh += zone[kk].h;
			  hx += sin(DTR * zone[kk].h);
			  hy += cos(DTR * zone[kk].h);
			  xx[0] = 1.0;
			  xx[1] = zone[kk].x;
			  xx[2] = zone[kk].y;
			  for (ii=0;ii<nmatrix;ii++)
			    {
			    vector[ii] += zone[kk].d * xx[ii];
			    for (jj=0;jj<nmatrix;jj++)
				{
				matrix[ii][jj] += xx[ii] * xx[jj];
				}
			    }
			  }

			/* solve the normal equations */
			gauss((double *)matrix,vector,nmatrix,nmatrix,1.0e-08,&error,1);
			if (error != 0)
				{
				fprintf(outfp,"matrix inversion error: %d\n",error);
				}

			/* get the solution */
			jaa = vector[0];
			jbb = vector[1];
			jcc = vector[2];
			hx = hx/jcount[indx];
			hy = hy/jcount[indx];
			dd = sqrt(hx * hx + hy * hy);
			if (dd > 0.0)
				jhh = RTD * atan2((hx/dd), (hy/dd));
			else
				jhh = jhh/jcount[indx];
			if (jhh > 360.0)
				jhh = jhh - 360.0;
			else if (jhh < 0.0)
				jhh = jhh + 360.0;

			/* report results */
			fprintf(outfp,"First data file:    %s\n",ifile);
			fprintf(outfp,"    Number of data: %d\n",
				icount[indx]);
			fprintf(outfp,"    Mean heading:   %f\n",ihh);
			fprintf(outfp,"    Plane fit:      %f %f %f\n",
				iaa,ibb,icc);
			fprintf(outfp,"Second data file:   %s\n",jfile);
			fprintf(outfp,"    Number of data: %d\n",
				jcount[indx]);
			fprintf(outfp,"    Mean heading:   %f\n",jhh);
			fprintf(outfp,"    Plane fit:      %f %f %f\n",
				jaa,jbb,jcc);

			/* calculate roll bias */
			if (fabs(ihh - jhh) > 90.0)
				{
				isine = sin(DTR*ihh);
				icosine = cos(DTR*ihh);
				jsine = sin(DTR*jhh);
				jcosine = cos(DTR*jhh);
				if (fabs(jcosine-icosine) > 1.0)
					{
					roll_bias = -(ibb - jbb)
						/(jcosine - icosine);
					}
				else
					{
					roll_bias = -(icc - jcc)
						/(isine - jsine);
					}
				fprintf(outfp,"Roll bias:   %f (%f degrees)\n",
					roll_bias,atan(roll_bias)/DTR);
				fprintf(outfp,"Roll bias is positive to starboard, negative to port.\n");
				fprintf(outfp,"A postive roll bias means the vertical reference used by \n    the swath system is biased to starboard, \n    giving rise to shallow bathymetry to port and \n    deep bathymetry to starboard.\n");
				}
			else
				fprintf(outfp,"Track headings too similar to calculate roll bias!\n");
			}
		else
			fprintf(outfp,"Not enough data to proceed!\n");
		}

	/* deallocate space for data */
	for (i=0;i<xdim;i++)
		for (j=0;j<ydim;j++)
			{
			k = i*ydim + j;
			if (icount[k] > 0)
				{
				status = mb_freed(verbose,__FILE__,__LINE__,(void **)&idata[k].ptr,&error);
				}
			if (jcount[k] > 0)
				{
				status = mb_freed(verbose,__FILE__,__LINE__,(void **)&jdata[k].ptr,&error);
				}
			}
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)&idata,&error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)&jdata,&error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)&icount,&error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)&jcount,&error);

	/* check memory */
	if (verbose >= 4)
		status = mb_memory_list(verbose,&error);

	/* print output debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  Program <%s> completed\n",
			program_name);
		fprintf(stderr,"dbg2  Ending status:\n");
		fprintf(stderr,"dbg2       status:  %d\n",status);
		}

	/* end it all */
	exit(error);
}
Пример #10
0
int main (int argc, char **argv)
{
	/* id variables */
	char program_name[] = "MBauvnavusbl";
	char help_message[] = "MBauvnavusbl reads a primary navigation file (usually from a submerged platform\n swath survey) and also reads secondary navigation (e.g. USBL fixes).\n The program calculates position offsets between the raw survey navigation\n and the secondary navigation every 3600 seconds (10 minutes), and then\n linearly interpolates and applies this adjustment vector for each\n primary navigation position. The adjusted navigation is output.";
	char usage_message[] = "mbauvnavusbl -Inavfile -Ooutfile -Uusblfile [-Fnavformat -Llonflip -Musblformat -V -H ]";

	/* parsing variables */
	extern char *optarg;
	int	errflg = 0;
	int	c;
	int	help = 0;
	int	flag = 0;

	/* MBIO status variables */
	int	status = MB_SUCCESS;
	int	verbose = 0;
	int	error = MB_ERROR_NO_ERROR;
	char	*message;

	/* Files and formats */
	char	ifile[MB_PATH_MAXLINE];
	char	ofile[MB_PATH_MAXLINE];
	char	ufile[MB_PATH_MAXLINE];
	int	navformat = 9;
	int	usblformat = 165;
	FILE	*fp;

	/* MBIO default parameters - only use lonflip */
	int	format;
	int	pings;
	int	lonflip;
	double	bounds[4];
	int	btime_i[7];
	int	etime_i[7];
	double	speedmin;
	double	timegap;

	/* read and write values */
	int	time_i[7];
	double	navlon;
	double	navlat;
	double	heading;
	double	sonardepth;

	/* navigation handling variables */
	int	useaverage = MB_NO;
	double	tieinterval = 600.0;
	int	nnav;
	double	*ntime = NULL;
	double	*nlon = NULL;
	double	*nlat = NULL;
	double	*nheading = NULL;
	double	*nspeed = NULL;
	double	*nsonardepth = NULL;
	double	*nroll = NULL;
	double	*npitch = NULL;
	double	*nheave = NULL;
	int	nusbl;
	double	*utime = NULL;
	double	*ulon = NULL;
	double	*ulat = NULL;
	double	*uheading = NULL;
	double	*usonardepth = NULL;
	double	*alon = NULL;
	double	*alat = NULL;
	double	*aheading = NULL;
	double	*asonardepth = NULL;
	int	ntie;
	double	*ttime = NULL;
	double	*tlon = NULL;
	double	*tlat = NULL;
	double	*theading = NULL;
	double	*tsonardepth = NULL;
	double	loncoravg;
	double	latcoravg;

	int	nav_ok;
	int	nstime_i[7], nftime_i[7];
	int	ustime_i[7], uftime_i[7];

	char	buffer[NCHARMAX], *result;
	int	nget;
	int	year;
	int	jday;
	double	timetag;
	double	easting, northing;
	double	rov_altitude, rov_roll, rov_pitch;
	int	position_flag, heading_flag, altitude_flag, attitude_flag, pressure_flag;
	double	sec;
	int	intstat;
	int	i, j;

	/* get current default values - only interested in lonflip */
	status = mb_defaults(verbose,&format,&pings,&lonflip,bounds,
		btime_i,etime_i,&speedmin,&timegap);

	/* set default input and output */
	strcpy (ifile, "stdin");
	strcpy (ofile, "stdout");
	strcpy (ufile, "\0");

	/* process argument list */
	while ((c = getopt(argc, argv, "VvHhAaF:f:L:l:I:i:O:o:M:m:U:u:")) != -1)
	  switch (c)
		{
		case 'H':
		case 'h':
			help++;
			break;
		case 'V':
		case 'v':
			verbose++;
			break;
		case 'A':
		case 'a':
			useaverage = MB_YES;
			flag++;
			break;
		case 'F':
		case 'f':
			sscanf (optarg,"%d", &navformat);
			flag++;
			break;
		case 'L':
		case 'l':
			sscanf (optarg,"%d", &lonflip);
			flag++;
			break;
		case 'I':
		case 'i':
			sscanf (optarg,"%s", ifile);
			flag++;
			break;
		case 'O':
		case 'o':
			sscanf (optarg,"%s", ofile);
			flag++;
			break;
		case 'M':
		case 'm':
			sscanf (optarg,"%d", &usblformat);
			flag++;
			break;
		case 'U':
		case 'u':
			sscanf (optarg,"%s", ufile);
			flag++;
			break;
		case '?':
			errflg++;
		}

	/* if error flagged then print it and exit */
	if (errflg)
		{
		fprintf(stderr,"usage: %s\n", usage_message);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		error = MB_ERROR_BAD_USAGE;
		exit(error);
		}

	/* print starting message */
	if (verbose == 1 || help)
		{
		fprintf(stderr,"\nProgram %s\n",program_name);
		fprintf(stderr,"Version %s\n",rcs_id);
		fprintf(stderr,"MB-system Version %s\n",MB_VERSION);
		}

	/* print starting debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  Program <%s>\n",program_name);
		fprintf(stderr,"dbg2  Version %s\n",rcs_id);
		fprintf(stderr,"dbg2  MB-system Version %s\n",MB_VERSION);
		fprintf(stderr,"dbg2  Control Parameters:\n");
		fprintf(stderr,"dbg2       verbose:         %d\n",verbose);
		fprintf(stderr,"dbg2       help:            %d\n",help);
		fprintf(stderr,"dbg2       lonflip:         %d\n",lonflip);
		fprintf(stderr,"dbg2       input file:      %s\n",ifile);
		fprintf(stderr,"dbg2       output file:     %s\n",ofile);
		fprintf(stderr,"dbg2       usbl file:       %s\n",ufile);
		fprintf(stderr,"dbg2       nav format:      %d\n",navformat);
		fprintf(stderr,"dbg2       usbl format:     %d\n",usblformat);
		fprintf(stderr,"dbg2       useaverage:      %d\n",useaverage);
		}

	/* if help desired then print it and exit */
	if (help)
		{
		fprintf(stderr,"\n%s\n",help_message);
		fprintf(stderr,"\nusage: %s\n", usage_message);
		exit(error);
		}

	/* count the nav points */
	nnav = 0;
	if ((fp = fopen(ifile, "r")) == NULL)
		{
		error = MB_ERROR_OPEN_FAIL;
		fprintf(stderr,"\nUnable to Open Navigation File <%s> for reading\n",ifile);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}
	while ((result = fgets(buffer,NCHARMAX,fp)) == buffer)
		nnav++;
	fclose(fp);

	/* allocate space for the nav points */
	status = mb_mallocd(verbose,__FILE__,__LINE__,nnav*sizeof(double),(void **)&ntime,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nnav*sizeof(double),(void **)&nlon,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nnav*sizeof(double),(void **)&nlat,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nnav*sizeof(double),(void **)&nheading,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nnav*sizeof(double),(void **)&nspeed,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nnav*sizeof(double),(void **)&nsonardepth,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nnav*sizeof(double),(void **)&nroll,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nnav*sizeof(double),(void **)&npitch,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nnav*sizeof(double),(void **)&nheave,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nnav*sizeof(double),(void **)&alon,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nnav*sizeof(double),(void **)&alat,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nnav*sizeof(double),(void **)&aheading,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nnav*sizeof(double),(void **)&asonardepth,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nnav*sizeof(double),(void **)&ttime,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nnav*sizeof(double),(void **)&tlon,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nnav*sizeof(double),(void **)&tlat,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nnav*sizeof(double),(void **)&theading,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nnav*sizeof(double),(void **)&tsonardepth,&error);

	/* if error initializing memory then quit */
	if (error != MB_ERROR_NO_ERROR)
		{
		mb_error(verbose,error,&message);
		fprintf(stderr,"\nMBIO Error allocating data arrays:\n%s\n",message);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* read in nav points */
	nnav = 0;
	if ((fp = fopen(ifile, "r")) == NULL)
		{
		status = MB_FAILURE;
		error = MB_ERROR_OPEN_FAIL;
		fprintf(stderr,"\nUnable to Open Navigation File <%s> for reading\n",ifile);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}
	strncpy(buffer,"\0",sizeof(buffer));
	while ((result = fgets(buffer,NCHARMAX,fp)) == buffer)
		{
		nav_ok = MB_NO;

		nget = sscanf(buffer,"%d %d %d %d %d %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf",
			&time_i[0],&time_i[1],&time_i[2],
			&time_i[3],&time_i[4],&sec,
			&ntime[nnav],
			&nlon[nnav],&nlat[nnav],
			&nheading[nnav],&nspeed[nnav],
			&nsonardepth[nnav],
			&nroll[nnav],&npitch[nnav],&nheave[nnav]);
		if (nget >= 12)
			nav_ok = MB_YES;

		/* make sure longitude is defined according to lonflip */
		if (nav_ok == MB_YES)
			{
			if (lonflip == -1 && nlon[nnav] > 0.0)
				nlon[nnav] = nlon[nnav] - 360.0;
			else if (lonflip == 0 && nlon[nnav] < -180.0)
				nlon[nnav] = nlon[nnav] + 360.0;
			else if (lonflip == 0 && nlon[nnav] > 180.0)
				nlon[nnav] = nlon[nnav] - 360.0;
			else if (lonflip == 1 && nlon[nnav] < 0.0)
				nlon[nnav] = nlon[nnav] + 360.0;
			}

		/* output some debug values */
		if (verbose >= 5 && nav_ok == MB_YES)
			{
			fprintf(stderr,"\ndbg5  New navigation point read in program <%s>\n",program_name);
			fprintf(stderr,"dbg5       nav[%d]: %f %f %f\n",
				nnav,ntime[nnav],nlon[nnav],nlat[nnav]);
			}
		else if (verbose >= 5)
			{
			fprintf(stderr,"\ndbg5  Error parsing line in navigation file in program <%s>\n",program_name);
			fprintf(stderr,"dbg5       line: %s\n",buffer);
			}

		/* check for reverses or repeats in time */
		if (nav_ok == MB_YES)
			{
			if (nnav == 0)
				nnav++;
			else if (ntime[nnav] > ntime[nnav-1])
				nnav++;
			else if (nnav > 0 && ntime[nnav] <= ntime[nnav-1]
				&& verbose >= 5)
				{
				fprintf(stderr,"\ndbg5  Navigation time error in program <%s>\n",program_name);
				fprintf(stderr,"dbg5       nav[%d]: %f %f %f\n",
					nnav-1,ntime[nnav-1],nlon[nnav-1],
					nlat[nnav-1]);
				fprintf(stderr,"dbg5       nav[%d]: %f %f %f\n",
					nnav,ntime[nnav],nlon[nnav],
					nlat[nnav]);
				}
			}
		strncpy(buffer,"\0",sizeof(buffer));
		}
	fclose(fp);

	/* check for nav */
	if (nnav < 2)
		{
		fprintf(stderr,"\nNo navigation read from file <%s>\n",ifile);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* count the usbl points */
	nusbl = 0;
	if ((fp = fopen(ufile, "r")) == NULL)
		{
		error = MB_ERROR_OPEN_FAIL;
		fprintf(stderr,"\nUnable to Open USBL Navigation File <%s> for reading\n",ufile);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}
	while ((result = fgets(buffer,NCHARMAX,fp)) == buffer)
		nusbl++;
	fclose(fp);

	/* allocate space for the nav points */
	status = mb_mallocd(verbose,__FILE__,__LINE__,nusbl*sizeof(double),(void **)&utime,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nusbl*sizeof(double),(void **)&ulon,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nusbl*sizeof(double),(void **)&ulat,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nusbl*sizeof(double),(void **)&uheading,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,nusbl*sizeof(double),(void **)&usonardepth,&error);

	/* if error initializing memory then quit */
	if (error != MB_ERROR_NO_ERROR)
		{
		mb_error(verbose,error,&message);
		fprintf(stderr,"\nMBIO Error allocating data arrays:\n%s\n",message);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* read in usbl points */
	nusbl = 0;
	if ((fp = fopen(ufile, "r")) == NULL)
		{
		status = MB_FAILURE;
		error = MB_ERROR_OPEN_FAIL;
		fprintf(stderr,"\nUnable to Open USBL Navigation File <%s> for reading\n",ufile);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}
	strncpy(buffer,"\0",sizeof(buffer));
	while ((result = fgets(buffer,NCHARMAX,fp)) == buffer)
		{
		nav_ok = MB_NO;

		/* ignore comments */
		if (buffer[0] == '#')
			{
			}
		else if (strchr(buffer, ',') != NULL)
			{
			nget = sscanf(buffer,
				"%d,%d,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%d,%d,%d,%d,%d",
				&year,
				&jday,
				&timetag,
				&utime[nusbl],
				&ulat[nusbl],
				&ulon[nusbl],
				&easting,
				&northing,
				&usonardepth[nusbl],
				&uheading[nusbl],
				&rov_altitude,
				&rov_pitch,
				&rov_roll,
				&position_flag,
				&pressure_flag,
				&heading_flag,
				&altitude_flag,
				&attitude_flag);
			}
		    else
			{
			nget = sscanf(buffer,
				"%d %d %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf,%d,%d,%d,%d,%d",
				&year,
				&jday,
				&timetag,
				&utime[nusbl],
				&ulat[nusbl],
				&ulon[nusbl],
				&easting,
				&northing,
				&usonardepth[nusbl],
				&uheading[nusbl],
				&rov_altitude,
				&rov_pitch,
				&rov_roll,
				&position_flag,
				&pressure_flag,
				&heading_flag,
				&altitude_flag,
				&attitude_flag);
			}
		if (nget == 18)
			nav_ok = MB_YES;

		/* make sure longitude is defined according to lonflip */
		if (nav_ok == MB_YES)
			{
			if (lonflip == -1 && ulon[nusbl] > 0.0)
				ulon[nusbl] = ulon[nusbl] - 360.0;
			else if (lonflip == 0 && ulon[nusbl] < -180.0)
				ulon[nusbl] = ulon[nusbl] + 360.0;
			else if (lonflip == 0 && ulon[nusbl] > 180.0)
				ulon[nusbl] = ulon[nusbl] - 360.0;
			else if (lonflip == 1 && ulon[nusbl] < 0.0)
				ulon[nusbl] = ulon[nusbl] + 360.0;
			}

		/* output some debug values */
		if (verbose >= 5 && nav_ok == MB_YES)
			{
			fprintf(stderr,"\ndbg5  New USBL navigation point read in program <%s>\n",program_name);
			fprintf(stderr,"dbg5       usbl[%d]: %f %f %f\n",
				nusbl,utime[nusbl],ulon[nusbl],ulat[nusbl]);
			}
		else if (verbose >= 5)
			{
			fprintf(stderr,"\ndbg5  Error parsing line in navigation file in program <%s>\n",program_name);
			fprintf(stderr,"dbg5       line: %s\n",buffer);
			}

		/* check for reverses or repeats in time */
		if (nav_ok == MB_YES)
			{
			if (nusbl == 0)
				nusbl++;
			else if (utime[nusbl] > utime[nusbl-1])
				nusbl++;
			else if (nusbl > 0 && utime[nusbl] <= utime[nusbl-1]
				&& verbose >= 5)
				{
				fprintf(stderr,"\ndbg5  USBL Navigation time error in program <%s>\n",program_name);
				fprintf(stderr,"dbg5       usbl[%d]: %f %f %f\n",
					nusbl-1,utime[nusbl-1],ulon[nusbl-1],
					ulat[nusbl-1]);
				fprintf(stderr,"dbg5       nav[%d]: %f %f %f\n",
					nusbl,utime[nusbl],ulon[nusbl],
					ulat[nusbl]);
				}
			}
		strncpy(buffer,"\0",sizeof(buffer));
		}
	fclose(fp);

	/* check for nav */
	if (nusbl < 2)
		{
		fprintf(stderr,"\nNo USBL navigation read from file <%s>\n",ufile);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* get start and finish times of nav */
	mb_get_date(verbose,ntime[0],nstime_i);
	mb_get_date(verbose,ntime[nnav-1],nftime_i);
	mb_get_date(verbose,utime[0],ustime_i);
	mb_get_date(verbose,utime[nusbl-1],uftime_i);

	/* give the statistics */
	if (verbose >= 1)
		{
		fprintf(stderr,"\n%d navigation records read\n",nnav);
		fprintf(stderr,"Nav start time: %4.4d %2.2d %2.2d %2.2d:%2.2d:%2.2d.%6.6d\n",
			nstime_i[0],nstime_i[1],nstime_i[2],nstime_i[3],
			nstime_i[4],nstime_i[5],nstime_i[6]);
		fprintf(stderr,"Nav end time:   %4.4d %2.2d %2.2d %2.2d:%2.2d:%2.2d.%6.6d\n",
			nftime_i[0],nftime_i[1],nftime_i[2],nftime_i[3],
			nftime_i[4],nftime_i[5],nftime_i[6]);
		fprintf(stderr,"\n%d USBL navigation records read\n",nusbl);
		fprintf(stderr,"Nav start time: %4.4d %2.2d %2.2d %2.2d:%2.2d:%2.2d.%6.6d\n",
			ustime_i[0],ustime_i[1],ustime_i[2],ustime_i[3],
			ustime_i[4],ustime_i[5],ustime_i[6]);
		fprintf(stderr,"Nav end time:   %4.4d %2.2d %2.2d %2.2d:%2.2d:%2.2d.%6.6d\n",
			uftime_i[0],uftime_i[1],uftime_i[2],uftime_i[3],
			uftime_i[4],uftime_i[5],uftime_i[6]);
		}

	/* now loop over nav data getting ties every tieinterval fixes */
	ntie = 0;
	loncoravg = 0.0;
	latcoravg = 0.0;
	for (i=0;i<nnav;i++)
		{
		if (ntie == 0
			|| (ntime[i] - ttime[ntie-1]) > tieinterval)
			{
			/* get time */
			ttime[ntie] = ntime[i];

			/* interpolate navigation from usbl navigation */
			intstat = mb_linear_interp(verbose,
					utime-1, ulon-1,
					nusbl, ttime[ntie], &navlon, &j,
					&error);
			intstat = mb_linear_interp(verbose,
					utime-1, ulat-1,
					nusbl, ttime[ntie], &navlat, &j,
					&error);
			intstat = mb_linear_interp(verbose,
					utime-1, uheading-1,
					nusbl, ttime[ntie], &heading, &j,
					&error);
			intstat = mb_linear_interp(verbose,
					utime-1, usonardepth-1,
					nusbl, ttime[ntie], &sonardepth, &j,
					&error);

			/* get adjustments */
			tlon[ntie] = navlon - nlon[i];
			tlat[ntie] = navlat - nlat[i];
			theading[ntie] = heading - nheading[i];
			if (theading[ntie] < -180.0)
				theading[ntie] += 360.0;
			if (theading[ntie] > 180.0)
				theading[ntie] -= 360.0;
			tsonardepth[ntie] = sonardepth - nsonardepth[i];
			ntie++;

			/* get averages */
			loncoravg += tlon[ntie-1];
			latcoravg += tlat[ntie-1];
			}
		}

	/* get averages */
	if (ntie > 0)
		{
		loncoravg /= ntie;
		latcoravg /= ntie;
		}

fprintf(stderr,"\nCalculated %d adjustment points:\n",ntie);
for (i=0;i<ntie;i++)
fprintf(stderr,"time:%f lon:%f lat:%f heading:%f sonardepth:%f\n",
ttime[i],tlon[i],tlat[i],theading[i],tsonardepth[i]);
fprintf(stderr,"Average lon:%f lat:%f\n",loncoravg,latcoravg);

	/* open output file */
	if ((fp = fopen(ofile, "w")) == NULL)
		{
		status = MB_FAILURE;
		error = MB_ERROR_OPEN_FAIL;
		fprintf(stderr,"\nUnable to Open Output Navigation File <%s> for writing\n",ofile);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* now loop over nav data applying adjustments */
	for (i=0;i<nnav;i++)
		{
		/* interpolate adjustment */
		if (useaverage == MB_NO)
			{
			/* get adjustment by interpolation */
			intstat = mb_linear_interp(verbose,
					ttime-1, tlon-1,
					ntie, ntime[i], &navlon, &j,
					&error);
			intstat = mb_linear_interp(verbose,
					ttime-1, tlat-1,
					ntie, ntime[i], &navlat, &j,
					&error);

			/* apply adjustment */
			nlon[i] += navlon;
			nlat[i] += navlat;
			}

		/* else use average adjustments */
		else
			{
			/* apply adjustment */
			nlon[i] += loncoravg;
			nlat[i] += latcoravg;
			}

		/* write out the adjusted navigation */
		mb_get_date(verbose,ntime[i],time_i);
		sprintf(buffer,
			"%4.4d %2.2d %2.2d %2.2d %2.2d %2.2d.%6.6d %16.6f %.6f %.6f %.2f %.2f %.2f %.2f %.2f %.2f\n",
			time_i[0],
			time_i[1],
			time_i[2],
			time_i[3],
			time_i[4],
			time_i[5],
			time_i[6],
			ntime[i],
			nlon[i],
			nlat[i],
			nheading[i],
			nspeed[i],
			nsonardepth[i],
			nroll[i],
			npitch[i],
			nheave[i]);
		if (fputs(buffer, fp) == EOF)
			{
			error = MB_ERROR_WRITE_FAIL;
			status = MB_FAILURE;
			}
		else
			{
			error = MB_ERROR_NO_ERROR;
			status = MB_SUCCESS;
			}
		}
	fclose(fp);

	/* deallocate memory for data arrays */
	mb_freed(verbose,__FILE__,__LINE__,(void **)&ntime,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&nlon,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&nlat,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&nheading,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&nspeed,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&nsonardepth,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&nroll,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&npitch,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&nheave,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&alon,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&alat,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&aheading,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&asonardepth,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&utime,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&ulon,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&ulat,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&uheading,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&usonardepth,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&ttime,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&tlon,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&tlat,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&theading,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&tsonardepth,&error);

	/* check memory */
	if (verbose >= 4)
		status = mb_memory_list(verbose,&error);

	/* give the statistics */
	if (verbose >= 1)
		{
		fprintf(stderr,"\n%d input navigation records\n",nnav);
		fprintf(stderr,"%d input usbl records\n",nusbl);
		}

	/* end it all */
	exit(error);
}
Пример #11
0
/*--------------------------------------------------------------------*/
int mb_close(int verbose, void **mbio_ptr, int *error)
{
	char	*function_name = "mb_close";
	int	status = MB_SUCCESS;
	struct mb_io_struct *mb_io_ptr;

	/* print input debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  MBIO function <%s> called\n",function_name);
		fprintf(stderr,"dbg2  Revision id: %s\n",rcs_id);
		fprintf(stderr,"dbg2  Input arguments:\n");
		fprintf(stderr,"dbg2       verbose:    %d\n",verbose);
		fprintf(stderr,"dbg2       mbio_ptr:   %p\n",(void *)*mbio_ptr);
		}

	/* get pointer to mbio descriptor */
	mb_io_ptr = (struct mb_io_struct *) *mbio_ptr;

	/* deallocate format dependent structures */
	status = (*mb_io_ptr->mb_io_format_free)(verbose,*mbio_ptr,error);

	/* deallocate system dependent structures */
	/*status = (*mb_io_ptr->mb_io_store_free)
			(verbose,*mbio_ptr,&(mb_io_ptr->store_data),error);*/

	/* deallocate memory for arrays within the mbio descriptor */
	if (mb_io_ptr->filetype == MB_FILETYPE_XDR
		&& mb_io_ptr->xdrs != NULL)
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->xdrs,error);
	if (mb_io_ptr->filetype == MB_FILETYPE_XDR
		&& mb_io_ptr->xdrs2 != NULL)
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->xdrs2,error);
	if (mb_io_ptr->filetype == MB_FILETYPE_XDR
		&& mb_io_ptr->xdrs3 != NULL)
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->xdrs3,error);
	if (mb_io_ptr->hdr_comment != NULL)
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->hdr_comment,error);
	status = mb_deall_ioarrays(verbose, *mbio_ptr, error);

	/* close the files if normal */
	if (mb_io_ptr->filetype == MB_FILETYPE_NORMAL
	    || mb_io_ptr->filetype == MB_FILETYPE_XDR)
	    {
	    if (mb_io_ptr->mbfp != NULL)
		    fclose(mb_io_ptr->mbfp);
	    if (mb_io_ptr->mbfp2 != NULL)
		    fclose(mb_io_ptr->mbfp2);
	    if (mb_io_ptr->mbfp3 != NULL)
		    fclose(mb_io_ptr->mbfp3);
	    }

	/* else handle single normal files to be closed with mb_fileio_close() */
	else if (mb_io_ptr->filetype == MB_FILETYPE_SINGLE)
	    {
	    status = mb_fileio_close(verbose, *mbio_ptr, error);
	    }

	/* else if gsf then use gsfClose */
	else if (mb_io_ptr->filetype == MB_FILETYPE_GSF)
	    {
	    gsfClose((int) mb_io_ptr->gsfid);
	    }

	/* else if netcdf then use nc_close */
	else if (mb_io_ptr->filetype == MB_FILETYPE_NETCDF)
	    {
	    if (mb_io_ptr->filemode == MB_FILEMODE_WRITE)
		nc_enddef(mb_io_ptr->ncid);
	    nc_close(mb_io_ptr->ncid);
	    }

        /* else handle surf files to be opened with libsapi */
        else if (mb_io_ptr->filetype == MB_FILETYPE_SURF)
            {
  	    SAPI_close();
	    }

	/* deallocate UTM projection if required */
	if (mb_io_ptr->projection_initialized == MB_YES)
		{
		mb_io_ptr->projection_initialized = MB_NO;
		mb_proj_free(verbose, &(mb_io_ptr->pjptr), error);
		}

	/* deallocate the mbio descriptor */
	status = mb_freed(verbose,__FILE__, __LINE__,(void **)mbio_ptr,error);

	/* print output debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  MBIO function <%s> completed\n",function_name);
		fprintf(stderr,"dbg2  Revision id: %s\n",rcs_id);
		fprintf(stderr,"dbg2  Return value:\n");
		fprintf(stderr,"dbg2       error:      %d\n",*error);
		fprintf(stderr,"dbg2  Return status:\n");
		fprintf(stderr,"dbg2       status:  %d\n",status);
		}

	/* return status */
	return(status);
}
Пример #12
0
int main (int argc, char **argv)
{
	char program_name[] = "MBHISTOGRAM";
	char help_message[] =  "MBHISTOGRAM reads a swath sonar data file and generates a histogram\n\tof the bathymetry,  amplitude,  or sidescan values. Alternatively, \n\tmbhistogram can output a list of values which break up the\n\tdistribution into equal sized regions.\n\tThe results are dumped to stdout.";
	char usage_message[] = "mbhistogram [-Akind -Byr/mo/da/hr/mn/sc -Dmin/max -Eyr/mo/da/hr/mn/sc -Fformat -G -Ifile -Llonflip -Mnintervals -Nnbins -Ppings -Rw/e/s/n -Sspeed -V -H]";
	extern char *optarg;
	int	errflg = 0;
	int	c;
	int	help = 0;
	int	flag = 0;

	/* MBIO status variables */
	int	status = MB_SUCCESS;
	int	verbose = 0;
	int	error = MB_ERROR_NO_ERROR;
	char	*message;

	/* MBIO read control parameters */
	int	read_datalist = MB_NO;
	char	read_file[MB_PATH_MAXLINE];
	void	*datalist;
	int	look_processed = MB_DATALIST_LOOK_UNSET;
	double	file_weight;
	int	format;
	int	pings;
	int	lonflip;
	double	bounds[4];
	int	btime_i[7];
	int	etime_i[7];
	double	btime_d;
	double	etime_d;
	double	speedmin;
	double	timegap;
	char	file[MB_PATH_MAXLINE];
	int	beams_bath;
	int	beams_amp;
	int	pixels_ss;

	/* MBIO read values */
	void	*mbio_ptr = NULL;
	int	kind;
	int	time_i[7];
	double	time_d;
	double	navlon;
	double	navlat;
	double	speed;
	double	heading;
	double	distance;
	double	altitude;
	double	sonardepth;
	char	*beamflag = NULL;
	double	*bath = NULL;
	double	*bathacrosstrack = NULL;
	double	*bathalongtrack = NULL;
	double	*amp = NULL;
	double	*ss = NULL;
	double	*ssacrosstrack = NULL;
	double	*ssalongtrack = NULL;
	char	comment[MB_COMMENT_MAXLINE];

	/* histogram variables */
	int	mode = MBHISTOGRAM_SS;
	int	gaussian = MB_NO;
	int	nbins = 0;
	int	nintervals = 0;
	double	value_min = 0.0;
	double	value_max = 128.0;
	double	dvalue_bin;
	double	value_bin_min;
	double	value_bin_max;
	double	data_min;
	double	data_max;
	int	data_first = MB_YES;
	double	target_min;
	double	target_max;
	double	*histogram = NULL;
	double	*intervals = NULL;
	double	total;
	double	sum;
	double	p;
	double	target;
	double	dinterval;
	double	bin_fraction;
	int	ibin;

	/* output stream for basic stuff (stdout if verbose <= 1,
		stderr if verbose > 1) */
	FILE	*output;

	int	read_data;
	int	nrec, nvalue;
	int	nrectot = 0;
	int	nvaluetot = 0;
	int	i, j;

	/* get current default values */
	status = mb_defaults(verbose,&format,&pings,&lonflip,bounds,
		btime_i,etime_i,&speedmin,&timegap);

	/* set default input to stdin */
	strcpy (read_file, "stdin");

	/* process argument list */
	while ((c = getopt(argc, argv, "A:a:B:b:D:d:E:e:F:f:GgHhI:i:L:l:M:m:N:n:P:p:R:r:S:s:T:t:Vv")) != -1)
	  switch (c)
		{
		case 'A':
		case 'a':
			sscanf (optarg,"%d", &mode);
			flag++;
			break;
		case 'B':
		case 'b':
			sscanf (optarg,"%d/%d/%d/%d/%d/%d",
				&btime_i[0],&btime_i[1],&btime_i[2],
				&btime_i[3],&btime_i[4],&btime_i[5]);
			btime_i[6] = 0;
			flag++;
			break;
		case 'D':
		case 'd':
			sscanf (optarg,"%lf/%lf", &value_min,&value_max);
			flag++;
			break;
		case 'E':
		case 'e':
			sscanf (optarg,"%d/%d/%d/%d/%d/%d",
				&etime_i[0],&etime_i[1],&etime_i[2],
				&etime_i[3],&etime_i[4],&etime_i[5]);
			etime_i[6] = 0;
			flag++;
			break;
		case 'F':
		case 'f':
			sscanf (optarg,"%d", &format);
			flag++;
			break;
		case 'G':
		case 'g':
			gaussian = MB_YES;
			break;
		case 'H':
		case 'h':
			help++;
			break;
		case 'I':
		case 'i':
			sscanf (optarg,"%s", read_file);
			flag++;
			break;
		case 'L':
		case 'l':
			sscanf (optarg,"%d", &lonflip);
			flag++;
			break;
		case 'M':
		case 'm':
			sscanf (optarg,"%d", &nintervals);
			flag++;
			break;
		case 'N':
		case 'n':
			sscanf (optarg,"%d", &nbins);
			flag++;
			break;
		case 'P':
		case 'p':
			sscanf (optarg,"%d", &pings);
			flag++;
			break;
		case 'R':
		case 'r':
			mb_get_bounds(optarg, bounds);
			flag++;
			break;
		case 'S':
		case 's':
			sscanf (optarg,"%lf", &speedmin);
			flag++;
			break;
		case 'T':
		case 't':
			sscanf (optarg,"%lf", &timegap);
			flag++;
			break;
		case 'V':
		case 'v':
			verbose++;
			break;
		case '?':
			errflg++;
		}

	/* set output stream */
	if (verbose <= 1)
		output = stdout;
	else
		output = stderr;

	/* if error flagged then print it and exit */
	if (errflg)
		{
		fprintf(output,"usage: %s\n", usage_message);
		fprintf(output,"\nProgram <%s> Terminated\n",
			program_name);
		error = MB_ERROR_BAD_USAGE;
		exit(error);
		}

	/* print starting message */
	if (verbose == 1 || help)
		{
		fprintf(output,"\nProgram %s\n",program_name);
		fprintf(output,"Version %s\n",rcs_id);
		fprintf(output,"MB-system Version %s\n",MB_VERSION);
		}

	/* get format if required */
	if (format == 0)
		mb_get_format(verbose,read_file,NULL,&format,&error);

	/* figure out histogram dimensions */
	if (nintervals > 0 && nbins <= 0)
		nbins = 50*nintervals;
	if (nbins <= 0)
		nbins = 16;

	/* print starting debug statements */
	if (verbose >= 2)
		{
		fprintf(output,"\ndbg2  Program <%s>\n",program_name);
		fprintf(output,"dbg2  Version %s\n",rcs_id);
		fprintf(output,"dbg2  MB-system Version %s\n",MB_VERSION);
		fprintf(output,"dbg2  Control Parameters:\n");
		fprintf(output,"dbg2       verbose:    %d\n",verbose);
		fprintf(output,"dbg2       help:       %d\n",help);
		fprintf(output,"dbg2       format:     %d\n",format);
		fprintf(output,"dbg2       pings:      %d\n",pings);
		fprintf(output,"dbg2       lonflip:    %d\n",lonflip);
		fprintf(output,"dbg2       bounds[0]:  %f\n",bounds[0]);
		fprintf(output,"dbg2       bounds[1]:  %f\n",bounds[1]);
		fprintf(output,"dbg2       bounds[2]:  %f\n",bounds[2]);
		fprintf(output,"dbg2       bounds[3]:  %f\n",bounds[3]);
		fprintf(output,"dbg2       btime_i[0]: %d\n",btime_i[0]);
		fprintf(output,"dbg2       btime_i[1]: %d\n",btime_i[1]);
		fprintf(output,"dbg2       btime_i[2]: %d\n",btime_i[2]);
		fprintf(output,"dbg2       btime_i[3]: %d\n",btime_i[3]);
		fprintf(output,"dbg2       btime_i[4]: %d\n",btime_i[4]);
		fprintf(output,"dbg2       btime_i[5]: %d\n",btime_i[5]);
		fprintf(output,"dbg2       btime_i[6]: %d\n",btime_i[6]);
		fprintf(output,"dbg2       etime_i[0]: %d\n",etime_i[0]);
		fprintf(output,"dbg2       etime_i[1]: %d\n",etime_i[1]);
		fprintf(output,"dbg2       etime_i[2]: %d\n",etime_i[2]);
		fprintf(output,"dbg2       etime_i[3]: %d\n",etime_i[3]);
		fprintf(output,"dbg2       etime_i[4]: %d\n",etime_i[4]);
		fprintf(output,"dbg2       etime_i[5]: %d\n",etime_i[5]);
		fprintf(output,"dbg2       etime_i[6]: %d\n",etime_i[6]);
		fprintf(output,"dbg2       speedmin:   %f\n",speedmin);
		fprintf(output,"dbg2       timegap:    %f\n",timegap);
		fprintf(output,"dbg2       file:       %s\n",read_file);
		fprintf(output,"dbg2       mode:       %d\n",mode);
		fprintf(output,"dbg2       gaussian:   %d\n",gaussian);
		fprintf(output,"dbg2       nbins:      %d\n",nbins);
		fprintf(output,"dbg2       nintervals: %d\n",nintervals);
		fprintf(output,"dbg2       value_min:  %f\n",value_min);
		fprintf(output,"dbg2       value_max:  %f\n",value_max);
		}

	/* if help desired then print it and exit */
	if (help)
		{
		fprintf(output,"\n%s\n",help_message);
		fprintf(output,"\nusage: %s\n", usage_message);
		exit(error);
		}

	/* allocate memory for histogram arrays */
	if (error == MB_ERROR_NO_ERROR)
		status = mb_mallocd(verbose,__FILE__,__LINE__,nbins*sizeof(double),
				(void **)&histogram,&error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_mallocd(verbose,__FILE__,__LINE__,nintervals*sizeof(double),
				(void **)&intervals,&error);

	/* if error initializing memory then quit */
	if (error != MB_ERROR_NO_ERROR)
		{
		mb_error(verbose,error,&message);
		fprintf(output,"\nMBIO Error allocating histogram arrays:\n%s\n",message);
		fprintf(output,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* output some information */
	if (verbose > 0)
		{
		fprintf(stderr, "\nNumber of data bins: %d\n", nbins);
		fprintf(stderr, "Minimum value:         %f\n", value_min);
		fprintf(stderr, "Maximum value:         %f\n", value_max);
		if (mode == MBHISTOGRAM_BATH)
			fprintf(stderr, "Working on bathymetry data...\n");
		else if (mode == MBHISTOGRAM_AMP)
			fprintf(stderr, "Working on beam amplitude data...\n");
		else
			fprintf(stderr, "Working on sidescan data...\n");
		}

	/* get size of bins */
	dvalue_bin = (value_max - value_min)/(nbins-1);
	value_bin_min = value_min - 0.5*dvalue_bin;
	value_bin_max = value_max + 0.5*dvalue_bin;

	/* initialize histogram */
	for (i=0;i<nbins;i++)
		histogram[i] = 0;

	/* determine whether to read one file or a list of files */
	if (format < 0)
		read_datalist = MB_YES;

	/* open file list */
	if (read_datalist == MB_YES)
	    {
	    if ((status = mb_datalist_open(verbose,&datalist,
					    read_file,look_processed,&error)) != MB_SUCCESS)
		{
		error = MB_ERROR_OPEN_FAIL;
		fprintf(stderr,"\nUnable to open data list file: %s\n",
			read_file);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}
	    if ((status = mb_datalist_read(verbose,datalist,
			    file,&format,&file_weight,&error))
			    == MB_SUCCESS)
		read_data = MB_YES;
	    else
		read_data = MB_NO;
	    }
	/* else copy single filename to be read */
	else
	    {
	    strcpy(file, read_file);
	    read_data = MB_YES;
	    }

	/* loop over all files to be read */
	while (read_data == MB_YES)
	{

	/* obtain format array location - format id will
		be aliased to current id if old format id given */
	status = mb_format(verbose,&format,&error);

	/* initialize reading the swath sonar data file */
	if ((status = mb_read_init(
		verbose,file,format,pings,lonflip,bounds,
		btime_i,etime_i,speedmin,timegap,
		&mbio_ptr,&btime_d,&etime_d,
		&beams_bath,&beams_amp,&pixels_ss,&error)) != MB_SUCCESS)
		{
		mb_error(verbose,error,&message);
		fprintf(output,"\nMBIO Error returned from function <mb_read_init>:\n%s\n",message);
		fprintf(output,"\nMultibeam File <%s> not initialized for reading\n",file);
		fprintf(output,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* allocate memory for data arrays */
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						sizeof(char), (void **)&beamflag, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						sizeof(double), (void **)&bath, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_AMPLITUDE,
						sizeof(double), (void **)&amp, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						sizeof(double), (void **)&bathacrosstrack, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						sizeof(double), (void **)&bathalongtrack, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_SIDESCAN,
						sizeof(double), (void **)&ss, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_SIDESCAN,
						sizeof(double), (void **)&ssacrosstrack, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_SIDESCAN,
						sizeof(double), (void **)&ssalongtrack, &error);

	/* if error initializing memory then quit */
	if (error != MB_ERROR_NO_ERROR)
		{
		mb_error(verbose,error,&message);
		fprintf(output,"\nMBIO Error allocating data arrays:\n%s\n",message);
		fprintf(output,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* output information */
	if (error == MB_ERROR_NO_ERROR && verbose > 0)
	    {
	    fprintf(stderr, "\nprocessing file: %s %d\n", file, format);
	    }

	/* initialize counting variables */
	nrec = 0;
	nvalue = 0;

	/* read and process data */
	while (error <= MB_ERROR_NO_ERROR)
		{

		/* read a ping of data */
		status = mb_get(verbose,mbio_ptr,&kind,&pings,
				time_i,&time_d,
				&navlon,&navlat,
				&speed,&heading,
				&distance,&altitude,&sonardepth,
				&beams_bath,&beams_amp,&pixels_ss,
				beamflag,bath,amp,bathacrosstrack,bathalongtrack,
				ss,ssacrosstrack,ssalongtrack,
				comment,&error);

		/* process the pings */
		if (error == MB_ERROR_NO_ERROR
			|| error == MB_ERROR_TIME_GAP)
			{
			/* increment record counter */
			nrec++;

			/* do the bathymetry */
			if (mode == MBHISTOGRAM_BATH)
			for (i=0;i<beams_bath;i++)
				{
				if (mb_beam_ok(beamflag[i]))
					{
					nvalue++;
					j = (bath[i] - value_bin_min)
						/dvalue_bin;
					if (j >= 0 && j < nbins)
						histogram[j]++;
					if (data_first == MB_YES)
						{
						data_min = bath[i];
						data_max = bath[i];
						data_first = MB_NO;
						}
					else
						{
						data_min = MIN(bath[i], data_min);
						data_max = MAX(bath[i], data_max);
						}
					}
				}

			/* do the amplitude */
			if (mode == MBHISTOGRAM_AMP)
			for (i=0;i<beams_amp;i++)
				{
				if (mb_beam_ok(beamflag[i]))
					{
					nvalue++;
					j = (amp[i] - value_bin_min)
						/dvalue_bin;
					if (j >= 0 && j < nbins)
						histogram[j]++;
					if (data_first == MB_YES)
						{
						data_min = amp[i];
						data_max = amp[i];
						data_first = MB_NO;
						}
					else
						{
						data_min = MIN(amp[i], data_min);
						data_max = MAX(amp[i], data_max);
						}
					}
				}

			/* do the sidescan */
			if (mode == MBHISTOGRAM_SS)
			for (i=0;i<pixels_ss;i++)
				{
				if (ss[i] > MB_SIDESCAN_NULL)
					{
					nvalue++;
					j = (ss[i] - value_bin_min)
						/dvalue_bin;
					if (j >= 0 && j < nbins)
						histogram[j]++;
					if (data_first == MB_YES)
						{
						data_min = ss[i];
						data_max = ss[i];
						data_first = MB_NO;
						}
					else
						{
						data_min = MIN(ss[i], data_min);
						data_max = MAX(ss[i], data_max);
						}
					}
				}

			}
		}

	/* close the swath sonar data file */
	status = mb_close(verbose,&mbio_ptr,&error);
	nrectot += nrec;
	nvaluetot += nvalue;

	/* output information */
	if (error == MB_ERROR_NO_ERROR && verbose > 0)
	    {
	    fprintf(stderr, "%d records processed\n%d data processed\n",
		    nrec, nvalue);
	    }

	/* figure out whether and what to read next */
        if (read_datalist == MB_YES)
                {
		if ((status = mb_datalist_read(verbose,datalist,
			    file,&format,&file_weight,&error))
			    == MB_SUCCESS)
                        read_data = MB_YES;
                else
                        read_data = MB_NO;
                }
        else
                {
                read_data = MB_NO;
                }

	/* end loop over files in list */
	}
	if (read_datalist == MB_YES)
		mb_datalist_close(verbose,&datalist,&error);

	/* output information */
	if (error == MB_ERROR_NO_ERROR && verbose > 0)
	    {
	    fprintf(stderr, "\n%d total records processed\n", nrectot);
	    fprintf(stderr, "%d total data processed\n\n", nvaluetot);
	    }

	/* recast histogram as gaussian */
	if (gaussian == MB_YES)
		{
		/* get total number of good values */
		total = 0.0;
		for (i=0;i<nbins;i++)
			total = total + histogram[i];

		/* recast histogram */
		sum = 0.0;
		for (i=0;i<nbins;i++)
			{
			p = (histogram[i]/2 + sum)/(total + 1);
			sum = sum + histogram[i];
			histogram[i] = qsnorm(p);
			}
		}

	/* calculate gaussian intervals if required */
	if (nintervals > 0 && gaussian == MB_YES)
		{
		/* get interval spacing */
		target_min = -2.0;
		target_max = 2.0;
		dinterval = (target_max - target_min)/(nintervals-1);

		/* get intervals */
		intervals[0] = MAX(data_min, value_min);
		intervals[nintervals-1] = MIN(data_max, value_max);
		ibin = 0;
		for (j=1;j<nintervals-1;j++)
			{
			target = target_min + j*dinterval;
			while (histogram[ibin] < target && ibin < nbins-1)
				ibin++;
			if (ibin > 0)
				bin_fraction = 1.0 - (histogram[ibin] - target)
					/(histogram[ibin] - histogram[ibin-1]);
			else
				bin_fraction = 0.0;
			intervals[j] = value_bin_min
					+ dvalue_bin*ibin
					+ bin_fraction*dvalue_bin;
			}
		}

	/* calculate linear intervals if required */
	else if (nintervals > 0)
		{
		/* get total number of good values */
		total = 0.0;
		for (i=0;i<nbins;i++)
			total = total + histogram[i];

		/* get interval spacing */
		dinterval = total/(nintervals-1);

		/* get intervals */
		intervals[0] = value_bin_min;
		total = 0.0;
		ibin = -1;
		for (j=1;j<nintervals;j++)
			{
			target = j*dinterval;
			while (total < target && ibin < nbins-1)
				{
				ibin++;
				total = total + histogram[ibin];
				if (total <= 0.0)
					intervals[0] = value_bin_min
						+ dvalue_bin*ibin;
				}
			bin_fraction = 1.0 - (total - target)/histogram[ibin];
			intervals[j] = value_bin_min
					+ dvalue_bin*ibin
					+ bin_fraction*dvalue_bin;
			}
		}

	/* print out the results */
	if (nintervals <= 0 && gaussian == MB_YES)
		{
		for (i=0;i<nbins;i++)
			{
			fprintf(output,"%f %f\n",
				value_min+i*dvalue_bin,histogram[i]);
			}
		}
	else if (nintervals <= 0)
		{
		for (i=0;i<nbins;i++)
			{
			fprintf(output,"%f %d\n",
				value_min+i*dvalue_bin,(int)histogram[i]);
			}
		}
	else
		{
		for (i=0;i<nintervals;i++)
			fprintf(output,"%f\n",intervals[i]);
		}

	/* deallocate memory used for data arrays */
	mb_freed(verbose,__FILE__,__LINE__,(void **)&histogram,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&intervals,&error);

	/* set program status */
	status = MB_SUCCESS;

	/* check memory */
	if (verbose >= 4)
		status = mb_memory_list(verbose,&error);

	/* print output debug statements */
	if (verbose >= 2)
		{
		fprintf(output,"\ndbg2  Program <%s> completed\n",
			program_name);
		fprintf(output,"dbg2  Ending status:\n");
		fprintf(output,"dbg2       status:  %d\n",status);
		}

	/* end it all */
	fprintf(output,"\n");
	exit(error);
}
Пример #13
0
int main (int argc, char **argv)
{
	char program_name[] = "MBPS";
	char help_message[] =  "MBPS reads a swath bathymetry data file and creates a postscript 3-d mesh plot";
	char usage_message[] = "mbps [-Iinfile -Fformat -Nnpings -Ppings\n\t-Byr/mo/da/hr/mn/sc -Eyr/mo/da/hr/mn/sc  \n\t-Aalpha -Keta -Dviewdir -Xvertexag \n\t-T\"title\" -Wmetersperinch \n\t-Sspeedmin -Ggap -Ydisplay_stats \n\t-Zdisplay_scales -V -H]";
	extern char *optarg;
	int	errflg = 0;
	int	c;
	int	help = 0;
	int	flag = 0;

	/*ALBERTO definitions */
	int	gap=1;
	double	*xp, *yp;
	double	xl[4], yl[4];
	double	alpha =		ALPHA_DEF;
	double	eta =		ETA_DEF;
	double	ve =		VE_DEF;
	char	viewdir =	VIEWDIR_DEF;
	int	display_stats = MB_YES;
	int	display_scales = MB_YES;
	double	sin_eta, cos_eta;
	double	sin_alpha, cos_alpha;
	double	track_length, xscale, zscale, zscale_inch;
	double	mean_xp=0.0, mean_yp=0.0, min_xp, max_xp, min_yp, max_yp;
	double	scaling, x_off, y_off;
	double	min_z, max_z, range_z, meters_per_inch=(-1.0);
	double	mean_lat=0.0;
	double	mean_lon=0.0;
	double	mean_latmin;
	double	mean_lonmin;
	double	mean_hdg=0.0;
	int	done, mean_knt=0;
	int	orient;
	char	label[100];
	int	a, b, rotate;
	double	x, y, z;

	/* MBIO status variables */
	int	status = MB_SUCCESS;
	int	verbose = 0;
	int	error = MB_ERROR_NO_ERROR;
	char	*message;

	/* MBIO read control parameters */
	int	format;
	int	lonflip;
	double	bounds[4];
	int	btime_i[7];
	int	etime_i[7];
	double	btime_d;
	double	etime_d;
	double	speedmin;
	double	timegap;
	char	file[MB_PATH_MAXLINE];
	int	pings = 1;
	int	beams_bath;
	int	beams_amp;
	int	pixels_ss;
	int	num_pings_max = MBPS_MAXPINGS;

	/* MBIO read values */
	void	*mbio_ptr = NULL;
	int	kind;
	struct ping data[MBPS_MAXPINGS+3];
	int	time_i[7];
	double	time_d;
	double	navlon;
	double	navlat;
	double	speed;
	double	heading;
	double	distance;
	double	altitude;
	double	sonardepth;
	char	*beamflag;
	double	*bath = NULL;
	double	*bathacrosstrack = NULL;
	double	*bathalongtrack = NULL;
	double	*amp = NULL;
	double	*ss = NULL;
	double	*ssacrosstrack = NULL;
	double	*ssalongtrack = NULL;
	char	comment[MB_COMMENT_MAXLINE];
	int	timbeg_i[7];
	int	timend_i[7];
	double	distot = 0.0;
	int	nread;

	char	title[MB_COMMENT_MAXLINE];
	int	forward;
	double	xx, yy, zz;
	double	heading_start, dheading, dheadingx, dheadingy;
	int	i, j, jj, k;
	
	void Polygon_Fill();
	void Good_Polygon();

	/* initialize some time variables */
	for (i=0;i<7;i++)
		{
		timbeg_i[i] = 0;
		timend_i[i] = 0;
		}

	/* get current default values */
	status = mb_defaults(verbose,&format,&pings,&lonflip,bounds,
		btime_i,etime_i,&speedmin,&timegap);

	/* set default input to stdin */
	strcpy (file, "stdin");

	/* process argument list */
	while ((c = getopt(argc, argv, "VvHhF:f:B:b:E:e:S:s:T:t:I:i:A:a:X:x:K:k:D:d:N:n:P:p:W:w:G:g:YyZz")) != -1)
	    switch (c) 
		{
		case 'H':
		case 'h':
			help++;
			break;
		case 'V':
		case 'v':
			verbose++;
			break;
		case 'A':
		case 'a':
			sscanf (optarg, "%lf", &alpha);
			flag++;
			break;
		case 'B':
		case 'b':
			sscanf (optarg,"%d/%d/%d/%d/%d/%d",
				&btime_i[0],&btime_i[1],&btime_i[2],
				&btime_i[3],&btime_i[4],&btime_i[5]);
			btime_i[6] = 0;
			flag++;
			break;
		case 'D':
		case 'd':
			sscanf (optarg, "%c", &viewdir);
			flag++;
			break;
		case 'E':
		case 'e':
			sscanf (optarg,"%d/%d/%d/%d/%d/%d",
				&etime_i[0],&etime_i[1],&etime_i[2],
				&etime_i[3],&etime_i[4],&etime_i[5]);
			etime_i[6] = 0;
			flag++;
			break;
		case 'F':
		case 'f':
			sscanf (optarg,"%d", &format);
			flag++;
			break;
		case 'G':
		case 'g':
			sscanf (optarg, "%d", &gap);
			flag++;
			break;
		case 'I':
		case 'i':
			sscanf (optarg,"%s", file);
			flag++;
			break;
		case 'K':
		case 'k':
			sscanf (optarg, "%lf", &eta);
			flag++;
			break;
		case 'N':
		case 'n':
			sscanf (optarg, "%d", &num_pings_max);
			if (num_pings_max < 2
			    || num_pings_max > MBPS_MAXPINGS) 
			num_pings_max = MBPS_MAXPINGS;
			flag++;
			break;
		case 'P':
		case 'p':
			sscanf (optarg, "%d", &pings);
			flag++;
			break;
		case 'S':
		case 's':
			sscanf (optarg,"%lf", &speedmin);
			flag++;
			break;
		case 'T':
		case 't':
			sscanf (optarg,"%s", title);
			flag++;
			break;
		case 'X':
		case 'x':
			sscanf (optarg, "%lf", &ve);
			flag++;
			break;
		case 'W':
		case 'w':
			sscanf (optarg, "%lf", &meters_per_inch);
			flag++;
			break;
		case 'Y':
		case 'y':
			display_stats = MB_NO;
			flag++;
			break;
		case 'Z':
		case 'z':
			display_scales = MB_NO;
			flag++;
			break;
		case '?':
			errflg++;
			break;
		} /* switch */

		
	/* Process the title of the plot */
	for (i = 1; i < argc; i++) 
		{
		if (argv[i][0] == '-'&& ((argv[i][1]=='T')||(argv[i][1]=='t')) ) {
			strcpy(title,argv[i]);
			title[0]=' ';
			title[1]=' ';
			}
		}

	/* check that otions are allowed */
	if ((viewdir!='P') && (viewdir!='S') && (viewdir!='B') && 
            (viewdir!='p') && (viewdir!='s') && (viewdir!='b'))
		{
		fprintf(stderr,"viewdir must be either P/p (port) S/s (stbd) or B/b (back)\n");
		errflg++;
		}

	/* if error flagged then print it and exit */
	if (errflg) 
		{
		fprintf(stderr,"usage: %s\n", usage_message);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		error = MB_ERROR_BAD_USAGE;
		exit(error);
		}

	/* print starting message */
	if (verbose == 1 || help) 
		{
		fprintf(stderr,"\nProgram %s\n",program_name);
		fprintf(stderr,"MB-system Version %s\n",MB_VERSION);
		}

	/* print starting debug statements */
	if (verbose >= 2) 
		{
		fprintf(stderr,"\ndbg2  Program <%s>\n",program_name);
		fprintf(stderr,"dbg2  MB-system Version %s\n",MB_VERSION);
		fprintf(stderr,"dbg2  Control Parameters:\n");
		fprintf(stderr,"dbg2       verbose:    %d\n",verbose);
		fprintf(stderr,"dbg2       help:       %d\n",help);
		fprintf(stderr,"dbg2       format:     %d\n",format);
		fprintf(stderr,"dbg2       btime_i[0]: %d\n",btime_i[0]);
		fprintf(stderr,"dbg2       btime_i[1]: %d\n",btime_i[1]);
		fprintf(stderr,"dbg2       btime_i[2]: %d\n",btime_i[2]);
		fprintf(stderr,"dbg2       btime_i[3]: %d\n",btime_i[3]);
		fprintf(stderr,"dbg2       btime_i[4]: %d\n",btime_i[4]);
		fprintf(stderr,"dbg2       btime_i[5]: %d\n",btime_i[5]);
		fprintf(stderr,"dbg2       btime_i[6]: %d\n",btime_i[6]);
		fprintf(stderr,"dbg2       etime_i[0]: %d\n",etime_i[0]);
		fprintf(stderr,"dbg2       etime_i[1]: %d\n",etime_i[1]);
		fprintf(stderr,"dbg2       etime_i[2]: %d\n",etime_i[2]);
		fprintf(stderr,"dbg2       etime_i[3]: %d\n",etime_i[3]);
		fprintf(stderr,"dbg2       etime_i[4]: %d\n",etime_i[4]);
		fprintf(stderr,"dbg2       etime_i[5]: %d\n",etime_i[5]);
		fprintf(stderr,"dbg2       etime_i[6]: %d\n",etime_i[6]);
		fprintf(stderr,"dbg2       speedmin:   %f\n",speedmin);
		fprintf(stderr,"dbg2       file:       %s\n",file);
		}

	/* if help desired then print it and exit */
	if (help) 
		{
		fprintf(stderr,"\n%s\n",help_message);
		fprintf(stderr,"\nusage: %s\n", usage_message);
		exit(error);
		}

	/* get format if required */
	if (format == 0)
		mb_get_format(verbose,file,NULL,&format,&error);

	/* initialize reading the swath file */
	if ((status = mb_read_init(
		verbose,file,format,pings,lonflip,bounds,
		btime_i,etime_i,speedmin,timegap,
		&mbio_ptr,&btime_d,&etime_d,
		&beams_bath,&beams_amp,&pixels_ss,&error)) != MB_SUCCESS) 
		{
		mb_error(verbose,error,&message);
		fprintf(stderr,"\nMBIO Error returned from function <mb_read_init>:\n%s\n",message);
		fprintf(stderr,"\nMultibeam File <%s> not initialized for reading\n",file);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* initialize values */
	sin_alpha = sin(alpha*DTR);
	cos_alpha = cos(alpha*DTR);
	sin_eta = sin(eta*DTR);
	cos_eta = cos(eta*DTR);
	min_z = 0.0;
	max_z = -9999.0;

	/* allocate memory for data arrays */
	beamflag = NULL;
	bath = NULL;
	bathacrosstrack = NULL;
	bathalongtrack = NULL;
	amp = NULL;
	ss = NULL;
	ssacrosstrack = NULL;
	ssalongtrack = NULL;
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						sizeof(char), (void **)&beamflag, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						sizeof(double), (void **)&bath, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						sizeof(double), (void **)&bathacrosstrack, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						sizeof(double), (void **)&bathalongtrack, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_AMPLITUDE,
						sizeof(double), (void **)&amp, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_SIDESCAN, 
						sizeof(double), (void **)&ss, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_SIDESCAN, 
						sizeof(double), (void **)&ssacrosstrack, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_SIDESCAN, 
						sizeof(double), (void **)&ssalongtrack, &error);
	for (i=0;i<num_pings_max+3;i++) 
		{
		data[i].beams_bath = 0;
		data[i].beamflag = NULL;
		data[i].bath = NULL;
		data[i].bathacrosstrack = NULL;
		data[i].bathalongtrack = NULL;
		data[i].xp = NULL;
		data[i].yp = NULL;
		}  


	/* if error initializing memory then quit */
	if (error != MB_ERROR_NO_ERROR)
		{
		mb_error(verbose,error,&message);
		fprintf(stderr,"\nMBIO Error allocating data arrays:\n%s\n",message);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* read and process data */
	nread = 0;
	done = MB_NO;
	error = MB_ERROR_NO_ERROR;
	while (done == MB_NO && error <= MB_ERROR_NO_ERROR)
		{
		/* read a ping of data */
		status = mb_get(verbose,mbio_ptr,&kind,&pings,
			time_i,&time_d,
			&navlon,&navlat,
			&speed,&heading,
			&distance,&altitude,&sonardepth,
			&beams_bath,&beams_amp,&pixels_ss,
			beamflag,bath,amp,
			bathacrosstrack,
			bathalongtrack,
			ss,
			ssacrosstrack,
			ssalongtrack,
			comment,&error);
			
		/* only work with survey data */
		if (error == MB_ERROR_NO_ERROR && kind == MB_DATA_DATA)
			{

			/* allocate arrays */
			data[nread].beams_bath = beams_bath;
			status = mb_mallocd(verbose, __FILE__, __LINE__, beams_bath*sizeof(char), (void **)&(data[nread].beamflag), &error);
			status = mb_mallocd(verbose, __FILE__, __LINE__, beams_bath*sizeof(double), (void **)&(data[nread].bath), &error);
			status = mb_mallocd(verbose, __FILE__, __LINE__, beams_bath*sizeof(double), (void **)&(data[nread].bathacrosstrack), &error);
			status = mb_mallocd(verbose, __FILE__, __LINE__, beams_bath*sizeof(double), (void **)&(data[nread].bathalongtrack), &error);
			status = mb_mallocd(verbose, __FILE__, __LINE__, beams_bath*sizeof(double), (void **)&(data[nread].xp), &error);
			status = mb_mallocd(verbose, __FILE__, __LINE__, beams_bath*sizeof(double), (void **)&(data[nread].yp), &error);

			/* copy data to storage arrays */
			for (i=0;i<beams_bath;i++)
				{
				data[nread].beamflag[i] = beamflag[i];
				data[nread].bath[i] = bath[i];
				data[nread].bathacrosstrack[i] = bathacrosstrack[i];
				data[nread].bathalongtrack[i] = bathalongtrack[i];
				data[nread].xp[i] = BAD;
				data[nread].yp[i] = BAD;
				}

			/* ignore time gaps */
			if (error == MB_ERROR_TIME_GAP)
				{
				error = MB_ERROR_NO_ERROR;
				status = MB_SUCCESS;
				}

			/* output error messages */
			if (error == MB_ERROR_COMMENT)
				{
				/* do nothing */
				}
			else if (verbose >= 1 && error < MB_ERROR_NO_ERROR
				&& error >= MB_ERROR_OTHER)
				{
				mb_error(verbose,error,&message);
				fprintf(stderr,"\nNonfatal MBIO Error:\n%s\n",
					message);
				fprintf(stderr,"Time: %d %d %d %d %d %d %d\n",
					time_i[0],time_i[1],time_i[2],
					time_i[3],time_i[4],time_i[5],
					time_i[6]);
				}
			else if (verbose >= 1 && error < MB_ERROR_NO_ERROR)
				{
				mb_error(verbose,error,&message);
				fprintf(stderr,"\nNonfatal MBIO Error:\n%s\n",
					message);
				fprintf(stderr,"Number of good records so far: %d\n",nread);
				}
			else if (verbose >= 1 && error > MB_ERROR_NO_ERROR 
				&& error != MB_ERROR_EOF)
				{
				mb_error(verbose,error,&message);
				fprintf(stderr,"\nFatal MBIO Error:\n%s\n",
					message);
				fprintf(stderr,"Last Good Time: %d %d %d %d %d %d %d\n",
					time_i[0],time_i[1],time_i[2],
					time_i[3],time_i[4],time_i[5],
					time_i[6]);
				}

			/* calculate raw x,y locations for each beam */
			if (status == MB_SUCCESS) 
				{
				/* set initial heading */
				if (nread == 0)
					heading_start = heading;

				/* get heading x and y components */
				dheading = heading - heading_start;
				if (dheading > 360.0)
				    dheading -= 360.0;
				else if (dheading < 0.0)
				    dheading += 360.0;
				dheadingx = sin(DTR * dheading);
				dheadingy = cos(DTR * dheading);

				/* get alongtrack distance in nav */
				distot += distance * 1000.0;	/* distance in meters */

				/* loop over the beams */
				for (j=0; j<beams_bath; j++) 
					{
					if (j >= data[nread].beams_bath)
						{
						data[nread].beamflag[j] = MB_FLAG_NULL;
						data[nread].xp[j] = BAD;
						data[nread].yp[j] = BAD;
						}
					else if (mb_beam_ok(beamflag[j])) 
						{
						xx = dheadingy * bathacrosstrack[j]
						    + dheadingx * bathalongtrack[j];
						yy = distot
						    - dheadingx * bathacrosstrack[j]
						    + dheadingy * bathalongtrack[j];
						zz = -bath[j];
						if (viewdir=='S' || viewdir=='s') 
							{
							data[nread].xp[j] = yy 
							    + xx * sin_eta * cos_alpha;
							data[nread].yp[j] = zz * cos_eta * ve
							    - xx * sin_eta * sin_alpha;
							}
						else if (viewdir=='P' || viewdir=='p') 
							{
							data[nread].xp[j]= -yy 
							    - xx * sin_eta * cos_alpha;
							data[nread].yp[j]= zz * cos_eta * ve
							    + xx * sin_eta * sin_alpha;
							}
						else if (viewdir=='B' || viewdir=='b') 
							{
							data[nread].xp[j] = xx
							    + yy * sin_eta * cos_alpha;
							data[nread].yp[j]= zz * cos_eta * ve
							    + yy * sin_eta * sin_alpha;
							}
						mean_lat += navlat;
						mean_lon += navlon;
						mean_hdg += heading;
						mean_xp += data[nread].xp[j];
						mean_yp += data[nread].yp[j];
						mean_knt++;

						if (-data[nread].bath[j] < min_z) 
						    min_z= -data[nread].bath[j];
						if (-data[nread].bath[j] > max_z) 
						    max_z= -data[nread].bath[j];
						}
					else 
						{
						data[nread].xp[j] = BAD;
						data[nread].yp[j] = BAD;
						}
					} /* for j=0 ... */

				if (nread == 0)
					{
					for (k=0; k<7; k++)
						timbeg_i[k] = time_i[k];
					}
				else
					{
					for (k=0; k<7; k++)
						timend_i[k]=time_i[k];
					}
				}	/* if status==MB_SUCCESS */

			/* increment counters */
			if (error == MB_ERROR_NO_ERROR)
				{
				nread++;
				}
			}

		/* print debug statements */
		if (verbose >= 2) 
			{
			fprintf(stderr,"\ndbg2  Reading loop finished in program <%s>\n",
			program_name);
			fprintf(stderr,"dbg2       status:     %d\n",status);
			fprintf(stderr,"dbg2       error:      %d\n",error);
			fprintf(stderr,"dbg2       nread:      %d\n",nread);
			fprintf(stderr,"dbg2       pings:      %d\n",pings);
			}

		/* test if done */
		if (nread >= num_pings_max
			&& verbose >= 1) 
			{
			fprintf(stderr, "%s: Maximum number of pings [%d] read before end of file reached...\n",
			    program_name, num_pings_max);
			done = MB_YES;
			}
		if (nread >= num_pings_max || error > MB_ERROR_NO_ERROR) 
			{
			done = MB_YES;
			}

		}  /* end of processing data, 1'st while under read/process data */

	/* close the swath file */
	status = mb_close(verbose,&mbio_ptr,&error);

	/* print debug statements */
	if (verbose >= 2) 
		{
		fprintf(stderr,"\ndbg2  Reading loop finished in program <%s>\n",
				program_name);
		fprintf(stderr,"dbg2       status:     %d\n",status);
		fprintf(stderr,"dbg2       error:      %d\n",error);
		fprintf(stderr,"dbg2       nread:      %d\n",nread);
		fprintf(stderr,"dbg2       pings: %d\n",pings);
		}

	/* total track length in m */
	track_length = distot;	
	mean_lat /= mean_knt;
	mean_latmin = fabs(mean_lat - (int) mean_lat) * 60.0;
	mean_lon /= mean_knt;
	mean_lonmin = fabs(mean_lon - (int) mean_lon) * 60.0;
	mean_hdg /= mean_knt;
	mean_xp /= mean_knt;
	mean_yp /= mean_knt;

	/* rescale xp[],yp[] to zero mean; get min and max */
	max_yp = min_yp = max_xp = min_xp = 0.0;
	for (i=0; i<nread; i++) 
		{
		beamflag = data[i].beamflag;
		xp = data[i].xp;
		yp = data[i].yp;
		for (j=0; j<data[i].beams_bath; j++) 
			{
			if (mb_beam_ok(beamflag[j])) 
				{
				yp[j] -= mean_yp;
				xp[j] -= mean_xp;
				min_xp = MIN(min_xp, xp[j]);
				max_xp = MAX(max_xp, xp[j]);
				min_yp = MIN(min_yp, yp[j]);
				max_yp = MAX(max_yp, yp[j]);
				} /* if yp[][] */
			} 	  /* for j */
		} 		  /* for i */

	/* get page orientation, scaling(in/m) factor and startup plot */
	if ((viewdir=='P') || (viewdir=='S') || (viewdir=='p') || (viewdir=='s')) 
		{
		/* Landscape */		
		orient = 0;
		if (meters_per_inch > 0.0) 
			{
			scaling = 1.0 / meters_per_inch;
			x_off = 11. / 2;
			y_off = 8.5 / 2.;
			} 
		else 
			{
			if ( (5.2 / (max_yp - min_yp)) < (8.5 / (max_xp - min_xp)) )
				scaling = (5.2 / (max_yp - min_yp));
			else
				scaling = (8.5 / (max_xp - min_xp));			
			x_off=(-(max_xp + min_xp) * scaling / 2.0) + (11. / 2);
			y_off=(-(max_yp + min_yp) * scaling / 2.0) + (8.5 / 2) - .2;
			}
		} 
	else 
		{
		/* Portrait */		
		orient = 1;
		if (meters_per_inch > 0.0) 
			{
			scaling = 1.0 / meters_per_inch;
			x_off = 8.5 / 2.0;
			y_off = 11. / 2.0;
			} 
		else 
			{
			if ( (8./(max_yp-min_yp))<(6.5/(max_xp-min_xp)) )
				scaling = (8./(max_yp-min_yp));
			else
				scaling = (6.5/(max_xp-min_xp));
			x_off=(-(max_xp+min_xp)*scaling/2.0)+(8.5/2);
			y_off=(-(max_yp+min_yp)*scaling/2.0)+(11./2)-.2;
			}
		}

       /* initialize the Postscript plotting */
#ifdef GMT_MINOR_VERSION
       ps_plotinit_hires(NULL,0,orient,x_off,y_off,1.0,1.0,1,300,1,
               gmtdefs.paper_width, gmtdefs.page_rgb, 
               gmtdefs.encoding.name, 
               GMT_epsinfo (argv[0]));
#else
       ps_plotinit(NULL,0,orient,x_off,y_off,1.0,1.0,1,300,1,
               gmtdefs.paper_width, gmtdefs.page_rgb, 
               gmtdefs.encoding.name, 
               GMT_epsinfo (argv[0]));
#endif
       GMT_echo_command (argc, argv);

	/* now loop over the data in the appropriate order
	    laying down white filled boxes with black outlines
	    wherever the data is good */
	
	if ((viewdir=='S') || (viewdir=='s')) 
		forward = MB_YES;
	else if ((viewdir=='P') || (viewdir=='p')) 
		forward = MB_NO;
	else if ((viewdir=='B') || (viewdir=='b')) 
		{
		if (alpha < 90.0) 
			forward = MB_YES;
		else 
			forward = MB_NO;
		}
	for (j=0;j<beams_bath-1;j++)
		{
		for (i=0;i<nread-1;i++)
			{
			if (forward == MB_YES)
				jj = j;
			else
				jj = beams_bath - 2 - j;
				
			/* make box */
			if (mb_beam_ok(data[i].beamflag[jj])
			    && mb_beam_ok(data[i+1].beamflag[jj])
			    && mb_beam_ok(data[i].beamflag[jj+1])
			    && mb_beam_ok(data[i+1].beamflag[jj+1]))
				{
				xl[0] = scaling * data[i].xp[jj];
				yl[0] = scaling * data[i].yp[jj];
				xl[1] = scaling * data[i+1].xp[jj];
				yl[1] = scaling * data[i+1].yp[jj];
				xl[2] = scaling * data[i+1].xp[jj+1];
				yl[2] = scaling * data[i+1].yp[jj+1];
				xl[3] = scaling * data[i].xp[jj+1];
				yl[3] = scaling * data[i].yp[jj+1];
				ps_polygon(xl,yl,4,rgb_white,1);
				}
			}
		}

	/* titles and such */
	ps_setline(2);	/* set line width */

	if (display_stats == MB_NO) 
		{
		/* plot a title */
		xl[0]=0;
		yl[0]=max_yp*scaling+.6;
		sprintf(label,"%s",title);
		ps_text(xl[0],yl[0],20.,label,0.,6,0);
		} 
	else 
		{
		/* plot a title */
		xl[0]=0;
		yl[0]=max_yp*scaling+1.3;
		sprintf(label,"%s",title);
		ps_text(xl[0],yl[0],20.,label,0.,6,0);

		/*xl[0]-=3.25;*/
		yl[0]-=0.3;
		sprintf(label,"Mean Lat.: %3d@+o@+ %4.1f'   Mean Lon.: %4d@+o @+%4.1f'   Heading: %.1lf@+o @+",(int)mean_lat, mean_latmin, (int)mean_lon, mean_lonmin, mean_hdg);
		ps_text(xl[0],yl[0],15.,label,0.,6,0);

		yl[0]-=0.3;
		sprintf(label,"View Angle: %.1lf@+o @+  V.E.: %.1lfX   Scale: %.0lf m/inch   Track Length: %.1lf km",eta,ve,1.0/scaling,track_length/1000.0);
		ps_text(xl[0],yl[0],15.,label,0.,6,0);

		yl[0]-=0.3;
		sprintf(label,
		"From %.4d/%.2d/%.2d %.2d:%.2d:%.2d   to  %.4d/%.2d/%.2d %.2d:%.2d:%.2d",
		timbeg_i[0],timbeg_i[1],timbeg_i[2],timbeg_i[3],
		timbeg_i[4],timbeg_i[5],timend_i[0],timend_i[1],
		timend_i[2],timend_i[3],timend_i[4],timend_i[5]);
		ps_text(xl[0],yl[0],15.,label,0.,6,0);
		} /* else after if display_stats */


	if (display_scales == MB_YES) 
		{
		/* plot the x-scale */
		xscale=10000;		/* x scale in m */
		if (track_length < 50000) xscale=5000;
		if (track_length < 20000) xscale=2000;
		if (track_length < 10000) xscale=1000;
		xl[0]=xl[1]= (-xscale*scaling/2.0);
		xl[2]=xl[3]= (-xl[0]);
		xl[0]+=2.;xl[1]+=2.;xl[2]+=2.;xl[3]+=2.;
		yl[1]=yl[2]= min_yp*scaling-1.;
		yl[0]=yl[3]= yl[1]+0.1;
	
#ifdef GMT_MINOR_VERSION
		ps_line(xl,yl,4,3,0);
#else
		ps_line(xl,yl,4,3,0,0);
#endif
		sprintf(label,"%.0f km",xscale/1000.0);
		ps_text(xl[0]+.5,yl[0]+.05,15.,label,0.,6,0);

	
		/* plot the z-scale */
		range_z=(max_z-min_z);
		zscale=2000;		/* z scale in m */
		if (range_z < 3000) zscale=1000;
		if (range_z < 1000) zscale=500;
		if (range_z < 500) zscale=200;
		if (range_z < 250) zscale=100;
		zscale_inch= zscale*scaling*cos_eta*ve;
		xl[1]=xl[2]+0.5;
		xl[2]=xl[1];
		xl[0]=xl[3]= xl[1]+.1;
		yl[0]=yl[1]= min_yp*scaling-1.;
		yl[2]=yl[3]= yl[0]+zscale_inch;

#ifdef GMT_MINOR_VERSION
		ps_line(xl,yl,4,3,0);
#else
		ps_line(xl,yl,4,3,0,0);
#endif
		sprintf(label,"%.0f m",zscale);
		ps_text(xl[0]+0.3,yl[0]+zscale_inch/2.0,15.,label,0.,6,0);


		/* plot an arrow in the ship's direction */
		a=0;
		b=beams_bath/2;
		while (!mb_beam_ok(data[a++].beamflag[b])) {}
		xl[0] = data[--a].xp[b];
		yl[0] = data[a].yp[b];
		a = nread - 1;
		while (!mb_beam_ok(data[a--].beamflag[b])) {}
		xl[1] = data[++a].xp[b];
		yl[1] = data[a].yp[b];
		xl[1] = ((xl[1]-xl[0])/distot/2)+.6;
		yl[1] = ((yl[1]-yl[0])/distot/2) + min_yp*scaling-1.;
		xl[0] = 0.+.6; 
		yl[0] = 0.+min_yp*scaling-0.85;
		ps_vector(xl[0],yl[0],xl[1],yl[1],
		    0.01,0.25,0.1,1.0,rgb_black,0);
		ps_text(xl[0]-1.7,yl[0]+.2,15.,"ship heading",0.,1,0);
		ps_text(xl[0]-1.7,yl[0],15.,"direction",0.,1,0);


		/* plot the three axes */
		for (i=0;i<3;i++) 
			{
			xl[0]=0.;	/* point in center of page */
			yl[0]=0.;
			rotate=0;	/* set to 1 if arrow is rotated below */
			if (i==0) 
				{	
				/* x-axis */
				x=1.;
				y=0;	
				z=0;
				} 
			else if (i==1) 
				{
				/* y-axis */
				x=0;	
				y=1.;	
				z=0;
				} 
			else if (i==2) 
				{	
				/* z-axis */
				x=0;
				y=0;	
				z=-1.;
				}

			if (viewdir=='P' || viewdir=='p') 
				{
				xl[1]=-y-x*sin_eta*cos_alpha+xl[0];
				yl[1]= -z*cos_eta+x*sin_eta*sin_alpha+yl[0];
				} 
			else if (viewdir=='B' || viewdir=='b') 
				{
				xl[1]=(x+y*sin_eta*cos_alpha)+xl[0];
				yl[1]=-z*cos_eta+y*sin_eta*sin_alpha+yl[0];
				} 
			else if (viewdir=='S' || viewdir=='s') 
				{
				xl[1]=y+x*sin_eta*cos_alpha+xl[0];
				yl[1]=z*cos_eta-x*sin_eta*sin_alpha+yl[0];
				}

			if (yl[1]<yl[0]) 
				{	
				/* rotate arrows 180 if facing downward */
				xl[1]=-xl[1];
				yl[1]=-yl[1];
				rotate=1;
				}

			xl[0]=(-3.);		/* move arrows from center to lower left corner */
			yl[0]=(min_yp*scaling-1.);
			xl[1]=xl[0]+xl[1];
			yl[1]=yl[0]+yl[1];

			ps_vector(xl[0],yl[0],xl[1],yl[1],
				0.01,0.25,0.1,1.0,rgb_black,0);

			if (i==0&&rotate==0)
				ps_text(xl[1],yl[1]+.15,15.,"x",0.,6,0);
			else if (i==1&&rotate==0)
				ps_text(xl[1],yl[1]+.15,15.,"y",0.,6,0);
			else if (i==2&&rotate==0)
				ps_text(xl[1],yl[1]+.15,15.,"z",0.,6,0);
			else if (i==0&&rotate==1)
				ps_text(xl[1],yl[1]+.15,15.,"-x",0.,6,0);
			else if (i==1&&rotate==1)
				ps_text(xl[1],yl[1]+.15,15.,"-y",0.,6,0);
			else if (i==2&&rotate==1)
				ps_text(xl[1],yl[1]+.15,15.,"z",0.,6,0);

			} /* (i=0;i<3;i++) */
		} /* if display_scales */

	/* end the postscript file */
	ps_plotend(1);
	
	/* deallocate arrays */
	for (i=0;i<nread;i++)
		{
		mb_freed(verbose,__FILE__, __LINE__, (void **)&(data[i].beams_bath), &error);
		mb_freed(verbose,__FILE__, __LINE__, (void **)&(data[i].bath), &error);
		mb_freed(verbose,__FILE__, __LINE__, (void **)&(data[i].bathacrosstrack), &error);
		mb_freed(verbose,__FILE__, __LINE__, (void **)&(data[i].bathalongtrack), &error);
		mb_freed(verbose,__FILE__, __LINE__, (void **)&(data[i].xp), &error);
		mb_freed(verbose,__FILE__, __LINE__, (void **)&(data[i].yp), &error);
		}

	/* check memory */
	if (verbose >= 4)
		status = mb_memory_list(verbose,&error);

	/* print output debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  Program <%s> completed\n",
			program_name);
		fprintf(stderr,"dbg2  Ending status:\n");
		fprintf(stderr,"dbg2       status:  %d\n",status);
		}

	/* end it all */
	exit(error);

}	/* main */
Пример #14
0
int main(int argc, char **argv) {
	char program_name[] = "mbminirovnav";
	char help_message[] = " MBminirov reads USBL tracking and CTD day files from the MBARI MiniROV\n"
                            "\tand produces a single ROV navigation file in one of the standard MBARI\n"
                            "\tformats handles preprocessing of swath sonar data as part of setting up\n"
                            "\tan MB-System processing structure for a dataset.\n";
	char usage_message[] = "mbminirovnav\n"
	                       "\t--help\n\n"
	                       "\t--input=fileroot\n"
	                       "\t--input-ctd-file=file\n"
	                       "\t--input-dvl-file=file\n"
	                       "\t--input-nav-file=file\n"
	                       "\t--input-rov-file=file\n"
						   "\t--interpolate-position\n"
						   "\t--interval=seconds\n"
	                       "\t--output=file\n"
						   "\t--rov-dive-start=yyyymmddhhmmss\n"
						   "\t--rov-dive-end=yyyymmddhhmmss\n"
						   "\t--utm-zone=zone_id/NorS\n"
	                       "\t--verbose\n\n";

	extern char *optarg;
	int option_index;
	int errflg = 0;
	int c;
	int help = MB_NO;
	
	/* ROV dive time start and end */
	int rov_dive_start_time_set = MB_NO;
	double rov_dive_start_time_d;
	int rov_dive_start_time_i[7];
	int rov_dive_end_time_set = MB_NO;
	double rov_dive_end_time_d;
	int rov_dive_end_time_i[7];
	int interpolate_position = MB_NO;

	/* MBIO status variables */
	int status = MB_SUCCESS;
	int verbose = 0;
	int error = MB_ERROR_NO_ERROR;
	char *message;
    
    int num_nav_alloc = 0;
    int num_nav = 0;
    double *nav_time_d = NULL;
    double *nav_lon = NULL;
    double *nav_lat = NULL;
   
    int num_ctd_alloc = 0;
    int num_ctd = 0;
    double *ctd_time_d = NULL;
    double *ctd_depth = NULL;
   
    int num_rov_alloc = 0;
    int num_rov = 0;
    double *rov_time_d = NULL;
    double *rov_heading = NULL;
    double *rov_roll = NULL;
    double *rov_pitch = NULL;
  
    int num_dvl_alloc = 0;
    int num_dvl = 0;
    double *dvl_time_d = NULL;
    double *dvl_altitude = NULL;
    double *dvl_stime = NULL;
    double *dvl_vx = NULL;
    double *dvl_vy = NULL;
    double *dvl_vz = NULL;
    double *dvl_status = NULL;
		
	double time_d;
	double rawlat, rawlon, dummydouble, ldegrees, lminutes;
	double reference_lon = 0.0;
	double reference_lat = 0.0;
	int utm_zone_set = MB_NO;
	int	utm_zone = 0;
	mb_path projection_id;
	void *pjptr = NULL;
	char NorS, EorW;
	mb_path dummystring;
	double ctd_C, ctd_T, ctd_D, ctd_S;
	double ctd_O2uM, ctd_O2raw, ctd_DGH_T, ctd_C2_T, ctd_C2_C;
	double rov_x, rov_y, rov_z, rov_yaw, rov_magna_amps;
	double rov_F1, rov_F2, rov_F3, rov_F4, rov_F5;
	double rov_Heading, rov_Pitch, rov_Roll;
	double dvl_Altitude, dvl_Stime, dvl_Vx, dvl_Vy, dvl_Vz, dvl_Status;

	double start_time_d = 0.0;
	double end_time_d = 0.0;
	double interval = 1.0;
	int onav_time_i[7], onav_time_j[5];
	int onav_year, onav_jday, onav_timetag;
	double num_output;
	double onav_time_d;
	double onav_lon;
	double onav_lat;
	double onav_easting;
	double onav_northing;
	double onav_depth;
	double onav_pressure;
	double onav_heading;
	double onav_altitude;
	double onav_pitch;
	double onav_roll;
	int onav_position_flag;
	int onav_pressure_flag;
	int onav_heading_flag;
	int onav_altitude_flag;
	int onav_attitude_flag;
    
	char buffer[MB_PATH_MAXLINE], *result;
	int nrecord;
	int nchar, nget, nscan;
	int ioutput;
	size_t size;
	FILE *fp;
	int jnav = 0;
	int jctd = 0;
	int jdvl = 0;
	int jrov = 0;
	int interp_status = MB_SUCCESS;
	int interp_error = MB_ERROR_NO_ERROR;
	int proj_status = 0;

	/* command line option definitions */
	/* mbminirovnav
	 * 		--verbose
	 * 		--help
	 *
	 * 		--input-nav=file
	 * 		--input-ctd=file
	 * 		--output=file
	 */
	static struct option options[] = {{"help", no_argument, NULL, 0},
	                                  {"input", required_argument, NULL, 0},
	                                  {"input-nav-file", required_argument, NULL, 0},
	                                  {"input-ctd-file", required_argument, NULL, 0},
	                                  {"input-dvl-file", required_argument, NULL, 0},
	                                  {"input-rov-file", required_argument, NULL, 0},
	                                  {"interpolate-position", no_argument, NULL, 0},
	                                  {"interval", required_argument, NULL, 0},
	                                  {"output", required_argument, NULL, 0},
	                                  {"rov-dive-start", required_argument, NULL, 0},
	                                  {"rov-dive-end", required_argument, NULL, 0},
	                                  {"utm-zone", required_argument, NULL, 0},
									  {"verbose", no_argument, NULL, 0},
	                                  {NULL, 0, NULL, 0}};

    /* files */
    mb_path input_root = "";
    mb_path input_nav_file = "";
    mb_path input_ctd_file = "";
    mb_path input_dvl_file = "";
    mb_path input_rov_file = "";
    mb_path output_file = "";

	/* process argument list */
	while ((c = getopt_long(argc, argv, "", options, &option_index)) != -1)
		switch (c) {
		/* long options all return c=0 */
		case 0:
			/* verbose */
			if (strcmp("verbose", options[option_index].name) == 0) {
				verbose++;
			}

			/* help */
			else if (strcmp("help", options[option_index].name) == 0) {
				help = MB_YES;
			}

			/*-------------------------------------------------------
			 * Define input and output files */

			/* input=file */
			else if (strcmp("input", options[option_index].name) == 0) {
				strcpy(input_root, optarg);
				sprintf(input_nav_file, "NAV_%s000000.txt", input_root);
				sprintf(input_ctd_file, "CTD_%s000000.txt", input_root);
				sprintf(input_dvl_file, "DVL_%s000000.txt", input_root);
				sprintf(input_rov_file, "ROV_%s000000.txt", input_root);
				sprintf(output_file, "MiniROV_nav_%s.mb165", input_root);
			}

			/* input-ctd=file */
			else if (strcmp("input-ctd-file", options[option_index].name) == 0) {
				strcpy(input_ctd_file, optarg);
			}

			/* input-dvl=file */
			else if (strcmp("input-dvl-file", options[option_index].name) == 0) {
				strcpy(input_dvl_file, optarg);
			}

			/* input-nav=file */
			else if (strcmp("input-nav-file", options[option_index].name) == 0) {
				strcpy(input_nav_file, optarg);
			}

			/* input-rov=file */
			else if (strcmp("input-rov-file", options[option_index].name) == 0) {
				strcpy(input_rov_file, optarg);
			}

			/* output=file */
			else if (strcmp("output", options[option_index].name) == 0) {
				strcpy(output_file, optarg);
			}

			/* interval */
			else if (strcmp("interval", options[option_index].name) == 0) {
				nscan = sscanf(optarg, "%lf", &interval);
				if (interval <= 0.0) {
					fprintf(stderr,"Program %s command error: %s %s\n\toutput interval reset to 1.0 seconds\n",
							program_name, options[option_index].name, optarg);
					
				}
			}

			/* start rov dive time */
			else if (strcmp("rov-dive-start", options[option_index].name) == 0) {
				nscan = sscanf(optarg, "%d/%d/%d/%d/%d/%d", &rov_dive_start_time_i[0],
					   &rov_dive_start_time_i[1], &rov_dive_start_time_i[2],
					   &rov_dive_start_time_i[3], &rov_dive_start_time_i[4],
					   &rov_dive_start_time_i[5]);
				if (nscan == 6) {
					rov_dive_start_time_i[6] = 0;
					mb_get_time(verbose, rov_dive_start_time_i, &rov_dive_start_time_d);
					rov_dive_start_time_set = MB_YES;
				}
				else {
					fprintf(stderr,"Program %s command error: %s %s\n",
							program_name, options[option_index].name, optarg);
				}
			}

			/* end rov dive time */
			else if (strcmp("rov-dive-end", options[option_index].name) == 0) {
				nscan = sscanf(optarg, "%d/%d/%d/%d/%d/%d", &rov_dive_end_time_i[0],
					   &rov_dive_end_time_i[1], &rov_dive_end_time_i[2],
					   &rov_dive_end_time_i[3], &rov_dive_end_time_i[4],
					   &rov_dive_end_time_i[5]);
				if (nscan == 6) {
					rov_dive_end_time_i[6] = 0;
					mb_get_time(verbose, rov_dive_end_time_i, &rov_dive_end_time_d);
					rov_dive_end_time_set = MB_YES;
				}
				else {
					fprintf(stderr,"Program %s command error: %s %s\n",
							program_name, options[option_index].name, optarg);
				}
			}

			/* utm zone */
			else if (strcmp("utm-zone", options[option_index].name) == 0) {
				nscan = sscanf(optarg, "%d/%c", &utm_zone, &NorS);
				if (nscan < 2)
					nscan = sscanf(optarg, "%d%c", &utm_zone, &NorS);
				if (nscan == 2) {
					utm_zone_set = MB_YES;
					if (NorS == 'N' || NorS == 'n')
						sprintf(projection_id, "UTM%2.2dN", utm_zone);
					else if (NorS == 'S' || NorS == 's')
						sprintf(projection_id, "UTM%2.2dS", utm_zone);
					else
						sprintf(projection_id, "UTM%2.2dN", utm_zone);
				}
				else {
					fprintf(stderr,"Program %s command error: %s %s\n",
							program_name, options[option_index].name, optarg);
				}
			}

			/* interpolate position over gaps in USBL fixes (rather than repeat position values) */
			else if (strcmp("interpolate-position", options[option_index].name) == 0) {
				interpolate_position = MB_YES;
			}

			/*----------------------------------------------------------------*/

			break;
		case '?':
			errflg++;
			break;
		}

	/* if error flagged then print it and exit */
	if (errflg) {
		fprintf(stderr, "usage: %s\n", usage_message);
		fprintf(stderr, "\nProgram <%s> Terminated\n", program_name);
		error = MB_ERROR_BAD_USAGE;
		exit(error);
	}

	/* print starting message */
	if (verbose == 1 || help) {
		fprintf(stderr, "\nProgram %s\n", program_name);
		fprintf(stderr, "Source File Version %s\n", version_id);
		fprintf(stderr, "MB-system Version %s\n", MB_VERSION);
	}

	/* print starting debug statements */
	if (verbose >= 2) {
		fprintf(stderr, "\ndbg2  Program <%s>\n", program_name);
		fprintf(stderr, "dbg2  Version %s\n", version_id);
		fprintf(stderr, "dbg2  MB-system Version %s\n", MB_VERSION);
		fprintf(stderr, "dbg2  Control Parameters:\n");
		fprintf(stderr, "dbg2       verbose:                      %d\n", verbose);
		fprintf(stderr, "dbg2       help:                         %d\n", help);
		fprintf(stderr, "dbg2       input_root:                   %s\n", input_root);
		fprintf(stderr, "dbg2       input_nav_file:               %s\n", input_nav_file);
		fprintf(stderr, "dbg2       input_ctd_file:               %s\n", input_ctd_file);
		fprintf(stderr, "dbg2       input_dvl_file:               %s\n", input_dvl_file);
		fprintf(stderr, "dbg2       input_rov_file:               %s\n", input_rov_file);
		fprintf(stderr, "dbg2       output_file:                  %s\n", output_file);
		fprintf(stderr, "dbg2       output time interval:         %f\n", interval);
		fprintf(stderr, "dbg2       rov_dive_start_time_set:      %d\n", rov_dive_start_time_set);
		if (rov_dive_start_time_set == MB_YES)
			fprintf(stderr, "dbg2       rov_dive_start_time_i:        %4.4d/%2.2d/%2.2d %2.2d:%2.2d:%2.2d.%6.6d\n",
					rov_dive_start_time_i[0], rov_dive_start_time_i[1], rov_dive_start_time_i[2],
					rov_dive_start_time_i[3], rov_dive_start_time_i[4], rov_dive_start_time_i[5],
					rov_dive_start_time_i[6]);
		fprintf(stderr, "dbg2       rov_dive_end_time_set:        %d\n", rov_dive_end_time_set);
		if (rov_dive_end_time_set == MB_YES)
			fprintf(stderr, "dbg2       rov_dive_end_time_i:          %4.4d/%2.2d/%2.2d %2.2d:%2.2d:%2.2d.%6.6d\n",
					rov_dive_end_time_i[0], rov_dive_end_time_i[1], rov_dive_end_time_i[2],
					rov_dive_end_time_i[3], rov_dive_end_time_i[4], rov_dive_end_time_i[5],
					rov_dive_end_time_i[6]);
		fprintf(stderr, "dbg2       utm_zone_set:                 %d\n", utm_zone_set);
		if (utm_zone_set == MB_YES) {
			fprintf(stderr, "dbg2       utm_zone:                     %d\n", utm_zone);
			fprintf(stderr, "dbg2       projection_id:                %s\n", projection_id);
		}
		fprintf(stderr, "dbg2       interpolate_position:         %d\n", interpolate_position);
	}

	/* print starting verbose */
	else if (verbose > 0) {
		fprintf(stderr, "\nProgram <%s>\n", program_name);
		fprintf(stderr, "Version %s\n", version_id);
		fprintf(stderr, "MB-system Version %s\n", MB_VERSION);
		fprintf(stderr, "Control Parameters:\n");
		fprintf(stderr, "     verbose:                      %d\n", verbose);
		fprintf(stderr, "     help:                         %d\n", help);
		fprintf(stderr, "     input_root:                   %s\n", input_root);
		fprintf(stderr, "     input_nav_file:               %s\n", input_nav_file);
		fprintf(stderr, "     input_ctd_file:               %s\n", input_ctd_file);
		fprintf(stderr, "     input_dvl_file:               %s\n", input_dvl_file);
		fprintf(stderr, "     input_rov_file:               %s\n", input_rov_file);
		fprintf(stderr, "     output_file:                  %s\n", output_file);
		fprintf(stderr, "     output time interval:         %f\n", interval);
		fprintf(stderr, "     rov_dive_start_time_set:      %d\n", rov_dive_start_time_set);
		if (rov_dive_start_time_set == MB_YES)
			fprintf(stderr, "     rov_dive_start_time_i:        %4.4d/%2.2d/%2.2d %2.2d:%2.2d:%2.2d.%6.6d\n",
					rov_dive_start_time_i[0], rov_dive_start_time_i[1], rov_dive_start_time_i[2],
					rov_dive_start_time_i[3], rov_dive_start_time_i[4], rov_dive_start_time_i[5],
					rov_dive_start_time_i[6]);
		fprintf(stderr, "     rov_dive_end_time_set:        %d\n", rov_dive_end_time_set);
		if (rov_dive_end_time_set == MB_YES)
			fprintf(stderr, "     rov_dive_end_time_i:          %4.4d/%2.2d/%2.2d %2.2d:%2.2d:%2.2d.%6.6d\n",
					rov_dive_end_time_i[0], rov_dive_end_time_i[1], rov_dive_end_time_i[2],
					rov_dive_end_time_i[3], rov_dive_end_time_i[4], rov_dive_end_time_i[5],
					rov_dive_end_time_i[6]);
		fprintf(stderr, "     utm_zone_set:                 %d\n", utm_zone_set);
		if (utm_zone_set == MB_YES) {
			fprintf(stderr, "     utm_zone:                     %d\n", utm_zone);
			fprintf(stderr, "     projection_id:                %s\n", projection_id);
		}
		fprintf(stderr, "     interpolate_position:         %d\n", interpolate_position);
	}

	/* if help desired then print it and exit */
	if (help) {
		fprintf(stderr, "\n%s\n", help_message);
		fprintf(stderr, "\nusage: %s\n", usage_message);
		exit(error);
	}

	/*-------------------------------------------------------------------*/
	/* load input nav data */

	/* count the records */
	error = MB_ERROR_NO_ERROR;
	nrecord = 0;
	nchar = MB_PATH_MAXLINE - 1;
	if ((fp = fopen(input_nav_file, "r")) != NULL) {
		/* loop over reading the records */
		while ((result = fgets(buffer, nchar, fp)) == buffer)
			if (buffer[0] != '#' && strlen(buffer) > 5)
				nrecord++;

		/* close the file */
		fclose(fp);
		fp = NULL;
	}
	else {
		error = MB_ERROR_OPEN_FAIL;
		status = MB_FAILURE;
	}

	/* allocate memory if necessary */
	if (status == MB_SUCCESS && num_nav_alloc < nrecord) {
		size = nrecord * sizeof(double);
		status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&nav_time_d, &error);
		if (status == MB_SUCCESS)
			status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&nav_lon, &error);
		if (status == MB_SUCCESS)
			status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&nav_lat, &error);
		if (status == MB_SUCCESS)
			num_nav_alloc = nrecord;
	}

	/* read the records */
	if (status == MB_SUCCESS) {
		nrecord = 0;
		if ((fp = fopen(input_nav_file, "r")) == NULL) {
			error = MB_ERROR_OPEN_FAIL;
			status = MB_FAILURE;
		}
		else {
			/* loop over reading the records - handle the different formats */
			while ((result = fgets(buffer, nchar, fp)) == buffer) {
				nget = sscanf(buffer, "%lf,$GPGLL,%lf,%c,%lf,%c,%lf,%s",
							  &time_d, &rawlat, &NorS, &rawlon, &EorW, &dummydouble, dummystring);
				if (nget == 7) {
					if (start_time_d <= 0.0)
						start_time_d = time_d;
					if (time_d > 0.0 && time_d < start_time_d)
						start_time_d = time_d;
					if (time_d > end_time_d)
						end_time_d = time_d;
						
					nav_time_d[num_nav] = time_d;
					ldegrees = floor(rawlat / 100.0);
					lminutes = rawlat - ldegrees * 100;
					nav_lat[num_nav] = ldegrees + (lminutes / 60.0);
					if (NorS == 'S')
						nav_lat[num_nav] *= -1;
					ldegrees = floor(rawlon / 100.0);
					lminutes = rawlon - ldegrees * 100;
					nav_lon[num_nav] = ldegrees + (lminutes / 60.0);
					if (EorW == 'W')
						nav_lon[num_nav] *= -1;
					
					if (interpolate_position == MB_NO
						|| num_nav <= 1
						|| nav_lon[num_nav] != nav_lon[num_nav-1]
						|| nav_lat[num_nav] != nav_lat[num_nav-1]) {
						reference_lon += nav_lon[num_nav];
						reference_lat += nav_lat[num_nav];
						if (num_nav < num_nav_alloc)
							num_nav++;
					}
						
					
				}
			}

			/* close the file */
			fclose(fp);
			
			/* calculate average longitude for UTM zone calcuation */
			if (num_nav > 0) {
				reference_lon /= num_nav;
				reference_lat /= num_nav;
			}
			if (reference_lon < 180.0)
				reference_lon += 360.0;
			if (reference_lon >= 180.0)
				reference_lon -= 360.0;
		}
	}

	/*-------------------------------------------------------------------*/
	/* load input ctd data */

	/* count the records */
	error = MB_ERROR_NO_ERROR;
	nrecord = 0;
	nchar = MB_PATH_MAXLINE - 1;
	if ((fp = fopen(input_ctd_file, "r")) != NULL) {
		/* loop over reading the records */
		while ((result = fgets(buffer, nchar, fp)) == buffer)
			if (buffer[0] != '#' && strlen(buffer) > 5)
				nrecord++;

		/* close the file */
		fclose(fp);
		fp = NULL;
	}
	else {
		error = MB_ERROR_OPEN_FAIL;
		status = MB_FAILURE;
	}

	/* allocate memory if necessary */
	if (status == MB_SUCCESS && num_ctd_alloc < nrecord) {
		size = nrecord * sizeof(double);
		status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&ctd_time_d, &error);
		if (status == MB_SUCCESS)
			status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&ctd_depth, &error);
		if (status == MB_SUCCESS)
			num_ctd_alloc = nrecord;
	}

	/* read the records */
	if (status == MB_SUCCESS) {
		nrecord = 0;
		if ((fp = fopen(input_ctd_file, "r")) == NULL) {
			error = MB_ERROR_OPEN_FAIL;
			status = MB_FAILURE;
		}
		else {
			/* loop over reading the records - handle the different formats */
			while ((result = fgets(buffer, nchar, fp)) == buffer) {
				nget = sscanf(buffer, "%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf",
							  &time_d, &ctd_C, &ctd_T, &ctd_D, &ctd_S,
							  &ctd_O2uM, &ctd_O2raw, &ctd_DGH_T, &ctd_C2_T, &ctd_C2_C);
				if (nget == 10) {
					if (start_time_d <= 0.0)
						start_time_d = time_d;
					if (time_d > 0.0 && time_d < start_time_d)
						start_time_d = time_d;
					if (time_d > end_time_d)
						end_time_d = time_d;
						
					ctd_time_d[num_ctd] = time_d;
					ctd_depth[num_ctd] = ctd_D;
					if (num_ctd < num_ctd_alloc)
						num_ctd++;
					}
				}

			/* close the file */
			fclose(fp);
		}
	}

	/*-------------------------------------------------------------------*/
	/* load input rov data */

	/* count the records */
	error = MB_ERROR_NO_ERROR;
	nrecord = 0;
	nchar = MB_PATH_MAXLINE - 1;
	if ((fp = fopen(input_rov_file, "r")) != NULL) {
		/* loop over reading the records */
		while ((result = fgets(buffer, nchar, fp)) == buffer)
			if (buffer[0] != '#' && strlen(buffer) > 5)
				nrecord++;

		/* close the file */
		fclose(fp);
		fp = NULL;
	}
	else {
		error = MB_ERROR_OPEN_FAIL;
		status = MB_FAILURE;
	}

	/* allocate memory if necessary */
	if (status == MB_SUCCESS && num_rov_alloc < nrecord) {
		size = nrecord * sizeof(double);
		status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&rov_time_d, &error);
		if (status == MB_SUCCESS)
			status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&rov_heading, &error);
		if (status == MB_SUCCESS)
			status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&rov_roll, &error);
		if (status == MB_SUCCESS)
			status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&rov_pitch, &error);
		if (status == MB_SUCCESS)
			num_rov_alloc = nrecord;
	}

	/* read the records */
	if (status == MB_SUCCESS) {
		nrecord = 0;
		if ((fp = fopen(input_rov_file, "r")) == NULL) {
			error = MB_ERROR_OPEN_FAIL;
			status = MB_FAILURE;
		}
		else {
			/* loop over reading the records - handle the different formats */
			while ((result = fgets(buffer, nchar, fp)) == buffer) {
				nget = sscanf(buffer, "%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf",
							  &time_d, &rov_x, &rov_y, &rov_z, &rov_yaw, &rov_magna_amps,
							  &rov_F1, &rov_F2, &rov_F3, &rov_F4, &rov_F5,
							  &rov_Heading, &rov_Pitch, &rov_Roll);
				if (nget == 14) {
					if (start_time_d <= 0.0)
						start_time_d = time_d;
					if (time_d > 0.0 && time_d < start_time_d)
						start_time_d = time_d;
					if (time_d > end_time_d)
						end_time_d = time_d;
						
					rov_time_d[num_rov] = time_d;
					rov_heading[num_rov] = rov_Heading;
					rov_roll[num_rov] = rov_Roll;
					rov_pitch[num_rov] = rov_Pitch;
					if (num_rov < num_rov_alloc)
						num_rov++;
					}
				}

			/* close the file */
			fclose(fp);
		}
	}

	/*-------------------------------------------------------------------*/
	/* load input dvl data */

	/* count the records */
	error = MB_ERROR_NO_ERROR;
	nrecord = 0;
	nchar = MB_PATH_MAXLINE - 1;
	if ((fp = fopen(input_dvl_file, "r")) != NULL) {
		/* loop over reading the records */
		while ((result = fgets(buffer, nchar, fp)) == buffer)
			if (buffer[0] != '#' && strlen(buffer) > 5)
				nrecord++;

		/* close the file */
		fclose(fp);
		fp = NULL;
	}
	else {
		error = MB_ERROR_OPEN_FAIL;
		status = MB_FAILURE;
	}

	/* allocate memory if necessary */
	if (status == MB_SUCCESS && num_dvl_alloc < nrecord) {
		size = nrecord * sizeof(double);
		status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&dvl_time_d, &error);
		if (status == MB_SUCCESS)
			status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&dvl_altitude, &error);
		if (status == MB_SUCCESS)
			status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&dvl_stime, &error);
		if (status == MB_SUCCESS)
			status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&dvl_vx, &error);
		if (status == MB_SUCCESS)
			status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&dvl_vy, &error);
		if (status == MB_SUCCESS)
			status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&dvl_vz, &error);
		if (status == MB_SUCCESS)
			status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&dvl_status, &error);
		if (status == MB_SUCCESS)
			num_dvl_alloc = nrecord;
	}

	/* read the records */
	if (status == MB_SUCCESS) {
		nrecord = 0;
		if ((fp = fopen(input_dvl_file, "r")) == NULL) {
			error = MB_ERROR_OPEN_FAIL;
			status = MB_FAILURE;
		}
		else {
			/* loop over reading the records - handle the different formats */
			while ((result = fgets(buffer, nchar, fp)) == buffer) {
				nget = sscanf(buffer, "%lf,%lf,%lf,%lf,%lf,%lf,%lf",
							  &time_d, &dvl_Altitude, &dvl_Stime, &dvl_Vx, &dvl_Vy, &dvl_Vz, &dvl_Status);
				if (nget == 7) {
					if (start_time_d <= 0.0)
						start_time_d = time_d;
					if (time_d > 0.0 && time_d < start_time_d)
						start_time_d = time_d;
					if (time_d > end_time_d)
						end_time_d = time_d;
						
					dvl_time_d[num_dvl] = time_d;
					dvl_altitude[num_dvl] = dvl_Altitude;
					dvl_stime[num_dvl] = dvl_Stime;
					dvl_vx[num_dvl] = dvl_Vx;
					dvl_vy[num_dvl] = dvl_Vy;
					dvl_vz[num_dvl] = dvl_Vz;
					dvl_status[num_dvl] = dvl_Status;
					if (num_dvl < num_dvl_alloc)
						num_dvl++;
					}
				}

			/* close the file */
			fclose(fp);
		}
	}
	/*-------------------------------------------------------------------*/
	
	fprintf(stderr,"\nProgram %s\n", program_name);
	fprintf(stderr,"Input data loaded:\n\tNavigation: %d\n\tCTD: %d\n\tAttitude:%d\n\tDVL: %d\n\n",
			num_nav, num_ctd, num_rov, num_dvl);
	
	/* get time range of output based on max bounds of any input data
		or use the specified time interval */
	if (rov_dive_start_time_set == MB_YES) {
		start_time_d = rov_dive_start_time_d;
	}
	if (rov_dive_end_time_set == MB_YES) {
		end_time_d = rov_dive_end_time_d;
	}
	start_time_d = floor(start_time_d);
	num_output = (int)(ceil((end_time_d - start_time_d) / interval));
	
	/* get UTM projection for easting and northing fields */
	if (utm_zone_set == MB_YES) {
		if (utm_zone < 0)
			sprintf(projection_id, "UTM%2.2dS", abs(utm_zone));
		else
			sprintf(projection_id, "UTM%2.2dN", utm_zone);
	}
	else {
		utm_zone = (int)(((reference_lon + 183.0) / 6.0) + 0.5);
		if (reference_lat >= 0.0)
			sprintf(projection_id, "UTM%2.2dN", utm_zone);
		else
			sprintf(projection_id, "UTM%2.2dS", utm_zone);
	}
	proj_status = mb_proj_init(verbose, projection_id, &(pjptr), &error);

	/* write the MiniROV navigation data */
	if (status == MB_SUCCESS) {
		if ((fp = fopen(output_file, "w")) == NULL) {
			error = MB_ERROR_OPEN_FAIL;
			status = MB_FAILURE;
		}
		else {
			/* loop over 1 second intervals from start time to end time */
			for (ioutput=0;ioutput<num_output;ioutput++) {
				
				/* set the output time */
				onav_time_d = start_time_d + ioutput * interval;
				mb_get_date(verbose, onav_time_d, onav_time_i);
				onav_year = onav_time_i[0];
				onav_timetag = 10000 * onav_time_i[3] + 100 * onav_time_i[4] + onav_time_i[5];
				mb_get_jtime(verbose, onav_time_i, onav_time_j);
				onav_jday = onav_time_j[1];
				
				/* interpolate values onto the target time */
				interp_status = mb_linear_interp_longitude(verbose, nav_time_d - 1, nav_lon - 1, num_nav, onav_time_d, &onav_lon, &jnav, &interp_error);
				interp_status = mb_linear_interp_latitude(verbose, nav_time_d - 1, nav_lat - 1, num_nav, onav_time_d, &onav_lat, &jnav, &interp_error);
				interp_status = mb_linear_interp(verbose, ctd_time_d - 1, ctd_depth - 1, num_ctd, onav_time_d, &onav_depth, &jctd, &interp_error);
				interp_status = mb_linear_interp(verbose, dvl_time_d - 1, dvl_altitude - 1, num_dvl, onav_time_d, &onav_altitude, &jdvl, &interp_error);
				interp_status = mb_linear_interp_heading(verbose, rov_time_d - 1, rov_heading - 1, num_rov, onav_time_d, &onav_heading, &jrov, &interp_error);
				interp_status = mb_linear_interp(verbose, rov_time_d - 1, rov_roll - 1, num_rov, onav_time_d, &onav_roll, &jrov, &interp_error);
				interp_status = mb_linear_interp(verbose, rov_time_d - 1, rov_pitch - 1, num_rov, onav_time_d, &onav_pitch, &jrov, &interp_error);
				
				if (onav_lon != 0.0 && onav_lat != 0.0)
					onav_position_flag = MB_YES;
				else
					onav_position_flag = MB_NO;
				if (onav_lon != 0.0 && onav_lat != 0.0)
					onav_pressure_flag = MB_YES;
				else
					onav_pressure_flag = MB_NO;
				if (onav_lon != 0.0 && onav_lat != 0.0)
					onav_heading_flag = MB_YES;
				else
					onav_heading_flag = MB_NO;
				if (onav_lon != 0.0 && onav_lat != 0.0)
					onav_altitude_flag = MB_YES;
				else
					onav_altitude_flag = MB_NO;
				if (onav_lon != 0.0 && onav_lat != 0.0)
					onav_attitude_flag = MB_YES;
				else
					onav_attitude_flag = MB_NO;
				
				/* get UTM eastings and northings */
				mb_proj_forward(verbose, pjptr, onav_lon, onav_lat, &onav_easting, &onav_northing, &error);

				/* get pressure from CTD depth */
				onav_pressure = onav_depth * (1.0052405 * (1 + 5.28E-3 * sin(DTR * onav_lat) * sin(DTR * onav_lat)));
		
				/* print output debug statements */
				if (verbose >= 4) {
					fprintf(stderr, "\ndbg4  Data to be written in MBIO function <%s>\n", program_name);
					fprintf(stderr, "dbg4  Values,read:\n");
					fprintf(stderr, "dbg4       onav_time_d:         %f\n", onav_time_d);
					fprintf(stderr, "dbg4       onav_lat:            %f\n", onav_lat);
					fprintf(stderr, "dbg4       onav_lon:            %f\n", onav_lon);
					fprintf(stderr, "dbg4       onav_easting:        %f\n", onav_easting);
					fprintf(stderr, "dbg4       onav_northing:       %f\n", onav_northing);
					fprintf(stderr, "dbg4       onav_depth:          %f\n", onav_depth);
					fprintf(stderr, "dbg4       onav_pressure:       %f\n", onav_pressure);
					fprintf(stderr, "dbg4       onav_heading:        %f\n", onav_heading);
					fprintf(stderr, "dbg4       onav_altitude:       %f\n", onav_altitude);
					fprintf(stderr, "dbg4       onav_pitch:          %f\n", onav_pitch);
					fprintf(stderr, "dbg4       onav_roll:           %f\n", onav_roll);
					fprintf(stderr, "dbg4       onav_position_flag:  %d\n", onav_position_flag);
					fprintf(stderr, "dbg4       onav_pressure_flag:  %d\n", onav_pressure_flag);
					fprintf(stderr, "dbg4       onav_heading_flag:   %d\n", onav_heading_flag);
					fprintf(stderr, "dbg4       onav_altitude_flag:  %d\n", onav_altitude_flag);
					fprintf(stderr, "dbg4       onav_attitude_flag:  %d\n", onav_attitude_flag);
					fprintf(stderr, "dbg4       error:               %d\n", error);
					fprintf(stderr, "dbg4       status:              %d\n", status);
				}
				
				/* write the record */
				fprintf(fp, "%4.4d,%3.3d,%6.6d,%9.0f,%10.6f,%11.6f,%7.0f,%7.0f,%7.2f,%5.1f,%6.2f,%4.1f,%4.1f,%d,%d,%d,%d,%d\n",
						onav_year, onav_jday, onav_timetag, onav_time_d,
						onav_lat, onav_lon, onav_easting, onav_northing,
						onav_pressure, onav_heading, onav_altitude, onav_pitch, onav_roll,
						onav_position_flag, onav_pressure_flag, onav_heading_flag,
						onav_altitude_flag, onav_attitude_flag);
				
			}

			/* close the file */
			fclose(fp);
		}
	}
	
	/*-------------------------------------------------------------------*/
	
	proj_status = mb_proj_free(verbose, &(pjptr), &error);
	mb_freed(verbose, __FILE__, __LINE__, (void **)&nav_time_d, &error);
	mb_freed(verbose, __FILE__, __LINE__, (void **)&nav_lon, &error);
	mb_freed(verbose, __FILE__, __LINE__, (void **)&nav_lat, &error);
	mb_freed(verbose, __FILE__, __LINE__, (void **)&ctd_time_d, &error);
	mb_freed(verbose, __FILE__, __LINE__, (void **)&ctd_depth, &error);
	mb_freed(verbose, __FILE__, __LINE__, (void **)&rov_time_d, &error);
	mb_freed(verbose, __FILE__, __LINE__, (void **)&rov_heading, &error);
	mb_freed(verbose, __FILE__, __LINE__, (void **)&rov_roll, &error);
	mb_freed(verbose, __FILE__, __LINE__, (void **)&rov_pitch, &error);
	mb_freed(verbose, __FILE__, __LINE__, (void **)&dvl_time_d, &error);
	mb_freed(verbose, __FILE__, __LINE__, (void **)&dvl_altitude, &error);
	mb_freed(verbose, __FILE__, __LINE__, (void **)&dvl_stime, &error);
	mb_freed(verbose, __FILE__, __LINE__, (void **)&dvl_vx, &error);
	mb_freed(verbose, __FILE__, __LINE__, (void **)&dvl_vy, &error);
	mb_freed(verbose, __FILE__, __LINE__, (void **)&dvl_vz, &error);
	mb_freed(verbose, __FILE__, __LINE__, (void **)&dvl_status, &error);
	
	exit(0);
	
	/*-------------------------------------------------------------------*/

}
Пример #15
0
int main (int argc, char **argv)
{
	char program_name[] = "MBauvloglist";
	char help_message[] =  "MBauvloglist lists table data from an MBARI AUV mission log file.";
	char usage_message[] = "MBauvloglist -Ifile [-Fprintformat -Llonflip -Olist -H -V]";
	extern char *optarg;
	int	errflg = 0;
	int	c;
	int	help = 0;
	int	flag = 0;

	/* MBIO status variables */
	int	status = MB_SUCCESS;
	int	verbose = 0;
	int	error = MB_ERROR_NO_ERROR;
	char	*message = NULL;

	/* MBIO read control parameters */
	int	pings;
	int	format;
	int	lonflip;
	double	bounds[4];
	int	btime_i[7];
	int	etime_i[7];
	double	speedmin;
	double	timegap;

	/* auv log data */
	FILE	*fp;
	char	file[MB_PATH_MAXLINE];
	struct	field
		{
		int	type;
		int	size;
		int	index;
		char	name[MB_PATH_MAXLINE];
		char	format[MB_PATH_MAXLINE];
		char	description[MB_PATH_MAXLINE];
		char	units[MB_PATH_MAXLINE];
		double	scale;
		};
	struct	printfield
		{
		char	name[MB_PATH_MAXLINE];
		int	index;
		int	formatset;
		char	format[MB_PATH_MAXLINE];
		};
	int	nfields = 0;
	struct field fields[NFIELDSMAX];
	int	nprintfields = 0;
	struct printfield printfields[NFIELDSMAX];
	int	nrecord;
	int	recordsize;
	int	printheader = MB_NO;
	int	angles_in_degrees = MB_NO;

	/* navigation, heading, attitude data for merging in fnv format */
	int	nav_merge = MB_NO;
	mb_path	nav_file;
	int	nav_num = 0;
	int	nav_alloc = 0;
	double	*nav_time_d = NULL;
	double	*nav_navlon = NULL;
	double	*nav_navlat = NULL;
	double	*nav_heading = NULL;
	double	*nav_speed = NULL;
	double	*nav_sensordepth = NULL;
	double	*nav_roll = NULL;
	double	*nav_pitch = NULL;
	double	*nav_heave = NULL;
	
	/* output control */
	int	output_mode = OUTPUT_MODE_TAB;

	double	time_d = 0.0;
	int	time_i[7];
	int	time_j[5];
	char	buffer[MB_PATH_MAXLINE];
	char	type[MB_PATH_MAXLINE];
	char	printformat[MB_PATH_MAXLINE];
	char	*result;
	int	nscan;
	double	dvalue;
	double	sec;
	int	ivalue;
	int	index;
	int	jinterp = 0;
	int	nchar;
	int	nget;
	int	nav_ok;
	int	interp_status;
	int	i, j;

	/* get current default values */
	status = mb_defaults(verbose,&format,&pings,&lonflip,bounds,
		btime_i,etime_i,&speedmin,&timegap);

	/* set file to null */
	file[0] = '\0';
	nav_file[0] = '\0';
	strcpy(printformat, "default");

	/* process argument list */
	while ((c = getopt(argc, argv, "F:f:I:i:L:l:M:m:N:n:O:o:PpSsVvWwHh")) != -1)
	  switch (c)
		{
		case 'H':
		case 'h':
			help++;
			break;
		case 'V':
		case 'v':
			verbose++;
			break;
		case 'F':
		case 'f':
			sscanf (optarg,"%s", printformat);
			flag++;
			break;
		case 'I':
		case 'i':
			sscanf (optarg,"%s", file);
			flag++;
			break;
		case 'L':
		case 'l':
			sscanf (optarg,"%d", &lonflip);
			flag++;
			break;
		case 'M':
		case 'm':
			sscanf (optarg,"%d", &output_mode);
			flag++;
			break;
		case 'N':
		case 'n':
			sscanf (optarg,"%s", nav_file);
			nav_merge = MB_YES;
			flag++;
			break;
		case 'O':
		case 'o':
			nscan = sscanf (optarg,"%s", printfields[nprintfields].name);
			if (strlen(printformat) > 0 && strcmp(printformat, "default") != 0)
				{
				printfields[nprintfields].formatset = MB_YES;
				strcpy(printfields[nprintfields].format,printformat);
				}
			else
				{
				printfields[nprintfields].formatset = MB_NO;
				strcpy(printfields[nprintfields].format,"");
				}
			printfields[nprintfields].index = -1;
			nprintfields++;
			flag++;
			break;
		case 'P':
		case 'p':
			printheader = MB_YES;
			flag++;
			break;
		case 'S':
		case 's':
			angles_in_degrees = MB_YES;
			flag++;
			break;
		case '?':
			errflg++;
		}

	/* if error flagged then print it and exit */
	if (errflg)
		{
		fprintf(stderr,"usage: %s\n", usage_message);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		error = MB_ERROR_BAD_USAGE;
		exit(error);
		}

	/* print starting message */
	if (verbose == 1 || help)
		{
		fprintf(stderr,"\nProgram %s\n",program_name);
		fprintf(stderr,"Version %s\n",rcs_id);
		fprintf(stderr,"MB-system Version %s\n",MB_VERSION);
		}

	/* print starting debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  Program <%s>\n",program_name);
		fprintf(stderr,"dbg2  Version %s\n",rcs_id);
		fprintf(stderr,"dbg2  MB-system Version %s\n",MB_VERSION);
		fprintf(stderr,"dbg2  Control Parameters:\n");
		fprintf(stderr,"dbg2       verbose:        %d\n",verbose);
		fprintf(stderr,"dbg2       help:           %d\n",help);
		fprintf(stderr,"dbg2       lonflip:        %d\n",lonflip);
		fprintf(stderr,"dbg2       bounds[0]:      %f\n",bounds[0]);
		fprintf(stderr,"dbg2       bounds[1]:      %f\n",bounds[1]);
		fprintf(stderr,"dbg2       bounds[2]:      %f\n",bounds[2]);
		fprintf(stderr,"dbg2       bounds[3]:      %f\n",bounds[3]);
		fprintf(stderr,"dbg2       btime_i[0]:     %d\n",btime_i[0]);
		fprintf(stderr,"dbg2       btime_i[1]:     %d\n",btime_i[1]);
		fprintf(stderr,"dbg2       btime_i[2]:     %d\n",btime_i[2]);
		fprintf(stderr,"dbg2       btime_i[3]:     %d\n",btime_i[3]);
		fprintf(stderr,"dbg2       btime_i[4]:     %d\n",btime_i[4]);
		fprintf(stderr,"dbg2       btime_i[5]:     %d\n",btime_i[5]);
		fprintf(stderr,"dbg2       btime_i[6]:     %d\n",btime_i[6]);
		fprintf(stderr,"dbg2       etime_i[0]:     %d\n",etime_i[0]);
		fprintf(stderr,"dbg2       etime_i[1]:     %d\n",etime_i[1]);
		fprintf(stderr,"dbg2       etime_i[2]:     %d\n",etime_i[2]);
		fprintf(stderr,"dbg2       etime_i[3]:     %d\n",etime_i[3]);
		fprintf(stderr,"dbg2       etime_i[4]:     %d\n",etime_i[4]);
		fprintf(stderr,"dbg2       etime_i[5]:     %d\n",etime_i[5]);
		fprintf(stderr,"dbg2       etime_i[6]:     %d\n",etime_i[6]);
		fprintf(stderr,"dbg2       speedmin:       %f\n",speedmin);
		fprintf(stderr,"dbg2       timegap:        %f\n",timegap);
		fprintf(stderr,"dbg2       file:           %s\n",file);
		fprintf(stderr,"dbg2       nav_file:       %s\n",nav_file);
		fprintf(stderr,"dbg2       output_mode:    %d\n",output_mode);
		fprintf(stderr,"dbg2       printheader:    %d\n",printheader);
		fprintf(stderr,"dbg2       angles_in_degrees:%d\n",angles_in_degrees);
		fprintf(stderr,"dbg2       nprintfields:   %d\n",nprintfields);
		for (i=0;i<nprintfields;i++)
			fprintf(stderr,"dbg2         printfields[%d]:      %s %d %s\n",
						i,printfields[i].name,
						printfields[i].formatset,
						printfields[i].format);
		}

	/* if help desired then print it and exit */
	if (help)
		{
		fprintf(stderr,"\n%s\n",help_message);
		fprintf(stderr,"\nusage: %s\n", usage_message);
		exit(error);
		}

	/* if nav merging to be done get nav */
	if (nav_merge == MB_YES && strlen(nav_file) > 0)
		{
		/* count the data points in the nav file */
		nav_num = 0;
		nchar = MB_PATH_MAXLINE-1;
		if ((fp = fopen(nav_file, "r")) == NULL)
			{
			error = MB_ERROR_OPEN_FAIL;
			fprintf(stderr,"\nUnable to Open Navigation File <%s> for reading\n",nav_file);
			fprintf(stderr,"\nProgram <%s> Terminated\n",
				program_name);
			exit(error);
			}
		while ((result = fgets(buffer,nchar,fp)) == buffer)
			nav_num++;
		fclose(fp);
    
		/* allocate arrays for nav */
		if (nav_num > 0)
			{
			nav_alloc = nav_num;
			status = mb_mallocd(verbose,__FILE__,__LINE__,nav_alloc*sizeof(double),(void **)&nav_time_d,&error);
			status = mb_mallocd(verbose,__FILE__,__LINE__,nav_alloc*sizeof(double),(void **)&nav_navlon,&error);
			status = mb_mallocd(verbose,__FILE__,__LINE__,nav_alloc*sizeof(double),(void **)&nav_navlat,&error);
			status = mb_mallocd(verbose,__FILE__,__LINE__,nav_alloc*sizeof(double),(void **)&nav_heading,&error);
			status = mb_mallocd(verbose,__FILE__,__LINE__,nav_alloc*sizeof(double),(void **)&nav_speed,&error);
			status = mb_mallocd(verbose,__FILE__,__LINE__,nav_alloc*sizeof(double),(void **)&nav_sensordepth,&error);
			status = mb_mallocd(verbose,__FILE__,__LINE__,nav_alloc*sizeof(double),(void **)&nav_roll,&error);
			status = mb_mallocd(verbose,__FILE__,__LINE__,nav_alloc*sizeof(double),(void **)&nav_pitch,&error);
			status = mb_mallocd(verbose,__FILE__,__LINE__,nav_alloc*sizeof(double),(void **)&nav_heave,&error);
	
			/* if error initializing memory then quit */
			if (error != MB_ERROR_NO_ERROR)
				{
				mb_error(verbose,error,&message);
				fprintf(stderr,"\nMBIO Error allocating data arrays:\n%s\n",message);
				fprintf(stderr,"\nProgram <%s> Terminated\n",
					program_name);
				exit(error);
				}
			}
    
		/* read the data points in the nav file */
		nav_num = 0;
		if ((fp = fopen(nav_file, "r")) == NULL)
			{
			error = MB_ERROR_OPEN_FAIL;
			fprintf(stderr,"\nUnable to Open navigation File <%s> for reading\n",nav_file);
			fprintf(stderr,"\nProgram <%s> Terminated\n",
				program_name);
			exit(error);
			}
		while ((result = fgets(buffer,nchar,fp)) == buffer)
			{
			nget = sscanf(buffer,"%d %d %d %d %d %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf",
				&time_i[0],&time_i[1],&time_i[2],
				&time_i[3],&time_i[4],&sec,
				&nav_time_d[nav_num],
				&nav_navlon[nav_num],&nav_navlat[nav_num],
				&nav_heading[nav_num],&nav_speed[nav_num],&nav_sensordepth[nav_num],
				&nav_roll[nav_num],&nav_pitch[nav_num],&nav_heave[nav_num]);
			if (nget >= 9)
				nav_ok = MB_YES;
			else
				nav_ok = MB_NO;
                        if (nav_num > 0 && nav_time_d[nav_num] <= nav_time_d[nav_num-1])
                                nav_ok = MB_NO;
			if (nav_ok == MB_YES)
			    nav_num++;
			}
		fclose(fp);
 		}
fprintf(stderr,"%d %d records read from nav file %s\n",nav_alloc,nav_num,nav_file);
		
	/* open the input file */
	if ((fp = fopen(file, "r")) == NULL)
		{
		error = MB_ERROR_OPEN_FAIL;
		status = MB_FAILURE;
		fprintf(stderr,"\nUnable to open log file <%s> for reading\n",file);
		exit(status);
		}

	nfields = 0;
	recordsize = 0;
	while ((result = fgets(buffer,MB_PATH_MAXLINE,fp)) == buffer
		&& strncmp(buffer, "# begin",7) != 0)
		{
		nscan = sscanf(buffer, "# %s %s %s",
				type,
				fields[nfields].name,
				fields[nfields].format);
		if (nscan == 2)
			{
			if (printheader == MB_YES)
				fprintf(stdout,"# csv %s\n",  fields[nfields].name);
			}

		else if (nscan == 3)
			{
			if (printheader == MB_YES)
				fprintf(stdout,"%s",buffer);

			result = (char *) strchr(buffer, ',');
			strcpy(fields[nfields].description, &(result[1]));
			result = (char *) strchr(fields[nfields].description, ',');
			result[0] = 0;
			result = (char *) strrchr(buffer, ',');
			strcpy(fields[nfields].units, &(result[1]));

			fields[nfields].index = recordsize;
			if (strcmp(type, "double") == 0)
				{
				fields[nfields].type = TYPE_DOUBLE;
				fields[nfields].size = 8;
				if (angles_in_degrees == MB_YES
					&&(strcmp(fields[nfields].name, "mLatK") == 0
						|| strcmp(fields[nfields].name, "mLonK") == 0
						|| strcmp(fields[nfields].name, "mLatK") == 0
						|| strcmp(fields[nfields].name, "mRollK") == 0
						|| strcmp(fields[nfields].name, "mPitchK") == 0
						|| strcmp(fields[nfields].name, "mHeadK") == 0
						|| strcmp(fields[nfields].name, "mYawK") == 0
						|| strcmp(fields[nfields].name, "mLonCB") == 0
						|| strcmp(fields[nfields].name, "mLatCB") == 0
						|| strcmp(fields[nfields].name, "mRollCB") == 0
						|| strcmp(fields[nfields].name, "mPitchCB") == 0
						|| strcmp(fields[nfields].name, "mHeadCB") == 0
						|| strcmp(fields[nfields].name, "mYawCB") == 0))
					fields[nfields].scale = RTD;
				else
					fields[nfields].scale = 1.0;
				recordsize += 8;
				}
			else if (strcmp(type, "integer") == 0)
				{
				fields[nfields].type = TYPE_INTEGER;
				fields[nfields].size = 4;
				fields[nfields].scale = 1.0;
				recordsize += 4;
				}
			else if (strcmp(type, "timeTag") == 0)
				{
				fields[nfields].type = TYPE_TIMETAG;
				fields[nfields].size = 8;
				fields[nfields].scale = 1.0;
				recordsize += 8;
				}
			else if (strcmp(type, "angle") == 0)
				{
				fields[nfields].type = TYPE_ANGLE;
				fields[nfields].size = 8;
				if (angles_in_degrees == MB_YES
					&&(strcmp(fields[nfields].name, "mRollCB") == 0
						|| strcmp(fields[nfields].name, "mOmega_xCB") == 0
						|| strcmp(fields[nfields].name, "mPitchCB") == 0
						|| strcmp(fields[nfields].name, "mOmega_yCB") == 0
						|| strcmp(fields[nfields].name, "mYawCB") == 0
						|| strcmp(fields[nfields].name, "mOmega_zCB") == 0))
					fields[nfields].scale = RTD;
				else
					fields[nfields].scale = 1.0;
				recordsize += 8;
				}
			nfields++;
			}
		}

	/* end here if asked only to print header */
	if (nprintfields == 0 && printheader == MB_YES)
		exit(error);

	/* by default print everything */
	if (nprintfields == 0)
		{
		nprintfields = nfields;
		for (i=0;i<nfields;i++)
			{
			strcpy(printfields[i].name, fields[i].name);
			printfields[i].index = i;
			printfields[i].formatset = MB_NO;
			strcpy(printfields[i].format, fields[i].format);
			}
		}

	/* check the fields to be printed */
	for (i=0;i<nprintfields;i++)
		{
		if (strcmp(printfields[i].name,"zero") == 0)
			{
			printfields[i].index = INDEX_ZERO;
			if (printfields[i].formatset == MB_NO)
				{
				strcpy(printfields[i].format, "%f");
				}
			}
		else if (strcmp(printfields[i].name,"timeTag") == 0)
			{
			printfields[i].index = INDEX_ZERO;
			if (printfields[i].formatset == MB_NO)
				{
				strcpy(printfields[i].format, "%.8f");
				}
			}
		else if (strcmp(printfields[i].name,"mergeLon") == 0)
			{
			printfields[i].index = INDEX_MERGE_LON;
			if (printfields[i].formatset == MB_NO)
				{
				strcpy(printfields[i].format, "%.9f");
				}
			}
		else if (strcmp(printfields[i].name,"mergeLat") == 0)
			{
			printfields[i].index = INDEX_MERGE_LAT;
			if (printfields[i].formatset == MB_NO)
				{
				strcpy(printfields[i].format, "%.9f");
				}
			}
		else if (strcmp(printfields[i].name,"mergeHeading") == 0)
			{
			printfields[i].index = INDEX_MERGE_HEADING;
			if (printfields[i].formatset == MB_NO)
				{
				strcpy(printfields[i].format, "%.3f");
				}
			}
		else if (strcmp(printfields[i].name,"mergeSpeed") == 0)
			{
			printfields[i].index = INDEX_MERGE_SPEED;
			if (printfields[i].formatset == MB_NO)
				{
				strcpy(printfields[i].format, "%.3f");
				}
			}
		else if (strcmp(printfields[i].name,"mergeDraft") == 0)
			{
			printfields[i].index = INDEX_MERGE_SENSORDEPTH;
			if (printfields[i].formatset == MB_NO)
				{
				strcpy(printfields[i].format, "%.3f");
				}
			}
		else if (strcmp(printfields[i].name,"mergeSensordepth") == 0)
			{
			printfields[i].index = INDEX_MERGE_SENSORDEPTH;
			if (printfields[i].formatset == MB_NO)
				{
				strcpy(printfields[i].format, "%.3f");
				}
			}
		else if (strcmp(printfields[i].name,"mergeRoll") == 0)
			{
			printfields[i].index = INDEX_MERGE_ROLL;
			if (printfields[i].formatset == MB_NO)
				{
				strcpy(printfields[i].format, "%.3f");
				}
			}
		else if (strcmp(printfields[i].name,"mergePitch") == 0)
			{
			printfields[i].index = INDEX_MERGE_PITCH;
			if (printfields[i].formatset == MB_NO)
				{
				strcpy(printfields[i].format, "%.3f");
				}
			}
		else if (strcmp(printfields[i].name,"mergeHeave") == 0)
			{
			printfields[i].index = INDEX_MERGE_HEAVE;
			if (printfields[i].formatset == MB_NO)
				{
				strcpy(printfields[i].format, "%.3f");
				}
			}
		else
			{
			for (j=0;j<nfields;j++)
				{
				if (strcmp(printfields[i].name, fields[j].name) == 0)
					printfields[i].index = j;
				}
			if (printfields[i].formatset == MB_NO)
				{
				strcpy(printfields[i].format, fields[printfields[i].index].format);
				}
			}
		}

	/* if verbose print list of print field names */
	if (verbose > 0)
		{
		for (i=0;i<nprintfields;i++)
			{
			if (i == 0)
				fprintf(stdout, "# ");
			fprintf(stdout, "%s", printfields[i].name);
			if (i < nprintfields-1)
				fprintf(stdout, " | ");
			else
				fprintf(stdout, "\n");
			}
		}

	/* read the data records in the auv log file */
	nrecord = 0;
	while (fread(buffer, recordsize, 1, fp) == 1)
		{
		for (i=0;i<nprintfields;i++)
			{
			index = printfields[i].index;
			if (index == INDEX_ZERO)
				{
				dvalue = 0.0;
				if (output_mode == OUTPUT_MODE_BINARY)
					fwrite(&dvalue, sizeof(double), 1, stdout);
				else
					fprintf(stdout, printfields[i].format, dvalue);
				}
			else if (index == INDEX_MERGE_LON)
				{
				interp_status = mb_linear_interp_longitude(verbose,
							nav_time_d-1, nav_navlon-1,
							nav_num, time_d, &dvalue, &jinterp,
							&error);
				if (jinterp < 2 || jinterp > nav_num-2)
					dvalue = 0.0;
				if (output_mode == OUTPUT_MODE_BINARY)
					fwrite(&dvalue, sizeof(double), 1, stdout);
				else
					fprintf(stdout, printfields[i].format, dvalue);
				}
			else if (index == INDEX_MERGE_LAT)
				{
				interp_status = mb_linear_interp_latitude(verbose,
							nav_time_d-1, nav_navlat-1,
							nav_num, time_d, &dvalue, &jinterp,
							&error);
				if (jinterp < 2 || jinterp > nav_num-2)
					dvalue = 0.0;
				if (output_mode == OUTPUT_MODE_BINARY)
					fwrite(&dvalue, sizeof(double), 1, stdout);
				else
					fprintf(stdout, printfields[i].format, dvalue);
				}
			else if (index == INDEX_MERGE_HEADING)
				{
				interp_status = mb_linear_interp_heading(verbose,
							nav_time_d-1, nav_heading-1,
							nav_num, time_d, &dvalue, &jinterp,
							&error);
				if (jinterp < 2 || jinterp > nav_num-2)
					dvalue = 0.0;
				if (output_mode == OUTPUT_MODE_BINARY)
					fwrite(&dvalue, sizeof(double), 1, stdout);
				else
					fprintf(stdout, printfields[i].format, dvalue);
				}
			else if (index == INDEX_MERGE_SPEED)
				{
				interp_status = mb_linear_interp(verbose,
							nav_time_d-1, nav_speed-1,
							nav_num, time_d, &dvalue, &jinterp,
							&error);
				if (jinterp < 2 || jinterp > nav_num-2)
					dvalue = 0.0;
				if (output_mode == OUTPUT_MODE_BINARY)
					fwrite(&dvalue, sizeof(double), 1, stdout);
				else
					fprintf(stdout, printfields[i].format, dvalue);
				}
			else if (index == INDEX_MERGE_SENSORDEPTH)
				{
				interp_status = mb_linear_interp(verbose,
							nav_time_d-1, nav_sensordepth-1,
							nav_num, time_d, &dvalue, &jinterp,
							&error);
				if (jinterp < 2 || jinterp > nav_num-2)
					dvalue = 0.0;
				if (output_mode == OUTPUT_MODE_BINARY)
					fwrite(&dvalue, sizeof(double), 1, stdout);
				else
					fprintf(stdout, printfields[i].format, dvalue);
				}
			else if (index == INDEX_MERGE_ROLL)
				{
				interp_status = mb_linear_interp(verbose,
							nav_time_d-1, nav_roll-1,
							nav_num, time_d, &dvalue, &jinterp,
							&error);
				if (jinterp < 2 || jinterp > nav_num-2)
					dvalue = 0.0;
				if (output_mode == OUTPUT_MODE_BINARY)
					fwrite(&dvalue, sizeof(double), 1, stdout);
				else
					fprintf(stdout, printfields[i].format, dvalue);
				}
			else if (index == INDEX_MERGE_PITCH)
				{
				interp_status = mb_linear_interp(verbose,
							nav_time_d-1, nav_pitch-1,
							nav_num, time_d, &dvalue, &jinterp,
							&error);
				if (jinterp < 2 || jinterp > nav_num-2)
					dvalue = 0.0;
				if (output_mode == OUTPUT_MODE_BINARY)
					fwrite(&dvalue, sizeof(double), 1, stdout);
				else
					fprintf(stdout, printfields[i].format, dvalue);
				}
			else if (index == INDEX_MERGE_HEAVE)
				{
				interp_status = mb_linear_interp(verbose,
							nav_time_d-1, nav_heave-1,
							nav_num, time_d, &dvalue, &jinterp,
							&error);
				if (jinterp < 2 || jinterp > nav_num-2)
					dvalue = 0.0;
				if (output_mode == OUTPUT_MODE_BINARY)
					fwrite(&dvalue, sizeof(double), 1, stdout);
				else
					fprintf(stdout, printfields[i].format, dvalue);
				}
			else if (fields[index].type == TYPE_DOUBLE)
				{
				mb_get_binary_double(MB_YES, &buffer[fields[index].index], &dvalue);
				dvalue *= fields[index].scale;
				if ((strcmp(fields[nfields].name, "mHeadK") == 0
					|| strcmp(fields[nfields].name, "mYawK") == 0)
					&& angles_in_degrees == MB_YES
					&& dvalue < 0.0)
					dvalue += 360.0;
				if (output_mode == OUTPUT_MODE_BINARY)
					fwrite(&dvalue, sizeof(double), 1, stdout);
				else
					fprintf(stdout, printfields[i].format, dvalue);
				}
			else if (fields[index].type == TYPE_INTEGER)
				{
				mb_get_binary_int(MB_YES, &buffer[fields[index].index], &ivalue);
				if (output_mode == OUTPUT_MODE_BINARY)
					fwrite(&ivalue, sizeof(int), 1, stdout);
				else
					fprintf(stdout, printfields[i].format, ivalue);
				}
			else if (fields[index].type == TYPE_TIMETAG)
				{
				mb_get_binary_double(MB_YES, &buffer[fields[index].index], &dvalue);
				time_d = dvalue;
				if (strcmp(printfields[i].format, "time_i") == 0)
					{
					mb_get_date(verbose,time_d,time_i);
					if (output_mode == OUTPUT_MODE_BINARY)
						{
						fwrite(time_i, sizeof(int), 7, stdout);
						}
					else
						{
						fprintf(stdout,"%4.4d %2.2d %2.2d %2.2d %2.2d %2.2d.%6.6d",
							time_i[0],time_i[1],time_i[2],time_i[3],time_i[4],time_i[5],time_i[6]);
						}
					}
				else if (strcmp(printfields[i].format, "time_j") == 0)
					{
					mb_get_date(verbose,time_d,time_i);
					mb_get_jtime(verbose,time_i,time_j);
					if (output_mode == OUTPUT_MODE_BINARY)
						{
						fwrite(&time_i[0], sizeof(int), 1, stdout);
						fwrite(&time_j[1], sizeof(int), 1, stdout);
						fwrite(&time_i[3], sizeof(int), 1, stdout);
						fwrite(&time_i[4], sizeof(int), 1, stdout);
						fwrite(&time_i[5], sizeof(int), 1, stdout);
						fwrite(&time_i[6], sizeof(int), 1, stdout);
						}
					else
						{
						fprintf(stdout,"%4.4d %3.3d %2.2d %2.2d %2.2d.%6.6d",
							time_i[0],time_j[1],time_i[3],time_i[4],time_i[5],time_i[6]);
						}
					}
				else
					{
					if (output_mode == OUTPUT_MODE_BINARY)
						fwrite(&dvalue, sizeof(double), 1, stdout);
					else
						fprintf(stdout, printfields[i].format, time_d);
					}
				}
			else if (fields[index].type == TYPE_ANGLE)
				{
				mb_get_binary_double(MB_YES, &buffer[fields[index].index], &dvalue);
				dvalue *= fields[index].scale;
				if (strcmp(fields[index].name, "mYawCB") == 0
					&& angles_in_degrees == MB_YES
					&& dvalue < 0.0)
					dvalue += 360.0;
				if (output_mode == OUTPUT_MODE_BINARY)
					fwrite(&dvalue, sizeof(double), 1, stdout);
				else
					fprintf(stdout, printfields[i].format, dvalue);
				}
			if (output_mode == OUTPUT_MODE_TAB)
				{
				if (i < nprintfields - 1)
					fprintf(stdout, "\t");
				else
					fprintf(stdout, "\n");
				}
			else if (output_mode == OUTPUT_MODE_CSV)
				{
				if (i < nprintfields - 1)
					fprintf(stdout, ",");
				else
					fprintf(stdout, "\n");
				}
			}
		nrecord++;
		}
	fclose(fp);

	/* deallocate arrays for navigation */
	if (nav_alloc > 0)
		{
		mb_freed(verbose,__FILE__,__LINE__,(void **)&nav_time_d,&error);
		mb_freed(verbose,__FILE__,__LINE__,(void **)&nav_navlon,&error);
		mb_freed(verbose,__FILE__,__LINE__,(void **)&nav_navlat,&error);
		mb_freed(verbose,__FILE__,__LINE__,(void **)&nav_heading,&error);
		mb_freed(verbose,__FILE__,__LINE__,(void **)&nav_speed,&error);
		mb_freed(verbose,__FILE__,__LINE__,(void **)&nav_sensordepth,&error);
		mb_freed(verbose,__FILE__,__LINE__,(void **)&nav_roll,&error);
		mb_freed(verbose,__FILE__,__LINE__,(void **)&nav_pitch,&error);
		mb_freed(verbose,__FILE__,__LINE__,(void **)&nav_heave,&error);
		}

	/* print output debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  Program <%s> completed\n",
			program_name);
		fprintf(stderr,"dbg2  Ending status:\n");
		fprintf(stderr,"dbg2       status:  %d\n",status);
		}

	/* end it all */
	exit(error);
}
Пример #16
0
int main (int argc, char **argv)
{
#ifdef MBCONTOURFILTER
	char program_name[] = "MBCONTOURFILTER";
	char help_message[] =  "MBCONTOURFILTER is a utility which creates a pen plot \ncontour map of multibeam swath bathymetry.  \nThe primary purpose of this program is to serve as \npart of a real-time plotting system.  The contour \nlevels and colors can be controlled \ndirectly or set implicitly using contour and color change intervals. \nContours can also be set to have ticks pointing downhill.";
	char usage_message[] = "mbcontourfilter -Jparameters -Rwest/east/south/north \n\t[-Acontour_int/color_int/tick_int/label_int/tick_len/label_hgt/label_spacing \n\t-Btickinfo -byr/mon/day/hour/min/sec -Ccontourfile \n\t-Dtime_tick/time_annot/date_annot/time_tick_len -Eyr/mon/day/hour/min/sec \n\t-fformat -Fred/green/blue -Idatalist -K -Llonflip -M -O -Nnplot \n\t-P -ppings -Q -Ttimegap -U -Xx-shift -Yy-shift -Zalgorithm -#copies -V -H]";
#else
	char program_name[] = "MBCONTOUR";
	char help_message[] =  "MBCONTOUR is a GMT compatible utility which creates a color postscript \ncontour map of multibeam swath bathymetry.  \nComplete maps are made by using MBCONTOUR in conjunction with the  \nusual GMT programs.  The contour levels and colors can be controlled \ndirectly or set implicitly using contour and color change intervals. \nContours can also be set to have ticks pointing downhill.";
	char usage_message[] = "mbcontour -Jparameters -Rwest/east/south/north \n\t[-Acontour_int/color_int/tick_int/label_int/tick_len/label_hgt/label_spacing \n\t-Btickinfo -byr/mon/day/hour/min/sec -Ccontourfile -ccopies \n\t-Dtime_tick/time_annot/date_annot/time_tick_len \n\t-Eyr/mon/day/hour/min/sec \n\t-fformat -Fred/green/blue -Idatalist -K -Llonflip -Nnplot -O \n\t-P -ppings -U -Xx-shift -Yy-shift -Zalgorithm -V -H]";
#endif

	extern char *optarg;
	int     argc_gmt = 0;
	char    *argv_gmt[MBCONTOUR_GMT_ARG_MAX];
	int	errflg = 0;
	int	c;
	int	help = 0;
	int	flag = 0;

	/* MBIO status variables */
	int	status = MB_SUCCESS;
	int	verbose = 0;
	int	error = MB_ERROR_NO_ERROR;
	char	*message = NULL;

	/* MBIO read control parameters */
	char	read_file[MBCONTOUR_LABEL_LEN];
        int     read_datalist;
	int	read_data;
	void	*datalist;
	int	look_processed = MB_DATALIST_LOOK_UNSET;
	double	file_weight;
	FILE	*fp;
	int	format;
	int	pings;
	int	lonflip;
	int	lonflip_set = MB_NO;
	double	bounds[4];
	double	mb_bounds[4];
	int	btime_i[7];
	int	etime_i[7];
	double	btime_d;
	double	etime_d;
	double	speedmin;
	double	timegap;
	char	file[MB_PATH_MAXLINE];
	int	file_in_bounds;
	int	beams_bath;
	int	beams_amp;
	int	pixels_ss;
	void	*mbio_ptr = NULL;

	/* mbio read values */
	struct swath *swath_plot = NULL;
	struct ping *pingcur = NULL;
	int	kind;
	int	pings_read;
	int	time_i[7];
	double	time_d;
	double	navlon;
	double	navlat;
	double	speed;
	double	heading;
	double	distance;
	double	altitude;
	double	sonardepth;
	char	*beamflag = NULL;
	double	*bath = NULL;
	double	*bathlon = NULL;
	double	*bathlat = NULL;
	double	*amp = NULL;
	double	*ss = NULL;
	double	*sslon = NULL;
	double	*sslat = NULL;
	char	comment[256];
	int	pingnumber;

	/* plot control variables */
	int	contour_algorithm;
	char	contourfile[MB_PATH_MAXLINE];
	int	plot;
	int	done;
	int	flush;
	int	save_new;
	int	*npings = NULL;
	int	nping_read;
	int	nplot;
	int	plot_contours;
	int	plot_triangles;
	int	set_contours;
	double	cont_int;
	double	col_int;
	double	tick_int;
	double	label_int;
	double	tick_len;
	double	label_hgt;
	double	label_spacing;
	double	tick_len_map;
	double	label_hgt_map;
	double	label_spacing_map;
	int 	plot_name;
	int	plotted_name;
	int	plot_track;
	double	time_tick_int;
	double	time_annot_int;
	double	date_annot_int;
	double	time_tick_len;
	double	time_tick_len_map;
	double	name_hgt;
	double	name_hgt_map;
	int	name_perp;
	double	scale;
	int	bathy_in_feet;
	int	plot_pingnumber;
	int	pingnumber_tick_int;
	int	pingnumber_annot_int;
	double	pingnumber_tick_len;
	double	pingnumber_tick_len_map;

	/* pen variables */
	int	ncolor;
	int	nlevel;
	double	*level = NULL;
	int	*red = NULL;
	int	*green = NULL;
	int	*blue = NULL;
	int	*label = NULL;
	int	*tick = NULL;

	/* inch to map scale */
	double	inchtolon;

	/* other variables */
	char	line[MBCONTOUR_LABEL_LEN];
	char	labelstr[MBCONTOUR_LABEL_LEN], tickstr[MBCONTOUR_LABEL_LEN];
	int	count;
	int	setcolors;
	double	navlon_old;
	double	navlat_old;
	int	i1, i2;
	double	d1, d2, d3, d4, d5, d6, d7;
	int	nscan;
	int	i;

	/* get current mb default values */
	status = mb_defaults(verbose,&format,&pings,&lonflip,bounds,
		btime_i,etime_i,&speedmin,&timegap);

	/* set default input to stdin */
	strcpy (read_file, "stdin");

	/* initialize some values */
	format = -1;
        read_datalist = MB_NO;
	contour_algorithm = MB_CONTOUR_OLD;
	strcpy (contourfile,"\0");
	set_contours = MB_NO;
	bounds[0] = 0.0;
	bounds[1] = 0.0;
	bounds[2] = 0.0;
	bounds[3] = 0.0;
	scale = 0.0;
	nplot = 0;
	cont_int = 25.;
	col_int = 100.;
	tick_int = 100.;
	label_int = 100.;
	label_hgt = 0.1;
	label_spacing = 0.0;
	tick_len = 0.05;
	plot_name = MB_NO;
	plot_track = MB_NO;
	time_tick_int = 0.25;
	time_annot_int = 1.0;
	date_annot_int = 4.0;
	time_tick_len = 0.1;
	name_hgt = 0.1;
	name_perp = MB_NO;
	ncolor = 4;
	nlevel = 0;
	plot_contours = MB_NO;
	plot_triangles = MB_NO;
	bathy_in_feet = MB_NO;
	plot_pingnumber = MB_NO;
	pingnumber_tick_int = 50;
	pingnumber_annot_int = 100;
	pingnumber_tick_len = 0.1;

	/* get GMT options into separate argv */
	argv_gmt[0] = argv[0];
	argc_gmt = 1;
	for (i=1;i<argc;i++)
	  {
	  if (argv[i][0] == '-')
	    {
	    switch (argv[i][1])
	        {
		case 'B':
		case 'F':
		case 'J':
		case 'j':
		case 'K':
		case 'k':
		case 'O':
		case 'o':
		case 'P':
		case 'R':
		case 'r':
		case 'U':
		case 'u':
		case 'V':
		case 'v':
		case 'X':
		case 'x':
		case 'Y':
		case 'y':
		case '#':
		        if (argc_gmt < MBCONTOUR_GMT_ARG_MAX)
			  {
			  argv_gmt[argc_gmt] = argv[i];
			  argc_gmt++;
			  break;
			  }
		}
	    }
	  }

	/* deal with mb options */
	while ((c = getopt(argc, argv, "VvHhA:a:B:b:C:c:D:d:E:e:F:f:G:g:I:i:J:j:KkL:l:M:m:N:n:OoPp:QqR:r:S:s:T:t:UuWwX:x:Y:y:Z:z:")) != -1)
	  switch (c)
		{
		case 'A':
		case 'a':
			nscan = sscanf (optarg, "%lf/%lf/%lf/%lf/%lf/%lf/%lf",
					&d1,&d2,&d3,&d4,&d5,&d6,&d7);
			if (nscan >= 1)
			    cont_int = d1;
			if (nscan >= 2)
			    col_int = d2;
			if (nscan >= 3)
			    tick_int = d3;
			if (nscan >= 4)
			    label_int = d4;
			if (nscan >= 5)
			    tick_len = d5;
			if (nscan >= 6)
			    label_hgt = d6;
			if (nscan >= 7)
			    label_spacing = d7;
			if (nscan >= 1)
			    plot_contours = MB_YES;
			break;
		case 'b':
			sscanf (optarg, "%d/%d/%d/%d/%d/%d",
				&btime_i[0],&btime_i[1],&btime_i[2],
				&btime_i[3],&btime_i[4],&btime_i[5]);
			btime_i[6] = 0;
			break;
		case 'C':
			sscanf (optarg,"%s", contourfile);
			plot_contours = MB_YES;
			set_contours = MB_YES;
			break;
		case 'D':
		case 'd':
			sscanf (optarg, "%lf/%lf/%lf/%lf",
				&time_tick_int,&time_annot_int,
				&date_annot_int,&time_tick_len);
			plot_track = MB_YES;
			break;
		case 'E':
		case 'e':
			sscanf (optarg, "%d/%d/%d/%d/%d/%d",
				&etime_i[0],&etime_i[1],&etime_i[2],
				&etime_i[3],&etime_i[4],&etime_i[5]);
			etime_i[6] = 0;
			break;
                case 'f':
                        sscanf (optarg, "%d",&format);
                        break;
		case 'G':
		case 'g':
			nscan = sscanf (optarg, "%lf/%d", &name_hgt, &name_perp);
			plot_name = MB_YES;
			if (nscan < 1)
			    name_hgt = 0.1;
			if (nscan < 2)
			    name_perp = MB_NO;
			break;
		case 'H':
		case 'h':
			help++;
			break;
		case 'I':
		case 'i':
			sscanf (optarg,"%s", read_file);
			flag++;
			break;
		case 'J':
			if (optarg[0] == 'm')
				sscanf (&optarg[1],"%lf", &scale);
			flag++;
			break;
		case 'L':
		case 'l':
			sscanf (optarg,"%d", &lonflip);
			lonflip_set = MB_YES;
			flag++;
			break;
		case 'M':
		case 'm':
			nscan = sscanf (optarg, "%d/%d/%lf",
					&i1,&i2,&d3);
			if (nscan >= 1)
			    pingnumber_tick_int = i1;
			if (nscan >= 2)
			    pingnumber_annot_int = i2;
			if (nscan >= 3)
			    pingnumber_tick_len = d3;
			if (nscan >= 1)
			    plot_pingnumber = MB_YES;
			break;
		case 'N':
		case 'n':
			sscanf (optarg,"%d", &nplot);
			if (nplot < 3) nplot = 3;
			break;
		case 'p':
			sscanf (optarg,"%d", &pings);
			flag++;
			break;
		case 'Q':
		case 'q':
			plot_triangles = MB_YES;
			break;
		case 'R':
		case 'r':
			sscanf(optarg,"%lf/%lf/%lf/%lf",
				&bounds[0],&bounds[1],
				&bounds[2],&bounds[3]);
			break;
		case 'S':
		case 's':
			sscanf (optarg, "%lf", &speedmin);
			break;
		case 'T':
		case 't':
			sscanf (optarg,"%lf", &timegap);
			flag++;
			break;
		case 'V':
		case 'v':
			verbose++;
			break;
		case 'W':
		case 'w':
			bathy_in_feet = MB_YES;
			break;
		case 'Z':
		case 'z':
			sscanf (optarg,"%d", &contour_algorithm);
			flag++;
			break;
		case 'B':
		case 'F':
		case 'K':
		case 'O':
		case 'P':
		case 'U':
		case 'X':
		case 'x':
		case 'Y':
		case 'y':
		case '#':
			break;
		case '?':
			errflg++;
		}

	/* if error flagged then print it and exit */
	if (errflg)
		{
		fprintf(stderr,"usage: %s\n", usage_message);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		error = MB_ERROR_BAD_USAGE;
		exit(error);
		}

	/* set number of pings to be plotted if not set */
	if (nplot == 0 && contour_algorithm == MB_CONTOUR_TRIANGLES)
		nplot = 5;
	else if (nplot == 0)
		nplot = 50;

	/* if nothing set to be plotted, plot contours and track */
	if (plot_contours == MB_NO && plot_triangles == MB_NO
		&& plot_track == MB_NO && plot_pingnumber == MB_NO)
		{
		plot_contours = MB_YES;
		plot_track = MB_YES;
		}
	if (plot_name == MB_YES && plot_track == MB_NO
		&& plot_pingnumber == MB_NO)
		{
		plot_track = MB_YES;
		}
	if (plot_track == MB_NO
		&& plot_pingnumber == MB_YES)
		{
		plot_track = MB_YES;
		time_tick_int = 10000000.0;
		time_annot_int = 10000000.0;
		date_annot_int = 10000000.0;
		}

	/* print starting message */
	if (verbose == 1 || help)
		{
		fprintf(stderr,"\nProgram %s\n",program_name);
		fprintf(stderr,"MB-system Version %s\n",MB_VERSION);
		}

	/* if help desired then print it and exit */
	if (help)
		{
		fprintf(stderr,"\n%s\n",help_message);
		fprintf(stderr,"\nusage: %s\n", usage_message);
		exit(error);
		}

	/* initialize plotting */
	status = plot_init(verbose,argc_gmt,argv_gmt,bounds,&scale,&inchtolon,&error);

	/* if error flagged then print it and exit */
	if (status == MB_FAILURE)
		{
		fprintf(stderr,"usage: %s\n", usage_message);
		fprintf(stderr,"GMT option error\n");
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		error = MB_ERROR_BAD_USAGE;
		exit(error);
		}

	/* print starting debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  Program <%s>\n",program_name);
		fprintf(stderr,"dbg2  MB-system Version %s\n",MB_VERSION);
		fprintf(stderr,"dbg2  Control Parameters:\n");
		fprintf(stderr,"dbg2       verbose:              %d\n",verbose);
		fprintf(stderr,"dbg2       help:                 %d\n",help);
		fprintf(stderr,"dbg2       format:               %d\n",format);
		fprintf(stderr,"dbg2       pings:                %d\n",pings);
		fprintf(stderr,"dbg2       lonflip:              %d\n",lonflip);
		fprintf(stderr,"dbg2       btime_i[0]:           %d\n",btime_i[0]);
		fprintf(stderr,"dbg2       btime_i[1]:           %d\n",btime_i[1]);
		fprintf(stderr,"dbg2       btime_i[2]:           %d\n",btime_i[2]);
		fprintf(stderr,"dbg2       btime_i[3]:           %d\n",btime_i[3]);
		fprintf(stderr,"dbg2       btime_i[4]:           %d\n",btime_i[4]);
		fprintf(stderr,"dbg2       btime_i[5]:           %d\n",btime_i[5]);
		fprintf(stderr,"dbg2       btime_i[6]:           %d\n",btime_i[6]);
		fprintf(stderr,"dbg2       etime_i[0]:           %d\n",etime_i[0]);
		fprintf(stderr,"dbg2       etime_i[1]:           %d\n",etime_i[1]);
		fprintf(stderr,"dbg2       etime_i[2]:           %d\n",etime_i[2]);
		fprintf(stderr,"dbg2       etime_i[3]:           %d\n",etime_i[3]);
		fprintf(stderr,"dbg2       etime_i[4]:           %d\n",etime_i[4]);
		fprintf(stderr,"dbg2       etime_i[5]:           %d\n",etime_i[5]);
		fprintf(stderr,"dbg2       etime_i[6]:           %d\n",etime_i[6]);
		fprintf(stderr,"dbg2       speedmin:             %f\n",speedmin);
		fprintf(stderr,"dbg2       timegap:              %f\n",timegap);
		fprintf(stderr,"dbg2       read file:            %s\n",read_file);
		fprintf(stderr,"dbg2       bounds[0]:            %f\n",bounds[0]);
		fprintf(stderr,"dbg2       bounds[1]:            %f\n",bounds[1]);
		fprintf(stderr,"dbg2       bounds[2]:            %f\n",bounds[2]);
		fprintf(stderr,"dbg2       bounds[3]:            %f\n",bounds[3]);
		fprintf(stderr,"dbg2       contour algorithm:    %d\n",contour_algorithm);
		fprintf(stderr,"dbg2       plot contours:        %d\n",plot_contours);
		fprintf(stderr,"dbg2       plot triangles:       %d\n",plot_triangles);
		fprintf(stderr,"dbg2       plot track:           %d\n",plot_track);
		fprintf(stderr,"dbg2       plot_pingnumber:      %d\n",plot_pingnumber);
		fprintf(stderr,"dbg2       plot name:            %d\n",plot_name);
		fprintf(stderr,"dbg2       contour interval:     %f\n",cont_int);
		fprintf(stderr,"dbg2       color interval:       %f\n",col_int);
		fprintf(stderr,"dbg2       tick interval:        %f\n",tick_int);
		fprintf(stderr,"dbg2       label interval:       %f\n",label_int);
		fprintf(stderr,"dbg2       tick length:          %f\n",tick_len);
		fprintf(stderr,"dbg2       label height:         %f\n",label_hgt);
		fprintf(stderr,"dbg2       label spacing:        %f\n",label_spacing);
		fprintf(stderr,"dbg2       number contoured:     %d\n",nplot);
		fprintf(stderr,"dbg2       time tick int:        %f\n",time_tick_int);
		fprintf(stderr,"dbg2       time interval:        %f\n",time_annot_int);
		fprintf(stderr,"dbg2       date interval:        %f\n",date_annot_int);
		fprintf(stderr,"dbg2       time tick length:     %f\n",time_tick_len);
		fprintf(stderr,"dbg2       name height:          %f\n",name_hgt);
		fprintf(stderr,"dbg2       pingnumber tick int:  %d\n",pingnumber_tick_int);
		fprintf(stderr,"dbg2       pingnumber annot int: %d\n",pingnumber_annot_int);
		fprintf(stderr,"dbg2       pingnumber tick len:  %f\n",pingnumber_tick_len);
		fprintf(stderr,"dbg2       bathy_in_feet:        %d\n\n",bathy_in_feet);
		}

	/* if bounds not specified then quit */
	if (bounds[0] >= bounds[1] || bounds[2] >= bounds[3]
		|| bounds[2] <= -90.0 || bounds[3] >= 90.0)
		{
		fprintf(stderr,"\nRegion bounds not properly specified:\n\t%f %f %f %f\n",bounds[0],bounds[1],bounds[2],bounds[3]);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		error = MB_ERROR_BAD_PARAMETER;
		exit(error);
		}

	/* scale label and tick sizes */
	label_hgt_map = inchtolon * label_hgt;
	label_spacing_map = inchtolon * label_spacing;
	tick_len_map = inchtolon * tick_len;
	time_tick_len_map = inchtolon * time_tick_len;
	name_hgt_map = inchtolon * name_hgt;
	pingnumber_tick_len_map = inchtolon * pingnumber_tick_len;

	/* read contours from file */
	if (set_contours == MB_YES)
		{
		/* open contour file */
		if ((fp = fopen(contourfile,"r")) == NULL)
			{
			error = MB_ERROR_OPEN_FAIL;
			fprintf(stderr,"\nUnable to open contour file: %s\n",
				contourfile);
			fprintf(stderr,"\nProgram <%s> Terminated\n",
				program_name);
			exit(error);
			}

		/* count lines in file */
		nlevel = 0;
		while (fgets(line,MBCONTOUR_LABEL_LEN,fp) != NULL)
			nlevel++;
		fclose(fp);

		/* set number of colors equal to levels */
		ncolor = nlevel;

		/* allocate memory */
		status = mb_mallocd(verbose, __FILE__, __LINE__, nlevel*sizeof(double), (void **)&level,&error);
		status = mb_mallocd(verbose, __FILE__, __LINE__, nlevel*sizeof(int), (void **)&label,&error);
		status = mb_mallocd(verbose, __FILE__, __LINE__, nlevel*sizeof(int), (void **)&tick,&error);
		status = mb_mallocd(verbose, __FILE__, __LINE__, ncolor*sizeof(int), (void **)&red,&error);
		status = mb_mallocd(verbose, __FILE__, __LINE__, ncolor*sizeof(int), (void **)&green,&error);
		status = mb_mallocd(verbose, __FILE__, __LINE__, ncolor*sizeof(int), (void **)&blue,&error);

		/* reopen contour file */
		if ((fp = fopen(contourfile,"r")) == NULL)
			{
			error = MB_ERROR_OPEN_FAIL;
			fprintf(stderr,"\nUnable to open contour file: %s\n",
				contourfile);
			fprintf(stderr,"\nProgram <%s> Terminated\n",
				program_name);
			exit(error);
			}

		/* read contour levels from file */
		nlevel = 0;
		while (fgets(line,MBCONTOUR_LABEL_LEN,fp) != NULL)
			{
			count = sscanf(line,"%lf %s %s %d %d %d",
				&level[nlevel],labelstr,tickstr,
				&red[nlevel],&green[nlevel],&blue[nlevel]);
			setcolors = MB_YES;
			if (count >= 2 && labelstr[0] == 'a')
				label[nlevel] = 1;
			else if (count >= 2 && labelstr[0] == 'n')
				label[nlevel] = 0;
			else
				{
				label[nlevel] = 0;
				setcolors = MB_NO;
				}
			if (count >= 3 && tickstr[0] == 't')
				tick[nlevel] = 1;
			else if (count >= 3 && tickstr[0] == 'n')
				tick[nlevel] = 0;
			else
				{
				tick[nlevel] = 0;
				setcolors = MB_NO;
				}
			if (count < 6 || setcolors == MB_NO)
				{
				red[nlevel] = 0;
				green[nlevel] = 0;
				blue[nlevel] = 0;
				}
			if (count > 0) nlevel++;
			}
		fclose(fp);
		}

	/* else set default colors and use contour intervals */
	else
		{
		/* set defaults */
		nlevel = 0;
		ncolor = 4;

		/* allocate memory */
		status = mb_mallocd(verbose, __FILE__, __LINE__, ncolor*sizeof(int), (void **)&red,&error);
		status = mb_mallocd(verbose, __FILE__, __LINE__, ncolor*sizeof(int), (void **)&green,&error);
		status = mb_mallocd(verbose, __FILE__, __LINE__, ncolor*sizeof(int), (void **)&blue,&error);

		/* set colors */
		red[0] =   0; green[0] =   0; blue[0] =   0; /* black */
		red[1] = 255; green[1] =   0; blue[1] =   0; /* red */
		red[2] =   0; green[2] = 200; blue[2] =   0; /* green */
		red[3] =   0; green[3] =   0; blue[3] = 255; /* blue */
		}

	/* set colors */
	set_colors(ncolor,red,green,blue);

	/* set bounds for multibeam reading larger than
		map borders */
	mb_bounds[0] = bounds[0] - 0.25*(bounds[1] - bounds[0]);
	mb_bounds[1] = bounds[1] + 0.25*(bounds[1] - bounds[0]);
	mb_bounds[2] = bounds[2] - 0.25*(bounds[3] - bounds[2]);
	mb_bounds[3] = bounds[3] + 0.25*(bounds[3] - bounds[2]);

	/* set lonflip if possible */
	if (lonflip_set == MB_NO)
		{
		if (mb_bounds[0] < -180.0)
			lonflip = -1;
		else if (mb_bounds[1] > 180.0)
			lonflip = 1;
		else if (lonflip == -1 && mb_bounds[1] > 0.0)
			lonflip = 0;
		else if (lonflip == 1 && mb_bounds[0] < 0.0)
			lonflip = 0;
		}

	/* determine whether to read one file or a list of files */
	if (format < 0)
		read_datalist = MB_YES;

	/* open file list */
	nping_read = 0;
	if (read_datalist == MB_YES)
	    {
	    if ((status = mb_datalist_open(verbose,&datalist,
					    read_file,look_processed,&error)) != MB_SUCCESS)
		{
		error = MB_ERROR_OPEN_FAIL;
		fprintf(stderr,"\nUnable to open data list file: %s\n",
			read_file);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}
	    if ((status = mb_datalist_read(verbose,datalist,
			    file,&format,&file_weight,&error))
			    == MB_SUCCESS)
		read_data = MB_YES;
	    else
		read_data = MB_NO;
	    }
	else
	    {
	    strcpy(file,read_file);
	    read_data = MB_YES;
	    }

	/* loop over files in file list */
	if (verbose == 1)
		fprintf(stderr,"\n");
	while (read_data == MB_YES)
	    {
	    /* check for mbinfo file - get file bounds if possible */
	    status = mb_check_info(verbose, file, lonflip, bounds,
			    &file_in_bounds, &error);
	    if (status == MB_FAILURE)
		    {
		    file_in_bounds = MB_YES;
		    status = MB_SUCCESS;
		    error = MB_ERROR_NO_ERROR;
		    }

	    /* read if data may be in bounds */
	    if (file_in_bounds == MB_YES)
		{
		/* check for "fast bathymetry" or "fbt" file */
		if (plot_contours == MB_YES)
		    {
		    mb_get_fbt(verbose, file, &format, &error);
		    }

		/* else check for "fast nav" or "fnv" file */
		else if (plot_track == MB_YES || plot_pingnumber == MB_YES)
		    {
		    mb_get_fnv(verbose, file, &format, &error);
		    }

		/* call mb_read_init() */
		if ((status = mb_read_init(
		    verbose,file,format,pings,lonflip,mb_bounds,
		    btime_i,etime_i,speedmin,timegap,
		    &mbio_ptr,&btime_d,&etime_d,
		    &beams_bath,&beams_amp,&pixels_ss,&error)) != MB_SUCCESS)
		    {
		    mb_error(verbose,error,&message);
		    fprintf(stderr,"\nMBIO Error returned from function <mb_read_init>:\n%s\n",message);
		    fprintf(stderr,"\nMultibeam File <%s> not initialized for reading\n",file);
		    fprintf(stderr,"\nProgram <%s> Terminated\n",
			    program_name);
		    exit(error);
		    }

		/* allocate memory for data arrays */
		if (error == MB_ERROR_NO_ERROR)
		    status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						    sizeof(char), (void **)&beamflag, &error);
		if (error == MB_ERROR_NO_ERROR)
		    status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						    sizeof(double), (void **)&bath, &error);
		if (error == MB_ERROR_NO_ERROR)
		    status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_AMPLITUDE,
						    sizeof(double), (void **)&amp, &error);
		if (error == MB_ERROR_NO_ERROR)
		    status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						    sizeof(double), (void **)&bathlon, &error);
		if (error == MB_ERROR_NO_ERROR)
		    status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						    sizeof(double), (void **)&bathlat, &error);
		if (error == MB_ERROR_NO_ERROR)
		    status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_SIDESCAN,
						    sizeof(double), (void **)&ss, &error);
		if (error == MB_ERROR_NO_ERROR)
		    status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_SIDESCAN,
						    sizeof(double), (void **)&sslon, &error);
		if (error == MB_ERROR_NO_ERROR)
		    status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_SIDESCAN,
						    sizeof(double), (void **)&sslat, &error);

		/* if error initializing memory then quit */
		if (error != MB_ERROR_NO_ERROR)
		    {
		    mb_error(verbose,error,&message);
		    fprintf(stderr,"\nMBIO Error allocating data arrays:\n%s\n",message);
		    fprintf(stderr,"\nProgram <%s> Terminated\n",
			    program_name);
		    exit(error);
		    }

		/* initialize contour controls */
		status = mb_contour_init(verbose,&swath_plot,nplot,beams_bath,
				    contour_algorithm,
				    plot_contours,plot_triangles,
				    plot_track,plot_name,plot_pingnumber,
				    cont_int,col_int,tick_int,label_int,
				    tick_len_map,label_hgt_map,label_spacing_map,
				    ncolor,nlevel,level,label,tick,
				    time_tick_int,time_annot_int,
				    date_annot_int,time_tick_len_map,name_hgt_map,
				    pingnumber_tick_int,pingnumber_annot_int,
				    pingnumber_tick_len_map,
				    &error);
		swath_plot->beams_bath = beams_bath;

		/* if error initializing memory then quit */
		if (error != MB_ERROR_NO_ERROR)
		    {
		    mb_error(verbose,error,&message);
		    fprintf(stderr,"\nMBIO Error allocating contour control structure:\n%s\n",message);
		    fprintf(stderr,"\nProgram <%s> Terminated\n",
			    program_name);
		    exit(error);
		    }

		/* print message */
		if (verbose >= 2)
		    fprintf(stderr,"\n");
		if (verbose >= 1)
		    fprintf(stderr,"processing data in %s...\n",file);

		/* loop over reading */
		npings = &swath_plot->npings;
		*npings = 0;
		done = MB_NO;
		plotted_name = MB_NO;
		while (done == MB_NO)
		    {
		    /* read the next ping */
		    status = mb_read(verbose,mbio_ptr,&kind,
			    &pings_read,time_i,&time_d,
			    &navlon,&navlat,
			    &speed,&heading,
			    &distance,&altitude,&sonardepth,
			    &beams_bath,&beams_amp,&pixels_ss,
			    beamflag,bath,amp,bathlon,bathlat,
			    ss,sslon,sslat,
			    comment,&error);

		    /* get pingnumber */
		    if (status == MB_SUCCESS)
		    	{
		    	status = mb_pingnumber(verbose,mbio_ptr,&pingnumber,&error);
			}

		    /* copy data to swath_plot */
		    if (status == MB_SUCCESS || error == MB_ERROR_TIME_GAP)
		    	{
		        pingcur = &swath_plot->pings[*npings];

			/* make sure enough memory is allocated */
			if (pingcur->beams_bath_alloc < beams_bath)
				{
				status = mb_reallocd(verbose, __FILE__, __LINE__, beams_bath*sizeof(char),
						(void **)&(pingcur->beamflag),&error);
				status = mb_reallocd(verbose, __FILE__, __LINE__, beams_bath*sizeof(double),
						(void **)&(pingcur->bath),&error);
				status = mb_reallocd(verbose, __FILE__, __LINE__, beams_bath*sizeof(double),
						(void **)&(pingcur->bathlon),&error);
				status = mb_reallocd(verbose, __FILE__, __LINE__, beams_bath*sizeof(double),
						(void **)&(pingcur->bathlat),&error);
                                status = mb_reallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(int),
                                                (void **)&(pingcur->bflag[0]),&error);
                                status = mb_reallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(int),
                                                (void **)&(pingcur->bflag[1]),&error);
				pingcur->beams_bath_alloc = beams_bath;
				}

			/* insert the data */
			for (i=0;i<7;i++)
				pingcur->time_i[i] = time_i[i];
			pingcur->time_d = time_d;
			pingcur->navlon = navlon;
			pingcur->navlat = navlat;
			pingcur->heading = heading;
			pingcur->beams_bath = beams_bath;
			pingcur->pingnumber = pingnumber;
			for (i=0;i<beams_bath;i++)
				{
				pingcur->beamflag[i] = beamflag[i];
				pingcur->bath[i] = bath[i];
				pingcur->bathlon[i] = bathlon[i];
				pingcur->bathlat[i] = bathlat[i];
                                pingcur->bflag[0][i] = 0;
                                pingcur->bflag[1][i] = 0;
				}
			}

		    /* null out any unused beams for formats with
			variable numbers of beams */
		    for (i=beams_bath;i<swath_plot->beams_bath;i++)
			    beamflag[i] = MB_FLAG_NULL;

		    /* print debug statements */
		    if (verbose >= 2)
			    {
			    fprintf(stderr,"\ndbg2  Ping read in program <%s>\n",
				    program_name);
			    fprintf(stderr,"dbg2       kind:           %d\n",
				    kind);
			    fprintf(stderr,"dbg2       npings:         %d\n",
				    *npings);
			    fprintf(stderr,"dbg2       time:           %4d %2d %2d %2d %2d %2d %6.6d\n",
				    time_i[0],time_i[1],time_i[2],
				    time_i[3],time_i[4],time_i[5],time_i[6]);
			    fprintf(stderr,"dbg2       navigation:     %f  %f\n",
				    navlon, navlat);
			    fprintf(stderr,"dbg2       beams_bath:     %d\n",
				    beams_bath);
			    fprintf(stderr,"dbg2       beams_amp:      %d\n",
					    beams_amp);
			    fprintf(stderr,"dbg2       pixels_ss:      %d\n",
					    pixels_ss);
			    fprintf(stderr,"dbg2       error:          %d\n",
				    error);
			    fprintf(stderr,"dbg2       status:         %d\n",
				    status);
			    }

		    /* scale bathymetry if necessary */
		    if (error == MB_ERROR_NO_ERROR
			    && bathy_in_feet == MB_YES)
			    {
			    for (i=0;i<beams_bath;i++)
				    {
				    bath[i] = 3.2808399 * bath[i];
				    }
			    }

		    /* update bookkeeping */
		    if (error == MB_ERROR_NO_ERROR)
			    {
			    /*if (*npings == 0 ||
				    (*npings > 0
				    && contour_algorithm == MB_CONTOUR_TRIANGLES)
				    || (*npings > 0
				    && (navlon != navlon_old
				    || navlat != navlat_old)))*/
				    {
				    nping_read += pings_read;
				    (*npings)++;
				    navlon_old = navlon;
				    navlat_old = navlat;
				    }
			    }

		    /* decide whether to plot, whether to
			    save the new ping, and if done */
		    plot = MB_NO;
		    flush = MB_NO;
		    if (*npings >= nplot)
			    plot = MB_YES;
		    if (*npings > 0
			    && (error > MB_ERROR_NO_ERROR
			    || error == MB_ERROR_TIME_GAP
			    || error == MB_ERROR_OUT_BOUNDS
			    || error == MB_ERROR_OUT_TIME
			    || error == MB_ERROR_SPEED_TOO_SMALL))
			    {
			    plot = MB_YES;
			    flush = MB_YES;
			    }
		    save_new = MB_NO;
		    if (error == MB_ERROR_TIME_GAP)
			    save_new = MB_YES;
		    if (error > MB_ERROR_NO_ERROR)
			    done = MB_YES;

		    /* if enough pings read in, plot them */
		    if (plot == MB_YES)
			    {

			    /* print debug statements */
			    if (verbose >= 2)
				    {
				    fprintf(stderr,"\ndbg2  Plotting %d pings in program <%s>\n",
					    *npings,program_name);
				    for (i=0;i<*npings;i++)
					    {
					    pingcur = &swath_plot->pings[i];
					    fprintf(stderr,"dbg2       %4d  %4d %2d %2d %2d %2d %2d %6.6d\n",
						    i,pingcur->time_i[0],
						    pingcur->time_i[1],
						    pingcur->time_i[2],
						    pingcur->time_i[3],
						    pingcur->time_i[4],
						    pingcur->time_i[5],
						    pingcur->time_i[6]);
					    }
				    }

			    /* plot data */
			    if (plot_contours == MB_YES
				    || plot_triangles == MB_YES)
				    mb_contour(verbose,swath_plot,&error);

			    /* plot nav track */
			    if (plot_track == MB_YES)
				    mb_track(verbose,swath_plot,&error);

			    /* annotate pingnumber */
			    if (plot_pingnumber == MB_YES)
			    	    {
				    mb_trackpingnumber(verbose,swath_plot,&error);
				    }

			    if (plot_name == MB_YES && plotted_name == MB_NO)
			    	    {
				    mb_trackname(verbose,name_perp,swath_plot,file,&error);
				    plotted_name = MB_YES;
				    }

			    /* reorganize data */
			    if (flush == MB_YES && save_new == MB_YES)
				    {
				    status = ping_copy(verbose,0,*npings,
					    swath_plot,&error);
				    *npings = 1;
				    }
			    else if (flush == MB_YES)
				    {
				    *npings = 0;
				    }
			    else if (*npings > 1)
				    {
				    status = ping_copy(verbose,0,*npings-1,
						    swath_plot,&error);
				    *npings = 1;
				    }

			    }
		    }
		status = mb_close(verbose,&mbio_ptr,&error);

		/* deallocate memory for data arrays */
		status = mb_contour_deall(verbose,swath_plot,&error);
		} /* end if file in bounds */

	    /* figure out whether and what to read next */
	    if (read_datalist == MB_YES)
                {
		if ((status = mb_datalist_read(verbose,datalist,
			    file,&format,&file_weight,&error))
			    == MB_SUCCESS)
                        read_data = MB_YES;
                else
                        read_data = MB_NO;
                }
	    else
                {
                read_data = MB_NO;
                }

	    /* end loop over files in list */
	    }
	if (read_datalist == MB_YES)
		mb_datalist_close(verbose,&datalist,&error);

	/* end plot */
	plot_end(verbose,&error);

	/* deallocate memory for data arrays */
	mb_freed(verbose,__FILE__, __LINE__, (void **)&level,&error);
	mb_freed(verbose,__FILE__, __LINE__, (void **)&label,&error);
	mb_freed(verbose,__FILE__, __LINE__, (void **)&tick,&error);
	mb_freed(verbose,__FILE__, __LINE__, (void **)&red,&error);
	mb_freed(verbose,__FILE__, __LINE__, (void **)&green,&error);
	mb_freed(verbose,__FILE__, __LINE__, (void **)&blue,&error);

	/* print ending info */
	if (verbose >= 1)
		fprintf(stderr,"\n%d pings read and plotted\n",
			nping_read);

	/* check memory */
	if (verbose >= 2)
		status = mb_memory_list(verbose,&error);

	/* print output debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  Program <%s> completed\n",
			program_name);
		fprintf(stderr,"dbg2  Ending status:\n");
		fprintf(stderr,"dbg2       status:  %d\n",status);
		}

	/* end it all */
	plot_exit(argc,argv);
	exit(status);
}
Пример #17
0
int main (int argc, char **argv)
{
	char program_name[] = "MBroutetime";
	char help_message[] =  "MBroutetime outputs a list of the times when a survey hit the waypoints\nof a planned survey route. This (lon lat time_d) list can then be used by mbextractsegy\nor mb7k2ss to extract subbottom (or sidescan) data into files corresponding\nto the lines between waypoints.";
	char usage_message[] = "mbroutetime  -Rroutefile [-Fformat -Ifile -Owaypointtimefile -Urangethreshold -H -V]";
	extern char *optarg;
	int	errflg = 0;
	int	c;
	int	help = 0;
	int	flag = 0;

	/* MBIO status variables */
	int	status = MB_SUCCESS;
	int	verbose = 0;
	int	error = MB_ERROR_NO_ERROR;
	char	*message;

	/* MBIO read control parameters */
	int	read_datalist = MB_NO;
	char	read_file[MB_PATH_MAXLINE];
	char	output_file[MB_PATH_MAXLINE];
	int	output_file_set = MB_NO;
	void	*datalist;
	int	look_processed = MB_DATALIST_LOOK_UNSET;
	double	file_weight;
	int	format;
	int	pings;
	int	lonflip;
	double	bounds[4];
	int	btime_i[7];
	int	etime_i[7];
	double	btime_d;
	double	etime_d;
	double	speedmin;
	double	timegap;
	char	file[MB_PATH_MAXLINE];
	int	beams_bath;
	int	beams_amp;
	int	pixels_ss;

	/* MBIO read values */
	void	*mbio_ptr = NULL;
	void	*store_ptr = NULL;
	int	kind;
	int	time_i[7];
	double	time_d;
	double	navlon;
	double	navlat;
	double	speed;
	double	heading;
	double	distance;
	double	altitude;
	double	sonardepth;
	char	*beamflag = NULL;
	double	*bath = NULL;
	double	*bathacrosstrack = NULL;
	double	*bathalongtrack = NULL;
	double	*amp = NULL;
	double	*ss = NULL;
	double	*ssacrosstrack = NULL;
	double	*ssalongtrack = NULL;
	char	comment[MB_COMMENT_MAXLINE];

	/* route and auto-line data */
	char	route_file[MB_PATH_MAXLINE];
	int	rawroutefile = MB_NO;
	int	nroutepoint = 0;
	int	nroutepointfound = 0;
	int	nroutepointalloc = 0;
	double	lon;
	double	lat;
	double	topo;
	int	waypoint;
	double	*routelon = NULL;
	double	*routelat = NULL;
	double	*routeheading = NULL;
	int	*routewaypoint = NULL;
	double	*routetime_d = NULL;
	double	range;
	double	rangethreshold = 25.0;
	double	rangelast;
	int	activewaypoint = 0;

	double	mtodeglon, mtodeglat;
	double	lastlon;
	double	lastlat;
	double	lastheading;
	double	lasttime_d;
	double	dx, dy;
	FILE	*fp = NULL;
	char	*result;
	int	nget;
	int	point_ok;
	int	read_data;
	int	nread;
	int	i;

	/* get current default values */
	status = mb_defaults(verbose,&format,&pings,&lonflip,bounds,
		btime_i,etime_i,&speedmin,&timegap);

	/* set default input to datalist.mb-1 */
	strcpy (read_file, "datalist.mb-1");

	/* process argument list */
	while ((c = getopt(argc, argv, "F:f:I:i:O:o:R:r:U:u:VvHh")) != -1)
	  switch (c)
		{
		case 'H':
		case 'h':
			help++;
			break;
		case 'V':
		case 'v':
			verbose++;
			break;
		case 'F':
		case 'f':
			sscanf (optarg,"%d", &format);
			flag++;
			break;
		case 'I':
		case 'i':
			sscanf (optarg,"%s", read_file);
			flag++;
			break;
		case 'O':
		case 'o':
			sscanf (optarg,"%s", output_file);
			output_file_set = MB_YES;
			flag++;
			break;
		case 'R':
		case 'r':
			sscanf (optarg,"%s", route_file);
			flag++;
			break;
		case 'U':
		case 'u':
			sscanf (optarg,"%lf", &rangethreshold);
			flag++;
			break;
		case '?':
			errflg++;
		}

	/* if error flagged then print it and exit */
	if (errflg)
		{
		fprintf(stderr,"usage: %s\n", usage_message);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		error = MB_ERROR_BAD_USAGE;
		exit(error);
		}

	/* print starting message */
	if (verbose == 1 || help)
		{
		fprintf(stderr,"\nProgram %s\n",program_name);
		fprintf(stderr,"Version %s\n",rcs_id);
		fprintf(stderr,"MB-system Version %s\n",MB_VERSION);
		}

	/* print starting debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  Program <%s>\n",program_name);
		fprintf(stderr,"dbg2  Version %s\n",rcs_id);
		fprintf(stderr,"dbg2  MB-system Version %s\n",MB_VERSION);
		fprintf(stderr,"dbg2  Control Parameters:\n");
		fprintf(stderr,"dbg2       verbose:           %d\n",verbose);
		fprintf(stderr,"dbg2       help:              %d\n",help);
		fprintf(stderr,"dbg2       format:            %d\n",format);
		fprintf(stderr,"dbg2       pings:             %d\n",pings);
		fprintf(stderr,"dbg2       lonflip:           %d\n",lonflip);
		fprintf(stderr,"dbg2       bounds[0]:         %f\n",bounds[0]);
		fprintf(stderr,"dbg2       bounds[1]:         %f\n",bounds[1]);
		fprintf(stderr,"dbg2       bounds[2]:         %f\n",bounds[2]);
		fprintf(stderr,"dbg2       bounds[3]:         %f\n",bounds[3]);
		fprintf(stderr,"dbg2       btime_i[0]:        %d\n",btime_i[0]);
		fprintf(stderr,"dbg2       btime_i[1]:        %d\n",btime_i[1]);
		fprintf(stderr,"dbg2       btime_i[2]:        %d\n",btime_i[2]);
		fprintf(stderr,"dbg2       btime_i[3]:        %d\n",btime_i[3]);
		fprintf(stderr,"dbg2       btime_i[4]:        %d\n",btime_i[4]);
		fprintf(stderr,"dbg2       btime_i[5]:        %d\n",btime_i[5]);
		fprintf(stderr,"dbg2       btime_i[6]:        %d\n",btime_i[6]);
		fprintf(stderr,"dbg2       etime_i[0]:        %d\n",etime_i[0]);
		fprintf(stderr,"dbg2       etime_i[1]:        %d\n",etime_i[1]);
		fprintf(stderr,"dbg2       etime_i[2]:        %d\n",etime_i[2]);
		fprintf(stderr,"dbg2       etime_i[3]:        %d\n",etime_i[3]);
		fprintf(stderr,"dbg2       etime_i[4]:        %d\n",etime_i[4]);
		fprintf(stderr,"dbg2       etime_i[5]:        %d\n",etime_i[5]);
		fprintf(stderr,"dbg2       etime_i[6]:        %d\n",etime_i[6]);
		fprintf(stderr,"dbg2       speedmin:          %f\n",speedmin);
		fprintf(stderr,"dbg2       timegap:           %f\n",timegap);
		fprintf(stderr,"dbg2       read_file:         %s\n",read_file);
		fprintf(stderr,"dbg2       route_file:        %s\n",route_file);
		fprintf(stderr,"dbg2       output_file_set:   %d\n",output_file_set);
		fprintf(stderr,"dbg2       output_file:       %s\n",output_file);
		fprintf(stderr,"dbg2       rangethreshold:    %f\n",rangethreshold);
		}

	/* if help desired then print it and exit */
	if (help)
		{
		fprintf(stderr,"\n%s\n",help_message);
		fprintf(stderr,"\nusage: %s\n", usage_message);
		exit(error);
		}

	/* read route file */
	if ((fp = fopen(route_file, "r")) == NULL)
		{
		error = MB_ERROR_OPEN_FAIL;
		status = MB_FAILURE;
		fprintf(stderr,"\nUnable to open route file <%s> for reading\n",route_file);
		exit(status);
		}
	rawroutefile = MB_NO;
	while ((result = fgets(comment,MB_PATH_MAXLINE,fp)) == comment)
		{
		if (comment[0] == '#')
			{
			if (strncmp(comment,"## Route File Version", 21) == 0)
				{
				rawroutefile = MB_NO;
				}
			}
		else
			{
			nget = sscanf(comment,"%lf %lf %lf %d %lf",
			    &lon, &lat, &topo, &waypoint, &heading);
			if (comment[0] == '#')
				{
				fprintf(stderr,"buffer:%s",comment);
				if (strncmp(comment,"## Route File Version", 21) == 0)
					{
					rawroutefile = MB_NO;
					}
				}
		    	if ((rawroutefile == MB_YES && nget >= 2)
				|| (rawroutefile == MB_NO && nget >= 3 && waypoint > MBES_ROUTE_WAYPOINT_TRANSIT))
				point_ok = MB_YES;
			else
				point_ok = MB_NO;

			/* if good data check for need to allocate more space */
			if (point_ok == MB_YES
				&& nroutepoint + 2 > nroutepointalloc)
				{
				nroutepointalloc += MBES_ALLOC_NUM;
				status = mb_reallocd(verbose, __FILE__, __LINE__, nroutepointalloc * sizeof(double),
							(void **)&routelon, &error);
				status = mb_reallocd(verbose, __FILE__, __LINE__, nroutepointalloc * sizeof(double),
							(void **)&routelat, &error);
				status = mb_reallocd(verbose, __FILE__, __LINE__, nroutepointalloc * sizeof(double),
							(void **)&routeheading, &error);
				status = mb_reallocd(verbose, __FILE__, __LINE__, nroutepointalloc * sizeof(int),
							(void **)&routewaypoint, &error);
				status = mb_reallocd(verbose, __FILE__, __LINE__, nroutepointalloc * sizeof(double),
							(void **)&routetime_d, &error);
				if (status != MB_SUCCESS)
					{
					mb_error(verbose,error,&message);
					fprintf(stderr,"\nMBIO Error allocating data arrays:\n%s\n",
						message);
					fprintf(stderr,"\nProgram <%s> Terminated\n",
						program_name);
					exit(error);
					}
				}

			/* add good point to route */
			if (point_ok == MB_YES && nroutepointalloc > nroutepoint)
				{
				routelon[nroutepoint] = lon;
				routelat[nroutepoint] = lat;
				routeheading[nroutepoint] = heading;
				routewaypoint[nroutepoint] = waypoint;
				routetime_d[nroutepoint] = 0.0;
				nroutepoint++;
				}
			}
		}

	/* close the file */
	fclose(fp);
	fp = NULL;
	
	/* Check that there are valid waypoints in memory */
	if (nroutepoint < 1)
		{
		error = MB_ERROR_EOF;
		status = MB_FAILURE;
		fprintf(stderr,"\nNo line start or line end waypoints read from route file: <%s>\n",route_file);
		fprintf(stderr,"\nProgram <%s> Terminated\n", program_name);
		exit(error);
		}
	else if (nroutepoint < 2)
		{
		error = MB_ERROR_EOF;
		status = MB_FAILURE;
		fprintf(stderr,"\nOnly one line start or line end waypoint read from route file: <%s>\n",route_file);
		fprintf(stderr,"\nProgram <%s> Terminated\n", program_name);
		exit(error);
		}

	/* set starting values */
	activewaypoint = 0;
	mb_coor_scale(verbose,routelat[activewaypoint], &mtodeglon, &mtodeglat);
	rangelast = 1000 * rangethreshold;

	/* output status */
	if (verbose > 0)
		{
		/* output info on file output */
		fprintf(stderr,"Read %d waypoints from route file: %s\n",
			nroutepoint, route_file);
		}

	/* get format if required */
	if (format == 0)
		mb_get_format(verbose,read_file,NULL,&format,&error);

	/* determine whether to read one file or a list of files */
	if (format < 0)
		read_datalist = MB_YES;

	/* open file list */
	if (read_datalist == MB_YES)
	    {
	    if ((status = mb_datalist_open(verbose,&datalist,
					    read_file,look_processed,&error)) != MB_SUCCESS)
		{
		error = MB_ERROR_OPEN_FAIL;
		fprintf(stderr,"\nUnable to open data list file: %s\n",
			read_file);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}
	    if ((status = mb_datalist_read(verbose,datalist,
			    file,&format,&file_weight,&error))
			    == MB_SUCCESS)
		read_data = MB_YES;
	    else
		read_data = MB_NO;
	    }
	/* else copy single filename to be read */
	else
	    {
	    strcpy(file, read_file);
	    read_data = MB_YES;
	    }

	/* loop over all files to be read */
	while (read_data == MB_YES)
		{
		/* read fnv file if possible */
		mb_get_fnv(verbose, file, &format, &error);

		/* initialize reading the swath file */
		if ((status = mb_read_init(
			verbose,file,format,pings,lonflip,bounds,
			btime_i,etime_i,speedmin,timegap,
			&mbio_ptr,&btime_d,&etime_d,
			&beams_bath,&beams_amp,&pixels_ss,&error)) != MB_SUCCESS)
			{
			mb_error(verbose,error,&message);
			fprintf(stderr,"\nMBIO Error returned from function <mb_read_init>:\n%s\n",message);
			fprintf(stderr,"\nMultibeam File <%s> not initialized for reading\n",file);
			fprintf(stderr,"\nProgram <%s> Terminated\n",
				program_name);
			exit(error);
			}

		/* allocate memory for data arrays */
		if (error == MB_ERROR_NO_ERROR)
			status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
							sizeof(char), (void **)&beamflag, &error);
		if (error == MB_ERROR_NO_ERROR)
			status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
							sizeof(double), (void **)&bath, &error);
		if (error == MB_ERROR_NO_ERROR)
			status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_AMPLITUDE,
							sizeof(double), (void **)&amp, &error);
		if (error == MB_ERROR_NO_ERROR)
			status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
							sizeof(double), (void **)&bathacrosstrack, &error);
		if (error == MB_ERROR_NO_ERROR)
			status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
							sizeof(double), (void **)&bathalongtrack, &error);
		if (error == MB_ERROR_NO_ERROR)
			status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_SIDESCAN,
							sizeof(double), (void **)&ss, &error);
		if (error == MB_ERROR_NO_ERROR)
			status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_SIDESCAN,
							sizeof(double), (void **)&ssacrosstrack, &error);
		if (error == MB_ERROR_NO_ERROR)
			status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_SIDESCAN,
							sizeof(double), (void **)&ssalongtrack, &error);

		/* if error initializing memory then quit */
		if (error != MB_ERROR_NO_ERROR)
			{
			mb_error(verbose,error,&message);
			fprintf(stderr,"\nMBIO Error allocating data arrays:\n%s\n",
				message);
			fprintf(stderr,"\nProgram <%s> Terminated\n",
				program_name);
			exit(error);
			}

		/* read and use data */
		nread = 0;
		while (error <= MB_ERROR_NO_ERROR && activewaypoint < nroutepoint)
			{
			/* reset error */
			error = MB_ERROR_NO_ERROR;

			/* read next data record */
			status = mb_get_all(verbose,mbio_ptr,&store_ptr,&kind,
			    time_i,&time_d,&navlon,&navlat,
			    &speed,&heading,
			    &distance,&altitude,&sonardepth,
			    &beams_bath,&beams_amp,&pixels_ss,
			    beamflag,bath,amp,bathacrosstrack,bathalongtrack,
			    ss,ssacrosstrack,ssalongtrack,
			    comment,&error);

			/* deal with nav and time from survey data only - not nav, sidescan, or subbottom */
			if (error <= MB_ERROR_NO_ERROR && kind == MB_DATA_DATA)
				{
				/* increment counter */
				nread++;

				/* save last nav and heading */
				if (navlon != 0.0)
					lastlon = navlon;
				if (navlat != 0.0)
					lastlat = navlat;
				if (heading != 0.0)
					lastheading = heading;
				if (time_d != 0.0)
					lasttime_d = time_d;


				/* check survey data position against waypoints */
				if (navlon != 0.0 && navlat != 0.0)
					{
					dx = (navlon - routelon[activewaypoint]) / mtodeglon;
					dy = (navlat - routelat[activewaypoint]) / mtodeglat;
					range = sqrt(dx * dx + dy * dy);
					if (verbose > 0)
						fprintf(stderr,"> activewaypoint:%d time_d:%f range:%f   lon: %f %f   lat: %f %f\n",
							activewaypoint, time_d, range, navlon,
							routelon[activewaypoint], navlat, routelat[activewaypoint]);

					if (range < rangethreshold
						&& (activewaypoint == 0 || range > rangelast)
						&& activewaypoint < nroutepoint)
						{
						fprintf(stderr,"Waypoint %d of %d found with range %f m\n",
								activewaypoint, nroutepoint, range);
						routetime_d[activewaypoint] = time_d;
						activewaypoint++;
						nroutepointfound++;
						mb_coor_scale(verbose,routelat[activewaypoint], &mtodeglon, &mtodeglat);
						rangelast = 1000 * rangethreshold;
						}
					else
						rangelast = range;
					}
				}

			/* print debug statements */
			if (verbose >= 2)
				{
				fprintf(stderr,"\ndbg2  Ping read in program <%s>\n",
					program_name);
				fprintf(stderr,"dbg2       kind:           %d\n",kind);
				fprintf(stderr,"dbg2       error:          %d\n",error);
				fprintf(stderr,"dbg2       status:         %d\n",status);
				}
			}

		/* close the swath file */
		status = mb_close(verbose,&mbio_ptr,&error);

		/* output read statistics */
		fprintf(stderr,"%d records read from %s\n", nread, file);

		/* figure out whether and what to read next */
        	if (read_datalist == MB_YES)
                	{
			if ((status = mb_datalist_read(verbose,datalist,
				    file,&format,&file_weight,&error))
				    == MB_SUCCESS)
                        	read_data = MB_YES;
                	else
                        	read_data = MB_NO;
                	}
        	else
                	{
                	read_data = MB_NO;
                	}

		/* end loop over files in list */
		}
	if (read_datalist == MB_YES)
		mb_datalist_close(verbose,&datalist,&error);

	/* if the last route point was not reached, add one last waypoint */
	if (nroutepointfound < nroutepoint)
		{
		fprintf(stderr,"Waypoint %d of %d set at end of data with range %f m to next specified waypoint\n",
				activewaypoint, nroutepoint, range);
		routelon[nroutepointfound] = lastlon;
		routelat[nroutepointfound] = lastlat;
		routeheading[nroutepointfound] = lastheading;
		routetime_d[nroutepointfound] = lasttime_d;
		routewaypoint[nroutepointfound] = MBES_ROUTE_WAYPOINT_ENDLINE;
		nroutepointfound++;
		}

	/* output time list for the route */
	if (output_file_set == MB_NO)
		{
		sprintf(output_file, "%s_wpttime_d.txt", read_file);
		}
	if ((fp = fopen(output_file, "w")) == NULL)
		{
		error = MB_ERROR_OPEN_FAIL;
		status = MB_FAILURE;
		fprintf(stderr,"\nUnable to open output waypoint time list file <%s> for writing\n",output_file);
		exit(status);
		}
	for (i=0;i<nroutepointfound;i++)
		{
		fprintf(fp,"%3d %3d %11.6f %10.6f %10.6f %.6f\n", i, routewaypoint[i], routelon[i], routelat[i], routeheading[i], routetime_d[i]);
		if (verbose > 0)
			fprintf(stderr,"%3d %3d %11.6f %10.6f %10.6f %.6f\n", i, routewaypoint[i], routelon[i], routelat[i], routeheading[i], routetime_d[i]);
		}
	fclose(fp);

	/* deallocate route arrays */
	status = mb_freed(verbose,__FILE__,__LINE__, (void **)&routelon, &error);
	status = mb_freed(verbose,__FILE__,__LINE__, (void **)&routelat, &error);
	status = mb_freed(verbose,__FILE__,__LINE__, (void **)&routeheading, &error);
	status = mb_freed(verbose,__FILE__,__LINE__, (void **)&routewaypoint, &error);
	status = mb_freed(verbose,__FILE__,__LINE__, (void **)&routetime_d, &error);

	/* check memory */
	if (verbose >= 4)
		status = mb_memory_list(verbose,&error);

	/* print output debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  Program <%s> completed\n",
			program_name);
		fprintf(stderr,"dbg2  Ending status:\n");
		fprintf(stderr,"dbg2       status:  %d\n",status);
		}

	/* end it all */
	exit(error);
}
Пример #18
0
int main (int argc, char **argv)
{
	/* id variables */
	char program_name[] = "HSDUMP";
	char help_message[] =  "HSDUMP lists the information contained in data records on\n\tHydrosweep DS data files, including survey, calibrate, water \n\tvelocity and comment records. The default input stream is stdin.";
	char usage_message[] = "hsdump [-Fformat -V -H -Iinfile -Okind]";

	/* parsing variables */
	extern char *optarg;
	int	errflg = 0;
	int	c;
	int	help = 0;
	int	flag = 0;

	/* MBIO status variables */
	int	status = MB_SUCCESS;
	int	verbose = 0;
	int	error = MB_ERROR_NO_ERROR;
	char	format_description[MB_DESCRIPTION_LENGTH];
	char	*message = NULL;

	/* MBIO read and write control parameters */
	int	format = 0;
	int	pings;
	int	lonflip;
	double	bounds[4];
	int	btime_i[7];
	int	etime_i[7];
	double	btime_d;
	double	etime_d;
	double	speedmin;
	double	timegap;
	int	beams_bath;
	int	beams_amp;
	int	pixels_ss;
	char	file[MB_PATH_MAXLINE];
	void	*mbio_ptr = NULL;

	/* mbio read and write values */
	void	*store_ptr;
	struct mbsys_hsds_struct *store;
	int	kind;
	int	time_i[7];
	double	time_d;
	double	navlon;
	double	navlat;
	double	speed;
	double	heading;
	double	distance;
	double	altitude;
	double	sonardepth;
	int	nbath;
	int	namp;
	int	nss;
	char	*beamflag = NULL;
	double	*bath = NULL;
	double	*bathacrosstrack = NULL;
	double	*bathalongtrack = NULL;
	double	*amp = NULL;
	double	*ss = NULL;
	double	*ssacrosstrack = NULL;
	double	*ssalongtrack = NULL;
	char	comment[MB_COMMENT_MAXLINE];

	/* dump control parameters */
	int	mb_data_data_list = MB_NO;
	int	mb_data_comment_list = MB_NO;
	int	mb_data_calibrate_list = MB_NO;
	int	mb_data_mean_velocity_list = MB_NO;
	int	mb_data_velocity_profile_list = MB_NO;
	int	mb_data_standby_list = MB_NO;
	int	mb_data_nav_source_list = MB_NO;
	int	mb_data_data_count = 0;
	int	mb_data_comment_count = 0;
	int	mb_data_calibrate_count = 0;
	int	mb_data_mean_velocity_count = 0;
	int	mb_data_velocity_profile_count = 0;
	int	mb_data_standby_count = 0;
	int	mb_data_nav_source_count = 0;

	/* output stream for basic stuff (stdout if verbose <= 1,
		stderr if verbose > 1) */
	FILE	*output;

	int	i;

	/* get current default values */
	status = mb_defaults(verbose,&format,&pings,&lonflip,bounds,
		btime_i,etime_i,&speedmin,&timegap);

	/* reset all defaults */
	format = MBF_HSATLRAW;
	pings = 1;
	lonflip = 0;
	bounds[0] = -360.;
	bounds[1] = 360.;
	bounds[2] = -90.;
	bounds[3] = 90.;
	btime_i[0] = 1962;
	btime_i[1] = 2;
	btime_i[2] = 21;
	btime_i[3] = 10;
	btime_i[4] = 30;
	btime_i[5] = 0;
	btime_i[6] = 0;
	etime_i[0] = 2062;
	etime_i[1] = 2;
	etime_i[2] = 21;
	etime_i[3] = 10;
	etime_i[4] = 30;
	etime_i[5] = 0;
	etime_i[6] = 0;
	speedmin = 0.0;
	timegap = 1000000000.0;

	/* set default input and output */
	strcpy (file, "stdin");

	/* process argument list */
	while ((c = getopt(argc, argv, "VvHhF:f:I:i:O:o:")) != -1)
	  switch (c) 
		{
		case 'H':
		case 'h':
			help++;
			break;
		case 'V':
		case 'v':
			verbose++;
			break;
		case 'F':
		case 'f':
			sscanf (optarg,"%d", &format);
			flag++;
			break;
		case 'I':
		case 'i':
			sscanf (optarg,"%s", file);
			flag++;
			break;
		case 'O':
		case 'o':
			sscanf (optarg,"%d", &kind);
			if (kind == MB_DATA_DATA)
				mb_data_data_list = MB_YES;
			if (kind == MB_DATA_COMMENT)
				mb_data_comment_list = MB_YES;
			if (kind == MB_DATA_CALIBRATE)
				mb_data_calibrate_list = MB_YES;
			if (kind == MB_DATA_MEAN_VELOCITY)
				mb_data_mean_velocity_list = MB_YES;
			if (kind == MB_DATA_VELOCITY_PROFILE)
				mb_data_velocity_profile_list = MB_YES;
			if (kind == MB_DATA_STANDBY)
				mb_data_standby_list = MB_YES;
			if (kind == MB_DATA_NAV_SOURCE)
				mb_data_nav_source_list = MB_YES;
			flag++;
			break;
		case '?':
			errflg++;
		}

	/* set output stream */
	if (verbose <= 1)
		output = stdout;
	else
		output = stderr;

	/* if error flagged then print it and exit */
	if (errflg)
		{
		fprintf(output,"usage: %s\n", usage_message);
		fprintf(output,"\nProgram <%s> Terminated\n",
			program_name);
		error = MB_ERROR_BAD_USAGE;
		exit(error);
		}

	/* print starting message */
	if (verbose == 1 || help)
		{
		fprintf(output,"\nProgram %s\n",program_name);
		fprintf(output,"MB-system Version %s\n",MB_VERSION);
		}

	/* print starting debug statements */
	if (verbose >= 2)
		{
		fprintf(output,"\ndbg2  Program <%s>\n",program_name);
		fprintf(output,"dbg2  MB-system Version %s\n",MB_VERSION);
		fprintf(output,"dbg2  Control Parameters:\n");
		fprintf(output,"dbg2       verbose:         %d\n",verbose);
		fprintf(output,"dbg2       help:            %d\n",help);
		fprintf(output,"dbg2       format:          %d\n",format);
		fprintf(output,"dbg2       pings:           %d\n",pings);
		fprintf(output,"dbg2       lonflip:         %d\n",lonflip);
		fprintf(output,"dbg2       bounds[0]:       %f\n",bounds[0]);
		fprintf(output,"dbg2       bounds[1]:       %f\n",bounds[1]);
		fprintf(output,"dbg2       bounds[2]:       %f\n",bounds[2]);
		fprintf(output,"dbg2       bounds[3]:       %f\n",bounds[3]);
		fprintf(output,"dbg2       btime_i[0]:      %d\n",btime_i[0]);
		fprintf(output,"dbg2       btime_i[1]:      %d\n",btime_i[1]);
		fprintf(output,"dbg2       btime_i[2]:      %d\n",btime_i[2]);
		fprintf(output,"dbg2       btime_i[3]:      %d\n",btime_i[3]);
		fprintf(output,"dbg2       btime_i[4]:      %d\n",btime_i[4]);
		fprintf(output,"dbg2       btime_i[5]:      %d\n",btime_i[5]);
		fprintf(output,"dbg2       btime_i[6]:      %d\n",btime_i[6]);
		fprintf(output,"dbg2       etime_i[0]:      %d\n",etime_i[0]);
		fprintf(output,"dbg2       etime_i[1]:      %d\n",etime_i[1]);
		fprintf(output,"dbg2       etime_i[2]:      %d\n",etime_i[2]);
		fprintf(output,"dbg2       etime_i[3]:      %d\n",etime_i[3]);
		fprintf(output,"dbg2       etime_i[4]:      %d\n",etime_i[4]);
		fprintf(output,"dbg2       etime_i[5]:      %d\n",etime_i[5]);
		fprintf(output,"dbg2       etime_i[6]:      %d\n",etime_i[6]);
		fprintf(output,"dbg2       speedmin:        %f\n",speedmin);
		fprintf(output,"dbg2       timegap:         %f\n",timegap);
		fprintf(output,"dbg2       input file:      %s\n",file);
		fprintf(output,"dbg2       mb_data_data_list:             %d\n",
			mb_data_data_list);
		fprintf(output,"dbg2       mb_data_comment_list:          %d\n",
			mb_data_comment_list);
		fprintf(output,"dbg2       mb_data_calibrate_list:        %d\n",
			mb_data_calibrate_list);
		fprintf(output,"dbg2       mb_data_mean_velocity_list:    %d\n",
			mb_data_mean_velocity_list);
		fprintf(output,"dbg2       mb_data_velocity_profile_list: %d\n",
			mb_data_velocity_profile_list);
		fprintf(output,"dbg2       mb_data_standby_list:          %d\n",
			mb_data_standby_list);
		fprintf(output,"dbg2       mb_data_nav_source_list:       %d\n",
			mb_data_nav_source_list);
		}

	/* if help desired then print it and exit */
	if (help)
		{
		fprintf(output,"\n%s\n",help_message);
		fprintf(output,"\nusage: %s\n", usage_message);
		exit(error);
		}

	/* if bad format specified then print it and exit */
	status = mb_format(verbose,&format,&error);
	if (format != MBF_HSATLRAW && format != MBF_HSLDEOIH)
		{
		fprintf(output,"\nProgram <%s> requires complete Hydrosweep DS data stream\n",program_name);
		fprintf(output,"!!Format %d is unacceptable, only formats %d and %d can be used\n",format,MBF_HSATLRAW,MBF_HSLDEOIH);
		fprintf(output,"\nProgram <%s> Terminated\n",
			program_name);
		error = MB_ERROR_BAD_FORMAT;
		exit(error);
		}

	/* initialize reading the input multibeam file */
	if ((status = mb_read_init(
		verbose,file,format,pings,lonflip,bounds,
		btime_i,etime_i,speedmin,timegap,
		&mbio_ptr,&btime_d,&etime_d,
		&beams_bath,&beams_amp,&pixels_ss,&error)) != MB_SUCCESS)
		{
		mb_error(verbose,error,&message);
		fprintf(output,"\nMBIO Error returned from function <mb_read_init>:\n%s\n",message);
		fprintf(output,"\nMultibeam File <%s> not initialized for reading\n",file);
		fprintf(output,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* allocate memory for data arrays */
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(char),(void **)&beamflag,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(double),(void **)&bath,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(double),
				(void **)&bathacrosstrack,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_bath*sizeof(double),
				(void **)&bathalongtrack,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,beams_amp*sizeof(double),(void **)&amp,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,pixels_ss*sizeof(double),(void **)&ss,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,pixels_ss*sizeof(double),
			(void **)&ssacrosstrack,&error);
	status = mb_mallocd(verbose,__FILE__,__LINE__,pixels_ss*sizeof(double),
			(void **)&ssalongtrack,&error);

	/* if error initializing memory then quit */
	if (error != MB_ERROR_NO_ERROR)
		{
		mb_error(verbose,error,&message);
		fprintf(output,"\nMBIO Error allocating data arrays:\n%s\n",message);
		fprintf(output,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* printf out file and format */
	mb_format_description(verbose, &format, format_description, &error);
	fprintf(output,"\nHydrosweep DS Data File:  %s\n",file);
	fprintf(output,"MBIO Data Format ID:  %d\n",format);
	fprintf(output,"%s",format_description);

	/* read and list */
	while (error <= MB_ERROR_NO_ERROR)
		{
		/* read some data */
		error = MB_ERROR_NO_ERROR;
		status = MB_SUCCESS;
		status = mb_get_all(verbose,mbio_ptr,&store_ptr,&kind,
				time_i,&time_d,&navlon,&navlat,
				&speed,&heading,
				&distance,&altitude,&sonardepth,
				&nbath,&namp,&nss,
				beamflag,bath,amp,bathacrosstrack,bathalongtrack,
				ss,ssacrosstrack,ssalongtrack,
				comment,&error);

		/* get data structure pointer */
		store = (struct mbsys_hsds_struct *) store_ptr;

		/* non-survey data do not matter to hsdump */
		if (error >= MB_ERROR_OTHER && error < MB_ERROR_NO_ERROR)
			{
			status = MB_SUCCESS;
			error = MB_ERROR_NO_ERROR;
			}

		/* output error messages */
		if (verbose >= 1 && error <= MB_ERROR_OTHER)
			{
			mb_error(verbose,error,&message);
			fprintf(output,"\nNonfatal MBIO Error:\n%s\n",message);
			}
		else if (verbose >= 1 && error > MB_ERROR_NO_ERROR 
			&& error != MB_ERROR_EOF)
			{
			mb_error(verbose,error,&message);
			fprintf(output,"\nFatal MBIO Error:\n%s\n",message);
			}

		/* deal with survey data record */
		if (kind == MB_DATA_DATA && mb_data_data_list == MB_YES)
			{
			mb_data_data_count++;
			fprintf(output,"\n");
			fprintf(output,"Survey Data Record (ERGNMESS + ERGNSLZT +ERGNAMPL):\n");
			fprintf(output,"  Time:            %2d/%2d/%4d %2.2d:%2.2d:%2.2d\n",
				store->month,store->day,store->year,
				store->hour,store->minute,store->second);
			fprintf(output,"  Alternate Time:   %4d  %4d\n",
				store->alt_minute,store->alt_second);
			fprintf(output,"  Longitude:        %f\n",store->lon);
			fprintf(output,"  Latitude:         %f\n",store->lat);
			fprintf(output,"  Course:           %f\n",
				store->course_true);
			fprintf(output,"  Course On Ground: %f\n",
				store->course_ground);
			fprintf(output,"  Speed:            %f\n",
				store->speed);
			fprintf(output,"  Speed On Ground:  %f\n",
				store->speed_ground);
			fprintf(output,"  Transverse Speed: %f\n",
				store->speed_transverse);
			fprintf(output,"  Speed Reference:  %c%c\n",
				store->speed_reference[0],
				store->speed_reference[1]);
			fprintf(output,"  Roll:             %f\n",
				store->roll);
			fprintf(output,"  Pitch:            %f\n",
				store->pitch);
			fprintf(output,"  Heave:            %f\n",
				store->heave);
			fprintf(output,"  Track:            %d\n",
				store->track);
			fprintf(output,"  Center Depth:     %f\n",
				store->depth_center);
			fprintf(output,"  Depth Scale:      %f\n",
				store->depth_scale);
			fprintf(output,"  Spare:            %d\n",
				store->spare);
			fprintf(output,"  Crosstrack Distances and Depths:\n");
			for (i=0;i<MBSYS_HSDS_BEAMS;i++)
				fprintf(output,"                    %5d %5d\n",
					store->distance[i],store->depth[i]);
			fprintf(output,"  Center Travel Time: %f\n",
				store->time_center);
			fprintf(output,"  Time Scale:       %f\n",
				store->time_scale);
			fprintf(output,"  Travel Times:\n");
			for (i=0;i<MBSYS_HSDS_BEAMS;i++)
				fprintf(output,"            %5d\n",
					store->time[i]);
			fprintf(output,"  Gyro Headings:\n");
			for (i=0;i<11;i++)
				fprintf(output,"            %f\n",
					store->gyro[i]);
			fprintf(output,"  Mode:             %c%c\n",
				store->mode[0],store->mode[1]);
			fprintf(output,"  Transmit Starboard: %d\n",
				store->trans_strbd);
			fprintf(output,"  Transmit Vertical:  %d\n",
				store->trans_vert);
			fprintf(output,"  Transmit Port:      %d\n",
				store->trans_port);
			fprintf(output,"  Pulse Starboard:    %d\n",
				store->pulse_len_strbd);
			fprintf(output,"  Pulse Vertical:     %d\n",
				store->pulse_len_vert);
			fprintf(output,"  Pulse Port:         %d\n",
				store->pulse_len_port);
			fprintf(output,"  Gain Start:         %d\n",
				store->gain_start);
			fprintf(output,"  Compensation Factor:%d\n",
				store->r_compensation_factor);
			fprintf(output,"  Compensation Start: %d\n",
				store->compensation_start);
			fprintf(output,"  Increase Start:     %d\n",
				store->increase_start);
			fprintf(output,"  Near TVC:           %d\n",
				store->tvc_near);
			fprintf(output,"  Far TVC:            %d\n",
				store->tvc_far);
			fprintf(output,"  Near Increase:      %d\n",
				store->increase_int_near);
			fprintf(output,"  Far Increase:       %d\n",
				store->increase_int_far);
			fprintf(output,"  Center Gain:        %d\n",
				store->gain_center);
			fprintf(output,"  Filter Gain:        %f\n",
				store->filter_gain);
			fprintf(output,"  Center Amplitude:   %d\n",
				store->amplitude_center);
			fprintf(output,"  Center Echo Time:   %d\n",
				store->echo_duration_center);
			fprintf(output,"  Echo Scale:         %d\n",
				store->echo_scale_center);

			fprintf(output,"  Amplitudes and Durations:\n");
			for (i=0;i<MBSYS_HSDS_BEAMS;i++)
				fprintf(output,"            %5d %5d\n",
					store->amplitude[i],
					store->echo_duration[i]);
			fprintf(output,"  Echo Gains and Scales:\n");
			for (i=0;i<16;i++)
				fprintf(output,"            %5d %5d\n",
					store->gain[i],
					store->echo_scale[i]);
			}

		/* deal with comment record */
		if (kind == MB_DATA_COMMENT && mb_data_comment_list == MB_YES)
			{
			mb_data_comment_count++;
			fprintf(output,"\n");
			fprintf(output,"Comment Record (LDEOCMNT):\n");
			fprintf(output,"  %s\n",store->comment);
			}

		/* deal with calibrate data record */
		if (kind == MB_DATA_CALIBRATE 
			&& mb_data_calibrate_list == MB_YES)
			{
			mb_data_calibrate_count++;
			fprintf(output,"\n");
			fprintf(output,"Calibrate Data Record (ERGNEICH + ERGNSLZT +ERGNAMPL):\n");
			fprintf(output,"  Time:            %2d/%2d/%4d %2.2d:%2.2d:%2.2d\n",
				store->month,store->day,store->year,
				store->hour,store->minute,store->second);
			fprintf(output,"  Alternate Time:   %4d  %4d\n",
				store->alt_minute,store->alt_second);
			fprintf(output,"  Longitude:        %f\n",store->lon);
			fprintf(output,"  Latitude:         %f\n",store->lat);
			fprintf(output,"  Course:           %f\n",
				store->course_true);
			fprintf(output,"  Course On Ground: %f\n",
				store->course_ground);
			fprintf(output,"  Speed:            %f\n",
				store->speed);
			fprintf(output,"  Speed On Ground:  %f\n",
				store->speed_ground);
			fprintf(output,"  Transverse Speed: %f\n",
				store->speed_transverse);
			fprintf(output,"  Speed Reference:  %c%c\n",
				store->speed_reference[0],
				store->speed_reference[1]);
			fprintf(output,"  Roll:             %f\n",
				store->roll);
			fprintf(output,"  Pitch:            %f\n",
				store->pitch);
			fprintf(output,"  Heave:            %f\n",
				store->heave);
			fprintf(output,"  Track:            %d\n",
				store->track);
			fprintf(output,"  Center Depth:     %f\n",
				store->depth_center);
			fprintf(output,"  Depth Scale:      %f\n",
				store->depth_scale);
			fprintf(output,"  Spare:            %d\n",
				store->spare);
			fprintf(output,"  Crosstrack Distances and Depths:\n");
			for (i=0;i<MBSYS_HSDS_BEAMS;i++)
				fprintf(output,"                    %5d %5d\n",
					store->distance[i],store->depth[i]);
			fprintf(output,"  Center Travel Time: %f\n",
				store->time_center);
			fprintf(output,"  Time Scale:       %f\n",
				store->time_scale);
			fprintf(output,"  Travel Times:\n");
			for (i=0;i<MBSYS_HSDS_BEAMS;i++)
				fprintf(output,"            %5d\n",
					store->time[i]);
			fprintf(output,"  Gyro Headings:\n");
			for (i=0;i<11;i++)
				fprintf(output,"            %f\n",
					store->gyro[i]);
			fprintf(output,"  Mode:             %c%c\n",
				store->mode[0],store->mode[1]);
			fprintf(output,"  Transmit Starboard: %d\n",
				store->trans_strbd);
			fprintf(output,"  Transmit Vertical:  %d\n",
				store->trans_vert);
			fprintf(output,"  Transmit Port:      %d\n",
				store->trans_port);
			fprintf(output,"  Pulse Starboard:    %d\n",
				store->pulse_len_strbd);
			fprintf(output,"  Pulse Vertical:     %d\n",
				store->pulse_len_vert);
			fprintf(output,"  Pulse Port:         %d\n",
				store->pulse_len_port);
			fprintf(output,"  Gain Start:         %d\n",
				store->gain_start);
			fprintf(output,"  Compensation Factor:%d\n",
				store->r_compensation_factor);
			fprintf(output,"  Compensation Start: %d\n",
				store->compensation_start);
			fprintf(output,"  Increase Start:     %d\n",
				store->increase_start);
			fprintf(output,"  Near TVC:           %d\n",
				store->tvc_near);
			fprintf(output,"  Far TVC:            %d\n",
				store->tvc_far);
			fprintf(output,"  Near Increase:      %d\n",
				store->increase_int_near);
			fprintf(output,"  Far Increase:       %d\n",
				store->increase_int_far);
			fprintf(output,"  Center Gain:        %d\n",
				store->gain_center);
			fprintf(output,"  Filter Gain:        %f\n",
				store->filter_gain);
			fprintf(output,"  Center Amplitude:   %d\n",
				store->amplitude_center);
			fprintf(output,"  Center Echo Time:   %d\n",
				store->echo_duration_center);
			fprintf(output,"  Echo Scale:         %d\n",
				store->echo_scale_center);

			fprintf(output,"  Amplitudes and Durations:\n");
			for (i=0;i<MBSYS_HSDS_BEAMS;i++)
				fprintf(output,"            %5d %5d\n",
					store->amplitude[i],
					store->echo_duration[i]);
			fprintf(output,"  Echo Gains and Scales:\n");
			for (i=0;i<16;i++)
				fprintf(output,"            %5d %5d\n",
					store->gain[i],
					store->echo_scale[i]);
			}

		/* deal with mean velocity data record */
		if (kind == MB_DATA_MEAN_VELOCITY 
			&& mb_data_mean_velocity_list == MB_YES)
			{
			mb_data_mean_velocity_count++;
			fprintf(output,"\n");
			fprintf(output,"Mean Water Velocity Record (ERGNHYDI):\n");
			fprintf(output,"  Time:            %2d/%2d/%4d %2.2d:%2.2d:%2.2d\n",
				store->month,store->day,store->year,
				store->hour,store->minute,store->second);
			fprintf(output,"  Alternate Time:   %4d  %4d\n",
				store->alt_minute,store->alt_second);
			fprintf(output,"  Longitude:        %f\n",store->lon);
			fprintf(output,"  Latitude:         %f\n",store->lat);
			fprintf(output,"  Draught:          %f\n",
				store->draught);
			fprintf(output,"  Mean velocity:    %f\n",
				store->vel_mean);
			fprintf(output,"  Keel velocity:    %f\n",
				store->vel_keel);
			fprintf(output,"  Tide:             %f\n",store->tide);
			}

		/* deal with velocity profile data record */
		if (kind == MB_DATA_VELOCITY_PROFILE
			&& mb_data_velocity_profile_list == MB_YES)
			{
			mb_data_velocity_profile_count++;
			fprintf(output,"\n");
			fprintf(output,"Water Velocity Profile Record (ERGNCTDS):\n");
			fprintf(output,"  Time:             %2d/%2d/%4d %2.2d:%2.2d:%2.2d\n",
				store->month,store->day,store->year,
				store->hour,store->minute,store->second);
			fprintf(output,"  Longitude:        %f\n",store->lon);
			fprintf(output,"  Latitude:         %f\n",store->lat);
			fprintf(output,"  Number of points: %d\n",
				store->num_vel);
			fprintf(output,"  Water Velocity Profile:\n");
			for (i=0;i<store->num_vel;i++)
				fprintf(output,"    %f %f\n",
					store->vdepth[i],store->velocity[i]);
			}

		/* deal with standby data record */
		if (kind == MB_DATA_STANDBY
			&& mb_data_standby_list == MB_YES)
			{
			mb_data_standby_count++;
			fprintf(output,"\n");
			fprintf(output,"Standby Data Record (ERGNPARA):\n");
			fprintf(output,"  Time:            %2d/%2d/%4d %2.2d:%2.2d:%2.2d\n",
				store->month,store->day,store->year,
				store->hour,store->minute,store->second);
			fprintf(output,"  Alternate Time:   %4d  %4d\n",
				store->alt_minute,store->alt_second);
			fprintf(output,"  Longitude:        %f\n",store->lon);
			fprintf(output,"  Latitude:         %f\n",store->lat);
			}

		/* deal with navigation source data record */
		if (kind == MB_DATA_NAV_SOURCE
			&& mb_data_nav_source_list == MB_YES)
			{
			mb_data_nav_source_count++;
			fprintf(output,"\n");
			fprintf(output,"Standby Data Record (ERGNPARA):\n");
			fprintf(output,"  Time:            %2d/%2d/%4d %2.2d:%2.2d:%2.2d\n",
				store->month,store->day,store->year,
				store->hour,store->minute,store->second);
			fprintf(output,"  Alternate Time:   %4d  %4d\n",
				store->alt_minute,store->alt_second);
			fprintf(output,"  Longitude:        %f\n",store->lon);
			fprintf(output,"  Latitude:         %f\n",store->lat);
			fprintf(output,"  X Correction:     %f\n",
				store->pos_corr_x);
			fprintf(output,"  Y Correction:     %f\n",
				store->pos_corr_y);
			fprintf(output,"  Sensors:          ");
			for (i=0;i<10;i++)
				fprintf(output,"%c",store->sensors[i]);
			fprintf(output,"\n");
			}

		}

	/* close the file */
	status = mb_close(verbose,&mbio_ptr,&error);

	/* deallocate memory for data arrays */
	mb_freed(verbose,__FILE__,__LINE__,(void **)&beamflag,&error); 
	mb_freed(verbose,__FILE__,__LINE__,(void **)&bath,&error); 
	mb_freed(verbose,__FILE__,__LINE__,(void **)&bathacrosstrack,&error); 
	mb_freed(verbose,__FILE__,__LINE__,(void **)&bathalongtrack,&error); 
	mb_freed(verbose,__FILE__,__LINE__,(void **)&amp,&error); 
	mb_freed(verbose,__FILE__,__LINE__,(void **)&ss,&error); 
	mb_freed(verbose,__FILE__,__LINE__,(void **)&ssacrosstrack,&error); 
	mb_freed(verbose,__FILE__,__LINE__,(void **)&ssalongtrack,&error); 

	/* check memory */
	if (verbose >= 4)
		status = mb_memory_list(verbose,&error);

	/* give the statistics */
	fprintf(output,"\n");
	if (mb_data_data_list == MB_YES)
		fprintf(output,"%d survey data records listed\n",
			mb_data_data_count);
	if (mb_data_comment_list == MB_YES)
		fprintf(output,"%d comment records listed\n",
			mb_data_comment_count);
	if (mb_data_calibrate_list == MB_YES)
		fprintf(output,"%d calibrate data records listed\n",
			mb_data_calibrate_count);
	if (mb_data_mean_velocity_list == MB_YES)
		fprintf(output,"%d mean velocity data records listed\n",
			mb_data_mean_velocity_count);
	if (mb_data_velocity_profile_list == MB_YES)
		fprintf(output,"%d velocity profile data records listed\n",
			mb_data_velocity_profile_count);
	if (mb_data_standby_list == MB_YES)
		fprintf(output,"%d standby data records listed\n",
			mb_data_standby_count);
	if (mb_data_nav_source_list == MB_YES)
		fprintf(output,"%d navigation source data records listed\n",
			mb_data_nav_source_count);

	/* end it all */
	exit(error);
}
Пример #19
0
int main (int argc, char **argv)
{
	/* id variables */
	char program_name[] = "MBrolltimelag";
	char help_message[] = "MBrolltimelag extracts the roll time series and the apparent \nbottom slope time series from swath data, and then calculates \nthe cross correlation between the roll and the slope minus roll \nfor a specified set of time lags.";
	char usage_message[] = "mbrolltimelag -Iswathdata [-Fformat -Krollsource -Nnping -Ooutputname -Snavchannel -Tnlag/lagmin/lagmax -V -H ]";

	/* parsing variables */
	extern char *optarg;
	int	errflg = 0;
	int	c;
	int	help = 0;
	int	flag = 0;

	/* MBIO status variables */
	int	status = MB_SUCCESS;
	int	verbose = 0;
	int	error = MB_ERROR_NO_ERROR;

	/* Files and formats */
	char	swathdata[MB_PATH_MAXLINE];
	char	swathfile[MB_PATH_MAXLINE];
	char	swathroot[MB_PATH_MAXLINE];
	char	outroot[MB_PATH_MAXLINE];
	char	outroot_defined = MB_NO;
	char	xcorfile[MB_PATH_MAXLINE];
	char	xcorfiletot[MB_PATH_MAXLINE];
	char	cmdfile[MB_PATH_MAXLINE];
	char	estimatefile[MB_PATH_MAXLINE];
	char	histfile[MB_PATH_MAXLINE];
	char	fhistfile[MB_PATH_MAXLINE];
	char	modelfile[MB_PATH_MAXLINE];
	int	format = 0;
	int	formatguess = 0;
	FILE	*fp = NULL;
	FILE	*fpx = NULL;
	FILE	*fpf = NULL;
	FILE	*fpt = NULL;
	FILE	*fpe = NULL;
	FILE	*fph = NULL;
	FILE	*fpm = NULL;
	int	read_datalist = MB_NO;
	int	read_data = MB_NO;
	void	*datalist;
	int	look_processed = MB_DATALIST_LOOK_UNSET;
	double	file_weight;

	/* cross correlation parameters */
	int	navchannel = MB_DATA_DATA;
	int	kind = MB_DATA_NONE;
	int	npings = 100;
	double	rthreshold = 0.9;
	int	nlag = 41;
	double	lagstart = -2.0;
	double	lagend = 2.0;
	double	lagmax;
	double	lagstep = 0.05;
	double	*rr = NULL;

	/* slope data */
	int	nslope = 0;
	int	nslopetot = 0;
	int	nslope_alloc = 0;
	double	*slope_time_d = NULL;
	double	*slope_slope = NULL;
	double	*slope_roll = NULL;
	int	nroll = 0;
	int	nroll_alloc = 0;
	double	*roll_time_d = NULL;
	double	*roll_roll = NULL;

	/* timelag histogram array */
	int	*timelaghistogram = NULL;

	double	time_d;
	double	roll;
	double	slope;
	double	timelag;
	double	sumsloperoll;
	double	sumslopesq;
	double	sumrollsq;
	double	slopeminusmean;
	double	rollminusmean;
	double	r;
	double	sum_x, sum_y, sum_xy, sum_x2, sum_y2;
	double	mmm, bbb;

	int	nrollmean;
	double	rollmean;
	double	slopemean;

	double	maxtimelag;
	double	maxr;
	double	peaktimelag;
	double	peakr;
	int	peakk;
	int	peakkmax;
	int	peakksum;
	double	time_d_avg;
	int	nestimate = 0;
	int	nmodel = 0;

	int	nr;
	double	rollint;
	int	found;
	int	nscan;
	int	j0, j1;
	int	i, j, k, l;

	/* set default input */
	strcpy(swathdata, "datalist.mb-1");

	/* process argument list */
	while ((c = getopt(argc, argv, "VvHhC:c:F:f:I:i:K:k:O:o:N:n:S:s:T:t:")) != -1)
	  switch (c)
		{
		case 'H':
		case 'h':
			help++;
			break;
		case 'V':
		case 'v':
			verbose++;
			break;
		case 'C':
		case 'c':
			sscanf (optarg,"%lf", &rthreshold);
			flag++;
			break;
		case 'F':
		case 'f':
			sscanf (optarg,"%d", &format);
			flag++;
			break;
		case 'I':
		case 'i':
			sscanf (optarg,"%s", swathdata);
			flag++;
			break;
		case 'K':
		case 'k':
			sscanf (optarg,"%d", &kind);
			flag++;
			break;
		case 'N':
		case 'n':
			sscanf (optarg,"%d", &npings);
			flag++;
			break;
		case 'O':
		case 'o':
			sscanf (optarg,"%s", outroot);
			outroot_defined = MB_YES;
			flag++;
			break;
		case 'S':
		case 's':
			sscanf (optarg,"%d", &navchannel);
			flag++;
			break;
		case 'T':
		case 't':
			sscanf (optarg,"%d/%lf/%lf", &nlag, &lagstart, &lagend);
			lagmax = MAX(fabs(lagstart), fabs(lagend));
			flag++;
			break;
		case '?':
			errflg++;
		}

	/* if error flagged then print it and exit */
	if (errflg)
		{
		fprintf(stderr,"usage: %s\n", usage_message);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		error = MB_ERROR_BAD_USAGE;
		exit(error);
		}

	/* print starting message */
	if (verbose == 1 || help)
		{
		fprintf(stderr,"\nProgram %s\n",program_name);
		fprintf(stderr,"MB-system Version %s\n",MB_VERSION);
		}

	/* print starting debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  Program <%s>\n",program_name);
		fprintf(stderr,"dbg2  MB-system Version %s\n",MB_VERSION);
		fprintf(stderr,"dbg2  Control Parameters:\n");
		fprintf(stderr,"dbg2       verbose:         %d\n",verbose);
		fprintf(stderr,"dbg2       help:            %d\n",help);
		fprintf(stderr,"dbg2       format:          %d\n",format);
		fprintf(stderr,"dbg2       rthreshold:      %f\n",rthreshold);
		fprintf(stderr,"dbg2       swathdata:       %s\n",swathdata);
		fprintf(stderr,"dbg2       npings:          %d\n",npings);
		fprintf(stderr,"dbg2       nlag:            %d\n",nlag);
		fprintf(stderr,"dbg2       lagstart:        %f\n",lagstart);
		fprintf(stderr,"dbg2       lagend:          %f\n",lagend);
		fprintf(stderr,"dbg2       lagmax:          %f\n",lagmax);
		fprintf(stderr,"dbg2       navchannel:      %d\n",navchannel);
		fprintf(stderr,"dbg2       kind:            %d\n",kind);
		}

	/* if help desired then print it and exit */
	if (help)
		{
		fprintf(stderr,"\n%s\n",help_message);
		fprintf(stderr,"\nusage: %s\n", usage_message);
		exit(error);
		}

	/* get format if required */
	mb_get_format(verbose,swathdata,swathroot,&formatguess,&error);
	if (format == 0)
		format = formatguess;
	if (outroot_defined == MB_NO)
		strcpy(outroot, swathroot);

	/* determine whether to read one file or a list of files */
	if (format < 0)
		read_datalist = MB_YES;

	/* get time lag step */
	lagstep = 2 * lagmax / (nlag - 1);
	status = mb_reallocd(verbose,__FILE__,__LINE__, nlag * sizeof(double), (void **)&rr, &error);
	status = mb_reallocd(verbose,__FILE__,__LINE__, nlag * sizeof(int), (void **)&timelaghistogram, &error);

	/* print out some helpful information */
	if (verbose > 0)
		{
		fprintf(stderr, "Program %s parameters:\n", program_name);
		fprintf(stderr, "  Input:                           %s\n", swathdata);
		fprintf(stderr, "  Format:                          %d\n", format);
		fprintf(stderr, "  Number of pings per estimate:    %d\n", npings);
		fprintf(stderr, "  Number of time lag calculations: %d\n", nlag);
		fprintf(stderr, "  Start time lag reported:         %f\n", lagstart);
		fprintf(stderr, "  End time lag reported:           %f\n", lagend);
		fprintf(stderr, "  Maximum time lag:                %f\n", lagmax);
		fprintf(stderr, "  Time lag step:                   %f\n", lagstep);
		}

	/* first get roll data from the entire swathdata (which can be a datalist ) */
	if (kind > MB_DATA_NONE)
		sprintf(cmdfile, "mbnavlist -I%s -F%d -K%d -OMR", swathdata, format, kind);
	else
		sprintf(cmdfile, "mbnavlist -I%s -F%d -N%d -OMR", swathdata, format, navchannel);
	fprintf(stderr,"\nRunning %s...\n",cmdfile);
	fp = popen(cmdfile, "r");
	while ((nscan = fscanf(fp, "%lf %lf", &time_d, &roll)) == 2)
		{
		if (nroll >= nroll_alloc)
			{
			nroll_alloc += MBRTL_ALLOC_CHUNK;
			status = mb_reallocd(verbose,__FILE__,__LINE__, nroll_alloc * sizeof(double), (void **)&roll_time_d, &error);
			status = mb_reallocd(verbose,__FILE__,__LINE__, nroll_alloc * sizeof(double), (void **)&roll_roll, &error);
			}
		if (nroll == 0 || time_d > roll_time_d[nroll-1])
			{
			roll_time_d[nroll] = time_d;
			roll_roll[nroll] = roll;
			nroll++;
			}
		}
	pclose(fp);
	fprintf(stderr,"%d roll data read from %s\n", nroll, swathdata);

	/* open total cross correlation file */
	if (read_datalist == MB_YES)
		{
		sprintf(xcorfiletot, "%s_xcorr.txt", outroot);
		if ((fpt = fopen(xcorfiletot, "w")) == NULL)
			{
			error = MB_ERROR_OPEN_FAIL;
			fprintf(stderr,"\nUnable to open cross correlation output: %s\n",
				xcorfiletot);
			fprintf(stderr,"\nProgram <%s> Terminated\n",
				program_name);
			exit(error);
			}
		}

	/* open time lag estimate file */
	sprintf(estimatefile, "%s_timelagest.txt", outroot);
	if ((fpe = fopen(estimatefile, "w")) == NULL)
		{
		error = MB_ERROR_OPEN_FAIL;
		fprintf(stderr,"\nUnable to open estimate output: %s\n",
			estimatefile);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* open time lag histogram file */
	sprintf(histfile, "%s_timelaghist.txt", outroot);
	if ((fph = fopen(histfile, "w")) == NULL)
		{
		error = MB_ERROR_OPEN_FAIL;
		fprintf(stderr,"\nUnable to open histogram output: %s\n",
			histfile);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* open time lag model file */
	sprintf(modelfile, "%s_timelagmodel.txt", outroot);
	if ((fpm = fopen(modelfile, "w")) == NULL)
		{
		error = MB_ERROR_OPEN_FAIL;
		fprintf(stderr,"\nUnable to open time lag model output: %s\n",
			modelfile);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* open file list */
	if (read_datalist == MB_YES)
	    {
	    if ((status = mb_datalist_open(verbose,&datalist,
					    swathdata,look_processed,&error)) != MB_SUCCESS)
		{
		error = MB_ERROR_OPEN_FAIL;
		fprintf(stderr,"\nUnable to open data list file: %s\n",
			swathdata);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}
	    if ((status = mb_datalist_read(verbose,datalist,
			    swathfile,&format,&file_weight,&error))
			    == MB_SUCCESS)
		read_data = MB_YES;
	    else
		read_data = MB_NO;
	    }
	/* else copy single filename to be read */
	else
	    {
	    strcpy(swathfile, swathdata);
	    read_data = MB_YES;
	    }

	/* loop over all files to be read */
	while (read_data == MB_YES)
		{
		nestimate = 0;
		nslope = 0;
		time_d_avg = 0.0;
		sprintf(cmdfile, "mblist -I%s -F%d -OMAR", swathfile, format);
		fprintf(stderr,"\nRunning %s...\n",cmdfile);
		fp = popen(cmdfile, "r");
		while ((nscan = fscanf(fp, "%lf %lf %lf", &time_d, &slope, &roll)) == 3)
			{
			if (nslope >= nslope_alloc)
				{
				nslope_alloc += MBRTL_ALLOC_CHUNK;
				status = mb_reallocd(verbose,__FILE__,__LINE__, nslope_alloc * sizeof(double), (void **)&slope_time_d, &error);
				status = mb_reallocd(verbose,__FILE__,__LINE__, nslope_alloc * sizeof(double), (void **)&slope_slope, &error);
				status = mb_reallocd(verbose,__FILE__,__LINE__, nslope_alloc * sizeof(double), (void **)&slope_roll, &error);
				}
			if (nslope == 0 || time_d > slope_time_d[nslope-1])
				{
				slope_time_d[nslope] = time_d;
				time_d_avg += time_d;
				slope_slope[nslope] = roll - slope;
				slope_roll[nslope] = roll;
				nslope++;
				}
			}
		pclose(fp);
		nslopetot += nslope;
		if (nslope > 0)
			time_d_avg /= nslope;
		fprintf(stderr,"%d slope data read from %s\n", nslope, swathfile);

		/* open time lag histogram file */
		sprintf(fhistfile, "%s_timelaghist.txt", swathfile);
		if ((fpf = fopen(fhistfile, "w")) == NULL)
			{
			error = MB_ERROR_OPEN_FAIL;
			fprintf(stderr,"\nUnable to open histogram output: %s\n",
				fhistfile);
			fprintf(stderr,"\nProgram <%s> Terminated\n",
				program_name);
			exit(error);
			}

		/* open cross correlation file */
		sprintf(xcorfile, "%s_xcorr.txt", swathfile);
		if ((fpx = fopen(xcorfile, "w")) == NULL)
			{
			error = MB_ERROR_OPEN_FAIL;
			fprintf(stderr,"\nUnable to open cross correlation output: %s\n",
				xcorfile);
			fprintf(stderr,"\nProgram <%s> Terminated\n",
				program_name);
			exit(error);
			}

		/* initialize time lag histogram */
		for (k=0;k<nlag;k++)
			{
			timelaghistogram[k] = 0;
			}

		/* now do cross correlation calculations */
		for (i=0;i<nslope/npings;i++)
			{
			/* get ping range in this chunk */
			j0 = i * npings;
			j1 = j0 + npings - 1;

			/* get mean slope in this chunk */
			slopemean = 0.0;
			for (j = j0; j <= j1; j++)
				{
				slopemean += slope_slope[j];
				}
			slopemean /= npings;

			/* get mean roll in this chunk */
			rollmean = 0.0;
			nrollmean = 0;
			for (j = 0; j < nroll; j++)
				{
				if ((roll_time_d[j] >= slope_time_d[j0] - lagmax)
					&& (roll_time_d[j] <= slope_time_d[j1] + lagmax))
					{
					rollmean += roll_roll[j];
					nrollmean++;
					}
				}
			if (nrollmean > 0)
				{
				rollmean /= nrollmean;
				}

			/* calculate cross correlation for the specified time lags */
			if (nrollmean > 0)
				{
				fprintf(fpx, ">\n");
				if (fpt != NULL)
					fprintf(fpt, ">\n");
				for (k = 0; k < nlag; k++)
					{
					timelag = -lagmax + k * lagstep;
					sumsloperoll = 0.0;
					sumslopesq = 0.0;
					sumrollsq = 0.0;
					nr = 0;

					for (j = j0; j <= j1; j++)
						{
						/* interpolate lagged roll value */
						found = MB_NO;
						time_d = slope_time_d[j] + timelag;
						for (l = nr; l < nroll - 1 && found == MB_NO; l++)
							{
							if (time_d >= roll_time_d[l]
								&& time_d <= roll_time_d[l+1])
								{
								nr = l;
								found = MB_YES;
								}
							}
						if (found == MB_NO && time_d < roll_time_d[0])
							{
							rollint = roll_roll[0];
							}
						else if (found == MB_NO && time_d > roll_time_d[nroll - 1])
							{
							rollint = roll_roll[nroll - 1];
							}
						else
							{
							rollint = roll_roll[nr] + (roll_roll[nr+1] - roll_roll[nr])
										* (time_d - roll_time_d[nr])
										/ (roll_time_d[nr+1] - roll_time_d[nr]);
							}

						/* add to sums */
						slopeminusmean = (slope_slope[j] - slopemean);
						rollminusmean = (rollint - rollmean);
						sumslopesq += slopeminusmean * slopeminusmean;
						sumrollsq += rollminusmean * rollminusmean;
						sumsloperoll += slopeminusmean * rollminusmean;
						}

					r = sumsloperoll / sqrt(sumslopesq) / sqrt(sumrollsq);
					rr[k] = r;

					/* output results */
					fprintf(fpx, "%5.3f %5.3f \n", timelag, r);
					if (fpt != NULL)
						fprintf(fpt, "%5.3f %5.3f \n", timelag, r);
					}

				/* get max and closest peak cross correlations */
				maxr = 0.0;
				peakr = 0.0;
				peaktimelag = 0.0;
				for (k = 0; k < nlag; k++)
					{
					timelag = -lagmax + k * lagstep;
					if (timelag >= lagstart && timelag <= lagend)
						{
						if (rr[k] > maxr)
							{
							maxr = rr[k];
							maxtimelag = timelag;
							}
						if (k == 0)
							{
							peakk = k;
							peakr = rr[k];
							peaktimelag = timelag;
							}
						else if (k < nlag - 1
							&& rr[k] > 0.0
							&& rr[k] > rr[k-1]
							&& rr[k] > rr[k+1]
							&& fabs(timelag) < fabs(peaktimelag))
							{
							peakk = k;
							peakr = rr[k];
							peaktimelag = timelag;
							}
						else if (k == nlag - 1
							&& peaktimelag == -lagmax
							&& rr[k] > peakr)
							{
							peakk = k;
							peakr = rr[k];
							peaktimelag = timelag;
							}
						}
					}
				}

			/* print out best correlated time lag estimates */
			if (peakr > rthreshold)
				{
				timelaghistogram[peakk]++;
				}

			/* augment histogram */
			if (peakr > rthreshold)
				{
				fprintf(fpe, "%10.3f %6.3f\n", slope_time_d[(j0+j1)/2], peaktimelag);
				fprintf(fpf, "%6.3f\n", peaktimelag);
				fprintf(fph, "%6.3f\n", peaktimelag);
				sum_x += slope_time_d[(j0+j1)/2];
				sum_y += peaktimelag;
				sum_xy += slope_time_d[(j0+j1)/2] * peaktimelag;
				sum_x2 += slope_time_d[(j0+j1)/2] * slope_time_d[(j0+j1)/2];
				sum_y2 += peaktimelag * peaktimelag;
				nestimate++;
				}

			/* print out max and closest peak cross correlations */
			if (verbose > 0)
				{
				fprintf(stderr, "cross correlation pings %5d - %5d: max: %6.3f %5.3f  peak: %6.3f %5.3f\n",
				j0, j1, maxtimelag, maxr, peaktimelag, peakr);
				}
			}

		/* close cross correlation and histogram files */
		fclose(fpx);
		fclose(fpf);

		/* generate plot shellscript for cross correlation file */
		sprintf(cmdfile, "mbm_xyplot -I%s -N", xcorfile);
		fprintf(stderr, "Running: %s...\n", cmdfile);
		system(cmdfile);

		/* generate plot shellscript for time lag histogram */
		sprintf(cmdfile, "mbm_histplot -I%s -C%g -L\"Frequency Histogram of %s:Time Lag (sec):Frequency:\"",
				fhistfile, lagstep, swathfile);
		fprintf(stderr, "Running: %s...\n", cmdfile);
		system(cmdfile);

		/* output peak time lag */
		peakk = 0;
		peakkmax = 0;
		peakksum = 0;
		timelag = 0.0;
		for (k=0;k<nlag;k++)
			{
			if (timelaghistogram[k] > peakkmax)
				{
				peakkmax = timelaghistogram[k];
				peakk = k;
				}
			peakksum += timelaghistogram[k];
			}
		if (nslope > 0 && peakksum > 0 && peakkmax > 1
			&& peakkmax > peakksum / 5)
			{
			timelag = -lagmax + peakk * lagstep;
			fprintf(fpm, "%f %f\n", time_d_avg, timelag);
			nmodel++;
			fprintf(stderr,"Time lag model point: %f %f | nslope:%d peakksum:%d peakkmax:%d\n",
				time_d_avg, timelag, nslope, peakksum, peakkmax);
			}
		else
			{
			if (peakkmax > 0)
				timelag = -lagmax + peakk * lagstep;
			fprintf(stderr,"Time lag model point: %f %f | nslope:%d peakksum:%d peakkmax:%d | REJECTED\n",
				time_d_avg, timelag, nslope, peakksum, peakkmax);
			}

		/* figure out whether and what to read next */
        	if (read_datalist == MB_YES)
                	{
			if ((status = mb_datalist_read(verbose,datalist,
				    swathfile,&format,&file_weight,&error))
				    == MB_SUCCESS)
                        	read_data = MB_YES;
                	else
                        	read_data = MB_NO;
                	}
        	else
                	{
                	read_data = MB_NO;
                	}

		/* end loop over files in list */
		}
	if (read_datalist == MB_YES)
		mb_datalist_close(verbose,&datalist,&error);

	/* close cross correlation file */
	if (read_datalist == MB_YES)
		fclose(fpt);

	/* close estimate file */
	fclose(fpe);

	/* close histogram file */
	fclose(fph);

	/* close time lag model file */
	fclose(fpm);

	/* generate plot shellscript for cross correlation file */
	if (read_datalist == MB_YES)
		{
		sprintf(cmdfile, "mbm_xyplot -I%s -N", xcorfiletot);
		fprintf(stderr, "Running: %s...\n", cmdfile);
		system(cmdfile);
		}

	/* generate plot shellscript for time lag histogram */
	sprintf(cmdfile, "mbm_histplot -I%s -C%g -L\"Frequency Histogram of %s:Time Lag (sec):Frequency:\"",
			histfile, lagstep, swathdata);
	fprintf(stderr, "Running: %s...\n", cmdfile);
	system(cmdfile);

	/* generate plot shellscript for time lag model if it exists */
	if (nmodel > 1 || nestimate > 1)
		{
		mmm = (nestimate * sum_xy - sum_x * sum_y) / (nestimate * sum_x2 - sum_x * sum_x);
		bbb = (sum_y - mmm * sum_x) / nestimate;

		sprintf(cmdfile, "mbm_xyplot -I%s -ISc0.05:%s -I%s -ISc0.1:%s -L\"Time lag model of %s:Time (sec):Time Lag (sec):\"",
				modelfile, estimatefile, modelfile, modelfile, swathdata);
		fprintf(stderr, "Running: %s...\n", cmdfile);
		system(cmdfile);
		}

	/* deallocate memory for data arrays */
	mb_freed(verbose,__FILE__,__LINE__,(void **)&slope_time_d,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&slope_slope,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&slope_roll,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&roll_time_d,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&roll_roll,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&rr,&error);
	mb_freed(verbose,__FILE__,__LINE__,(void **)&timelaghistogram,&error);

	/* check memory */
	if (verbose >= 4)
		status = mb_memory_list(verbose,&error);

	/* give the statistics */
	if (verbose >= 1)
		{
		fprintf(stderr,"\n%d input roll records\n", nroll);
		fprintf(stderr,"%d input slope\n", nslopetot);
		}

	/* end it all */
	exit(error);
}
Пример #20
0
/*--------------------------------------------------------------------------*/
int mb_spline_init(int verbose, double *x, double *y,
	int n, double yp1, double ypn, double *y2, int *error)
{
	char	*function_name = "mb_spline_init";
	int	status = MB_SUCCESS;
	int	i, k;
	double	p, qn, sig, un, *u;

	/* print input debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  MBBA function <%s> called\n",function_name);
		fprintf(stderr,"dbg2  Revision id: %s\n",rcs_id);
		fprintf(stderr,"dbg2  Input arguments:\n");
		fprintf(stderr,"dbg2       verbose:          %d\n",verbose);
		fprintf(stderr,"dbg2       x:                %p\n",x);
		fprintf(stderr,"dbg2       y:                %p\n",y);
		fprintf(stderr,"dbg2       n:                %d\n",n);
		fprintf(stderr,"dbg2       yp1:              %f\n",yp1);
		fprintf(stderr,"dbg2       ypn:              %f\n",ypn);
		fprintf(stderr,"dbg2       y2:               %p\n",y2);
		}

	/* check for n > 2 */
	if (n < 3)
		{
		status = MB_FAILURE;
		*error = MB_ERROR_NOT_ENOUGH_DATA;
		}

	/* allocate memory for working vector */
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__,__LINE__, n * sizeof(double), (void **)&u, error);

	/* set up spline interpolation coefficients */
	if (status == MB_SUCCESS)
		{
		if (yp1 > 0.99e30)
			y2[1]=u[1]=0.0;
		else
			{
			y2[1] = -0.5;
			u[1]=(3.0/(x[2]-x[1]))*((y[2]-y[1])/(x[2]-x[1])-yp1);
			}
		for (i=2;i<=n-1;i++)
			{
			sig=(x[i]-x[i-1])/(x[i+1]-x[i-1]);
			p=sig*y2[i-1]+2.0;
			y2[i]=(sig-1.0)/p;
			u[i]=(y[i+1]-y[i])/(x[i+1]-x[i]) - (y[i]-y[i-1])/(x[i]-x[i-1]);
			u[i]=(6.0*u[i]/(x[i+1]-x[i-1])-sig*u[i-1])/p;
			}
		if (ypn > 0.99e30)
			qn=un=0.0;
		else
			{
			qn=0.5;
			un=(3.0/(x[n]-x[n-1]))*(ypn-(y[n]-y[n-1])/(x[n]-x[n-1]));
			}
		y2[n]=(un-qn*u[n-1])/(qn*y2[n-1]+1.0);
		for (k=n-1;k>=1;k--)
			y2[k]=y2[k]*y2[k+1]+u[k];

		/* deallocate memory for vector */
		status = mb_freed(verbose,__FILE__, __LINE__, (void **)&u, error);
		}

	/* print output debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  MBIO function <%s> completed\n",function_name);
		fprintf(stderr,"dbg2  Return values:\n");
		fprintf(stderr,"dbg2       error:      %d\n",*error);
		fprintf(stderr,"dbg2  Return status:\n");
		fprintf(stderr,"dbg2       status:     %d\n",status);
		}

	return(status);
}
Пример #21
0
/*------------------------------------------------------------------------------*/
int mbview_freeprofilearrays(int verbose, 
			double	**distance,
			double	**zdata,
			int	**boundary,
			double	**xlon,
			double	**ylat,
			double	**distovertopo,
			double	**bearing,
			double	**slope,
			int *error)

{
	/* local variables */
	char	*function_name = "mbview_freeprofilearrays";
	int	status = MB_SUCCESS;

	/* print starting debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  MBIO function <%s> called\n",
			function_name);
		fprintf(stderr,"dbg2  MB-system Version %s\n",MB_VERSION);
		fprintf(stderr,"dbg2  Input arguments:\n");
		fprintf(stderr,"dbg2       verbose:                   %d\n", verbose);
		fprintf(stderr,"dbg2       distance:                  %lu\n", (size_t)*distance);
		fprintf(stderr,"dbg2       zdata:                     %lu\n", (size_t)*zdata);
		fprintf(stderr,"dbg2       boundary:                  %lu\n", (size_t)*boundary);
		fprintf(stderr,"dbg2       xlon:                      %lu\n", (size_t)*xlon);
		fprintf(stderr,"dbg2       ylat:                      %lu\n", (size_t)*ylat);
		fprintf(stderr,"dbg2       distovertopo:              %lu\n", (size_t)*distovertopo);
		fprintf(stderr,"dbg2       bearing:                   %lu\n", (size_t)*bearing);
		fprintf(stderr,"dbg2       slope:                     %lu\n", (size_t)*slope);
		}

	/* free the arrays using mb_free */
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)distance,error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)zdata,error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)boundary,error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)xlon,error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)ylat,error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)distovertopo,error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)bearing,error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)slope,error);

	/* print output debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  MBIO function <%s> completed\n",
			function_name);
		fprintf(stderr,"dbg2  Return values:\n");
		fprintf(stderr,"dbg2       distance:                  %lu\n", (size_t)*distance);
		fprintf(stderr,"dbg2       zdata:                     %lu\n", (size_t)*zdata);
		fprintf(stderr,"dbg2       boundary:                  %lu\n", (size_t)*boundary);
		fprintf(stderr,"dbg2       xlon:                      %lu\n", (size_t)*xlon);
		fprintf(stderr,"dbg2       ylat:                      %lu\n", (size_t)*ylat);
		fprintf(stderr,"dbg2       distovertopo:              %lu\n", (size_t)*distovertopo);
		fprintf(stderr,"dbg2       bearing:                   %lu\n", (size_t)*bearing);
		fprintf(stderr,"dbg2       slope:                     %lu\n", (size_t)*slope);
		fprintf(stderr,"dbg2       error:                     %d\n", *error);
		fprintf(stderr,"dbg2  Return status:\n");
		fprintf(stderr,"dbg2       status:                    %d\n", status);
		}

	/* return */
	return(status);
}
Пример #22
0
/*------------------------------------------------------------------------------*/
int mbview_vector_delete(size_t instance, int ivec) {

	/* local variables */
	char *function_name = "mbview_vector_delete";
	int error = MB_ERROR_NO_ERROR;
	int status = MB_SUCCESS;
	struct mbview_world_struct *view;
	struct mbview_struct *data;
	int i;

	/* print starting debug statements */
	if (mbv_verbose >= 2) {
		fprintf(stderr, "\ndbg2  MBIO function <%s> called\n", function_name);
		fprintf(stderr, "dbg2  MB-system Version %s\n", MB_VERSION);
		fprintf(stderr, "dbg2  Input arguments:\n");
		fprintf(stderr, "dbg2       ivec:            %d\n", ivec);
		fprintf(stderr, "dbg2       instance:         %zu\n", instance);
	}

	/* get view */
	view = &(mbviews[instance]);
	data = &(view->data);

	/* delete vec if its the same as previously selected */
	if (ivec >= 0 && ivec < shared.shareddata.nvector) {
		/* free memory for deleted vec */
		mb_freed(mbv_verbose, __FILE__, __LINE__, (void **)&(shared.shareddata.vectors[ivec].vectorpts), &error);
		mb_freed(mbv_verbose, __FILE__, __LINE__, (void **)&(shared.shareddata.vectors[ivec].segments), &error);

		/* move vec data if necessary */
		for (i = ivec; i < shared.shareddata.nvector - 1; i++) {
			shared.shareddata.vectors[i] = shared.shareddata.vectors[i + 1];
		}

		/* rest last vec */
		shared.shareddata.vectors[shared.shareddata.nvector - 1].color = MBV_COLOR_RED;
		shared.shareddata.vectors[shared.shareddata.nvector - 1].size = 4;
		shared.shareddata.vectors[shared.shareddata.nvector - 1].name[0] = '\0';
		shared.shareddata.vectors[shared.shareddata.nvector - 1].npoints = 0;
		shared.shareddata.vectors[shared.shareddata.nvector - 1].npoints_alloc = 0;
		shared.shareddata.vectors[shared.shareddata.nvector - 1].vectorpts = NULL;
		shared.shareddata.vectors[shared.shareddata.nvector - 1].segments = NULL;

		/* set nvector */
		shared.shareddata.nvector--;

		/* no selection */
		shared.shareddata.vector_selected = MBV_SELECT_NONE;
	}
	else {
		status = MB_FAILURE;
	}

	/* print output debug statements */
	if (mbv_verbose >= 2) {
		fprintf(stderr, "\ndbg2  MBIO function <%s> completed\n", function_name);
		fprintf(stderr, "dbg2  Return status:\n");
		fprintf(stderr, "dbg2       status:          %d\n", status);
	}

	/* return */
	return (status);
}
Пример #23
0
/*--------------------------------------------------------------------*/
int mb_read_init(int verbose, char *file,
		int format, int pings, int lonflip, double bounds[4],
		int btime_i[7], int etime_i[7],
		double speedmin, double timegap,
		void **mbio_ptr, double *btime_d, double *etime_d,
		int *beams_bath, int *beams_amp, int *pixels_ss,
		int *error)
{
	char	*function_name = "mb_read_init";
	int	status;
	struct mb_io_struct *mb_io_ptr;
	int	status_save;
	int	error_save;
	int	sapi_status;
	char	*lastslash;
	char	path[MB_PATH_MAXLINE], name[MB_PATH_MAXLINE];
	char	prjfile[MB_PATH_MAXLINE];
	char	projection_id[MB_NAME_LENGTH];
	int	proj_status;
	FILE	*pfp;
	struct stat file_status;
	int	fstat;
	int	nscan;
	int	i;
	char	*stdin_string = "stdin";

	/* print input debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  MBIO function <%s> called\n",function_name);
		fprintf(stderr,"dbg2  Revision id: %s\n",rcs_id);
		fprintf(stderr,"dbg2  Input arguments:\n");
		fprintf(stderr,"dbg2       verbose:    %d\n",verbose);
		fprintf(stderr,"dbg2       file:       %s\n",file);
		fprintf(stderr,"dbg2       format:     %d\n",format);
		fprintf(stderr,"dbg2       pings:      %d\n",pings);
		fprintf(stderr,"dbg2       lonflip:    %d\n",lonflip);
		fprintf(stderr,"dbg2       bounds[0]:  %f\n",bounds[0]);
		fprintf(stderr,"dbg2       bounds[1]:  %f\n",bounds[1]);
		fprintf(stderr,"dbg2       bounds[2]:  %f\n",bounds[2]);
		fprintf(stderr,"dbg2       bounds[3]:  %f\n",bounds[3]);
		fprintf(stderr,"dbg2       btime_i[0]: %d\n",btime_i[0]);
		fprintf(stderr,"dbg2       btime_i[1]: %d\n",btime_i[1]);
		fprintf(stderr,"dbg2       btime_i[2]: %d\n",btime_i[2]);
		fprintf(stderr,"dbg2       btime_i[3]: %d\n",btime_i[3]);
		fprintf(stderr,"dbg2       btime_i[4]: %d\n",btime_i[4]);
		fprintf(stderr,"dbg2       btime_i[5]: %d\n",btime_i[5]);
		fprintf(stderr,"dbg2       btime_i[6]: %d\n",btime_i[6]);
		fprintf(stderr,"dbg2       etime_i[0]: %d\n",etime_i[0]);
		fprintf(stderr,"dbg2       etime_i[1]: %d\n",etime_i[1]);
		fprintf(stderr,"dbg2       etime_i[2]: %d\n",etime_i[2]);
		fprintf(stderr,"dbg2       etime_i[3]: %d\n",etime_i[3]);
		fprintf(stderr,"dbg2       etime_i[4]: %d\n",etime_i[4]);
		fprintf(stderr,"dbg2       etime_i[5]: %d\n",etime_i[5]);
		fprintf(stderr,"dbg2       etime_i[6]: %d\n",etime_i[6]);
		fprintf(stderr,"dbg2       speedmin:   %f\n",speedmin);
		fprintf(stderr,"dbg2       timegap:    %f\n",timegap);
		}

	/* allocate memory for mbio descriptor */
	status = mb_mallocd(verbose,__FILE__, __LINE__,sizeof(struct mb_io_struct),
				(void **) mbio_ptr,error);
	if (status == MB_SUCCESS)
		{
		memset(*mbio_ptr, 0, sizeof(struct mb_io_struct));
		mb_io_ptr = (struct mb_io_struct *) *mbio_ptr;
		}

	/* set system byte order flag */
	if (status == MB_SUCCESS)
		{
		mb_io_ptr->byteswapped = mb_swap_check();
		}

	/* get format information */
	if (status == MB_SUCCESS)
		{
		status = mb_format_register(verbose, &format,
					*mbio_ptr, error);
		}

	/* quit if there is a problem */
	if (status == MB_FAILURE)
		{
		/* free memory for mbio descriptor */
		if (mbio_ptr != NULL)
			{
			status_save = status;
			error_save = *error;
			status = mb_freed(verbose,__FILE__, __LINE__,(void **)mbio_ptr,error);
			status = status_save;
			*error = error_save;
			}

		/* output debug information */
		if (verbose >= 2)
			{
			fprintf(stderr,"\ndbg2  MBIO function <%s> terminated with error\n",
				function_name);
			fprintf(stderr,"dbg2  Return values:\n");
			fprintf(stderr,"dbg2       error:      %d\n",*error);
			fprintf(stderr,"dbg2  Return status:\n");
			fprintf(stderr,"dbg2       status:  %d\n",status);
			}
		return(status);
		}

	/* initialize file access for the mbio descriptor */
	mb_io_ptr->filemode = MB_FILEMODE_READ;
	mb_io_ptr->mbfp = NULL;
	strcpy(mb_io_ptr->file,file);
	mb_io_ptr->file_pos = 0;
	mb_io_ptr->file_bytes = 0;
	mb_io_ptr->mbfp2 = NULL;
	strcpy(mb_io_ptr->file2,"\0");
	mb_io_ptr->file2_pos = 0;
	mb_io_ptr->file2_bytes = 0;
	mb_io_ptr->mbfp3 = NULL;
	strcpy(mb_io_ptr->file3,"\0");
	mb_io_ptr->file3_pos = 0;
	mb_io_ptr->file3_bytes = 0;
	mb_io_ptr->ncid = 0;
#ifdef WITH_GSF
	mb_io_ptr->gsfid = 0;
#else
        /* TODO: possibly set to -666 */
#endif
	mb_io_ptr->xdrs = NULL;
	mb_io_ptr->xdrs2 = NULL;
	mb_io_ptr->xdrs3 = NULL;

	/* load control parameters into the mbio descriptor */
	mb_io_ptr->format = format;
	mb_io_ptr->pings = pings;
	mb_io_ptr->lonflip = lonflip;
	for (i=0;i<4;i++)
		mb_io_ptr->bounds[i] = bounds[i];
	for (i=0;i<7;i++)
		{
		mb_io_ptr->btime_i[i] = btime_i[i];
		mb_io_ptr->etime_i[i] = etime_i[i];
		}
	mb_io_ptr->speedmin = speedmin;
	mb_io_ptr->timegap = timegap;

	/* get mbio internal time */
	status = mb_get_time(verbose,mb_io_ptr->btime_i,btime_d);
	status = mb_get_time(verbose,mb_io_ptr->etime_i,etime_d);
	mb_io_ptr->btime_d = *btime_d;
	mb_io_ptr->etime_d = *etime_d;

	/* set the number of beams and allocate storage arrays */
	*beams_bath = mb_io_ptr->beams_bath_max;
	*beams_amp = mb_io_ptr->beams_amp_max;
	*pixels_ss = mb_io_ptr->pixels_ss_max;
	mb_io_ptr->new_beams_bath = 0;
	mb_io_ptr->new_beams_amp = 0;
	mb_io_ptr->new_pixels_ss = 0;
	if (verbose >= 4)
		{
		fprintf(stderr,"\ndbg4  Beam and pixel dimensions set in MBIO function <%s>\n",
				function_name);
		fprintf(stderr,"dbg4       beams_bath: %d\n",
			mb_io_ptr->beams_bath_max);
		fprintf(stderr,"dbg4       beams_amp:  %d\n",
			mb_io_ptr->beams_amp_max);
		fprintf(stderr,"dbg4       pixels_ss:  %d\n",
			mb_io_ptr->pixels_ss_max);
		}

	/* initialize pointers */
	mb_io_ptr->raw_data = NULL;
	mb_io_ptr->store_data = NULL;
	mb_io_ptr->beamflag = NULL;
	mb_io_ptr->bath = NULL;
	mb_io_ptr->amp = NULL;
	mb_io_ptr->bath_acrosstrack = NULL;
	mb_io_ptr->bath_alongtrack = NULL;
	mb_io_ptr->bath_num = NULL;
	mb_io_ptr->amp_num = NULL;
	mb_io_ptr->ss = NULL;
	mb_io_ptr->ss_acrosstrack = NULL;
	mb_io_ptr->ss_alongtrack = NULL;
	mb_io_ptr->ss_num = NULL;
	mb_io_ptr->new_beamflag = NULL;
	mb_io_ptr->new_bath = NULL;
	mb_io_ptr->new_amp = NULL;
	mb_io_ptr->new_bath_acrosstrack = NULL;
	mb_io_ptr->new_bath_alongtrack = NULL;
	mb_io_ptr->new_ss = NULL;
	mb_io_ptr->new_ss_acrosstrack = NULL;
	mb_io_ptr->new_ss_alongtrack = NULL;

	/* initialize projection parameters */
	mb_io_ptr->projection_initialized = MB_NO;
	mb_io_ptr->projection_id[0] = '\0';
	mb_io_ptr->pjptr = NULL;

	/* initialize ancillary variables used
		to save information in certain cases */
	mb_io_ptr->save_flag = MB_NO;
	mb_io_ptr->save_label_flag = MB_NO;
	mb_io_ptr->save1 = 0;
	mb_io_ptr->save2 = 0;
	mb_io_ptr->save3 = 0;
	mb_io_ptr->save4 = 0;
	mb_io_ptr->save5 = 0;
	mb_io_ptr->save6 = 0;
	mb_io_ptr->save7 = 0;
	mb_io_ptr->save8 = 0;
	mb_io_ptr->save9 = 0;
	mb_io_ptr->save10 = 0;
	mb_io_ptr->save11 = 0;
	mb_io_ptr->save12 = 0;
	mb_io_ptr->save13 = 0;
	mb_io_ptr->save14 = 0;
	mb_io_ptr->saved1 = 0;
	mb_io_ptr->saved2 = 0;
	mb_io_ptr->saved3 = 0;
	mb_io_ptr->saved4 = 0;
	mb_io_ptr->saved5 = 0;
	mb_io_ptr->saveptr1 = NULL;
	mb_io_ptr->saveptr2 = NULL;

	/* allocate arrays */
	mb_io_ptr->beams_bath_alloc = mb_io_ptr->beams_bath_max;
	mb_io_ptr->beams_amp_alloc = mb_io_ptr->beams_amp_max;
	mb_io_ptr->pixels_ss_alloc = mb_io_ptr->pixels_ss_max;
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->beams_bath_alloc*sizeof(char),
				(void **) &mb_io_ptr->beamflag,error);
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->beams_bath_alloc*sizeof(double),
				(void **) &mb_io_ptr->bath,error);
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->beams_amp_alloc*sizeof(double),
				(void **) &mb_io_ptr->amp,error);
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->beams_bath_alloc*sizeof(double),
				(void **) &mb_io_ptr->bath_acrosstrack,error);
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->beams_bath_alloc*sizeof(double),
				(void **) &mb_io_ptr->bath_alongtrack,error);
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->beams_bath_alloc*sizeof(int),
				(void **) &mb_io_ptr->bath_num,error);
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->beams_amp_alloc*sizeof(int),
				(void **) &mb_io_ptr->amp_num,error);
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->pixels_ss_alloc*sizeof(double),
				(void **) &mb_io_ptr->ss,error);
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->pixels_ss_alloc*sizeof(double),
				(void **) &mb_io_ptr->ss_acrosstrack,error);
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->pixels_ss_alloc*sizeof(double),
				(void **) &mb_io_ptr->ss_alongtrack,error);
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->pixels_ss_alloc*sizeof(int),
				(void **) &mb_io_ptr->ss_num,error);
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->beams_bath_alloc*sizeof(char),
				(void **) &mb_io_ptr->new_beamflag,error);
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->beams_bath_alloc*sizeof(double),
				(void **) &mb_io_ptr->new_bath,error);
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->beams_amp_alloc*sizeof(double),
				(void **) &mb_io_ptr->new_amp,error);
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->beams_bath_alloc*sizeof(double),
				(void **) &mb_io_ptr->new_bath_acrosstrack,error);
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->beams_bath_alloc*sizeof(double),
				(void **) &mb_io_ptr->new_bath_alongtrack,error);
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->pixels_ss_alloc*sizeof(double),
				(void **) &mb_io_ptr->new_ss,error);
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->pixels_ss_alloc*sizeof(double),
				(void **) &mb_io_ptr->new_ss_acrosstrack,error);
	if (status == MB_SUCCESS)
		status = mb_mallocd(verbose,__FILE__, __LINE__,mb_io_ptr->pixels_ss_alloc*sizeof(double),
				(void **) &mb_io_ptr->new_ss_alongtrack,error);

	/* call routine to allocate memory for format dependent i/o */
	if (status == MB_SUCCESS)
		status = (*mb_io_ptr->mb_io_format_alloc)(verbose,*mbio_ptr,error);

	/* deal with a memory allocation failure */
	if (status == MB_FAILURE)
		{
		status = mb_deall_ioarrays(verbose, mbio_ptr, error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr,error);
		mb_io_ptr->beams_bath_alloc = 0;
		mb_io_ptr->beams_amp_alloc = 0;
		mb_io_ptr->pixels_ss_alloc = 0;
		status = MB_FAILURE;
		*error = MB_ERROR_MEMORY_FAIL;
		if (verbose >= 2)
			{
			fprintf(stderr,"\ndbg2  MBIO function <%s> terminated with error\n",
				function_name);
			fprintf(stderr,"dbg2  Return values:\n");
			fprintf(stderr,"dbg2       error:      %d\n",*error);
			fprintf(stderr,"dbg2  Return status:\n");
			fprintf(stderr,"dbg2       status:  %d\n",status);
			}
		return(status);
		}

	/* handle normal or xdr files to be opened
	   directly with fopen */
	if (mb_io_ptr->filetype == MB_FILETYPE_NORMAL
	    || mb_io_ptr->filetype == MB_FILETYPE_XDR)
	    {
	    /* open the first file */
	    if (strncmp(file,stdin_string,5) == 0)
		mb_io_ptr->mbfp = stdin;
	    else
		if ((mb_io_ptr->mbfp = fopen(mb_io_ptr->file, "r")) == NULL)
		    {
		    *error = MB_ERROR_OPEN_FAIL;
		    status = MB_FAILURE;
		    }

	    /* open the second file if required */
	    if (status == MB_SUCCESS
		&& mb_io_ptr->numfile >= 2)
		{
		if ((mb_io_ptr->mbfp2 = fopen(mb_io_ptr->file2, "r")) == NULL)
		    {
		    *error = MB_ERROR_OPEN_FAIL;
		    status = MB_FAILURE;
		    }
		}

	    /* or open the second file if desired and possible */
	    else if (status == MB_SUCCESS
		&& mb_io_ptr->numfile <= -2)
		{
		if ((fstat = stat(mb_io_ptr->file2, &file_status)) == 0
		    && (file_status.st_mode & S_IFMT) != S_IFDIR
		    && file_status.st_size > 0)
			mb_io_ptr->mbfp2 = fopen(mb_io_ptr->file2, "r");
		}

	    /* open the third file if required */
	    if (status == MB_SUCCESS
		&& mb_io_ptr->numfile >= 3)
		{
		if ((mb_io_ptr->mbfp3 = fopen(mb_io_ptr->file3, "r")) == NULL)
		    {
		    *error = MB_ERROR_OPEN_FAIL;
		    status = MB_FAILURE;
		    }
		}

	    /* or open the third file if desired and possible */
	    else if (status == MB_SUCCESS
		&& mb_io_ptr->numfile <= -3)
		{
		if ((fstat = stat(mb_io_ptr->file2, &file_status)) == 0
		    && (file_status.st_mode & S_IFMT) != S_IFDIR
		    && file_status.st_size > 0)
			mb_io_ptr->mbfp3 = fopen(mb_io_ptr->file3, "r");
		}

	    /* if needed, initialize XDR stream */
	    if (status == MB_SUCCESS
		&& mb_io_ptr->filetype == MB_FILETYPE_XDR)
		{
		status = mb_mallocd(verbose,__FILE__, __LINE__,sizeof(XDR),
				(void **) &mb_io_ptr->xdrs,error);
		if (status == MB_SUCCESS)
		    {
		    xdrstdio_create((XDR *)mb_io_ptr->xdrs,
			    mb_io_ptr->mbfp, XDR_DECODE);
		    }
		else
		    {
		    status = MB_FAILURE;
		    *error = MB_ERROR_MEMORY_FAIL;
		    }
		}

	    /* if needed, initialize second XDR stream */
	    if (status == MB_SUCCESS
		&& mb_io_ptr->filetype == MB_FILETYPE_XDR
		&& (mb_io_ptr->numfile >= 2 || mb_io_ptr->numfile <= -2)
		&& mb_io_ptr->mbfp2 != NULL)
		{
		status = mb_mallocd(verbose,__FILE__, __LINE__,sizeof(XDR),
				(void **) &mb_io_ptr->xdrs2,error);
		if (status == MB_SUCCESS)
		    {
		    xdrstdio_create((XDR *)mb_io_ptr->xdrs2,
			    mb_io_ptr->mbfp2, XDR_DECODE);
		    }
		else
		    {
		    status = MB_FAILURE;
		    *error = MB_ERROR_MEMORY_FAIL;
		    }
		}

	    /* if needed, initialize third XDR stream */
	    if (status == MB_SUCCESS
		&& mb_io_ptr->filetype == MB_FILETYPE_XDR
		&& (mb_io_ptr->numfile >= 3 || mb_io_ptr->numfile <= -3)
		&& mb_io_ptr->mbfp3 != NULL)
		{
		status = mb_mallocd(verbose,__FILE__, __LINE__,sizeof(XDR),
				(void **) &mb_io_ptr->xdrs3,error);
		if (status == MB_SUCCESS)
		    {
		    xdrstdio_create((XDR *)mb_io_ptr->xdrs3,
			    mb_io_ptr->mbfp3, XDR_DECODE);
		    }
		else
		    {
		    status = MB_FAILURE;
		    *error = MB_ERROR_MEMORY_FAIL;
		    }
		}
	    }

	/* else handle single normal files to be opened with mb_fileio_open() */
	else if (mb_io_ptr->filetype == MB_FILETYPE_SINGLE)
	    {
	    status = mb_fileio_open(verbose, *mbio_ptr, error);
	    }

#ifdef WITH_GSF
	/* else handle gsf files to be opened with gsflib */
	else if (mb_io_ptr->filetype == MB_FILETYPE_GSF)
	    {
	    status = gsfOpen(mb_io_ptr->file,
				GSF_READONLY,
				(int *) &(mb_io_ptr->gsfid));
	    if (status == 0)
		{
		status = MB_SUCCESS;
		*error = MB_ERROR_NO_ERROR;
		}
	    else
		{
		status = MB_FAILURE;
		*error = MB_ERROR_OPEN_FAIL;
		}
	    }
#else
        /* TODO: should issue an error */
#endif

	/* else handle netcdf files to be opened with libnetcdf */
	else if (mb_io_ptr->filetype == MB_FILETYPE_NETCDF)
	    {
	    status = nc_open(mb_io_ptr->file,
				NC_NOWRITE,
				(int *) &(mb_io_ptr->ncid));
	    if (status == 0)
		{
		status = MB_SUCCESS;
		*error = MB_ERROR_NO_ERROR;
		}
	    else
		{
		status = MB_FAILURE;
		*error = MB_ERROR_OPEN_FAIL;
		}
	    }

	/* else handle surf files to be opened with libsapi */
	else if (mb_io_ptr->filetype == MB_FILETYPE_SURF)
	    {
	    lastslash = strrchr(file, '/');
	    if (lastslash != NULL && strlen(lastslash) > 1)
	    	{
		strcpy(name,&(lastslash[1]));
		strcpy(path,file);
		path[strlen(file) - strlen(lastslash)] = '\0';
		}
	    else if (strlen(file) > 0)
	    	{
		strcpy(path, ".");
		strcpy(name, file);
		}
	    else
	     	{
		status = MB_FAILURE;
		*error = MB_ERROR_OPEN_FAIL;
		}
	    if (status == MB_SUCCESS)
	    	{
		if (strcmp(&name[strlen(name)-4],".sda") == 0)
			name[strlen(name)-4] = '\0';
		else if (strcmp(&name[strlen(name)-4],".SDA") == 0)
			name[strlen(name)-4] = '\0';
		else if (strcmp(&name[strlen(name)-4],".six") == 0)
			name[strlen(name)-4] = '\0';
		else if (strcmp(&name[strlen(name)-4],".SIX") == 0)
			name[strlen(name)-4] = '\0';
	    	sapi_status = SAPI_open(path,name,verbose);
	    	if (sapi_status == 0)
			{
			status = MB_SUCCESS;
			*error = MB_ERROR_NO_ERROR;
			}
	    	else
			{
			status = MB_FAILURE;
			*error = MB_ERROR_OPEN_FAIL;
			}
		}
	    else
		{
		status = MB_FAILURE;
		*error = MB_ERROR_OPEN_FAIL;
		}
	    }

	/* else handle segy files to be opened with mb_segy */
	else if (mb_io_ptr->filetype == MB_FILETYPE_SEGY)
	    {
	    status = mb_segy_read_init(verbose, mb_io_ptr->file,
		(void **)&(mb_io_ptr->mbfp), NULL, NULL, error);
	    if (status != MB_SUCCESS)
		{
		status = MB_FAILURE;
		*error = MB_ERROR_OPEN_FAIL;
		}
	    }

	/* if error terminate */
	if (status == MB_FAILURE)
		{
		/* save status and error values */
		status_save = status;
		error_save = *error;

		/* free allocated memory */
		if (mb_io_ptr->filetype == MB_FILETYPE_XDR
		    && mb_io_ptr->xdrs != NULL)
			status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->xdrs,error);
		if (mb_io_ptr->filetype == MB_FILETYPE_XDR
		    && mb_io_ptr->xdrs2 != NULL)
			status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->xdrs2,error);
		if (mb_io_ptr->filetype == MB_FILETYPE_XDR
		    && mb_io_ptr->xdrs3 != NULL)
			status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->xdrs3,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->beamflag,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->bath,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->amp,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->bath_acrosstrack,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->bath_alongtrack,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->bath_num,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->amp_num,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->ss,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->ss_acrosstrack,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->ss_alongtrack,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->ss_num,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->new_beamflag,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->new_bath,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->new_amp,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->new_bath_acrosstrack,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->new_bath_alongtrack,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->new_ss,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->new_ss_acrosstrack,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr->new_ss_alongtrack,error);
		status = mb_freed(verbose,__FILE__, __LINE__,(void **)&mb_io_ptr,error);

		/* restore error and status values */
		status = status_save;
		*error = error_save;

		/* output debug message */
		if (verbose >= 2)
			{
			fprintf(stderr,"\ndbg2  MBIO function <%s> terminated with error\n",
				function_name);
			fprintf(stderr,"dbg2  Return values:\n");
			fprintf(stderr,"dbg2       error:      %d\n",
				*error);
			fprintf(stderr,"dbg2  Return status:\n");
			fprintf(stderr,"dbg2       status:  %d\n",
				status);
			}
		return(status);
		}

	/* initialize the working variables */
	mb_io_ptr->ping_count = 0;
	mb_io_ptr->nav_count = 0;
	mb_io_ptr->comment_count = 0;
	if (pings == 0)
		mb_io_ptr->pings_avg = 2;
	else
		mb_io_ptr->pings_avg = pings;
	mb_io_ptr->pings_read = 0;
	mb_io_ptr->error_save = MB_ERROR_NO_ERROR;
	mb_io_ptr->last_time_d = 0.0;
	mb_io_ptr->last_lon = 0.0;
	mb_io_ptr->last_lat = 0.0;
	mb_io_ptr->old_time_d = 0.0;
	mb_io_ptr->old_lon = 0.0;
	mb_io_ptr->old_lat = 0.0;
	mb_io_ptr->old_ntime_d = 0.0;
	mb_io_ptr->old_nlon = 0.0;
	mb_io_ptr->old_nlat = 0.0;
	mb_io_ptr->time_d = 0.0;
	mb_io_ptr->lon = 0.0;
	mb_io_ptr->lat = 0.0;
	mb_io_ptr->speed = 0.0;
	mb_io_ptr->heading = 0.0;
	for (i=0;i<mb_io_ptr->beams_bath_max;i++)
		{
		mb_io_ptr->beamflag[i] = MB_FLAG_NULL;
		mb_io_ptr->bath[i] = 0.0;
		mb_io_ptr->bath_acrosstrack[i] = 0.0;
		mb_io_ptr->bath_alongtrack[i] = 0.0;
		mb_io_ptr->bath_num[i] = 0;
		}
	for (i=0;i<mb_io_ptr->beams_amp_max;i++)
		{
		mb_io_ptr->amp[i] = 0.0;
		mb_io_ptr->amp_num[i] = 0;
		}
	for (i=0;i<mb_io_ptr->pixels_ss_max;i++)
		{
		mb_io_ptr->ss[i] = 0.0;
		mb_io_ptr->ss_acrosstrack[i] = 0.0;
		mb_io_ptr->ss_alongtrack[i] = 0.0;
		mb_io_ptr->ss_num[i] = 0;
		}
	mb_io_ptr->need_new_ping = MB_YES;

	/* initialize variables for interpolating asynchronous data */
	mb_io_ptr->nfix = 0;
	mb_io_ptr->nattitude = 0;
	mb_io_ptr->nheading = 0;
	mb_io_ptr->nsonardepth = 0;
	mb_io_ptr->naltitude = 0;
	for (i=0;i<MB_ASYNCH_SAVE_MAX;i++)
		{
		mb_io_ptr->fix_time_d[i] = 0.0;
		mb_io_ptr->fix_lon[i] = 0.0;
		mb_io_ptr->fix_lat[i] = 0.0;
		mb_io_ptr->attitude_time_d[i] = 0.0;
		mb_io_ptr->attitude_heave[i] = 0.0;
		mb_io_ptr->attitude_roll[i] = 0.0;
		mb_io_ptr->attitude_pitch[i] = 0.0;
		mb_io_ptr->heading_time_d[i] = 0.0;
		mb_io_ptr->heading_heading[i] = 0.0;
		mb_io_ptr->sonardepth_time_d[i] = 0.0;
		mb_io_ptr->sonardepth_sonardepth[i] = 0.0;
		mb_io_ptr->altitude_time_d[i] = 0.0;
		mb_io_ptr->altitude_altitude[i] = 0.0;
		}

	/* initialize notices */
	for (i=0;i<MB_NOTICE_MAX;i++)
		mb_io_ptr->notice_list[i] = 0;

	/* check for projection specification file */
	sprintf(prjfile, "%s.prj", file);
	if ((pfp = fopen(prjfile, "r")) != NULL)
		{
		nscan = fscanf(pfp,"%s", projection_id);
		proj_status = mb_proj_init(verbose,projection_id,
			&(mb_io_ptr->pjptr), error);
		if (proj_status == MB_SUCCESS)
			{
			mb_io_ptr->projection_initialized = MB_YES;
			strcpy(mb_io_ptr->projection_id, projection_id);
			}
		else
			{
			fprintf(stderr, "Unable to initialize projection %s from file %s\n\n",
				projection_id, prjfile);
			}
		fclose(pfp);
		}
	else
		{
		*error = MB_ERROR_OPEN_FAIL;
		status = MB_FAILURE;
		}

	/* set error and status (if you got here you succeeded */
	*error = MB_ERROR_NO_ERROR;
	status = MB_SUCCESS;

	/* print output debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  MBIO function <%s> completed\n",function_name);
		fprintf(stderr,"dbg2  Revision id: %s\n",rcs_id);
		fprintf(stderr,"dbg2  Return values:\n");
		fprintf(stderr,"dbg2       mbio_ptr:   %p\n",(void *)*mbio_ptr);
		fprintf(stderr,"dbg2       ->numfile:  %d\n",mb_io_ptr->numfile);
		fprintf(stderr,"dbg2       ->file:     %s\n",mb_io_ptr->file);
		if (mb_io_ptr->numfile >= 2 || mb_io_ptr->numfile <= -2)
		    fprintf(stderr,"dbg2       ->file2:    %s\n",mb_io_ptr->file2);
		if (mb_io_ptr->numfile >= 3 || mb_io_ptr->numfile <= -3)
		    fprintf(stderr,"dbg2       ->file3:    %s\n",mb_io_ptr->file3);
		fprintf(stderr,"dbg2       ->mbfp:     %p\n",(void *)mb_io_ptr->mbfp);
		if (mb_io_ptr->numfile >= 2 || mb_io_ptr->numfile <= -2)
		    fprintf(stderr,"dbg2       ->mbfp2:    %p\n",(void *)mb_io_ptr->mbfp2);
		if (mb_io_ptr->numfile >= 3 || mb_io_ptr->numfile <= -3)
		    fprintf(stderr,"dbg2       ->mbfp3:    %p\n",(void *)mb_io_ptr->mbfp3);
		fprintf(stderr,"dbg2       btime_d:    %f\n",*btime_d);
		fprintf(stderr,"dbg2       etime_d:    %f\n",*etime_d);
		fprintf(stderr,"dbg2       beams_bath: %d\n",*beams_bath);
		fprintf(stderr,"dbg2       beams_amp:  %d\n",*beams_amp);
		fprintf(stderr,"dbg2       pixels_ss:  %d\n",*pixels_ss);
		fprintf(stderr,"dbg2       error:      %d\n",*error);
		fprintf(stderr,"dbg2  Return status:\n");
		fprintf(stderr,"dbg2       status:  %d\n",status);
		}

	/* return status */
	return(status);
}
Пример #24
0
int main (int argc, char **argv)
{
	extern char *optarg;
	int	errflg = 0;
	int	c;
	int	help = 0;
	int	flag = 0;

	/* MBIO status variables */
	int	status = MB_SUCCESS;
	int	verbose = 0;
	int	error = MB_ERROR_NO_ERROR;
	char	*message;

	/* segy data */
	char	segyfile[MB_PATH_MAXLINE];
	void	*mbsegyioptr;
	struct mb_segyasciiheader_struct asciiheader;
	struct mb_segyfileheader_struct fileheader;
	struct mb_segytraceheader_struct traceheader;
	float	*trace = NULL;
	float	*worktrace = NULL;
	double	*spsd = NULL;
	double	*wpsd = NULL;
	double	*spsdtot = NULL;
	double	*wpsdtot = NULL;
	
	/* fft controls */
	int		nfft = 1024;
	fftw_plan 	plan;
	fftw_complex	*fftw_in = NULL;
	fftw_complex	*fftw_out = NULL;
	int		nsection;

	/* grid controls */
	char	fileroot[MB_PATH_MAXLINE];
	char	gridfile[MB_PATH_MAXLINE];
	char	psdfile[MB_PATH_MAXLINE];
	int	decimatex = 1;
	int	tracemode = MBSEGYPSD_USESHOT;
	int	tracestart = 0;
	int	traceend = 0;
	int	chanstart = 0;
	int	chanend = -1;
	double	timesweep = 0.0;
	double	timedelay = 0.0;
	double	sampleinterval = 0.0;
	int	windowmode = MBSEGYPSD_WINDOW_OFF;
	double	windowstart, windowend;
	int	ntraces;
	int	ngridx = 0;
	int	ngridy = 0;
	int	ngridxy = 0;
	float	*grid = NULL;
	double	xmin;
	double	xmax;
	double	ymin;
	double	ymax;
	double	dx;
	double	dy;
	double	gridmintot = 0.0;
	double	gridmaxtot = 0.0;
	char	projection[MB_PATH_MAXLINE];
	char	xlabel[MB_PATH_MAXLINE];
	char	ylabel[MB_PATH_MAXLINE];
	char	zlabel[MB_PATH_MAXLINE];
	char	title[MB_PATH_MAXLINE];
	char	plot_cmd[MB_PATH_MAXLINE];
	int	scale2distance = MB_NO;
	double	shotscale = 1.0;
	double	frequencyscale = 1.0;
	int	logscale = MB_NO;

	int	sinftracemode = MBSEGYPSD_USESHOT;
	int	sinftracestart = 0;
	int	sinftraceend = 0;
	int	sinfchanstart = 0;
	int	sinfchanend = -1;
	double	sinftimesweep = 0.0;
	double	sinftimedelay = 0.0;
	
	double	soundpressurelevel;
	
	double	sint, taper;
	double	norm, normraw, normtaper, normfft;

	FILE	*fp;
	int	nread;
	int	tracecount, tracenum, channum, traceok;
	double	tracemin, tracemax;
	double	xwidth, ywidth;
	int	ix, iy, iys;
	int	itstart, itend;
	double	factor, btime, stime, dtime;
	double	btimesave = 0.0;
	double	stimesave = 0.0;
	double	dtimesave = 0.0;
	int	plot_status;
	int	kstart, kend;
	int	i, j, k, n;

	/* set file to null */
	segyfile[0] = '\0';

	/* get NaN value */
	GMT_make_fnan(NaN);

	/* process argument list */
	while ((c = getopt(argc, argv, "A:a:D:d:I:i:LlN:n:O:o:PpS:s:T:t:VvW:w:Hh")) != -1)
	  switch (c) 
		{
		case 'H':
		case 'h':
			help++;
			break;
		case 'V':
		case 'v':
			verbose++;
			break;
		case 'A':
		case 'a':
			n = sscanf (optarg,"%lf/%lf", &shotscale, &frequencyscale);
			if (n == 2)
				scale2distance = MB_YES;
			flag++;
			break;
		case 'D':
		case 'd':
			n = sscanf (optarg,"%d", &decimatex);
			flag++;
			break;
		case 'I':
		case 'i':
			sscanf (optarg,"%s", segyfile);
			flag++;
			break;
		case 'L':
		case 'l':
			logscale = MB_YES;
			flag++;
			break;
		case 'N':
		case 'n':
			n = sscanf (optarg,"%d", &nfft);
			flag++;
			break;
		case 'G':
		case 'O':
		case 'o':
			sscanf (optarg,"%s", fileroot);
			flag++;
			break;
		case 'S':
		case 's':
			n = sscanf (optarg,"%d/%d/%d/%d/%d", &tracemode, &tracestart, &traceend, &chanstart, &chanend);
			if (n < 5)
				{
				chanstart = 0;
				chanend = -1;
				}
			if (n < 3)
				{
				tracestart = 0;
				traceend = 0;
				}
			if (n < 1)
				{
				tracemode = MBSEGYPSD_USESHOT;
				}
			flag++;
			break;
		case 'T':
		case 't':
			n = sscanf (optarg,"%lf/%lf", &timesweep, &timedelay);
			if (n < 2)
				timedelay = 0.0;
			flag++;
			break;
		case 'W':
		case 'w':
			n = sscanf (optarg,"%d/%lf/%lf", &windowmode, &windowstart, &windowend);
			flag++;
			break;
		case '?':
			errflg++;
		}

	/* set output stream to stdout or stderr */
	if (verbose >= 2)
	    outfp = stderr;
	else
	    outfp = stdout;

	/* if error flagged then print it and exit */
	if (errflg)
		{
		fprintf(outfp,"usage: %s\n", usage_message);
		fprintf(outfp,"\nProgram <%s> Terminated\n",
			program_name);
		error = MB_ERROR_BAD_USAGE;
		exit(error);
		}

	/* print starting message */
	if (verbose == 1 || help)
		{
		fprintf(outfp,"\nProgram %s\n",program_name);
		fprintf(outfp,"MB-system Version %s\n",MB_VERSION);
		}

	/* print starting debug statements */
	if (verbose >= 2)
		{
		fprintf(outfp,"\ndbg2  Program <%s>\n",program_name);
		fprintf(outfp,"dbg2  MB-system Version %s\n",MB_VERSION);
		fprintf(outfp,"dbg2  Control Parameters:\n");
		fprintf(outfp,"dbg2       verbose:        %d\n",verbose);
		fprintf(outfp,"dbg2       help:           %d\n",help);
		fprintf(outfp,"dbg2       segyfile:       %s\n",segyfile);
		fprintf(outfp,"dbg2       fileroot:       %s\n",fileroot);
		fprintf(outfp,"dbg2       nfft:           %d\n",nfft);
		fprintf(outfp,"dbg2       decimatex:      %d\n",decimatex);
		fprintf(outfp,"dbg2       tracemode:      %d\n",tracemode);
		fprintf(outfp,"dbg2       tracestart:     %d\n",tracestart);
		fprintf(outfp,"dbg2       traceend:       %d\n",traceend);
		fprintf(outfp,"dbg2       chanstart:      %d\n",chanstart);
		fprintf(outfp,"dbg2       chanend:        %d\n",chanend);
		fprintf(outfp,"dbg2       timesweep:      %f\n",timesweep);
		fprintf(outfp,"dbg2       timedelay:      %f\n",timedelay);
		fprintf(outfp,"dbg2       ngridx:         %d\n",ngridx);
		fprintf(outfp,"dbg2       ngridy:         %d\n",ngridy);
		fprintf(outfp,"dbg2       ngridxy:        %d\n",ngridxy);
		fprintf(outfp,"dbg2       windowmode:     %d\n",windowmode);
		fprintf(outfp,"dbg2       windowstart:    %f\n",windowstart);
		fprintf(outfp,"dbg2       windowend:      %f\n",windowend);
		fprintf(outfp,"dbg2       scale2distance: %d\n",scale2distance);
		fprintf(outfp,"dbg2       shotscale:      %f\n",shotscale);
		fprintf(outfp,"dbg2       frequencyscale: %f\n",frequencyscale);
		fprintf(outfp,"dbg2       logscale:       %d\n",logscale);
		}

	/* if help desired then print it and exit */
	if (help)
		{
		fprintf(outfp,"\n%s\n",help_message);
		fprintf(outfp,"\nusage: %s\n", usage_message);
		exit(error);
		}
		
	/* get segy limits if required */
	if (traceend < 1 || traceend < tracestart || timesweep <= 0.0)
		{
		get_segy_limits(verbose, 
				segyfile,  
				&sinftracemode,
				&sinftracestart,
				&sinftraceend,
				&sinfchanstart,
				&sinfchanend,
				&sinftimesweep,
				&sinftimedelay,
				&error);
		if (traceend < 1 || traceend < tracestart)
			{
			tracemode = sinftracemode;
			tracestart = sinftracestart;
			traceend = sinftraceend;
			}
		if (chanend < 1 || chanend < chanstart)
			{
			chanstart = sinfchanstart;
			chanend = sinfchanend;
			}
		if (timesweep <= 0.0)
			{
			timesweep = sinftimesweep;
			timedelay = sinftimedelay;
			}
		}
		
	/* check specified parameters */
	if (traceend < 1 || traceend < tracestart)
		{
		fprintf(outfp,"\nBad trace numbers: %d %d specified...\n", tracestart, traceend);
		fprintf(outfp,"\nProgram <%s> Terminated\n", program_name);
		exit(error);
		}
	if (timesweep <= 0.0)
		{
		fprintf(outfp,"\nBad time sweep: %f specified...\n", timesweep);
		fprintf(outfp,"\nProgram <%s> Terminated\n", program_name);
		exit(error);
		}

	/* initialize reading the segy file */
	if (mb_segy_read_init(verbose, segyfile, 
		&mbsegyioptr, &asciiheader, &fileheader, &error) != MB_SUCCESS)
		{
		mb_error(verbose,error,&message);
		fprintf(outfp,"\nMBIO Error returned from function <mb_segy_read_init>:\n%s\n",message);
		fprintf(outfp,"\nSEGY File <%s> not initialized for reading\n",segyfile);
		fprintf(outfp,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}
		
	/* calculate implied grid parameters */
	strcpy(gridfile,fileroot);
	strcat(gridfile,".grd");
	strcpy(psdfile,fileroot);
	strcat(psdfile,"_psd.txt");
	if (chanend >= chanstart)
		ntraces = (traceend - tracestart + 1) * (chanend - chanstart + 1);
	else
		ntraces = traceend - tracestart + 1;
	ngridx = ntraces / decimatex;
	sampleinterval = 0.000001 * (double) (fileheader.sample_interval);
	ngridy = nfft / 2 + 1;
	ngridxy = ngridx * ngridy;
	dx = decimatex;
	xmin = (double) tracestart - 0.5;
	xmax = (double) traceend + 0.5;
	dy = 1.0 / (2.0 * sampleinterval * ngridy);
	ymin = -0.5 * dy;
	ymax = (ngridy - 0.5) * dy;
	
	/* get start and end samples */
	if (windowmode == MBSEGYPSD_WINDOW_OFF)
		{
		itstart = 0;
		itend = ngridy - 1;
		}
	else if (windowmode == MBSEGYPSD_WINDOW_ON)
		{
		itstart = MAX((windowstart) / sampleinterval, 0);
		itend = MIN((windowend) / sampleinterval, ngridy - 1);
		}		
	
	/* allocate memory for grid array */
	status = mb_mallocd(verbose,__FILE__,__LINE__, 2 * ngridxy * sizeof(float), (void **)&grid, &error);
	status = mb_mallocd(verbose,__FILE__,__LINE__, ngridy * sizeof(double), (void **)&spsd, &error);
	status = mb_mallocd(verbose,__FILE__,__LINE__, ngridy * sizeof(double), (void **)&wpsd, &error);
	status = mb_mallocd(verbose,__FILE__,__LINE__, ngridy * sizeof(double), (void **)&spsdtot, &error);
	status = mb_mallocd(verbose,__FILE__,__LINE__, ngridy * sizeof(double), (void **)&wpsdtot, &error);

	/* zero working psd array */
	for (iy=0;iy<ngridy;iy++)
		{
		spsdtot[iy] = 0.0;
		wpsdtot[iy] = 0.0;
		}

	/* output info */
	if (verbose >= 0)
		{
		fprintf(outfp,"\nMBsegypsd Parameters:\n");
		fprintf(outfp,"Input segy file:         %s\n",segyfile);
		fprintf(outfp,"Output fileroot:         %s\n",fileroot);
		fprintf(outfp,"Input Parameters:\n");
		fprintf(outfp,"     trace mode:         %d\n",tracemode);
		fprintf(outfp,"     trace start:        %d\n",tracestart);
		fprintf(outfp,"     trace end:          %d\n",traceend);
		fprintf(outfp,"     channel start:      %d\n",chanstart);
		fprintf(outfp,"     channel end:        %d\n",chanend);
		fprintf(outfp,"     trace decimation:   %d\n",decimatex);
		fprintf(outfp,"     time sweep:         %f seconds\n",timesweep);
		fprintf(outfp,"     time delay:         %f seconds\n",timedelay);
		fprintf(outfp,"     sample interval:    %f seconds\n",sampleinterval);
		fprintf(outfp,"     window mode:        %d\n",windowmode);
		fprintf(outfp,"     window start:       %f seconds\n",windowstart);
		fprintf(outfp,"     window end:         %f seconds\n",windowend);
		fprintf(outfp,"Output Parameters:\n");
		fprintf(outfp,"     grid filename:      %s\n",gridfile);
		fprintf(outfp,"     psd filename:       %s\n",psdfile);
		fprintf(outfp,"     x grid dimension:   %d\n",ngridx);
		fprintf(outfp,"     y grid dimension:   %d\n",ngridy);
		fprintf(outfp,"     grid xmin:          %f\n",xmin);
		fprintf(outfp,"     grid xmax:          %f\n",xmax);
		fprintf(outfp,"     grid ymin:          %f\n",ymin);
		fprintf(outfp,"     grid ymax:          %f\n",ymax);
		fprintf(outfp,"     NaN values used to flag regions with no data\n");
		fprintf(outfp,"     shotscale:          %f\n",shotscale);
		fprintf(outfp,"     frequencyscale:     %f\n",frequencyscale);
		if (scale2distance == MB_YES)
			{
			fprintf(outfp,"     trace numbers scaled to distance in meters\n");
			fprintf(outfp,"     scaled grid xmin    %f\n",0.0);
			fprintf(outfp,"     scaled grid xmax:   %f\n",shotscale * (xmax - xmin));
			}
		}
	if (verbose > 0)
		fprintf(outfp,"\n");
	
	/* proceed if all ok */
	if (status == MB_SUCCESS)
		{
	
		/* fill grid with NaNs */
		for (i=0;i<ngridxy;i++)
			grid[i] = NaN;
			
		/* generate the fftw plan */
		fftw_in = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nfft);
		fftw_out = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nfft);
		plan = fftw_plan_dft_1d(nfft, fftw_in, fftw_out, FFTW_FORWARD, FFTW_MEASURE);

		/* read and print data */
		nread = 0;
		while (error <= MB_ERROR_NO_ERROR)
			{
			/* reset error */
			error = MB_ERROR_NO_ERROR;

			/* read a trace */
			status = mb_segy_read_trace(verbose, mbsegyioptr, 
					&traceheader, &trace, &error);

			/* now process the trace */
			if (status == MB_SUCCESS)
				{
				/* figure out where this trace is in the grid */
				if (tracemode == MBSEGYPSD_USESHOT)
					{
					tracenum = traceheader.shot_num;
					channum = traceheader.shot_tr;
					}
				else
					{
					tracenum = traceheader.rp_num;
					channum = traceheader.rp_tr;
					}
				if (chanend >= chanstart)
					{
					tracecount = (tracenum - tracestart) * (chanend - chanstart + 1)
							+ (channum - chanstart);
					}
				else
					{
					tracecount = tracenum - tracestart;
					}
				ix = tracecount / decimatex;
				if (traceheader.elev_scalar < 0)
					factor = 1.0 / ((float) (-traceheader.elev_scalar));
				else
					factor = (float) traceheader.elev_scalar;
				if (traceheader.src_depth > 0)
					{
					btime = factor * traceheader.src_depth / 750.0 + 0.001 * traceheader.delay_mils;
					dtime = factor * traceheader.src_depth / 750.0;
					btimesave = btime;
					dtimesave = dtime;
					}
				else if (traceheader.src_elev > 0)
					{
					btime = -factor * traceheader.src_elev / 750.0 + 0.001 * traceheader.delay_mils;
					dtime = -factor * traceheader.src_elev / 750.0;
					btimesave = btime;
					dtimesave = dtime;
					}
				else
					{
					btime = btimesave;
					dtime = dtimesave;
					}
				if (traceheader.src_wbd > 0)
					{
					stime = factor * traceheader.src_wbd / 750.0;
					stimesave = stime;
					}
				else
					{
					stime = stimesave;
					}
				iys = (btime - timedelay) / sampleinterval;
				
				/* now check if this is a trace of interest */
				traceok = MB_YES;
				if (tracenum < tracestart 
					|| tracenum > traceend)
					traceok = MB_NO;
				else if (chanend >= chanstart
						&& (channum < chanstart
							|| channum > chanend))
					traceok = MB_NO;
				else if (tracecount % decimatex != 0)
					traceok = MB_NO;

				/* get trace min and max */
				tracemin = trace[0];
				tracemax = trace[0];
				for (i=0;i<traceheader.nsamps;i++)
					{
					tracemin = MIN(tracemin, trace[i]);
					tracemax = MAX(tracemin, trace[i]);
					}	

				if ((verbose == 0 && nread % 250 == 0) || (nread % 25 == 0))
					{
					if (traceok == MB_YES) 
						fprintf(outfp,"PROCESS ");
					else 
						fprintf(outfp,"IGNORE  ");
					if (tracemode == MBSEGYPSD_USESHOT) 
						fprintf(outfp,"read:%d position:%d shot:%d channel:%d ",
							nread,tracecount,tracenum,channum);
					else 
						fprintf(outfp,"read:%d position:%d rp:%d channel:%d ",
							nread,tracecount,tracenum,channum);
					fprintf(outfp,"%4.4d/%3.3d %2.2d:%2.2d:%2.2d.%3.3d samples:%d interval:%d usec minmax: %f %f\n",
					traceheader.year,traceheader.day_of_yr,
					traceheader.hour,traceheader.min,traceheader.sec,traceheader.mils,
					traceheader.nsamps,traceheader.si_micros,
					tracemin, tracemax);
					}

				/* now actually process traces of interest */
				if (traceok == MB_YES)
					{
					/* zero working psd array */
					for (iy=0;iy<ngridy;iy++)
						{
						spsd[iy] = 0.0;
						wpsd[iy] = 0.0;
						}

					/* get bounds of trace in depth window mode */
					if (windowmode == MBSEGYPSD_WINDOW_DEPTH)
						{
						itstart = (int)((dtime + windowstart - timedelay) / sampleinterval);
						itstart = MAX(itstart, 0);
						itend = (int)((dtime + windowend - timedelay) / sampleinterval);
						itend = MIN(itend, ngridy - 1);
						}
					else if (windowmode == MBSEGYPSD_WINDOW_SEAFLOOR)
						{
						itstart = MAX((stime + windowstart - timedelay) / sampleinterval, 0);
						itend = MIN((stime + windowend - timedelay) / sampleinterval, ngridy - 1);
						}
						
					/* loop over the data calculating fft in nfft long sections */
					nsection = (itend - itstart + 1) / nfft;
					if (((itend - itstart + 1) % nfft) > 0)
						nsection++;
					for (j=0;j<nsection;j++)
						{
						/* initialize normalization factors */
						normraw = 0.0;
						normtaper = 0.0;
						normfft = 0.0;
						
						/* extract data section to be fft'd with taper */
						kstart = itstart + j * nfft;
						kend = MIN(kstart + nfft, itend);
						for (i=0;i<nfft;i++)
							{
							k = itstart + j * nfft + i;
							if (k <= kend)
								{
								sint = sin(M_PI * ((double)(k - kstart)) / ((double)(kend - kstart)));
								taper = sint * sint;
								fftw_in[i][0] = taper * trace[k]; 
								normraw += trace[k] * trace[k];
								normtaper += fftw_in[i][0] * fftw_in[i][0];
								}
							else
								fftw_in[i][0] = 0.0;
/*if (ix < 500)
fftw_in[i][0] = sin(2.0 * M_PI * 1000.0 * i * sampleinterval) 
			+ sin(2.0 * M_PI * 3000.0 * i * sampleinterval) 
			+ sin(2.0 * M_PI * 6000.0 * i * sampleinterval);*/
							fftw_in[i][1] = 0.0;
							}
						soundpressurelevel = 20.0 * log10(normraw / nfft);
/*fprintf(stderr,"Sound Pressure Level: %f dB re 1 uPa\n",soundpressurelevel);*/
							
						/* execute the fft */
						fftw_execute(plan);
						
						/* get normalization factor - require variance of transform to equal variance of input */
						for (i=1;i<nfft;i++)
							{
							normfft += fftw_out[i][0] * fftw_out[i][0] + fftw_out[i][1] * fftw_out[i][1];
							}
						norm = normraw / normfft;
						
						/* apply normalization factor */
						for (i=1;i<nfft;i++)
							{
							fftw_out[i][0] = norm * fftw_out[i][0];
							fftw_out[i][1] = norm * fftw_out[i][1];
							}
							
						/* calculate psd from result of transform */
						spsd[0] += fftw_out[0][0] * fftw_out[0][0] + fftw_out[0][1] * fftw_out[0][1];
						wpsd[0] += 1.0;
/* fprintf(stderr,"FFT result: i:%d  %f %f  %f\n",
0,fftw_out[0][0],fftw_out[0][1],fftw_out[0][0] * fftw_out[0][0] + fftw_out[0][1] * fftw_out[0][1]);*/
						for (i=1;i<nfft/2;i++)
							{
							spsd[i] += 2.0 * (fftw_out[i][0] * fftw_out[i][0] + fftw_out[i][1] * fftw_out[i][1]);
							wpsd[i] += 1.0;
/* fprintf(stderr,"FFT result: i:%d  %f %f  %f\n",
i,fftw_out[i][0],fftw_out[i][1],2.0 * fftw_out[i][0] * fftw_out[i][0] + fftw_out[i][1] * fftw_out[i][1]);*/
							}
						if (nfft % 2 == 0)
							{
							spsd[i] += fftw_out[nfft/2][0] * fftw_out[nfft/2][0] + fftw_out[nfft/2][1] * fftw_out[nfft/2][1];
							wpsd[i] += 1.0;
/* fprintf(stderr,"FFT result: i:%d  %f %f  %f\n",
nfft/2,fftw_out[nfft/2][0],fftw_out[nfft/2][1],fftw_out[nfft/2][0] * fftw_out[nfft/2][0] + fftw_out[nfft/2][1] * fftw_out[nfft/2][1]); */
							}
						}
						
					/* output psd for this trace to the grid */
/*fprintf(stderr,"N:%d Normalization: %f %f %f    ratios: %f %f     %f %f\n",
nfft,normraw,normtaper,normfft,normraw/normfft,normfft/normraw,normtaper/normfft,normfft/normtaper);*/
					for (iy=0;iy<ngridy;iy++)
						{
						k = (ngridy - 1 - iy) * ngridx + ix;
						if (wpsd[iy] > 0.0)
							{
							if (logscale == MB_NO)
								grid[k] = spsd[iy] / wpsd[iy];
							else
								grid[k] = 20.0 * log10(spsd[iy] / wpsd[iy]);
							spsdtot[iy] += grid[k];
							wpsdtot[iy] += 1.0;
/*fprintf(stderr,"ix:%d iy:%d k:%d spsd:%f wpsd:%f     f:%f p:%f\n",
ix,iy,k,spsd[iy],wpsd[iy],ymax * iy / ngridy,grid[k]);*/
							gridmintot = MIN(grid[k], gridmintot);
							gridmaxtot = MAX(grid[k], gridmaxtot);
							}
						}
					}
				}

			/* now process the trace */
			if (status == MB_SUCCESS)
				nread++;
			}
			
		/* deallocate fftw arrays and plan */
		fftw_destroy_plan(plan);
		fftw_free(fftw_in);
		fftw_free(fftw_out);
		}

	/* write out the grid */
	error = MB_ERROR_NO_ERROR;
	status = MB_SUCCESS;
	strcpy(projection, "GenericLinear");
	if (scale2distance == MB_YES)
		{
		strcpy(xlabel, "Distance (m)");
		strcpy(ylabel, "Frequency (Hz)");
		xmax *= shotscale;
		xmin *= shotscale;
		dx *= shotscale;
		}
	else
		{
		strcpy(xlabel, "Trace Number");
		strcpy(ylabel, "Frequency (Hz)");
		dx = (double) decimatex;
		}
	if (logscale == MB_YES)
		strcpy(zlabel, "dB/Hz");
	else
		strcpy(zlabel, "Intensity/Hz");
	sprintf(title, "Power Spectral Density Grid from %s", segyfile);
	status = write_cdfgrd(verbose, gridfile, grid,
		ngridx, ngridy, 
		xmin, xmax, ymin, ymax,
		gridmintot, gridmaxtot, dx, dy, 
		xlabel, ylabel, zlabel, title, 
		projection, argc, argv, &error);

	/* output average power spectra */
	if ((fp = fopen(psdfile, "w")) != NULL)
		{
		for (iy=0;iy<ngridy;iy++)
			{
			if (wpsdtot[iy] > 0.0)
				{
				spsdtot[iy] = spsdtot[iy] / wpsdtot[iy];
				}
			fprintf(fp, "%f %f\n", dy * iy, spsdtot[iy]);
			}
		fclose(fp);
		}

	/* close the segy file */
	status = mb_segy_close(verbose,&mbsegyioptr,&error);

	/* deallocate memory for grid array */
	if (worktrace != NULL)
		status = mb_freed(verbose,__FILE__,__LINE__,(void **)&worktrace, &error);	
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)&grid, &error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)&spsd, &error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)&wpsd, &error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)&spsdtot, &error);
	status = mb_freed(verbose,__FILE__,__LINE__,(void **)&wpsdtot, &error);
	
	/* run mbm_grdplot */
	xwidth = MIN(0.01 * (double) ngridx, 55.0);
	ywidth = MIN(0.01 * (double) ngridy, 28.0);
	sprintf(plot_cmd, "mbm_grdplot -I%s -JX%f/%f -G1 -S -V -L\"File %s - %s:%s\"", 
			gridfile, xwidth, ywidth, gridfile, title, zlabel);
	if (verbose)
		{
		fprintf(outfp, "\nexecuting mbm_grdplot...\n%s\n", 
			plot_cmd);
		}
	plot_status = system(plot_cmd);
	if (plot_status == -1)
		{
		fprintf(outfp, "\nError executing mbm_grdplot on grid file %s\n", gridfile);
		}
	
	/* run mbm_xyplot */
	xwidth = 9.0;
	ywidth = 7.0;
	sprintf(plot_cmd, "mbm_xyplot -I%s -JX%f/%f -V -L\"File %s - %s:%s\"", 
			psdfile, xwidth, ywidth, psdfile, title, zlabel);
	if (verbose)
		{
		fprintf(outfp, "\nexecuting mbm_xyplot...\n%s\n", 
			plot_cmd);
		}
	plot_status = system(plot_cmd);
	if (plot_status == -1)
		{
		fprintf(outfp, "\nError executing mbm_xyplot on psd file %s\n", psdfile);
		}

	/* check memory */
	if (verbose >= 4)
		status = mb_memory_list(verbose,&error);

	/* print output debug statements */
	if (verbose >= 2)
		{
		fprintf(outfp,"\ndbg2  Program <%s> completed\n",
			program_name);
		fprintf(outfp,"dbg2  Ending status:\n");
		fprintf(outfp,"dbg2       status:  %d\n",status);
		}

	/* end it all */
	exit(error);
}
Пример #25
0
int main (int argc, char **argv)
{
	char program_name[] = "mbctdlist";
	char help_message[] =  "mbctdlist lists all CTD records within swath data files\nThe -O option specifies how the values are output\nin an mblist-likefashion.\n";
	char usage_message[] = "mbctdlist [-A -Ddecimate -Fformat -Gdelimeter -H -Ifile -Llonflip -Ooutput_format -V -Zsegment]";
	extern char *optarg;
	int	errflg = 0;
	int	c;
	int	help = 0;
	int	flag = 0;

	/* MBIO status variables */
	int	status = MB_SUCCESS;
	int	interp_status = MB_SUCCESS;
	int	verbose = 0;
	int	error = MB_ERROR_NO_ERROR;
	char	*message;

	/* MBIO read control parameters */
	int	read_datalist = MB_NO;
	char	read_file[MB_PATH_MAXLINE];
	void	*datalist;
	int	look_processed = MB_DATALIST_LOOK_UNSET;
	double	file_weight;
	int	format;
	int	pings;
	int	decimate;
	int	lonflip;
	double	bounds[4];
	int	btime_i[7];
	int	etime_i[7];
	double	btime_d;
	double	etime_d;
	double	speedmin;
	double	timegap;
	char	file[MB_PATH_MAXLINE];
	int	beams_bath;
	int	beams_amp;
	int	pixels_ss;

	/* output format list controls */
	char	list[MAX_OPTIONS];
	int	n_list;
	double	distance_total = 0.0;
	int	time_j[5];
	int	mblist_next_value = MB_NO;
	int	invert_next_value = MB_NO;
	int	signflip_next_value = MB_NO;
	int	first = MB_YES;
	int	ascii = MB_YES;
	int	segment = MB_NO;
	char	segment_tag[MB_PATH_MAXLINE];
	char	delimiter[MB_PATH_MAXLINE];

	/* MBIO read values */
	void	*mbio_ptr = NULL;
	void	*store_ptr;
	int	kind;
	int	time_i[7];
	double	time_d;
	double	navlon;
	double	navlat;
	double	speed;
	double	heading;
	double	distance;
	double	altitude;
	double	sonardepth;
	char	*beamflag = NULL;
	double	*bath = NULL;
	double	*bathacrosstrack = NULL;
	double	*bathalongtrack = NULL;
	double	*amp = NULL;
	double	*ss = NULL;
	double	*ssacrosstrack = NULL;
	double	*ssalongtrack = NULL;
	char	comment[MB_COMMENT_MAXLINE];

	/* navigation, heading, attitude data */
	int	survey_count = 0;
	int	survey_count_tot = 0;
	int	nnav = 0;
	int	nnav_alloc = 0;
	double	*nav_time_d = NULL;
	double	*nav_lon = NULL;
	double	*nav_lat = NULL;
	double	*nav_sonardepth = NULL;
	double	*nav_heading = NULL;
	double	*nav_speed = NULL;
	double	*nav_altitude = NULL;

	/* CTD values */
	int	ctd_count = 0;
	int	ctd_count_tot = 0;
	int	nctd;
	double	ctd_time_d[MB_CTD_MAX];
	double	ctd_conductivity[MB_CTD_MAX];
	double	ctd_temperature[MB_CTD_MAX];
	double	ctd_depth[MB_CTD_MAX];
	double	ctd_salinity[MB_CTD_MAX];
	double	ctd_soundspeed[MB_CTD_MAX];
	int	nsensor;
	double	sensor_time_d[MB_CTD_MAX];
	double	sensor1[MB_CTD_MAX];
	double	sensor2[MB_CTD_MAX];
	double	sensor3[MB_CTD_MAX];
	double	sensor4[MB_CTD_MAX];
	double	sensor5[MB_CTD_MAX];
	double	sensor6[MB_CTD_MAX];
	double	sensor7[MB_CTD_MAX];
	double	sensor8[MB_CTD_MAX];
	double	conductivity;
	double	temperature;
	double	potentialtemperature;
	double	depth;
	double	salinity;
	double	soundspeed;

	/* additional time variables */
	int	first_m = MB_YES;
	double	time_d_ref;
	int	first_u = MB_YES;
	time_t	time_u;
	time_t	time_u_ref;
	double	seconds;

	/* course calculation variables */
	double	dlon, dlat, minutes;
	int	degrees;
	char	hemi;
	double	headingx, headingy, mtodeglon, mtodeglat;
	double	course, course_old;
	double	time_d_old;
	double	time_interval;
	double	speed_made_good, speed_made_good_old;
	double	navlon_old, navlat_old;
	double	dx, dy;
	double	b;

	int	read_data;
	int	ictd;
	int	i, j;

	/* get current default values */
	status = mb_defaults(verbose,&format,&pings,&lonflip,bounds,
		btime_i,etime_i,&speedmin,&timegap);
	pings = 1;
	bounds[0] = -360.0;
	bounds[1] = 360.0;
	bounds[2] = -90.0;
	bounds[3] = 90.0;
	ctd_count = 0;
	ctd_count_tot = 0;

	/* set default input to datalist.mb-1 */
	strcpy (read_file, "datalist.mb-1");

	/* set up the default list controls
		(Time, lon, lat, conductivity, temperature, depth, salinity, sound speed) */
	list[0]='T';
	list[1]='X';
	list[2]='Y';
	list[3]='H';
	list[4]='C';
	list[5]='c';
	list[6]='^';
	list[7]='c';
	list[8]='S';
	list[9]='s';
	n_list = 10;
	sprintf(delimiter, "\t");
	decimate = 1;

	/* process argument list */
	while ((c = getopt(argc, argv, "AaDdF:f:G:g:I:i:L:l:O:o:Z:z:VvHh")) != -1)
	  switch (c)
		{
		case 'H':
		case 'h':
			help++;
			break;
		case 'V':
		case 'v':
			verbose++;
			break;
		case 'A':
		case 'a':
			ascii = MB_NO;
			flag++;
			break;
		case 'D':
		case 'd':
			sscanf (optarg,"%d", &decimate);
			flag++;
			break;
		case 'F':
		case 'f':
			sscanf (optarg,"%d", &format);
			flag++;
			break;
		case 'G':
		case 'g':
			sscanf (optarg,"%s", delimiter);
			flag++;
			break;
		case 'I':
		case 'i':
			sscanf (optarg,"%s", read_file);
			flag++;
			break;
		case 'L':
		case 'l':
			sscanf (optarg,"%d", &lonflip);
			flag++;
			break;
		case 'O':
		case 'o':
			for(j=0,n_list=0;j<(int)strlen(optarg);j++,n_list++)
				if (n_list<MAX_OPTIONS)
					list[n_list] = optarg[j];
			break;
		case 'Z':
		case 'z':
			segment = MB_YES;
			sscanf (optarg,"%s", segment_tag);
			flag++;
			break;
		case '?':
			errflg++;
		}

	/* if error flagged then print it and exit */
	if (errflg)
		{
		fprintf(stderr,"usage: %s\n", usage_message);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		error = MB_ERROR_BAD_USAGE;
		exit(error);
		}

	/* print starting message */
	if (verbose == 1 || help)
		{
		fprintf(stderr,"\nProgram %s\n",program_name);
		fprintf(stderr,"Version %s\n",rcs_id);
		fprintf(stderr,"MB-system Version %s\n",MB_VERSION);
		}

	/* print starting debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  Program <%s>\n",program_name);
		fprintf(stderr,"dbg2  Version %s\n",rcs_id);
		fprintf(stderr,"dbg2  MB-system Version %s\n",MB_VERSION);
		fprintf(stderr,"dbg2  Control Parameters:\n");
		fprintf(stderr,"dbg2       verbose:        %d\n",verbose);
		fprintf(stderr,"dbg2       help:           %d\n",help);
		fprintf(stderr,"dbg2       format:         %d\n",format);
		fprintf(stderr,"dbg2       pings:          %d\n",pings);
		fprintf(stderr,"dbg2       lonflip:        %d\n",lonflip);
		fprintf(stderr,"dbg2       decimate:       %d\n",decimate);
		fprintf(stderr,"dbg2       bounds[0]:      %f\n",bounds[0]);
		fprintf(stderr,"dbg2       bounds[1]:      %f\n",bounds[1]);
		fprintf(stderr,"dbg2       bounds[2]:      %f\n",bounds[2]);
		fprintf(stderr,"dbg2       bounds[3]:      %f\n",bounds[3]);
		fprintf(stderr,"dbg2       btime_i[0]:     %d\n",btime_i[0]);
		fprintf(stderr,"dbg2       btime_i[1]:     %d\n",btime_i[1]);
		fprintf(stderr,"dbg2       btime_i[2]:     %d\n",btime_i[2]);
		fprintf(stderr,"dbg2       btime_i[3]:     %d\n",btime_i[3]);
		fprintf(stderr,"dbg2       btime_i[4]:     %d\n",btime_i[4]);
		fprintf(stderr,"dbg2       btime_i[5]:     %d\n",btime_i[5]);
		fprintf(stderr,"dbg2       btime_i[6]:     %d\n",btime_i[6]);
		fprintf(stderr,"dbg2       etime_i[0]:     %d\n",etime_i[0]);
		fprintf(stderr,"dbg2       etime_i[1]:     %d\n",etime_i[1]);
		fprintf(stderr,"dbg2       etime_i[2]:     %d\n",etime_i[2]);
		fprintf(stderr,"dbg2       etime_i[3]:     %d\n",etime_i[3]);
		fprintf(stderr,"dbg2       etime_i[4]:     %d\n",etime_i[4]);
		fprintf(stderr,"dbg2       etime_i[5]:     %d\n",etime_i[5]);
		fprintf(stderr,"dbg2       etime_i[6]:     %d\n",etime_i[6]);
		fprintf(stderr,"dbg2       speedmin:       %f\n",speedmin);
		fprintf(stderr,"dbg2       timegap:        %f\n",timegap);
		fprintf(stderr,"dbg2       ascii:          %d\n",ascii);
		fprintf(stderr,"dbg2       segment:        %d\n",segment);
		fprintf(stderr,"dbg2       segment_tag:    %s\n",segment_tag);
		fprintf(stderr,"dbg2       delimiter:      %s\n",delimiter);
		fprintf(stderr,"dbg2       file:           %s\n",file);
		fprintf(stderr,"dbg2       n_list:         %d\n",n_list);
		for (i=0;i<n_list;i++)
			fprintf(stderr,"dbg2         list[%d]:      %c\n",
						i,list[i]);
		}

	/* if help desired then print it and exit */
	if (help)
		{
		fprintf(stderr,"\n%s\n",help_message);
		fprintf(stderr,"\nusage: %s\n", usage_message);
		exit(error);
		}

	/* get format if required */
	if (format == 0)
		mb_get_format(verbose,read_file,NULL,&format,&error);

	/* determine whether to read one file or a list of files */
	if (format < 0)
		read_datalist = MB_YES;

	/**************************************************************************************/

	/* section 1 - read all data and save nav etc for interpolation onto ctd data */


	/* open file list */
	if (read_datalist == MB_YES)
	    {
	    if ((status = mb_datalist_open(verbose,&datalist,
					    read_file,look_processed,&error)) != MB_SUCCESS)
		{
		error = MB_ERROR_OPEN_FAIL;
		fprintf(stderr,"\nUnable to open data list file: %s\n",
			read_file);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}
	    if ((status = mb_datalist_read(verbose,datalist,
			    file,&format,&file_weight,&error))
			    == MB_SUCCESS)
		read_data = MB_YES;
	    else
		read_data = MB_NO;
	    }
	/* else copy single filename to be read */
	else
	    {
	    strcpy(file, read_file);
	    read_data = MB_YES;
	    }

	/* loop over all files to be read */
	while (read_data == MB_YES)
	{
	/* initialize reading the swath file */
	if ((status = mb_read_init(
		verbose,file,format,pings,lonflip,bounds,
		btime_i,etime_i,speedmin,timegap,
		&mbio_ptr,&btime_d,&etime_d,
		&beams_bath,&beams_amp,&pixels_ss,&error)) != MB_SUCCESS)
		{
		mb_error(verbose,error,&message);
		fprintf(stderr,"\nMBIO Error returned from function <mb_read_init>:\n%s\n",message);
		fprintf(stderr,"\nMultibeam File <%s> not initialized for reading\n",file);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* allocate memory for data arrays */
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						sizeof(char), (void **)&beamflag, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						sizeof(double), (void **)&bath, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_AMPLITUDE,
						sizeof(double), (void **)&amp, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						sizeof(double), (void **)&bathacrosstrack, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						sizeof(double), (void **)&bathalongtrack, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_SIDESCAN,
						sizeof(double), (void **)&ss, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_SIDESCAN,
						sizeof(double), (void **)&ssacrosstrack, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_SIDESCAN,
						sizeof(double), (void **)&ssalongtrack, &error);

	/* if error initializing memory then quit */
	if (error != MB_ERROR_NO_ERROR)
		{
		mb_error(verbose,error,&message);
		fprintf(stderr,"\nMBIO Error allocating data arrays:\n%s\n",
			message);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* output separator for GMT style segment file output */
	if (segment == MB_YES && ascii == MB_YES)
		{
		printf("%s\n", segment_tag);
		}

	/* output info */
	if (verbose >= 1)
		{
		fprintf(stderr, "\nSearching %s for survey records\n", file);
		}

	/* read and print data */
	survey_count = 0;
	first = MB_YES;
	while (error <= MB_ERROR_NO_ERROR)
		{
		/* read a data record */
		status = mb_get_all(verbose,mbio_ptr,&store_ptr,&kind,
			time_i,&time_d,&navlon,&navlat,
			&speed,&heading,
			&distance,&altitude,&sonardepth,
			&beams_bath,&beams_amp,&pixels_ss,
			beamflag,bath,amp,bathacrosstrack,bathalongtrack,
			ss,ssacrosstrack,ssalongtrack,
			comment,&error);

		/* print debug statements */
		if (verbose >= 2)
			{
			fprintf(stderr,"\ndbg2  Ping read in program <%s>\n",
				program_name);
			fprintf(stderr,"dbg2       kind:           %d\n",kind);
			fprintf(stderr,"dbg2       error:          %d\n",error);
			fprintf(stderr,"dbg2       status:         %d\n",status);
			}

		/* if survey data save the nav etc */
		if (error <= MB_ERROR_NO_ERROR
			&& kind == MB_DATA_DATA)
			{
			/* allocate memory for navigation/attitude arrays if needed */
			if (nnav + 1 >= nnav_alloc)
				{
				nnav_alloc +=  MBCTDLIST_ALLOC_CHUNK;
				status = mb_reallocd(verbose,__FILE__,__LINE__,nnav_alloc*sizeof(double),(void **)&nav_time_d,&error);
				status = mb_reallocd(verbose,__FILE__,__LINE__,nnav_alloc*sizeof(double),(void **)&nav_lon,&error);
				status = mb_reallocd(verbose,__FILE__,__LINE__,nnav_alloc*sizeof(double),(void **)&nav_lat,&error);
				status = mb_reallocd(verbose,__FILE__,__LINE__,nnav_alloc*sizeof(double),(void **)&nav_speed,&error);
				status = mb_reallocd(verbose,__FILE__,__LINE__,nnav_alloc*sizeof(double),(void **)&nav_sonardepth,&error);
				status = mb_reallocd(verbose,__FILE__,__LINE__,nnav_alloc*sizeof(double),(void **)&nav_heading,&error);
				status = mb_reallocd(verbose,__FILE__,__LINE__,nnav_alloc*sizeof(double),(void **)&nav_altitude,&error);
				if (error != MB_ERROR_NO_ERROR)
					{
					mb_error(verbose,error,&message);
					fprintf(stderr,"\nMBIO Error allocating data arrays:\n%s\n",message);
					fprintf(stderr,"\nProgram <%s> Terminated\n",
					    program_name);
					exit(error);
					}
				}

			/* save the nav etc */
			if (nnav == 0 || time_d > nav_time_d[nnav-1])
				{
				nav_time_d[nnav] = time_d;
				nav_lon[nnav] = navlon;
				nav_lat[nnav] = navlat;
				nav_speed[nnav] = speed;
				nav_sonardepth[nnav] = sonardepth;
				nav_heading[nnav] = heading;
				nav_altitude[nnav] = altitude;
				nnav++;
				}
			survey_count++;
			survey_count_tot++;
			}

		}

	/* close the swath file */
	status = mb_close(verbose,&mbio_ptr,&error);

	/* output info */
	if (verbose >= 1)
		{
		fprintf(stderr, "nav extracted from %d survey records\n", survey_count);
		}

	/* figure out whether and what to read next */
        if (read_datalist == MB_YES)
                {
		if ((status = mb_datalist_read(verbose,datalist,
				    file,&format,&file_weight,&error))
				    == MB_SUCCESS)
                        read_data = MB_YES;
                else
                        read_data = MB_NO;
                }
        else
                {
                read_data = MB_NO;
                }

	/* end loop over files in list */
	}
	if (read_datalist == MB_YES)
		mb_datalist_close(verbose,&datalist,&error);

	/* output info */
	if (verbose >= 1)
		{
		fprintf(stderr, "\nTotal %d survey records\n", survey_count_tot);
		}

	/**************************************************************************************/

	/* section 2 - read data and output ctd data with time interpolation of nav etc */

	/* open file list */
	if (read_datalist == MB_YES)
	    {
	    if ((status = mb_datalist_open(verbose,&datalist,
					    read_file,look_processed,&error)) != MB_SUCCESS)
		{
		error = MB_ERROR_OPEN_FAIL;
		fprintf(stderr,"\nUnable to open data list file: %s\n",
			read_file);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}
	    if ((status = mb_datalist_read(verbose,datalist,
			    file,&format,&file_weight,&error))
			    == MB_SUCCESS)
		read_data = MB_YES;
	    else
		read_data = MB_NO;
	    }
	/* else copy single filename to be read */
	else
	    {
	    strcpy(file, read_file);
	    read_data = MB_YES;
	    }

	/* loop over all files to be read */
	while (read_data == MB_YES)
	{
	/* initialize reading the swath file */
	if ((status = mb_read_init(
		verbose,file,format,pings,lonflip,bounds,
		btime_i,etime_i,speedmin,timegap,
		&mbio_ptr,&btime_d,&etime_d,
		&beams_bath,&beams_amp,&pixels_ss,&error)) != MB_SUCCESS)
		{
		mb_error(verbose,error,&message);
		fprintf(stderr,"\nMBIO Error returned from function <mb_read_init>:\n%s\n",message);
		fprintf(stderr,"\nMultibeam File <%s> not initialized for reading\n",file);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* allocate memory for data arrays */
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						sizeof(char), (void **)&beamflag, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						sizeof(double), (void **)&bath, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_AMPLITUDE,
						sizeof(double), (void **)&amp, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						sizeof(double), (void **)&bathacrosstrack, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_BATHYMETRY,
						sizeof(double), (void **)&bathalongtrack, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_SIDESCAN,
						sizeof(double), (void **)&ss, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_SIDESCAN,
						sizeof(double), (void **)&ssacrosstrack, &error);
	if (error == MB_ERROR_NO_ERROR)
		status = mb_register_array(verbose, mbio_ptr, MB_MEM_TYPE_SIDESCAN,
						sizeof(double), (void **)&ssalongtrack, &error);

	/* if error initializing memory then quit */
	if (error != MB_ERROR_NO_ERROR)
		{
		mb_error(verbose,error,&message);
		fprintf(stderr,"\nMBIO Error allocating data arrays:\n%s\n",
			message);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* output info */
	if (verbose >= 1)
		{
		fprintf(stderr, "\nSearching %s for CTD records\n", file);
		}

	/* read and print data */
	ctd_count = 0;
	first = MB_YES;
	while (error <= MB_ERROR_NO_ERROR)
		{
		/* read a data record */
		status = mb_get_all(verbose,mbio_ptr,&store_ptr,&kind,
			time_i,&time_d,&navlon,&navlat,
			&speed,&heading,
			&distance,&altitude,&sonardepth,
			&beams_bath,&beams_amp,&pixels_ss,
			beamflag,bath,amp,bathacrosstrack,bathalongtrack,
			ss,ssacrosstrack,ssalongtrack,
			comment,&error);

		/* print debug statements */
		if (verbose >= 2)
			{
			fprintf(stderr,"\ndbg2  Ping read in program <%s>\n",
				program_name);
			fprintf(stderr,"dbg2       kind:           %d\n",kind);
			fprintf(stderr,"dbg2       error:          %d\n",error);
			fprintf(stderr,"dbg2       status:         %d\n",status);
			}

		/* if ctd then extract data */
		if (error <= MB_ERROR_NO_ERROR
			&& (kind == MB_DATA_CTD || kind == MB_DATA_SSV))
			{
			/* extract ctd */
			status = mb_ctd(verbose, mbio_ptr, store_ptr,
						&kind, &nctd, ctd_time_d,
						ctd_conductivity, ctd_temperature,
						ctd_depth, ctd_salinity, ctd_soundspeed, &error);

			/* extract ancilliary sensor data */
			status = mb_ancilliarysensor(verbose, mbio_ptr, store_ptr,
						&kind, &nsensor, sensor_time_d,
						sensor1, sensor2, sensor3,
						sensor4, sensor5, sensor6,
						sensor7, sensor8,
						&error);

			/* loop over the nctd ctd points, outputting each one */
			if (error == MB_ERROR_NO_ERROR && nctd > 0)
				{
				for (ictd=0;ictd<nctd;ictd++)
					{
					/* get data */
					time_d = ctd_time_d[ictd];
					mb_get_date(verbose, time_d, time_i);
					conductivity = ctd_conductivity[ictd];
					temperature = ctd_temperature[ictd];
					depth = ctd_depth[ictd];
					salinity = ctd_salinity[ictd];
					soundspeed = ctd_soundspeed[ictd];

					/* get navigation */
					j = 0;
					speed = 0.0;
					interp_status = mb_linear_interp_longitude(verbose,
								nav_time_d-1, nav_lon-1,
								nnav, time_d, &navlon, &j,
								&error);
					if (interp_status == MB_SUCCESS)
					interp_status = mb_linear_interp_latitude(verbose,
								nav_time_d-1, nav_lat-1,
								nnav, time_d, &navlat, &j,
								&error);
					if (interp_status == MB_SUCCESS)
					interp_status = mb_linear_interp_heading(verbose,
								nav_time_d-1, nav_heading-1,
								nnav, time_d, &heading, &j,
								&error);
					if (interp_status == MB_SUCCESS)
					interp_status = mb_linear_interp(verbose,
								nav_time_d-1, nav_sonardepth-1,
								nnav, time_d, &sonardepth, &j,
								&error);
					if (interp_status == MB_SUCCESS)
					interp_status = mb_linear_interp(verbose,
								nav_time_d-1, nav_altitude-1,
								nnav, time_d, &altitude, &j,
								&error);
					if (interp_status == MB_SUCCESS)
					interp_status = mb_linear_interp(verbose,
								nav_time_d-1, nav_speed-1,
								nnav, time_d, &speed, &j,
								&error);

					/* only output if interpolation of nav etc has worked */
					if (interp_status == MB_YES)
						{

						/* calculate course made good and distance */
						mb_coor_scale(verbose,navlat, &mtodeglon, &mtodeglat);
						headingx = sin(DTR * heading);
						headingy = cos(DTR * heading);
						if (first == MB_YES)
							{
							time_interval = 0.0;
							course = heading;
							speed_made_good = 0.0;
							course_old = heading;
							speed_made_good_old = speed;
							distance = 0.0;
							}
						else
							{
							time_interval = time_d - time_d_old;
							dx = (navlon - navlon_old)/mtodeglon;
							dy = (navlat - navlat_old)/mtodeglat;
							distance = sqrt(dx*dx + dy*dy);
							if (distance > 0.0)
								course = RTD*atan2(dx/distance,dy/distance);
							else
								course = course_old;
							if (course < 0.0)
								course = course + 360.0;
							if (time_interval > 0.0)
								speed_made_good = 3.6*distance/time_interval;
							else
								speed_made_good
									= speed_made_good_old;
							}
						distance_total += 0.001 * distance;

						/* reset old values */
						navlon_old = navlon;
						navlat_old = navlat;
						course_old = course;
						speed_made_good_old = speed_made_good;
						time_d_old = time_d;

						/* now loop over list of output parameters */
						ctd_count++;
						ctd_count_tot++;
						if (nctd % decimate == 0)
						for (i=0; i<n_list; i++)
							{
							switch (list[i])
								{
								case '/': /* Inverts next simple value */
									invert_next_value = MB_YES;
									break;
								case '-': /* Flip sign on next simple value */
									signflip_next_value = MB_YES;
									break;
								case '^': /* use mblist definitions of CcSsTt */
									mblist_next_value = MB_YES;
									break;
								case '1': /* Sensor 1 - volts */
									printsimplevalue(verbose, sensor1[ictd], 0, 3, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									break;
								case '2': /* Sensor 2 - volts */
									printsimplevalue(verbose, sensor2[ictd], 0, 3, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									break;
								case '3': /* Sensor 3 - volts */
									printsimplevalue(verbose, sensor3[ictd], 0, 3, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									break;
								case '4': /* Sensor 4 - volts */
									printsimplevalue(verbose, sensor4[ictd], 0, 3, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									break;
								case '5': /* Sensor 5 - volts */
									printsimplevalue(verbose, sensor5[ictd], 0, 3, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									break;
								case '6': /* Sensor 6 - volts */
									printsimplevalue(verbose, sensor6[ictd], 0, 3, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									break;
								case '7': /* Sensor 7 - volts */
									printsimplevalue(verbose, sensor7[ictd], 0, 3, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									break;
								case '8': /* Sensor 8 - volts */
									printsimplevalue(verbose, sensor8[ictd], 0, 3, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									break;
								case 'C': /* Conductivity or Sonar altitude (m) */
									if (mblist_next_value == MB_NO)
										printsimplevalue(verbose, conductivity, 0, 5, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									else
										{
										printsimplevalue(verbose, altitude, 0, 3, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
										mblist_next_value = MB_NO;
										}
									break;
								case 'c': /* Temperature or sonar transducer depth (m) */
									if (mblist_next_value == MB_NO)
										printsimplevalue(verbose, temperature, 0, 5, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									else
										{
										printsimplevalue(verbose, sonardepth, 0, 3, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
										mblist_next_value = MB_NO;
										}
									break;
								case 'H': /* heading */
									printsimplevalue(verbose, heading, 6, 2, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									break;
								case 'h': /* course */
									printsimplevalue(verbose, course, 6, 2, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									break;
								case 'J': /* time string */
									mb_get_jtime(verbose,time_i,time_j);
									seconds = time_i[5] + 0.000001 * time_i[6];
									if (ascii == MB_YES)
									    {
									    printf("%.4d %.3d %.2d %.2d %9.6f",
										time_j[0],time_j[1],
										time_i[3],time_i[4],
										seconds);
									    }
									else
									    {
									    b = time_j[0];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = time_j[1];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = time_i[3];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = time_i[4];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = time_i[5];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = time_i[6];
									    fwrite(&b, sizeof(double), 1, stdout);
									    }
									break;
								case 'j': /* time string */
									mb_get_jtime(verbose,time_i,time_j);
									seconds = time_i[5] + 0.000001 * time_i[6];
									if (ascii == MB_YES)
									    {
									    printf("%.4d %.3d %.4d %9.6f",
										time_j[0],time_j[1],
										time_j[2],seconds);
									    }
									else
									    {
									    b = time_j[0];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = time_j[1];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = time_j[2];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = time_j[3];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = time_j[4];
									    fwrite(&b, sizeof(double), 1, stdout);
									    }
									break;
								case 'L': /* along-track distance (km) */
									printsimplevalue(verbose, distance_total, 7, 3, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									break;
								case 'l': /* along-track distance (m) */
									printsimplevalue(verbose, 1000.0 * distance_total, 7, 3, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									break;
								case 'M': /* Decimal unix seconds since
										1/1/70 00:00:00 */
									printsimplevalue(verbose, time_d, 0, 6, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									break;
								case 'm': /* time in decimal seconds since
										first record */
									if (first_m == MB_YES)
										{
										time_d_ref = time_d;
										first_m = MB_NO;
										}
									b = time_d - time_d_ref;
									printsimplevalue(verbose, b, 0, 6, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									break;
								case 'P': /* potential temperature (degrees) */
									/* approximation taken from http://mason.gmu.edu/~bklinger/seawater.pdf
									  on 4/25/2012 - to be replaced by a better calculation at some point */
									potentialtemperature = temperature
												- 0.04 * (1.0 + 0.185 * temperature + 0.35 * (salinity - 35.0)) * (sonardepth / 1000.0)
												-  0.0075 * (1.0 - temperature / 30.0) * (sonardepth * sonardepth / 1000000.0);
									printsimplevalue(verbose, potentialtemperature, 0, 5, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									break;
								case 'S': /* salinity or speed */
									if (mblist_next_value == MB_NO)
										printsimplevalue(verbose, salinity, 0, 5, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									else
										{
										printsimplevalue(verbose, speed, 5, 2, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
										mblist_next_value = MB_NO;
										}
									break;
								case 's': /* speed made good */
									if (mblist_next_value == MB_NO)
										printsimplevalue(verbose, soundspeed, 0, 3, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									else
										{
										printsimplevalue(verbose, speed_made_good, 5, 2, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
										mblist_next_value = MB_NO;
										}
									break;
								case 'T': /* yyyy/mm/dd/hh/mm/ss time string */
									seconds = time_i[5] + 1e-6 * time_i[6];
									if (ascii == MB_YES)
									    printf("%.4d/%.2d/%.2d/%.2d/%.2d/%9.6f",
										time_i[0],time_i[1],time_i[2],
										time_i[3],time_i[4],seconds);
									else
									    {
									    b = time_i[0];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = time_i[1];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = time_i[2];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = time_i[3];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = time_i[4];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = seconds;
									    fwrite(&b, sizeof(double), 1, stdout);
									    }
									break;
								case 't': /* yyyy mm dd hh mm ss time string */
									seconds = time_i[5] + 1e-6 * time_i[6];
									if (ascii == MB_YES)
									    printf("%.4d %.2d %.2d %.2d %.2d %9.6f",
										time_i[0],time_i[1],time_i[2],
										time_i[3],time_i[4],seconds);
									else
									    {
									    b = time_i[0];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = time_i[1];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = time_i[2];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = time_i[3];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = time_i[4];
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = seconds;
									    fwrite(&b, sizeof(double), 1, stdout);
									    }
									break;
								case 'U': /* unix time in seconds since 1/1/70 00:00:00 */
									time_u = (int) time_d;
									if (ascii == MB_YES)
									    printf("%ld",time_u);
									else
									    {
									    b = time_u;
									    fwrite(&b, sizeof(double), 1, stdout);
									    }
									break;
								case 'u': /* time in seconds since first record */
									time_u = (int) time_d;
									if (first_u == MB_YES)
										{
										time_u_ref = time_u;
										first_u = MB_NO;
										}
									if (ascii == MB_YES)
									    printf("%ld",time_u - time_u_ref);
									else
									    {
									    b = time_u - time_u_ref;
									    fwrite(&b, sizeof(double), 1, stdout);
									    }
									break;
								case 'V': /* time in seconds since last value */
								case 'v':
									if (ascii == MB_YES)
									    {
									    if ( fabs(time_interval) > 100. )
										printf("%g",time_interval);
									    else
										printf("%7.3f",time_interval);
									    }
									else
									    {
									    fwrite(&time_interval, sizeof(double), 1, stdout);
									    }
									break;
								case 'X': /* longitude decimal degrees */
									dlon = navlon;
									printsimplevalue(verbose, dlon, 11, 6, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									break;
								case 'x': /* longitude degress + decimal minutes */
									dlon = navlon;
									if (dlon < 0.0)
										{
										hemi = 'W';
										dlon = -dlon;
										}
									else
										hemi = 'E';
									degrees = (int) dlon;
									minutes = 60.0*(dlon - degrees);
									if (ascii == MB_YES)
									    {
									    printf("%3d %8.5f%c",
										degrees, minutes, hemi);
									    }
									else
									    {
									    b = degrees;
									    if (hemi == 'W') b = -b;
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = minutes;
									    fwrite(&b, sizeof(double), 1, stdout);
									    }
									break;
								case 'Y': /* latitude decimal degrees */
									dlat = navlat;
									printsimplevalue(verbose, dlat, 11, 6, ascii,
											    &invert_next_value,
											    &signflip_next_value, &error);
									break;
								case 'y': /* latitude degrees + decimal minutes */
									dlat = navlat;
									if (dlat < 0.0)
										{
										hemi = 'S';
										dlat = -dlat;
										}
									else
										hemi = 'N';
									degrees = (int) dlat;
									minutes = 60.0*(dlat - degrees);
									if (ascii == MB_YES)
									    {
									    printf("%3d %8.5f%c",
										degrees, minutes, hemi);
									    }
									else
									    {
									    b = degrees;
									    if (hemi == 'S') b = -b;
									    fwrite(&b, sizeof(double), 1, stdout);
									    b = minutes;
									    fwrite(&b, sizeof(double), 1, stdout);
									    }
									break;
								default:
									if (ascii == MB_YES)
									    printf("<Invalid Option: %c>",
										list[i]);
									break;
								}
							if (ascii == MB_YES)
								{
								if (i<(n_list-1)) printf ("%s", delimiter);
								else printf ("\n");
								}
							}
						first = MB_NO;
						}
					}
				}
			}

		/* else if survey data ignore */
		else if (error <= MB_ERROR_NO_ERROR
			&& kind == MB_DATA_DATA)
			{
			}

		}

	/* close the swath file */
	status = mb_close(verbose,&mbio_ptr,&error);

	/* output info */
	if (verbose >= 1)
		{
		fprintf(stderr, "%d CTD records\n", ctd_count);
		}

	/* figure out whether and what to read next */
        if (read_datalist == MB_YES)
                {
		if ((status = mb_datalist_read(verbose,datalist,
				    file,&format,&file_weight,&error))
				    == MB_SUCCESS)
                        read_data = MB_YES;
                else
                        read_data = MB_NO;
                }
        else
                {
                read_data = MB_NO;
                }

	/* end loop over files in list */
	}
	if (read_datalist == MB_YES)
		mb_datalist_close(verbose,&datalist,&error);

	/* output info */
	if (verbose >= 1)
		{
		fprintf(stderr, "\nTotal %d CTD records\n", ctd_count_tot);
		}

	/* deallocate navigation arrays */
	if (nnav > 0)
		{
		status = mb_freed(verbose,__FILE__,__LINE__,(void **)&nav_time_d,&error);
		status = mb_freed(verbose,__FILE__,__LINE__,(void **)&nav_lon,&error);
		status = mb_freed(verbose,__FILE__,__LINE__,(void **)&nav_lat,&error);
		status = mb_freed(verbose,__FILE__,__LINE__,(void **)&nav_speed,&error);
		status = mb_freed(verbose,__FILE__,__LINE__,(void **)&nav_sonardepth,&error);
		status = mb_freed(verbose,__FILE__,__LINE__,(void **)&nav_heading,&error);
		status = mb_freed(verbose,__FILE__,__LINE__,(void **)&nav_altitude,&error);
		}

	/* check memory */
	if (verbose >= 4)
		status = mb_memory_list(verbose,&error);

	/* print output debug statements */
	if (verbose >= 2)
		{
		fprintf(stderr,"\ndbg2  Program <%s> completed\n",
			program_name);
		fprintf(stderr,"dbg2  Ending status:\n");
		fprintf(stderr,"dbg2       status:  %d\n",status);
		}

	/* end it all */
	exit(error);
}