function loadnetcdf(inputfile,varargin)

% loadnetcdf

% Mike Wolovick, 12/14/2011

% This function loads a netcdf file as if you were calling matlab's usual
% "load" command.  It is based on the more specialized script
% "getALBMAPv1.m" which I wrote to load the albmap dataset.

% Modification, 7/16/2013:
% The function automatically replaces "-" in variable names with "_".  This
% was a problem loading the Bamber DEM for Greenland, since "-" is not
% allowed in matlab variable names (matlab interprets it as a minus sign).
% In addition, the function replaces -9999 as the nodata value with NaN.

% Modification, 6/16/2016: The function puts the variables into the
% workspace of the function that called it, rather than the base
% workspace.  

% Modification, 11/23/2020:  the function no longer permutes x and y.

% Modification, 3/9/2022:  the function allows you to load specific
% variables from the file, just like the regular "load" command.  The
% syntax is:  "loadnetcdf(inputfile,varname1,varname2,...)"  variable names
% can include wildcards ('*') but no other regular expressions.  Note that the
% comparison is made with respect to the original variable names in the
% netcdf file, not to the fixed matlab-legal names that are output from
% this function.  If no variable names are requested then the function
% loads everything.


% Open netcdf file and get number of variables:
ncid=netcdf.open(inputfile,'NC_NOWRITE');
[ndims,nvars,ngatts,unlimdimid]=netcdf.inq(ncid);

% Loop through variables::
for ii=1:nvars
    
    % Get information about the variable:
    [varname,xtype,dimids,natts]=netcdf.inqVar(ncid,ii-1);
    
    % Check the variable name:
    % check if we requested specific variables:
    if ~isempty(varargin)
        % loop through requested variables:
        foundone=0;
        for jj=1:length(varargin)
            % check if there's a wildcard in this name:
            if ~isempty(strfind(varargin{jj},'*'))
                % look for regexp match:
                dummyinds=regexp(varname,varargin{jj},'ONCE');
                if ~isempty(dummyinds)
                    foundone=1;
                    break
                end
            else
                % look for exact character match:
                if strcmp(varname,varargin{jj})
                    foundone=1;
                    break
                end
            end
        end
        % did we find anything?
        if ~foundone
            continue
        end
    end
    
    %     % Create permute vector:
    %     if length(dimids)<3
    %         permutevector=[2,1];
    %     else
    %         permutevector=[2,1,linspace(3,length(dimids),length(dimids)-2)];
    %     end
    
    % Load the variable:
    %eval(['data=','double(permute(netcdf.getVar(ncid,',num2str(ii),'-1),[',num2str(permutevector),']));'])
    data=double(netcdf.getVar(ncid,ii-1));
    
    % Replace -9999 as the nodata value with NaN:
    data(data==-9999)=NaN;
    
    % Fix variable names to make them matlab-legal:
    % All invalid characters replaced with "_":
    badcharnums=[strfind(varname,'-'),strfind(varname,'['),strfind(varname,']'),...
        strfind(varname,'{'),strfind(varname,'}'),strfind(varname,'('),strfind(varname,')')];
    if isempty(badcharnums)==0
        varname(badcharnums)='_';
        % Invalid first character preceeded by "A":
        if min(badcharnums)==1 || isnan(str2double(varname(1)))==0
            varname=['A',varname];
        end
    end
    
    % Put the variable in the parent workspace:
    assignin('caller',varname,data)
    
end

% Close the netcdf file:
netcdf.close(ncid);
