%function [out,mission,missionFile] = writeMissionFile(mission,missionFile,hideDefaults)
function [out,mission,missionFile] = writeMissionFile(mission,missionFile,hideDefaults)

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

button = questdlg('Output degrees as DDD MM.MMMMM?');
if strcmp(button,'Cancel'), return, end
if strcmp(button,'Yes'), ddmm = 1; else ddmm = 0; end

if nargin < 3, hideDefaults = 1; end

if nargin == 1 | isempty(missionFile),
	missionFile = [];
	[fname,pname] = uiputfile([mission{1}.name '.txt'],'Save mission as:');
	if fname == 0, return, end
	missionFile = [pname fname];
else
	fname = fliplr(strtok(fliplr(missionFile),'\/'));
end

mission{1}.name = fname;
fid = fopen(missionFile,'w');
if fid < 0, disp(['Could not open file ' routeFile]), return, end

fprintf(fid,'##########################################\n');
fprintf(fid,'# Bluefin mission file\n');
fprintf(fid,'# Date:\t%s\n',datestr(now,0));
fields = fieldnames(mission{1});
values = mystruct2cell(mission{1});
for i=1:length(fields),
	if ~isempty(values{i}) & ~strcmp(values{i},'*'),
		fprintf(fid,'#   %s:  %s\n',fields{i},mynum2str(values{i}));
	end
end
fprintf(fid,'#');
fprintf(fid,'##########################################\n\n');
j = 1;
for i=length(mission):-1:2,
	bstruct = mission{i};
	if strcmp(bstruct.name,'trackline'),
		if isfield(bstruct,'initialn') & isfield(bstruct,'initiale'),
			str = [mynum2str(bstruct.initialn) ' ' mynum2str(bstruct.initiale)];
		elseif isfield(bstruct,'initiallat') & isfield(bstruct,'initiallong'),
			if ddmm,
				str = [lat2str(bstruct.initiallat) ' ' lon2str(bstruct.initiallong)];
			else
				str = [mynum2str(bstruct.initiallat) ' ' mynum2str(bstruct.initiallong)];
			end
		end
		fprintf(fid,[int2str(j) ' %s\n'],str);
		j = j+1;
	end
end
fclose(fid);
uiwait(msgbox(['Saved mission as ' missionFile],'modal'))
out = 1;