function [JE,JJ,normJE] = calcjejj(net,Pd,Zb,Zi,Zl,N,Ac,En,Q,TS,MR)
%CALCJEJJ Calculate Jacobian performance vector.
%
%	Syntax
%
%	  [je,jj,normje] = calcjejj(net,Pd,BZ,IWZ,LWZ,N,Ac,En,Q,TS,MR)
%
%	Warning!!
%
%	  This function may be altered or removed in future
%	  releases of the Neural Network Toolbox. We recommend
%	  you do not write code which calls this function.

% Mark Beale, 11-31-97
% Copyright (c) 1992-1998 by The MathWorks, Inc.
% $Revision: 1.4 $

% Inputs
%
% Pd - NlxNixTS cell array         PD{i,j,ts}  - DijxQ matrix or []
% Zb - Nlx1 cell array             Zb{i}       - SixQ matrix or []
% Zi - NlxNixTS cell array         Zi{i,j,ts}  - SixQ matrix or []
% Zl - NlxNlxTS cell array         Zl{i,j,ts}  - SixQ matrix or []
% N  - NlxTS cell array            N{i}        - SixQ matrix
% Ac - Nlx(LD+TS) cell array       Ac{i,LD+ts} - SixQ matrix
% En - NlxTS cell array            E{i,ts}     - SixQ matrix or []
%
% Locals
%
% Em - sum(Vi)xQ matrix
% Ex - sum(Vi)*Q vector
% Jx - XLenxsum(Vi)*Q matrix
%
% Outputs
%
% JE - XLen vector
% JJ - XLenxXLen matrix

% Standard Calculation
if (MR == 1)
  Em = cell2mat(En);
  Ex = Em(:);
  Jx = calcjx(net,Pd,Zb,Zi,Zl,N,Ac,Q,TS);
  JE = Jx * Ex;
  JJ = Jx * Jx';
  
% Reduced Memory Calculation
else
  MR = min(MR,Q);
  Qstop = floor((1:MR)*(Q/MR));
  Qstart = [0 Qstop(1:(end-1))]+1;
  Q2 = Qstop-Qstart+1;

  Pd = batchdiv(Pd,MR,Qstart,Qstop);
  Zb = batchdiv(Zb,MR,Qstart,Qstop);
  Zi = batchdiv(Zi,MR,Qstart,Qstop);
  Zl = batchdiv(Zl,MR,Qstart,Qstop);
  N = batchdiv(N,MR,Qstart,Qstop);
  Ac = batchdiv(Ac,MR,Qstart,Qstop);
  En = batchdiv(En,MR,Qstart,Qstop);

  Em = cell2mat(En{1});
  Ex = Em(:);
  Jx = calcjx(net,Pd{1},Zb{1},Zi{1},Zl{1},N{1},Ac{1},Q2(1),TS);
  JE = Jx * Ex;
  JJ = Jx * Jx';
  for q=2:MR
    Em = cell2mat(En{q});
    Ex = Em(:);
    Jx = calcjx(net,Pd{q},Zb{q},Zi{q},Zl{q},N{q},Ac{q},Q2(q),TS);
    JE = JE + Jx * Ex;
    JJ = JJ + Jx * Jx';
  end
end

normJE = sqrt(JE'*JE);

%===============================================================
function b_div = batchdiv(b,QD,Qstart,Qstop)

size_b = size(b);
len_b = prod(size_b);
b_div = cell(1,QD);
for q=1:QD
  b_div_q = cell(size_b);
  Qind = Qstart(q):Qstop(q);
  for i=1:len_b
    if ~isempty(b{i})
      b_div_q{i} = b{i}(:,Qind);
	end
  end
  b_div{q} = b_div_q;
end

%===============================================================
