function Value = getValue(M,OptArg)
%GETVALUE  Computes current/nominal value of generalized model.
%
%   V = GETVALUE(M) evaluates the generalized model M for the current/nominal 
%   values of the Control Design blocks in M.  The output V is a numeric array 
%   for static models and a numeric LTI model for dynamic models (see NUMLTI). 
%
%   V = GETVALUE(M,'usample') further samples the uncertain blocks in M.
%   When M has uncertainty, this returns 20 sample values in addition to 
%   the nominal value. Otherwise this just returns the nominal value.
%
%   V = GETVALUE(M,BLOCKVALUES) evaluates M for the block values specified 
%   in BLOCKVALUES. The field names and values in the structure BLOCKVALUES
%   specify the block names and their values. Blocks of M not listed in 
%   BLOCKVALUES are replaced by their current/nominal values.
%
%   V = GETVALUE(M,MREF) uses the block values in MREF to evaluate M. This
%   is equivalent to V = GETVALUE(M,MREF.Blocks).
%
%   Example: If you have a closed-loop model T0 of your control system with
%   two tunable blocks C1 and C2 and use
%      T = hinfstruct(T0)
%   to tune them, you can get the tuned values of C1, C2, and any loop 
%   transfer function H depending on C1,C2 by
%      BV = T.Blocks
%      C1V = getValue(C1,BV)
%      C2V = getValue(C2,BV)
%      HV = getValue(H,BV)
%
%   See also getBlockValue, replaceBlock, GENMAT, GENLTI, ControlDesignBlock, InputOutputModel.

%   Copyright 1986-2011 The MathWorks, Inc.
if nargin>1
   if strcmpi(OptArg,'usample')
      % Sample uncertainty 
      if isUncertain(M)
         s = size(M);
         s = [s(3:end) 1];
         dim = max([0 find(s>1,1,'last')]) + 1;
         M = stack(dim,M,usample(M,20));
      end
   else
      % Apply specific block values
      if isstruct(OptArg)
         BlockValues = OptArg;
      elseif isa(OptArg,'ltipack.LFTModelArray')
         BlockValues = OptArg.Blocks;
      else
         error(message('Control:lftmodel:getValue1'))
      end
      % Cast dynamic Control Design blocks to GENSS to avoid losing I/O names
      if isa(M,'DynamicBlock')
         M = genss(M);
      end
      % Update block values
      try
         M = replaceBlock(M,BlockValues);
      catch ME
         throw(ME)
      end
   end
end
% Fold all blocks in to get nominal value
if isnumeric(M)
   % genmat with values specified for all blocks
   Value = M;
else
   Value = getValue_(M);
end
