
function theResult = rd_netcdf(theNetCDFFile, varargin)
% load the variables in a netcdf file into structured array
% FOR MATLAB 2008b netcdf capabilities
%   PENNY M. ROWE
%   Jan. 21, 2009
%   
%   Update: C Cox 3/20/09 Ability to open only selected vars (varargin)
%   Update: C Cox 7/30/12 Ability to read vars beginning with numeric.

if nargin < 1, help(mfilename), return, end

result = [];
if nargout > 0, theResult = result; end

% open the file
ncid = netcdf.open(theNetCDFFile, 'NC_NOWRITE');

% if varargin is selected
if isempty(varargin) == 0
    for h = 1:length(varargin)
        tmp = char(varargin(h));
        varid = netcdf.inqVarID(ncid,tmp);
        result.(tmp) = netcdf.getVar(ncid,varid);
    end
else
    % get # of dimensions, # of variables, # of attributes,
    % and the record dimension
    [ndims,nvars,natts,unlimdimID] = netcdf.inq(ncid) ;

    if isempty(ncid), return, end

    for ivar=0:nvars-1
        [varname, vartype, dimids, natts] = netcdf.inqVar(ncid,ivar) ;
        varname(varname=='-'|varname=='.')=[];
        try
            result.(varname) = netcdf.getVar(ncid,ivar) ;
        catch
            result.(['varname' varname]) = netcdf.getVar(ncid,ivar) ;  % update 7/31/12
        end
    end
end


netcdf.close(ncid);

if nargout > 0
  theResult = result;
else
  ncans(result)
end





