function mmerge_4dvar ( ncfiles, output_ncfile, t_epsilon )
% MMERGE_4DVAR:  merges multiple 4dvar obs netcdf files into one.
%
% PARAMETERS:
% ncfiles:
%     cell array of 4dvar netcdf files which are to be merged
% output_ncfile:
%     merged aggregate netcdf file
% t_epsilon:
%     threshold that determines if two surveys are close enough to be
%     combined into one.
%
% EXAMPLE:
%     >> ncfiles = { 'ZTObsJan02Jan09_02.nc', 'ZTObsJan10Jan16_02.nc', 'ZTObsJan17Jan23_02.nc' };
%     >> output_ncfile = 'ZTObsJan.nc';
%     >> t_epsilon = 1/24/60;  % one minute threshold
%     >> mmerge_4dvar ( ncfiles, output_ncfile, t_epsilon );

[pathstr, name, ext, versn] = fileparts ( output_ncfile );

%
% Go thru list, merging them two at a time.
current_ncfile = ncfiles{1};
for j = 2:length(ncfiles)-1

	ncfile_to_merge = ncfiles{j};

	%
	% construct a temporary file
	tmpfile = sprintf ( '%s.tmp.%0d.nc', name, j );

	fprintf ( 'Merging %s with %s into %s...\n', current_ncfile, ncfile_to_merge, tmpfile );
	nc_4dvar_meld ( current_ncfile, ncfile_to_merge, 1/24/60, tmpfile );

	current_ncfile = tmpfile;

end

%
% And now do the last one
fprintf ( 'Merging %s with %s into %s...\n', current_ncfile, ncfiles{end}, output_ncfile );
nc_4dvar_meld ( current_ncfile, ncfiles{end}, 1/24/60, output_ncfile );

%
% Finally, get rid of all the tmp files
for j = 2:length(ncfiles)-1
	tmpfile = sprintf ( '%s.tmp.%0d.nc', name, j );
	delete(tmpfile);
end

