%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;

if nargin < 3, hideDefaults = 1; end

if nargin == 1 | isempty(missionFile),
	missionFile = [];
	[fname,pname] = uiputfile([mission{1}.name],'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 ' missionFile]), return, end

fprintf(fid,'##########################################\n');
fprintf(fid,'# Auto-generated mission file from editor.m\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,'#\n');
fprintf(fid,'##########################################\n\n');
for i=2:length(mission),
	fprintf(fid,'#behavior %d\n',i-1);
	bstruct = mission{i};
	if hideDefaults, bstruct = removeDefaults(bstruct); end
	fields = fieldnames(bstruct);
	values = mystruct2cell(bstruct);
	if isfield(bstruct,'description')
		desc = getfield(bstruct,'description');
		if ~strcmp(desc,'*'), fprintf(fid,'#%s\n',desc); end
	end
	fprintf(fid,'behavior %s\n', bstruct.name);
	fprintf(fid,'{\n');
	
	for j=1:length(fields),
		if ~strcmp(fields{j},'name') & ~strcmp(values{j},'*') & ...
				~strcmp(fields{j},'description'),
			fprintf(fid,'    %s = %s;\n',fields{j},mynum2str(values{j}));
		end
	end
	fprintf(fid,'}\n\n');
end
fclose(fid);
uiwait(msgbox(['Saved mission as ' missionFile],'modal'))
out = 1;