function varargout = readcmsgrd(filename,varargin)
% sol = readcmshgrd(filename,...'dataset1','dataset2',...)
%
%DESCRIPTION:
% Reads a CMS grid file and creates
% a structure variable containing the grid
% datasets values
%
%INPUT:
% filename - input file name including full path
% varargin - dataset names
%
%OUTPUT:
% sol - structure variable containing dataset values and times
% varargout - variable length datasets corresponding to varargin
%
%USAGE:
% filename = 'test_grd.h5';
% grd = readcmsgrd(filename);
% x = readcmsgrd(filename,'x');
% [x,y] = readcmsgrd(filename,'x','y');
%
% written by Alex Sanchez, USACE-ERDC-CHL


x = []; y = []; x0 = []; y0 = []; angle = []; nx = []; ny = [];
depth = []; mannings = [];
info = hdf5info(filename);
s = info.GroupHierarchy.Groups;
simlabel = s.Name(2:end);
for i=1:length(s.Attributes)
%     disp(s.Attributes(i).Name)
    if strcmpi(s.Attributes(i).Name,[s.Name,'/Orientation'])
        angle = s.Attributes(i).Value;
    elseif strcmpi(s.Attributes(i).Name,[s.Name,'/Origin'])
        x0 = s.Attributes(i).Value(1);
        y0 = s.Attributes(i).Value(2);
    elseif strcmpi(s.Attributes(i).Name,[s.Name,'/NumI'])
        nx = s.Attributes(i).Value;
    elseif strcmpi(s.Attributes(i).Name,[s.Name,'/NumJ'])
        ny = s.Attributes(i).Value;    
    end
end

for i=1:length(s.Datasets)
%     disp(s.Datasets(i).Name)
    if strcmpi(s.Datasets(i).Name,[s.Name,'/CoordsI'])
        x = hdf5read(s.Datasets(i));
    elseif strcmpi(s.Datasets(i).Name,[s.Name,'/CoordsJ'])
        y = hdf5read(s.Datasets(i));
    end 
end
x = x + x0 - abs(x(2)-x(1))/2;
y = y + y0 - abs(y(2)-y(1))/2;

for k=1:length(s.Groups)
    for i=1:length(s.Groups(k).Groups)
        if strcmpi(s.Groups(k).Groups(i).Name,[s.Name,'/Datasets/Depth'])
            depth = hdf5read(s.Groups(k).Groups(i).Datasets(4));
        elseif strcmpi(s.Groups(k).Groups(i).Name,[s.Name,'/Datasets/ManningsN'])
            mannings = hdf5read(s.Groups(k).Groups(i).Datasets(4));
        end
    end
end

if nargin>1 && nargout==1
    for k=1:nargin-1
        eval(['grd.(varargin{k}) = ',varargin{k},';']);
    end
elseif nargin>1
    for k=1:nargin-1
        eval(['varargout{k} = ',varargin{k},';']);
    end    
elseif nargin==1
    %Save to output structure
    varargout{1}.simlabel = simlabel;
    varargout{1}.angle = angle;
    varargout{1}.nx = nx;
    varargout{1}.ny = ny;
    varargout{1}.x0 = x0;
    varargout{1}.x = x;
    varargout{1}.y0 = y0;
    varargout{1}.y = y;
    varargout{1}.depth = depth;
    varargout{1}.mannings = mannings;
end

return

