function  new_X = rearrange_by_context(old_X,context,mapping)

%REARRANGE_BY_CONTEXT -- "Left"/"Right" --> "congruent"/"incongruent"
%
%  new_X = rearrange_by_congr(old_X,block2_idx)
%  new_X = rearrange_by_congr(old_X,block2_idx,mapping)
%
%  OLD_X is a matrix with N_COND rows (= "conditions") and N_TRIALS cols.
%  CONTEXT is a vector of "context IDs" for each trial. A context ID is
%  an integer between 1 and K, where K is the total number of possible
%  contexts. (In PLM applications, K=2 and the two contexts corresponds
%  to left-oriented and right-oriented background noise, respectively.)
%  MAPPING is a matrix with N_COND rows and K columns. Each column must
%  be a permutation of the indices 1:N_COND. The default MAPPING is
%  [1 2 3 4 5 6  8 7 10 9 12 11 ; 8 7 10 9 12 11  1 2 3 4 5 6]' , which
%  translates the stimulus IDs of MAKE_PLE_STIM and CACHE_INPUTS into:
%    1: congruent Gabor, contrast 0.23, current background;
%    2: incongruent Gabor, contrast 0.23, current background;
%    3: congruent Gabor, contrast 0.15, current background;
%    4: incongruent Gabor, contrast 0.15, current background;
%    5: congruent Gabor, contrast 0.10, current background;
%    6: incongruent Gabor, contrast 0.10, current background;
%    7: congruent Gabor, contrast 0.23, "other" background;
%    8: incongruent Gabor, contrast 0.23, "other" background;
%    9: congruent Gabor, contrast 0.15, "other" background;
%   10: incongruent Gabor, contrast 0.15, "other" background;
%   11: congruent Gabor, contrast 0.10, "other" background;
%   12: incongruent Gabor, contrast 0.10, "other" background.
%
%  See also PLM_ZCONGR1, PLM_PROBAB1, CACHE_INPUTS, .

%  Original coding by Alexander Petrov, UC Irvine.
%  $Revision: 1.0 $  $Date: 2002/07/29 16:00 $

if (nargin < 3)
   mapping = [1  2  3  4  5  6  8  7 10  9 12 11 ; ...
              8  7 10  9 12 11  1  2  3  4  5  6]' ;
end

[N_cond,K] = size(mapping) ;
new_X = zeros(size(old_X)) ;
for c = 1:K
   idx = find(context==c) ;
   new_X(:,idx) = old_X(mapping(:,c),idx) ;
end

%--- Return NEW_X
%%%%% End of file REARRANGE_BY_CONTEXT.M
