%function mission = compassStar(lat0,lon0,rng,az,depth,rpm,nGps,nLegs, ...
%	transittime)
%  lat0			start lat (degrees)
%  lon0			start lon (degrees)
%  rng			length of legs
%  az			azimuth (degrees clockwise from North)
%  depth		depth of survey
%  rpm			rpm of tailcone
%  nGps			GPS hits per trackline (-n,...-2,-1,0,1,2,...,n)
%				where negative values skip n legs between fixes
%  nLegs		number of tracklines (odd integer)
%  transittime  time to transit to first waypoint
function mission = compassStar(lat0,lon0,rng,az,depth,rpm,nGps,nLegs, ...
	transittime)

mission = [];
geoid = selectGeoid;
getLegs('set',nLegs);
getGpsLegs('clear');
lat = lat0;
lon = lon0;
gps = nGps;
j = 1;
if ~rem(nLegs,2), turn = 180*(1-2/nLegs);
else turn = 180*(1-1/nLegs); end
h = waitbar(0,'Calculating Mission, Please wait...');
for i=1:nLegs,
	if nGps < 0,
		if rem(j,abs(nGps)+1) == 0,
			gps = 1;
			j = 1;
		else, gps = 0; end
	end
	[leg,lat,lon] = surveyLeg(lat,lon,rng,az,depth,rpm,gps);
	mission = [mission leg];
	az = mod(az+turn,360);
	j = j+1;
	getGpsLegs('set',gps);
	waitbar(i/nLegs,h)
end
close(h)

% create transit to start and turn on sonar
firstleg = mission{2};
transit{1} = getgps;
transit{2} = waypointgeo(firstleg.initiallat,firstleg.initiallong, ...
	firstleg.depth,firstleg.rpm,transittime);
transit{3} = ascend(0,rpm,depth);
transit{4} = getgps;
transit{5} = controlsonar('normal');

% add transit
mission = [transit mission];

% power down sonar
mission{end+1} = controlsonar('lowpower');

% delete empties
ind = [];
for ii=1:length(mission),
	if isempty(mission{ii}), ind = [ind ii]; end
end
mission(ind) = [];

% reverse order
mission = fliplr(mission);


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [leg,endlat,endlon] = surveyLeg(lat0,lon0,rng,az,depth,rpm,nGps)
leg = [];
j = 0;
n = 3 + 2*(nGps > 0);
[lat,lon] = reckonTrackline(lat0,lon0,0,rng,az,nGps);
for i=1:4:length(lat),
	leg{j*n+1} = controlsonar('on');	
	leg{j*n+2} = tracklinegeo(lat(i+1),lon(i+1),lat(i+2),lon(i+2),depth,rpm);
	leg{j*n+3} = controlsonar('off');
	if nGps == 0, break, end
	leg{j*n+4} = ascend(az,rpm,depth);
	leg{j*n+5} = getgps;
	j = j+1;
end
endlat = lat(end-1);
endlon = lon(end-1);
