%function out = checkMissionFile(mission,ptsOnly)
%  returns 0 if error, 1 if valid
function out = checkMissionFile(mission,ptsOnly)

out = 1;
if nargin == 1, ptsOnly = 0; end
for i=1:length(mission),
	fields = fieldnames(mission{i});
	values = struct2cell(mission{i});
	for j=1:length(values),
		if isempty(values{j}) & shouldBeChecked(fields{j},ptsOnly),
			uiwait(msgbox(['mission{' int2str(i) '}: ' mission{i}.name '.' ...
				fields{j} ' missing value.'],'modal'))
			out = 0;
		end
	end
end

if ~ptsOnly,
	index = findin(mission,'name','missiontimer');
	if ~index,
		uiwait(msgbox('No mission timer found.','modal')),
		out = 0;
	end
	
	[pass,range,altitude,desiredAlt] = checkSonarRange(mission);
	if pass == 0,
		button = questdlg(['Sonar range (' num2str(range) ') does not agree with ' ...
			'minaltitude (' num2str(altitude) ').  Standard altitude for this ' ...
			'sonar range would be ' int2str(desiredAlt) '.'],'Confirm Altitude:','Cancel', ...
			'Save Anyway','Cancel');
		if strcmp(button,'Cancel'), out = 0; end
	end	
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [out,range,altitude,desired] = checkSonarRange(mission)
out = 0;
range = [];
altitude = [];
desired = [];
index = findin(mission,'name','controlsonar',1);
if ~index, out = -1; return, end
if isfield(mission{index},'setrange'),
	range = getfield(mission{index},'setrange');
else, range = []; end
index = findin(mission,'name','depthenvelope',1);
if index & isfield(mission{index},'minaltitude'),
	altitude = getfield(mission{index},'minaltitude');
else, altitude = []; end
if ~isempty(range) & ~isempty(altitude),
	if isstr(range), range = str2num(range); end
	if isstr(altitude), altitude = str2num(altitude); end
	desired = range*0.1;
	if abs(desired - altitude) < 1, out = 1; end
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function out = shouldBeChecked(field,ptsOnly)
if ~ptsOnly, out = 1; return, end
out = strcmp(field,'latitude') | strcmp(field,'longitude') | ...
	strcmp(field,'initiallat') | strcmp(field,'initiallong');