function [J,dJ]=gmmjc(theta);
%GMMJ  Hansen's (1982) J statistic.
%      [J,dJ]=gmmjc(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  6-30-89,  ERM
%
if nargout>1;
  [H,dH]=gmmhc(theta);
else;
  H=gmmhc(theta);
end;
[tem,m]=size(H);
l=length(theta);

F=[ ];
for i=1:m;
  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:l;
    F=[ ];
    for j=i:l:l*m;
      F=[F,(dH(:,j)*ones(1,qgmm)).*zgmm];
    end;
    dg(i,:)=sum(F)/nobs;
  end;
  dJ=2*dg*Wgmm*g;
end;

