Example #1
0
int main (int argc, char **argv)
{
	char program_name[] = "mbnavlist";
	char help_message[] =  "mbnavlist prints the specified contents of navigation records\nin a swath sonar data file to stdout. The form of the \noutput is quite flexible; mbnavlist is tailored to produce \nascii files in spreadsheet style with data columns separated by tabs.";
	char usage_message[] = "mbnavlist [-Byr/mo/da/hr/mn/sc -Ddecimate -Eyr/mo/da/hr/mn/sc \n-Fformat -Gdelimiter -H -Ifile -Kkind -Llonflip \n-Ooptions -Rw/e/s/n -Sspeed \n-Ttimegap -V -Zsegment]";
	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	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;

	/* data record source types */
	int	nav_source;
	int	heading_source;
	int	vru_source;
	int	svp_source;
	int	aux_nav_channel = -1;
	int	data_kind = -1;

	/* output format list controls */
	char	list[MAX_OPTIONS];
	int	n_list;
	double	distance_total;
	int	nread;
	int	time_j[5];
	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;
	double	draft;
	double	roll;
	double	pitch;
	double	heave;
	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];
	int	atime_i[7 * MB_ASYNCH_SAVE_MAX];
	double	atime_d[MB_ASYNCH_SAVE_MAX];
	double	anavlon[MB_ASYNCH_SAVE_MAX];
	double	anavlat[MB_ASYNCH_SAVE_MAX];
	double	aspeed[MB_ASYNCH_SAVE_MAX];
	double	aheading[MB_ASYNCH_SAVE_MAX];
	double	adraft[MB_ASYNCH_SAVE_MAX];
	double	aroll[MB_ASYNCH_SAVE_MAX];
	double	apitch[MB_ASYNCH_SAVE_MAX];
	double	aheave[MB_ASYNCH_SAVE_MAX];

	/* 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;

	/* 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	inav, n;
	int	nnav;
	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 datalist.mb-1 */
	strcpy (read_file, "datalist.mb-1");

	/* set up the default list controls
		(lon, lat, along-track distance, center beam depth) */
	list[0]='t';
	list[1]='M';
	list[2]='X';
	list[3]='Y';
	list[4]='H';
	list[5]='s';
	n_list = 6;
	sprintf(delimiter, "\t");
	decimate = 1;

	/* process argument list */
	while ((c = getopt(argc, argv, "AaB:b:D:d:E:e:F:f:G:g:I:i:K:k:L:l:N:n:O:o:R:r:S:s:T:t: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 '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,"%d", &decimate);
			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,"%s", delimiter);
			flag++;
			break;
		case 'I':
		case 'i':
			sscanf (optarg,"%s", read_file);
			flag++;
			break;
		case 'K':
		case 'k':
			sscanf (optarg,"%d", &data_kind);
			flag++;
			break;
		case 'L':
		case 'l':
			sscanf (optarg,"%d", &lonflip);
			flag++;
			break;
		case 'N':
		case 'n':
			sscanf (optarg,"%d", &aux_nav_channel);
			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];
			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 '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,"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       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       aux_nav_channel:%d\n",aux_nav_channel);
		fprintf(stderr,"dbg2       data_kind:      %d\n",data_kind);
		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;

	/* 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)
	{
	/* check format and get data sources */
	if ((status = mb_format_source(verbose, &format,
			&nav_source, &heading_source,
			&vru_source, &svp_source,
			&error)) == MB_FAILURE)
		{
		mb_error(verbose,error,&message);
		fprintf(stderr,"\nMBIO Error returned from function <mb_format_source>:\n%s\n",message);
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(error);
		}

	/* set auxilliary nav source if requested
		- note this is superceded by data_kind if the -K option is used */
	if (aux_nav_channel > 0)
		{
		if (aux_nav_channel == 1)
		    nav_source = MB_DATA_NAV1;
		else if (aux_nav_channel == 2)
		    nav_source = MB_DATA_NAV2;
		else if (aux_nav_channel == 3)
		    nav_source = MB_DATA_NAV3;
		}

	/* 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);
		}

	/* read and print data */
	distance_total = 0.0;
	nread = 0;
	nnav = 0;
	first = MB_YES;
	while (error <= MB_ERROR_NO_ERROR)
		{
		/* read a ping of data */
		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);

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

		/* check for appropriate navigation record */

		/* if the -K option is used look for a particular
			sort of data record */
		if (error <= MB_ERROR_NO_ERROR
			&& data_kind > 0)
			{
			if (error <= MB_ERROR_NO_ERROR
				&& kind == data_kind)
				{
				error = MB_ERROR_NO_ERROR;
				status = MB_SUCCESS;
				}
			else
				{
				error = MB_ERROR_IGNORE;
				status = MB_FAILURE;
				}
			}
		else if (error <= MB_ERROR_NO_ERROR
			&& kind != nav_source)
			{
			error = MB_ERROR_IGNORE;
			status = MB_FAILURE;
			}
		else if (error <= MB_ERROR_NO_ERROR
			&& kind == nav_source)
			{
			error = MB_ERROR_NO_ERROR;
			status = MB_SUCCESS;
			}

		/* extract additional nav info */
		if (error == MB_ERROR_NO_ERROR)
		   	status = mb_extract_nnav(verbose,mbio_ptr,store_ptr,
					MB_ASYNCH_SAVE_MAX, &kind, &n,
				    	atime_i,atime_d,anavlon,anavlat,
				    	aspeed,aheading,adraft,
					aroll,apitch,aheave,&error);

		/* increment counter */
		if (error == MB_ERROR_NO_ERROR)
			nread++;

		/* print debug statements */
		if (verbose >= 2)
			{
			fprintf(stderr,"\ndbg2  Nsv data 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);
			fprintf(stderr,"dbg2       n:              %d\n",n);
			}

		/* loop over the n navigation points, outputting each one */
		/* calculate course made good and distance */
		if (error == MB_ERROR_NO_ERROR && n > 0)
			{
			for (inav=0;inav<n;inav++)
				{
				/* get data */
				for (j=0;j<7;j++)
					time_i[j] = atime_i[inav * 7 + j];
				time_d = atime_d[inav];
				navlon = anavlon[inav];
				navlat = anavlat[inav];
				speed = aspeed[inav];
				heading = aheading[inav];
				draft = adraft[inav];
				roll = aroll[inav];
				pitch = apitch[inav];
				heave = aheave[inav];

/*fprintf(stdout, "kind:%d error:%d %d of %d: time:%4d/%2d/%2d %2.2d:%2.2d:%2.2d.%6.6d\n",
kind, error, i, n,
time_i[0],  time_i[1],  time_i[2],
time_i[3],  time_i[4],  time_i[5],   time_i[6]);*/

				/* 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 */
				if (nnav % 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 'c': /* Sonar transducer depth (m) */
							printsimplevalue(verbose, sonardepth, 0, 3, ascii,
									    &invert_next_value,
									    &signflip_next_value, &error);
							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);
							if (ascii == MB_YES)
							    {
							    printf("%.4d %.3d %.2d %.2d %.2d.%6.6d",
								time_j[0],time_j[1],
								time_i[3],time_i[4],
								time_i[5],time_i[6]);
							    }
							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);
							if (ascii == MB_YES)
							    {
							    printf("%.4d %.3d %.4d %.2d.%6.6d",
								time_j[0],time_j[1],
								time_j[2],time_j[3],time_j[4]);
							    }
							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': /* pitch */
							printsimplevalue(verbose, pitch, 5, 2, ascii,
									    &invert_next_value,
									    &signflip_next_value, &error);
							break;
						case 'p': /* draft */
							printsimplevalue(verbose, draft, 5, 2, ascii,
									    &invert_next_value,
									    &signflip_next_value, &error);
							break;
						case 'R': /* roll */
							printsimplevalue(verbose, roll, 5, 2, ascii,
									    &invert_next_value,
									    &signflip_next_value, &error);
							break;
						case 'r': /* heave */
							printsimplevalue(verbose, heave, 5, 2, ascii,
									    &invert_next_value,
									    &signflip_next_value, &error);
							break;
						case 'S': /* speed */
							printsimplevalue(verbose, speed, 5, 2, ascii,
									    &invert_next_value,
									    &signflip_next_value, &error);
							break;
						case 's': /* speed made good */
							printsimplevalue(verbose, speed_made_good, 5, 2, ascii,
									    &invert_next_value,
									    &signflip_next_value, &error);
							break;
						case 'T': /* yyyy/mm/dd/hh/mm/ss time string */
							if (ascii == MB_YES)
							    printf("%.4d/%.2d/%.2d/%.2d/%.2d/%.2d.%.6d",
								time_i[0],time_i[1],time_i[2],
								time_i[3],time_i[4],time_i[5],
								time_i[6]);
							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 = time_i[5] + 1e-6 * time_i[6];
							    fwrite(&b, sizeof(double), 1, stdout);
							    }
							break;
						case 't': /* yyyy mm dd hh mm ss time string */
							if (ascii == MB_YES)
							    printf("%.4d %.2d %.2d %.2d %.2d %.2d.%.6d",
								time_i[0],time_i[1],time_i[2],
								time_i[3],time_i[4],time_i[5],
								time_i[6]);
							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 = time_i[5] + 1e-6 * time_i[6];
							    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 ping */
						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, 14, 9, 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 %9.6f%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, 14, 9, 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 %9.6f%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");
						}
					}
				nnav++;
				first = MB_NO;
				}
			}
		}

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

	/* 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);

	/* 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);
}
Example #2
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);
}
Example #3
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);
}
Example #4
0
/*----------------------------------------------------------------------*/
int main(int argc, char **argv)
{
	/* MBIO status variables */
	int status = MB_SUCCESS;
	int error = MB_ERROR_NO_ERROR;

	/* MBIO read control parameters */
	int read_datalist = MB_NO;
	void *datalist;
	int look_processed = MB_DATALIST_LOOK_UNSET;
	double file_weight;
	mb_path ifile;

	/* MBIO read values */
	int read_data;

	/* counting variables */
	counts filerecs;
	counts totrecs;

	/* processing variables */
	options opts;
	mbdefaults mbdflts;

	/* set default options */
	default_options(&opts);

	/* mb_mem_debug_on(opts.verbose, &error); */

	/* get mbsystem default values */
	status = mb_defaults(opts.verbose, &(mbdflts.format), &(mbdflts.pings_get),
		&(mbdflts.lonflip), mbdflts.bounds, mbdflts.btime_i,
		mbdflts.etime_i, &(mbdflts.speedmin),
		&(mbdflts.timegap));

	if (status == MB_SUCCESS)
		{
		parse_options(opts.verbose, argc, argv, &opts, &error);
		}

	if (opts.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 debug statements */
	if (opts.verbose >= 1)
		{
		print_mbdefaults(opts.verbose, &opts, &mbdflts, &error);
		}

	/* if help desired then print it and exit */
	if (opts.help)
		{
		fprintf(stderr, "\nProgram %s\n", program_name);
		fprintf(stderr, "Version %s\n", rcs_id);
		fprintf(stderr, "MB-system Version %s\n", MB_VERSION);
		fprintf(stderr, "\nusage: %s\n", usage_message);
		fprintf(stderr, "\n%s\n", help_message);
		exit(error);
		}
		
	/* get format if required */
	if (opts.format == 0)
		{
		mb_get_format(opts.verbose, opts.read_file, NULL, &(opts.format),
			&error);
		}

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

	/* open file list */
	if (read_datalist == MB_YES)
		{
		if ((status =
			mb_datalist_open(opts.verbose, &datalist, opts.read_file,
				look_processed, &error)) != MB_SUCCESS)
			{
			char message[MAX_ERROR_STRING];
			sprintf(message, "Unable to open data list file: %s\n",
				opts.read_file);
			error_exit(opts.verbose, MB_ERROR_OPEN_FAIL, "mb_datalist_open",
				message);
			}

		if ((status =
			mb_datalist_read(opts.verbose, datalist, ifile, &(opts.format),
				&file_weight, &error)) == MB_SUCCESS)
			{
			read_data = MB_YES;
			}
		else
			{
			read_data = MB_NO;
			}
		}
	/* else copy single filename to be read */
	else
		{
		strcpy(ifile, opts.read_file);
		read_data = MB_YES;
		}

	/* reset total record counter */
	zero_counts(opts.verbose, &totrecs, &error);

	/* loop over files to be read */
	while (read_data == MB_YES)
		{
		/* reset file record counter */
		zero_counts(opts.verbose, &filerecs, &error);

		/* process the output files */
		if (status == MB_SUCCESS)
			{
			status = process_output(opts.verbose, &mbdflts, &opts, ifile,
				&filerecs, &error);
			}

		/* output counts */
		filerecs.files_read++;
		if (opts.verbose >= 1)
			{
			fprintf(stdout, "\nData records read from: %s\n", ifile);
			print_counts(opts.verbose, &filerecs, &error);
			}

		/* add this file's counts to total */
		add_counts(opts.verbose, &totrecs, &filerecs, &error);

		/* figure out whether and what to read next */
		if (read_datalist == MB_YES)
			{
			if ((status =
				mb_datalist_read(opts.verbose, datalist, ifile, &(opts.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 */

	/* output counts */
	if (opts.verbose >= 1)
		{
		fprintf(stdout, "\nTotal data records read:\n");
		print_counts(opts.verbose, &totrecs, &error);
		}

	if (read_datalist == MB_YES)
		{
		mb_datalist_close(opts.verbose, &datalist, &error);
		}

	/* check memory */
	status = mb_memory_list(opts.verbose, &error);

	/* mb_mem_debug_off(opts.verbose, &error); */

	return (status);
}	/* main */
Example #5
0
/*----------------------------------------------------------------------*/
static int set_outfile_names(int verbose, mb_path *ofile, mb_path ifile,
	mb_path *basename, int ofile_set, int split_txers,
	int *error)
{
	char *function_name = "set_outfile_names";
	mb_path fileroot;
	int format;
	int status = MB_SUCCESS;
	int 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       ofile:      %p\n", (void *)ofile);
		fprintf(stderr, "dbg2       ifile:      %p\n", (void *)ifile);
		}

	/* clear ofile array */
	for (i = 0; i < SWPLS_MAX_TXERS; i++)
		{
		strncpy(ofile[i], "", sizeof(ofile[i]));
		}

	/* get the fileroot name and format from the input name */
	status = mb_get_format(verbose, ifile, fileroot, &format, error);

	if ((ofile_set == MB_NO) && (split_txers == MB_NO))
		{
		if ((format == MBF_SWPLSSXP) &&
			(strncmp(".sxp", &ifile[strlen(ifile) - 4], 4) == 0))
			{
			sprintf(ofile[0], "%s.mb%d", fileroot, format);
			}
		else if ((format == MBF_SWPLSSXI) &&
			(strncmp(".sxi", &ifile[strlen(ifile) - 4], 4) == 0))
			{
			sprintf(ofile[0], "%s.mb%d", fileroot, format);
			}
		else
			{
			sprintf(ofile[0], "%s.mb%d", ifile, format);
			}
		}
	else if ((ofile_set == MB_NO) && (split_txers == MB_YES))
		{
		if ((format == MBF_SWPLSSXP) &&
			(strncmp(".sxp", &ifile[strlen(ifile) - 4], 4) == 0))
			{
			for (i = 0; i < SWPLS_MAX_TXERS; i++)
				{
				sprintf(ofile[i], "%s_txer%d.mb%d", fileroot, i + 1, format);
				}
			}
		else if ((format == MBF_SWPLSSXI) &&
			(strncmp(".sxi", &ifile[strlen(ifile) - 4], 4) == 0))
			{
			for (i = 0; i < SWPLS_MAX_TXERS; i++)
				{
				sprintf(ofile[i], "%s_txer%d.mb%d", fileroot, i + 1, format);
				}
			}
		else
			{
			for (i = 0; i < SWPLS_MAX_TXERS; i++)
				{
				sprintf(ofile[i], "%s_txer%d.mb%d", ifile, i + 1, format);
				}
			}
		}
	else if ((ofile_set == MB_YES) && (split_txers == MB_NO))
		{
		if ((format == MBF_SWPLSSXP) &&
			(strncmp(".sxp", &ifile[strlen(ifile) - 4], 4) == 0))
			{
			sprintf(ofile[0], "%s.mb%d", *basename, format);
			}
		else if ((format == MBF_SWPLSSXI) &&
			(strncmp(".sxi", &ifile[strlen(ifile) - 4], 4) == 0))
			{
			sprintf(ofile[0], "%s.mb%d", *basename, format);
			}
		else
			{
			sprintf(ofile[0], "%s.mb%d", ifile, format);
			}
		}
	else if ((ofile_set == MB_YES) && (split_txers == MB_YES))
		{
		if ((format == MBF_SWPLSSXP) &&
			(strncmp(".sxp", &ifile[strlen(ifile) - 4], 4) == 0))
			{
			for (i = 0; i < SWPLS_MAX_TXERS; i++)
				{
				sprintf(ofile[i], "%s_txer%d.mb%d", *basename, i + 1, format);
				}
			}
		else if ((format == MBF_SWPLSSXI) &&
			(strncmp(".sxi", &ifile[strlen(ifile) - 4], 4) == 0))
			{
			for (i = 0; i < SWPLS_MAX_TXERS; i++)
				{
				sprintf(ofile[i], "%s_txer%d.mb%d", *basename, i + 1, format);
				}
			}
		else
			{
			for (i = 0; i < SWPLS_MAX_TXERS; i++)
				{
				sprintf(ofile[i], "%s_txer%d.mb%d", ifile, i + 1, format);
				}
			}
		}

	if (verbose >= 2)
		{
		fprintf(stderr, "\ndbg2  function <%s> completed\n", function_name);
		fprintf(stderr, "dbg2  Return values:\n");
		for (i = 0; i < SWPLS_MAX_TXERS; i++)
			{
			fprintf(stderr, "dbg2    ofile[%d]:      %s\n", i, ofile[i]);
			}
		fprintf(stderr, "dbg2       error:      %d\n", *error);
		fprintf(stderr, "dbg2  Return status:\n");
		fprintf(stderr, "dbg2       status:     %d\n", status);
		}

	return (status);
}	/* set_outfile_names */
Example #6
0
int main
(
  int argc,
  char **argv
)
{
  static char program_name[] = "mbotps";
  static char help_message[] =
    "MBotps predicts tides using methods and data derived from the OSU Tidal Prediction Software (OTPS) distributions.";
  static char usage_message[] =
    "mbotps [-Atideformat -Byear/month/day/hour/minute/second -Ctidestationformat\n"
    "\t-Dinterval -Eyear/month/day/hour/minute/second -Fformat\n"
    "\t-Idatalist -Lopts_path -Ntidestationfile -Ooutput -Potps_location\n"
    "\t-Rlon/lat -S -Tmodel -Utidestationlon/tidestationlat -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;
  mb_path read_file;
  void *datalist;
  int look_processed = MB_DATALIST_LOOK_UNSET;
  double file_weight;
  mb_path swath_file;
  mb_path file;
  mb_path dfile;
  int format;
  int pings;
  int lonflip;
  double bounds[4];
  double speedmin;
  double timegap;
  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];

  /* mbotps control parameters */
  mb_path otps_location_use;
  int notpsmodels = 0;
  int nmodeldatafiles = 0;
  int mbotps_mode = MBOTPS_MODE_POSITION;
  double tidelon;
  double tidelat;
  double btime_d;
  double etime_d;
  int btime_i[7];
  int etime_i[7];
  double interval = 300.0;
  mb_path tide_file;
  int mbprocess_update = MB_NO;
  int skip_existing = MB_NO;
  int tideformat = 2;
  int ngood;

  /* tide station data */
  mb_path tidestation_file;
  double tidestation_lon = 0.0;
  double tidestation_lat = 0.0;
  int tidestation_format = 2;
  int tidestation_ok = MB_NO;
  int ntidestation = 0;
  double *tidestation_time_d = NULL;
  double *tidestation_tide = NULL;
  double *tidestation_model = NULL;
  double *tidestation_correction = NULL;
  int time_j[5];
  int tidestation_stime_i[7], tidestation_etime_i[7];
  double tidestation_stime_d, tidestation_etime_d;
  double tidestation_d_min, tidestation_d_max;
  double tidestation_m_min, tidestation_m_max;
  double tidestation_c_min, tidestation_c_max;
  int ihr, intstat, itime;
  int size;
  double sec, correction;

  /* time parameters */
  time_t right_now;
  char date[32], user[MB_PATH_MAXLINE], *user_ptr, host[MB_PATH_MAXLINE];
  int pid;

  FILE *tfp, *mfp, *ofp;
  struct stat file_status;
  int fstat;
  double start_time_d;
  double end_time_d;
  int istart, iend;
  int proceed = MB_YES;
  int input_size, input_modtime, output_size, output_modtime;
  mb_path lltfile = "";
  mb_path otpsfile = "";
  mb_path line = "";
  mb_path predict_tide = "";
  int otps_model_set = MB_NO;
  mb_path otps_model = "";
  mb_path modelname = "";
  mb_path modelfile = "";
  mb_path modeldatafile = "";
  int read_data;
  int ntime;
  int nread;
  int nline;
  int nget;
  int output;
  double savetime_d;
  double lasttime_d;
  double lastlon;
  double lastlat;
  double lon;
  double lat;
  double tide;
  double depth;
  char *result;
  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");

  /* set default location of the OTPS package */
  strcpy(otps_location_use, otps_location);

  /* set defaults for the AUV survey we were running on Coaxial Segment, Juan de Fuca Ridge
      while I wrote this code */
  sprintf(otps_model, MBOTPS_DEFAULT_MODEL);
  sprintf(tide_file, "tide_model.txt");
  tidelon = -129.588618;
  tidelat = 46.50459;
  interval = 60.0;
  btime_i[0] = 2009;
  btime_i[1] = 7;
  btime_i[2] = 31;
  btime_i[3] = 0;
  btime_i[4] = 0;
  btime_i[5] = 0;
  btime_i[6] = 0;
  etime_i[0] = 2009;
  etime_i[1] = 8;
  etime_i[2] = 2;
  etime_i[3] = 1;
  etime_i[4] = 0;
  etime_i[5] = 0;
  etime_i[6] = 0;

  /* process argument list */
  while ((c =
    getopt(argc, argv, "A:a:B:b:C:c:D:d:E:e:F:f:I:i:MmN:n:O:o:P:p:R:r:SST:t:U:u:VvHh")) != -1)
    switch (c)
      {
    case 'H':
    case 'h':
      help++;
      break;
    case 'V':
    case 'v':
      verbose++;
      break;
    case 'A':
    case 'a':
      sscanf(optarg, "%d", &tideformat);
      if (tideformat != 2)
        tideformat = 1;
      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 'C':
    case 'c':
      sscanf(optarg, "%d", &tidestation_format);
      if (tidestation_format < 1 || tidestation_format > 4)
        tidestation_format = 2;
      break;
    case 'D':
    case 'd':
      sscanf(optarg, "%lf", &interval);
      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 'I':
    case 'i':
      sscanf(optarg, "%s", read_file);
      mbotps_mode = mbotps_mode | MBOTPS_MODE_NAVIGATION;
      flag++;
      break;
    case 'M':
    case 'm':
      mbprocess_update = MB_YES;
      break;
    case 'N':
    case 'n':
      sscanf(optarg, "%s", tidestation_file);
      mbotps_mode = mbotps_mode | MBOTPS_MODE_TIDESTATION;
      break;
    case 'O':
    case 'o':
      sscanf(optarg, "%s", tide_file);
      break;
    case 'P':
    case 'p':
      sscanf(optarg, "%s", otps_location_use);
      break;
    case 'R':
    case 'r':
      sscanf(optarg, "%lf/%lf", &tidelon, &tidelat);
      break;
    case 'S':
    case 's':
      skip_existing = MB_YES;
      break;
    case 'T':
    case 't':
      sscanf(optarg, "%s", otps_model);
      otps_model_set = MB_YES;
      break;
    case 'U':
    case 'u':
      sscanf(optarg, "%lf/%lf", &tidestation_lon, &tidestation_lat);
      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);
    }

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

  /* Check for available tide models */
  if (help || ( verbose > 0) )
    {
    fprintf(stderr, "\nChecking for available OTPS tide models\n");
    fprintf(stderr, "OTPS location: %s\nValid OTPS tidal models:\n", otps_location_use);
    }
  notpsmodels = 0;
  sprintf(line, "/bin/ls -1 %s/DATA | grep Model_ | sed \"s/^Model_//\"", otps_location_use);
  if ((tfp = popen(line, "r")) != NULL)
    {
    /* send relevant input to predict_tide through its stdin stream */
    while (fgets(line, sizeof(line), tfp))
      {
      sscanf(line, "%s", modelname);
      sprintf(modelfile, "%s/DATA/Model_%s", otps_location_use, modelname);
      nmodeldatafiles = 0;

      /* check the files referenced in the model file */
      if ((mfp = fopen(modelfile, "r")) != NULL)
        {
        /* stat the file referenced in each line */
        while (fgets(modeldatafile, MB_PATH_MAXLINE, mfp) != NULL)
          {
          if (strlen(modeldatafile) > 0)
            modeldatafile[strlen(modeldatafile) - 1] = '\0';
          if (( (fstat =
            stat(modeldatafile,
              &file_status)) == 0) && ( (file_status.st_mode & S_IFMT) != S_IFDIR) )
            nmodeldatafiles++;
          }
        fclose(mfp);
        }
      if (nmodeldatafiles >= 3)
        {
        if (help || ( verbose > 0) )
          fprintf(stderr, "     %s\n", modelname);
        if (otps_model_set == MB_NO)
          if (( notpsmodels == 0) || ( strcmp(modelname, MBOTPS_DEFAULT_MODEL) == 0) )
            strcpy(otps_model, modelname);
        notpsmodels++;
        }
      }

    /* close the process */
    pclose(tfp);
    }
  else
    {
    error = MB_ERROR_OPEN_FAIL;
    fprintf(stderr, "\nUnable to open ls using popen()\n");
    fprintf(stderr, "\nProgram <%s> Terminated\n", program_name);
    exit(MB_FAILURE);
    }
  if (help || ( verbose > 0) )
    {
    fprintf(stderr, "Number of available OTPS tide models: %d\n", notpsmodels);
    fprintf(stderr, "\nUsing OTPS tide model:            %s\n", otps_model);
    }

  /* 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       otps_location:        %s\n", otps_location);
    fprintf(stderr, "dbg2       otps_location_use:    %s\n", otps_location_use);
    fprintf(stderr, "dbg2       otps_model_set:       %d\n", otps_model_set);
    fprintf(stderr, "dbg2       otps_model:           %s\n", otps_model);
    fprintf(stderr, "dbg2       mbotps_mode:          %d\n", mbotps_mode);
    fprintf(stderr, "dbg2       tidelon:              %f\n", tidelon);
    fprintf(stderr, "dbg2       tidelat:              %f\n", tidelat);
    fprintf(stderr, "dbg2       tidestation_file:     %s\n", tidestation_file);
    fprintf(stderr, "dbg2       tidestation_lon:       %f\n", tidestation_lon);
    fprintf(stderr, "dbg2       tidestation_lat:       %f\n", tidestation_lat);
    fprintf(stderr, "dbg2       tidestation_format:    %d\n", tidestation_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       interval:             %f\n", interval);
    fprintf(stderr, "dbg2       tide_file:            %s\n", tide_file);
    fprintf(stderr, "dbg2       mbprocess_update:     %d\n", mbprocess_update);
    fprintf(stderr, "dbg2       skip_existing:        %d\n", skip_existing);
    fprintf(stderr, "dbg2       tideformat:           %d\n", tideformat);
    fprintf(stderr, "dbg2       format:               %d\n", format);
    fprintf(stderr, "dbg2       read_file:            %s\n", read_file);
    }

  /* exit if no valid OTPS models can be found */
  if (notpsmodels <= 0)
    {
    error = MB_ERROR_OPEN_FAIL;
    fprintf(stderr, "\nUnable to find a valid OTPS tidal model\n");
    fprintf(stderr, "\nProgram <%s> Terminated\n", program_name);
    exit(MB_FAILURE);
    }

  /* if help was all that was desired then exit */
  if (help)
    exit(error);

  /* -------------------------------------------------------------------------
   * if specified read in tide station data and calculate model values for the
   * same location and times- the difference is applied as a correction to the
   * model values calculated at the desired locations and times
   * -----------------------------------------------------------------------*/
  if (mbotps_mode & MBOTPS_MODE_TIDESTATION)
    {

    /* make sure longitude is positive */
    if (tidestation_lon < 0.0)
      tidestation_lon += 360.0;

    /* open the tide station data file */
    if ((tfp = fopen(tidestation_file, "r")) == NULL)
      {
      error = MB_ERROR_OPEN_FAIL;
      fprintf(stderr,
        "\nUnable to open tide station file <%s> for writing\n",
        tidestation_file);
      fprintf(stderr, "\nProgram <%s> Terminated\n", program_name);
      exit(MB_FAILURE);
      }

    /* count the lines in the tide station data */
    ntidestation = 0;
    while ((result = fgets(line, MB_PATH_MAXLINE, tfp)) == line)
      ntidestation++;
    rewind(tfp);

    /* allocate memory for tide station arrays */
    size = ntidestation * sizeof(double);
    status =mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&tidestation_time_d, &error);
    if (error == MB_ERROR_NO_ERROR)
      status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&tidestation_tide, &error);
    if (error == MB_ERROR_NO_ERROR)
      status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&tidestation_model, &error);
    if (error == MB_ERROR_NO_ERROR)
      status = mb_mallocd(verbose, __FILE__, __LINE__, size, (void **)&tidestation_correction, &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);
      }

    /* read the tide station data in the specified format */
    ntidestation = 0;
    while ((result = fgets(line, MB_PATH_MAXLINE, tfp)) == line)
      {
      tidestation_ok = MB_NO;

      /* ignore comments */
      if (line[0] != '#')
        {
        /* deal with tide station data in form: time_d tide */
        if (tidestation_format == 1)
          {
          nget = sscanf(line,
            "%lf %lf",
            &tidestation_time_d[ntidestation],
            &tidestation_tide[ntidestation]);
          if (nget == 2)
            tidestation_ok = MB_YES;
          }

        /* deal with tide station data in form: yr mon day hour min sec tide */
        else if (tidestation_format == 2)
          {
          nget = sscanf(line,
            "%d %d %d %d %d %lf %lf",
            &time_i[0],
            &time_i[1],
            &time_i[2],
            &time_i[3],
            &time_i[4],
            &sec,
            &tidestation_tide[ntidestation]);
          time_i[5] = (int)sec;
          time_i[6] = 1000000 * (sec - time_i[5]);
          mb_get_time(verbose, time_i, &time_d);
          tidestation_time_d[ntidestation] = time_d;
          if (nget == 7)
            tidestation_ok = MB_YES;
          }

        /* deal with tide station data in form: yr jday hour min sec tide */
        else if (tidestation_format == 3)
          {
          nget = sscanf(line,
            "%d %d %d %d %lf %lf",
            &time_j[0],
            &time_j[1],
            &ihr,
            &time_j[2],
            &sec,
            &tidestation_tide[ntidestation]);
          time_j[2] = time_j[2] + 60 * ihr;
          time_j[3] = (int)sec;
          time_j[4] = 1000000 * (sec - time_j[3]);
          mb_get_itime(verbose, time_j, time_i);
          mb_get_time(verbose, time_i, &time_d);
          tidestation_time_d[ntidestation] = time_d;
          if (nget == 6)
            tidestation_ok = MB_YES;
          }

        /* deal with tide station data in form: yr jday daymin sec tide */
        else if (tidestation_format == 4)
          {
          nget = sscanf(line,
            "%d %d %d %lf %lf",
            &time_j[0],
            &time_j[1],
            &time_j[2],
            &sec,
            &tidestation_tide[ntidestation]);
          time_j[3] = (int)sec;
          time_j[4] = 1000000 * (sec - time_j[3]);
          mb_get_itime(verbose, time_j, time_i);
          mb_get_time(verbose, time_i, &time_d);
          tidestation_time_d[ntidestation] = time_d;
          if (nget == 5)
            tidestation_ok = MB_YES;
          }
        }

      /* output some debug values */
      if ((verbose >= 5) && (tidestation_ok == MB_YES))
        {
        fprintf(stderr, "\ndbg5  New tide point read in program <%s>\n", program_name);
        fprintf(stderr, "dbg5       tide[%d]: %f %f\n", ntidestation,
          tidestation_time_d[ntidestation], tidestation_tide[ntidestation]);
        }
      else if (verbose >= 5)
        {
        fprintf(stderr,
          "\ndbg5  Error parsing line in tide file in program <%s>\n",
          program_name);
        fprintf(stderr, "dbg5       line: %s\n", line);
        }

      /* check for reverses or repeats in time */
      if (tidestation_ok == MB_YES)
        {
        if (ntidestation == 0)
          {
          ntidestation++;
          }
        else if (tidestation_time_d[ntidestation] > tidestation_time_d[ntidestation - 1])
          {
          ntidestation++;
          }
        else if ((ntidestation > 0) &&
          ( tidestation_time_d[ntidestation] <= tidestation_time_d[ntidestation - 1]) &&
          ( verbose >= 5) )
          {
          fprintf(stderr, "\ndbg5  Tide time error in program <%s>\n", program_name);
          fprintf(stderr,
            "dbg5       tide[%d]: %f %f\n",
            ntidestation - 1,
            tidestation_time_d[ntidestation - 1],
            tidestation_tide[ntidestation - 1]);
          fprintf(stderr,
            "dbg5       tide[%d]: %f %f\n",
            ntidestation,
            tidestation_time_d[ntidestation],
            tidestation_tide[ntidestation]);
          }
        }
      strncpy(line, "\0", sizeof(line));
      }
    fclose(tfp);

    /* now get time and tide model values at the tide station location
       first open temporary file of lat lon time*/
    pid = getpid();
    sprintf(lltfile, "tmp_mbotps_llt_%d.txt", pid);
    sprintf(otpsfile, "tmp_mbotps_llttd_%d.txt", pid);
    if ((tfp = fopen(lltfile, "w")) == NULL)
      {
      error = MB_ERROR_OPEN_FAIL;
      fprintf(stderr,
        "\nUnable to open temporary lat-lon-time file <%s> for writing\n",
        lltfile);
      fprintf(stderr, "\nProgram <%s> Terminated\n", program_name);
      exit(MB_FAILURE);
      }
    else {
      for (i = 0; i < ntidestation; i++) {
        mb_get_date(verbose, tidestation_time_d[i], time_i);
        fprintf(tfp, "%.6f %.6f %4.4d %2.2d %2.2d %2.2d %2.2d %2.2d\n",
          tidestation_lat, tidestation_lon,
          time_i[0], time_i[1], time_i[2], time_i[3], time_i[4], time_i[5]);
      }
      fclose(tfp);
    }

    /* call predict_tide with popen */
    sprintf(predict_tide, "%s/predict_tide", otps_location_use);
    if ((tfp = popen(predict_tide, "w")) == NULL)
      {
      error = MB_ERROR_OPEN_FAIL;
      fprintf(stderr, "\nUnable to open predict_time program using popen()\n");
      fprintf(stderr, "\nProgram <%s> Terminated\n", program_name);
      exit(MB_FAILURE);
      }

    /* send relevant input to predict_tide through its stdin stream */
    fprintf(tfp, "%s/DATA/Model_%s\n", otps_location_use, otps_model);
    fprintf(tfp, "%s\n", lltfile);
    fprintf(tfp, "z\n\nAP\noce\n1\n");
    /*fprintf(tfp, "z\nm2,s2,n2,k2,k1,o1,p1,q1\nAP\noce\n1\n");*/
    fprintf(tfp, "%s\n", otpsfile);

    /* close the process */
    pclose(tfp);

    /* now read results from predict_tide and rewrite them in a useful form */
    if ((tfp = fopen(otpsfile, "r")) == NULL)
      {
      error = MB_ERROR_OPEN_FAIL;
      fprintf(stderr, "\nUnable to open predict_time results temporary file <%s>\n",
        otpsfile);
      fprintf(stderr, "\nProgram <%s> Terminated\n", program_name);
      exit(MB_FAILURE);
      }

    nline = 0;
    ngood = 0;
    while ((result = fgets(line, MB_PATH_MAXLINE, tfp)) == line)
      {
      nline++;
      if (nline > 6)
        {
        nget = sscanf(line,
          "%lf %lf %d.%d.%d %d:%d:%d %lf %lf",
          &lat, &lon,
          &time_i[1], &time_i[2], &time_i[0], &time_i[3], &time_i[4], &time_i[5],
          &tide, &depth);
        if (nget == 10)
          {
          tidestation_model[ngood] = tide;
          tidestation_correction[ngood] = tidestation_tide[ngood] - tidestation_model[ngood];
          ngood++;
          }
        }
      }
    fclose(tfp);
    if (ngood != ntidestation)
      {
      error = MB_ERROR_BAD_FORMAT;
      fprintf(stderr,
        "\nNumber of tide station values does not match number of model values <%d != %d>\n",
        ntidestation,
        ngood);
      fprintf(stderr, "\nProgram <%s> Terminated\n", program_name);
      exit(MB_FAILURE);
      }

    /* get start end min max of tide station data */
    tidestation_d_min = 0.0;
    tidestation_d_max = 0.0;
    tidestation_m_min = 0.0;
    tidestation_m_max = 0.0;
    tidestation_c_min = 0.0;
    tidestation_c_max = 0.0;
    for (i = 0; i < ntidestation; i++) {
      if (i == 0) {
        tidestation_d_min = tidestation_tide[i];
        tidestation_d_max = tidestation_tide[i];
        tidestation_m_min = tidestation_model[i];
        tidestation_m_max = tidestation_model[i];
        tidestation_c_min = tidestation_correction[i];
        tidestation_c_max = tidestation_correction[i];
        tidestation_stime_d = tidestation_time_d[i];
      } else {
        tidestation_d_min = MIN(tidestation_tide[i], tidestation_d_min);
        tidestation_d_max = MAX(tidestation_tide[i], tidestation_d_max);
        tidestation_m_min = MIN(tidestation_model[i], tidestation_m_min);
        tidestation_m_max = MAX(tidestation_model[i], tidestation_m_max);
        tidestation_c_min = MIN(tidestation_correction[i], tidestation_c_min);
        tidestation_c_max = MAX(tidestation_correction[i], tidestation_c_max);
        tidestation_etime_d = tidestation_time_d[i];
      }
    }
    mb_get_date(verbose, tidestation_stime_d, tidestation_stime_i);
    mb_get_date(verbose, tidestation_etime_d, tidestation_etime_i);

    /* output info on tide station data */
    if (( verbose > 0) && mbotps_mode & MBOTPS_MODE_TIDESTATION)
      {
      fprintf(stderr, "\nTide station data file:             %s\n", tidestation_file);
      fprintf(stderr, "  Tide station longitude:           %f\n", tidestation_lon);
      fprintf(stderr, "  Tide station latitude:            %f\n", tidestation_lat);
      fprintf(stderr, "  Tide station format:              %d\n", tidestation_format);
      fprintf(stderr, "  Tide station data summary:\n");
      fprintf(stderr, "    Number of samples:              %d\n", ntidestation);
      fprintf(stderr,
        "    Start time:                     %4.4d/%2.2d/%2.2d %2.2d:%2.2d:%2.2d.%6.6d\n",
        tidestation_stime_i[0],
        tidestation_stime_i[1],
        tidestation_stime_i[2],
        tidestation_stime_i[3],
        tidestation_stime_i[4],
        tidestation_stime_i[5],
        tidestation_stime_i[6]);
      fprintf(stderr,
        "    End time:                       %4.4d/%2.2d/%2.2d %2.2d:%2.2d:%2.2d.%6.6d\n",
        tidestation_etime_i[0],
        tidestation_etime_i[1],
        tidestation_etime_i[2],
        tidestation_etime_i[3],
        tidestation_etime_i[4],
        tidestation_etime_i[5],
        tidestation_etime_i[6]);
      fprintf(stderr, "    Minimum values:     %7.3f %7.3f %7.3f\n",
              tidestation_d_min, tidestation_m_min, tidestation_c_min);
      fprintf(stderr, "    Maximum values:     %7.3f %7.3f %7.3f\n",
              tidestation_d_max, tidestation_m_max, tidestation_c_max);
      }

    /* remove the temporary files */
    unlink(lltfile);
    unlink(otpsfile);
    }

  /* -------------------------------------------------------------------------
   * calculate tide model  for a single position and time range
   * -----------------------------------------------------------------------*/
  if (!(mbotps_mode & MBOTPS_MODE_NAVIGATION))
    {
    /* first open temporary file of lat lon time */
    pid = getpid();
    sprintf(lltfile, "tmp_mbotps_llt_%d.txt", pid);
    sprintf(otpsfile, "tmp_mbotps_llttd_%d.txt", pid);
    if ((tfp = fopen(lltfile, "w")) == NULL)
      {
      error = MB_ERROR_OPEN_FAIL;
      fprintf(stderr,
        "\nUnable to open temporary lat-lon-time file <%s> for writing\n",
        lltfile);
      fprintf(stderr, "\nProgram <%s> Terminated\n", program_name);
      exit(MB_FAILURE);
      }

    /* make sure longitude is positive */
    if (tidelon < 0.0)
      tidelon += 360.0;

    /* loop over the time of interest generating the lat-lon-time values */
    mb_get_time(verbose, btime_i, &btime_d);
    mb_get_time(verbose, etime_i, &etime_d);
    ntime = 1 + (int)floor((etime_d - btime_d) / interval);
    for (i = 0; i < ntime; i++)
      {
      time_d = btime_d + i * interval;
      mb_get_date(verbose, time_d, time_i);
      fprintf(tfp,
        "%.6f %.6f %4.4d %2.2d %2.2d %2.2d %2.2d %2.2d\n",
        tidelat,
        tidelon,
        time_i[0],
        time_i[1],
        time_i[2],
        time_i[3],
        time_i[4],
        time_i[5]);
      }

    /* close the llt file */
    fclose(tfp);

    /* call predict_tide with popen */
    sprintf(predict_tide, "%s/predict_tide", otps_location_use);
    if ((tfp = popen(predict_tide, "w")) == NULL)
      {
      error = MB_ERROR_OPEN_FAIL;
      fprintf(stderr, "\nUnable to open predict_time program using popen()\n");
      fprintf(stderr, "\nProgram <%s> Terminated\n", program_name);
      exit(MB_FAILURE);
      }

    /* send relevant input to predict_tide through its stdin stream */
    fprintf(tfp, "%s/DATA/Model_%s\n", otps_location_use, otps_model);
    fprintf(tfp, "%s\n", lltfile);
    fprintf(tfp, "z\n\nAP\noce\n1\n");
    /*fprintf(tfp, "z\nm2,s2,n2,k2,k1,o1,p1,q1\nAP\noce\n1\n");*/
    fprintf(tfp, "%s\n", otpsfile);

    /* close the process */
    pclose(tfp);

    /* now read results from predict_tide and rewrite them in a useful form */
    if ((tfp = fopen(otpsfile, "r")) == NULL)
      {
      error = MB_ERROR_OPEN_FAIL;
      fprintf(stderr, "\nUnable to open predict_time results temporary file <%s>\n",
        otpsfile);
      fprintf(stderr, "\nProgram <%s> Terminated\n", program_name);
      exit(MB_FAILURE);
      }
    if ((ofp = fopen(tide_file, "w")) == NULL)
      {
      error = MB_ERROR_OPEN_FAIL;
      fprintf(stderr, "\nUnable to open tide output file <%s>\n", tide_file);
      fprintf(stderr, "\nProgram <%s> Terminated\n", program_name);
      exit(MB_FAILURE);
      }
    fprintf(ofp, "# Tide model generated by program %s\n", program_name);
    fprintf(ofp, "# MB-System Version: %s\n", MB_VERSION);
    fprintf(ofp, "# Tide model generated by program %s\n", program_name);
    fprintf(ofp, "# which in turn calls OTPS program predict_tide obtained from:\n");
    fprintf(ofp, "#     http://www.coas.oregonstate.edu/research/po/research/tide/\n");
    fprintf(ofp, "#\n");
    fprintf(ofp, "# OTPSnc tide model: \n");
    fprintf(ofp, "#      %s\n", otps_model);
    if (tideformat == 2)
      {
      fprintf(ofp, "# Output format:\n");
      fprintf(ofp, "#      year month day hour minute second tide\n");
      fprintf(ofp, "# where tide is in meters\n");
      }
    else
      {
      fprintf(ofp, "# Output format:\n");
      fprintf(ofp, "#      time_d tide\n");
      fprintf(ofp, "# where time_d is in seconds since January 1, 1970\n");
      fprintf(ofp, "# and tide is in meters\n");
      }
    right_now = time((time_t *)0);
    strcpy(date, ctime(&right_now));
    date[strlen(date) - 1] = '\0';
    if ((user_ptr = getenv("USER")) == NULL)
      user_ptr = getenv("LOGNAME");
    if (user_ptr != NULL)
      strcpy(user, user_ptr);
    else
      strcpy(user, "unknown");
    gethostname(host, MBP_FILENAMESIZE);
    fprintf(ofp, "# Run by user <%s> on cpu <%s> at <%s>\n", user, host, date);

    /* loop over tide model values, writing them out in the specified format */
    nline = 0;
    ngood = 0;
    while ((result = fgets(line, MB_PATH_MAXLINE, tfp)) == line)
      {
      nline++;
      if (( nline == 2) || ( nline == 3) )
        {
        fprintf(ofp, "#%s", line);
        }
      else if (nline > 6)
        {
        nget = sscanf(line,
          "%lf %lf %d.%d.%d %d:%d:%d %lf %lf",
          &lat,
          &lon,
          &time_i[1],
          &time_i[2],
          &time_i[0],
          &time_i[3],
          &time_i[4],
          &time_i[5],
          &tide,
          &depth);
        if (nget == 10)
          {
          ngood++;

          /* if tide station data have been loaded, interpolate the
           * correction value to apply to the tide model */
          if (mbotps_mode & MBOTPS_MODE_TIDESTATION && (ntidestation > 0))
            {
            intstat = mb_linear_interp(verbose,
              tidestation_time_d - 1,
              tidestation_correction - 1,
              ntidestation,
              time_d,
              &correction,
              &itime,
              &error);
            if (intstat == MB_SUCCESS)
              tide += correction;
/*fprintf(stderr,"TIDE STATION CORRECTION: intstat:%d itime:%dof%d time_d:%f correction:%f
   tide:%f\n", */
/*        intstat, itime, ntidestation, time_d, correction, tide); */
            }

          /* write out the tide model */
          if (tideformat == 2)
            {
            fprintf(ofp,
              "%4.4d %2.2d %2.2d %2.2d %2.2d %2.2d %9.4f\n",
              time_i[0],
              time_i[1],
              time_i[2],
              time_i[3],
              time_i[4],
              time_i[5],
              tide);
            }
          else
            {
            mb_get_time(verbose, time_i, &time_d);
            fprintf(ofp, "%.3f %9.4f\n", time_d, tide);
            }
          }
        }
      }
    fclose(tfp);
    fclose(ofp);

    /* remove the temporary files */
    unlink(lltfile);
    unlink(otpsfile);

    /* some helpful output */
    fprintf(stderr, "\nResults are really in %s\n", tide_file);
    }  /* end single position mode */

  /* -------------------------------------------------------------------------
   * else get tides along the navigation contained in a set of swath files
   * -----------------------------------------------------------------------*/
  else if (mbotps_mode & MBOTPS_MODE_NAVIGATION)
    {
/*fprintf(stderr,"Doing tide correction for swath navigation\n"); */
    /* 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, dfile, &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)
      {
      /* Figure out if the file needs a tide model - don't generate a new tide
         model if one was made previously and is up to date AND the
         appropriate request has been made */
      proceed = MB_YES;
      sprintf(tide_file, "%s.tde", file);
      if (skip_existing == MB_YES)
        {
        if (( (fstat =
          stat(file,
            &file_status)) == 0) && ( (file_status.st_mode & S_IFMT) != S_IFDIR) )
          {
          input_modtime = file_status.st_mtime;
          input_size = file_status.st_size;
          }
        else
          {
          input_modtime = 0;
          input_size = 0;
          }
        if (( (fstat =
          stat(tide_file,
            &file_status)) == 0) && ( (file_status.st_mode & S_IFMT) != S_IFDIR) )
          {
          output_modtime = file_status.st_mtime;
          output_size = file_status.st_size;
          }
        else
          {
          output_modtime = 0;
          output_size = 0;
          }
        if (( output_modtime > input_modtime) && ( input_size > 0) && ( output_size > 0) )
          proceed = MB_NO;
        }

      /* skip the file */
      if (proceed == MB_NO)
        {
        /* some helpful output */
        fprintf(stderr,
          "\n---------------------------------------\n\nProcessing tides for %s\n\n",
          file);
        fprintf(stderr, "Skipped - tide model file is up to date\n\n");
        }

      /* generate the tide model */
      else
        {
        /* some helpful output */
        fprintf(stderr,
          "\n---------------------------------------\n\nProcessing tides for %s\n\n",
          file);

        /* note tide station correction */
        if (mbotps_mode & MBOTPS_MODE_TIDESTATION && (ntidestation > 0)) {
          fprintf(stderr, "Applying tide station correction\n\n");
        }

        /* first open temporary file of lat lon time */
        pid = getpid();
        strcpy(swath_file, file);
        sprintf(lltfile, "tmp_mbotps_llt_%d.txt", pid);
        sprintf(otpsfile, "tmp_mbotps_llttd_%d.txt", pid);
        if ((tfp = fopen(lltfile, "w")) == NULL)
          {
          error = MB_ERROR_OPEN_FAIL;
          fprintf(stderr,
            "\nUnable to open temporary lat-lon-time file <%s> for writing\n",
            lltfile);
          fprintf(stderr, "\nProgram <%s> Terminated\n", program_name);
          exit(MB_FAILURE);
          }

        /* 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)
          {
          /* reset error */
          error = MB_ERROR_NO_ERROR;
          output = MB_NO;

          /* 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);

          /* 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);
            }

          /* deal with nav and time from survey data only - not nav, sidescan, or
             subbottom */
          if (( error <= MB_ERROR_NO_ERROR) && ( kind == MB_DATA_DATA) )
            {
            /* flag positions and times for output at specified interval */
            if (( nread == 0) || ( time_d - savetime_d >= interval) )
              {
              savetime_d = time_d;
              output = MB_YES;
              }
            lasttime_d = time_d;
            lastlon = navlon;
            lastlat = navlat;

            /* increment counter */
            nread++;
            }

          /* output position and time if flagged or end of file */
          if (( output == MB_YES) || ( error == MB_ERROR_EOF) )
            {
            if (lastlon < 0.0)
              lastlon += 360.0;
            mb_get_date(verbose, lasttime_d, time_i);
            fprintf(tfp,
              "%.6f %.6f %4.4d %2.2d %2.2d %2.2d %2.2d %2.2d\n",
              lastlat,
              lastlon,
              time_i[0],
              time_i[1],
              time_i[2],
              time_i[3],
              time_i[4],
              time_i[5]);
            }
          }

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

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

        /* close the llt file */
        fclose(tfp);

        /* call predict_tide with popen */
        sprintf(predict_tide, "%s/predict_tide", otps_location_use);
        if ((tfp = popen(predict_tide, "w")) == NULL)
          {
          error = MB_ERROR_OPEN_FAIL;
          fprintf(stderr, "\nUnable to open predict_time program using popen()\n");
          fprintf(stderr, "\nProgram <%s> Terminated\n", program_name);
          exit(MB_FAILURE);
          }

        /* send relevant input to predict_tide through its stdin stream */
        fprintf(tfp, "%s/DATA/Model_%s\n", otps_location_use, otps_model);
        fprintf(tfp, "%s\n", lltfile);
        fprintf(tfp, "z\n\nAP\noce\n1\n");
        /*fprintf(tfp, "z\nm2,s2,n2,k2,k1,o1,p1,q1\nAP\noce\n1\n");*/
        fprintf(tfp, "%s\n", otpsfile);

        /* close the process */
        pclose(tfp);

        /* now read results from predict_tide and rewrite them in a useful form */
        if ((tfp = fopen(otpsfile, "r")) == NULL)
          {
          error = MB_ERROR_OPEN_FAIL;
          fprintf(stderr,
            "\nUnable to open predict_time results temporary file <%s>\n",
            otpsfile);
          fprintf(stderr, "\nProgram <%s> Terminated\n", program_name);
          exit(MB_FAILURE);
          }
        if ((ofp = fopen(tide_file, "w")) == NULL)
          {
          error = MB_ERROR_OPEN_FAIL;
          fprintf(stderr, "\nUnable to open tide output file <%s>\n", tide_file);
          fprintf(stderr, "\nProgram <%s> Terminated\n", program_name);
          exit(MB_FAILURE);
          }
        fprintf(ofp, "# Tide model generated by program %s\n", program_name);
        fprintf(ofp, "# MB-System Version: %s\n", MB_VERSION);
        fprintf(ofp, "# Tide model generated by program %s\n", program_name);
        fprintf(ofp, "# which in turn calls OTPS program predict_tide obtained from:\n");
        fprintf(ofp, "#     http://www.coas.oregonstate.edu/research/po/research/tide/\n");
        right_now = time((time_t *)0);
        strcpy(date, ctime(&right_now));
        date[strlen(date) - 1] = '\0';
        if ((user_ptr = getenv("USER")) == NULL)
          user_ptr = getenv("LOGNAME");
        if (user_ptr != NULL)
          strcpy(user, user_ptr);
        else
          strcpy(user, "unknown");
        gethostname(host, MBP_FILENAMESIZE);
        fprintf(ofp, "# Run by user <%s> on cpu <%s> at <%s>\n", user, host, date);

        /* loop over tide model values, writing them out in the specified format */
        nline = 0;
        ngood = 0;
        while ((result = fgets(line, MB_PATH_MAXLINE, tfp)) == line)
          {
          nline++;
          if (( nline == 2) || ( nline == 3) )
            {
            fprintf(ofp, "#%s", line);
            }
          else if (nline > 6)
            {
            nget = sscanf(line,
              "%lf %lf %d.%d.%d %d:%d:%d %lf %lf",
              &lat,
              &lon,
              &time_i[1],
              &time_i[2],
              &time_i[0],
              &time_i[3],
              &time_i[4],
              &time_i[5],
              &tide,
              &depth);
            if (nget == 10)
              {
              ngood++;

              /* if tide station data have been loaded, interpolate the
               * correction value to apply to the tide model */
              if (mbotps_mode & MBOTPS_MODE_TIDESTATION && (ntidestation > 0))
                {
                intstat = mb_linear_interp(verbose,
                  tidestation_time_d - 1,
                  tidestation_correction - 1,
                  ntidestation,
                  time_d,
                  &correction,
                  &itime,
                  &error);
                if (intstat == MB_SUCCESS)
                  tide += correction;
// fprintf(stderr,"TIDE STATION CORRECTION: intstat:%d itime:%dof%d time_d:%f correction:%f   tide:%f\n",
// intstat, itime, ntidestation, time_d, correction, tide);
                }

              /* write out the tide model */
              if (tideformat == 2)
                {
                fprintf(ofp,
                  "%4.4d %2.2d %2.2d %2.2d %2.2d %2.2d %9.4f\n",
                  time_i[0],
                  time_i[1],
                  time_i[2],
                  time_i[3],
                  time_i[4],
                  time_i[5],
                  tide);
                }
              else
                {
                mb_get_time(verbose, time_i, &time_d);
                fprintf(ofp, "%.3f %9.4f\n", time_d, tide);
                }
              }
            }
          }
        fclose(tfp);
        fclose(ofp);

        /* remove the temporary files */
        unlink(lltfile);
        unlink(otpsfile);

        /* some helpful output */
        fprintf(stderr, "\nResults are really in %s\n", tide_file);

        /* set mbprocess usage of tide file */
        if (( mbprocess_update == MB_YES) && ( ngood > 0) )
          {
          status = mb_pr_update_tide(verbose,
            swath_file,
            MBP_TIDE_ON,
            tide_file,
            tideformat,
            &error);
          fprintf(stderr, "MBprocess set to apply tide correction to %s\n", swath_file);
          }
        }

      /* figure out whether and what to read next */
      if (read_datalist == MB_YES)
        {
        if ((status =
          mb_datalist_read(verbose, datalist, file, dfile, &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);
    }

  /* 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 */
Example #7
0
int main (int argc, char **argv)
{
	/* id variables */
	char program_name[] = "MBFORMAT";
	char help_message[] = "MBFORMAT is an utility which identifies the swath data formats \nassociated with MBIO format id's.  If no format id is specified, \nMBFORMAT lists all of the currently supported formats.";
	char usage_message[] = "mbformat [-Fformat -Ifile -L -W -V -H]";

	/* parsing variables */
	extern char *optarg;
	int	errflg = 0;
	int	c;
	int	error = MB_ERROR_NO_ERROR;
	int	status;
	int	help;
	int	html;
	int	verbose;
	char	file[MB_PATH_MAXLINE];
	char	root[MB_PATH_MAXLINE];
	int	file_specified;
	int	format;
	int	format_save;
	int	format_specified;
	char	format_description[MB_DESCRIPTION_LENGTH];
	char	*format_informal_ptr;
	char	*format_attributes_ptr;
	char	format_name[MB_DESCRIPTION_LENGTH];
	char	format_informal[MB_DESCRIPTION_LENGTH];
	char	format_attributes[MB_DESCRIPTION_LENGTH];
	int	list_mode;
	int	i;

	help = 0;
	verbose = 0;
	file_specified = MB_NO;
	format = 0;
	format_specified = MB_NO;
	html = MB_NO;
	list_mode = MBFORMAT_LIST_LONG;

	/* process argument list */
	while ((c = getopt(argc, argv, "F:f:HhI:i:LlKkVvWw")) != -1)
	  switch (c) 
		{
		case 'F':
		case 'f':
			sscanf (optarg,"%d", &format);
			format_specified = MB_YES;
			break;
		case 'L':
		case 'l':
			list_mode = MBFORMAT_LIST_SIMPLE;
			break;
		case 'K':
		case 'k':
			list_mode = MBFORMAT_LIST_ROOT;
			break;
		case 'H':
		case 'h':
			help++;
			break;
		case 'I':
		case 'i':
			sscanf (optarg,"%s", file);
			file_specified = MB_YES;
			break;
		case 'V':
		case 'v':
			verbose++;
			break;
		case 'W':
		case 'w':
			html = MB_YES;
			break;
		case '?':
			errflg++;
		}

	/* if error flagged then print it and exit */
	if (errflg)
		{
		fprintf(stderr,"usage: %s\n", usage_message);
		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);
		if (format_specified == MB_YES)
		    fprintf(stderr,"dbg2       format:  %d\n",format);
		if (file_specified == MB_YES)
		    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);
		}
		
	/* print out the info */
	if (file_specified == MB_YES)
		{
		format_save = format;
		status = mb_get_format(verbose,file,root,&format,&error);
		}
	else if (format_specified == MB_YES)
		{
		format_save = format;
		status = mb_format(verbose,&format,&error);
		}
	if (file_specified == MB_YES
		&& format == 0)
		{
		if (list_mode == MBFORMAT_LIST_SIMPLE)
			printf("%d\n",format);
		else if (list_mode == MBFORMAT_LIST_ROOT)
			printf("%s %d\n", root, format);
		else
			printf("Program %s unable to infer format from filename %s\n",program_name,file);
		}
	else if (format_specified == MB_YES
		&& format == 0)
		{
		if (list_mode == MBFORMAT_LIST_SIMPLE)
			printf("%d\n",format);
		else if (list_mode == MBFORMAT_LIST_ROOT)
			printf("%s %d\n", root, format);
		else
			printf("Specified format %d invalid for MB-System\n",format_save);
		}
	else if (format != 0)
		{
		if (list_mode == MBFORMAT_LIST_SIMPLE)
			{
			printf("%d\n",format);
			}
		else if (list_mode == MBFORMAT_LIST_ROOT)
			{
			printf("%s %d\n", root, format);
			}
		else
			{
			status = mb_format_description(verbose,&format,format_description,&error);
			if (status == MB_SUCCESS)
				{
				printf("\nMBIO data format id: %d\n",format);
				printf("%s",format_description);
				}
			else if (file_specified == MB_YES)
				{
				printf("Program %s unable to infer format from filename %s\n",program_name,file);
				}
			else if (format_specified == MB_YES)
				{
				printf("Specified format %d invalid for MB-System\n",format_save);
				}
			}
		}
	else if (html == MB_YES)
		{
		printf("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\n");
		printf("<HTML>\n<HEAD>\n   <TITLE>MB-System Supported Data Formats</TITLE>\n");
		printf("</HEAD>\n<BODY TEXT=\"#000000\" BGCOLOR=\"#FFFFFF\" LINK=\"#336699\" VLINK=\"#997040\" ALINK=\"#CC9900\">\n\n");
		printf("<CENTER><P><B><FONT SIZE=+2>MB-System Supported Swath Data Formats</FONT></B></P></CENTER>\n\n");
		printf("<P>Each swath mapping sonar system outputs a data stream which includes\n");
		printf("some values or parameters unique to that system. In general, a number of\n");
		printf("different data formats have come into use for data from each of the sonar\n");
		printf("systems; many of these formats include only a subset of the original data\n");
		printf("stream. Internally, MBIO recognizes which sonar system each data format\n");
		printf("is associated with and uses a data structure including the complete data\n");
		printf("stream for that sonar. At present, formats associated with the following\n");
		printf("sonars are supported: </P>\n\n");
		printf("<UL>\n<LI>Sea Beam &quot;classic&quot; multibeam sonar </LI>\n\n");
		printf("<LI>Hydrosweep DS multibeam sonar </LI>\n\n");
		printf("<LI>Hydrosweep DS2 multibeam sonar </LI>\n\n");
		printf("<LI>Hydrosweep MD multibeam sonar </LI>\n\n");
		printf("<LI>Sea Beam 2000 multibeam sonar </LI>\n\n");
		printf("<LI>Sea Beam 2112 and 2136 multibeam sonars </LI>\n\n");
		printf("<LI>Sea Beam 2120 multibeam sonars </LI>\n\n");
		printf("<LI>Simrad EM12, EM121, EM950, and EM1000 multibeam sonars </LI>\n\n");
		printf("<LI>Simrad EM120, EM300, and EM3000 multibeam sonars</LI>\n\n");
		printf("<LI>Simrad EM122, EM302, EM710, and EM3002 multibeam sonars</LI>\n\n");
		printf("<LI>Simrad Mesotech SM2000 multibeam sonar</LI>\n\n");
		printf("<LI>Hawaii MR-1 shallow tow interferometric sonar </LI>\n\n");
		printf("<LI>ELAC Bottomchart and Bottomchart MkII shallow water multibeam sonars</LI>\n\n");
		printf("<LI>Reson Seabat multibeam sonars (e.g. 9001, 8081, 7125)</LI>\n\n");
		printf("<LI>WHOI DSL AMS-120 deep tow interferometric sonar </LI>\n\n");
		printf("<LI>Sea Scan sidescan sonar</LI>\n\n");
		printf("<LI>Furuno HS-1 multibeam sonar</LI>\n\n");
		printf("<LI>Edgetech sidescan and subbottom profiler sonars</LI>\n\n");
		printf("<LI>Imagenex DeltaT multibeam sonars</LI>\n\n");
		printf("<LI>Odom ES3 multibeam sonar</LI>\n\n");
		printf("</UL>\n\n");
		printf("<P>The following swath mapping sonar data formats are currently supported by MB-System:</P>\n\n");

		for (i=0;i<=1000;i++)
			{
			format = i;
			if ((status = mb_format_description(verbose,&format,format_description,&error)) == MB_SUCCESS
				&& format == i)
				{
				format_informal_ptr = (char *) 
				    strstr(format_description, "Informal Description:");
				format_attributes_ptr = (char *) 
				    strstr(format_description, "Attributes:");
				strncpy(format_name, format_description, 
					strlen(format_description) 
					    - strlen(format_informal_ptr));
				format_name[strlen(format_description) 
					    - strlen(format_informal_ptr) - 1] = '\0';
				strncpy(format_informal, format_informal_ptr, 
					strlen(format_informal_ptr) 
					    - strlen(format_attributes_ptr));
				format_informal[strlen(format_informal_ptr) 
					    - strlen(format_attributes_ptr) - 1] = '\0';
				strcpy(format_attributes, format_attributes_ptr);
				format_attributes[strlen(format_attributes_ptr)-1] = '\0';
				printf("\n<UL>\n<LI>MBIO Data Format ID:  %d </LI>\n",format);
				printf("\n<UL>\n<LI>%s</LI>\n",format_name);
				printf("\n<LI>%s</LI>\n",format_informal);
				printf("\n<LI>%s</LI>\n",format_attributes);
				printf("</UL>\n</UL>\n");
				}
			}

		printf("\n<CENTER><P><BR>\n");
		printf("Last Updated: %s</P></CENTER>\n", MB_FORMAT_UPDATEDATE);
		printf("\n<P>\n<HR WIDTH=\"100%%\"></P>\n\n");
		printf("<P><IMG SRC=\"mbsystem_logo_small.gif\" HEIGHT=55 WIDTH=158><A HREF=\"mbsystem_home.html\">Back\n");
		printf("to MB-System Home Page...</A></P>\n");
		printf("\n</BODY>\n</HTML>\n");

		status = MB_SUCCESS;
		error = MB_ERROR_NO_ERROR;
		}
	else if (list_mode == MB_YES)
		{
		for (i=0;i<=1000;i++)
			{
			format = i;
			if ((status = mb_format(verbose,&format,&error)) == MB_SUCCESS
				&& format == i)
				{
				printf("%d\n",format);
				}
			}
		status = MB_SUCCESS;
		error = MB_ERROR_NO_ERROR;
		}
	else
		{
		printf("\nSupported MBIO Formats:\n");
		for (i=0;i<=1000;i++)
			{
			format = i;
			if ((status = mb_format_description(verbose,&format,format_description,&error)) == MB_SUCCESS
				&& format == i)
				{
				printf("\nMBIO Data Format ID:  %d\n",format);
				printf("%s",format_description);
				}
			}
		status = MB_SUCCESS;
		error = MB_ERROR_NO_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);
}
Example #8
0
int main (int argc, char **argv)
{
	static char rcs_id[] = "$Id$";
	static char program_name[] = "mbotps";
	static char help_message[] =  "MBotps predicts tides using methods and data derived from the OSU Tidal Prediction Software (OTPS) distributions.";
	static char usage_message[] = "mbotps [-Atideformat -Byear/month/day/hour/minute/second -Dinterval\n\t-Eyear/month/day/hour/minute/second -Fformat\n"
					"\t-Idatalist.mb-1 -Lopts_path -Ooutput -Potps_location -Rlon/lat -Tmodel -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;
	mb_path	read_file;
	void	*datalist;
	int	look_processed = MB_DATALIST_LOOK_UNSET;
	double	file_weight;
	mb_path	swath_file;
	mb_path	file;
	int	format;
	int	pings;
	int	lonflip;
	double	bounds[4];
	double	speedmin;
	double	timegap;
	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];

	/* mbotps control parameters */
	mb_path	otps_location_use;
	int	notpsmodels = 0;
	int	nmodeldatafiles = 0;
	int	mbotps_mode = MBOTPS_MODE_POSITION;
	double	tidelon;
	double	tidelat;
	double	btime_d;
	double	etime_d;
	int	btime_i[7];
	int	etime_i[7];
	double	interval = 300.0;
	mb_path	tidefile;
	int	mbprocess_update = MB_NO;
	int	tideformat = 2;
	int	ngood;

	/* time parameters */
	time_t	right_now;
	char	date[32], user[MB_PATH_MAXLINE], *user_ptr, host[MB_PATH_MAXLINE];
	int	pid;

	FILE	*tfp, *mfp, *ofp;
	struct stat file_status;
	int	fstat;
	mb_path	lltfile;
	mb_path	otpsfile;
	mb_path	line;
	mb_path	predict_tide;
	int	otps_model_set = MB_NO;
	mb_path	otps_model;
	mb_path	modelname;
	mb_path	modelfile;
	mb_path	modeldatafile;
	int	read_data;
	int	ntime;
	int	nread;
	int	nline;
	int	nget;
	int	output;
	double	savetime_d;
	double	lasttime_d;
	double	lastlon;
	double	lastlat;
	double	lon;
	double	lat;
	double	tide;
	double	depth;
	char	*result;
	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");

	/* set default location of the OTPS package */
	strcpy(otps_location_use, otps_location);

	/* set defaults for the AUV survey we were running on Coaxial Segment, Juan de Fuca Ridge
		while I wrote this code */
	sprintf(otps_model, "tpxo7.2");
	sprintf(tidefile, "tide_model.txt");
	tidelon = -129.588618;
	tidelat = 46.50459;
	interval = 60.0;
	btime_i[0] = 2009;
	btime_i[1] = 7;
	btime_i[2] = 31;
	btime_i[3] = 0;
	btime_i[4] = 0;
	btime_i[5] = 0;
	btime_i[6] = 0;
	etime_i[0] = 2009;
	etime_i[1] = 8;
	etime_i[2] = 2;
	etime_i[3] = 1;
	etime_i[4] = 0;
	etime_i[5] = 0;
	etime_i[6] = 0;

	/* process argument list */
	while ((c = getopt(argc, argv, "A:a:B:b:D:d:E:e:F:f:I:i:MmO:o:P:p:R:r:T:t:VvHh")) != -1)
	  switch (c)
		{
		case 'H':
		case 'h':
			help++;
			break;
		case 'V':
		case 'v':
			verbose++;
			break;
		case 'A':
		case 'a':
			sscanf (optarg,"%d", &tideformat);
			if (tideformat != 2)
				tideformat = 1;
			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", &interval);
			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 'I':
		case 'i':
			sscanf (optarg,"%s", read_file);
			mbotps_mode = MBOTPS_MODE_NAVIGATION;
			flag++;
			break;
		case 'M':
		case 'm':
			mbprocess_update = MB_YES;
			break;
		case 'O':
		case 'o':
			sscanf (optarg,"%s", tidefile);
			break;
		case 'P':
		case 'p':
			sscanf (optarg,"%s", otps_location_use);
			break;
		case 'R':
		case 'r':
			sscanf (optarg,"%lf/%lf", &tidelon, &tidelat);
			break;
		case 'T':
		case 't':
			sscanf (optarg,"%s", otps_model);
			otps_model_set = MB_YES;
			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);
		}

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

	/* Check for available tide models */
	if (help || verbose > 0)
		{
		fprintf(stderr,"\nChecking for available OTPS tide models\n");
		fprintf(stderr,"OTPS location: %s\nValid OTPS tidal models:\n", otps_location_use);
		}
	notpsmodels = 0;
	sprintf(line, "/bin/ls -1 %s/DATA | grep Model_ | sed \"s/^Model_//\"", otps_location_use);
	if ((tfp = popen(line, "r")) != NULL)
		{
		/* send relevant input to predict_tide through its stdin stream */
		while (fgets(line, sizeof(line), tfp))
			{
			sscanf(line, "%s", modelname);
			sprintf(modelfile, "%s/DATA/Model_%s", otps_location_use, modelname);
			nmodeldatafiles = 0;

			/* check the files referenced in the model file */
			if ((mfp = fopen(modelfile, "r")) != NULL)
				{
				/* stat the file referenced in each line */
				while (fgets(modeldatafile, MB_PATH_MAXLINE, mfp) != NULL)
					{
					if (strlen(modeldatafile) > 0)
						modeldatafile[strlen(modeldatafile)-1] = '\0';
					if ((fstat = stat(modeldatafile, &file_status)) == 0
						&& (file_status.st_mode & S_IFMT) != S_IFDIR)
						{
						nmodeldatafiles++;
						}
					}
				fclose(mfp);
				}
			if (nmodeldatafiles >= 3)
				{
				if (help || verbose > 0)
					fprintf(stderr,"     %s\n", modelname);
				if (otps_model_set == MB_NO)
					{
					if (notpsmodels == 0 || strcmp(modelname, "tpxo7.2") == 0)
						strcpy(otps_model, modelname);
					}
				notpsmodels++;
				}
			}

		/* close the process */
		pclose(tfp);
		}
	else
		{
		error = MB_ERROR_OPEN_FAIL;
		fprintf(stderr,"\nUnable to open ls using popen()\n");
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(MB_FAILURE);
		}
	if (help || verbose > 0)
		{
		fprintf(stderr,"Number of available OTPS tide models: %d\n", notpsmodels);
		fprintf(stderr,"\nUsing OTPS tide model:            %s\n", otps_model);
		}

	/* 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       otps_location:    %s\n",otps_location);
		fprintf(stderr,"dbg2       otps_location_use:%s\n",otps_location_use);
		fprintf(stderr,"dbg2       otps_model_set:   %d\n",otps_model_set);
		fprintf(stderr,"dbg2       otps_model:       %s\n",otps_model);
		fprintf(stderr,"dbg2       mbotps_mode:      %d\n",mbotps_mode);
		fprintf(stderr,"dbg2       tidelon:          %f\n",tidelon);
		fprintf(stderr,"dbg2       tidelat:          %f\n",tidelat);
		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       interval:         %f\n",interval);
		fprintf(stderr,"dbg2       tidefile:         %s\n",tidefile);
		fprintf(stderr,"dbg2       mbprocess_update: %d\n",mbprocess_update);
		fprintf(stderr,"dbg2       tideformat:       %d\n",tideformat);
		fprintf(stderr,"dbg2       format:           %d\n",format);
		fprintf(stderr,"dbg2       read_file:        %s\n",read_file);
		}

	/* exit if no valid OTPS models can be found */
	if (notpsmodels <= 0)
		{
		error = MB_ERROR_OPEN_FAIL;
		fprintf(stderr,"\nUnable to find a valid OTPS tidal model\n");
		fprintf(stderr,"\nProgram <%s> Terminated\n",
			program_name);
		exit(MB_FAILURE);
		}

	/* if help was all that was desired then exit */
	if (help)
		{
		exit(error);
		}

	/* get tides for a single position and time range */
	if (mbotps_mode == MBOTPS_MODE_POSITION)
		{
		/* first open temporary file of lat lon time */
		pid = getpid();
		sprintf(lltfile, "tmp_mbotps_llt_%d.txt", pid);
		sprintf(otpsfile, "tmp_mbotps_llttd_%d.txt", pid);
		if ((tfp = fopen(lltfile,"w")) == NULL)
			{
			error = MB_ERROR_OPEN_FAIL;
			fprintf(stderr,"\nUnable to open temporary lat-lon-time file <%s> for writing\n",lltfile);
			fprintf(stderr,"\nProgram <%s> Terminated\n",
				program_name);
			exit(MB_FAILURE);
			}

		/* make sure longitude is positive */
		if (tidelon < 0.0)
			tidelon += 360.0;

		/* loop over the time of interest generating the lat-lon-time values */
		mb_get_time(verbose, btime_i, &btime_d);
		mb_get_time(verbose, etime_i, &etime_d);
		ntime = 1 + (int)floor((etime_d - btime_d) / interval);
		for (i=0;i<ntime;i++)
			{
			time_d = btime_d + i * interval;
			mb_get_date(verbose, time_d, time_i);
			fprintf(tfp, "%.6f %.6f %4.4d %2.2d %2.2d %2.2d %2.2d %2.2d\n",
				tidelat, tidelon, time_i[0], time_i[1], time_i[2], time_i[3], time_i[4], time_i[5]);
			}

		/* close the llt file */
		fclose(tfp);

		/* call predict_tide with popen */
		sprintf(predict_tide, "%s/predict_tide", otps_location_use);
		if ((tfp = popen(predict_tide, "w")) == NULL)
			{
			error = MB_ERROR_OPEN_FAIL;
			fprintf(stderr,"\nUnable to open predict_time program using popen()\n");
			fprintf(stderr,"\nProgram <%s> Terminated\n",
				program_name);
			exit(MB_FAILURE);
			}

		/* send relevant input to predict_tide through its stdin stream */
		fprintf(tfp, "%s/DATA/Model_%s\n", otps_location_use,otps_model);
		fprintf(tfp, "%s\n", lltfile);
		fprintf(tfp, "z\n\nAP\noce\n1\n");
		/*fprintf(tfp, "z\nm2,s2,n2,k2,k1,o1,p1,q1\nAP\noce\n1\n");*/
		fprintf(tfp, "%s\n", otpsfile);

		/* close the process */
		pclose(tfp);

		/* now read results from predict_tide and rewrite them in a useful form */
		if ((tfp = fopen(otpsfile, "r")) == NULL)
			{
			error = MB_ERROR_OPEN_FAIL;
			fprintf(stderr,"\nUnable to open predict_time results temporary file <%s>\n", otpsfile);
			fprintf(stderr,"\nProgram <%s> Terminated\n",
				program_name);
			exit(MB_FAILURE);
			}
		if ((ofp = fopen(tidefile, "w")) == NULL)
			{
			error = MB_ERROR_OPEN_FAIL;
			fprintf(stderr,"\nUnable to open tide output file <%s>\n", tidefile);
			fprintf(stderr,"\nProgram <%s> Terminated\n",
				program_name);
			exit(MB_FAILURE);
			}
		fprintf(ofp, "# Tide model generated by program %s\n", program_name);
		fprintf(ofp, "# Version: %s\n", rcs_id);
		fprintf(ofp, "# MB-System Version: %s\n", MB_VERSION);
		fprintf(ofp, "# Tide model generated by program %s\n", program_name);
		fprintf(ofp, "# which in turn calls OTPS program predict_tide obtained from:\n");
		fprintf(ofp, "#     http://www.coas.oregonstate.edu/research/po/research/tide/\n");
		fprintf(ofp, "#\n");
		fprintf(ofp, "# OTPSnc tide model: \n");
		fprintf(ofp, "#      %s\n",otps_model);
		if (tideformat == 2)
			{
			fprintf(ofp, "# Output format:\n");
			fprintf(ofp, "#      year month day hour minute second tide\n");
			fprintf(ofp, "# where tide is in meters\n");
			}
		else
			{
			fprintf(ofp, "# Output format:\n");
			fprintf(ofp, "#      time_d tide\n");
			fprintf(ofp, "# where time_d is in seconds since January 1, 1970\n");
			fprintf(ofp, "# and tide is in meters\n");
			}
		right_now = time((time_t *)0);
		strcpy(date,ctime(&right_now));
                date[strlen(date)-1] = '\0';
		if ((user_ptr = getenv("USER")) == NULL)
			user_ptr = getenv("LOGNAME");
		if (user_ptr != NULL)
			strcpy(user,user_ptr);
		else
			strcpy(user, "unknown");
		gethostname(host,MBP_FILENAMESIZE);
		fprintf(ofp,"# Run by user <%s> on cpu <%s> at <%s>\n", user,host,date);

		nline = 0;
		ngood = 0;
		while ((result = fgets(line,MB_PATH_MAXLINE,tfp)) == line)
			{
			nline++;
			if (nline == 2 || nline == 3)
				{
				fprintf(ofp, "#%s", line);
				}
			else if (nline > 6)
				{
				nget = sscanf(line,"%lf %lf %d.%d.%d %d:%d:%d %lf %lf",
					&lat, &lon, &time_i[1], &time_i[2], &time_i[0],
					&time_i[3], &time_i[4], &time_i[5], &tide, &depth);
				if (nget == 10)
					{
					ngood++;
					if (tideformat ==2)
						{
						fprintf(ofp, "%4.4d %2.2d %2.2d %2.2d %2.2d %2.2d %9.4f\n",
							time_i[0], time_i[1],  time_i[2],
							time_i[3], time_i[4],  time_i[5], tide);
						}
					else
						{
						mb_get_time(verbose,time_i,&time_d);
						fprintf(ofp, "%.3f %9.4f\n",time_d, tide);
						}
					}
				}
			}
		fclose(tfp);
		fclose(ofp);

		/* remove the temporary files */
		unlink("lltfile");
		unlink("otpsfile");

		/* some helpful output */
		fprintf(stderr, "\nResults are really in %s\n", tidefile);
		} /* end single position mode */

	/* else get tides along the navigation contained in a set of swath files */
	else if (mbotps_mode == MBOTPS_MODE_NAVIGATION)
		{
		/* 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)
			{
			/* some helpful output */
			fprintf(stderr, "\n---------------------------------------\n\nProcessing tides for %s\n\n", file);

			/* first open temporary file of lat lon time */
			pid = getpid();
			strcpy(swath_file, file);
			sprintf(lltfile, "tmp_mbotps_llt_%d.txt", pid);
			sprintf(otpsfile, "tmp_mbotps_llttd_%d.txt", pid);
			sprintf(tidefile, "%s.tde", file);
			if ((tfp = fopen(lltfile,"w")) == NULL)
				{
				error = MB_ERROR_OPEN_FAIL;
				fprintf(stderr,"\nUnable to open temporary lat-lon-time file <%s> for writing\n",lltfile);
				fprintf(stderr,"\nProgram <%s> Terminated\n",
					program_name);
				exit(MB_FAILURE);
				}

			/* 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)
				{
				/* reset error */
				error = MB_ERROR_NO_ERROR;
				output = MB_NO;

				/* 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);

				/* 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);
					}

				/* deal with nav and time from survey data only - not nav, sidescan, or subbottom */
				if (error <= MB_ERROR_NO_ERROR && kind == MB_DATA_DATA)
					{
					/* flag positions and times for output at specified interval */
					if (nread == 0 || time_d - savetime_d >= interval)
						{
						savetime_d = time_d;
						output = MB_YES;
						}
					lasttime_d = time_d;
					lastlon = navlon;
					lastlat = navlat;

					/* increment counter */
					nread++;
					}

				/* output position and time if flagged or end of file */
				if (output == MB_YES || error == MB_ERROR_EOF)
					{
					if (lastlon < 0.0)
						lastlon += 360.0;
					mb_get_date(verbose, lasttime_d, time_i);
					fprintf(tfp, "%.6f %.6f %4.4d %2.2d %2.2d %2.2d %2.2d %2.2d\n",
							lastlat, lastlon, time_i[0], time_i[1], time_i[2],
							time_i[3], time_i[4], time_i[5]);
					}
				}

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

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

			/* close the llt file */
			fclose(tfp);

			/* call predict_tide with popen */
			sprintf(predict_tide, "%s/predict_tide", otps_location_use);
			if ((tfp = popen(predict_tide, "w")) == NULL)
				{
				error = MB_ERROR_OPEN_FAIL;
				fprintf(stderr,"\nUnable to open predict_time program using popen()\n");
				fprintf(stderr,"\nProgram <%s> Terminated\n",
					program_name);
				exit(MB_FAILURE);
				}

			/* send relevant input to predict_tide through its stdin stream */
			fprintf(tfp, "%s/DATA/Model_%s\n", otps_location_use,otps_model);
			fprintf(tfp, "%s\n", lltfile);
			fprintf(tfp, "z\n\nAP\noce\n1\n");
			/*fprintf(tfp, "z\nm2,s2,n2,k2,k1,o1,p1,q1\nAP\noce\n1\n");*/
			fprintf(tfp, "%s\n", otpsfile);

			/* close the process */
			pclose(tfp);

			/* now read results from predict_tide and rewrite them in a useful form */
			if ((tfp = fopen(otpsfile, "r")) == NULL)
				{
				error = MB_ERROR_OPEN_FAIL;
				fprintf(stderr,"\nUnable to open predict_time results temporary file <%s>\n", otpsfile);
				fprintf(stderr,"\nProgram <%s> Terminated\n",
					program_name);
				exit(MB_FAILURE);
				}
			if ((ofp = fopen(tidefile, "w")) == NULL)
				{
				error = MB_ERROR_OPEN_FAIL;
				fprintf(stderr,"\nUnable to open tide output file <%s>\n", tidefile);
				fprintf(stderr,"\nProgram <%s> Terminated\n",
					program_name);
				exit(MB_FAILURE);
				}
			fprintf(ofp, "# Tide model generated by program %s\n", program_name);
			fprintf(ofp, "# Version: %s\n", rcs_id);
			fprintf(ofp, "# MB-System Version: %s\n", MB_VERSION);
			fprintf(ofp, "# Tide model generated by program %s\n", program_name);
			fprintf(ofp, "# which in turn calls OTPS program predict_tide obtained from:\n");
			fprintf(ofp, "#     http://www.coas.oregonstate.edu/research/po/research/tide/\n");
			right_now = time((time_t *)0);
			strcpy(date,ctime(&right_now));
			date[strlen(date)-1] = '\0';
			if ((user_ptr = getenv("USER")) == NULL)
				user_ptr = getenv("LOGNAME");
			if (user_ptr != NULL)
				strcpy(user,user_ptr);
			else
				strcpy(user, "unknown");
			gethostname(host,MBP_FILENAMESIZE);
			fprintf(ofp,"# Run by user <%s> on cpu <%s> at <%s>\n", user,host,date);

			nline = 0;
			ngood = 0;
			while ((result = fgets(line,MB_PATH_MAXLINE,tfp)) == line)
				{
				nline++;
				if (nline == 2 || nline == 3)
					{
					fprintf(ofp, "#%s", line);
					}
				else if (nline > 6)
					{
					nget = sscanf(line,"%lf %lf %d.%d.%d %d:%d:%d %lf %lf",
						&lat, &lon, &time_i[1], &time_i[2], &time_i[0],
						&time_i[3], &time_i[4], &time_i[5], &tide, &depth);
					if (nget == 10)
						{
						ngood++;
						if (tideformat == 2)
							{
							fprintf(ofp, "%4.4d %2.2d %2.2d %2.2d %2.2d %2.2d %9.4f\n",
								time_i[0], time_i[1],  time_i[2],
								time_i[3], time_i[4],  time_i[5], tide);
							}
						else
							{
							mb_get_time(verbose,time_i,&time_d);
							fprintf(ofp, "%.3f %9.4f\n",time_d, tide);
							}
						}
					}
				}
			fclose(tfp);
			fclose(ofp);

			/* remove the temporary files */
			unlink(lltfile);
			unlink(otpsfile);

			/* some helpful output */
			fprintf(stderr, "\nResults are really in %s\n", tidefile);

			/* set mbprocess usage of tide file */
			if (mbprocess_update == MB_YES && ngood > 0)
				{
				status = mb_pr_update_tide(verbose, swath_file,
							MBP_TIDE_ON, tidefile, tideformat, &error);
				fprintf(stderr, "MBprocess set to apply tide correction to %s\n", swath_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);
		}

	/* 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);
}
Example #9
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);
}
Example #10
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 */
Example #11
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);
}
Example #12
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);
}