function dat = dspace2struct(dspacename)
% ------------------------------------------------
% dat = dspace2struct(dspacename)
% Function to export dSPACE-mat-file to Matlab struct.
% The fieldnames of the struct are the same as the dSPACE-signalnames.
% ------------------------------------------------
% dspacename ... .mat-File generated by dSPACE (string)
% dat    ... matlab struct
%
% author: Alexander Michel
% date: 2010/08/09
%

% Copyright 2010 Thomas König, Alexander Michel
%
% This file is part of NumericPlots.
%
% NumericPlots is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% any later version.
% 
% NumericPlots is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with NumericPlots.  If not, see <http://www.gnu.org/licenses/>.


load(dspacename);
idx = strfind(dspacename,'\');
if(isempty(idx))
    fname = dspacename;
else
    fname = dspacename(idx(end)+1:end);
end
dspace = eval(genvarname(fname));
dat.time = dspace.X.Data;
for ii = 1:length(dspace.Y)
    stridx = findstr(dspace.Y(ii).Name,'"');
    newfieldname = dspace.Y(ii).Name(stridx(end-3)+1:stridx(end-2)-1);
    if(isvarname(newfieldname) == 0)
        stridx = find(isstrprop(newfieldname,'alphanum'));
        newfieldname = newfieldname(stridx);
        if(isvarname(newfieldname) == 0)
            newfieldname = newfieldname(2:end);
        end
    end
    dat = setfield(dat, newfieldname, dspace.Y(ii).Data);
end