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

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

if nargin == 1,
	surveyFile = [];
	[fname,pname] = uiputfile(['surline.pts'],'Save survey to:');
	if fname == 0, return, end
	surveyFile = [pname fname];
else
	fname = fliplr(strtok(fliplr(surveyFile),'\/'));
end

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

firstLeg = 1;
writeRouteHeader(mission)
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 survey to ' surveyFile],'modal'))

% Write waypoint file
[t,pname]=strtok(fliplr(surveyFile),'\/');
fname = strtok(fname,'.');
waypointFile = [fliplr(pname) fname '.wpt'];
writeWinfrogWPTFile(mission,waypointFile);
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 writeRouteHeader(mission)
	global fid
c1 = '0';											%Header (0) or Waypoint(1)	
c2 = mission{1}.name;								%Name
c3 = '0';											%?	
c4 = '0.000';										%?	
c5 = '0.000';										%?
c6 = '1';											%?	
c7 = int2str(countWaypoints(mission));				%Num waypoints
c8 = '65280';										%?
c9 = '0';											%?
c10 = '0.200';										%?
c11 = '0';											%?
fprintf(fid,[c1 ',' c2 ',' c3 ',' c4 ',' c5 ',' c6 ',' c7 ...
	',' c8 ',' c9 ',' c10 ',' c11 '\n']);


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function writeWaypoint(lat,lon,bstruct,n)
	global fid, global numWaypoint
numWaypoint = numWaypoint + 1;
if ~ischar(lat), lat = mynum2str(lat); end
if ~ischar(lon), lon = mynum2str(lon); end
c1 = '1';											%Header (0) or Waypoint(1)	
c2 = lat;											%Latitude
c3 = lon;											%Longitude
c4 = '0.00m';										%Elevation
c5 = '0.00m';										%Radius	
c6 = '0';											%?
c7 = '0';											%?
c8 = '0';											%?
fprintf(fid,[c1 ',' c2 ',' c3 ',' c4 ',' c5 ',' c6 ',' c7 ...
	',' c8 '\n']);
