eval '(exit $?0)' && eval 'exec perl -S $0 ${1+"$@"}'
                    & eval 'exec perl -S $0 $argv:q'
                         if 0;
#--------------------------------------------------------------------
#    The MB-system: mbm_route2mission.perl   7/18/2004
#    $Id:  $
#
#    Copyright (c) 2004 by 
#    D. W. Caress (caress@mbari.org)
#      Monterey Bay Aquarium Research Institute
#      Moss Landing, CA
#    and D. N. Chayes (dale@lamont.ldgo.columbia.edu)
#      Lamont-Doherty Earth Observatory
#      Palisades, NY  10964
#
#    See README file for copying and redistribution conditions.
#--------------------------------------------------------------------
#
# Command:
#   mbm_route2mission
#
# Purpose: 
#   Perl shellscript to translate survey route file derived from 
#   MBgrdviz into an MBARI AUV mission script. Developed for use
#   in survey planning for the MBARI Mapping AUV.
#
# Usage:
#   mbm_route2mission -Iroutefile [-Aaltitudemin -Ddepthmax -Fforwarddistance -Omissionfile -Wwaypointspacing -V -H]
#
# 
# Author:
#   David W. Caress
#      Monterey Bay Aquarium Research Institute
#      Moss Landing, CA
#
# Version:
# $Id:  $
#
# Revisions:
#   $Log:  $
#
$program_name = "mbm_route2mission";

# set defaults
$altitudemin = 18.0;
$altitudeabort = 10.0;
$depthmax = 130.0;
$depthabort = 150.0;
$forwarddistance = 400.0;
$waypointspacing = 200.0;
$ascendrate = 0.5; # m/s
$gpsduration = 600;
$descentdepth = 3.0;

# Deal with command line arguments
&Getopts('A:a:D:d:F:f:I:i:O:o:P:p:S:s:W:w:VvHh');
$routefile =		($opt_I || $opt_i);
$altitudearg =		($opt_A || $opt_a);
$deptharg =		($opt_D || $opt_d);
$forwarddistance =	($opt_F || $opt_f);
$missionfile =		($opt_O || $opt_o);
$startposition =	($opt_P || $opt_p);
$starttime =		($opt_S || $opt_s);
$waypointspacing =	($opt_W || $opt_w);
$help =			($opt_H || $opt_h);
$verbose =		($opt_V || $opt_v);

# print out help message if required
if ($help) {
    print "\r\n$program_name:\r\n";    
    print "\r\nPerl shellscript to translate survey route file derived from \r\n";
    print "MBgrdviz into an MBARI AUV mission script. Developed for use\r\n";
    print "in survey planning for the MBARI Mapping AUV.\r\n";
    print "Usage: mbm_route2mission -Iroutefile \r\n";
    print "\t\t[-Aaltitudemin/altitudeabort -Ddepthmax/depthabort[/depthdescent] -Fforwarddistance \r\n";
    print "\t\t-Omissionfile -Pstartlon/startlat -Sstarttime -Wwaypointspacing -V -H]\r\n";
    exit 0;
}

# get user info
$user = `whoami`;
$date = `date`;
$host = `hostname -s`;
chop $user;
chop $date;
chop $host;

# deal with command line values
if ($altitudearg)
	{
	($altitudemin, $altitudeabort) 
		= $altitudearg =~ /^(\S+)\/(\S+)/;
	}
if ($deptharg
	&& $deptharg =~ /^(\S+)\/(\S+)\/(\S+)/)
	{
	($depthmax, $depthabort, $descentdepth) 
		= $deptharg =~ /^(\S+)\/(\S+)\/(\S+)/;
	}
elsif ($deptharg
	&& $deptharg =~ /^(\S+)\/(\S+)/)
	{
	($depthmax, $depthabort) 
		= $deptharg =~ /^(\S+)\/(\S+)/;
	}
if ($startposition)
	{
	($startlon, $startlat) 
		= $startposition =~ /^(\S+)\/(\S+)/;
	}

# Open the input and output files
open(RFILE,"$routefile") || die "Cannot open input route file: $routefile\r\n$program_name aborted.\r\n";
if ($routefile =~ /\S+.rte/)
	{
	($root) = $routefile =~ /(\S+).rte/;
	}
else
	{
	$root = $routefile;
	}
if (!$missionfile)
	{
	$missionfile = "$root.cfg";
	}
open(MFILE,">$missionfile") || die "Cannot open output mission file: $missionfile\r\n$program_name aborted.\r\n";

# Read in the initial route data
$cnt = 0;
$nwaypoints = 0;
while ($line = <RFILE>) 
	{
	if ($line =~ /^## /)
		{
#		printf "Comment: $line";
		}
	elsif ($line =~ /^> ## STARTROUTE/)
		{
#		printf "Route: $line";
		}
	elsif ($line =~ /^> ## ENDROUTE/)
		{
#		printf "Route: $line";
		}
	elsif ($line =~ /(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)/)
		{
		#extract route data
		($lon, $lat, $topo, $waypoint, $bearing, $distance, $distonbottom, $slope) 
			= $line 
			=~ /(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)/;
		push(@lons, $lon);
		push(@lats, $lat);
		push(@topos, $topo);
		push(@waypoints, $waypoint);
		push(@bearings, $bearing);
		push(@distances, $distance);
		push(@distonbottoms, $distonbottom);
		push(@slopes, $slope);
		
		if ($waypoint == 1)
			{
			$nwaypoints++;
			}

		$cnt++;
		}
	}
$npoints = $cnt;
	
# Write out the input route data
# $cnt = 0;
# foreach $lon (@lons)
# 	{
# 	# print route data
# 	print "$waypoints[$cnt] $lons[$cnt] $lats[$cnt] $topos[$cnt] $bearings[$cnt] $distances[$cnt] $distonbottoms[$cnt] $slopes[$cnt]\r\n";
# 	
# 	# increment counter
# 	$cnt++;
# 	}
	
# Print out program parameters
if ($verbose)
	{
	print "\r\nRunning $program_name\r\n";
	print "\tRoute File:               $routefile\r\n";
	print "\tMission File:             $missionfile\r\n";
	print "\tMinimum Vehicle Altitude: $altitudemin (m)\r\n";
	print "\tAbort Vehicle Altitude:   $altitudeabort (m)\r\n";
	print "\tMaximum Vehicle Depth:    $depthmax (m)\r\n";
	print "\tAbort Vehicle Depth:      $depthabort (m)\r\n";
	print "\tDescent Vehicle Depth:    $descentdepth (m)\r\n";
	print "\tForward Looking Distance: $forwarddistance (m)\r\n";
	print "\tWaypoint Spacing:         $waypointspacing (m)\r\n";
	if ($starttime)
		{
		print "\tTime to First Waypoint:   $starttime (s)\r\n";
		}
	if ($startposition)
		{
		print "\tStart Longitude:          $startlon (deg)\r\n";
		print "\tStart Latitude:           $startlat (deg)\r\n";
		}
	print "\tGPS Duration:             $gpsduration (s)\r\n";
	print "\tAscend Rate:              $ascendrate (m/s)\r\n";
	}
	
# Process the route data to generate AUV waypoints that keep the 
# vehicle a safe distance above the bottom.
$distancelastmpoint = 0.0;
$nmissionpoints = 0;
$ilast = 0;
for ($i = 0; $i < $npoints; $i++)
	{
	# first figure out if this is a point to be output
	$output = 0;
	if ($waypoints[$i] == 1)
		{
		$output = 1;
		}
	elsif (($distances[$i] - $distancelastmpoint) >= $waypointspacing)
		{
		$output = 1;
		}
		
	# process points of interest
	if ($output == 1)
		{
		# insert points into arrays so they can be printed out last to first
		# to follow the MBARI AUV mission file convention
		push(@mwaypoints, $waypoints[$i]);
		push(@mlons, $lons[$i]);
		push(@mlats, $lats[$i]);
		push(@mtopos, $topos[$i]);
		push(@mbearings, $bearings[$i]);
		push(@mdistances, $distances[$i]);
		$nmissionpoints++;
		
		# print it out
#		if ($verbose)
#			{
#			print "$i $waypoints[$i] $lons[$i] $lats[$i] $topos[$i] $topomax $distances[$i] $bearings[$i]\r\n";
#			}

		# reset distance from last mission point
		$distancelastmpoint = $distances[$i];
		$ilast = $i;
		}
	}
	
# get safe depth for each mission segment
for ($i = 0; $i < $nmissionpoints; $i++)
	{
	$topomax = $mtopos[$i];
	for ($j = 0; $j < $npoints; $j++)
		{
		$ii = $i - 1;
		if ($ii < 0)
			{
			$ii = 0;
			}
		$ddist = $distances[$j] - $mdistances[$ii];
		if ($ddist > 0.0 
			&& $ddist <= $forwarddistance
			&& $topos[$j] > $topomax)
			{
			$topomax = $topos[$j];
			}
		}
	push(@mtopomaxs, $topomax);
	push(@mmissiondepths, $topomax);
	}

# Calculate estimated time of mission
$mission_speed = 1.5;
$missiontime = $distancelastmpoint / $mission_speed;

# Calculate time to first waypoint
if ($startposition)
	{
	# get local scaling of lon lat to distance
	$C1 = 111412.84;
	$C2 = -93.5;
	$C3 = 0.118;
	$C4 = 111132.92;
	$C5 = -559.82;
	$C6 = 1.175;
	$C7 = 0.0023;
	$DTR = 3.14159265358979323846 / 180.0;
	$radlat = $mlats[0] * DTR;
	$mtodeglat = 1./abs($C4 + $C5*cos(2*$radlat) 
				+ $C6*cos(4*$radlat) + $C7*cos(6*$radlat));
	$mtodeglon = 1./abs($C1*cos($radlat) + $C2*cos(3*$radlat) 
				+ $C3*cos(5*$radlat));
				
	# calculate distance to first point
	$dx = ($mlons[0] - $startlon) / $mtodeglon;
	$dy = ($mlats[0] - $startlat) / $mtodeglat;
	$startdistance = sqrt($dx * $dx + $dy * $dy);
	}
elsif ($starttime)
	{
	$startdistance = $starttime * $mission_speed;
	}
else
	{
	$startdistance = 500.0;
	}
	
# Print out program parameters
if ($verbose)
	{
	printf "\r\nInput route file %s read...\r\n", $routefile;
	printf "\tNumber of input waypoints:       %d\r\n", $nwaypoints;
	printf "\tNumber of input route points:    %d\r\n", $npoints;
	printf "\tNumber of output mission points: %d\r\n", $nmissionpoints;
	}

# output mission file comments
print MFILE "# This MBARI Mapping AUV mission file has been generated\r\n";
print MFILE "# by the MB-System program $program_name run by\r\n";
print MFILE "# user <$user> on cpu <$host> at <$date>\r\n";
print MFILE "# \r\n";
print MFILE "# Mission Parameters:\r\n";
print MFILE "#     Route File:               $routefile\r\n";
print MFILE "#     Mission File:             $missionfile\r\n";
print MFILE "#     Minimum Vehicle Altitude: $altitudemin (m)\r\n";
print MFILE "#     Abort Vehicle Altitude:   $altitudeabort (m)\r\n";
print MFILE "#     Maximum Vehicle Depth:    $depthmax (m)\r\n";
print MFILE "#     Abort Vehicle Depth:      $depthabort (m)\r\n";
print MFILE "#     Descent Vehicle Depth:    $descentdepth (m)\r\n";
print MFILE "#     Forward Looking Distance: $forwarddistance (m)\r\n";
print MFILE "#     Waypoint Spacing:         $waypointspacing (m)\r\n";
if ($starttime)
	{
	print MFILE "#     Time to First Waypoint:   $starttime (s)\r\n";
	}
if ($startposition)
	{
	print MFILE "#     Start Longitude:          $startlon (deg)\r\n";
	print MFILE "#     Start Latitude:           $startlat (deg)\r\n";
	}
print MFILE "#     GPS Duration:             $gpsduration (s)\r\n";
print MFILE "#     Ascend Rate:              $ascendrate (m/s)\r\n";
print MFILE "# \r\n";
print MFILE "# The primary waypoints from the route file are:\r\n";
print MFILE "#   <number> <longitude (deg)> <latitude (deg)> <topography (m)> <distance (m)>\r\n";
$cnt = 0;
for ($i = 0; $i < $npoints; $i++)
 	{
	if ($waypoints[$i] == 1)
		{
 		print MFILE "#   $cnt $lons[$i] $lats[$i] $topos[$i] $distances[$i]\r\n";
		$cnt++;
		}
 	}
print MFILE "# \r\n";
printf MFILE "# A total of %d mission points have been defined.\r\n", $nmissionpoints;
print MFILE "# \r\n";
print MFILE "# Define Mission parameters:\r\n";
printf MFILE "#define MISSION_SPEED     %f\r\n", $mission_speed;
printf MFILE "#define MISSION_DISTANCE  %f\r\n", $distancelastmpoint;
printf MFILE "#define MISSION_TIME      %f\r\n", $missiontime;
printf MFILE "#define MISSION_TIMEOUT   %d\r\n", (1.2 * $missiontime);
printf MFILE "#define DEPTH_MAX         %f\r\n", $depthmax;
printf MFILE "#define DEPTH_ABORT       %f\r\n", ($depthmax + 20.0);
printf MFILE "#define ALTITUDE_MIN      %f\r\n", $altitudemin;
printf MFILE "#define ALTITUDE_ABORT    %f\r\n", (0.6 * $altitudemin);
printf MFILE "#define GPS_DURATION      %d\r\n", $gpsduration;
printf MFILE "#define DESCENT_DEPTH     %f\r\n", $descentdepth;
print MFILE "# \r\n";
print MFILE "#######################################################\r\n";
print MFILE "# Set Mission Behaviors\r\n";
print MFILE "# \r\n";
print MFILE "# mission timer set to 120% of estimated time of mission\r\n";
print MFILE "behavior missionTimer \r\n";
print MFILE "{\r\n";
print MFILE "timeOut = MISSION_TIMEOUT;\r\n";
print MFILE "}\r\n";
print MFILE "# \r\n";
print MFILE "# depth envelope\r\n";
print MFILE "behavior depthEnvelope \r\n";
print MFILE "{\r\n";
print MFILE "minDepth = 0;\r\n";
print MFILE "maxDepth     = DEPTH_MAX;\r\n";
print MFILE "abortDepth   = DEPTH_ABORT;\r\n";
print MFILE "minAltitude  = ALTITUDE_MIN;\r\n";
print MFILE "abortAltitude = ALTITUDE_ABORT;\r\n";
print MFILE "}\r\n";
print MFILE "#######################################################\r\n";
print MFILE "# Set End-of-Mission Behaviors\r\n";
print MFILE "# \r\n";
print MFILE "# \r\n";
print MFILE "# acquire gps fix \r\n";
print MFILE "behavior getgps  \r\n";
print MFILE "{ \r\n";
print MFILE "duration = GPS_DURATION; \r\n";
print MFILE "minHits = 60; \r\n";
print MFILE "abortOnTimeout = True; \r\n";
print MFILE "} \r\n";
print MFILE "# \r\n";
print MFILE "# ascend behavior \r\n";
print MFILE "behavior ascend  \r\n";
print MFILE "{ \r\n";
print MFILE "duration  = 300; \r\n";
print MFILE "horizontalMode   = rudder; \r\n";
print MFILE "horizontal       = 10; \r\n";
print MFILE "pitch            = 20; \r\n";
print MFILE "speed            = MISSION_SPEED; \r\n";
print MFILE "endDepth         = 2; \r\n";
print MFILE "} \r\n";
print MFILE "# \r\n";
print MFILE "# Turn off power to sonars and stop logging on the PLC \r\n";
print MFILE "# by setting the value of the mode attribute to 0 (used to be False). \r\n";
print MFILE "behavior reson \r\n";
print MFILE "{ \r\n";
print MFILE "duration  = 6; \r\n";
print MFILE "SBP_Mode  = 0; \r\n";
print MFILE "LoSS_Mode = 0; \r\n";
print MFILE "HiSS_Mode = 0; \r\n";
print MFILE "Log_Mode  = 0; \r\n";
print MFILE "} \r\n";

# output mission points in reverse order
$iwaypoint = $nwaypoints;
for ($i = $nmissionpoints - 1; $i >= 0; $i--)
	{
	# figure out which waypoint this is
	if ($mwaypoints[$i] == 1)
		{
		$iwaypoint--;
		}

	# put comment break in at waypoint
	if ($mwaypoints[$i] == 1)
		{
		print MFILE "#######################################################\r\n";
		}

	# calculate distance and depth
	if ($i == 0)
		{
		$distance = $startdistance;
		}
	else
		{
		$distance = $mdistances[$i] - $mdistances[$i-1];
		}
	$mmissiondepths[$i] = -$mtopomaxs[$i] - $altitudemin;
	$maxdepthapplied = 0;
	if ($mmissiondepths[$i] > $depthmax)
		{
		$mmissiondepths[$i] = $depthmax;
		$maxdepthapplied = 1;
		}
	elsif ($mmissiondepths[$i] < $altitudemin)
		{
		$mmissiondepths[$i] = $altitudemin;
		$maxdepthapplied = 0;
		}
	$ascendtime = 1.2 * $mmissiondepths[$i] / $ascendrate;
	if ($ascendtime < 300)
		{
		$ascendtime = 300;
		}
		
	# at end of main lines do ascend, gps, descend
	if (($mwaypoints[$i] == 1) 
		&& ($iwaypoint % 2 == 1) 
		&& ($iwaypoint != $nwaypoints - 1))
		{
		print MFILE "# \r\n";
		printf MFILE "# Ascend, gps, descend after reaching waypoint %d at end of line %d\r\n", $iwaypoint, $iwaypoint;
		print MFILE "# \r\n";
		print MFILE "# Descend behavior \r\n";
		print MFILE "behavior descend  \r\n";
		print MFILE "{ \r\n";
		print MFILE "horizontalMode   = heading; \r\n";
		printf MFILE "horizontal   = %f; \r\n", $mbearings[$i];
		print MFILE "pitch        = -15; \r\n";
		print MFILE "speed        = MISSION_SPEED; \r\n";
		print MFILE "maxDepth     = 20; \r\n";
		print MFILE "duration     = 300; \r\n";
		print MFILE "} \r\n";
		print MFILE "# \r\n";
		print MFILE "# setpoint on surface to gather momentum \r\n";
		print MFILE "behavior setpoint \r\n";
		print MFILE "{ \r\n";
		print MFILE "duration     = 30; \r\n";
		printf MFILE "heading      = %f; \r\n", $mbearings[$i];
		print MFILE "speed        = MISSION_SPEED; \r\n";
		print MFILE "verticalMode = pitch; \r\n";
		print MFILE "pitch        = 0; \r\n";
		print MFILE "} \r\n";
		print MFILE "# \r\n";
		print MFILE "# acquire gps fix \r\n";
		print MFILE "behavior getgps  \r\n";
		print MFILE "{ \r\n";
		print MFILE "duration = GPS_DURATION; \r\n";
		print MFILE "minHits = 30; \r\n";
		print MFILE "abortOnTimeout = True; \r\n";
		print MFILE "} \r\n";
		print MFILE "# \r\n";
		print MFILE "# ascend behavior \r\n";
		print MFILE "behavior ascend  \r\n";
		print MFILE "{ \r\n";
		printf MFILE "duration  = %d; \r\n", $ascendtime;
		print MFILE "horizontalMode   = rudder; \r\n";
		print MFILE "horizontal       = 10; \r\n";
		print MFILE "pitch            = 20; \r\n";
		print MFILE "speed            = MISSION_SPEED; \r\n";
		print MFILE "endDepth         = 2; \r\n";
		print MFILE "} \r\n";
		print MFILE "# \r\n";
		}
		
	# output mission point behavior
	print MFILE "# \r\n";
	if ($mwaypoints[$i] == 1 && $iwaypoint == 0)
		{
		print MFILE "# Waypoint behavior to get to start of line 1\r\n";
		}
	elsif ($mwaypoints[$i] == 1)
		{
		printf MFILE "# Waypoint behavior to get to end of line %d\r\n", $iwaypoint;
		}
	else
		{
		printf MFILE "# Waypoint behavior during line %d\r\n", $iwaypoint;
		}
	printf MFILE "#   Segment length %f meters\r\n", $distance;
	printf MFILE "#   Minimum depth: %f meters looking forward %f meters along route\r\n", -$mtopomaxs[$i], $forwarddistance;
	printf MFILE "#   Maximum vehicle depth: %f meters\r\n", $depthmax;
	printf MFILE "#   Minimum vehicle altitude: %f meters\r\n", $altitudemin;
	if ($maxdepthapplied == 0)
		{
		printf MFILE "#   Behavior depth of %f meters set by local depth and minimum altitude\r\n", $mmissiondepths[$i];
		}
	else
		{
		printf MFILE "#   Behavior depth of %f meters set to maximum vehicle depth\r\n", $mmissiondepths[$i];
		}
	print MFILE "behavior waypoint  \r\n";
	print MFILE "{ \r\n";
	printf MFILE "latitude     = %f; \r\n", $mlats[$i];
	printf MFILE "longitude    = %f; \r\n", $mlons[$i];
	print MFILE "captureRadius = 10; \r\n";
	printf MFILE "duration     = %d; \r\n", (1.2 * $distance / $mission_speed);
	printf MFILE "depth        = %f; \r\n", $mmissiondepths[$i];
	print MFILE "speed        = MISSION_SPEED; \r\n";
	print MFILE "} \r\n";

	# put comment break in at waypoint
	if ($mwaypoints[$i] == 1)
		{
		print MFILE "#######################################################\r\n";
		}
	}

# output beginning of mission
print MFILE "#######################################################\r\n";
print MFILE "# \r\n";
print MFILE "# Set power levels and high-freq rate \r\n";
print MFILE "# \r\n";
print MFILE "behavior reson \r\n";
print MFILE "{ \r\n";
print MFILE "duration  = 6; \r\n";	
print MFILE "SBP_Power = 100.0; \r\n";
print MFILE "LoSS_Power = 100.0; \r\n";
print MFILE "LoSS_Range = 400.0; \r\n";
print MFILE "LoSS_Rate  = 1.0; \r\n";
print MFILE "HiSS_Power = 100.0; \r\n";
print MFILE "HiSS_Range = 400.0; \r\n";
print MFILE "HiSS_Rate  = 1.0; \r\n";
print MFILE "} \r\n";
print MFILE "# \r\n";
print MFILE "# Turn on power to sonars and start logging on the PLC \r\n";
print MFILE "# by setting the value of the mode attribute to 1 (used to be True). \r\n";
print MFILE "# \r\n";
print MFILE "behavior reson \r\n";
print MFILE "{ \r\n";
print MFILE "duration  = 6; \r\n";
print MFILE "SBP_Mode  = 1; \r\n";
print MFILE "LoSS_Mode = 1; \r\n";
print MFILE "HiSS_Mode = 0; \r\n";
print MFILE "Log_Mode  = 1; \r\n";
print MFILE "} \r\n";
print MFILE "# \r\n";
print MFILE "# Descend behavior \r\n";
print MFILE "behavior descend  \r\n";
print MFILE "{ \r\n";
print MFILE "horizontalMode   = heading; \r\n";
printf MFILE "horizontal   = %f; \r\n", $mbearings[0];
print MFILE "pitch        = -15; \r\n";
print MFILE "speed        = MISSION_SPEED; \r\n";
print MFILE "maxDepth     = DESCENT_DEPTH; \r\n";
print MFILE "minAltitude  = ALTITUDE_MIN; \r\n";
print MFILE "duration     = 300; \r\n";
print MFILE "} \r\n";
print MFILE "# \r\n";
print MFILE "# setpoint on surface to gather momentum \r\n";
print MFILE "behavior setpoint \r\n";
print MFILE "{ \r\n";
print MFILE "duration     = 30; \r\n";
printf MFILE "heading      = %f; \r\n", $mbearings[0];
print MFILE "speed        = MISSION_SPEED; \r\n";
print MFILE "verticalMode = pitch; \r\n";
print MFILE "pitch        = 0; \r\n";
print MFILE "} \r\n";
print MFILE "# \r\n";
print MFILE "# acquire gps fix \r\n";
print MFILE "behavior getgps  \r\n";
print MFILE "{ \r\n";
print MFILE "duration = GPS_DURATION; \r\n";
print MFILE "minHits = 30; \r\n";
print MFILE "abortOnTimeout = True; \r\n";
print MFILE "} \r\n";
print MFILE "#######################################################\r\n";

# Close the input and output files
close(RFILE);
close(MFILE);

# generate data for plots
$topodatafile = "$root" . "_topo.xy";
open(TFILE,">$topodatafile") || die "Cannot open output distance vs topo file: $topodatafile\r\n$program_name aborted.\r\n";
for ($i = 0; $i < $npoints; $i++)
	{
	printf TFILE "%f %f\r\n", $distances[$i], $topos[$i];
	}
close(TFILE);
$topodatafile = "$root" . "_mission.xy";
open(TFILE,">$topodatafile") || die "Cannot open output distance vs topo file: $topodatafile\r\n$program_name aborted.\r\n";
for ($i = 0; $i < $nmissionpoints-1; $i++)
	{
	printf TFILE "%f %f\r\n", $mdistances[$i], -$mmissiondepths[$i];
	printf TFILE "%f %f\r\n", $mdistances[$i+1], -$mmissiondepths[$i];
	}
close(TFILE);

# End it all
print "\r\nAll done!\r\n";
exit 0;

#-----------------------------------------------------------------------
# This should be loaded from the library but its safer to
# just include it....
#
;# getopts.pl - a better getopt.pl

;# Usage:
;#      do Getopts('a:bc');  # -a takes arg. -b & -c not. Sets opt_* as a
;#                           #  side effect.

sub Getopts {
    local($argumentative) = @_;
    local(@args,$_,$first,$rest);
    local($errs) = 0;
    local($[) = 0;

    @args = split( / */, $argumentative );
    while(@ARGV && ($_ = $ARGV[0]) =~ /^-(.)(.*)/) {
     ($first,$rest) = ($1,$2);
     $pos = index($argumentative,$first);
     if($pos >= $[) {
         if($args[$pos+1] eq ':') {
          shift(@ARGV);
          if($rest eq '') {
              ++$errs unless @ARGV;
              $rest = shift(@ARGV);
          }
          eval "\$opt_$first = \$rest;";
         }
         else {
          eval "\$opt_$first = 1";
          if($rest eq '') {
              shift(@ARGV);
          }
          else {
              $ARGV[0] = "-$rest";
          }
         }
     }
     else {
         print STDERR "Unknown option: $first\r\n";
         ++$errs;
         if($rest ne '') {
          $ARGV[0] = "-$rest";
         }
         else {
          shift(@ARGV);
         }
     }
    }
    $errs == 0;
}


#-----------------------------------------------------------------------
