function  sumsq2 = PLM_sumsqfit2(model_Zcongr,human_Zcongr)

%PLM_SUMSQFIT2 -- Compares PLMODEL1 performance against human data.
%
%  sumsq2 = PLM_sumsqfit2(model_Zcongr)
%  sumsq2 = PLM_sumsqfit2(model_Zcongr,human_Zcongr)
%
%  The same as PLM_SUMSQFIT but the three d-prime curves also participate
%  in the calculation of the fit. Thus, each zP value is used twice:
%  first in its own right, and second as averaged within the corresp. d'.
%  This is done in an attempt to boost the influence of the congruent
%  condition and to improve the fit to the d-prime profiles themselves.
%
%  See also PLM_SUMSQFIT, PLM_DPRIME3, PLM_ZCONGR1, PLM_PARAMSEARCH.

%  Original coding by Alexander Petrov, UC Irvine.
%  $Revision: 1.0 $  $Date: 2003/06/01 12:44 $

global HUMAN_ZCONGR

if (nargin==1)  human_Zcongr = HUMAN_ZCONGR ; end   % default

if (iscell(model_Zcongr))       % {sumstats.zP_congr',sumstats.zP_incon'}
   model_Zcongr = cat(1,model_Zcongr{:}) ;
   model_Zcongr([2,3,4,5],:) = model_Zcongr([4,2,5,3],:) ;
end

[h_rows,h_cols] = size(human_Zcongr) ;
[m_rows,m_cols] = size(model_Zcongr) ;

%-- Ignore the bottom (="other") part of MODEL_ZCONGR if necessary
if (m_rows > h_rows)
   model_Zcongr = model_Zcongr(1:h_rows,:) ;
   m_rows = h_rows ;
elseif ((m_rows==3) & (h_rows==6))  % special case: d' rather than zProb
   %human_Zcongr = human_Zcongr([1 3 5],:) + human_Zcongr([2 4 6],:) ;
   error(['PLM_SUMSQFIT2 does not support this case. ' ...
          'Use PLM_SUMSQFIT instead.']) ;
elseif (m_rows < h_rows)
   error('MODEL_ZCONGR has less rows (stimulus types) than HUMAN_ZCONGR.');
%else  (m_rows==h_rows)
end

%-- Average across sub-blocks if necessary
if (m_cols > h_cols)
   if (rem(m_cols,h_cols)~=0)
      error('Model N_blocks must be a multiple of human N_blocks.');
   end
   N = m_cols / h_cols ;
   model_Zcongr = reshape(model_Zcongr',[N h_cols , m_rows]) ;
   model_Zcongr = squeeze(mean(model_Zcongr,1))' ;
elseif (m_cols < h_cols)
   error('MODEL_ZCONGR has less blocks than HUMAN_ZCONGR.');
%else  (m_cols==h_cols)
end

%-- D-primes  (that's what is added in PLM_SUMSQFIT2)
human_dprime = (human_Zcongr([1 3 5],:) + human_Zcongr([2 4 6],:)) /2 ;
model_dprime = (model_Zcongr([1 3 5],:) + model_Zcongr([2 4 6],:)) /2 ;

%-- Return the sum of squares
sumsq_zP  = sum(sum((model_Zcongr-human_Zcongr).^2)) ;
sumsq_dpr = sum(sum((model_dprime-human_dprime).^2)) ;
sumsq2 = sumsq_zP + 2*sumsq_dpr ;

%-- Return SUMSQ2
%%%%% End of file PLM_SUMSQFIT2.M
