function nc_add_dimension ( ncfile, dimension_name, dimension_length )
% NC_ADD_DIMENSION:  adds a dimension to an existing netcdf file
%
% USAGE:  nc_add_dimension ( ncfile, dimension_name, dimension_size );
%
% PARAMETERS:
% Input:
%     ncfile:  path to netcdf file
%     dimension_name:  name of dimension to be added
%     dimension_size:  length of new dimension.  If zero, it will be an
%         unlimited dimension.
% Output:
%     none
%
% In case of an error, an exception is thrown.
%
% Because of underlying limitations, this m-file requires mexnc.
% 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% $Id: nc_add_dimension.m 1738 2006-08-29 15:30:09Z johnevans007 $
% $LastChangedDate: 2006-08-29 11:30:09 -0400 (Tue, 29 Aug 2006) $
% $LastChangedRevision: 1738 $
% $LastChangedBy: johnevans007 $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargin ~= 3
	error ( '%s:  Must provide three input arguments.\n', mfilename );
end

if ~ischar(dimension_name)
	error ( '%s:  second input must be character.\n', mfilename );
end

if ~isnumeric(dimension_length)
	error ( '%s:  third input must be numeric.\n', mfilename );
end


[ncid, status] = mexnc ( 'open', ncfile, nc_write_mode );
if status
	ncerr = mexnc ( 'strerror', status );
	fmt = '%s:  mexnc:open failed on ''%s'', error message ''%s''.\n';
	error ( fmt, mfilename, ncfile, ncerr );
end

%
% go into define mode
status = mexnc ( 'redef', ncid );
if status
	ncerr = mexnc ( 'strerror', status );
	mexnc ( 'close', ncid );
	error ( '%s:  mexnc:redef failed on %s, ''%s''.\n', mfilename, ncfile, ncerr );
end

[dimid, status] = mexnc ( 'def_dim', ncid, dimension_name, dimension_length );
if status
	ncerr = mexnc ( 'strerror', status );
	mexnc ( 'close', ncid );
	error ( '%s:  mexnc:def_dim failed on %s, ''%s''.\n', mfilename, ncfile, ncerr );
end

status = mexnc ( 'endef', ncid );
if status
	ncerr = mexnc ( 'strerror', status );
	mexnc ( 'close', ncid );
	error ( '%s:  mexnc:redef failed on %s, ''%s''.\n', mfilename, ncfile, ncerr );
end


status = mexnc ( 'close', ncid );
if status 
	ncerr = mexnc ( 'strerror', status );
	error ( '%s:  mexnc:close failed on %s, ''%s''.\n', mfilename, ncfile, ncerr );
end



return












