function []=convertmattonc(matfile,ncfile);
%    convertmattonc -- function to convert mat-format file to nc-format file
%
%    usage:
%        convertmattonc(matfile,ncfile);
%    where:
%        matfile    name of mat-format file
%        ncfile     name of nc-format file (optional)
%

	if ~exist('matfile','var') || isempty(matfile)
		help convertmattonc
		error('convertmattonc usage error.');
	end

	[pathstr,name,ext]=fileparts(matfile);
	if isempty(ext)
		ext='.mat';
	end
	matfile=fullfile(pathstr,[name ext]);

	if ~exist('ncfile','var') || isempty(ncfile)
		ncfile=fullfile(pathstr,[name '.nc']);
	end

	if exist(ncfile,'file')
		delete(ncfile);
	end

	a=load(matfile,'-mat');
	disp(sprintf('mat-format file ''%s'' read.',matfile));
	fnames=fieldnames(a);

	for i=1:length(fnames)
		if isstruct(a.(fnames{i})) || iscell(a.(fnames{i}))
			warning('field ''%s'' is of class ''%s'' and will not be written.',fnames{i},class(a.(fnames{i})));
		else
			% matlab writes the dimensions reversed and matrices transposed into netcdf, so compensate for that
			nccreate(ncfile,fnames{i},...
                     'Dimensions',{[fnames{i} '_2'] size(a.(fnames{i}),2) [fnames{i} '_1'] size(a.(fnames{i}),1)},...
                     'Format','classic');
			ncwrite(ncfile,fnames{i},transpose(a.(fnames{i})));
			disp(sprintf('field ''%s'' of class ''%s'' and size [%dx%d] written.',...
			             fnames{i},class(a.(fnames{i})),size(a.(fnames{i}),1),size(a.(fnames{i}),2)));
		end
	end
	disp(sprintf('nc-format  file ''%s'' written.',ncfile));

end

