function nc_varrename ( ncfile, old_variable_name, new_variable_name )
% NC_VARRENAME:  Renames a NetCDF variable.
%
% USAGE:  nc_varrename ( netcdf_file, old_variable_name, new_variable_name );
%
% PARAMETERS:
% Input:
%     netcdf_file:  
%        Input netcdf file name.
%     old_variable_name:
%        Name of variable that we wish to rename.
%     new_variable_name:
%        The variable is renamed to this.
% Output:
%     None.  An exception is thrown in case of an error condition.
%
%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% $Id: nc_varrename.m 1741 2006-08-29 16:35:33Z johnevans007 $
% $LastChangedDate: 2006-08-29 12:35:33 -0400 (Tue, 29 Aug 2006) $
% $LastChangedRevision: 1741 $
% $LastChangedBy: johnevans007 $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%



% Show usage if too few arguments.
%
if nargin~=3 
	error ( '%s:  must have three input arguments.\n', mfilename );
end


%
% Open netCDF file
%
[ncid,status ]=mexnc('OPEN',ncfile,nc_write_mode);
if status < 0
	error ( '%s:  mexnc:open failed on %s.\n', mfilename, ncfile );
end


%
% Put into redef mode
status = mexnc('REDEF', ncid);
if status < 0
	mexnc('close',ncid);
	error ( '%s:  mexnc:redef failed on %s.\n', mfilename, ncfile );
end



% 
% Find the old variable.
[varid, status] = mexnc('INQ_VARID', ncid, old_variable_name);
if status < 0
	mexnc('close',ncid);
	error ( '%s:  mexnc:varid failed on %s:%s.\n', mfilename, ncfile, old_variable_name );
end


status = mexnc('RENAME_VAR', ncid, varid, new_variable_name);
if status < 0
	mexnc('close',ncid);
	error ( '%s:  mexnc:varrename failed on %s:%s.\n', mfilename, ncfile, old_variable_name );
end

%
% Leave redef mode
status = mexnc('END_DEF', ncid);
if status < 0
	mexnc('close',ncid);
	error ( '%s:  mexnc:endef failed on %s.\n', mfilename, ncfile );
end

mexnc('close',ncid);

return;
