function [g, badg] = YADAnumgrad(fcn,x,varargin)
% function [g badg] = YADAnumgrad(fcn,x,varargin)
%
% NOTE:  YADAnumgrad is a minor rewrite of Christopher Sims' numgrad function. The changes
%        only reflect some needs of YADA. The actual computations have not been changed. All disp
%        calls have been commented out. The scale variable has been altered such that it depends
%        on the value of the parameter.
%
%        First YADA version: August 9, 2006.
%         This YADA version: May 28, 2008.
%

delta = 1e-6;
n=length(x);
tvec=delta*eye(n);
g=zeros(n,1);
%
f0 = feval(fcn,x,varargin{:});
%
badg=0;
for i=1:n
%   scale=1; % originally 1
   if abs(x(i))>0;
      scale = abs(x(i));
   else;
      scale = 1;
   end;
   % i,tveci=tvec(:,i)% ,plus=x+scale*tvec(:,i) % Jinill Kim on 9/6/95
   if size(x,1)>size(x,2)
      tvecv=tvec(i,:);
   else
      tvecv=tvec(:,i);
   end
   g0 = (feval(fcn,x+scale*tvecv', varargin{:}) - f0) ...
         /(scale*delta);
   %
   if abs(g0)< 1e15
      g(i)=g0;
   else
%      disp('bad gradient ------------------------') % Jinill Kim
      if isnan(g0)==0;
         g(i)=g0;
      end;
      badg=1;
      % return
      % can return here to save time if the gradient will never be
      % used when badg returns as true.
   end
end

%
% end of YADAnumgrad.m
%
