%function [out,mission,worksiteFile] = writeWorksiteFile(mission,worksiteFile,hideDefaults)
function [out,mission,worksiteFile] = writeWorksiteFile(mission,worksiteFile,hideDefaults)

out = checkWorksiteFile(mission{1});
if ~out, return, end
out = 0;

if nargin < 3, hideDefaults = 1; end

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

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

bdefault = behaviorDefaults;
worksite = bdefault{findin(bdefault,'name','worksite')};
fields = fields(worksite);

fprintf(fid,'##########################################\n');
fprintf(fid,'# Auto-generated worksite file from editor.m\n');
fprintf(fid,'# Mission:\t%s\n',mission{1}.name);
fprintf(fid,'# Date:\t%s\n',datestr(now,0));
fprintf(fid,'##########################################\n\n');

for ii=1:length(fields),
	if strcmp(fields{ii},'name'), continue, end
	value = getfield(mission{1},fields{ii});
	if ~isempty(value) & ~strcmp(value,'*'),
		fprintf(fid,'%s = %s;\n',fields{ii},upper(mynum2str(value)));
	end
end

fclose(fid);
uiwait(msgbox(['Saved worksite as ' worksiteFile],'modal'))
out = 1;