% FROMPARAMETER Construct an ao from a param object
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FUNCTION:    fromParameter
%
% DESCRIPTION: Construct an ao from a param object
%
% CALL:        a = fromParameter(a, pl)
%
% PARAMETER:   pl: Parameter list object
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function a = fromParameter(a, pli)
  
  VERSION = '$Id: fromParameter.m,v 1.2 2011/07/06 06:37:06 mauro Exp $';
  % get AO info
  ii = ao.getInfo('ao', 'From Parameter');
  
  % Set the method version string in the minfo object
  ii.setMversion([VERSION '-->' ii.mversion]);
  
  % Add default values
  pl = parse(pli, ii.plists);
  pl = parse(pl, plist('fcn', []));
  pl.getSetRandState();
  
  pin = find(pl, 'parameter');
  name = '';
  pval = [];
  switch class(pin)
    case 'plist'
      key = find(pl, 'key');
      if isempty(key)
        error('When inputting a plist, the required key should be specified');
      end
      
      pidx = pin.getIndexForKey(key);
      p = pin.params(pidx);
      name = p.key;
      pval = p.val;
      
    case 'param'
      
      name = pin.key;
      pval = pin.val;
      
    case 'paramValue'
      
      pval = pin;
      
    case 'char'
      pl_model_list = plist.getBuiltInModels();
      if any(strcmp(pl_model_list(:,1), pin))
        pl_model = plist(plist('built-in', pin));
      else
        error('The input name ''%s'' is not a supported built-in model', pin);
      end
      
      key = find(pl, 'key');
      if isempty(key)
        error('When inputting a plist, the required key should be specified');
      end
      
      pidx = pl_model.getIndexForKey(key);
      p = pl_model.params(pidx);
      name = p.key;
      pval = p.val;
    otherwise
      error('The input parameter class is not supported [%s]', class(pin));
  end
  
  
  yunits = '';
  props = [];
  switch class(pval)
    case 'double'
      dval = pval;
    case 'paramValue'
      dval = pval.getVal;
      
      % do we have other properties?
      propnames = fieldnames(pval.property);
      if ismember('unit', propnames)
        yunits = pval.getProperty('unit');
      end
      if ismember('units', propnames)
        yunits = pval.getProperty('units');
      end
      
      props = pval.property;
      
    otherwise
      error('Unsupported value class [%s] for key %s', class(pval), name);
  end
  
  data = cdata(dval);
  data.setYunits(yunits);
  a.setName(name);
  a.data = data;
  a.setProcinfo(plist('properties', props));
  
  % Add history
  a.addHistory(ii, pl, [], []);
  
end

