%function [out,mission,waypointFile] = writeWinfrogWPTFile(mission,waypointFile)
%  mission must be in geo not utm
function [out,mission,waypointFile] = writeWinfrogWPTFile(mission,waypointFile)
	global numWaypoint, global fid
	
numWaypoint = 0;

out = checkMissionFile(mission,1);
if ~out, return, end
out = 0;

if nargin == 1,
	waypointFile = [];
	[fname,pname] = uiputfile(['waypoint.wpt'],'Save waypoints to:');
	if fname == 0, return, end
	waypointFile = [pname fname];
else
	fname = fliplr(strtok(fliplr(waypointFile),'\/'));
end

fid = fopen(waypointFile,'w');
if fid < 0, disp(['Could not open file ' waypointFile]), return, end

firstLeg = 1;
for i=length(mission):-1:1,
	switch lower(mission{i}.name)
	case 'waypoint'
		lat = mission{i}.latitude;
		lon = mission{i}.longitude;
		if ischar(lat), lat = str2num(lat); end
		if ischar(lon), lon = str2num(lon); end
		writeWaypoint(lat,lon,mission{i},i)
		firstLeg = 1;
	case 'trackline'
		if firstLeg,
			ilat = mission{i}.initiallat;
			ilon = mission{i}.initiallong;
			if ischar(ilat), ilat = str2num(ilat); end
			if ischar(ilon), ilon = str2num(ilon); end	
			writeWaypoint(ilat,ilon,mission{i},i)
			firstLeg = 0;
		end
		lat = mission{i}.latitude;
		lon = mission{i}.longitude;
		if ischar(lat), lat = str2num(lat); end
		if ischar(lon), lon = str2num(lon); end	
		writeWaypoint(lat,lon,mission{i},i)		
	end
end

fclose(fid);
uiwait(msgbox(['Saved waypoints to ' waypointFile],'modal'))
out = 1;


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function n = countWaypoints(mission)
n = 0;
firstLeg = 1;
for i=1:length(mission),
	switch lower(mission{i}.name)
	case 'waypoint'
		n = n+1;
		firstLeg = 1;
	case 'trackline'
		if firstLeg,
			n = n+1;
			firstLeg = 0;
		end
		n = n+1;
	end
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function writeWaypoint(lat,lon,bstruct,n)
	global fid, global numWaypoint
numWaypoint = numWaypoint + 1;
if ischar(lat), lat = str2num(lat); end
if ischar(lon), lon = str2num(lon); end
c1 = ['Wp' int2str(n)];								%Waypoint name (#)
c2 = lat2str(lat,6);									%Latitude
c3 = lon2str(lon,6);									%Longitude
c4 = '17';											%?
c5 = '0.000';										%?
c6 = '0.00';										%?
c7 = '0.00';										%?
c8 = '255';											%?
c9 = '0.00';											%?
fprintf(fid,[c1 ',' c2 ',' c3 ',' c4 ',' c5 ',' c6 ',' c7 ...
	',' c8 ',' c9 '\n']);
