function data = read_netcdf_all(filename)


%+
% FUNCTION read_netcdf_all
% (c) Stuart MacCallum (2010)
% The School of GeoSciences
% The University of Edinburgh, UK
%
% Developed for the ARCLake project
% ARCLake is an ESA funded project
%
% NAME:
% read_netcdf_all
%
% DESCRIPTION:
% Reads in the entire contents of a NetCDF file to a structure
%
% INPUT:
% filename      - Input filename
%
% OUTPUT
% None
%
% RETURN VALUE:
% data          - Structure containing the data in the netCDF file
%               - Returns -1 of file does not exist
%
% KEYWORDS:
% None
% 
% REQUIRES:
% None
% 
% COMMENTS:
% dd/mm/yy - 
% 
% HISTORY:
% 22/02/10 - FUNCTION created
%-

prog_name = 'read_netcdf_all';

data = [];

% Abort the program if no data file has been provided.
   if isempty(filename)
      disp([prog_name ': ERROR - No input filename was specified.'])
      return
   end

% Get a file id value.
   ncid   = netcdf.open(filename,'NC_NOWRITE');

% Abort the program if the file does not exist or cannot be read.
   if ncid == -1
      disp([prog_name ': ERROR - ' filename ' could not be opened.'])
      netcdf.close(ncid);
      return
   end

% Read in the info about the file contents
[numdims, numvars, numglobalatts, unlimdimID] = netcdf.inq(ncid);

% Read in the global attibutes and put it in a structure
for jj=0:numglobalatts-1,
  gattname = netcdf.inqAttName(ncid,netcdf.getConstant('NC_GLOBAL'),jj);
  gattval = netcdf.getAtt(ncid,netcdf.getConstant('NC_GLOBAL'),gattname);
  data.(gattname) = gattval;
end

% Read in the variables and their associated attributes
for ii = 0:numvars-1,
  [varname,xtype,dimids,numatts] = netcdf.inqVar(ncid,ii);
  varid = netcdf.inqVarID(ncid,varname);
  tmp = netcdf.getVar(ncid,varid);  
  data.(varname) =  tmp;
  for jj=0:numatts-1,
    attname = netcdf.inqAttName(ncid,varid,jj);
    attval = netcdf.getAtt(ncid,varid,attname);
    data.(strcat(varname,attname)) = attval;
  end
end  

netcdf.close(ncid)
