
% Read a netcdf file's variables, attributes and other into a structure

function NC = getnet(filepath)

%% Open netcdf file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
nci = ncinfo(filepath);
ncid = netcdf.open(filepath,'nc_nowrite');

% Assign output:
NC = nci;

%% Attributes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
NC.Attributes = struct;
NC.Attributes.Global = nci.Attributes;

% ALSO ASSIGN ATTRIBUTES FROM VARIABLES TO THE ATTRIBUTES FIELD:
for i = 1:length(nci.Variables)
    NC.Attributes.(nci.Variables(i).Name) = nci.Variables(i).Attributes;
end

%% Data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

NC.Data = struct;

for i = 1:length(nci.Variables)
    NC.Data.(nci.Variables(i).Name) = double(netcdf.getVar(ncid,i-1));
end

%% Apply scale factors and offsets if they exist %%%%%%%%%%%%%%%%%%%%%%%%%%
% note these names are for the ECMWF netcdf formats, not clear if they'll
% work for other formats, but you've got the attributes anyway now so you
% can do it afterward.
for i = 1:length(nci.Variables)
    
    % Fill values to NaN:
    if any(strcmpi({nci.Variables(i).Attributes.Name},'_FillValue'))
        ind = find(strcmpi({nci.Variables(i).Attributes.Name},'_FillValue'));
        fill_value = nci.Variables(i).Attributes(ind).Value;
        NC.Data.(nci.Variables(i).Name)(NC.Data.(nci.Variables(i).Name) == fill_value) = NaN;
    end
    % missing values to NaN:
    if any(strcmpi({nci.Variables(i).Attributes.Name},'missing_value'))
        ind = find(strcmpi({nci.Variables(i).Attributes.Name},'missing_value'));
        missing_value = nci.Variables(i).Attributes(ind).Value;
        NC.Data.(nci.Variables(i).Name)(NC.Data.(nci.Variables(i).Name) == missing_value) = NaN;
    end
end

%% Close netcdf %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

netcdf.close(ncid); clear ncid;

% removing useless fields:
NC = rmfield(NC,'Name');
NC = rmfield(NC,'Groups');
NC = rmfield(NC,'Format');
NC = rmfield(NC,'Datatypes');
NC = rmfield(NC,'Dimensions');


end





