%-----------------------%
%   Write netcdf-file   % 
%-----------------------%
% please report bugs to marvin.heidkamp@mpimet.mpg.de
function writeNetcdf(outputPath, glo, dim, var)

% Extract file and folder from path (--> netcdf.create cannot handle paths)
filePos = strfind(outputPath,'/');
if( isempty(filePos))
    outputFile   = outputPath;
else 
    filePos      = filePos(end);
    outputFolder = outputPath(1:filePos);
    outputFile   = outputPath(filePos+1:end);
end

% Create a netCDF file
ncID = netcdf.create(outputFile,'CLOBBER');

% Define global attributes
for iAtt = 1:glo.Num
    netcdf.putAtt(ncID,netcdf.getConstant('NC_GLOBAL'),glo.Name{iAtt},glo.Data{iAtt});
end

% Define dimensions
for iDim = 1:dim.Num
    netcdf.defDim(ncID,dim.Name{iDim},dim.Len(iDim));
end

% Define variables
varType = 'double';
for iVar = 1:var.Num
    netcdf.defVar(ncID,var.Name{iVar},varType,var.Dim{iVar});
    attNum = var.attNum(iVar);
    for iAtt = 1:attNum
        netcdf.putAtt(ncID,iVar-1,var.attName{iVar,iAtt},var.attData{iVar,iAtt})
    end
end

% Close definition
netcdf.endDef(ncID)

% Write data to variable
for iVar = 1:var.Num  
    netcdf.putVar(ncID,iVar-1,var.(var.Name{iVar}));
end

% Close netcdf-file
netcdf.close(ncID)

% Move file to output folder
if(~isempty(filePos))
    movefile(outputFile,outputFolder)
end

end
