function [dimid, return_status] = nc_add_dimension ( ncfile, dimension_name, dimension_length )
% NC_ADD_DIMENSION:  adds a dimension to an existing netcdf file
%
% USAGE:  [dimid, status] = 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:
%     dimid:  netcdf dimension id of newly-created dimension
%     status:  -1 if routine not successful, 0 if it is successful
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% $Name:  $
% $Id: nc_add_dimension.m,v 1.1 2005/06/29 16:07:00 brian Exp $
% AUTHOR:  johnevans@acm.org
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

dimid = -1;
return_status = -1;

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

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

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

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

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

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

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


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


return_status = 0;

return
