% Construct a ltpda_ob from a file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FUNCTION:    fromFile
%
% DESCRIPTION: Construct a ltpda_ob from a file
%
% CALL:        obj = obj.fromFile(filename)
%              obj = obj.fromFile(pl)
%
% VERSION:     $Id: fromFile.m,v 1.8 2011/02/11 12:44:33 hewitson Exp $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function objs = fromFile(obj, pli)

  VERSION = '$Id: fromFile.m,v 1.8 2011/02/11 12:44:33 hewitson Exp $';

  % Which file type are we dealing with?
  if ischar(pli)
    pli = plist('filename', pli);
  end

  % get filename
  filename = find(pli, 'filename');

  % Get the correct parameter set
  [path, name, ext] = fileparts(filename);

  % Load a MAT file if the file extension doesn't exist
  if isempty(ext)
    ext = '.mat';
    filename = strcat(filename, ext);
    pli.pset('filename', filename);
  end
  
  switch ext

    case '.mat'
      ii = obj.getInfo(class(obj), 'From MAT File');
      ii.setMversion([VERSION '-->' ii.mversion]);

      % Combine input and default plist
      pl = combine(pli, ii.plists);

      % Load MAT-File
      objs = load(filename);

      if ((isfield(objs, 'objs') && isstruct(objs.objs)) || ...
          (isfield(objs, 'a')    && isstruct(objs.a)))
        if isfield(objs, 'a')
          objs = objs.a;
        else
          objs = objs.objs;
        end
        scl = utils.helper.classFromStruct(objs);
        if isempty(scl)
          if isfield(objs, 'class')
            scl = objs.class;
          else
            error('### The structure does not match any LTPDA object.');
          end
        end
        if ~strcmp(class(obj), scl)
          error('### The structure does not match the chosen LTPDA object constructor. It seems to be a [%s] object.', scl)
        end
        fcn_name   = [class(obj) '.update_struct'];
        struct_ver = sscanf(objs(1).creator.ltpda_version, '%s.%s.%s');
        objs = feval(fcn_name, objs, struct_ver);
        objs = feval(class(obj), objs);
      elseif ismember('a', fieldnames(objs))
        objs = objs.a;
      elseif ismember('objs', fieldnames(objs))
        objs = objs.objs;
      else
        objs = obj.fromDataInMAT(objs, pl);
      end


    case '.xml'
      ii = obj.getInfo(class(obj), 'From XML File');
      ii.setMversion([VERSION '-->' ii.mversion]);

      % Combine input and default plist
      pl = combine(pli, ii.plists);

      root_node = xmlread(filename);
      objs = utils.xml.xmlread(root_node, class(obj));

    otherwise
      error('### Unknown file type [%s].', ext(2:end));
  end

end

