%----------------------%
%   Read netcdf-file   %
%----------------------%
% please report bugs to marvin.heidkamp@mpimet.mpg.de

function [glo, dim, var] = readNetcdf(inputPath)



ncID        = netcdf.open(inputPath,'NC_NOWRITE');
glo.ID      = netcdf.getConstant('NC_GLOBAL');

[dim.Num,var.Num,glo.Num,glo.dimID] = netcdf.inq(ncID);

glo.Name    = cell(glo.Num,1);
glo.Data    = cell(glo.Num,1);

dim.Name    = cell(dim.Num,1);
dim.Len     = nan (dim.Num,1);

var.Name    = cell(var.Num,1);
var.Type    = nan (var.Num,1);
var.Dim     = cell(var.Num,1);
var.Data    = cell(var.Num,1);
var.ID      = cell(var.Num,1);
var.attNum  = nan (var.Num,1);
var.attName = cell(var.Num,1);
var.attData = cell(var.Num,1);

% Read global attributes
for iAtt = 1:glo.Num
    gloName        = netcdf.inqAttName(ncID,glo.ID,iAtt-1);
    gloData        = netcdf.getAtt(ncID,glo.ID,gloName);
    gloName        = matlab.lang.makeValidName(gloName,'ReplacementStyle','delete');
    
    glo.Name{iAtt} = gloName;
    glo.Data{iAtt} = gloData;
    glo.(gloName)  = gloData;
end

% Read dimensions
for iDim = 1:dim.Num
    [dimName,dimLen] = netcdf.inqDim(ncID,iDim-1);
    dimName        = matlab.lang.makeValidName(dimName,'ReplacementStyle','delete');
    
    dim.Name{iDim} = dimName;
    dim.Len(iDim)  = dimLen;
    dim.(dimName)  = dimLen;
end

% Read variables
for iVar = 1:var.Num
    clc
    disp(['Read netcdf-file(' inputPath ')'])
    disp( 'This may take a while (for large netcdf-files)')
    disp( ' ' )
    disp(['Progress: ' num2str(iVar) '/' num2str(var.Num) '...'])
    
    [varName,varType,varDim,attNum] = netcdf.inqVar(ncID,iVar-1);
    varData        = netcdf.getVar(ncID,iVar-1);
    varName        = matlab.lang.makeValidName(varName,'ReplacementStyle','delete');
    
    var.Name{iVar} = varName;
    var.Type(iVar) = varType;
    var.Dim{iVar}  = varDim;
    var.Data{iVar} = varData;
    var.(varName)  = varData;
    
    var.attNum(iVar)  = attNum;
    % Read attributes
    for iAtt = 1:attNum
        attName    = netcdf.inqAttName(ncID,iVar-1,iAtt-1);
        attData    = netcdf.getAtt(ncID,iVar-1,attName);
          
        % Remove underscore as first character of an attribute name 
        if(strcmp(attName(1),'_')) 
           attName = attName(2:end);
        end
        
        var.attName{iVar,iAtt} = attName;
        var.attData{iVar,iAtt} = attData;
    end
end

% Close netcdf-file
netcdf.close(ncID)

disp('Reading successfully terminated.')

end
