% FROMSTRUCT Construct a ltpda_obj from a struct
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FUNCTION:    fromStruct
%
% DESCRIPTION: Construct a ltpda_obj from a struct
%
% CALL:        obj = fromStruct(obj, struct)
%
% VERSION:     $Id: fromStruct.m,v 1.1 2010/12/20 12:50:15 hewitson Exp $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function objs = fromStruct(objs, obj_struct)

  cn = class(objs);

  % build/update struct
  for kk = 1:numel(obj_struct)

    objs(kk) = feval(cn);
    %%% Update the structure to the current toolbox version
    if isfield(obj_struct, 'tbxver')
      fcn_name = ([cn '.update_struct']);
      up_struct = feval(fcn_name, obj_struct(kk), obj_struct(kk).tbxver);
    else
      up_struct = obj_struct(kk);
    end

    props  = properties(cn);
    nprops = numel(props);

    for jj=1:nprops
      prop = props{jj};
      if isfield(up_struct, prop) && isstruct(up_struct.(prop))
        % what class?
        if isfield(up_struct.(prop), 'class')
          objs(kk).(prop) = utils.helper.struct2obj(up_struct.(prop), up_struct.(prop).class);
        else
          % can we guess class ?
          cln = utils.helper.classFromStruct(up_struct.(prop));
          if ~isempty(cln)
            objs(kk).(prop) = feval(cln, up_struct.(prop));
          else
            if isfield(up_struct, prop)
              objs(kk).(prop) = up_struct.(prop);
            end
          end
        end
      else
        if isfield(up_struct, prop)
          % ATTENTION: Special case for 'ntaps'
          %            It is not necessary to set this value because it
          %            will be computed.
          if ~strcmp(prop, 'ntaps')
            objs(kk).(prop) = up_struct.(prop);
          end
        end
      end
    end

  end

  % Reshape the objects
  objs = reshape(objs, size(obj_struct));

end

