function  grARL2 = protoanchor_ARL2(Mdata)

% PROTOANCHOR_ARL2 -- Tool for fitting PROTOANCHOR using PARAMSEARCH
%   
%  grARL2 = protoanchor_ARL2(Mdata)
%
% Mdata is a structure suitable for passing to PROTOANCHOR_EXPECT
% or PROTOANCHOR_CHEV. Mdata must have two additional fields:
%   * ARL_params -- see FDBK1_ARL2
%   * group_idx -- a cell vector of index sets
%
% GRARL2 is a matrix of group-averaged ARL2 profiles, where:
% grARL2(:,gr) = mean(ARL2(:,group_idx{gr}),2)
%
% Example 1 (10+10 runs in Groups P1 and N1 of Fdbk1 experiment):
%  Sparams = protoanchor_search_params([0 1 0 0 1 0 0 0],1);
%  N_runs = 10 ; gr = [2 3] ; gr_idx = {[1:N_runs], [1:N_runs]+N_runs} ;
%  [stim(:,gr_idx{2}),foo,fdbk(:,gr_idx{2})]=make_fdbk1_stimuli(gr(2),N_runs);
%  [stim(:,gr_idx{1}),foo,fdbk(:,gr_idx{1})]=make_fdbk1_stimuli(gr(1),N_runs);
%  Mdata.stim = stim ; Mdata.fdbk = fdbk ; Mdata.params = Sparams.params ;
%  Mdata.chev = make_protoanchor_chev(size(stim,1),size(stim,2)) ;
%  Mdata.ARL_params = Sparams.ARL_params ; Mdata.group_idx = gr_idx ;
%  Mdata.params.mem_k=.050 ; Mdata.params.cutoffs=.70.*[-3 -1 .9 2.7] ;
%  grARL2 = protoanchor_ARL2(Mdata) ; plot(grARL2,'o-');
%
% Example 2 (search for the two cutoff parameters):
%  Sparams.target_vals = grARL2 ;   % generated with mem_k=.050, c-=.70
%  
%  Mdata.params = opt_params ; opt_grARL2 = protoanchor_ARL2(Mdata) ;
%  plot([grARL2 opt_grARL2],'o-') ;
%
% See also PROTOANCHOR_EXPECT, PROTOANCHOR_SEARCH_PARAMS, FDBK1_ARL2.

% Original coding by Alex Petrov, Ohio State University
% $Revision: 1.0 $  $Date: 2007-08-15 $
%
% Copyright (c) Alexander Petrov 1999-2007, http://alexpetrov.com
% Please read the LICENSE and NO WARRANTY statement in anchor_license.m

%-- Run the model to generate responses
%resp = protoanchor_chev(Mdata) ;
E_resp = protoanchor_expect(Mdata) ;

%-- Convert stim-resp sequences into ARL2 profiles
ARL2 = fdbk1_ARL2(Mdata.stim,E_resp,Mdata.ARL_params) ;

%-- Average across groups, pack, and return
idx = Mdata.group_idx ;
N_groups = length(idx) ;
grARL2 = zeros(size(ARL2,1),N_groups) ;
for gr = 1:N_groups
    grARL2(:,gr) = mean(ARL2(:,idx{gr}),2) ;
end

%--- Return GRARL2
%%%%% End of file PROTOANCHOR_ARL2.M
