function [values, return_status] = nc_getlast(ncfile, var, num_records)
% NC_GETLAST:  Get last few datums from an unlimited NetCDF variable.
%
% USAGE: [values, status] = nc_getlast( netcdf_file, variable, n )
%
% PARAMETERS:
% Input:
%    netcdf_file:  
%        Name of input netcdf file.
%    variable:  
%        Name of NetCDF variable whose last few records we want.
%    n:  
%        Optional, default is 1.
%        This is the number of records to get, starting at the end
% Output:
%    values:  return data
%    status:  -1 if function failed 
%              0 if ok 
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% $Name:  $
% $Id: nc_getlast.m,v 1.1 2005/06/29 16:07:00 brian Exp $
% AUTHOR:  johnevans@acm.org
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%






%
% assume failure until success is known
values = [];
return_status = -1;


% Show usage if too few arguments.
%
if (nargin <= 1)
	fprintf ( 2, '%s:  not enough input arguments.\n', mfilename );
	return
end
if (nargin > 3) 
	fprintf ( 2, '%s:  must supply at least 2 and no more than 3 input arguments.\n', mfilename );
	return
end

if ~ischar(ncfile) 
	fprintf ( 2, '%s:  First argument must be character.\n', mfilename );
	return
end

if ~ischar(var) 
	fprintf ( 2, '%s:  2nd argument must be character.\n', mfilename );
	return
end

if ( nargin == 2 )
	num_records = 1;
else
	if ~isnumeric(num_records) 
		fprintf ( 2, '%s:  3rd argument must be numeric.\n', mfilename );
		return
	end
	if num_records <= 0
		fprintf ( 2, '%s:  3rd argument must be positive.\n', mfilename );
		return
	end

end

varlist = { var };
[nb, status] = nc_getbuffer ( ncfile, varlist, -1, num_records );
if ( status < 0 )
	fprintf ( 2, '%s:  nc_getbuffer failed on %s, file %s.\n', mfilename, var, ncfile );
	return
end

values = getfield ( nb, var );
return_status = 0;

return
