function snc2mat ( ncfile, matfile )
% SNC2MAT:  saves netcdf file to *.mat format
%
% USAGE:  snc2mat ( ncfile, matfile );
%
% PARAMETERS:
% Input:
%     ncfile:
%         path of input netcdf file
%     matfile:
%         path of output MATLAB mat file 
%
% Output:
%     None.  In case of an error, an exception is thrown.
% 
% The basic structure of the netcdf file is maintained in the *.mat file.
% If one does
%
% >> b = load ( matfile );
%
% then b will be a matlab structure with fields corresponding to the
% netcdf variables and global attributes.   See NC_GETALL to get a 
% general idea of how the structure is put together.
%
% This routine will break down on files or single datasets that would
% constitute a large percentage of your system RAM.  So just be aware
% of that.  This routine will not be supported with SNCTOOLS(netcdf-4).
%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% $Id: snc2mat.m 1574 2006-07-17 15:31:43Z johnevans007 $
% $LastChangedDate: 2006-07-17 11:31:43 -0400 (Mon, 17 Jul 2006) $
% $LastChangedRevision: 1574 $
% $LastChangedBy: johnevans007 $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


%
% create the MATLAB file
ncdata = nc_getall ( ncfile );

fnames = fieldnames ( ncdata );
save_command = '';
global_atts = [];
for j = 1:length(fnames)
	theVar = fnames{j};
	if ( strcmp(theVar,'global_atts' ) )
		global_atts = ncdata.global_atts;
	else
		command = sprintf ( '%s = ncdata.%s;', theVar, theVar );
		eval(command);
		save_command = sprintf ( '%s''%s'',', save_command, theVar );
	end
end
if ~isempty(global_atts)
	save_command = sprintf ( '%s''global_atts''', save_command );
else
	%
	% This chops off a bad comma that's not needed if no global attributes.
	save_command(end) = '';
end
save_command = sprintf ( 'save ( matfile, %s );', save_command );
try
	eval(save_command);
catch
	fprintf ( 2, '%s:  Could not execute ''%s'', got error message ''%s''\n', mfilename, save_command, lasterr );
	error ( msg );
end


	

return
