function varargout = readcmsh5(filename,varargin)
% sol = readcmsh5(filename,...'dataset1','dataset2',...)
%
%DESCRIPTION:
% Reads a CMS solution file and creates
% a structure variable containing the solution
% datasets values and times
%
%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_sol.h5';
% sol = readcmsh5(filename);
% wse = readcmsh5(filename,'Water_Elevation');
% [wse,uv] = readcmsh5(filename,'Water_Elevation','Current_Velocity');
%
% written by Alex Sanchez, USACE-ERDC-CHL
info = hdf5info(filename);
s = info.GroupHierarchy.Groups.Groups;
sol = struct();
for i=1:length(s);
    field = s(i).Name;
    ind = findstr(field,'/');
    field = field(ind(end)+1:end);
    if nargin>1 %select only few datasets
        for k=1:nargin-1
            if strcmpi(field,varargin{k})
                varargout{k}.Times = hdf5read(s(i).Datasets(3));
                varargout{k}.Values = hdf5read(s(i).Datasets(4));
                continue
            end
        end
    else %write all datasets
        sol = setfield(sol,field,'Times',hdf5read(s(i).Datasets(3)));
        sol = setfield(sol,field,'Values',hdf5read(s(i).Datasets(4)));
    end    
end
if nargin>1 && nargout==1
    for k=1:nargin-1
        sol.(varargin{k}) = varargout{k};
    end
elseif nargin==1
    simlabel = info.GroupHierarchy.Groups.Name(2:end);
    sol.Simulation_Label = simlabel;
    varargout{1} = sol;
end
return

