function [J,dJ]=gmmj(theta);
%GMMJ  Hansen's (1982) J statistic.
%      [J,dJ]=gmmj(theta) computes 
%
%                J = g(theta)' W g(theta) 
%
%      and (if iagflg=1 in UNCMIN) dJ=dJ(theta)/dtheta where 
%
%         g(theta) = E [ f(x(t+n),z(t),theta) ] 
%
%      and W is some (globally known) weighting matrix.
%
%      This file is called by GMM and UNCMIN.  
%      See also GMM, GMMSTART, GMMH, and UNCMIN.
%

%      Ellen McGrattan,  3-25-89
%      Revised  11-14-92,  ERM
%
theta
if nargout>1;
  [H,dH]=gmmh(theta);
else;
  H=gmmh(theta);
end;

if H == -99;
  J  = 1e+20;
  dJ = 1e+20*ones(lgmm,1);
  return
end; 

F=[ ];
for i=1:mgmm;
  F=[F,(H(:,i)*ones(1,qgmm)).*zgmm];
end;
g=sum(F)'/nobs;
J=g'*Wgmm*g;

% check to see if the following computation for g is not faster than 
% that above for your application (esp. if mgmm large)  ..
%
% g=sum( (H*kron(eye(mgmm),ones(1,qgmm))).*(zgmm* ..
%           kron(ones(1,mgmm),eye(qgmm))) )'/nobs;

if nargout>1;
  for i=1:lgmm;
    F=[ ];
    for j=i:lgmm:lgmm*mgmm;
      F=[F,(dH(:,j)*ones(1,qgmm)).*zgmm];
    end;
    dg(i,:)=sum(F)/nobs;
  end;
  dJ=2*dg*Wgmm*g;
end;

