function var=ncgetvar(filename,varname,start,count,stride)
% NCGETVAR Return data from netCDF file.
%    VARDATA = NCGETVAR(FILENAME,VARNAME,START,COUNT,STRIDE) returns the
%    data from the variable VARNAME in the netCDF file FILENAME. If
%    START,COUNT,STRIDE is omitted all data is returned. For an
%    N-dimensional variable START is a vector of 1-based indices of
%    length N specifying the starting location. COUNT is also a vector
%    of length N specifying the number of elements to read along
%    corresponding dimensions. If a particular element of COUNT is Inf,
%    data is read until the end of that dimension. The optional argument
%    STRIDE specifies the inter-element spacing along each dimension.
%    STRIDE defaults to a vector of ones. Missing values indicated by
%    a CF standard fill value attribute will be set to NaNs. CF standard
%    attributes for scale factor and offset will be recognised and
%    automatically applied to the variable.

% Mats Bentsen (mats.bentsen@uni.no) 2011/11/17

error(nargchk(2,5,nargin))
error(nargoutchk(0,1,nargout))

ncid=netcdf.open(filename,'NC_NOWRITE');
varid=netcdf.inqVarID(ncid,varname);
[~,xtype,dimids,natts]=netcdf.inqVar(ncid,varid);

ndims=length(dimids);
dims=zeros(1,ndims);
for dimnum=1:ndims
  [~,dims(dimnum)]=netcdf.inqDim(ncid,dimids(dimnum));
end
if     nargin==2
  start=ones(1,ndims);
  count=dims;
  stride=ones(1,ndims);
elseif nargin==3
  count=ones(1,ndims);
  stride=ones(1,ndims);
elseif nargin==4
  stride=ones(1,ndims);
end
start=start-1;
ind=find(isinf(count));
count(ind)=dims(ind);

fill_value_used=0;
scale_factor_used=0;
add_offset_used=0;
scale_factor=1;
add_offset=0;
for attnum=0:natts-1
  attname=netcdf.inqAttName(ncid,varid,attnum);
  switch lower(attname)
    case {'_fillvalue'}
      fill_value_used=1;
      fill_value=double(netcdf.getAtt(ncid,varid,attname));
    case {'scale_factor'}
      scale_factor_used=1;
      scale_factor=double(netcdf.getAtt(ncid,varid,attname));
    case {'add_offset'}
      add_offset_used=1;
      add_offset=double(netcdf.getAtt(ncid,varid,attname));
  end
end
var=double(netcdf.getVar(ncid,varid,start,count,stride));
netcdf.close(ncid)
if fill_value_used
  var(find(var==fill_value))=nan;
end
if scale_factor_used||add_offset_used
  var=var*scale_factor+add_offset;
end
